LCOV - code coverage report
Current view: top level - src/motion - bfgs_optimizer.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 88.8 % 810 719
Test Date: 2026-11-24 01:22:08 Functions: 100.0 % 21 21

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief Routines for Geometry optimization using BFGS algorithm
      10              : !> \par History
      11              : !>      Module modified by Pierre-André Cazade [pcazade] 01.2020 - University of Limerick.
      12              : !>      Modifications enable Space Group Symmetry.
      13              : ! **************************************************************************************************
      14              : MODULE bfgs_optimizer
      15              : 
      16              :    USE atomic_kind_list_types,          ONLY: atomic_kind_list_type
      17              :    USE atomic_kind_types,               ONLY: get_atomic_kind,&
      18              :                                               get_atomic_kind_set
      19              :    USE bibliography,                    ONLY: Lindh1995,&
      20              :                                               cite_reference
      21              :    USE cell_types,                      ONLY: cell_type,&
      22              :                                               pbc
      23              :    USE constraint_fxd,                  ONLY: fix_atom_control
      24              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_create,&
      25              :                                               cp_blacs_env_release,&
      26              :                                               cp_blacs_env_type
      27              :    USE cp_external_control,             ONLY: external_control
      28              :    USE cp_files,                        ONLY: close_file,&
      29              :                                               open_file
      30              :    USE cp_fm_basic_linalg,              ONLY: cp_fm_column_scale,&
      31              :                                               cp_fm_matvec,&
      32              :                                               cp_fm_transpose
      33              :    USE cp_fm_diag,                      ONLY: choose_eigv_solver
      34              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      35              :                                               cp_fm_struct_release,&
      36              :                                               cp_fm_struct_type
      37              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      38              :                                               cp_fm_get_info,&
      39              :                                               cp_fm_read_unformatted,&
      40              :                                               cp_fm_release,&
      41              :                                               cp_fm_set_all,&
      42              :                                               cp_fm_to_fm,&
      43              :                                               cp_fm_type,&
      44              :                                               cp_fm_write_unformatted
      45              :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      46              :                                               cp_logger_type,&
      47              :                                               cp_to_string
      48              :    USE cp_output_handling,              ONLY: cp_iterate,&
      49              :                                               cp_p_file,&
      50              :                                               cp_print_key_finished_output,&
      51              :                                               cp_print_key_should_output,&
      52              :                                               cp_print_key_unit_nr
      53              :    USE cp_subsys_types,                 ONLY: cp_subsys_get,&
      54              :                                               cp_subsys_type
      55              :    USE force_env_types,                 ONLY: force_env_get,&
      56              :                                               force_env_get_nparticle,&
      57              :                                               force_env_type
      58              :    USE global_types,                    ONLY: global_environment_type
      59              :    USE gopt_f_methods,                  ONLY: &
      60              :         cp_eval_at, gopt_f_ii, gopt_f_io, gopt_f_io_finalize, gopt_f_io_init, &
      61              :         gopt_f_project_coord, gopt_f_project_vector, gopt_f_restore_cell_manifold, &
      62              :         gopt_f_set_h_ref, print_geo_opt_header, print_geo_opt_nc
      63              :    USE gopt_f_types,                    ONLY: gopt_f_type
      64              :    USE gopt_param_types,                ONLY: gopt_param_type
      65              :    USE ieee_arithmetic,                 ONLY: ieee_is_finite
      66              :    USE input_constants,                 ONLY: bfgs_direct,&
      67              :                                               bfgs_inverse,&
      68              :                                               default_cell_method_id,&
      69              :                                               default_ts_method_id
      70              :    USE input_section_types,             ONLY: section_vals_get_subs_vals,&
      71              :                                               section_vals_type,&
      72              :                                               section_vals_val_get,&
      73              :                                               section_vals_val_set
      74              :    USE iso_fortran_env,                 ONLY: iostat_end
      75              :    USE kinds,                           ONLY: default_path_length,&
      76              :                                               dp
      77              :    USE machine,                         ONLY: m_flush,&
      78              :                                               m_walltime
      79              :    USE mathlib,                         ONLY: det_3x3,&
      80              :                                               inv_3x3
      81              :    USE message_passing,                 ONLY: mp_para_env_type
      82              :    USE parallel_gemm_api,               ONLY: parallel_gemm
      83              :    USE particle_list_types,             ONLY: particle_list_type
      84              : #include "../base/base_uses.f90"
      85              : 
      86              :    IMPLICIT NONE
      87              :    PRIVATE
      88              : 
      89              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'bfgs_optimizer'
      90              :    ! Parameters of the Lindh 1995 model Hessian (atom rows H/C/O-N, pair
      91              :    ! columns). Screening constants for construct_initial_hess.
      92              :    REAL(KIND=dp), PARAMETER, PRIVATE :: lindh_alpha(3, 3) = &
      93              :                                         RESHAPE([1.0_dp, 0.3494_dp, 0.3494_dp, &
      94              :                                                  0.3949_dp, 0.2800_dp, 0.2800_dp, &
      95              :                                                  0.3949_dp, 0.2800_dp, 0.1800_dp], [3, 3])
      96              :    REAL(KIND=dp), PARAMETER, PRIVATE :: lindh_r0(3, 3) = &
      97              :                                         RESHAPE([1.35_dp, 2.10_dp, 2.53_dp, &
      98              :                                                  2.10_dp, 2.87_dp, 3.40_dp, &
      99              :                                                  2.53_dp, 3.40_dp, 3.40_dp], [3, 3])
     100              :    REAL(KIND=dp), PARAMETER, PRIVATE :: lindh_cutoff = 6.0_dp
     101              :    REAL(KIND=dp), PARAMETER, PRIVATE :: lindh_stretch_factor = 0.45_dp
     102              :    REAL(KIND=dp), PARAMETER, PRIVATE :: lindh_angle_factor = 0.15_dp
     103              :    REAL(KIND=dp), PARAMETER, PRIVATE :: lindh_denom_floor = 0.01_dp
     104              :    LOGICAL, PARAMETER                   :: debug_this_module = .TRUE.
     105              : 
     106              :    ! Both matrix representations share one restart format and the existing file name.
     107              :    CHARACTER(LEN=16), PARAMETER         :: bfgs_restart_magic = "CP2K BFGS STATE "
     108              :    INTEGER, PARAMETER                   :: bfgs_restart_version = 1
     109              :    REAL(KIND=dp), PARAMETER             :: min_hessian_eigenvalue = 1.0e-4_dp
     110              : 
     111              :    PUBLIC :: bfgs_read_restart_header, geoopt_bfgs
     112              : 
     113              : CONTAINS
     114              : 
     115              : ! **************************************************************************************************
     116              : !> \brief Main driver for BFGS geometry optimizations
     117              : !> \param force_env ...
     118              : !> \param gopt_param ...
     119              : !> \param globenv ...
     120              : !> \param geo_section ...
     121              : !> \param gopt_env ...
     122              : !> \param x0 ...
     123              : !> \par History
     124              : !>      01.2020 modified to perform Space Group Symmetry [pcazade]
     125              : ! **************************************************************************************************
     126          915 :    RECURSIVE SUBROUTINE geoopt_bfgs(force_env, gopt_param, globenv, geo_section, gopt_env, x0)
     127              : 
     128              :       TYPE(force_env_type), POINTER                      :: force_env
     129              :       TYPE(gopt_param_type), POINTER                     :: gopt_param
     130              :       TYPE(global_environment_type), POINTER             :: globenv
     131              :       TYPE(section_vals_type), POINTER                   :: geo_section
     132              :       TYPE(gopt_f_type), POINTER                         :: gopt_env
     133              :       REAL(KIND=dp), DIMENSION(:), POINTER               :: x0
     134              : 
     135              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'geoopt_bfgs'
     136              :       REAL(KIND=dp), PARAMETER                           :: one = 1.0_dp, zero = 0.0_dp
     137              : 
     138              :       CHARACTER(LEN=5)                                   :: wildcard
     139              :       INTEGER                                            :: handle, info, iter_nr, its, &
     140              :                                                             matrix_method, maxiter, ndf, &
     141              :                                                             output_unit
     142              :       LOGICAL                                            :: conv, hesrest, hess_reset, inverse, &
     143              :                                                             method_explicit, shell_present, &
     144              :                                                             should_stop, step_on_ray, use_mod_hes, &
     145              :                                                             use_rfo
     146              :       REAL(KIND=dp)                                      :: ediff, emin, eold, etot, pred, rad, rat, &
     147              :                                                             step, t_diff, t_now, t_old
     148          915 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: b_dx, dg, dr, dx, eigval, gold, s_raw, &
     149          915 :                                                             work, xold
     150          915 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: g
     151              :       TYPE(atomic_kind_list_type), POINTER               :: atomic_kinds
     152              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
     153              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct_hes
     154              :       TYPE(cp_fm_type)                                   :: eigvec_mat, hess_mat, hess_tmp
     155              :       TYPE(cp_logger_type), POINTER                      :: logger
     156              :       TYPE(cp_subsys_type), POINTER                      :: subsys
     157              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     158              :       TYPE(section_vals_type), POINTER                   :: print_key, root_section
     159              : 
     160          915 :       NULLIFY (logger, g, blacs_env)
     161         1830 :       logger => cp_get_default_logger()
     162          915 :       para_env => force_env%para_env
     163          915 :       root_section => force_env%root_section
     164          915 :       t_old = m_walltime()
     165              : 
     166          915 :       CALL timeset(routineN, handle)
     167          915 :       CALL section_vals_val_get(geo_section, "BFGS%TRUST_RADIUS", r_val=rad)
     168          915 :       print_key => section_vals_get_subs_vals(geo_section, "BFGS%RESTART")
     169          915 :       CALL section_vals_val_get(geo_section, "BFGS%METHOD", i_val=matrix_method, explicit=method_explicit)
     170          915 :       CALL section_vals_val_get(geo_section, "BFGS%USE_RAT_FUN_OPT", l_val=use_rfo)
     171          915 :       IF (use_rfo .AND. .NOT. method_explicit) matrix_method = bfgs_direct
     172          915 :       inverse = matrix_method == bfgs_inverse
     173          915 :       maxiter = gopt_param%max_iter
     174          915 :       conv = .FALSE.
     175          915 :       step_on_ray = .FALSE.
     176          915 :       rat = 0.0_dp
     177          915 :       wildcard = " BFGS"
     178              : 
     179              :       ! Stop if not yet implemented
     180          915 :       SELECT CASE (gopt_env%type_id)
     181              :       CASE (default_ts_method_id)
     182          915 :          CPABORT("BFGS method not yet working with DIMER")
     183              :       END SELECT
     184              : 
     185          915 :       CALL section_vals_val_get(geo_section, "BFGS%USE_MODEL_HESSIAN", l_val=use_mod_hes)
     186          915 :       CALL section_vals_val_get(geo_section, "BFGS%RESTART_HESSIAN", l_val=hesrest)
     187          915 :       IF (inverse .AND. use_rfo) THEN
     188              :          CALL cp_abort(__LOCATION__, &
     189            0 :                        "BFGS METHOD INVERSE does not support USE_RAT_FUN_OPT")
     190              :       END IF
     191              :       IF (inverse) THEN
     192          760 :          IF (.NOT. ieee_is_finite(rad) .OR. rad <= 0.0_dp) THEN
     193              :             CALL cp_abort(__LOCATION__, &
     194            0 :                           "BFGS TRUST_RADIUS must be finite and positive")
     195              :          END IF
     196              :       END IF
     197              :       output_unit = cp_print_key_unit_nr(logger, geo_section, "PRINT%PROGRAM_RUN_INFO", &
     198          915 :                                          extension=".geoLog")
     199          915 :       IF (output_unit > 0) THEN
     200          481 :          IF (inverse) THEN
     201          380 :             WRITE (UNIT=output_unit, FMT="(/,T2,A)") "BFGS| Matrix update method: INVERSE"
     202              :          ELSE
     203          101 :             WRITE (UNIT=output_unit, FMT="(/,T2,A)") "BFGS| Matrix update method: DIRECT"
     204              :          END IF
     205          481 :          IF (use_rfo) THEN
     206              :             WRITE (UNIT=output_unit, FMT="(/,T2,A,T78,A3)") &
     207            6 :                "BFGS| Use rational function optimization for step estimation: ", "YES"
     208              :          ELSE
     209              :             WRITE (UNIT=output_unit, FMT="(/,T2,A,T78,A3)") &
     210          475 :                "BFGS| Use rational function optimization for step estimation: ", " NO"
     211              :          END IF
     212          481 :          IF (use_mod_hes) THEN
     213              :             WRITE (UNIT=output_unit, FMT="(T2,A,T78,A3)") &
     214          411 :                "BFGS| Use model Hessian for initial guess: ", "YES"
     215              :          ELSE
     216              :             WRITE (UNIT=output_unit, FMT="(T2,A,T78,A3)") &
     217           70 :                "BFGS| Use model Hessian for initial guess: ", " NO"
     218              :          END IF
     219          481 :          IF (hesrest) THEN
     220              :             WRITE (UNIT=output_unit, FMT="(T2,A,T78,A3)") &
     221            5 :                "BFGS| Restart Hessian: ", "YES"
     222              :          ELSE
     223              :             WRITE (UNIT=output_unit, FMT="(T2,A,T78,A3)") &
     224          476 :                "BFGS| Restart Hessian: ", " NO"
     225              :          END IF
     226              :          WRITE (UNIT=output_unit, FMT="(T2,A,T61,F20.3)") &
     227          481 :             "BFGS| Trust radius: ", rad
     228              :       END IF
     229              : 
     230          915 :       ndf = SIZE(x0)
     231          915 :       IF (ndf > 3000 .AND. .NOT. inverse) THEN
     232              :          CALL cp_warn(__LOCATION__, &
     233              :                       "The dimension of the Hessian matrix ("// &
     234              :                       TRIM(ADJUSTL(cp_to_string(ndf)))//") is greater than 3000. "// &
     235              :                       "The diagonalisation of the full Hessian  matrix needed for BFGS "// &
     236              :                       "is computationally expensive. You should consider to use the linear "// &
     237            0 :                       "scaling variant L-BFGS instead.")
     238              :       END IF
     239              : 
     240              :       ! Initialize hessian (hes = unitary matrix or model hessian )
     241              :       CALL cp_blacs_env_create(blacs_env, para_env, globenv%blacs_grid_layout, &
     242          915 :                                globenv%blacs_repeatable)
     243              :       CALL cp_fm_struct_create(fm_struct_hes, para_env=para_env, context=blacs_env, &
     244          915 :                                nrow_global=ndf, ncol_global=ndf)
     245          915 :       CALL cp_fm_create(hess_mat, fm_struct_hes, name="hess_mat")
     246              : 
     247          915 :       CALL force_env_get(force_env=force_env, subsys=subsys)
     248          915 :       CALL cp_subsys_get(subsys, atomic_kinds=atomic_kinds)
     249          915 :       CALL get_atomic_kind_set(atomic_kind_set=atomic_kinds%els, shell_present=shell_present)
     250          915 :       IF (use_mod_hes) THEN
     251          775 :          IF (shell_present) THEN
     252              :             CALL cp_warn(__LOCATION__, &
     253              :                          "No model Hessian is available for core-shell models. "// &
     254            4 :                          "A unit matrix is used as the initial Hessian.")
     255            4 :             use_mod_hes = .FALSE.
     256              :          END IF
     257          775 :          IF (gopt_env%type_id == default_cell_method_id) THEN
     258              :             CALL cp_warn(__LOCATION__, &
     259              :                          "No model Hessian is available for cell optimizations. "// &
     260            0 :                          "A unit matrix is used as the initial Hessian.")
     261            0 :             use_mod_hes = .FALSE.
     262              :          END IF
     263              :       END IF
     264              : 
     265              :       ! hess_mat stores B for DIRECT and H = B^{-1} for INVERSE.
     266              :       ! DIRECT keeps the spectral work arrays for step construction; INVERSE
     267              :       ! only needs them while building a model-Hessian initial guess.
     268          915 :       IF (.NOT. inverse .OR. (use_mod_hes .AND. .NOT. hesrest)) THEN
     269          791 :          CALL cp_fm_create(hess_tmp, fm_struct_hes, name="hess_tmp")
     270          791 :          CALL cp_fm_create(eigvec_mat, fm_struct_hes, name="eigvec_mat")
     271         2373 :          ALLOCATE (eigval(ndf))
     272         1582 :          eigval(:) = zero
     273              :       END IF
     274              : 
     275          915 :       IF (inverse) THEN
     276          760 :          IF (use_mod_hes .AND. .NOT. hesrest) THEN
     277              :             CALL build_initial_hess(hess_mat, hess_tmp, eigvec_mat, eigval, force_env, &
     278          636 :                                     use_mod_hes, .TRUE.)
     279              :          ELSE
     280          124 :             CALL cp_fm_set_all(hess_mat, alpha=zero, beta=one)
     281              :          END IF
     282              :       ELSE
     283              :          CALL build_initial_hess(hess_mat, hess_tmp, eigvec_mat, eigval, force_env, &
     284          155 :                                  use_mod_hes, .FALSE.)
     285              :       END IF
     286              : 
     287          915 :       IF (inverse .AND. ALLOCATED(eigval)) THEN
     288          636 :          CALL cp_fm_release(eigvec_mat)
     289          636 :          CALL cp_fm_release(hess_tmp)
     290          636 :          DEALLOCATE (eigval)
     291              :       END IF
     292              : 
     293              :       ! Restore the reference coordinates before symmetry setup and the first evaluation.
     294          915 :       IF (hesrest) CALL read_bfgs_hessian(geo_section, hess_mat, logger, gopt_env, x0, matrix_method)
     295              : 
     296         2745 :       ALLOCATE (xold(ndf))
     297        26183 :       xold(:) = x0(:)
     298              : 
     299         1830 :       ALLOCATE (g(ndf))
     300        26183 :       g(:) = 0.0_dp
     301              : 
     302         1830 :       ALLOCATE (gold(ndf))
     303          915 :       gold(:) = 0.0_dp
     304              : 
     305         1830 :       ALLOCATE (dx(ndf))
     306          915 :       dx(:) = 0.0_dp
     307              : 
     308         1830 :       ALLOCATE (dg(ndf))
     309          915 :       dg(:) = 0.0_dp
     310              : 
     311         1830 :       ALLOCATE (work(ndf))
     312          915 :       work(:) = 0.0_dp
     313              : 
     314         1830 :       ALLOCATE (dr(ndf))
     315          915 :       dr(:) = 0.0_dp
     316          915 :       IF (inverse) THEN
     317         2280 :          ALLOCATE (b_dx(ndf), s_raw(ndf))
     318          760 :          b_dx(:) = 0.0_dp
     319          760 :          s_raw(:) = 0.0_dp
     320              :       END IF
     321              : 
     322              :       ! Geometry optimization starts now
     323          915 :       CALL cp_iterate(logger%iter_info, increment=0, iter_nr_out=iter_nr)
     324          915 :       CALL print_geo_opt_header(gopt_env, output_unit, wildcard)
     325              : 
     326              :       ! Calculate Energy & Gradients
     327              :       CALL cp_eval_at(gopt_env, x0, etot, g, master=gopt_env%force_env%para_env%mepos, &
     328          915 :                       para_env=gopt_env%force_env%para_env)
     329              : 
     330              :       ! Symmetrize coordinates and forces
     331          915 :       CALL gopt_f_project_coord(gopt_env, x0)
     332          915 :       CALL gopt_f_project_vector(gopt_env, g)
     333              : 
     334              :       ! Print info at time 0
     335          915 :       emin = etot
     336          915 :       t_now = m_walltime()
     337          915 :       t_diff = t_now - t_old
     338          915 :       t_old = t_now
     339          915 :       CALL gopt_f_io_init(gopt_env, output_unit, etot, wildcard=wildcard, its=iter_nr, used_time=t_diff)
     340         4604 :       DO its = iter_nr + 1, maxiter
     341         4594 :          CALL cp_iterate(logger%iter_info, last=(its == maxiter))
     342         4594 :          CALL section_vals_val_set(geo_section, "STEP_START_VAL", i_val=its)
     343         4594 :          CALL gopt_f_ii(its, output_unit)
     344              : 
     345         4594 :          IF ((its - iter_nr) > 1) THEN
     346              :             ! Symmetrize old coordinates and old forces.
     347         3689 :             CALL gopt_f_project_coord(gopt_env, xold)
     348         3689 :             CALL gopt_f_project_vector(gopt_env, gold)
     349              : 
     350              :             ! cp_eval_at may project the proposed geometry: use the actual displacement.
     351       353911 :             dx(:) = x0(:) - xold(:)
     352       353911 :             dg(:) = g(:) - gold(:)
     353         3689 :             IF (inverse) THEN
     354              :                ! Reuse step_on_ray checked when step dx = x0 - xold was accepted on the previous pass.
     355         1798 :                IF (step_on_ray) THEN
     356              :                   CALL bfgs_inverse_update(ndf, dx, dg, hess_mat, work, b_dx=b_dx, &
     357         1798 :                                            output_unit=output_unit)
     358              :                ELSE
     359            0 :                   CALL bfgs_inverse_update(ndf, dx, dg, hess_mat, work)
     360              :                END IF
     361              :             ELSE
     362         1891 :                CALL bfgs(ndf, dx, dg, hess_mat, work, para_env, output_unit, hess_reset)
     363         1891 :                IF (hess_reset) THEN
     364              :                   CALL build_initial_hess(hess_mat, hess_tmp, eigvec_mat, eigval, force_env, &
     365            0 :                                           use_mod_hes, .FALSE.)
     366              :                END IF
     367              :             END IF
     368              : 
     369         3689 :             CALL gopt_f_project_vector(gopt_env, dx)
     370         3689 :             CALL gopt_f_project_vector(gopt_env, dg)
     371              : 
     372         3689 :             IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
     373         3364 :                CALL write_bfgs_hessian(geo_section, hess_mat, logger, gopt_env, matrix_method)
     374              :             END IF
     375              :          END IF
     376              : 
     377              :          ! Symmetrize coordinates and forces
     378         4594 :          CALL gopt_f_project_coord(gopt_env, x0)
     379         4594 :          CALL gopt_f_project_vector(gopt_env, g)
     380              : 
     381              :          ! Setting the present positions & gradients as old
     382       379940 :          xold(:) = x0
     383       379940 :          gold(:) = g
     384              : 
     385         4594 :          IF (inverse) THEN
     386         2548 :             CALL bfgs_inverse_step(hess_mat, g, dr)
     387       172234 :             s_raw(:) = dr(:)
     388              :          ELSE
     389              :             ! Copying hessian hes to (ndf x ndf) matrix hes_mat for diagonalization
     390         2046 :             CALL cp_fm_to_fm(hess_mat, hess_tmp)
     391              : 
     392         2046 :             CALL choose_eigv_solver(hess_tmp, eigvec_mat, eigval, info=info)
     393              : 
     394              :             ! In rare cases the diagonalization of hess_mat fails (bug in scalapack?)
     395         2046 :             IF (info /= 0) THEN
     396            0 :                IF (output_unit > 0) THEN
     397              :                   WRITE (output_unit, *) &
     398            0 :                      "BFGS: Matrix diagonalization failed, resetting Hessian to unity."
     399              :                END IF
     400            0 :                CALL cp_fm_set_all(hess_mat, alpha=zero, beta=one)
     401            0 :                CALL cp_fm_to_fm(hess_mat, hess_tmp)
     402            0 :                CALL choose_eigv_solver(hess_tmp, eigvec_mat, eigval)
     403              :             END IF
     404              : 
     405         2046 :             IF (use_rfo) THEN
     406          542 :                CALL set_hes_eig(ndf, eigval, work)
     407        75180 :                dx(:) = eigval
     408          542 :                CALL rat_fun_opt(ndf, dg, eigval, work, eigvec_mat, g, para_env)
     409              :             END IF
     410         2046 :             CALL geoopt_get_step(ndf, eigval, eigvec_mat, hess_tmp, dr, g, para_env, use_rfo)
     411              : 
     412              :          END IF
     413         4594 :          CALL gopt_f_project_vector(gopt_env, dr)
     414              : 
     415         4594 :          IF (inverse) THEN
     416              :             ! Avoid a zero-step division and initialize the reported scale on every step.
     417         2548 :             rat = 1.0_dp
     418       172234 :             step = MAXVAL(ABS(dr))
     419         2548 :             IF (step > rad) THEN
     420          294 :                rat = rad/step
     421        19892 :                dr(:) = rat*dr(:)
     422              :                step = rad
     423              :             END IF
     424              :             ! Along the scaled inverse-Newton ray s_raw = rat*(-H*g), B*s_raw = -rat*g
     425              :             ! holds without forming B, enabling primal Powell damping next step.
     426       172234 :             s_raw(:) = rat*s_raw(:)
     427       172234 :             b_dx(:) = -rat*gold(:)
     428              :          ELSE
     429         2046 :             CALL trust_radius(ndf, step, rad, rat, dr, output_unit)
     430              :          END IF
     431              : 
     432              :          ! Update the atomic positions
     433       379940 :          x0 = x0 + dr
     434              : 
     435              :          ! Symmetrize coordinates
     436         4594 :          CALL gopt_f_project_coord(gopt_env, x0)
     437              : 
     438         4594 :          eold = etot
     439              : 
     440              :          ! Energy & Gradients at new step
     441              :          CALL cp_eval_at(gopt_env, x0, etot, g, master=gopt_env%force_env%para_env%mepos, &
     442         4594 :                          para_env=gopt_env%force_env%para_env)
     443              : 
     444              :          ! Use the displacement actually accepted by constraints and cell projection.
     445       379940 :          dr(:) = x0(:) - xold(:)
     446       379940 :          step = MAXVAL(ABS(dr))
     447              : 
     448         4594 :          IF (inverse) THEN
     449         2548 :             step_on_ray = is_step_on_ray(x0, xold, s_raw, dr)
     450         2548 :             CALL para_env%bcast(step_on_ray, para_env%source)
     451              :             ! When dr stays on the ray rat*(-H*gold), B*dr = -rat*gold holds without forming B.
     452       172202 :             IF (step_on_ray) pred = (one - 0.5_dp*rat)*DOT_PRODUCT(gold, dr)
     453              :          ELSE
     454         2046 :             CALL energy_predict(ndf, work, hess_mat, dr, gold, pred, para_env)
     455         2046 :             step_on_ray = .TRUE.
     456              :          END IF
     457              : 
     458         4594 :          ediff = etot - eold
     459              : 
     460              :          ! Symmetrize forces
     461         4594 :          CALL gopt_f_project_vector(gopt_env, g)
     462              : 
     463              :          ! check for an external exit command
     464         4594 :          CALL external_control(should_stop, "GEO", globenv=globenv)
     465         4594 :          IF (should_stop) EXIT
     466              : 
     467              :          ! Some IO and Convergence check
     468         4594 :          t_now = m_walltime()
     469         4594 :          t_diff = t_now - t_old
     470         4594 :          t_old = t_now
     471         4594 :          IF (step_on_ray) THEN
     472              :             CALL gopt_f_io(gopt_env, force_env, root_section, its, etot, output_unit, &
     473              :                            eold, emin, wildcard, gopt_param, ndf, dr, g, conv, pred, rat, &
     474         4590 :                            step, rad, used_time=t_diff)
     475              :          ELSE
     476              :             CALL gopt_f_io(gopt_env, force_env, root_section, its, etot, output_unit, &
     477              :                            eold, emin, wildcard, gopt_param, ndf, dr, g, conv, &
     478            4 :                            rat=rat, step=step, rad=rad, used_time=t_diff)
     479              :          END IF
     480              : 
     481         4594 :          IF (conv .OR. (its == maxiter)) EXIT
     482         3689 :          IF (etot < emin) emin = etot
     483        13792 :          IF (use_rfo) CALL update_trust_rad(rat, rad, step, ediff)
     484              :       END DO
     485              : 
     486          915 :       IF (its == maxiter .AND. (.NOT. conv)) THEN
     487          633 :          CALL print_geo_opt_nc(gopt_env, output_unit)
     488              :       END IF
     489              : 
     490              :       ! Write final  information, if converged
     491          915 :       CALL cp_iterate(logger%iter_info, last=.TRUE., increment=0)
     492          915 :       CALL write_bfgs_hessian(geo_section, hess_mat, logger, gopt_env, matrix_method)
     493              :       CALL gopt_f_io_finalize(gopt_env, force_env, x0, conv, its, root_section, &
     494          915 :                               gopt_env%force_env%para_env, gopt_env%force_env%para_env%mepos, output_unit)
     495              : 
     496          915 :       CALL cp_fm_struct_release(fm_struct_hes)
     497          915 :       CALL cp_fm_release(hess_mat)
     498          915 :       IF (.NOT. inverse) THEN
     499          155 :          CALL cp_fm_release(eigvec_mat)
     500          155 :          CALL cp_fm_release(hess_tmp)
     501              :       END IF
     502              : 
     503          915 :       CALL cp_blacs_env_release(blacs_env)
     504          915 :       DEALLOCATE (xold)
     505          915 :       DEALLOCATE (g)
     506          915 :       DEALLOCATE (gold)
     507          915 :       DEALLOCATE (dx)
     508          915 :       DEALLOCATE (dg)
     509          915 :       IF (ALLOCATED(eigval)) DEALLOCATE (eigval)
     510          915 :       DEALLOCATE (work)
     511          915 :       DEALLOCATE (dr)
     512          915 :       IF (ALLOCATED(b_dx)) DEALLOCATE (b_dx)
     513          915 :       IF (ALLOCATED(s_raw)) DEALLOCATE (s_raw)
     514              : 
     515              :       CALL cp_print_key_finished_output(output_unit, logger, geo_section, &
     516          915 :                                         "PRINT%PROGRAM_RUN_INFO")
     517          915 :       CALL timestop(handle)
     518              : 
     519         7320 :    END SUBROUTINE geoopt_bfgs
     520              : 
     521              : ! **************************************************************************************************
     522              : !> \brief Check whether the accepted geometry x0 remains on xold + s_raw.
     523              : !> \param x0 Accepted coordinates after projection and evaluation
     524              : !> \param xold Coordinates at the start of the step
     525              : !> \param s_raw Scaled inverse-Newton trial displacement
     526              : !> \param step_vec Accepted displacement x0 - xold
     527              : !> \return True when constraints or projections did not deflect the step off the ray
     528              : ! **************************************************************************************************
     529         2548 :    PURE FUNCTION is_step_on_ray(x0, xold, s_raw, step_vec) RESULT(on_ray)
     530              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: x0, xold, s_raw, step_vec
     531              :       LOGICAL                                            :: on_ray
     532              : 
     533              :       REAL(KIND=dp), PARAMETER :: coord_roundoff_tol = 64.0_dp*EPSILON(1.0_dp), &
     534              :          primal_step_tol = 1.0E-10_dp
     535              : 
     536              :       REAL(KIND=dp)                                      :: tol
     537              : 
     538              :       ! Compare x0 against xold + s_raw directly so small steps avoid cancellation noise, while
     539              :       ! still allowing coordinate-scale roundoff from projection transforms.
     540              :       tol = MAX(primal_step_tol*MAXVAL(ABS(step_vec)), &
     541       344468 :                 coord_roundoff_tol*MAXVAL(ABS(x0)), TINY(1.0_dp))
     542       172234 :       on_ray = MAXVAL(ABS(x0 - (xold + s_raw))) <= tol
     543         2548 :    END FUNCTION is_step_on_ray
     544              : 
     545              : ! **************************************************************************************************
     546              : !> \brief Damped inverse-BFGS update, using only a matvec and local rank-two updates.
     547              : !> \param ndf Number of optimization variables
     548              : !> \param dx Actual change of optimization variables (not modified by damping)
     549              : !> \param dg Change of gradients in the same coordinate system
     550              : !> \param hess_mat Inverse Hessian, updated in place
     551              : !> \param work Replicated workspace for H*dg
     552              : !> \param b_dx Optional direct Hessian action B*dx; when present, applies
     553              : !>             primal Powell damping via Sherman-Morrison-Woodbury
     554              : !> \param output_unit Optional geometry log unit for damping diagnostics
     555              : ! **************************************************************************************************
     556         1798 :    SUBROUTINE bfgs_inverse_update(ndf, dx, dg, hess_mat, work, b_dx, output_unit)
     557              :       INTEGER, INTENT(IN)                                :: ndf
     558              :       REAL(KIND=dp), INTENT(IN)                          :: dx(ndf), dg(ndf)
     559              :       TYPE(cp_fm_type), INTENT(IN)                       :: hess_mat
     560              :       REAL(KIND=dp), INTENT(OUT)                         :: work(ndf)
     561              :       REAL(KIND=dp), INTENT(IN), OPTIONAL                :: b_dx(ndf)
     562              :       INTEGER, INTENT(IN), OPTIONAL                      :: output_unit
     563              : 
     564              :       REAL(KIND=dp), PARAMETER                           :: min_curvature = 0.2_dp, &
     565              :                                                             min_sbs = 10.0_dp*TINY(1.0_dp)
     566              : 
     567              :       INTEGER                                            :: handle, i, ig, invalid, j, jg, nc, nr
     568         1798 :       INTEGER, DIMENSION(:), POINTER                     :: cols, rows
     569              :       REAL(KIND=dp)                                      :: coeff, rho, sbs, sy, theta, yhy
     570              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
     571         1798 :          POINTER                                         :: data
     572         1798 :       REAL(KIND=dp), DIMENSION(ndf)                      :: secant
     573              : 
     574         1798 :       CALL timeset("bfgs_inverse_update", handle)
     575       312408 :       IF (.NOT. ALL(ieee_is_finite(dx)) .OR. .NOT. ALL(ieee_is_finite(dg))) THEN
     576            0 :          CPABORT("Non-finite displacement or gradient difference in inverse BFGS")
     577              :       END IF
     578         1798 :       IF (PRESENT(b_dx)) THEN
     579       156204 :          IF (.NOT. ALL(ieee_is_finite(b_dx))) THEN
     580            0 :             CPABORT("Non-finite curvature vector in inverse BFGS")
     581              :          END IF
     582              :       END IF
     583       156204 :       work = 0.0_dp
     584       310610 :       IF (NORM2(dx) == 0.0_dp .OR. NORM2(dg) == 0.0_dp) THEN
     585            0 :          CALL timestop(handle)
     586            0 :          RETURN
     587              :       END IF
     588              : 
     589         1798 :       CALL cp_fm_matvec(hess_mat, dg, work)
     590       156204 :       sy = DOT_PRODUCT(dx, dg)
     591       156204 :       yhy = DOT_PRODUCT(dg, work)
     592         1798 :       IF (.NOT. ieee_is_finite(sy) .OR. .NOT. ieee_is_finite(yhy)) THEN
     593            0 :          CPABORT("Non-finite curvature in inverse BFGS")
     594              :       END IF
     595         1798 :       invalid = 0
     596         1798 :       IF (yhy <= 0.0_dp) invalid = 1
     597         1798 :       CALL hess_mat%matrix_struct%para_env%max(invalid)
     598         1798 :       IF (invalid /= 0) THEN
     599              :          CALL cp_warn(__LOCATION__, &
     600            0 :                       "BFGS: non-positive inverse curvature; resetting to unity.")
     601            0 :          CALL cp_fm_set_all(hess_mat, alpha=0.0_dp, beta=1.0_dp)
     602            0 :          CALL timestop(handle)
     603            0 :          RETURN
     604              :       END IF
     605              : 
     606       156204 :       secant = dx
     607         1798 :       IF (PRESENT(b_dx)) THEN
     608              :          ! Primal Powell damping in inverse form: with H*b_dx = dx, replacing y
     609              :          ! by eta = theta*y + (1-theta)*B*s maps H*eta = theta*H*y + (1-theta)*dx
     610              :          ! without forming B, yielding the exact inverse of the DIRECT update.
     611       156204 :          sbs = DOT_PRODUCT(dx, b_dx)
     612         1798 :          invalid = 0
     613         1798 :          IF (.NOT. ieee_is_finite(sbs) .OR. sbs <= MAX(EPSILON(1.0_dp)*ABS(sy), min_sbs)) invalid = 1
     614         1798 :          CALL hess_mat%matrix_struct%para_env%max(invalid)
     615         1798 :          IF (invalid /= 0) THEN
     616              :             CALL cp_warn(__LOCATION__, &
     617            0 :                          "BFGS: vanishing or non-positive predicted curvature; resetting to unity.")
     618            0 :             CALL cp_fm_set_all(hess_mat, alpha=0.0_dp, beta=1.0_dp)
     619            0 :             CALL timestop(handle)
     620            0 :             RETURN
     621              :          END IF
     622         1798 :          IF (sy < min_curvature*sbs) THEN
     623           16 :             theta = ((1.0_dp - min_curvature)*sbs)/(sbs - sy)
     624           16 :             IF (PRESENT(output_unit)) THEN
     625           16 :                IF (output_unit > 0) THEN
     626              :                   WRITE (UNIT=output_unit, FMT="(T2,A,F10.4,A,F3.1,A)") &
     627            8 :                      "BFGS| Damped update, curvature ratio y.s/(s.B.s): ", sy/sbs, &
     628           16 :                      " (threshold ", min_curvature, ")"
     629            8 :                   CALL m_flush(output_unit)
     630              :                END IF
     631              :             END IF
     632         1794 :             work = theta*work + (1.0_dp - theta)*dx
     633           16 :             sy = theta*sy + (1.0_dp - theta)*sbs
     634         3572 :             yhy = theta*DOT_PRODUCT(dg, work) + (1.0_dp - theta)*DOT_PRODUCT(b_dx, work)
     635              :          END IF
     636            0 :       ELSE IF (sy < min_curvature*yhy) THEN
     637              :          ! Dual-space damping: y^T*s_tilde >= min_curvature*y^T*H*y.
     638              :          ! Unlike damping y with B*s, this does not need the direct Hessian.
     639            0 :          theta = ((1.0_dp - min_curvature)*yhy)/(yhy - sy)
     640            0 :          secant = theta*dx + (1.0_dp - theta)*work
     641            0 :          sy = DOT_PRODUCT(secant, dg)
     642              :       END IF
     643         1798 :       IF (sy <= TINY(1.0_dp)/EPSILON(1.0_dp)) THEN
     644            0 :          CALL timestop(handle)
     645            0 :          RETURN
     646              :       END IF
     647         1798 :       rho = 1.0_dp/sy
     648         1798 :       coeff = (1.0_dp + yhy*rho)*rho
     649         1798 :       IF (.NOT. ieee_is_finite(coeff)) THEN
     650              :          CALL cp_warn(__LOCATION__, &
     651            0 :                       "BFGS: unrepresentable inverse update; retaining the previous matrix.")
     652            0 :          CALL timestop(handle)
     653            0 :          RETURN
     654              :       END IF
     655              : 
     656              :       CALL cp_fm_get_info(hess_mat, row_indices=rows, col_indices=cols, &
     657         1798 :                           local_data=DATA, nrow_local=nr, ncol_local=nc)
     658         1798 :       !$OMP PARALLEL DO DEFAULT(NONE) SHARED(nc,nr,rows,cols,data,coeff,rho,secant,work) PRIVATE(i,j,ig,jg)
     659              :       DO j = 1, nc
     660              :          jg = cols(j)
     661              :          DO i = 1, nr
     662              :             ig = rows(i)
     663              :             DATA(i, j) = DATA(i, j) + coeff*(secant(ig)*secant(jg)) - &
     664              :                          rho*(secant(ig)*work(jg) + work(ig)*secant(jg))
     665              :          END DO
     666              :       END DO
     667              :       !$OMP END PARALLEL DO
     668         1798 :       invalid = 0
     669     13207659 :       IF (.NOT. ALL(ieee_is_finite(DATA(1:nr, 1:nc)))) invalid = 1
     670         1798 :       CALL hess_mat%matrix_struct%para_env%max(invalid)
     671         1798 :       IF (invalid /= 0) THEN
     672              :          CALL cp_warn(__LOCATION__, &
     673            0 :                       "BFGS: non-finite inverse matrix; resetting to unity.")
     674            0 :          CALL cp_fm_set_all(hess_mat, alpha=0.0_dp, beta=1.0_dp)
     675              :       END IF
     676         1798 :       CALL timestop(handle)
     677         3596 :    END SUBROUTINE bfgs_inverse_update
     678              : 
     679              : ! **************************************************************************************************
     680              : !> \brief Form -H*g and recover a descent direction if roundoff has corrupted H.
     681              : !> \param hess_mat Inverse Hessian
     682              : !> \param g Gradient
     683              : !> \param dr Search direction
     684              : ! **************************************************************************************************
     685         2548 :    SUBROUTINE bfgs_inverse_step(hess_mat, g, dr)
     686              :       TYPE(cp_fm_type), INTENT(IN)                       :: hess_mat
     687              :       REAL(KIND=dp), INTENT(IN)                          :: g(:)
     688              :       REAL(KIND=dp), INTENT(OUT)                         :: dr(:)
     689              : 
     690              :       REAL(KIND=dp)                                      :: slope
     691              : 
     692       172234 :       IF (.NOT. ALL(ieee_is_finite(g))) THEN
     693            0 :          CALL cp_abort(__LOCATION__, "Non-finite gradient in inverse BFGS")
     694              :       END IF
     695       172234 :       dr = 0.0_dp
     696       172234 :       IF (MAXVAL(ABS(g)) == 0.0_dp) RETURN
     697         2548 :       CALL cp_fm_matvec(hess_mat, g, dr, alpha=-1.0_dp)
     698       172234 :       slope = DOT_PRODUCT(g, dr)
     699         2548 :       IF (.NOT. ieee_is_finite(slope) .OR. slope >= 0.0_dp) THEN
     700              :          CALL cp_warn(__LOCATION__, &
     701            0 :                       "BFGS: inverse matrix is not a descent model; resetting to unity.")
     702            0 :          CALL cp_fm_set_all(hess_mat, alpha=0.0_dp, beta=1.0_dp)
     703         2548 :          dr = -g
     704              :       END IF
     705              :    END SUBROUTINE bfgs_inverse_step
     706              : 
     707              : ! **************************************************************************************************
     708              : !> \brief Convert a restart matrix once, not during normal inverse-BFGS iterations.
     709              : !> \param matrix Input matrix, replaced by its (regularized) inverse
     710              : !> \param from_inverse Whether the input already represents the inverse Hessian
     711              : ! **************************************************************************************************
     712            6 :    SUBROUTINE bfgs_invert_matrix(matrix, from_inverse)
     713              :       TYPE(cp_fm_type), INTENT(IN)                       :: matrix
     714              :       LOGICAL, INTENT(IN)                                :: from_inverse
     715              : 
     716              :       INTEGER                                            :: handle, info, ndf
     717              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenvalues
     718              :       TYPE(cp_fm_struct_type), POINTER                   :: matrix_struct
     719              :       TYPE(cp_fm_type)                                   :: eigenvectors, scratch
     720              : 
     721            6 :       CALL timeset("bfgs_invert_matrix", handle)
     722            6 :       CALL cp_fm_get_info(matrix, matrix_struct=matrix_struct, nrow_global=ndf)
     723            6 :       CALL cp_fm_create(scratch, matrix_struct, name="bfgs_restart_scratch")
     724            6 :       CALL cp_fm_create(eigenvectors, matrix_struct, name="bfgs_restart_eigenvectors")
     725           18 :       ALLOCATE (eigenvalues(ndf))
     726            6 :       CALL cp_fm_to_fm(matrix, scratch)
     727            6 :       CALL choose_eigv_solver(scratch, eigenvectors, eigenvalues, info=info)
     728            6 :       IF (info /= 0) THEN
     729            0 :          CALL cp_abort(__LOCATION__, "BFGS restart matrix diagonalization failed")
     730              :       END IF
     731          246 :       IF (.NOT. ALL(ieee_is_finite(eigenvalues))) THEN
     732            0 :          CALL cp_abort(__LOCATION__, "Non-finite BFGS restart spectrum")
     733              :       END IF
     734            6 :       IF (from_inverse) THEN
     735              :          ! Do not apply the direct-Hessian cutoff to inverse-Hessian eigenvalues.
     736          220 :          IF (MINVAL(eigenvalues) <= 0.0_dp) THEN
     737              :             CALL cp_abort(__LOCATION__, &
     738            0 :                           "BFGS inverse restart matrix is not positive definite")
     739              :          END IF
     740              :       ELSE
     741           26 :          IF (MINVAL(eigenvalues) < min_hessian_eigenvalue) THEN
     742              :             CALL cp_warn(__LOCATION__, &
     743            0 :                          "BFGS: regularizing the direct restart before conversion to INVERSE.")
     744              :          END IF
     745           26 :          eigenvalues(:) = MAX(min_hessian_eigenvalue, eigenvalues(:))
     746              :       END IF
     747          246 :       eigenvalues(:) = 1.0_dp/eigenvalues(:)
     748          246 :       IF (.NOT. ALL(ieee_is_finite(eigenvalues))) THEN
     749              :          CALL cp_abort(__LOCATION__, &
     750            0 :                        "Unrepresentable inverse of BFGS restart matrix")
     751              :       END IF
     752            6 :       CALL cp_fm_to_fm(eigenvectors, scratch)
     753            6 :       CALL cp_fm_column_scale(scratch, eigenvalues)
     754            6 :       CALL parallel_gemm("N", "T", ndf, ndf, ndf, 1.0_dp, scratch, eigenvectors, 0.0_dp, matrix)
     755            6 :       CALL cp_fm_release(scratch)
     756            6 :       CALL cp_fm_release(eigenvectors)
     757            6 :       DEALLOCATE (eigenvalues)
     758            6 :       CALL timestop(handle)
     759           12 :    END SUBROUTINE bfgs_invert_matrix
     760              : 
     761              : ! **************************************************************************************************
     762              : !> \brief Read the metadata of a tagged BFGS restart, or identify a legacy raw Hessian.
     763              : !> \param unit File unit, returned positioned at the first matrix column
     764              : !> \param stored_method Matrix representation in the file
     765              : !> \param stored_ndf Matrix dimension stored in a tagged file; zero for legacy files
     766              : !> \param stored_type Optimization type stored in a tagged file; zero for legacy files
     767              : !> \param tagged Whether the file contains coordinate and representation metadata
     768              : !> \param reference_cell Stored CELL_OPT reference cell
     769              : !> \param cell_frame Stored canonical-to-input cell frame
     770              : ! **************************************************************************************************
     771            9 :    SUBROUTINE bfgs_read_restart_header(unit, stored_method, stored_ndf, stored_type, tagged, &
     772              :                                        reference_cell, cell_frame)
     773              :       INTEGER, INTENT(IN)                                :: unit
     774              :       INTEGER, INTENT(OUT)                               :: stored_method, stored_ndf, stored_type
     775              :       LOGICAL, INTENT(OUT)                               :: tagged
     776              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(OUT)        :: reference_cell, cell_frame
     777              : 
     778              :       CHARACTER(LEN=16)                                  :: magic
     779              :       INTEGER                                            :: ios, version
     780              : 
     781            9 :       stored_method = bfgs_direct
     782            9 :       stored_ndf = 0
     783            9 :       stored_type = 0
     784            9 :       reference_cell = 0.0_dp
     785            9 :       cell_frame = 0.0_dp
     786            9 :       magic = ""
     787            9 :       READ (unit, IOSTAT=ios) magic
     788            9 :       tagged = ios == 0 .AND. magic == bfgs_restart_magic
     789            9 :       REWIND (unit)
     790            9 :       IF (tagged) THEN
     791            9 :          READ (unit, IOSTAT=ios) magic, version, stored_method, stored_ndf, stored_type, &
     792           18 :             reference_cell, cell_frame
     793            9 :          IF (ios /= 0) CPABORT("Invalid BFGS restart header")
     794            9 :          IF (version /= bfgs_restart_version) THEN
     795            0 :             CALL cp_abort(__LOCATION__, "Unsupported BFGS restart version")
     796              :          END IF
     797            9 :          IF (stored_method /= bfgs_direct .AND. stored_method /= bfgs_inverse) THEN
     798            0 :             CPABORT("Unknown matrix representation in BFGS restart")
     799              :          END IF
     800            9 :          IF (stored_ndf <= 0) CPABORT("Invalid matrix dimension in BFGS restart")
     801          234 :          IF (.NOT. ALL(ieee_is_finite(reference_cell)) .OR. .NOT. ALL(ieee_is_finite(cell_frame))) THEN
     802            0 :             CPABORT("Non-finite coordinate frame in BFGS restart")
     803              :          END IF
     804              :       END IF
     805            9 :    END SUBROUTINE bfgs_read_restart_header
     806              : 
     807              : ! **************************************************************************************************
     808              : !> \brief Read and validate a tagged or legacy BFGS restart on the I/O rank.
     809              : !> \param unit File unit, returned positioned at the first matrix column
     810              : !> \param ndf Expected dimension
     811              : !> \param opt_type Expected optimization type
     812              : !> \param stored_method Matrix representation in the file
     813              : !> \param tagged Whether the file contains coordinate and representation metadata
     814              : !> \param reference_cell Stored CELL_OPT reference cell
     815              : !> \param cell_frame Stored canonical-to-input cell frame
     816              : ! **************************************************************************************************
     817            5 :    SUBROUTINE bfgs_read_header(unit, ndf, opt_type, stored_method, tagged, reference_cell, cell_frame)
     818              :       INTEGER, INTENT(IN)                                :: unit, ndf, opt_type
     819              :       INTEGER, INTENT(OUT)                               :: stored_method
     820              :       LOGICAL, INTENT(OUT)                               :: tagged
     821              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(OUT)        :: reference_cell, cell_frame
     822              : 
     823              :       INTEGER                                            :: ios, j, stored_ndf, stored_type
     824              :       REAL(KIND=dp)                                      :: extra
     825           10 :       REAL(KIND=dp), DIMENSION(ndf)                      :: column
     826              : 
     827              :       CALL bfgs_read_restart_header(unit, stored_method, stored_ndf, stored_type, tagged, &
     828            5 :                                     reference_cell, cell_frame)
     829            5 :       IF (tagged) THEN
     830            5 :          IF (stored_ndf /= ndf) THEN
     831              :             CALL cp_abort(__LOCATION__, &
     832            0 :                           "BFGS restart dimension does not match the optimization variables")
     833              :          END IF
     834            5 :          IF (stored_type /= opt_type) THEN
     835            0 :             CALL cp_abort(__LOCATION__, "BFGS restart optimization type does not match")
     836              :          END IF
     837              :       END IF
     838              : 
     839              :       ! Preflight before any collective read: reject truncated/non-finite payloads and
     840              :       ! incompatible legacy dimensions with a CP2K error, not a rank-local Fortran I/O failure.
     841          151 :       DO j = 1, ndf
     842          146 :          READ (unit, IOSTAT=ios) column
     843          146 :          IF (ios /= 0) THEN
     844              :             CALL cp_abort(__LOCATION__, &
     845            0 :                           "Truncated BFGS restart or incompatible legacy matrix dimension")
     846              :          END IF
     847         9995 :          IF (.NOT. ALL(ieee_is_finite(column))) THEN
     848            0 :             CALL cp_abort(__LOCATION__, "Non-finite matrix in BFGS restart")
     849              :          END IF
     850              :       END DO
     851            5 :       READ (unit, IOSTAT=ios) extra
     852            5 :       IF (ios /= iostat_end) THEN
     853              :          CALL cp_abort(__LOCATION__, &
     854            0 :                        "Extra matrix columns or invalid trailing data in BFGS restart")
     855              :       END IF
     856            5 :       REWIND (unit)
     857            5 :       IF (tagged) READ (unit)
     858            5 :    END SUBROUTINE bfgs_read_header
     859              : 
     860              : ! **************************************************************************************************
     861              : !> \brief Read a common BFGS restart, restoring its coordinates and converting if needed.
     862              : !> \param geo_section BFGS input section
     863              : !> \param hess_mat Matrix to initialize
     864              : !> \param logger Logger
     865              : !> \param gopt_env Optimization environment
     866              : !> \param x0 Current coordinates, re-expressed in the stored reference cell for CELL_OPT
     867              : !> \param matrix_method Requested in-memory representation
     868              : ! **************************************************************************************************
     869           10 :    SUBROUTINE read_bfgs_hessian(geo_section, hess_mat, logger, gopt_env, x0, matrix_method)
     870              :       TYPE(section_vals_type), POINTER                   :: geo_section
     871              :       TYPE(cp_fm_type), INTENT(INOUT)                    :: hess_mat
     872              :       TYPE(cp_logger_type), POINTER                      :: logger
     873              :       TYPE(gopt_f_type), POINTER                         :: gopt_env
     874              :       REAL(KIND=dp), DIMENSION(:), INTENT(INOUT)         :: x0
     875              :       INTEGER, INTENT(IN)                                :: matrix_method
     876              : 
     877              :       CHARACTER(LEN=default_path_length)                 :: filename
     878              :       INTEGER                                            :: ndf, stored_method, unit
     879              :       LOGICAL                                            :: tagged
     880              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: cell_frame, reference_cell
     881              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     882              : 
     883           10 :       para_env => gopt_env%force_env%para_env
     884           10 :       ndf = SIZE(x0)
     885           10 :       unit = -1
     886           10 :       IF (para_env%is_source()) THEN
     887            5 :          CALL section_vals_val_get(geo_section, "BFGS%RESTART_FILE_NAME", c_val=filename)
     888            5 :          IF (LEN_TRIM(filename) == 0) filename = TRIM(logger%iter_info%project_name)//"-BFGS.Hessian"
     889              :          CALL open_file(file_name=TRIM(filename), file_status="OLD", &
     890            5 :                         file_form="UNFORMATTED", file_action="READ", unit_number=unit)
     891            5 :          CALL bfgs_read_header(unit, ndf, gopt_env%type_id, stored_method, tagged, reference_cell, cell_frame)
     892              :       END IF
     893           10 :       CALL para_env%bcast(stored_method, 0)
     894           10 :       CALL para_env%bcast(tagged, 0)
     895           10 :       CALL para_env%bcast(reference_cell, 0)
     896           10 :       CALL para_env%bcast(cell_frame, 0)
     897           10 :       CALL cp_fm_read_unformatted(hess_mat, unit)
     898           10 :       IF (para_env%is_source()) CALL close_file(unit_number=unit)
     899              : 
     900           10 :       IF (gopt_env%type_id == default_cell_method_id) THEN
     901            4 :          IF (tagged) THEN
     902            4 :             CALL bfgs_restore_cell_frame(gopt_env, x0, reference_cell, cell_frame)
     903              :          ELSE
     904              :             CALL cp_warn(__LOCATION__, "Legacy BFGS restart has no reference cell; "// &
     905            0 :                          "assuming the current CELL_OPT coordinate frame. Exact frame recovery is not possible.")
     906              :          END IF
     907              :       END IF
     908           10 :       IF (stored_method /= matrix_method) THEN
     909            6 :          CALL bfgs_invert_matrix(hess_mat, stored_method == bfgs_inverse)
     910              :       END IF
     911           10 :    END SUBROUTINE read_bfgs_hessian
     912              : 
     913              : ! **************************************************************************************************
     914              : !> \brief Re-express coordinates in the saved frame without changing physical positions.
     915              : !> \param gopt_env Optimization environment
     916              : !> \param x0 Optimization coordinates
     917              : !> \param reference_cell Reference cell that defines the stored Hessian coordinates
     918              : !> \param cell_frame Canonical-to-input cell orientation used when writing the matrix
     919              : ! **************************************************************************************************
     920            4 :    SUBROUTINE bfgs_restore_cell_frame(gopt_env, x0, reference_cell, cell_frame)
     921              :       TYPE(gopt_f_type), POINTER                         :: gopt_env
     922              :       REAL(KIND=dp), DIMENSION(:), INTENT(INOUT)         :: x0
     923              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN)         :: reference_cell, cell_frame
     924              : 
     925              :       INTEGER                                            :: i
     926              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: transform
     927              : 
     928              :       ! A normal continuation preserves this orientation even when lengths and angles change.
     929              :       ! Do not silently attach a matrix to a separately rotated or reordered structure.
     930           52 :       IF (MAXVAL(ABS(cell_frame - gopt_env%cell_env%opt_to_input)) > 1.0E-8_dp) THEN
     931              :          CALL cp_abort(__LOCATION__, &
     932            0 :                        "BFGS restart cell orientation differs; use a matching structure or RESTART_HESSIAN F")
     933              :       END IF
     934           52 :       IF (ABS(det_3x3(reference_cell)) <= EPSILON(1.0_dp)*MAXVAL(ABS(reference_cell))**3) THEN
     935            0 :          CPABORT("Singular reference cell in BFGS restart")
     936              :       END IF
     937          268 :       transform = MATMUL(reference_cell, inv_3x3(gopt_env%h_ref))
     938           72 :       DO i = 1, 3*force_env_get_nparticle(gopt_env%force_env), 3
     939         1296 :          x0(i:i + 2) = MATMUL(transform, x0(i:i + 2))
     940              :       END DO
     941            4 :       CALL gopt_f_set_h_ref(gopt_env, reference_cell)
     942            4 :       CALL gopt_f_restore_cell_manifold(gopt_env, reference_cell, x0)
     943            4 :    END SUBROUTINE bfgs_restore_cell_frame
     944              : 
     945              : ! **************************************************************************************************
     946              : !> \brief ...
     947              : !> \param ndf ...
     948              : !> \param dg ...
     949              : !> \param eigval ...
     950              : !> \param work ...
     951              : !> \param eigvec_mat ...
     952              : !> \param g ...
     953              : !> \param para_env ...
     954              : ! **************************************************************************************************
     955         1084 :    SUBROUTINE rat_fun_opt(ndf, dg, eigval, work, eigvec_mat, g, para_env)
     956              : 
     957              :       INTEGER, INTENT(IN)                                :: ndf
     958              :       REAL(KIND=dp), INTENT(INOUT)                       :: dg(ndf), eigval(ndf), work(ndf)
     959              :       TYPE(cp_fm_type), INTENT(IN)                       :: eigvec_mat
     960              :       REAL(KIND=dp), INTENT(INOUT)                       :: g(ndf)
     961              :       TYPE(mp_para_env_type), OPTIONAL, POINTER          :: para_env
     962              : 
     963              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'rat_fun_opt'
     964              :       REAL(KIND=dp), PARAMETER                           :: one = 1.0_dp
     965              : 
     966              :       INTEGER                                            :: handle, i, indf, iref, iter, j, k, l, &
     967              :                                                             maxit, ncol_local, nrow_local
     968          542 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
     969              :       LOGICAL                                            :: bisec, conv, fail, set
     970              :       REAL(KIND=dp)                                      :: fun, fun1, fun2, fun3, fung, lam1, lam2, &
     971              :                                                             ln, lp, ssize, step, stol
     972              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
     973          542 :          POINTER                                         :: local_data
     974              : 
     975          542 :       CALL timeset(routineN, handle)
     976              : 
     977          542 :       stol = 1.0E-8_dp
     978          542 :       ssize = 0.2_dp
     979          542 :       maxit = 999
     980          542 :       fail = .FALSE.
     981          542 :       bisec = .FALSE.
     982              : 
     983        75180 :       dg = 0._dp
     984              : 
     985              :       CALL cp_fm_get_info(eigvec_mat, row_indices=row_indices, col_indices=col_indices, &
     986          542 :                           local_data=local_data, nrow_local=nrow_local, ncol_local=ncol_local)
     987              : 
     988        42931 :       DO i = 1, nrow_local
     989        42389 :          j = row_indices(i)
     990     11782082 :          DO k = 1, ncol_local
     991     11739151 :             l = col_indices(k)
     992     11781540 :             dg(l) = dg(l) + local_data(i, k)*g(j)
     993              :          END DO
     994              :       END DO
     995          542 :       CALL para_env%sum(dg)
     996              : 
     997          542 :       set = .FALSE.
     998              : 
     999              :       DO
    1000              : 
    1001              : !   calculating Lambda
    1002              : 
    1003          566 :          lp = 0.0_dp
    1004          566 :          iref = 1
    1005          566 :          ln = 0.0_dp
    1006          566 :          IF (eigval(iref) < 0.0_dp) ln = eigval(iref) - 0.01_dp
    1007              : 
    1008          566 :          conv = .FALSE.
    1009          566 :          iter = 0
    1010              :          DO
    1011         1282 :             iter = iter + 1
    1012         1282 :             fun = 0.0_dp
    1013         1282 :             fung = 0.0_dp
    1014       161894 :             DO indf = 1, ndf
    1015       160612 :                fun = fun + dg(indf)**2/(ln - eigval(indf))
    1016       161894 :                fung = fung - dg(indf)**2/((ln - eigval(indf))**2)
    1017              :             END DO
    1018         1282 :             fun = fun - ln
    1019         1282 :             fung = fung - one
    1020         1282 :             step = fun/fung
    1021         1282 :             ln = ln - step
    1022         1282 :             IF (ABS(step) < stol) THEN
    1023              :                conv = .TRUE.
    1024              :                EXIT
    1025              :             END IF
    1026          716 :             IF (iter >= maxit) EXIT
    1027              :          END DO
    1028              :          outer: DO
    1029          590 :             IF (.NOT. conv) THEN
    1030          744 :                bisec = .TRUE.
    1031          744 :                iter = 0
    1032          744 :                maxit = 9999
    1033          744 :                lam1 = 0.0_dp
    1034          744 :                IF (eigval(iref) < 0.0_dp) lam1 = eigval(iref) - 0.01_dp
    1035              :                fun1 = 0.0_dp
    1036          744 :                DO indf = 1, ndf
    1037          744 :                   fun1 = fun1 + dg(indf)**2/(lam1 - eigval(indf))
    1038              :                END DO
    1039           24 :                fun1 = fun1 - lam1
    1040           24 :                step = ABS(lam1)/1000.0_dp
    1041              :                IF (step < ssize) step = ssize
    1042              :                inner: DO
    1043       240000 :                   iter = iter + 1
    1044       240000 :                   IF (iter > maxit) THEN
    1045              :                      ln = 0.0_dp
    1046          566 :                      lp = 0.0_dp
    1047              :                      fail = .TRUE.
    1048              :                      EXIT outer
    1049              :                   END IF
    1050       239976 :                   fun2 = 0.0_dp
    1051       239976 :                   lam2 = lam1 - iter*step
    1052      7439256 :                   DO indf = 1, ndf
    1053      7439256 :                      fun2 = fun2 + dg(indf)**2/(lam2 - eigval(indf))
    1054              :                   END DO
    1055       239976 :                   fun2 = fun2 - lam2
    1056       239976 :                   IF (fun2*fun1 < 0.0_dp) THEN
    1057              :                      iter = 0
    1058              :                      DO
    1059            0 :                         iter = iter + 1
    1060            0 :                         IF (iter > maxit) THEN
    1061              :                            ln = 0.0_dp
    1062              :                            lp = 0.0_dp
    1063              :                            fail = .TRUE.
    1064              :                            EXIT outer
    1065              :                         END IF
    1066            0 :                         step = (lam1 + lam2)/2
    1067            0 :                         fun3 = 0.0_dp
    1068            0 :                         DO indf = 1, ndf
    1069            0 :                            fun3 = fun3 + dg(indf)**2/(step - eigval(indf))
    1070              :                         END DO
    1071            0 :                         fun3 = fun3 - step
    1072              : 
    1073            0 :                         IF (ABS(step - lam2) < stol) THEN
    1074              :                            ln = step
    1075              :                            EXIT inner
    1076              :                         END IF
    1077              : 
    1078            0 :                         IF (fun3*fun1 < stol) THEN
    1079              :                            lam2 = step
    1080              :                         ELSE
    1081            0 :                            lam1 = step
    1082              :                         END IF
    1083              :                      END DO
    1084              :                   END IF
    1085              :                END DO inner
    1086              :             END IF
    1087          566 :             IF ((ln > eigval(iref)) .OR. ((ln > 0.0_dp) .AND. &
    1088              :                                           (eigval(iref) > 0.0_dp))) THEN
    1089              : 
    1090           24 :                IF (.NOT. bisec) THEN
    1091              :                   conv = .FALSE.
    1092              :                   CYCLE outer
    1093              :                END IF
    1094              :                ln = 0.0_dp
    1095              :                lp = 0.0_dp
    1096              :                fail = .TRUE.
    1097              :             END IF
    1098              :             EXIT outer
    1099              :          END DO outer
    1100              : 
    1101          566 :          IF (fail .AND. .NOT. set) THEN
    1102          744 :             set = .TRUE.
    1103          744 :             DO indf = 1, ndf
    1104          744 :                eigval(indf) = eigval(indf)*work(indf)
    1105              :             END DO
    1106              :             CYCLE
    1107              :          END IF
    1108              : 
    1109          542 :          IF (.NOT. set) THEN
    1110        74436 :             work(1:ndf) = one
    1111              :          END IF
    1112              : 
    1113        75180 :          DO indf = 1, ndf
    1114        75180 :             eigval(indf) = eigval(indf) - ln
    1115              :          END DO
    1116              :          EXIT
    1117              :       END DO
    1118              : 
    1119          542 :       CALL timestop(handle)
    1120              : 
    1121          542 :    END SUBROUTINE rat_fun_opt
    1122              : 
    1123              : ! **************************************************************************************************
    1124              : !> \brief Update the direct Hessian with the damped BFGS formula
    1125              : !> \param ndf Number of optimization variables
    1126              : !> \param dx Change of the optimization variables
    1127              : !> \param dg Change of the gradients in the same coordinate system
    1128              : !> \param hess_mat Direct Hessian, updated in place
    1129              : !> \param work Replicated workspace, holds B*dx on exit
    1130              : !> \param para_env ...
    1131              : !> \param output_unit Geometry log unit, activates at the default MEDIUM print level
    1132              : !> \param hess_reset Set if the update had to be refused and the caller must
    1133              : !>                  collectively rebuild the initial Hessian
    1134              : ! **************************************************************************************************
    1135         3782 :    SUBROUTINE bfgs(ndf, dx, dg, hess_mat, work, para_env, output_unit, hess_reset)
    1136              :       INTEGER, INTENT(IN)                                :: ndf
    1137              :       REAL(KIND=dp), INTENT(INOUT)                       :: dx(ndf), dg(ndf)
    1138              :       TYPE(cp_fm_type), INTENT(IN)                       :: hess_mat
    1139              :       REAL(KIND=dp), INTENT(INOUT)                       :: work(ndf)
    1140              :       TYPE(mp_para_env_type), OPTIONAL, POINTER          :: para_env
    1141              :       INTEGER, INTENT(IN)                                :: output_unit
    1142              :       LOGICAL, INTENT(OUT)                               :: hess_reset
    1143              : 
    1144              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'bfgs'
    1145              :       INTEGER, PARAMETER                                 :: exit_reset = 2, exit_skip = 1, &
    1146              :                                                             exit_update = 0
    1147              :       REAL(KIND=dp), PARAMETER                           :: min_curvature = 0.2_dp, one = 1.0_dp, &
    1148              :                                                             min_sbs = 10.0_dp*TINY(one), &
    1149              :                                                             zero = 0.0_dp
    1150              : 
    1151              :       INTEGER                                            :: exit_flag, handle, i, invalid, j, k, l, &
    1152              :                                                             ncol_local, nrow_local
    1153         1891 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1154              :       REAL(KIND=dp)                                      :: dxw, eta_i, eta_j, gdx, sbs, seta, sy, &
    1155              :                                                             theta
    1156              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
    1157         1891 :          POINTER                                         :: local_hes
    1158              : 
    1159         1891 :       CALL timeset(routineN, handle)
    1160         1891 :       hess_reset = .FALSE.
    1161              : 
    1162              :       CALL cp_fm_get_info(hess_mat, row_indices=row_indices, col_indices=col_indices, &
    1163         1891 :                           local_data=local_hes, nrow_local=nrow_local, ncol_local=ncol_local)
    1164              : 
    1165              :       ! Refuse corrupted input instead of poisoning the Hessian with Inf/NaN.
    1166       395414 :       IF (.NOT. ALL(ieee_is_finite(dx(1:ndf))) .OR. .NOT. ALL(ieee_is_finite(dg(1:ndf)))) THEN
    1167            0 :          CPABORT("Non-finite displacement or gradient difference")
    1168              :       END IF
    1169              : 
    1170       197707 :       work = zero
    1171       119872 :       DO i = 1, nrow_local
    1172       117981 :          j = row_indices(i)
    1173     20247061 :          DO k = 1, ncol_local
    1174     20127189 :             l = col_indices(k)
    1175     20245170 :             work(j) = work(j) + local_hes(i, k)*dx(l)
    1176              :          END DO
    1177              :       END DO
    1178              : 
    1179         1891 :       IF (PRESENT(para_env)) CALL para_env%sum(work)
    1180              : 
    1181       197707 :       sy = DOT_PRODUCT(dg(1:ndf), dx(1:ndf))
    1182       197707 :       sbs = DOT_PRODUCT(dx(1:ndf), work(1:ndf))
    1183              : 
    1184              :       ! One collective decision covers every early exit, so that all ranks
    1185              :       ! take the same path. sbs and sy share the units of the energy, so the
    1186              :       ! curvature floor is relative to sy. min_sbs only fences off values for
    1187              :       ! which the divisions in the update below would overflow: with a
    1188              :       ! smaller sbs, 0.2*sbs (the least possible seta) falls below the
    1189              :       ! smallest normal number. The floor is never negative, so a non-positive
    1190              :       ! sbs (lost positive definiteness) is caught as well.
    1191         1891 :       exit_flag = exit_update
    1192       395414 :       IF (DOT_PRODUCT(dx(1:ndf), dx(1:ndf)) == zero .OR. &
    1193              :           DOT_PRODUCT(dg(1:ndf), dg(1:ndf)) == zero) THEN
    1194            0 :          exit_flag = exit_skip
    1195         1891 :       ELSE IF (.NOT. ieee_is_finite(sy) .OR. .NOT. ieee_is_finite(sbs) .OR. &
    1196              :                sbs <= MAX(EPSILON(one)*ABS(sy), min_sbs)) THEN
    1197            0 :          exit_flag = exit_reset
    1198              :       END IF
    1199              :       ! The max folds the votes into the most conservative action all ranks
    1200              :       ! can agree on. The exit codes are ordered by severity, so a skip vote
    1201              :       ! on one rank and a reset vote on another reset both. Every rank takes
    1202              :       ! the same branch, so the rebuild stays collective.
    1203         1891 :       IF (PRESENT(para_env)) CALL para_env%max(exit_flag)
    1204              : 
    1205         1891 :       IF (exit_flag == exit_skip) THEN
    1206              :          ! A zero displacement or gradient difference carries no curvature
    1207              :          ! information, so there is nothing to learn from this step.
    1208         1891 :       ELSE IF (exit_flag == exit_reset) THEN
    1209              :          ! The Hessian has lost positive definiteness along dx or the predicted
    1210              :          ! curvature is not representable, so the secant pair cannot be damped:
    1211              :          ! the caller restarts from the initial Hessian and skips this update.
    1212              :          CALL cp_warn(__LOCATION__, &
    1213            0 :                       "BFGS: vanishing or non-positive predicted curvature, resetting the Hessian")
    1214            0 :          hess_reset = .TRUE.
    1215              :       ELSE
    1216              :          ! Damped update after M.J.D. Powell, Lecture Notes in Mathematics 630 (1978),
    1217              :          ! eq. 3.7: whenever the measured curvature sy drops below 20% of the predicted
    1218              :          ! curvature s.B.s, replace y by eta = theta*y + (1-theta)*B*s. The blended
    1219              :          ! curvature satisfies eta.s = 0.2*s.B.s exactly, so the update stays positive
    1220              :          ! definite in exact arithmetic, also for secant pairs that no line search
    1221              :          ! checked. Because sbs passed the floor above, seta >= 0.2*sbs stays a
    1222              :          ! normal number, so one/seta cannot overflow and no further floor on seta
    1223              :          ! is needed.
    1224         1891 :          theta = one
    1225         1891 :          IF (sy < min_curvature*sbs) THEN
    1226           63 :             theta = ((one - min_curvature)*sbs)/(sbs - sy)
    1227           63 :             IF (output_unit > 0) THEN
    1228              :                WRITE (UNIT=output_unit, FMT="(T2,A,F10.4,A,F3.1,A)") &
    1229           25 :                   "BFGS| Damped update, curvature ratio y.s/(s.B.s): ", sy/sbs, &
    1230           50 :                   " (threshold ", min_curvature, ")"
    1231           25 :                CALL m_flush(output_unit)
    1232              :             END IF
    1233              :          END IF
    1234         1891 :          seta = theta*sy + (one - theta)*sbs
    1235         1891 :          gdx = one/seta
    1236         1891 :          dxw = one/sbs
    1237              : 
    1238       119872 :          DO i = 1, nrow_local
    1239       117981 :             j = row_indices(i)
    1240       117981 :             eta_i = theta*dg(j) + (one - theta)*work(j)
    1241     20247061 :             DO k = 1, ncol_local
    1242     20127189 :                l = col_indices(k)
    1243     20127189 :                eta_j = theta*dg(l) + (one - theta)*work(l)
    1244              :                local_hes(i, k) = local_hes(i, k) + gdx*eta_i*eta_j - &
    1245     20245170 :                                  dxw*work(j)*work(l)
    1246              :             END DO
    1247              :          END DO
    1248              : 
    1249              :          ! Collective verdict: if any local block is corrupted, every rank resets.
    1250         1891 :          invalid = 0
    1251     20324896 :          IF (.NOT. ALL(ieee_is_finite(local_hes(1:nrow_local, 1:ncol_local)))) invalid = 1
    1252         1891 :          IF (PRESENT(para_env)) CALL para_env%max(invalid)
    1253         1891 :          IF (invalid /= 0) THEN
    1254            0 :             CALL cp_warn(__LOCATION__, "BFGS: non-finite Hessian after the update, resetting")
    1255            0 :             hess_reset = .TRUE.
    1256              :          END IF
    1257              :       END IF
    1258              : 
    1259         1891 :       CALL timestop(handle)
    1260              : 
    1261         1891 :    END SUBROUTINE bfgs
    1262              : 
    1263              : ! **************************************************************************************************
    1264              : !> \brief Build the initial direct or inverse Hessian: sanitized model Hessian or unity
    1265              : !> \param hess_mat BFGS matrix (direct or inverse Hessian), replaced in place
    1266              : !> \param hess_tmp Eigensolver scratch matrix, same structure as hess_mat
    1267              : !> \param eigvec Eigensolver eigenvector matrix, same structure as hess_mat
    1268              : !> \param eigval Eigensolver workspace of length ndf
    1269              : !> \param force_env Environment providing the model Hessian at the current geometry
    1270              : !> \param use_model Build the sanitized model Hessian; otherwise fall back to unity
    1271              : !> \param inverse Store the inverse of the sanitized model Hessian
    1272              : !> \note Must be called by all ranks together: construct_initial_hess reduces internally.
    1273              : ! **************************************************************************************************
    1274          791 :    SUBROUTINE build_initial_hess(hess_mat, hess_tmp, eigvec, eigval, force_env, use_model, inverse)
    1275              :       TYPE(cp_fm_type), INTENT(IN)                       :: hess_mat, hess_tmp, eigvec
    1276              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: eigval
    1277              :       TYPE(force_env_type), POINTER                      :: force_env
    1278              :       LOGICAL, INTENT(IN)                                :: use_model, inverse
    1279              : 
    1280              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_initial_hess'
    1281              :       REAL(KIND=dp), PARAMETER                           :: min_eig = 0.1_dp, one = 1.0_dp, &
    1282              :                                                             zero = 0.0_dp
    1283              : 
    1284              :       INTEGER                                            :: handle, indf, info, ndf
    1285              : 
    1286          791 :       CALL timeset(routineN, handle)
    1287              : 
    1288          791 :       IF (use_model) THEN
    1289          769 :          CPASSERT(ASSOCIATED(force_env))
    1290          769 :          ndf = SIZE(eigval)
    1291              :          ! The raw model Hessian is not guaranteed positive definite, so
    1292              :          ! eigenfactorize, floor the eigenvalues, and rebuild.
    1293          769 :          CALL cp_fm_set_all(hess_mat, alpha=zero)
    1294          769 :          CALL construct_initial_hess(force_env, hess_mat)
    1295          769 :          CALL cp_fm_to_fm(hess_mat, hess_tmp)
    1296          769 :          CALL choose_eigv_solver(hess_tmp, eigvec, eigval, info=info)
    1297          769 :          IF (info /= 0) THEN
    1298              :             ! In rare cases the diagonalization fails (bug in scalapack?)
    1299            0 :             CALL cp_warn(__LOCATION__, "BFGS: model Hessian diagonalization failed, using unity")
    1300            0 :             CALL cp_fm_set_all(hess_mat, alpha=zero, beta=one)
    1301            0 :             eigval = one
    1302              :          ELSE
    1303        16807 :             DO indf = 1, ndf
    1304        16038 :                IF (eigval(indf) < min_eig) eigval(indf) = min_eig
    1305        16807 :                IF (inverse) eigval(indf) = one/eigval(indf)
    1306              :             END DO
    1307          769 :             CALL cp_fm_to_fm(eigvec, hess_tmp)
    1308          769 :             CALL cp_fm_column_scale(eigvec, eigval)
    1309          769 :             CALL parallel_gemm("N", "T", ndf, ndf, ndf, one, hess_tmp, eigvec, zero, hess_mat)
    1310              :          END IF
    1311              :       ELSE
    1312              :          ! No sanitized prior exists (user opt-out, cell optimization, or
    1313              :          ! core-shell model): fall back to unity. eigval mirrors the unity
    1314              :          ! spectrum, keeping the INTENT(OUT) argument defined on every path.
    1315           22 :          CALL cp_fm_set_all(hess_mat, alpha=zero, beta=one)
    1316         4592 :          eigval = one
    1317              :       END IF
    1318              : 
    1319          791 :       CALL timestop(handle)
    1320              : 
    1321          791 :    END SUBROUTINE build_initial_hess
    1322              : 
    1323              : ! **************************************************************************************************
    1324              : !> \brief ...
    1325              : !> \param ndf ...
    1326              : !> \param eigval ...
    1327              : !> \param work ...
    1328              : ! **************************************************************************************************
    1329          542 :    SUBROUTINE set_hes_eig(ndf, eigval, work)
    1330              :       INTEGER, INTENT(IN)                                :: ndf
    1331              :       REAL(KIND=dp), INTENT(INOUT)                       :: eigval(ndf), work(ndf)
    1332              : 
    1333              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'set_hes_eig'
    1334              :       REAL(KIND=dp), PARAMETER                           :: max_eig = 1000.0_dp, max_neg = -0.5_dp, &
    1335              :                                                             max_pos = 5.0_dp, min_eig = 0.005_dp, &
    1336              :                                                             one = 1.0_dp
    1337              : 
    1338              :       INTEGER                                            :: handle, indf
    1339              : 
    1340          542 :       CALL timeset(routineN, handle)
    1341              : 
    1342        75180 :       DO indf = 1, ndf
    1343        75180 :          IF (eigval(indf) > max_eig) eigval(indf) = max_eig
    1344              :       END DO
    1345        75180 :       DO indf = 1, ndf
    1346        75180 :          IF (eigval(indf) < 0.0_dp) THEN
    1347           24 :             IF (eigval(indf) < max_neg) THEN
    1348            0 :                eigval(indf) = max_neg
    1349           24 :             ELSE IF (eigval(indf) > -min_eig) THEN
    1350           24 :                eigval(indf) = -min_eig
    1351              :             END IF
    1352        74614 :          ELSE IF (eigval(indf) < 1000.0_dp) THEN
    1353        74590 :             IF (eigval(indf) < min_eig) THEN
    1354          168 :                eigval(indf) = min_eig
    1355        74422 :             ELSE IF (eigval(indf) > max_pos) THEN
    1356            5 :                eigval(indf) = max_pos
    1357              :             END IF
    1358              :          END IF
    1359              :       END DO
    1360              : 
    1361        75180 :       DO indf = 1, ndf
    1362        75180 :          IF (eigval(indf) < 0.0_dp) THEN
    1363           24 :             work(indf) = -one
    1364              :          ELSE
    1365        74614 :             work(indf) = one
    1366              :          END IF
    1367              :       END DO
    1368              : 
    1369          542 :       CALL timestop(handle)
    1370              : 
    1371          542 :    END SUBROUTINE set_hes_eig
    1372              : 
    1373              : ! **************************************************************************************************
    1374              : !> \brief ...
    1375              : !> \param ndf ...
    1376              : !> \param eigval ...
    1377              : !> \param eigvec_mat ...
    1378              : !> \param hess_tmp ...
    1379              : !> \param dr ...
    1380              : !> \param g ...
    1381              : !> \param para_env ...
    1382              : !> \param use_rfo ...
    1383              : ! **************************************************************************************************
    1384         6138 :    SUBROUTINE geoopt_get_step(ndf, eigval, eigvec_mat, hess_tmp, dr, g, para_env, use_rfo)
    1385              : 
    1386              :       INTEGER, INTENT(IN)                                :: ndf
    1387              :       REAL(KIND=dp), INTENT(INOUT)                       :: eigval(ndf)
    1388              :       TYPE(cp_fm_type), INTENT(IN)                       :: eigvec_mat, hess_tmp
    1389              :       REAL(KIND=dp), INTENT(INOUT)                       :: dr(ndf), g(ndf)
    1390              :       TYPE(mp_para_env_type), OPTIONAL, POINTER          :: para_env
    1391              :       LOGICAL                                            :: use_rfo
    1392              : 
    1393              :       REAL(KIND=dp), PARAMETER                           :: one = 1.0_dp, zero = 0.0_dp
    1394              : 
    1395              :       INTEGER                                            :: i, indf, j, k, l, ncol_local, nrow_local
    1396         2046 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1397              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
    1398         2046 :          POINTER                                         :: local_data
    1399              :       TYPE(cp_fm_struct_type), POINTER                   :: matrix_struct
    1400              :       TYPE(cp_fm_type)                                   :: tmp
    1401              : 
    1402         2046 :       CALL cp_fm_to_fm(eigvec_mat, hess_tmp)
    1403         2046 :       IF (use_rfo) THEN
    1404        75180 :          DO indf = 1, ndf
    1405        75180 :             eigval(indf) = one/eigval(indf)
    1406              :          END DO
    1407              :       ELSE
    1408       132526 :          DO indf = 1, ndf
    1409       132526 :             eigval(indf) = one/MAX(min_hessian_eigenvalue, eigval(indf))
    1410              :          END DO
    1411              :       END IF
    1412              : 
    1413         2046 :       CALL cp_fm_column_scale(hess_tmp, eigval)
    1414         2046 :       CALL cp_fm_get_info(eigvec_mat, matrix_struct=matrix_struct)
    1415         2046 :       CALL cp_fm_create(tmp, matrix_struct, name="tmp")
    1416         2046 :       CALL cp_fm_set_all(tmp, alpha=zero)
    1417              : 
    1418         2046 :       CALL parallel_gemm("N", "T", ndf, ndf, ndf, one, hess_tmp, eigvec_mat, zero, tmp)
    1419              : 
    1420         2046 :       CALL cp_fm_transpose(tmp, hess_tmp)
    1421         2046 :       CALL cp_fm_release(tmp)
    1422              : 
    1423              :       ! New step
    1424              : 
    1425              :       CALL cp_fm_get_info(hess_tmp, row_indices=row_indices, col_indices=col_indices, &
    1426         2046 :                           local_data=local_data, nrow_local=nrow_local, ncol_local=ncol_local)
    1427              : 
    1428       207706 :       dr = 0.0_dp
    1429       126674 :       DO i = 1, nrow_local
    1430       124628 :          j = row_indices(i)
    1431     21241326 :          DO k = 1, ncol_local
    1432     21114652 :             l = col_indices(k)
    1433     21239280 :             dr(j) = dr(j) - local_data(i, k)*g(l)
    1434              :          END DO
    1435              :       END DO
    1436              : 
    1437         2046 :       CALL para_env%sum(dr)
    1438              : 
    1439         2046 :    END SUBROUTINE geoopt_get_step
    1440              : 
    1441              : ! **************************************************************************************************
    1442              : !> \brief ...
    1443              : !> \param ndf ...
    1444              : !> \param step ...
    1445              : !> \param rad ...
    1446              : !> \param rat ...
    1447              : !> \param dr ...
    1448              : !> \param output_unit ...
    1449              : ! **************************************************************************************************
    1450         2046 :    SUBROUTINE trust_radius(ndf, step, rad, rat, dr, output_unit)
    1451              :       INTEGER, INTENT(IN)                                :: ndf
    1452              :       REAL(KIND=dp), INTENT(INOUT)                       :: step, rad, rat, dr(ndf)
    1453              :       INTEGER, INTENT(IN)                                :: output_unit
    1454              : 
    1455              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'trust_radius'
    1456              :       REAL(KIND=dp), PARAMETER                           :: one = 1.0_dp
    1457              : 
    1458              :       INTEGER                                            :: handle
    1459              :       REAL(KIND=dp)                                      :: scal
    1460              : 
    1461         2046 :       CALL timeset(routineN, handle)
    1462              : 
    1463       207706 :       step = MAXVAL(ABS(dr))
    1464         2046 :       scal = MAX(one, rad/step)
    1465              : 
    1466         2046 :       IF (step > rad) THEN
    1467          144 :          rat = rad/step
    1468          144 :          CALL DSCAL(ndf, rat, dr, 1)
    1469          144 :          step = rad
    1470          144 :          IF (output_unit > 0) THEN
    1471              :             WRITE (unit=output_unit, FMT="(/,T2,A,F8.5)") &
    1472           82 :                " Step is scaled; Scaling factor = ", rat
    1473           82 :             CALL m_flush(output_unit)
    1474              :          END IF
    1475              :       END IF
    1476         2046 :       CALL timestop(handle)
    1477              : 
    1478         2046 :    END SUBROUTINE trust_radius
    1479              : 
    1480              : ! **************************************************************************************************
    1481              : !> \brief ...
    1482              : !> \param ndf ...
    1483              : !> \param work ...
    1484              : !> \param hess_mat ...
    1485              : !> \param dr ...
    1486              : !> \param g ...
    1487              : !> \param pred ...
    1488              : !> \param para_env ...
    1489              : ! **************************************************************************************************
    1490         4092 :    SUBROUTINE energy_predict(ndf, work, hess_mat, dr, g, pred, para_env)
    1491              : 
    1492              :       INTEGER, INTENT(IN)                                :: ndf
    1493              :       REAL(KIND=dp), INTENT(INOUT)                       :: work(ndf)
    1494              :       TYPE(cp_fm_type), INTENT(IN)                       :: hess_mat
    1495              :       REAL(KIND=dp), INTENT(INOUT)                       :: dr(ndf), g(ndf), pred
    1496              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1497              : 
    1498              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'energy_predict'
    1499              :       REAL(KIND=dp), PARAMETER                           :: zero = 0.0_dp
    1500              : 
    1501              :       INTEGER                                            :: handle, i, j, k, l, ncol_local, &
    1502              :                                                             nrow_local
    1503         2046 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1504              :       REAL(KIND=dp)                                      :: ener1, ener2
    1505              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
    1506         2046 :          POINTER                                         :: local_data
    1507              : 
    1508         2046 :       CALL timeset(routineN, handle)
    1509              : 
    1510       207706 :       ener1 = DOT_PRODUCT(g(1:ndf), dr(1:ndf))
    1511              : 
    1512              :       CALL cp_fm_get_info(hess_mat, row_indices=row_indices, col_indices=col_indices, &
    1513         2046 :                           local_data=local_data, nrow_local=nrow_local, ncol_local=ncol_local)
    1514              : 
    1515       207706 :       work = zero
    1516       126674 :       DO i = 1, nrow_local
    1517       124628 :          j = row_indices(i)
    1518     21241326 :          DO k = 1, ncol_local
    1519     21114652 :             l = col_indices(k)
    1520     21239280 :             work(j) = work(j) + local_data(i, k)*dr(l)
    1521              :          END DO
    1522              :       END DO
    1523              : 
    1524         2046 :       CALL para_env%sum(work)
    1525       207706 :       ener2 = DOT_PRODUCT(dr(1:ndf), work(1:ndf))
    1526         2046 :       pred = ener1 + 0.5_dp*ener2
    1527         2046 :       CALL timestop(handle)
    1528              : 
    1529         2046 :    END SUBROUTINE energy_predict
    1530              : 
    1531              : ! **************************************************************************************************
    1532              : !> \brief ...
    1533              : !> \param rat ...
    1534              : !> \param rad ...
    1535              : !> \param step ...
    1536              : !> \param ediff ...
    1537              : ! **************************************************************************************************
    1538          517 :    SUBROUTINE update_trust_rad(rat, rad, step, ediff)
    1539              : 
    1540              :       REAL(KIND=dp), INTENT(INOUT)                       :: rat, rad, step, ediff
    1541              : 
    1542              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'update_trust_rad'
    1543              :       REAL(KIND=dp), PARAMETER                           :: max_trust = 1.0_dp, min_trust = 0.1_dp
    1544              : 
    1545              :       INTEGER                                            :: handle
    1546              : 
    1547          517 :       CALL timeset(routineN, handle)
    1548              : 
    1549          517 :       IF (rat > 4.0_dp) THEN
    1550            0 :          IF (ediff < 0.0_dp) THEN
    1551            0 :             rad = step*0.5_dp
    1552              :          ELSE
    1553            0 :             rad = step*0.25_dp
    1554              :          END IF
    1555          517 :       ELSE IF (rat > 2.0_dp) THEN
    1556            0 :          IF (ediff < 0.0_dp) THEN
    1557            0 :             rad = step*0.75_dp
    1558              :          ELSE
    1559            0 :             rad = step*0.5_dp
    1560              :          END IF
    1561          517 :       ELSE IF (rat > 4.0_dp/3.0_dp) THEN
    1562            0 :          IF (ediff < 0.0_dp) THEN
    1563            0 :             rad = step
    1564              :          ELSE
    1565            0 :             rad = step*0.75_dp
    1566              :          END IF
    1567          517 :       ELSE IF (rat > 10.0_dp/9.0_dp) THEN
    1568            0 :          IF (ediff < 0.0_dp) THEN
    1569            0 :             rad = step*1.25_dp
    1570              :          ELSE
    1571            0 :             rad = step
    1572              :          END IF
    1573          517 :       ELSE IF (rat > 0.9_dp) THEN
    1574           41 :          IF (ediff < 0.0_dp) THEN
    1575           41 :             rad = step*1.5_dp
    1576              :          ELSE
    1577            0 :             rad = step*1.25_dp
    1578              :          END IF
    1579          476 :       ELSE IF (rat > 0.75_dp) THEN
    1580          114 :          IF (ediff < 0.0_dp) THEN
    1581          109 :             rad = step*1.25_dp
    1582              :          ELSE
    1583            5 :             rad = step
    1584              :          END IF
    1585          362 :       ELSE IF (rat > 0.5_dp) THEN
    1586           42 :          IF (ediff < 0.0_dp) THEN
    1587           42 :             rad = step
    1588              :          ELSE
    1589            0 :             rad = step*0.75_dp
    1590              :          END IF
    1591          320 :       ELSE IF (rat > 0.25_dp) THEN
    1592            4 :          IF (ediff < 0.0_dp) THEN
    1593            4 :             rad = step*0.75_dp
    1594              :          ELSE
    1595            0 :             rad = step*0.5_dp
    1596              :          END IF
    1597          316 :       ELSE IF (ediff < 0.0_dp) THEN
    1598          314 :          rad = step*0.5_dp
    1599              :       ELSE
    1600            2 :          rad = step*0.25_dp
    1601              :       END IF
    1602              : 
    1603          517 :       rad = MAX(rad, min_trust)
    1604          517 :       rad = MIN(rad, max_trust)
    1605          517 :       CALL timestop(handle)
    1606              : 
    1607          517 :    END SUBROUTINE update_trust_rad
    1608              : 
    1609              : ! **************************************************************************************************
    1610              : 
    1611              : ! **************************************************************************************************
    1612              : !> \brief ...
    1613              : !> \param geo_section ...
    1614              : !> \param hess_mat ...
    1615              : !> \param logger ...
    1616              : !> \param gopt_env Optimization coordinate system
    1617              : !> \param matrix_method Stored matrix representation
    1618              : ! **************************************************************************************************
    1619         8558 :    SUBROUTINE write_bfgs_hessian(geo_section, hess_mat, logger, gopt_env, matrix_method)
    1620              : 
    1621              :       TYPE(section_vals_type), POINTER                   :: geo_section
    1622              :       TYPE(cp_fm_type), INTENT(IN)                       :: hess_mat
    1623              :       TYPE(cp_logger_type), POINTER                      :: logger
    1624              :       TYPE(gopt_f_type), POINTER                         :: gopt_env
    1625              :       INTEGER, INTENT(IN)                                :: matrix_method
    1626              : 
    1627              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'write_bfgs_hessian'
    1628              : 
    1629              :       INTEGER                                            :: handle, hesunit, ndf
    1630              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: cell_frame
    1631              : 
    1632         4279 :       CALL timeset(routineN, handle)
    1633         4279 :       CALL cp_fm_get_info(hess_mat, nrow_global=ndf)
    1634         4279 :       cell_frame = 0.0_dp
    1635        12895 :       IF (gopt_env%type_id == default_cell_method_id) cell_frame = gopt_env%cell_env%opt_to_input
    1636              :       hesunit = cp_print_key_unit_nr(logger, geo_section, "BFGS%RESTART", &
    1637              :                                      extension=".Hessian", file_form="UNFORMATTED", file_action="WRITE", &
    1638         4279 :                                      file_position="REWIND")
    1639         4279 :       IF (hesunit > 0) THEN
    1640         2461 :          WRITE (hesunit) bfgs_restart_magic, bfgs_restart_version, matrix_method, ndf, &
    1641        34454 :             gopt_env%type_id, gopt_env%h_ref, cell_frame
    1642              :       END IF
    1643              :       ! Store the native representation. Conversions occur only when reading a different METHOD.
    1644         4279 :       CALL cp_fm_write_unformatted(hess_mat, hesunit)
    1645         4279 :       CALL cp_print_key_finished_output(hesunit, logger, geo_section, "BFGS%RESTART")
    1646         4279 :       CALL timestop(handle)
    1647              : 
    1648         4279 :    END SUBROUTINE write_bfgs_hessian
    1649              : 
    1650              : ! **************************************************************************************************
    1651              : !> \brief Constructs model Hessian as described in https://doi.org/10.1016/0009-2614(95)00646-L.
    1652              : !> \param force_env ...
    1653              : !> \param hess_mat ...
    1654              : !> \author Florian Schiffmann
    1655              : ! **************************************************************************************************
    1656          769 :    SUBROUTINE construct_initial_hess(force_env, hess_mat)
    1657              : 
    1658              :       TYPE(force_env_type), POINTER                      :: force_env
    1659              :       TYPE(cp_fm_type), INTENT(IN)                       :: hess_mat
    1660              : 
    1661              :       INTEGER                                            :: i, iat_col, iat_row, iglobal, iind, j, &
    1662              :                                                             jat_row, jglobal, jind, k, natom, &
    1663              :                                                             ncol_local, nrow_local, z
    1664          769 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: at_row
    1665          769 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1666              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: d_ij, rho_ij
    1667              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: r_ij
    1668              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
    1669          769 :          POINTER                                         :: fixed, local_data
    1670              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: alpha, r0
    1671              :       TYPE(cell_type), POINTER                           :: cell
    1672              :       TYPE(cp_subsys_type), POINTER                      :: subsys
    1673              :       TYPE(particle_list_type), POINTER                  :: particles
    1674              : 
    1675          769 :       CALL cite_reference(Lindh1995)
    1676              : 
    1677          769 :       CALL force_env_get(force_env=force_env, subsys=subsys, cell=cell)
    1678              :       CALL cp_subsys_get(subsys, &
    1679          769 :                          particles=particles)
    1680              : 
    1681          769 :       alpha = lindh_alpha
    1682          769 :       r0 = lindh_r0
    1683              : 
    1684              :       CALL cp_fm_get_info(hess_mat, row_indices=row_indices, col_indices=col_indices, &
    1685          769 :                           local_data=local_data, nrow_local=nrow_local, ncol_local=ncol_local)
    1686          769 :       natom = particles%n_els
    1687         2307 :       ALLOCATE (at_row(natom))
    1688         3076 :       ALLOCATE (rho_ij(natom, natom))
    1689         2307 :       ALLOCATE (d_ij(natom, natom))
    1690         3845 :       ALLOCATE (r_ij(natom, natom, 3))
    1691         2307 :       ALLOCATE (fixed(3, natom))
    1692        22153 :       fixed = 1.0_dp
    1693          769 :       CALL fix_atom_control(force_env, fixed)
    1694         3076 :       DO i = 1, 3
    1695        35152 :          CALL hess_mat%matrix_struct%para_env%min(fixed(i, :))
    1696              :       END DO
    1697          769 :       rho_ij = 0
    1698         6115 :       at_row = 3
    1699         6115 :       DO i = 1, natom
    1700         5346 :          CALL get_atomic_kind(atomic_kind=particles%els(i)%atomic_kind, z=z)
    1701         5346 :          IF (z <= 10) at_row(i) = 2
    1702        11461 :          IF (z <= 2) at_row(i) = 1
    1703              :       END DO
    1704         5346 :       DO i = 2, natom
    1705         4577 :          iat_row = at_row(i)
    1706        68323 :          DO j = 1, i - 1
    1707        62977 :             jat_row = at_row(j)
    1708              :             !pbc for a distance vector
    1709       251908 :             r_ij(j, i, :) = pbc(particles%els(i)%r, particles%els(j)%r, cell)
    1710       251908 :             r_ij(i, j, :) = -r_ij(j, i, :)
    1711       251908 :             d_ij(j, i) = NORM2(r_ij(j, i, :))
    1712        62977 :             d_ij(i, j) = d_ij(j, i)
    1713        62977 :             rho_ij(j, i) = EXP(alpha(jat_row, iat_row)*(r0(jat_row, iat_row)**2 - d_ij(j, i)**2))
    1714        67554 :             rho_ij(i, j) = rho_ij(j, i)
    1715              :          END DO
    1716              :       END DO
    1717        16807 :       DO i = 1, ncol_local
    1718        16038 :          iglobal = col_indices(i)
    1719        16038 :          iind = MOD(iglobal - 1, 3) + 1
    1720        16038 :          iat_col = (iglobal + 2)/3
    1721        16038 :          IF (iat_col > natom) CYCLE
    1722       691537 :          DO j = 1, nrow_local
    1723       674730 :             jglobal = row_indices(j)
    1724       674730 :             jind = MOD(jglobal - 1, 3) + 1
    1725       674730 :             iat_row = (jglobal + 2)/3
    1726       674730 :             IF (iat_row > natom) CYCLE
    1727       674730 :             IF (iat_row /= iat_col) THEN
    1728       645498 :                IF (d_ij(iat_row, iat_col) < lindh_cutoff) THEN
    1729              :                   local_data(j, i) = local_data(j, i) + &
    1730       214074 :                                      angle_second_deriv(r_ij, d_ij, rho_ij, iind, jind, iat_col, iat_row, natom)
    1731              :                END IF
    1732              :             ELSE
    1733              :                local_data(j, i) = local_data(j, i) + &
    1734        29232 :                                   angle_second_deriv(r_ij, d_ij, rho_ij, iind, jind, iat_col, iat_row, natom)
    1735              :             END IF
    1736       674730 :             IF (iat_col /= iat_row) THEN
    1737       645498 :                IF (d_ij(iat_row, iat_col) < lindh_cutoff) THEN
    1738              :                   local_data(j, i) = local_data(j, i) - &
    1739              :                                      dist_second_deriv(r_ij(iat_col, iat_row, :), &
    1740       856296 :                                                        iind, jind, d_ij(iat_row, iat_col), rho_ij(iat_row, iat_col))
    1741              :                END IF
    1742              :             ELSE
    1743       703962 :                DO k = 1, natom
    1744       674730 :                   IF (k == iat_col) CYCLE
    1745       674730 :                   IF (d_ij(iat_row, k) < lindh_cutoff) THEN
    1746              :                      local_data(j, i) = local_data(j, i) + &
    1747              :                                         dist_second_deriv(r_ij(iat_col, k, :), &
    1748       856296 :                                                           iind, jind, d_ij(iat_row, k), rho_ij(iat_row, k))
    1749              :                   END IF
    1750              :                END DO
    1751              :             END IF
    1752       690768 :             IF (fixed(jind, iat_row) < 0.5_dp .OR. fixed(iind, iat_col) < 0.5_dp) THEN
    1753        10161 :                local_data(j, i) = 0.0_dp
    1754        10161 :                IF (jind == iind .AND. iat_row == iat_col) local_data(j, i) = 1.0_dp
    1755              :             END IF
    1756              :          END DO
    1757              :       END DO
    1758          769 :       DEALLOCATE (fixed)
    1759          769 :       DEALLOCATE (rho_ij)
    1760          769 :       DEALLOCATE (d_ij)
    1761          769 :       DEALLOCATE (r_ij)
    1762          769 :       DEALLOCATE (at_row)
    1763              : 
    1764         1538 :    END SUBROUTINE construct_initial_hess
    1765              : 
    1766              : ! **************************************************************************************************
    1767              : !> \brief ...
    1768              : !> \param r1 ...
    1769              : !> \param i ...
    1770              : !> \param j ...
    1771              : !> \param d ...
    1772              : !> \param rho ...
    1773              : !> \return ...
    1774              : ! **************************************************************************************************
    1775       428148 :    PURE FUNCTION dist_second_deriv(r1, i, j, d, rho) RESULT(deriv)
    1776              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: r1
    1777              :       INTEGER, INTENT(IN)                                :: i, j
    1778              :       REAL(KIND=dp), INTENT(IN)                          :: d, rho
    1779              :       REAL(KIND=dp)                                      :: deriv
    1780              : 
    1781       428148 :       deriv = lindh_stretch_factor*rho*(r1(i)*r1(j))/d**2
    1782       428148 :    END FUNCTION dist_second_deriv
    1783              : 
    1784              : ! **************************************************************************************************
    1785              : !> \brief ...
    1786              : !> \param r_ij ...
    1787              : !> \param d_ij ...
    1788              : !> \param rho_ij ...
    1789              : !> \param idir ...
    1790              : !> \param jdir ...
    1791              : !> \param iat_der ...
    1792              : !> \param jat_der ...
    1793              : !> \param natom ...
    1794              : !> \return ...
    1795              : ! **************************************************************************************************
    1796       243306 :    FUNCTION angle_second_deriv(r_ij, d_ij, rho_ij, idir, jdir, iat_der, jat_der, natom) RESULT(deriv)
    1797              :       REAL(KIND=dp), DIMENSION(:, :, :)                  :: r_ij
    1798              :       REAL(KIND=dp), DIMENSION(:, :)                     :: d_ij, rho_ij
    1799              :       INTEGER                                            :: idir, jdir, iat_der, jat_der, natom
    1800              :       REAL(KIND=dp)                                      :: deriv
    1801              : 
    1802              :       REAL(KIND=dp), PARAMETER                           :: rho_thre = 1.0E-5_dp
    1803              : 
    1804              :       INTEGER                                            :: i, iat, idr, j, jat, jdr
    1805              :       REAL(KIND=dp)                                      :: d12, d23, d31, D_mat(3, 2), denom1, &
    1806              :                                                             denom2, denom3, ka1, ka2, ka3, rho12, &
    1807              :                                                             rho23, rho31, rsst1, rsst2, rsst3
    1808              :       REAL(KIND=dp), DIMENSION(3)                        :: r12, r23, r31
    1809              : 
    1810       243306 :       deriv = 0._dp
    1811       243306 :       IF (iat_der == jat_der) THEN
    1812       674730 :          DO i = 1, natom - 1
    1813       645498 :             IF (rho_ij(iat_der, i) < rho_thre) CYCLE
    1814      3579021 :             DO j = i + 1, natom
    1815      3352383 :                IF (rho_ij(iat_der, j) < rho_thre) CYCLE
    1816       972108 :                IF (i == iat_der .OR. j == iat_der) CYCLE
    1817       972108 :                IF (iat_der < i .OR. iat_der > j) THEN
    1818      5894010 :                   r12 = r_ij(iat_der, i, :); r23 = r_ij(i, j, :); r31 = r_ij(j, iat_der, :)
    1819       589401 :                   d12 = d_ij(iat_der, i); d23 = d_ij(i, j); d31 = d_ij(j, iat_der)
    1820       589401 :                   rho12 = rho_ij(iat_der, i); rho23 = rho_ij(i, j); rho31 = rho_ij(j, iat_der)
    1821              :                ELSE
    1822      3827070 :                   r12 = r_ij(iat_der, j, :); r23 = r_ij(j, i, :); r31 = r_ij(i, iat_der, :)
    1823       382707 :                   d12 = d_ij(iat_der, j); d23 = d_ij(j, i); d31 = d_ij(i, iat_der)
    1824       382707 :                   rho12 = rho_ij(iat_der, j); rho23 = rho_ij(j, i); rho31 = rho_ij(i, iat_der)
    1825              :                END IF
    1826       972108 :                ka1 = lindh_angle_factor*rho12*rho23; ka2 = lindh_angle_factor*rho23*rho31; ka3 = lindh_angle_factor*rho31*rho12
    1827      9721080 :                rsst1 = DOT_PRODUCT(r12, r23); rsst2 = DOT_PRODUCT(r23, r31); rsst3 = DOT_PRODUCT(r31, r12)
    1828       972108 :                denom1 = 1.0_dp - rsst1**2/(d12**2*d23**2); denom2 = 1.0_dp - rsst2**2/(d23**2*d31**2)
    1829       972108 :                denom3 = 1.0_dp - rsst3**2/(d31**2*d12**2)
    1830       972108 :                denom1 = SIGN(1.0_dp, denom1)*MAX(ABS(denom1), lindh_denom_floor)
    1831       972108 :                denom2 = SIGN(1.0_dp, denom2)*MAX(ABS(denom2), lindh_denom_floor)
    1832       972108 :                denom3 = SIGN(1.0_dp, denom3)*MAX(ABS(denom3), lindh_denom_floor)
    1833       972108 :                D_mat(1, 1) = r23(idir)/(d12*d23) - rsst1*r12(idir)/(d12**3*d23)
    1834       972108 :                D_mat(1, 2) = r23(jdir)/(d12*d23) - rsst1*r12(jdir)/(d12**3*d23)
    1835       972108 :                D_mat(2, 1) = -r23(idir)/(d23*d31) + rsst2*r31(idir)/(d23*d31**3)
    1836       972108 :                D_mat(2, 2) = -r23(jdir)/(d23*d31) + rsst2*r31(jdir)/(d23*d31**3)
    1837              :                D_mat(3, 1) = (r31(idir) - r12(idir))/(d31*d12) + rsst3*r31(idir)/(d31**3*d12) - &
    1838       972108 :                              rsst3*r12(idir)/(d31*d12**3)
    1839              :                D_mat(3, 2) = (r31(jdir) - r12(jdir))/(d31*d12) + rsst3*r31(jdir)/(d31**3*d12) - &
    1840       972108 :                              rsst3*r12(jdir)/(d31*d12**3)
    1841       972108 :                IF (ABS(denom1) <= 0.011_dp) D_mat(1, 1) = 0.0_dp
    1842       972108 :                IF (ABS(denom2) <= 0.011_dp) D_mat(2, 1) = 0.0_dp
    1843       972108 :                IF (ABS(denom3) <= 0.011_dp) D_mat(3, 1) = 0.0_dp
    1844              :                deriv = deriv + ka1*D_mat(1, 1)*D_mat(1, 2)/denom1 + &
    1845              :                        ka2*D_mat(2, 1)*D_mat(2, 2)/denom2 + &
    1846      3997881 :                        ka3*D_mat(3, 1)*D_mat(3, 2)/denom3
    1847              : 
    1848              :             END DO
    1849              :          END DO
    1850              :       ELSE
    1851      6360930 :          DO i = 1, natom
    1852      6146856 :             IF (i == iat_der .OR. i == jat_der) CYCLE
    1853      5718708 :             IF (jat_der < iat_der) THEN
    1854      2859354 :                iat = jat_der; jat = iat_der; idr = jdir; jdr = idir
    1855              :             ELSE
    1856      2859354 :                iat = iat_der; jat = jat_der; idr = idir; jdr = jdir
    1857              :             END IF
    1858      5718708 :             IF (jat < i .OR. iat > i) THEN
    1859     45474480 :                r12 = r_ij(iat, jat, :); r23 = r_ij(jat, i, :); r31 = r_ij(i, iat, :)
    1860      4547448 :                d12 = d_ij(iat, jat); d23 = d_ij(jat, i); d31 = d_ij(i, iat)
    1861      4547448 :                rho12 = rho_ij(iat, jat); rho23 = rho_ij(jat, i); rho31 = rho_ij(i, iat)
    1862              :             ELSE
    1863     11712600 :                r12 = r_ij(iat, i, :); r23 = r_ij(i, jat, :); r31 = r_ij(jat, iat, :)
    1864      1171260 :                d12 = d_ij(iat, i); d23 = d_ij(i, jat); d31 = d_ij(jat, iat)
    1865      1171260 :                rho12 = rho_ij(iat, i); rho23 = rho_ij(i, jat); rho31 = rho_ij(jat, iat)
    1866              :             END IF
    1867      5718708 :             ka1 = lindh_angle_factor*rho12*rho23; ka2 = lindh_angle_factor*rho23*rho31; ka3 = lindh_angle_factor*rho31*rho12
    1868     57187080 :             rsst1 = DOT_PRODUCT(r12, r23); rsst2 = DOT_PRODUCT(r23, r31); rsst3 = DOT_PRODUCT(r31, r12)
    1869      5718708 :             denom1 = 1.0_dp - rsst1**2/(d12**2*d23**2); denom2 = 1.0_dp - rsst2**2/(d23**2*d31**2)
    1870      5718708 :             denom3 = 1.0_dp - rsst3**2/(d31**2*d12**2)
    1871      5718708 :             denom1 = SIGN(1.0_dp, denom1)*MAX(ABS(denom1), lindh_denom_floor)
    1872      5718708 :             denom2 = SIGN(1.0_dp, denom2)*MAX(ABS(denom2), lindh_denom_floor)
    1873      5718708 :             denom3 = SIGN(1.0_dp, denom3)*MAX(ABS(denom3), lindh_denom_floor)
    1874      5718708 :             D_mat(1, 1) = r23(idr)/(d12*d23) - rsst1*r12(idr)/(d12**3*d23)
    1875      5718708 :             D_mat(2, 1) = -r23(idr)/(d23*d31) + rsst2*r31(idr)/(d23*d31**3)
    1876              :             D_mat(3, 1) = (r31(idr) - r12(idr))/(d31*d12) + rsst3*r31(idr)/(d31**3*d12) - &
    1877      5718708 :                           rsst3*r12(idr)/(d31*d12**3)
    1878      5718708 :             IF (jat < i .OR. iat > i) THEN
    1879              :                D_mat(1, 2) = (r12(jdr) - r23(jdr))/(d12*d23) + rsst1*r12(jdr)/(d12**3*d23) - &
    1880      4547448 :                              rsst1*r23(jdr)/(d12*d23**3)
    1881      4547448 :                D_mat(2, 2) = r31(jdr)/(d23*d31) - rsst2*r23(jdr)/(d23**3*d31)
    1882      4547448 :                D_mat(3, 2) = -r31(jdr)/(d31*d12) + rsst3*r12(jdr)/(d31*d12**3)
    1883              :             ELSE
    1884      1171260 :                D_mat(1, 2) = -r12(jdr)/(d12*d23) + rsst1*r23(jdr)/(d12*d23**3)
    1885              :                D_mat(2, 2) = (r23(jdr) - r31(jdr))/(d23*d31) + rsst2*r23(jdr)/(d23**3*d31) - &
    1886      1171260 :                              rsst2*r31(jdr)/(d23*d31**3)
    1887      1171260 :                D_mat(3, 2) = r12(jdr)/(d31*d12) - rsst3*r31(jdr)/(d31**3*d12)
    1888              :             END IF
    1889      5718708 :             IF (ABS(denom1) <= 0.011_dp) D_mat(1, 1) = 0.0_dp
    1890      5718708 :             IF (ABS(denom2) <= 0.011_dp) D_mat(2, 1) = 0.0_dp
    1891      5718708 :             IF (ABS(denom3) <= 0.011_dp) D_mat(3, 1) = 0.0_dp
    1892              : 
    1893              :             deriv = deriv + ka1*D_mat(1, 1)*D_mat(1, 2)/denom1 + &
    1894              :                     ka2*D_mat(2, 1)*D_mat(2, 2)/denom2 + &
    1895      6360930 :                     ka3*D_mat(3, 1)*D_mat(3, 2)/denom3
    1896              :          END DO
    1897              :       END IF
    1898       243306 :       deriv = 0.25_dp*deriv
    1899              : 
    1900       243306 :    END FUNCTION angle_second_deriv
    1901              : 
    1902              : END MODULE bfgs_optimizer
        

Generated by: LCOV version 2.0-1