LCOV - code coverage report
Current view: top level - src - qs_active_space_methods.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 79.2 % 1870 1481
Test Date: 2026-11-24 01:22:08 Functions: 75.0 % 32 24

            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 Determine active space Hamiltonian
      10              : !> \par History
      11              : !>      04.2016 created [JGH]
      12              : !> \author JGH
      13              : ! **************************************************************************************************
      14              : MODULE qs_active_space_methods
      15              :    USE admm_types, ONLY: admm_type, &
      16              :                          get_admm_env, &
      17              :                          admm_env_release
      18              :    USE atomic_kind_types, ONLY: atomic_kind_type
      19              :    USE basis_set_types, ONLY: allocate_sto_basis_set, &
      20              :                               create_gto_from_sto_basis, &
      21              :                               deallocate_sto_basis_set, &
      22              :                               gto_basis_set_type, &
      23              :                               init_orb_basis_set, &
      24              :                               set_sto_basis_set, &
      25              :                               srules, &
      26              :                               sto_basis_set_type
      27              :    USE cell_types, ONLY: cell_type, use_perd_none, use_perd_xyz
      28              :    USE cell_methods, ONLY: init_cell, set_cell_param, write_cell_low
      29              :    USE cp_blacs_env, ONLY: cp_blacs_env_type, cp_blacs_env_create, cp_blacs_env_release, BLACS_GRID_SQUARE
      30              :    USE cp_control_types, ONLY: dft_control_type, qs_control_type
      31              :    USE cp_dbcsr_operations, ONLY: cp_dbcsr_plus_fm_fm_t, &
      32              :                                   cp_dbcsr_sm_fm_multiply, &
      33              :                                   dbcsr_allocate_matrix_set, &
      34              :                                   cp_dbcsr_m_by_n_from_template, copy_dbcsr_to_fm
      35              :    USE cp_dbcsr_output, ONLY: cp_dbcsr_write_sparse_matrix
      36              :    USE cp_files, ONLY: close_file, &
      37              :                        file_exists, &
      38              :                        open_file
      39              :    USE cp_fm_basic_linalg, ONLY: cp_fm_column_scale
      40              :    USE cp_fm_struct, ONLY: cp_fm_struct_create, &
      41              :                            cp_fm_struct_release, &
      42              :                            cp_fm_struct_type
      43              :    USE cp_fm_types, ONLY: &
      44              :       cp_fm_create, cp_fm_get_element, cp_fm_get_info, cp_fm_init_random, cp_fm_release, &
      45              :       cp_fm_set_all, cp_fm_set_element, cp_fm_to_fm, cp_fm_type, cp_fm_write_formatted
      46              :    USE cp_log_handling, ONLY: cp_get_default_logger, &
      47              :                               cp_logger_get_default_io_unit, &
      48              :                               cp_logger_type
      49              :    USE cp_output_handling, ONLY: &
      50              :       cp_p_file, cp_print_key_finished_output, cp_print_key_should_output, cp_print_key_unit_nr, &
      51              :       debug_print_level, high_print_level, low_print_level, medium_print_level, &
      52              :       silent_print_level
      53              :    USE cp_realspace_grid_cube, ONLY: cp_pw_to_cube
      54              :    USE cp_dbcsr_api, ONLY: &
      55              :       dbcsr_copy, dbcsr_p_type, dbcsr_type, dbcsr_release, &
      56              :       dbcsr_type_no_symmetry, dbcsr_create, dbcsr_set, dbcsr_multiply, dbcsr_iterator_next_block, &
      57              :       dbcsr_iterator_start, dbcsr_iterator_stop, dbcsr_iterator_blocks_left, &
      58              :       dbcsr_iterator_type, dbcsr_type_symmetric, dbcsr_get_occupation, dbcsr_get_info
      59              :    USE cp_dbcsr_csr, ONLY: dbcsr_csr_create, dbcsr_csr_type
      60              :    USE erf_complex, ONLY: erfz_fast
      61              :    USE group_dist_types, ONLY: get_group_dist, release_group_dist, group_dist_d1_type
      62              :    USE input_constants, ONLY: &
      63              :       casci_canonical, eri_method_full_gpw, eri_method_gpw_ht, eri_operator_coulomb, &
      64              :       eri_operator_erf, eri_operator_erfc, eri_operator_gaussian, eri_operator_yukawa, &
      65              :       eri_operator_trunc, eri_operator_lr_trunc, &
      66              :       fci_solver, manual_selection, mao_projection, no_solver, qiskit_solver, wannier_projection, &
      67              :       eri_poisson_analytic, eri_poisson_periodic, eri_poisson_mt, high_spin_roks, &
      68              :       ot_precond_full_single_inverse, ot_precond_solver_default
      69              :    USE kpoint_types, ONLY: get_kpoint_info, kpoint_type
      70              :    USE input_section_types, ONLY: section_vals_get, section_vals_get_subs_vals, &
      71              :                                   section_vals_set_subs_vals, section_vals_type, &
      72              :                                   section_vals_val_get, &
      73              :                                   section_vals_val_set
      74              :    USE ISO_C_BINDING, ONLY: c_null_char
      75              :    USE kinds, ONLY: default_path_length, &
      76              :                     default_string_length, &
      77              :                     dp, &
      78              :                     int_8
      79              :    USE hfx_types, ONLY: hfx_create, hfx_release
      80              :    USE machine, ONLY: m_walltime, m_flush
      81              :    USE mathlib, ONLY: diamat_all
      82              :    USE mathconstants, ONLY: fourpi, twopi, pi, rootpi
      83              :    USE memory_utilities, ONLY: reallocate
      84              :    USE molden_utils, ONLY: write_mos_molden
      85              :    USE message_passing, ONLY: mp_comm_type, &
      86              :                               mp_para_env_type, &
      87              :                               mp_para_env_release
      88              :    USE mp2_gpw, ONLY: create_mat_munu, grep_rows_in_subgroups, build_dbcsr_from_rows
      89              :    USE mt_util, ONLY: MT0D
      90              :    USE parallel_gemm_api, ONLY: parallel_gemm
      91              :    USE particle_list_types, ONLY: particle_list_type
      92              :    USE particle_types, ONLY: particle_type
      93              :    USE periodic_table, ONLY: ptable
      94              :    USE physcon, ONLY: angstrom, bohr
      95              :    USE preconditioner, ONLY: make_preconditioner
      96              :    USE preconditioner_types, ONLY: destroy_preconditioner, &
      97              :                                    init_preconditioner, &
      98              :                                    preconditioner_type
      99              :    USE pw_env_methods, ONLY: pw_env_create, &
     100              :                              pw_env_rebuild
     101              :    USE pw_env_types, ONLY: pw_env_get, &
     102              :                            pw_env_release, &
     103              :                            pw_env_type
     104              :    USE pw_methods, ONLY: pw_integrate_function, &
     105              :                          pw_multiply, &
     106              :                          pw_multiply_with, &
     107              :                          pw_transfer, &
     108              :                          pw_zero, pw_integral_ab, pw_scale, &
     109              :                          pw_gauss_damp, pw_compl_gauss_damp
     110              :    USE pw_poisson_methods, ONLY: pw_poisson_rebuild, &
     111              :                                  pw_poisson_solve
     112              :    USE pw_poisson_types, ONLY: ANALYTIC0D, &
     113              :                                PERIODIC3D, &
     114              :                                greens_fn_type, &
     115              :                                pw_poisson_analytic, &
     116              :                                pw_poisson_periodic, &
     117              :                                pw_poisson_type
     118              :    USE pw_pool_types, ONLY: &
     119              :       pw_pool_type
     120              :    USE pw_types, ONLY: &
     121              :       pw_c1d_gs_type, &
     122              :       pw_r3d_rs_type
     123              :    USE qcschema, ONLY: qcschema_env_create, &
     124              :                        qcschema_env_release, &
     125              :                        qcschema_to_hdf5, &
     126              :                        qcschema_type
     127              :    USE qs_active_space_fci, ONLY: solve_active_space_fci
     128              :    USE qs_active_space_types, ONLY: active_space_type, &
     129              :                                     create_active_space_type, &
     130              :                                     csr_idx_from_combined, &
     131              :                                     csr_idx_to_combined, &
     132              :                                     eri_type, &
     133              :                                     eri_type_eri_element_func
     134              :    USE qs_active_space_mixing, ONLY: active_space_mixing_label, &
     135              :                                      initialize_active_space_mixing, &
     136              :                                      update_active_density
     137              :    USE qs_active_space_utils, ONLY: eri_to_array, &
     138              :                                     find_degenerate_splits, &
     139              :                                     subspace_matrix_to_array
     140              :    USE qs_collocate_density, ONLY: calculate_wavefunction
     141              :    USE qs_density_matrices, ONLY: calculate_density_matrix
     142              :    USE qs_energy_types, ONLY: qs_energy_type
     143              :    USE qs_environment_types, ONLY: get_qs_env, &
     144              :                                    qs_environment_type, &
     145              :                                    set_qs_env
     146              :    USE qs_integrate_potential, ONLY: integrate_v_rspace
     147              :    USE qs_kind_types, ONLY: qs_kind_type
     148              :    USE qs_ks_methods, ONLY: qs_ks_update_qs_env, qs_ks_build_kohn_sham_matrix, &
     149              :                             evaluate_core_matrix_traces
     150              :    USE qs_ks_types, ONLY: qs_ks_did_change, &
     151              :                           qs_ks_env_type, set_ks_env
     152              :    USE qs_mo_io, ONLY: write_mo_set_to_output_unit
     153              :    USE qs_mo_methods, ONLY: calculate_orbital_fock_elements, &
     154              :                             calculate_subspace_eigenvalues, &
     155              :                             make_mo_set_canonical
     156              :    USE qs_mo_types, ONLY: allocate_mo_set, &
     157              :                           deallocate_mo_set, &
     158              :                           get_mo_set, &
     159              :                           init_mo_set, &
     160              :                           mo_set_type
     161              :    USE qs_neighbor_list_types, ONLY: neighbor_list_set_p_type, release_neighbor_list_sets
     162              :    USE qs_ot_eigensolver, ONLY: ot_eigensolver
     163              :    USE qs_rho_methods, ONLY: qs_rho_update_rho
     164              :    USE qs_rho_types, ONLY: qs_rho_get, &
     165              :                            qs_rho_type
     166              :    USE qs_subsys_types, ONLY: qs_subsys_get, &
     167              :                               qs_subsys_type
     168              :    USE qs_scf_post_scf, ONLY: qs_scf_compute_properties
     169              :    USE scf_control_types, ONLY: scf_control_type
     170              : #ifndef __NO_SOCKETS
     171              :    USE sockets_interface, ONLY: accept_socket, &
     172              :                                 close_socket, &
     173              :                                 listen_socket, &
     174              :                                 open_bind_socket, &
     175              :                                 readbuffer, &
     176              :                                 remove_socket_file, &
     177              :                                 writebuffer
     178              : #endif
     179              :    USE task_list_methods, ONLY: generate_qs_task_list
     180              :    USE task_list_types, ONLY: allocate_task_list, &
     181              :                               deallocate_task_list, &
     182              :                               task_list_type
     183              :    USE util, ONLY: get_limit
     184              : #include "./base/base_uses.f90"
     185              : 
     186              :    IMPLICIT NONE
     187              :    PRIVATE
     188              : 
     189              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_active_space_methods'
     190              : 
     191              :    PUBLIC :: active_space_main
     192              : 
     193              :    TYPE, EXTENDS(eri_type_eri_element_func) :: eri_fcidump_print
     194              :       INTEGER :: unit_nr = -1, bra_start = -1, ket_start = -1
     195              :       INTEGER :: nalpha = 0, nbeta = 0
     196              :       REAL(KIND=dp) :: determinant_energy = 0.0_dp
     197              :    CONTAINS
     198              :       PROCEDURE :: func => eri_fcidump_print_func
     199              :    END TYPE eri_fcidump_print
     200              : 
     201              :    TYPE, EXTENDS(eri_type_eri_element_func) :: eri_fcidump_checksum
     202              :       INTEGER :: bra_start = 0, ket_start = 0
     203              :       REAL(KIND=dp) :: checksum = 0.0_dp
     204              :    CONTAINS
     205              :       PROCEDURE, PASS :: set => eri_fcidump_set
     206              :       PROCEDURE :: func => eri_fcidump_checksum_func
     207              :    END TYPE eri_fcidump_checksum
     208              : 
     209              : CONTAINS
     210              : 
     211              : ! **************************************************************************************************
     212              : !> \brief Sets the starting indices of the bra and ket.
     213              : !> \param this object reference
     214              : !> \param bra_start starting index of the bra
     215              : !> \param ket_start starting index of the ket
     216              : ! **************************************************************************************************
     217          130 :    SUBROUTINE eri_fcidump_set(this, bra_start, ket_start)
     218              :       CLASS(eri_fcidump_checksum) :: this
     219              :       INTEGER, INTENT(IN) :: bra_start, ket_start
     220          130 :       this%bra_start = bra_start
     221          130 :       this%ket_start = ket_start
     222          130 :    END SUBROUTINE eri_fcidump_set
     223              : 
     224              : ! **************************************************************************************************
     225              : !> \brief Main method for determining the active space Hamiltonian
     226              : !> \param qs_env ...
     227              : ! **************************************************************************************************
     228        29079 :    SUBROUTINE active_space_main(qs_env)
     229              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     230              : 
     231              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'active_space_main'
     232              : 
     233              :       CHARACTER(len=10)                                  :: cshell, lnam(5)
     234              :       CHARACTER(len=default_path_length)                 :: qcschema_filename
     235              :       CHARACTER(LEN=default_string_length)               :: basis_type, kp_scheme
     236              :       INTEGER :: as_solver, eri_method, eri_operator, eri_print, group_size, handle, i, iatom, &
     237              :          ishell, isp, ispin, iw, j, jm, m, max_orb_ind, mselect, n1, n2, nao, natom, nel, &
     238              :          nelec_active, nelec_inactive, nelec_total, nkp, nmo, nmo_active, nmo_available, &
     239              :          nmo_inactive, nmo_inactive_remaining, nmo_occ, nmo_virtual, nn1, nn2, nrow_global, nspins
     240              :       INTEGER, DIMENSION(5)                              :: nshell
     241        29079 :       INTEGER, DIMENSION(:), POINTER                     :: invals
     242              :       LOGICAL                                            :: do_ddapc, do_kpoints, ex_omega, &
     243              :                                                             ex_operator, ex_perd, ex_rcut, &
     244              :                                                             explicit, stop_after_print, store_wfn, &
     245              :                                                             use_real_wfn
     246              :       REAL(KIND=dp) :: eri_eps_filter, eri_eps_grid, eri_eps_int, eri_gpw_cutoff, eri_op_omega, &
     247              :          eri_rcut, eri_rel_cutoff, fel, focc, max_offdiag, maxocc, nze_percentage
     248        29079 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: eigenvalues
     249        29079 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: evals_virtual
     250              :       TYPE(active_space_type), POINTER                   :: active_space_env
     251        29079 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     252              :       TYPE(cell_type), POINTER                           :: cell
     253              :       TYPE(cp_blacs_env_type), POINTER                   :: context
     254              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct_tmp
     255              :       TYPE(cp_fm_type)                                   :: mo_virtual
     256              :       TYPE(cp_fm_type), POINTER                          :: fm_target_active, fm_target_inactive, &
     257              :                                                             fmat, mo_coeff, mo_ref, mo_target
     258              :       TYPE(cp_logger_type), POINTER                      :: logger
     259              :       TYPE(dbcsr_csr_type), POINTER                      :: eri_mat
     260        58158 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_matrix, rho_ao, s_matrix
     261        58158 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: ks_matrix_kp, rho_ao_kp, s_matrix_kp
     262              :       TYPE(dbcsr_type), POINTER                          :: denmat
     263              :       TYPE(dft_control_type), POINTER                    :: dft_control
     264              :       TYPE(kpoint_type), POINTER                         :: kpoints
     265        29079 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     266              :       TYPE(mo_set_type), POINTER                         :: mo_set, mo_set_active, mo_set_inactive
     267              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     268        29079 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     269              :       TYPE(preconditioner_type), POINTER                 :: local_preconditioner
     270       116316 :       TYPE(qcschema_type)                                :: qcschema_env
     271              :       TYPE(qs_energy_type), POINTER                      :: energy
     272        29079 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     273              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
     274              :       TYPE(qs_rho_type), POINTER                         :: rho
     275              :       TYPE(scf_control_type), POINTER                    :: scf_control
     276              :       TYPE(section_vals_type), POINTER                   :: adiabatic_rescaling, as_input, &
     277              :                                                             hfx_section, input, loc_print, &
     278              :                                                             loc_section, print_orb, xc_section
     279              : 
     280              :       !--------------------------------------------------------------------------------------------!
     281              : 
     282        29079 :       CALL get_qs_env(qs_env, input=input)
     283        29079 :       as_input => section_vals_get_subs_vals(input, "DFT%ACTIVE_SPACE")
     284        29079 :       CALL section_vals_get(as_input, explicit=explicit)
     285        29079 :       IF (.NOT. explicit) RETURN
     286          110 :       CALL timeset(routineN, handle)
     287              : 
     288          110 :       logger => cp_get_default_logger()
     289          110 :       iw = cp_logger_get_default_io_unit(logger)
     290              : 
     291          110 :       IF (iw > 0) THEN
     292              :          WRITE (iw, '(/,T2,A)') &
     293           55 :             '!-----------------------------------------------------------------------------!'
     294           55 :          WRITE (iw, '(T26,A)') "Active Space Embedding Module"
     295              :          WRITE (iw, '(T2,A)') &
     296           55 :             '!-----------------------------------------------------------------------------!'
     297              :       END IF
     298              : 
     299              :       ! k-points?
     300          110 :       NULLIFY (kpoints)
     301          110 :       CALL get_qs_env(qs_env, do_kpoints=do_kpoints, dft_control=dft_control, kpoints=kpoints)
     302          110 :       IF (do_kpoints) THEN
     303            2 :          IF (.NOT. ASSOCIATED(kpoints)) THEN
     304            0 :             CALL cp_abort(__LOCATION__, "Missing Gamma-point environment for active space module")
     305              :          END IF
     306            2 :          CALL get_kpoint_info(kpoints, kp_scheme=kp_scheme, nkp=nkp, use_real_wfn=use_real_wfn)
     307            2 :          IF (TRIM(kp_scheme) /= "GAMMA" .OR. nkp /= 1 .OR. .NOT. use_real_wfn) THEN
     308              :             CALL cp_abort(__LOCATION__, &
     309            0 :                           "Only Gamma-point DFT%KPOINTS are supported in the active space module")
     310              :          END IF
     311            2 :          IF (.NOT. ASSOCIATED(kpoints%kp_env)) THEN
     312            0 :             CALL cp_abort(__LOCATION__, "Missing Gamma-point environment for active space module")
     313              :          END IF
     314            2 :          IF (.NOT. ASSOCIATED(kpoints%kp_env(1)%kpoint_env)) THEN
     315            0 :             CALL cp_abort(__LOCATION__, "Missing Gamma-point environment for active space module")
     316              :          END IF
     317            2 :          IF (.NOT. ASSOCIATED(kpoints%kp_env(1)%kpoint_env%mos)) THEN
     318            0 :             CALL cp_abort(__LOCATION__, "Missing Gamma-point MOs for active space module")
     319              :          END IF
     320              :       END IF
     321              : 
     322              :       ! adiabatic rescaling?
     323          110 :       adiabatic_rescaling => section_vals_get_subs_vals(input, "DFT%XC%ADIABATIC_RESCALING")
     324          110 :       CALL section_vals_get(adiabatic_rescaling, explicit=explicit)
     325          110 :       IF (explicit) THEN
     326            0 :          CALL cp_abort(__LOCATION__, "Adiabatic rescaling not supported in active space module")
     327              :       END IF
     328              : 
     329              :       ! Setup the possible usage of DDAPC charges
     330              :       do_ddapc = dft_control%qs_control%ddapc_restraint .OR. &
     331              :                  qs_env%cp_ddapc_ewald%do_decoupling .OR. &
     332              :                  qs_env%cp_ddapc_ewald%do_qmmm_periodic_decpl .OR. &
     333          110 :                  qs_env%cp_ddapc_ewald%do_solvation
     334              :       IF (do_ddapc) THEN
     335            0 :          CALL cp_abort(__LOCATION__, "DDAPC charges are not supported in the active space module")
     336              :       END IF
     337          110 :       IF (dft_control%do_sccs) THEN
     338            0 :          CALL cp_abort(__LOCATION__, "SCCS is not supported in the active space module")
     339              :       END IF
     340          110 :       IF (dft_control%correct_surf_dip) THEN
     341            0 :          IF (dft_control%surf_dip_correct_switch) THEN
     342            0 :             CALL cp_abort(__LOCATION__, "Surface dipole correction not supported in the AS module")
     343              :          END IF
     344              :       END IF
     345          110 :       IF (dft_control%smeagol_control%smeagol_enabled) THEN
     346            0 :          CALL cp_abort(__LOCATION__, "SMEAGOL is not supported in the active space module")
     347              :       END IF
     348          110 :       IF (dft_control%qs_control%do_kg) THEN
     349            0 :          CALL cp_abort(__LOCATION__, "KG correction not supported in the active space module")
     350              :       END IF
     351              : 
     352          110 :       NULLIFY (active_space_env)
     353          110 :       CALL create_active_space_type(active_space_env)
     354          110 :       active_space_env%energy_total = 0.0_dp
     355          110 :       active_space_env%energy_ref = 0.0_dp
     356          110 :       active_space_env%energy_inactive = 0.0_dp
     357          110 :       active_space_env%energy_active = 0.0_dp
     358              : 
     359              :       ! input options
     360              : 
     361          110 :       CALL section_vals_val_get(as_input, "EPS_FCI", r_val=active_space_env%eps_fci)
     362          110 :       IF (.NOT. (active_space_env%eps_fci > 0.0_dp)) THEN
     363            0 :          CPABORT("ACTIVE_SPACE%EPS_FCI must be positive.")
     364              :       END IF
     365              : 
     366              :       ! figure out what needs to be printed/stored
     367          110 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, as_input, "FCIDUMP"), cp_p_file)) THEN
     368          106 :          active_space_env%fcidump = .TRUE.
     369              :       END IF
     370              : 
     371          110 :       CALL section_vals_val_get(as_input, "QCSCHEMA", c_val=qcschema_filename, explicit=explicit)
     372          110 :       IF (explicit) THEN
     373            6 :          active_space_env%qcschema = .TRUE.
     374            6 :          active_space_env%qcschema_filename = qcschema_filename
     375              :       END IF
     376              : 
     377          110 :       CALL section_vals_val_get(as_input, "ACTIVE_ELECTRONS", i_val=nelec_active)
     378          110 :       CALL get_qs_env(qs_env, nelectron_total=nelec_total)
     379              : 
     380          110 :       IF (nelec_active <= 0) CPABORT("Specify a positive number of active electrons.")
     381          110 :       IF (nelec_active > nelec_total) CPABORT("More active electrons than total electrons.")
     382              : 
     383          110 :       nelec_inactive = nelec_total - nelec_active
     384          110 :       IF (MOD(nelec_inactive, 2) /= 0) THEN
     385            0 :          CPABORT("The remaining number of inactive electrons has to be even.")
     386              :       END IF
     387              : 
     388          110 :       IF (iw > 0) THEN
     389           55 :          WRITE (iw, '(T3,A,T70,I10)') "Total number of electrons", nelec_total
     390           55 :          WRITE (iw, '(T3,A,T70,I10)') "Number of inactive electrons", nelec_inactive
     391           55 :          WRITE (iw, '(T3,A,T70,I10)') "Number of active electrons", nelec_active
     392              :       END IF
     393              : 
     394          110 :       CALL get_qs_env(qs_env, dft_control=dft_control)
     395          110 :       nspins = dft_control%nspins
     396              : 
     397          110 :       active_space_env%nelec_active = nelec_active
     398          110 :       active_space_env%nelec_inactive = nelec_inactive
     399          110 :       active_space_env%nelec_total = nelec_total
     400          110 :       active_space_env%nspins = nspins
     401          110 :       active_space_env%multiplicity = dft_control%multiplicity
     402          110 :       active_space_env%restricted_orbitals = dft_control%roks
     403              : 
     404              :       ! define the active/inactive space orbitals
     405          110 :       CALL section_vals_val_get(as_input, "ACTIVE_ORBITALS", explicit=explicit, i_val=nmo_active)
     406          110 :       IF (.NOT. explicit) THEN
     407            0 :          CALL cp_abort(__LOCATION__, "Number of Active Orbitals has to be specified.")
     408              :       END IF
     409          110 :       active_space_env%nmo_active = nmo_active
     410              :       ! this is safe because nelec_inactive is always even
     411          110 :       nmo_inactive = nelec_inactive/2
     412          110 :       active_space_env%nmo_inactive = nmo_inactive
     413              : 
     414          110 :       CALL initialize_active_space_mixing(active_space_env, as_input)
     415              : 
     416          110 :       CALL section_vals_val_get(as_input, "ORBITAL_SELECTION", i_val=mselect)
     417          110 :       IF (iw > 0) THEN
     418            0 :          SELECT CASE (mselect)
     419              :          CASE DEFAULT
     420            0 :             CPABORT("Unknown orbital selection method")
     421              :          CASE (casci_canonical)
     422              :             WRITE (iw, '(/,T3,A)') &
     423           40 :                "Active space orbitals selected using energy ordered canonical orbitals"
     424              :          CASE (wannier_projection)
     425              :             WRITE (iw, '(/,T3,A)') &
     426            0 :                "Active space orbitals selected using projected Wannier orbitals"
     427              :          CASE (mao_projection)
     428              :             WRITE (iw, '(/,T3,A)') &
     429            0 :                "Active space orbitals selected using modified atomic orbitals (MAO)"
     430              :          CASE (manual_selection)
     431              :             WRITE (iw, '(/,T3,A)') &
     432           55 :                "Active space orbitals selected manually"
     433              :          END SELECT
     434              : 
     435           55 :          WRITE (iw, '(T3,A,T70,I10)') "Number of inactive orbitals", nmo_inactive
     436           55 :          WRITE (iw, '(T3,A,T70,I10)') "Number of active orbitals", nmo_active
     437              :       END IF
     438              : 
     439              :       ! get projection spaces
     440          110 :       CALL section_vals_val_get(as_input, "SUBSPACE_ATOM", i_val=iatom, explicit=explicit)
     441          110 :       IF (explicit) THEN
     442            0 :          CALL get_qs_env(qs_env, natom=natom)
     443            0 :          IF (iatom <= 0 .OR. iatom > natom) THEN
     444            0 :             IF (iw > 0) THEN
     445            0 :                WRITE (iw, '(/,T3,A,I3)') "ERROR: SUBSPACE_ATOM number is not valid", iatom
     446              :             END IF
     447            0 :             CPABORT("Select a valid SUBSPACE_ATOM")
     448              :          END IF
     449              :       END IF
     450          110 :       CALL section_vals_val_get(as_input, "SUBSPACE_SHELL", c_val=cshell, explicit=explicit)
     451          110 :       nshell = 0
     452          660 :       lnam = ""
     453          110 :       IF (explicit) THEN
     454            0 :          cshell = ADJUSTL(cshell)
     455            0 :          n1 = 1
     456            0 :          DO i = 1, 5
     457            0 :             ishell = i
     458            0 :             IF (cshell(n1:n1) == " ") THEN
     459          110 :                ishell = ishell - 1
     460              :                EXIT
     461              :             END IF
     462            0 :             READ (cshell(n1:), "(I1,A1)") nshell(i), lnam(i)
     463            0 :             n1 = n1 + 2
     464              :          END DO
     465              :       END IF
     466              : 
     467              :       ! generate orbitals
     468            0 :       SELECT CASE (mselect)
     469              :       CASE DEFAULT
     470            0 :          CPABORT("Unknown orbital selection method")
     471              :       CASE (casci_canonical)
     472           80 :          IF (do_kpoints) THEN
     473            2 :             mos => kpoints%kp_env(1)%kpoint_env%mos(:)
     474              :          ELSE
     475           78 :             CALL get_qs_env(qs_env, mos=mos)
     476              :          END IF
     477              : 
     478              :          ! total number of occupied orbitals, i.e. inactive plus active MOs
     479           80 :          nmo_occ = nmo_inactive + nmo_active
     480              : 
     481              :          ! set inactive orbital indices, these are trivially 1...nmo_inactive
     482          268 :          ALLOCATE (active_space_env%inactive_orbitals(nmo_inactive, nspins))
     483          172 :          DO ispin = 1, nspins
     484          248 :             DO i = 1, nmo_inactive
     485          168 :                active_space_env%inactive_orbitals(i, ispin) = i
     486              :             END DO
     487              :          END DO
     488              : 
     489              :          ! set active orbital indices, these are shifted by nmo_inactive
     490          320 :          ALLOCATE (active_space_env%active_orbitals(nmo_active, nspins))
     491          172 :          DO ispin = 1, nspins
     492          454 :             DO i = 1, nmo_active
     493          374 :                active_space_env%active_orbitals(i, ispin) = nmo_inactive + i
     494              :             END DO
     495              :          END DO
     496              : 
     497              :          ! allocate and initialize inactive and active mo coefficients.
     498              :          ! These are stored in a data structure for the full occupied space:
     499              :          ! for inactive mos, the active subset is set to zero, vice versa for the active mos
     500              :          ! TODO: allocate data structures only for the eaxct number MOs
     501           80 :          maxocc = 2.0_dp
     502           80 :          IF (nspins > 1) maxocc = 1.0_dp
     503          332 :          ALLOCATE (active_space_env%mos_active(nspins))
     504          252 :          ALLOCATE (active_space_env%mos_inactive(nspins))
     505          172 :          DO ispin = 1, nspins
     506           92 :             CALL get_mo_set(mos(ispin), mo_coeff=mo_ref, nao=nao)
     507           92 :             CALL cp_fm_get_info(mo_ref, context=context, para_env=para_env, nrow_global=nrow_global)
     508              :             ! the right number of active electrons per spin channel is initialized further down
     509           92 :             CALL allocate_mo_set(active_space_env%mos_active(ispin), nao, nmo_occ, 0, 0.0_dp, maxocc, 0.0_dp)
     510              :             CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=context, &
     511           92 :                                      nrow_global=nrow_global, ncol_global=nmo_occ)
     512           92 :             CALL init_mo_set(active_space_env%mos_active(ispin), fm_struct=fm_struct_tmp, name="Active Space MO")
     513           92 :             CALL cp_fm_struct_release(fm_struct_tmp)
     514           92 :             IF (nspins == 2) THEN
     515           24 :                nel = nelec_inactive/2
     516              :             ELSE
     517           68 :                nel = nelec_inactive
     518              :             END IF
     519              :             CALL allocate_mo_set(active_space_env%mos_inactive(ispin), nao, nmo_occ, nel, &
     520           92 :                                  REAL(nel, KIND=dp), maxocc, 0.0_dp)
     521              :             CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=context, &
     522           92 :                                      nrow_global=nrow_global, ncol_global=nmo_occ)
     523           92 :             CALL init_mo_set(active_space_env%mos_inactive(ispin), fm_struct=fm_struct_tmp, name="Inactive Space MO")
     524          264 :             CALL cp_fm_struct_release(fm_struct_tmp)
     525              :          END DO
     526              : 
     527              :          ! create canonical orbitals
     528           80 :          CALL get_qs_env(qs_env, scf_control=scf_control)
     529           80 :          IF (dft_control%roks .AND. scf_control%roks_scheme /= high_spin_roks) THEN
     530              :             CALL cp_abort(__LOCATION__, &
     531              :                           "Only high-spin ROKS is supported for ACTIVE_SPACE FCI; "// &
     532            0 :                           "general ROKS MO definitions are not implemented.")
     533              :          ELSE
     534           80 :             IF (dft_control%do_admm) THEN
     535            0 :                IF (dft_control%do_admm_mo) THEN
     536            0 :                   CPABORT("ADMM currently possible only with purification none_dm")
     537              :                END IF
     538              :             END IF
     539              : 
     540          320 :             ALLOCATE (eigenvalues(nmo_occ, nspins))
     541           80 :             eigenvalues = 0.0_dp
     542           80 :             IF (do_kpoints) THEN
     543              :                CALL get_qs_env(qs_env, matrix_ks_kp=ks_matrix_kp, matrix_s_kp=s_matrix_kp, &
     544            2 :                                scf_control=scf_control)
     545            2 :                ks_matrix => ks_matrix_kp(:, 1)
     546            2 :                s_matrix => s_matrix_kp(:, 1)
     547              :             ELSE
     548           78 :                CALL get_qs_env(qs_env, matrix_ks=ks_matrix, matrix_s=s_matrix, scf_control=scf_control)
     549              :             END IF
     550              : 
     551              :             ! calculate virtual MOs and copy inactive and active orbitals
     552           80 :             IF (iw > 0) THEN
     553           40 :                WRITE (iw, '(/,T3,A)') "Calculating virtual MOs..."
     554              :             END IF
     555          172 :             DO ispin = 1, nspins
     556              :                ! the selection needs canonical SCF orbitals (e.g. not after OT)
     557              :                CALL ensure_canonical_orbitals(qs_env, mos(ispin), ks_matrix(ispin)%matrix, ispin, &
     558           92 :                                               .FALSE., do_kpoints, iw)
     559              :                ! nmo_available is the number of MOs available from the SCF calculation:
     560              :                ! this is at least the number of occupied orbitals in the SCF, plus
     561              :                ! any number of added MOs (virtuals) requested in the SCF section
     562           92 :                CALL get_mo_set(mos(ispin), mo_coeff=mo_ref, nmo=nmo_available)
     563              : 
     564              :                ! calculate how many extra MOs we still have to compute
     565           92 :                nmo_virtual = nmo_occ - nmo_available
     566           92 :                nmo_virtual = MAX(nmo_virtual, 0)
     567              : 
     568              :                NULLIFY (evals_virtual)
     569          186 :                ALLOCATE (evals_virtual(nmo_virtual))
     570              : 
     571              :                CALL cp_fm_get_info(mo_ref, context=context, para_env=para_env, &
     572           92 :                                    nrow_global=nrow_global)
     573              : 
     574              :                CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=context, &
     575           92 :                                         nrow_global=nrow_global, ncol_global=nmo_virtual)
     576           92 :                CALL cp_fm_create(mo_virtual, fm_struct_tmp, name="virtual")
     577           92 :                CALL cp_fm_struct_release(fm_struct_tmp)
     578           92 :                CALL cp_fm_init_random(mo_virtual, nmo_virtual)
     579              : 
     580              :                ! compute missing virtual MOs
     581              :                CALL virtual_orbital_preconditioner(local_preconditioner, mos(ispin), ks_matrix(ispin)%matrix, &
     582           92 :                                                    s_matrix(1)%matrix, nmo_virtual, para_env, context)
     583              :                CALL ot_eigensolver(matrix_h=ks_matrix(ispin)%matrix, matrix_s=s_matrix(1)%matrix, &
     584              :                                    matrix_c_fm=mo_virtual, matrix_orthogonal_space_fm=mo_ref, &
     585              :                                    eps_gradient=scf_control%eps_lumos, &
     586              :                                    preconditioner=local_preconditioner, &
     587              :                                    iter_max=scf_control%max_iter_lumos, &
     588           92 :                                    size_ortho_space=nmo_available)
     589           92 :                IF (ASSOCIATED(local_preconditioner)) THEN
     590            2 :                   CALL destroy_preconditioner(local_preconditioner)
     591            2 :                   DEALLOCATE (local_preconditioner)
     592              :                END IF
     593              : 
     594              :                ! get the eigenvalues
     595           92 :                CALL calculate_subspace_eigenvalues(mo_virtual, ks_matrix(ispin)%matrix, evals_virtual)
     596              : 
     597              :                ! orbital energies <i|F|i> of the SCF orbitals, which are used unchanged
     598              :                CALL calculate_orbital_fock_elements(mo_ref, ks_matrix(ispin)%matrix, &
     599           92 :                                                     eigenvalues(:, ispin), max_offdiag)
     600              : 
     601              :                ! copy inactive orbitals
     602           92 :                mo_set => active_space_env%mos_inactive(ispin)
     603           92 :                CALL get_mo_set(mo_set, mo_coeff=mo_target)
     604          168 :                DO i = 1, SIZE(active_space_env%inactive_orbitals, 1)
     605           76 :                   m = active_space_env%inactive_orbitals(i, ispin)
     606           76 :                   CALL cp_fm_to_fm(mo_ref, mo_target, 1, m, m)
     607           76 :                   mo_set%eigenvalues(m) = eigenvalues(m, ispin)
     608          168 :                   IF (nspins > 1) THEN
     609           32 :                      mo_set%occupation_numbers(m) = 1.0_dp
     610              :                   ELSE
     611           44 :                      mo_set%occupation_numbers(m) = 2.0_dp
     612              :                   END IF
     613              :                END DO
     614              : 
     615              :                ! copy active orbitals
     616           92 :                mo_set => active_space_env%mos_active(ispin)
     617           92 :                CALL get_mo_set(mo_set, mo_coeff=mo_target)
     618              :                ! for mult > 1, put the polarized electrons in the alpha channel
     619           92 :                IF (nspins == 2) THEN
     620           24 :                   IF (ispin == 1) THEN
     621           12 :                      nel = (nelec_active + active_space_env%multiplicity - 1)/2
     622              :                   ELSE
     623           12 :                      nel = (nelec_active - active_space_env%multiplicity + 1)/2
     624              :                   END IF
     625              :                ELSE
     626           68 :                   nel = nelec_active
     627              :                END IF
     628           92 :                mo_set%nelectron = nel
     629           92 :                mo_set%n_el_f = REAL(nel, KIND=dp)
     630          374 :                DO i = 1, nmo_active
     631          282 :                   m = active_space_env%active_orbitals(i, ispin)
     632          282 :                   IF (m > nmo_available) THEN
     633            8 :                      CALL cp_fm_to_fm(mo_virtual, mo_target, 1, m - nmo_available, m)
     634            8 :                      eigenvalues(m, ispin) = evals_virtual(m - nmo_available)
     635            8 :                      mo_set%occupation_numbers(m) = 0.0_dp
     636              :                   ELSE
     637          274 :                      CALL cp_fm_to_fm(mo_ref, mo_target, 1, m, m)
     638          274 :                      mo_set%occupation_numbers(m) = mos(ispin)%occupation_numbers(m)
     639              :                   END IF
     640          374 :                   mo_set%eigenvalues(m) = eigenvalues(m, ispin)
     641              :                END DO
     642              :                ! Release
     643           92 :                DEALLOCATE (evals_virtual)
     644          448 :                CALL cp_fm_release(mo_virtual)
     645              :             END DO
     646              : 
     647           80 :             IF (iw > 0) THEN
     648           86 :                DO ispin = 1, nspins
     649           46 :                   WRITE (iw, '(/,T3,A,I3,T66,A)') "Canonical Orbital Selection for spin", ispin, &
     650           92 :                      "[atomic units]"
     651           64 :                   DO i = 1, nmo_inactive, 4
     652           18 :                      jm = MIN(3, nmo_inactive - i)
     653          102 :                      WRITE (iw, '(T3,4(F14.6,A5))') (eigenvalues(i + j, ispin), " [I]", j=0, jm)
     654              :                   END DO
     655           97 :                   DO i = nmo_inactive + 1, nmo_inactive + nmo_active, 4
     656           51 :                      jm = MIN(3, nmo_inactive + nmo_active - i)
     657          238 :                      WRITE (iw, '(T3,4(F14.6,A5))') (eigenvalues(i + j, ispin), " [A]", j=0, jm)
     658              :                   END DO
     659           46 :                   WRITE (iw, '(/,T3,A,I3)') "Active Orbital Indices for spin", ispin
     660          137 :                   DO i = 1, SIZE(active_space_env%active_orbitals, 1), 4
     661           51 :                      jm = MIN(3, SIZE(active_space_env%active_orbitals, 1) - i)
     662          238 :                      WRITE (iw, '(T3,4(I4))') (active_space_env%active_orbitals(i + j, ispin), j=0, jm)
     663              :                   END DO
     664              :                END DO
     665              :             END IF
     666           80 :             DEALLOCATE (eigenvalues)
     667              :          END IF
     668              : 
     669              :       CASE (manual_selection)
     670              :          ! create canonical orbitals
     671           30 :          IF (dft_control%roks) THEN
     672              :             CALL cp_abort(__LOCATION__, &
     673              :                           "Manual ACTIVE_SPACE orbital selection is not supported for ROKS; "// &
     674            0 :                           "use canonical high-spin ROKS.")
     675              :          ELSE
     676           30 :             IF (dft_control%do_admm) THEN
     677              :                ! For admm_mo, the auxiliary density is computed from the MOs, which never change
     678              :                ! in the rs-dft embedding, therefore the energy is wrong as the LR HFX never changes.
     679              :                ! For admm_dm, the auxiliary density is computed from the density matrix, which is
     680              :                ! updated at each iteration and therefore works.
     681            0 :                IF (dft_control%do_admm_mo) THEN
     682            0 :                   CPABORT("ADMM currently possible only with purification none_dm")
     683              :                END IF
     684              :             END IF
     685              : 
     686           30 :             CALL section_vals_val_get(as_input, "ACTIVE_ORBITAL_INDICES", explicit=explicit, i_vals=invals)
     687           30 :             IF (.NOT. explicit) THEN
     688              :                CALL cp_abort(__LOCATION__, "Manual orbital selection requires to explicitly "// &
     689            0 :                              "set the active orbital indices via ACTIVE_ORBITAL_INDICES")
     690              :             END IF
     691              : 
     692           30 :             IF (nspins == 1) THEN
     693           22 :                CPASSERT(SIZE(invals) == nmo_active)
     694              :             ELSE
     695            8 :                CPASSERT(SIZE(invals) == 2*nmo_active)
     696              :             END IF
     697          104 :             ALLOCATE (active_space_env%inactive_orbitals(nmo_inactive, nspins))
     698          120 :             ALLOCATE (active_space_env%active_orbitals(nmo_active, nspins))
     699              : 
     700           68 :             DO ispin = 1, nspins
     701          180 :                DO i = 1, nmo_active
     702          150 :                   active_space_env%active_orbitals(i, ispin) = invals(i + (ispin - 1)*nmo_active)
     703              :                END DO
     704              :             END DO
     705              : 
     706           30 :             IF (do_kpoints) THEN
     707            0 :                mos => kpoints%kp_env(1)%kpoint_env%mos(:)
     708              :             ELSE
     709           30 :                CALL get_qs_env(qs_env, mos=mos)
     710              :             END IF
     711              : 
     712              :             ! include MOs up to the largest index in the list
     713          142 :             max_orb_ind = MAXVAL(invals)
     714           30 :             maxocc = 2.0_dp
     715           30 :             IF (nspins > 1) maxocc = 1.0_dp
     716          128 :             ALLOCATE (active_space_env%mos_active(nspins))
     717           98 :             ALLOCATE (active_space_env%mos_inactive(nspins))
     718           68 :             DO ispin = 1, nspins
     719              :                ! init active orbitals
     720           38 :                CALL get_mo_set(mos(ispin), mo_coeff=mo_ref, nao=nao)
     721           38 :                CALL cp_fm_get_info(mo_ref, context=context, para_env=para_env, nrow_global=nrow_global)
     722           38 :                CALL allocate_mo_set(active_space_env%mos_active(ispin), nao, max_orb_ind, 0, 0.0_dp, maxocc, 0.0_dp)
     723              :                CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=context, &
     724           38 :                                         nrow_global=nrow_global, ncol_global=max_orb_ind)
     725           38 :                CALL init_mo_set(active_space_env%mos_active(ispin), fm_struct=fm_struct_tmp, name="Active Space MO")
     726           38 :                CALL cp_fm_struct_release(fm_struct_tmp)
     727              : 
     728              :                ! init inactive orbitals
     729           38 :                IF (nspins == 2) THEN
     730           16 :                   nel = nelec_inactive/2
     731              :                ELSE
     732           22 :                   nel = nelec_inactive
     733              :                END IF
     734           38 :                CALL allocate_mo_set(active_space_env%mos_inactive(ispin), nao, max_orb_ind, nel, REAL(nel, KIND=dp), maxocc, 0.0_dp)
     735              :                CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=context, &
     736           38 :                                         nrow_global=nrow_global, ncol_global=max_orb_ind)
     737           38 :                CALL init_mo_set(active_space_env%mos_inactive(ispin), fm_struct=fm_struct_tmp, name="Inactive Space MO")
     738              :                ! small hack: set the correct inactive occupations down below
     739          186 :                active_space_env%mos_inactive(ispin)%occupation_numbers = 0.0_dp
     740          106 :                CALL cp_fm_struct_release(fm_struct_tmp)
     741              :             END DO
     742              : 
     743          120 :             ALLOCATE (eigenvalues(max_orb_ind, nspins))
     744           30 :             eigenvalues = 0.0_dp
     745           30 :             IF (do_kpoints) THEN
     746              :                CALL get_qs_env(qs_env, matrix_ks_kp=ks_matrix_kp, matrix_s_kp=s_matrix_kp, &
     747            0 :                                scf_control=scf_control)
     748            0 :                ks_matrix => ks_matrix_kp(:, 1)
     749            0 :                s_matrix => s_matrix_kp(:, 1)
     750              :             ELSE
     751           30 :                CALL get_qs_env(qs_env, matrix_ks=ks_matrix, matrix_s=s_matrix, scf_control=scf_control)
     752              :             END IF
     753              : 
     754              :             ! calculate virtual MOs and copy inactive and active orbitals
     755           30 :             IF (iw > 0) THEN
     756           15 :                WRITE (iw, '(/,T3,A)') "Calculating virtual MOs..."
     757              :             END IF
     758           68 :             DO ispin = 1, nspins
     759              :                ! the orbital indices refer to canonical SCF orbitals (e.g. not after OT)
     760              :                CALL ensure_canonical_orbitals(qs_env, mos(ispin), ks_matrix(ispin)%matrix, ispin, &
     761           38 :                                               .TRUE., do_kpoints, iw)
     762           38 :                CALL get_mo_set(mos(ispin), mo_coeff=mo_ref, nmo=nmo_available)
     763           38 :                nmo_virtual = max_orb_ind - nmo_available
     764           38 :                nmo_virtual = MAX(nmo_virtual, 0)
     765              : 
     766              :                NULLIFY (evals_virtual)
     767           78 :                ALLOCATE (evals_virtual(nmo_virtual))
     768              : 
     769              :                CALL cp_fm_get_info(mo_ref, context=context, para_env=para_env, &
     770           38 :                                    nrow_global=nrow_global)
     771              : 
     772              :                CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=context, &
     773           38 :                                         nrow_global=nrow_global, ncol_global=nmo_virtual)
     774           38 :                CALL cp_fm_create(mo_virtual, fm_struct_tmp, name="virtual")
     775           38 :                CALL cp_fm_struct_release(fm_struct_tmp)
     776           38 :                CALL cp_fm_init_random(mo_virtual, nmo_virtual)
     777              : 
     778              :                CALL virtual_orbital_preconditioner(local_preconditioner, mos(ispin), ks_matrix(ispin)%matrix, &
     779           38 :                                                    s_matrix(1)%matrix, nmo_virtual, para_env, context)
     780              :                CALL ot_eigensolver(matrix_h=ks_matrix(ispin)%matrix, matrix_s=s_matrix(1)%matrix, &
     781              :                                    matrix_c_fm=mo_virtual, matrix_orthogonal_space_fm=mo_ref, &
     782              :                                    eps_gradient=scf_control%eps_lumos, &
     783              :                                    preconditioner=local_preconditioner, &
     784              :                                    iter_max=scf_control%max_iter_lumos, &
     785           38 :                                    size_ortho_space=nmo_available)
     786           38 :                IF (ASSOCIATED(local_preconditioner)) THEN
     787            2 :                   CALL destroy_preconditioner(local_preconditioner)
     788            2 :                   DEALLOCATE (local_preconditioner)
     789              :                END IF
     790              : 
     791              :                CALL calculate_subspace_eigenvalues(mo_virtual, ks_matrix(ispin)%matrix, &
     792           38 :                                                    evals_virtual)
     793              : 
     794              :                ! orbital energies <i|F|i> of the SCF orbitals, which are used unchanged
     795              :                CALL calculate_orbital_fock_elements(mo_ref, ks_matrix(ispin)%matrix, &
     796           38 :                                                     eigenvalues(:, ispin), max_offdiag)
     797              : 
     798           38 :                mo_set_active => active_space_env%mos_active(ispin)
     799           38 :                CALL get_mo_set(mo_set_active, mo_coeff=fm_target_active)
     800           38 :                mo_set_inactive => active_space_env%mos_inactive(ispin)
     801           38 :                CALL get_mo_set(mo_set_inactive, mo_coeff=fm_target_inactive)
     802              : 
     803              :                ! copy orbitals
     804           38 :                nmo_inactive_remaining = nmo_inactive
     805          186 :                DO i = 1, max_orb_ind
     806              :                   ! case for i being an active orbital
     807          454 :                   IF (ANY(active_space_env%active_orbitals(:, ispin) == i)) THEN
     808          112 :                      IF (i > nmo_available) THEN
     809            8 :                         CALL cp_fm_to_fm(mo_virtual, fm_target_active, 1, i - nmo_available, i)
     810            8 :                         eigenvalues(i, ispin) = evals_virtual(i - nmo_available)
     811            8 :                         mo_set_active%occupation_numbers(i) = 0.0_dp
     812              :                      ELSE
     813          104 :                         CALL cp_fm_to_fm(mo_ref, fm_target_active, 1, i, i)
     814          104 :                         mo_set_active%occupation_numbers(i) = mos(ispin)%occupation_numbers(i)
     815              :                      END IF
     816          112 :                      mo_set_active%eigenvalues(i) = eigenvalues(i, ispin)
     817              :                      ! if it was not an active orbital, check whether it is an inactive orbital
     818           36 :                   ELSE IF (nmo_inactive_remaining > 0) THEN
     819           20 :                      CALL cp_fm_to_fm(mo_ref, fm_target_inactive, 1, i, i)
     820              :                      ! store on the fly the mapping of inactive orbitals
     821           20 :                      active_space_env%inactive_orbitals(nmo_inactive - nmo_inactive_remaining + 1, ispin) = i
     822           20 :                      mo_set_inactive%eigenvalues(i) = eigenvalues(i, ispin)
     823           20 :                      mo_set_inactive%occupation_numbers(i) = mos(ispin)%occupation_numbers(i)
     824              :                      ! hack: set homo and lumo manually
     825           20 :                      IF (nmo_inactive_remaining == 1) THEN
     826            8 :                         mo_set_inactive%homo = i
     827            8 :                         mo_set_inactive%lfomo = i + 1
     828              :                      END IF
     829           20 :                      nmo_inactive_remaining = nmo_inactive_remaining - 1
     830              :                   ELSE
     831           16 :                      CYCLE
     832              :                   END IF
     833              :                END DO
     834              : 
     835              :                ! Release
     836           38 :                DEALLOCATE (evals_virtual)
     837          182 :                CALL cp_fm_release(mo_virtual)
     838              :             END DO
     839              : 
     840           30 :             IF (iw > 0) THEN
     841           34 :                DO ispin = 1, nspins
     842           19 :                   WRITE (iw, '(/,T3,A,I3,T66,A)') "Orbital Energies and Selection for spin", ispin, "[atomic units]"
     843              : 
     844           42 :                   DO i = 1, max_orb_ind, 4
     845           23 :                      jm = MIN(3, max_orb_ind - i)
     846           23 :                      WRITE (iw, '(T4)', advance="no")
     847           97 :                      DO j = 0, jm
     848          231 :                         IF (ANY(active_space_env%active_orbitals(:, ispin) == i + j)) THEN
     849           56 :                            WRITE (iw, '(T3,F12.6,A5)', advance="no") eigenvalues(i + j, ispin), " [A]"
     850           23 :                         ELSE IF (ANY(active_space_env%inactive_orbitals(:, ispin) == i + j)) THEN
     851           10 :                            WRITE (iw, '(T3,F12.6,A5)', advance="no") eigenvalues(i + j, ispin), " [I]"
     852              :                         ELSE
     853            8 :                            WRITE (iw, '(T3,F12.6,A5)', advance="no") eigenvalues(i + j, ispin), " [V]"
     854              :                         END IF
     855              :                      END DO
     856           42 :                      WRITE (iw, *)
     857              :                   END DO
     858           19 :                   WRITE (iw, '(/,T3,A,I3)') "Active Orbital Indices for spin", ispin
     859           56 :                   DO i = 1, SIZE(active_space_env%active_orbitals, 1), 4
     860           22 :                      jm = MIN(3, SIZE(active_space_env%active_orbitals, 1) - i)
     861           97 :                      WRITE (iw, '(T3,4(I4))') (active_space_env%active_orbitals(i + j, ispin), j=0, jm)
     862              :                   END DO
     863              :                END DO
     864              :             END IF
     865           60 :             DEALLOCATE (eigenvalues)
     866              :          END IF
     867              : 
     868              :       CASE (wannier_projection)
     869            0 :          NULLIFY (loc_section, loc_print)
     870            0 :          loc_section => section_vals_get_subs_vals(as_input, "LOCALIZE")
     871            0 :          CPASSERT(ASSOCIATED(loc_section))
     872            0 :          loc_print => section_vals_get_subs_vals(as_input, "LOCALIZE%PRINT")
     873              :          !
     874            0 :          CPABORT("not yet available")
     875              :          !
     876              :       CASE (mao_projection)
     877              :          !
     878          110 :          CPABORT("not yet available")
     879              :          !
     880              :       END SELECT
     881              : 
     882              :       ! Warn if the active space splits a set of degenerate orbitals
     883          110 :       CALL check_active_space_degeneracy(active_space_env, mos)
     884              : 
     885              :       ! Print orbitals on Cube files
     886          110 :       print_orb => section_vals_get_subs_vals(as_input, "PRINT_ORBITAL_CUBES")
     887          110 :       CALL section_vals_get(print_orb, explicit=explicit)
     888          110 :       CALL section_vals_val_get(print_orb, "STOP_AFTER_CUBES", l_val=stop_after_print)
     889          110 :       IF (explicit) THEN
     890              :          !
     891            4 :          CALL print_orbital_cubes(print_orb, qs_env, active_space_env%mos_active)
     892              :          !
     893            4 :          IF (stop_after_print) THEN
     894              : 
     895            0 :             IF (iw > 0) THEN
     896              :                WRITE (iw, '(/,T2,A)') &
     897            0 :                   '!----------------- Early End of Active Space Interface -----------------------!'
     898              :             END IF
     899              : 
     900            0 :             CALL timestop(handle)
     901              : 
     902            0 :             RETURN
     903              :          END IF
     904              :       END IF
     905              : 
     906              :       ! calculate inactive density matrix
     907          110 :       CALL get_qs_env(qs_env, rho=rho)
     908          110 :       IF (do_kpoints) THEN
     909            2 :          CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
     910            2 :          rho_ao => rho_ao_kp(:, 1)
     911              :       ELSE
     912          108 :          CALL qs_rho_get(rho, rho_ao=rho_ao)
     913              :       END IF
     914          110 :       CPASSERT(ASSOCIATED(rho_ao))
     915          110 :       CALL dbcsr_allocate_matrix_set(active_space_env%pmat_inactive, nspins)
     916          240 :       DO ispin = 1, nspins
     917          130 :          ALLOCATE (denmat)
     918          130 :          CALL dbcsr_copy(denmat, rho_ao(ispin)%matrix)
     919          130 :          mo_set => active_space_env%mos_inactive(ispin)
     920          130 :          CALL calculate_density_matrix(mo_set, denmat)
     921          240 :          active_space_env%pmat_inactive(ispin)%matrix => denmat
     922              :       END DO
     923              : 
     924              :       ! read in ERI parameters
     925          110 :       CALL section_vals_val_get(as_input, "ERI%METHOD", i_val=eri_method)
     926          110 :       active_space_env%eri%method = eri_method
     927          110 :       CALL section_vals_val_get(as_input, "ERI%OPERATOR", i_val=eri_operator, explicit=ex_operator)
     928          110 :       active_space_env%eri%operator = eri_operator
     929          110 :       CALL section_vals_val_get(as_input, "ERI%OMEGA", r_val=eri_op_omega, explicit=ex_omega)
     930          110 :       active_space_env%eri%omega = eri_op_omega
     931          110 :       CALL section_vals_val_get(as_input, "ERI%CUTOFF_RADIUS", r_val=eri_rcut, explicit=ex_rcut)
     932          110 :       active_space_env%eri%cutoff_radius = eri_rcut  ! this is already converted to bohr!
     933          110 :       CALL section_vals_val_get(as_input, "ERI%PERIODICITY", i_vals=invals, explicit=ex_perd)
     934          110 :       CALL section_vals_val_get(as_input, "ERI%EPS_INTEGRAL", r_val=eri_eps_int)
     935          110 :       active_space_env%eri%eps_integral = eri_eps_int
     936              :       ! if eri periodicity is explicitly set, we use it, otherwise we use the cell periodicity
     937          110 :       IF (ex_perd) THEN
     938           98 :          IF (SIZE(invals) == 1) THEN
     939            0 :             active_space_env%eri%periodicity(1:3) = invals(1)
     940              :          ELSE
     941          686 :             active_space_env%eri%periodicity(1:3) = invals(1:3)
     942              :          END IF
     943              :       ELSE
     944           12 :          CALL get_qs_env(qs_env, cell=cell)
     945           84 :          active_space_env%eri%periodicity(1:3) = cell%perd(1:3)
     946              :       END IF
     947          110 :       IF (iw > 0) THEN
     948           55 :          WRITE (iw, '(/,T3,A)') "Calculation of Electron Repulsion Integrals"
     949              : 
     950           47 :          SELECT CASE (eri_method)
     951              :          CASE (eri_method_full_gpw)
     952           47 :             WRITE (iw, '(T3,A,T50,A)') "Integration method", "GPW Fourier transform over MOs"
     953              :          CASE (eri_method_gpw_ht)
     954            8 :             WRITE (iw, '(T3,A,T44,A)') "Integration method", "Half transformed integrals from GPW"
     955              :          CASE DEFAULT
     956           55 :             CPABORT("Unknown ERI method")
     957              :          END SELECT
     958              : 
     959           45 :          SELECT CASE (eri_operator)
     960              :          CASE (eri_operator_coulomb)
     961           45 :             WRITE (iw, '(T3,A,T73,A)') "ERI operator", "Coulomb"
     962              : 
     963              :          CASE (eri_operator_yukawa)
     964            0 :             WRITE (iw, '(T3,A,T74,A)') "ERI operator", "Yukawa"
     965            0 :             IF (.NOT. ex_omega) CALL cp_abort(__LOCATION__, &
     966            0 :                                               "Yukawa operator requires OMEGA to be explicitly set")
     967            0 :             WRITE (iw, '(T3,A,T66,F14.3)') "ERI operator parameter OMEGA", eri_op_omega
     968              : 
     969              :          CASE (eri_operator_erf)
     970            8 :             WRITE (iw, '(T3,A,T63,A)') "ERI operator", "Longrange Coulomb"
     971            8 :             IF (.NOT. ex_omega) CALL cp_abort(__LOCATION__, &
     972            0 :                                               "Longrange operator requires OMEGA to be explicitly set")
     973            8 :             WRITE (iw, '(T3,A,T66,F14.3)') "ERI operator parameter OMEGA", eri_op_omega
     974              : 
     975              :          CASE (eri_operator_erfc)
     976            0 :             WRITE (iw, '(T3,A,T62,A)') "ERI operator", "Shortrange Coulomb"
     977            0 :             IF (.NOT. ex_omega) CALL cp_abort(__LOCATION__, &
     978            0 :                                               "Shortrange operator requires OMEGA to be explicitly set")
     979            0 :             WRITE (iw, '(T3,A,T66,F14.3)') "ERI operator parameter OMEGA", eri_op_omega
     980              : 
     981              :          CASE (eri_operator_trunc)
     982            0 :             WRITE (iw, '(T3,A,T63,A)') "ERI operator", "Truncated Coulomb"
     983            0 :             IF (.NOT. ex_rcut) CALL cp_abort(__LOCATION__, &
     984            0 :                                              "Cutoff radius not specified for trunc. Coulomb operator")
     985            0 :             WRITE (iw, '(T3,A,T66,F14.3)') "ERI operator cutoff radius (au)", eri_rcut
     986              : 
     987              :          CASE (eri_operator_lr_trunc)
     988            2 :             WRITE (iw, '(T3,A,T53,A)') "ERI operator", "Longrange truncated Coulomb"
     989            2 :             IF (.NOT. ex_rcut) CALL cp_abort(__LOCATION__, &
     990            0 :                                              "Cutoff radius not specified for trunc. longrange operator")
     991            2 :             WRITE (iw, '(T3,A,T66,F14.3)') "ERI operator cutoff radius (au)", eri_rcut
     992            2 :             IF (.NOT. ex_omega) CALL cp_abort(__LOCATION__, &
     993            0 :                                               "LR truncated operator requires OMEGA to be explicitly set")
     994            2 :             WRITE (iw, '(T3,A,T66,F14.3)') "ERI operator parameter OMEGA", eri_op_omega
     995            2 :             IF (eri_op_omega < 0.01_dp) THEN
     996            0 :                CPABORT("LR truncated operator requires OMEGA >= 0.01 to be stable")
     997              :             END IF
     998              : 
     999              :          CASE DEFAULT
    1000           55 :             CPABORT("Unknown ERI operator")
    1001              : 
    1002              :          END SELECT
    1003              : 
    1004           55 :          WRITE (iw, '(T3,A,T68,E12.4)') "Accuracy of ERIs", eri_eps_int
    1005          220 :          WRITE (iw, '(T3,A,T71,3I3)') "Periodicity", active_space_env%eri%periodicity(1:3)
    1006              : 
    1007              :          ! TODO: should be moved after ERI calculation, as it depends on screening
    1008           55 :          IF (nspins < 2) THEN
    1009           45 :             WRITE (iw, '(T3,A,T68,I12)') "Total Number of ERI", (nmo_active**4)/8
    1010              :          ELSE
    1011           10 :             WRITE (iw, '(T3,A,T68,I12)') "Total Number of ERI (aa|aa)", (nmo_active**4)/8
    1012           10 :             WRITE (iw, '(T3,A,T68,I12)') "Total Number of ERI (bb|bb)", (nmo_active**4)/8
    1013           10 :             WRITE (iw, '(T3,A,T68,I12)') "Total Number of ERI (aa|bb)", (nmo_active**4)/4
    1014              :          END IF
    1015              :       END IF
    1016              : 
    1017              :       ! allocate container for integrals (CSR matrix)
    1018          110 :       CALL get_qs_env(qs_env, para_env=para_env)
    1019          110 :       m = (nspins*(nspins + 1))/2
    1020              :       ! With ROHF/ROKS, we need ERIs from only a single set of orbitals
    1021          110 :       IF (dft_control%roks) m = 1
    1022          468 :       ALLOCATE (active_space_env%eri%eri(m))
    1023          248 :       DO i = 1, m
    1024          138 :          CALL get_mo_set(active_space_env%mos_active(1), nmo=nmo)
    1025          138 :          ALLOCATE (active_space_env%eri%eri(i)%csr_mat)
    1026          138 :          eri_mat => active_space_env%eri%eri(i)%csr_mat
    1027          138 :          IF (i == 1) THEN
    1028          110 :             n1 = nmo
    1029          110 :             n2 = nmo
    1030           28 :          ELSE IF (i == 2) THEN
    1031           14 :             n1 = nmo
    1032           14 :             n2 = nmo
    1033              :          ELSE
    1034           14 :             n1 = nmo
    1035           14 :             n2 = nmo
    1036              :          END IF
    1037          138 :          nn1 = (n1*(n1 + 1))/2
    1038          138 :          nn2 = (n2*(n2 + 1))/2
    1039          138 :          CALL dbcsr_csr_create(eri_mat, nn1, nn2, 0_int_8, 0, 0, para_env%get_handle())
    1040          386 :          active_space_env%eri%norb = nmo
    1041              :       END DO
    1042              : 
    1043          110 :       SELECT CASE (eri_method)
    1044              :       CASE (eri_method_full_gpw, eri_method_gpw_ht)
    1045          110 :          CALL section_vals_val_get(as_input, "ERI_GPW%EPS_GRID", r_val=eri_eps_grid)
    1046          110 :          active_space_env%eri%eri_gpw%eps_grid = eri_eps_grid
    1047          110 :          CALL section_vals_val_get(as_input, "ERI_GPW%EPS_FILTER", r_val=eri_eps_filter)
    1048          110 :          active_space_env%eri%eri_gpw%eps_filter = eri_eps_filter
    1049          110 :          CALL section_vals_val_get(as_input, "ERI_GPW%CUTOFF", r_val=eri_gpw_cutoff)
    1050          110 :          active_space_env%eri%eri_gpw%cutoff = eri_gpw_cutoff
    1051          110 :          CALL section_vals_val_get(as_input, "ERI_GPW%REL_CUTOFF", r_val=eri_rel_cutoff)
    1052          110 :          active_space_env%eri%eri_gpw%rel_cutoff = eri_rel_cutoff
    1053          110 :          CALL section_vals_val_get(as_input, "ERI_GPW%PRINT_LEVEL", i_val=eri_print)
    1054          110 :          active_space_env%eri%eri_gpw%print_level = eri_print
    1055          110 :          CALL section_vals_val_get(as_input, "ERI_GPW%STORE_WFN", l_val=store_wfn)
    1056          110 :          active_space_env%eri%eri_gpw%store_wfn = store_wfn
    1057          110 :          CALL section_vals_val_get(as_input, "ERI_GPW%GROUP_SIZE", i_val=group_size)
    1058          110 :          active_space_env%eri%eri_gpw%group_size = group_size
    1059              :          ! Always redo Poisson solver for now
    1060          110 :          active_space_env%eri%eri_gpw%redo_poisson = .TRUE.
    1061              :          ! active_space_env%eri%eri_gpw%redo_poisson = (ex_operator .OR. ex_perd)
    1062          110 :          IF (iw > 0) THEN
    1063           55 :             WRITE (iw, '(/,T2,A,T71,F10.1)') "ERI_GPW| Energy cutoff [Ry]", eri_gpw_cutoff
    1064           55 :             WRITE (iw, '(T2,A,T71,F10.1)') "ERI_GPW| Relative energy cutoff [Ry]", eri_rel_cutoff
    1065              :          END IF
    1066              :          !
    1067              :          CALL calculate_eri_gpw(active_space_env%mos_active, active_space_env%active_orbitals, active_space_env%eri, qs_env, iw, &
    1068          110 :                                 dft_control%roks)
    1069              :          !
    1070              :       CASE DEFAULT
    1071          110 :          CPABORT("Unknown ERI method")
    1072              :       END SELECT
    1073          110 :       IF (iw > 0) THEN
    1074          124 :          DO isp = 1, SIZE(active_space_env%eri%eri)
    1075           69 :             eri_mat => active_space_env%eri%eri(isp)%csr_mat
    1076              :             nze_percentage = 100.0_dp*(REAL(eri_mat%nze_total, KIND=dp) &
    1077           69 :                                        /REAL(eri_mat%nrows_total, KIND=dp))/REAL(eri_mat%ncols_total, KIND=dp)
    1078           69 :             WRITE (iw, '(/,T2,A,I2,T30,A,T68,I12)') "ERI_GPW| Spinmatrix:", isp, &
    1079          138 :                "Number of  CSR non-zero elements:", eri_mat%nze_total
    1080           69 :             WRITE (iw, '(T2,A,I2,T30,A,T68,F12.4)') "ERI_GPW| Spinmatrix:", isp, &
    1081          138 :                "Percentage CSR non-zero elements:", nze_percentage
    1082           69 :             WRITE (iw, '(T2,A,I2,T30,A,T68,I12)') "ERI_GPW| Spinmatrix:", isp, &
    1083          138 :                "nrows_total", eri_mat%nrows_total
    1084           69 :             WRITE (iw, '(T2,A,I2,T30,A,T68,I12)') "ERI_GPW| Spinmatrix:", isp, &
    1085          138 :                "ncols_total", eri_mat%ncols_total
    1086           69 :             WRITE (iw, '(T2,A,I2,T30,A,T68,I12)') "ERI_GPW| Spinmatrix:", isp, &
    1087          193 :                "nrows_local", eri_mat%nrows_local
    1088              :          END DO
    1089           55 :          CALL m_flush(iw)
    1090              :       END IF
    1091          110 :       CALL para_env%sync()
    1092              : 
    1093              :       ! set the reference active space density matrix
    1094          110 :       nspins = active_space_env%nspins
    1095          460 :       ALLOCATE (active_space_env%p_active(nspins))
    1096          240 :       DO isp = 1, nspins
    1097          130 :          mo_set => active_space_env%mos_active(isp)
    1098          130 :          CALL get_mo_set(mo_set, mo_coeff=mo_coeff, nmo=nmo)
    1099          240 :          CALL create_subspace_matrix(mo_coeff, active_space_env%p_active(isp), nmo)
    1100              :       END DO
    1101            0 :       SELECT CASE (mselect)
    1102              :       CASE DEFAULT
    1103            0 :          CPABORT("Unknown orbital selection method")
    1104              :       CASE (casci_canonical, manual_selection)
    1105          110 :          focc = 2.0_dp
    1106          110 :          IF (nspins == 2) focc = 1.0_dp
    1107          240 :          DO isp = 1, nspins
    1108          130 :             fmat => active_space_env%p_active(isp)
    1109          130 :             CALL cp_fm_set_all(fmat, alpha=0.0_dp)
    1110          130 :             IF (nspins == 2) THEN
    1111           40 :                IF (isp == 1) THEN
    1112           20 :                   nel = (active_space_env%nelec_active + active_space_env%multiplicity - 1)/2
    1113              :                ELSE
    1114           20 :                   nel = (active_space_env%nelec_active - active_space_env%multiplicity + 1)/2
    1115              :                END IF
    1116              :             ELSE
    1117           90 :                nel = active_space_env%nelec_active
    1118              :             END IF
    1119          634 :             DO i = 1, nmo_active
    1120          394 :                m = active_space_env%active_orbitals(i, isp)
    1121          394 :                fel = MIN(focc, REAL(nel, KIND=dp))
    1122          394 :                CALL cp_fm_set_element(fmat, m, m, fel)
    1123          394 :                nel = nel - NINT(fel)
    1124          524 :                nel = MAX(nel, 0)
    1125              :             END DO
    1126              :          END DO
    1127              :       CASE (wannier_projection)
    1128            0 :          CPABORT("NOT IMPLEMENTED")
    1129              :       CASE (mao_projection)
    1130          110 :          CPABORT("NOT IMPLEMENTED")
    1131              :       END SELECT
    1132              : 
    1133              :       ! compute alpha-beta overlap matrix in case of spin-polarized calculation
    1134          110 :       CALL calculate_spin_pol_overlap(active_space_env%mos_active, qs_env, active_space_env)
    1135              : 
    1136              :       ! figure out if we have a new xc section for the AS
    1137          110 :       xc_section => section_vals_get_subs_vals(input, "DFT%ACTIVE_SPACE%XC")
    1138          110 :       explicit = .FALSE.
    1139          110 :       IF (ASSOCIATED(xc_section)) CALL section_vals_get(xc_section, explicit=explicit)
    1140              : 
    1141              :       ! rebuild KS matrix if needed
    1142          110 :       IF (explicit) THEN
    1143              :          ! release the hfx data if it was part of the SCF functional
    1144            2 :          IF (ASSOCIATED(qs_env%x_data)) CALL hfx_release(qs_env%x_data)
    1145              :          ! also release the admm environment in case we are using admm
    1146            2 :          IF (ASSOCIATED(qs_env%admm_env)) CALL admm_env_release(qs_env%admm_env)
    1147              : 
    1148              :          CALL get_qs_env(qs_env, atomic_kind_set=atomic_kind_set, qs_kind_set=qs_kind_set, &
    1149            2 :                          particle_set=particle_set, cell=cell, ks_env=ks_env)
    1150            2 :          IF (dft_control%do_admm) THEN
    1151            0 :             basis_type = 'AUX_FIT'
    1152              :          ELSE
    1153            2 :             basis_type = 'ORB'
    1154              :          END IF
    1155            2 :          hfx_section => section_vals_get_subs_vals(xc_section, "HF")
    1156              :          CALL hfx_create(qs_env%x_data, para_env, hfx_section, atomic_kind_set, &
    1157              :                          qs_kind_set, particle_set, dft_control, cell, orb_basis=basis_type, &
    1158            2 :                          nelectron_total=nelec_total)
    1159              : 
    1160            2 :          qs_env%requires_matrix_vxc = .TRUE.  ! needs to be set only once
    1161              : 
    1162              :          ! a bit of a hack: this forces a new re-init of HFX
    1163            2 :          CALL set_ks_env(ks_env, s_mstruct_changed=.TRUE.)
    1164              :          CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., &
    1165              :                                            just_energy=.FALSE., &
    1166            2 :                                            ext_xc_section=xc_section)
    1167              :          ! we need to reset it to false
    1168            2 :          CALL set_ks_env(ks_env, s_mstruct_changed=.FALSE.)
    1169              :       ELSE
    1170          108 :          xc_section => section_vals_get_subs_vals(input, "DFT%XC")
    1171              :       END IF
    1172              :       ! set the xc_section
    1173          110 :       active_space_env%xc_section => xc_section
    1174              : 
    1175          110 :       CALL get_qs_env(qs_env, energy=energy)
    1176              :       ! transform KS/Fock, Vxc and Hcore to AS MO basis
    1177          110 :       CALL calculate_operators(active_space_env%mos_active, qs_env, active_space_env)
    1178              :       ! set the reference energy in the active space
    1179          110 :       active_space_env%energy_ref = energy%total
    1180              :       ! calculate inactive energy and embedding potential
    1181          110 :       CALL subspace_fock_matrix(active_space_env, dft_control%roks)
    1182              : 
    1183              :       ! associate the active space environment with the qs environment
    1184          110 :       CALL set_qs_env(qs_env, active_space=active_space_env)
    1185              : 
    1186              :       ! Perform the embedding calculation when an active-space solver is specified
    1187          110 :       CALL section_vals_val_get(as_input, "AS_SOLVER", i_val=as_solver)
    1188          104 :       SELECT CASE (as_solver)
    1189              :       CASE (no_solver)
    1190          104 :          IF (iw > 0) THEN
    1191           52 :             WRITE (iw, '(/,T3,A)') "No active space solver specified, skipping embedding calculation"
    1192           52 :             CALL m_flush(iw)
    1193              :          END IF
    1194          104 :          CALL para_env%sync()
    1195              :       CASE (qiskit_solver)
    1196            0 :          CALL rsdft_embedding(qs_env, active_space_env, as_input)
    1197            0 :          CALL qs_scf_compute_properties(qs_env, wf_type="MC-DFT", do_mp2=.FALSE.)
    1198              :       CASE (fci_solver)
    1199            6 :          CALL local_fci_embedding(qs_env, active_space_env, as_input)
    1200            6 :          CALL qs_scf_compute_properties(qs_env, wf_type="MC-DFT", do_mp2=.FALSE.)
    1201              :       CASE DEFAULT
    1202          110 :          CPABORT("Unknown active space solver")
    1203              :       END SELECT
    1204              : 
    1205              :       ! Output a FCIDUMP file if requested
    1206          110 :       IF (active_space_env%fcidump) THEN
    1207              :          CALL fcidump(active_space_env, as_input, dft_control%roks, &
    1208          208 :                       dft_control%roks .AND. mselect == casci_canonical .AND. as_solver == no_solver)
    1209              :       END IF
    1210              : 
    1211              :       ! Output the inactive and active orbitals in FCIDUMP order as a Molden file if requested
    1212          110 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, as_input, "MOLDEN"), cp_p_file)) THEN
    1213            2 :          CALL write_active_space_molden(qs_env, active_space_env, as_input)
    1214              :       END IF
    1215              : 
    1216              :       ! Output a QCSchema file if requested
    1217          110 :       IF (active_space_env%qcschema) THEN
    1218            6 :          CALL qcschema_env_create(qcschema_env, qs_env)
    1219            6 :          IF (para_env%is_source()) THEN
    1220            3 :             CALL qcschema_to_hdf5(qcschema_env, active_space_env%qcschema_filename)
    1221              :          END IF
    1222            6 :          CALL qcschema_env_release(qcschema_env)
    1223              :       END IF
    1224              : 
    1225          110 :       IF (iw > 0) THEN
    1226              :          WRITE (iw, '(/,T2,A)') &
    1227           55 :             '!-------------------- End of Active Space Interface --------------------------!'
    1228           55 :          CALL m_flush(iw)
    1229              :       END IF
    1230          110 :       CALL para_env%sync()
    1231              : 
    1232          110 :       CALL timestop(handle)
    1233              : 
    1234       117526 :    END SUBROUTINE active_space_main
    1235              : 
    1236              : ! **************************************************************************************************
    1237              : !> \brief Makes sure that the SCF orbitals used for the orbital selection are canonical. Orbitals
    1238              : !>        of a diagonalization SCF are left unchanged; non-canonical orbitals (OT) are rotated in
    1239              : !>        place once, separately within the occupied and the virtual orbitals (determinant
    1240              : !>        unchanged), together with the DBCSR copy and the OT orbital derivatives, so that later
    1241              : !>        users of the SCF orbitals see the same orbitals. The orbitals are left untouched for
    1242              : !>        k-points and ROKS (diagonalization only) and for orbitals localized on the fly in OT
    1243              : !>        (ON_THE_FLY_LOC), where MANUAL indices refer to the localized orbitals.
    1244              : !> \param qs_env the QS environment
    1245              : !> \param mo_set the SCF orbitals of one spin
    1246              : !> \param ks_matrix Kohn-Sham or Fock matrix of that spin
    1247              : !> \param ispin spin index
    1248              : !> \param manual MANUAL orbital selection (else CANONICAL)
    1249              : !> \param do_kpoints k-point calculation
    1250              : !> \param iw output unit (> 0 on the I/O node)
    1251              : ! **************************************************************************************************
    1252          130 :    SUBROUTINE ensure_canonical_orbitals(qs_env, mo_set, ks_matrix, ispin, manual, do_kpoints, iw)
    1253              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1254              :       TYPE(mo_set_type), INTENT(INOUT)                   :: mo_set
    1255              :       TYPE(dbcsr_type), POINTER                          :: ks_matrix
    1256              :       INTEGER, INTENT(IN)                                :: ispin
    1257              :       LOGICAL, INTENT(IN)                                :: manual, do_kpoints
    1258              :       INTEGER, INTENT(IN)                                :: iw
    1259              : 
    1260              :       LOGICAL                                            :: on_the_fly_loc, rotated
    1261              :       REAL(KIND=dp)                                      :: eps_canonical, max_offdiag
    1262          130 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: energies
    1263          130 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: mo_derivs
    1264              :       TYPE(dbcsr_type), POINTER                          :: mo_deriv
    1265              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1266              :       TYPE(scf_control_type), POINTER                    :: scf_control
    1267              :       TYPE(section_vals_type), POINTER                   :: input
    1268              : 
    1269              :       ! k-point SCF and ROKS use diagonalization; ROKS orbitals are canonical with respect to the
    1270              :       ! ROKS Fock matrix and not to the spin Fock matrices, so the test below does not apply
    1271          120 :       IF (do_kpoints) RETURN
    1272          128 :       NULLIFY (dft_control, input, mo_derivs, mo_deriv, scf_control)
    1273              :       CALL get_qs_env(qs_env, dft_control=dft_control, scf_control=scf_control, input=input, &
    1274          128 :                       mo_derivs=mo_derivs)
    1275          128 :       IF (dft_control%roks) RETURN
    1276              : 
    1277              :       ! a converged diagonalization SCF leaves off-diagonal elements of the order of EPS_SCF
    1278          116 :       eps_canonical = MAX(1.0E-4_dp, 100.0_dp*scf_control%eps_scf)
    1279          116 :       IF (mo_set%use_mo_coeff_b) CALL copy_dbcsr_to_fm(mo_set%mo_coeff_b, mo_set%mo_coeff)
    1280          348 :       ALLOCATE (energies(mo_set%nmo))
    1281          116 :       CALL calculate_orbital_fock_elements(mo_set%mo_coeff, ks_matrix, energies, max_offdiag)
    1282          116 :       DEALLOCATE (energies)
    1283          116 :       IF (max_offdiag <= eps_canonical) THEN
    1284          156 :          IF (iw > 0) WRITE (iw, '(/,T3,A,I0,A,ES9.2,A)') "SCF orbitals of spin ", ispin, &
    1285          104 :             " are canonical (max |<i|F|j>| = ", max_offdiag, ")"
    1286          104 :          RETURN
    1287              :       END IF
    1288              : 
    1289           12 :       on_the_fly_loc = .FALSE.
    1290           12 :       IF (scf_control%use_ot) CALL section_vals_val_get(input, "DFT%SCF%OT%ON_THE_FLY_LOC", l_val=on_the_fly_loc)
    1291           12 :       IF (on_the_fly_loc) THEN
    1292            2 :          IF (.NOT. manual) THEN
    1293              :             CALL cp_abort(__LOCATION__, &
    1294              :                           "ORBITAL_SELECTION CANONICAL needs canonical orbitals, but the "// &
    1295              :                           "SCF orbitals are localized (ON_THE_FLY_LOC). Use ORBITAL_SELECTION MANUAL "// &
    1296            0 :                           "to select localized orbitals, or switch off ON_THE_FLY_LOC.")
    1297              :          END IF
    1298            3 :          IF (iw > 0) WRITE (iw, '(/,T3,A,I0,A)') "SCF orbitals of spin ", ispin, &
    1299            2 :             " are localized (ON_THE_FLY_LOC): ACTIVE_ORBITAL_INDICES refer to the localized orbitals"
    1300            2 :          RETURN
    1301              :       END IF
    1302              : 
    1303           10 :       IF (ASSOCIATED(mo_derivs)) THEN
    1304           10 :          IF (SIZE(mo_derivs) >= ispin) mo_deriv => mo_derivs(ispin)%matrix
    1305              :       END IF
    1306           10 :       CALL make_mo_set_canonical(mo_set, ks_matrix, eps_canonical, rotated, max_offdiag, mo_deriv)
    1307           10 :       IF (iw > 0) THEN
    1308            5 :          WRITE (iw, '(/,T3,A,I0,A,ES9.2,A)') "SCF orbitals of spin ", ispin, &
    1309           10 :             " are not canonical (max |<i|F|j>| = ", max_offdiag, ")"
    1310            5 :          WRITE (iw, '(T3,A)') "Rotated into canonical orbitals, separately for occupied and virtual orbitals"
    1311              :       END IF
    1312              : 
    1313          374 :    END SUBROUTINE ensure_canonical_orbitals
    1314              : 
    1315              : ! **************************************************************************************************
    1316              : !> \brief Preconditioner (FULL_SINGLE_INVERSE) for the OT eigensolver that computes the virtual
    1317              : !>        orbitals not available from the SCF; without it the eigensolver hardly converges.
    1318              : !> \param preconditioner the preconditioner, not associated if no virtual orbitals are needed
    1319              : !> \param mo_set the SCF orbitals of one spin
    1320              : !> \param ks_matrix Kohn-Sham or Fock matrix of that spin
    1321              : !> \param s_matrix overlap matrix
    1322              : !> \param nmo_virtual number of virtual orbitals to compute
    1323              : !> \param para_env ...
    1324              : !> \param blacs_env ...
    1325              : ! **************************************************************************************************
    1326          130 :    SUBROUTINE virtual_orbital_preconditioner(preconditioner, mo_set, ks_matrix, s_matrix, nmo_virtual, &
    1327              :                                              para_env, blacs_env)
    1328              :       TYPE(preconditioner_type), POINTER                 :: preconditioner
    1329              :       TYPE(mo_set_type), INTENT(IN)                      :: mo_set
    1330              :       TYPE(dbcsr_type), POINTER                          :: ks_matrix, s_matrix
    1331              :       INTEGER, INTENT(IN)                                :: nmo_virtual
    1332              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1333              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
    1334              : 
    1335          130 :       NULLIFY (preconditioner)
    1336          130 :       IF (nmo_virtual <= 0) RETURN
    1337           16 :       ALLOCATE (preconditioner)
    1338            4 :       CALL init_preconditioner(preconditioner, para_env=para_env, blacs_env=blacs_env)
    1339              :       CALL make_preconditioner(preconditioner, precon_type=ot_precond_full_single_inverse, &
    1340              :                                solver_type=ot_precond_solver_default, matrix_h=ks_matrix, &
    1341              :                                matrix_s=s_matrix, convert_precond_to_dbcsr=.TRUE., &
    1342            4 :                                mo_set=mo_set, energy_gap=0.2_dp)
    1343              : 
    1344              :    END SUBROUTINE virtual_orbital_preconditioner
    1345              : 
    1346              : ! **************************************************************************************************
    1347              : !> \brief Warns if active and non-active orbitals are degenerate, i.e. if the active space
    1348              : !>        splits a set of degenerate orbitals. The orbitals of such a set are only defined up
    1349              : !>        to rotations within the set, so the active space is not uniquely defined.
    1350              : !> \param active_space_env the active space environment
    1351              : !> \param mos the SCF orbitals with their eigenvalues
    1352              : ! **************************************************************************************************
    1353          110 :    SUBROUTINE check_active_space_degeneracy(active_space_env, mos)
    1354              :       TYPE(active_space_type), POINTER                   :: active_space_env
    1355              :       TYPE(mo_set_type), DIMENSION(:), INTENT(IN)        :: mos
    1356              : 
    1357              :       REAL(KIND=dp), PARAMETER                           :: eps_degenerate = 1.0E-5_dp
    1358              : 
    1359              :       CHARACTER(LEN=200)                                 :: message
    1360              :       INTEGER                                            :: first_active, first_other, ispin, mspin, &
    1361              :                                                             nmo, npairs
    1362          110 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: eigenvalues
    1363              : 
    1364          240 :       DO ispin = 1, SIZE(active_space_env%active_orbitals, 2)
    1365          130 :          mspin = MIN(ispin, SIZE(mos))
    1366          130 :          CALL get_mo_set(mos(mspin), nmo=nmo, eigenvalues=eigenvalues)
    1367              :          ! no orbital energies available
    1368          130 :          IF (.NOT. ASSOCIATED(eigenvalues)) CYCLE
    1369          138 :          IF (ALL(ABS(eigenvalues(1:nmo)) < EPSILON(1.0_dp))) CYCLE
    1370              :          CALL find_degenerate_splits(eigenvalues(1:nmo), active_space_env%active_orbitals(:, ispin), &
    1371          128 :                                      eps_degenerate, npairs, first_active, first_other)
    1372          368 :          IF (npairs > 0) THEN
    1373              :             WRITE (message, '(A,I0,A,I0,A,I0,A,I0,A)') &
    1374            0 :                "The active space splits a set of degenerate orbitals: active orbital ", first_active, &
    1375            0 :                " and inactive/virtual orbital ", first_other, " (spin ", ispin, ", ", npairs, &
    1376            0 :                " degenerate pairs in total)."
    1377            0 :             CPWARN(TRIM(message))
    1378              :          END IF
    1379              :       END DO
    1380              : 
    1381          110 :    END SUBROUTINE check_active_space_degeneracy
    1382              : 
    1383              : ! **************************************************************************************************
    1384              : !> \brief Writes the orbitals of the active space Hamiltonian to a Molden file: the inactive
    1385              : !>        orbitals first, then the active orbitals in the order of the active orbital list,
    1386              : !>        i.e. the orbital order of the FCIDUMP file.
    1387              : !> \param qs_env the QS environment
    1388              : !> \param active_space_env the active space environment
    1389              : !> \param as_input the ACTIVE_SPACE input section
    1390              : ! **************************************************************************************************
    1391            2 :    SUBROUTINE write_active_space_molden(qs_env, active_space_env, as_input)
    1392              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1393              :       TYPE(active_space_type), POINTER                   :: active_space_env
    1394              :       TYPE(section_vals_type), POINTER                   :: as_input
    1395              : 
    1396              :       INTEGER                                            :: i, iorb, ispin, m, nao, nmo_active, &
    1397              :                                                             nmo_inactive, nmo_out, nspins
    1398              :       REAL(KIND=dp)                                      :: maxocc
    1399              :       TYPE(cell_type), POINTER                           :: cell
    1400              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    1401              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff_active, mo_coeff_inactive
    1402            2 :       TYPE(mo_set_type), ALLOCATABLE, DIMENSION(:)       :: mos_out
    1403            2 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1404            2 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1405              :       TYPE(section_vals_type), POINTER                   :: molden_section
    1406              : 
    1407            2 :       NULLIFY (cell, fm_struct, mo_coeff_active, mo_coeff_inactive, particle_set, qs_kind_set)
    1408            2 :       CALL get_qs_env(qs_env, cell=cell, particle_set=particle_set, qs_kind_set=qs_kind_set)
    1409            2 :       molden_section => section_vals_get_subs_vals(as_input, "MOLDEN")
    1410              : 
    1411            2 :       nspins = SIZE(active_space_env%mos_active)
    1412            2 :       nmo_active = SIZE(active_space_env%active_orbitals, 1)
    1413            2 :       nmo_inactive = SIZE(active_space_env%inactive_orbitals, 1)
    1414            2 :       nmo_out = nmo_inactive + nmo_active
    1415            8 :       ALLOCATE (mos_out(nspins))
    1416            4 :       DO ispin = 1, nspins
    1417              :          CALL get_mo_set(active_space_env%mos_active(ispin), nao=nao, maxocc=maxocc, &
    1418            2 :                          mo_coeff=mo_coeff_active)
    1419            2 :          CALL get_mo_set(active_space_env%mos_inactive(ispin), mo_coeff=mo_coeff_inactive)
    1420            2 :          CALL allocate_mo_set(mos_out(ispin), nao, nmo_out, 0, 0.0_dp, maxocc, 0.0_dp)
    1421              :          CALL cp_fm_struct_create(fm_struct, nrow_global=nao, ncol_global=nmo_out, &
    1422            2 :                                   template_fmstruct=mo_coeff_active%matrix_struct)
    1423            2 :          CALL init_mo_set(mos_out(ispin), fm_struct=fm_struct, name="active space orbitals")
    1424            2 :          CALL cp_fm_struct_release(fm_struct)
    1425              :          ! the MO sets of the active space store each orbital in the column of its MO index
    1426            6 :          DO i = 1, nmo_inactive
    1427            4 :             m = active_space_env%inactive_orbitals(i, ispin)
    1428            4 :             CALL cp_fm_to_fm(mo_coeff_inactive, mos_out(ispin)%mo_coeff, 1, m, i)
    1429            4 :             mos_out(ispin)%eigenvalues(i) = active_space_env%mos_inactive(ispin)%eigenvalues(m)
    1430            6 :             mos_out(ispin)%occupation_numbers(i) = active_space_env%mos_inactive(ispin)%occupation_numbers(m)
    1431              :          END DO
    1432           18 :          DO i = 1, nmo_active
    1433           12 :             m = active_space_env%active_orbitals(i, ispin)
    1434           12 :             iorb = nmo_inactive + i
    1435           12 :             CALL cp_fm_to_fm(mo_coeff_active, mos_out(ispin)%mo_coeff, 1, m, iorb)
    1436           12 :             mos_out(ispin)%eigenvalues(iorb) = active_space_env%mos_active(ispin)%eigenvalues(m)
    1437           14 :             mos_out(ispin)%occupation_numbers(iorb) = active_space_env%mos_active(ispin)%occupation_numbers(m)
    1438              :          END DO
    1439              :       END DO
    1440              : 
    1441            2 :       CALL write_mos_molden(mos_out, qs_kind_set, particle_set, molden_section, cell=cell)
    1442              : 
    1443            4 :       DO ispin = 1, nspins
    1444            4 :          CALL deallocate_mo_set(mos_out(ispin))
    1445              :       END DO
    1446            2 :       DEALLOCATE (mos_out)
    1447              : 
    1448            2 :    END SUBROUTINE write_active_space_molden
    1449              : 
    1450              : ! **************************************************************************************************
    1451              : !> \brief computes the alpha-beta overlap within the active subspace
    1452              : !> \param mos the molecular orbital set within the active subspace
    1453              : !> \param qs_env ...
    1454              : !> \param active_space_env ...
    1455              : !> \par History
    1456              : !>      04.2016 created [JGH]
    1457              : ! **************************************************************************************************
    1458          110 :    SUBROUTINE calculate_spin_pol_overlap(mos, qs_env, active_space_env)
    1459              : 
    1460              :       TYPE(mo_set_type), DIMENSION(:), INTENT(IN)        :: mos
    1461              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1462              :       TYPE(active_space_type), POINTER                   :: active_space_env
    1463              : 
    1464              :       CHARACTER(len=*), PARAMETER :: routineN = 'calculate_spin_pol_overlap'
    1465              : 
    1466              :       INTEGER                                            :: handle, nmo, nspins
    1467              :       LOGICAL                                            :: do_kpoints
    1468              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff_a, mo_coeff_b
    1469          110 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: s_matrix
    1470          110 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: s_matrix_kp
    1471              : 
    1472          110 :       CALL timeset(routineN, handle)
    1473              : 
    1474          110 :       nspins = active_space_env%nspins
    1475              : 
    1476              :       ! overlap in AO
    1477          110 :       IF (nspins > 1) THEN
    1478           20 :          CALL get_qs_env(qs_env, do_kpoints=do_kpoints)
    1479           20 :          IF (do_kpoints) THEN
    1480            0 :             CALL get_qs_env(qs_env, matrix_s_kp=s_matrix_kp)
    1481            0 :             s_matrix => s_matrix_kp(:, 1)
    1482              :          ELSE
    1483           20 :             CALL get_qs_env(qs_env, matrix_s=s_matrix)
    1484              :          END IF
    1485           40 :          ALLOCATE (active_space_env%sab_sub(1))
    1486              : 
    1487           20 :          CALL get_mo_set(mo_set=mos(1), mo_coeff=mo_coeff_a, nmo=nmo)
    1488           20 :          CALL get_mo_set(mo_set=mos(2), mo_coeff=mo_coeff_b, nmo=nmo)
    1489           20 :          CALL subspace_operator(mo_coeff_a, nmo, s_matrix(1)%matrix, active_space_env%sab_sub(1), mo_coeff_b)
    1490              :       END IF
    1491              : 
    1492          110 :       CALL timestop(handle)
    1493              : 
    1494          110 :    END SUBROUTINE calculate_spin_pol_overlap
    1495              : 
    1496              : ! **************************************************************************************************
    1497              : !> \brief computes the one-electron operators in the subspace of the provided orbital set
    1498              : !> \param mos the molecular orbital set within the active subspace
    1499              : !> \param qs_env ...
    1500              : !> \param active_space_env ...
    1501              : !> \par History
    1502              : !>      04.2016 created [JGH]
    1503              : ! **************************************************************************************************
    1504          132 :    SUBROUTINE calculate_operators(mos, qs_env, active_space_env)
    1505              : 
    1506              :       TYPE(mo_set_type), DIMENSION(:), INTENT(IN)        :: mos
    1507              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1508              :       TYPE(active_space_type), POINTER                   :: active_space_env
    1509              : 
    1510              :       CHARACTER(len=*), PARAMETER :: routineN = 'calculate_operators'
    1511              : 
    1512              :       INTEGER                                            :: handle, ispin, nmo, nspins
    1513              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1514          132 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: h_matrix, ks_matrix
    1515              : 
    1516          132 :       CALL timeset(routineN, handle)
    1517              : 
    1518          132 :       nspins = active_space_env%nspins
    1519              : 
    1520              :       ! Kohn-Sham / Fock operator
    1521          132 :       CALL cp_fm_release(active_space_env%ks_sub)
    1522          132 :       CALL get_qs_env(qs_env, matrix_ks_kp=ks_matrix)
    1523          562 :       ALLOCATE (active_space_env%ks_sub(nspins))
    1524          298 :       DO ispin = 1, nspins
    1525          166 :          CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, nmo=nmo)
    1526          298 :          CALL subspace_operator(mo_coeff, nmo, ks_matrix(ispin, 1)%matrix, active_space_env%ks_sub(ispin))
    1527              :       END DO
    1528              : 
    1529              :       ! Core Hamiltonian
    1530          132 :       CALL cp_fm_release(active_space_env%h_sub)
    1531              : 
    1532          132 :       NULLIFY (h_matrix)
    1533          132 :       CALL get_qs_env(qs_env=qs_env, matrix_h_kp=h_matrix)
    1534          430 :       ALLOCATE (active_space_env%h_sub(nspins))
    1535          298 :       DO ispin = 1, nspins
    1536          166 :          CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, nmo=nmo)
    1537          298 :          CALL subspace_operator(mo_coeff, nmo, h_matrix(1, 1)%matrix, active_space_env%h_sub(ispin))
    1538              :       END DO
    1539              : 
    1540          132 :       CALL timestop(handle)
    1541              : 
    1542          132 :    END SUBROUTINE calculate_operators
    1543              : 
    1544              : ! **************************************************************************************************
    1545              : !> \brief computes a one-electron operator in the subspace of the provided orbital set
    1546              : !> \param mo_coeff the orbital coefficient matrix
    1547              : !> \param nmo the number of subspace orbitals
    1548              : !> \param op_matrix operator matrix in AO basis
    1549              : !> \param op_sub operator in orbital basis
    1550              : !> \param mo_coeff_b the beta orbital coefficients
    1551              : !> \par History
    1552              : !>      04.2016 created [JGH]
    1553              : ! **************************************************************************************************
    1554          704 :    SUBROUTINE subspace_operator(mo_coeff, nmo, op_matrix, op_sub, mo_coeff_b)
    1555              : 
    1556              :       TYPE(cp_fm_type), INTENT(IN)                       :: mo_coeff
    1557              :       INTEGER, INTENT(IN)                                :: nmo
    1558              :       TYPE(dbcsr_type), POINTER                          :: op_matrix
    1559              :       TYPE(cp_fm_type), INTENT(INOUT)                    :: op_sub
    1560              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: mo_coeff_b
    1561              : 
    1562              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'subspace_operator'
    1563              : 
    1564              :       INTEGER                                            :: handle, ncol, nrow
    1565              :       TYPE(cp_fm_type)                                   :: vectors
    1566              : 
    1567          352 :       CALL timeset(routineN, handle)
    1568              : 
    1569          352 :       CALL cp_fm_get_info(matrix=mo_coeff, ncol_global=ncol, nrow_global=nrow)
    1570          352 :       CPASSERT(nmo <= ncol)
    1571              : 
    1572          352 :       IF (nmo > 0) THEN
    1573          352 :          CALL cp_fm_create(vectors, mo_coeff%matrix_struct, "vectors")
    1574          352 :          CALL create_subspace_matrix(mo_coeff, op_sub, nmo)
    1575              : 
    1576          352 :          IF (PRESENT(mo_coeff_b)) THEN
    1577              :             ! if beta orbitals are present, compute the cross alpha_beta term
    1578           20 :             CALL cp_dbcsr_sm_fm_multiply(op_matrix, mo_coeff_b, vectors, nmo)
    1579              :          ELSE
    1580              :             ! otherwise the same spin, whatever that is
    1581          332 :             CALL cp_dbcsr_sm_fm_multiply(op_matrix, mo_coeff, vectors, nmo)
    1582              :          END IF
    1583              : 
    1584          352 :          CALL parallel_gemm('T', 'N', nmo, nmo, nrow, 1.0_dp, mo_coeff, vectors, 0.0_dp, op_sub)
    1585          352 :          CALL cp_fm_release(vectors)
    1586              :       END IF
    1587              : 
    1588          352 :       CALL timestop(handle)
    1589              : 
    1590          352 :    END SUBROUTINE subspace_operator
    1591              : 
    1592              : ! **************************************************************************************************
    1593              : !> \brief creates a matrix of subspace size
    1594              : !> \param orbitals the orbital coefficient matrix
    1595              : !> \param op_sub operator in orbital basis
    1596              : !> \param n the number of orbitals
    1597              : !> \par History
    1598              : !>      04.2016 created [JGH]
    1599              : ! **************************************************************************************************
    1600          482 :    SUBROUTINE create_subspace_matrix(orbitals, op_sub, n)
    1601              : 
    1602              :       TYPE(cp_fm_type), INTENT(IN)                       :: orbitals
    1603              :       TYPE(cp_fm_type), INTENT(OUT)                      :: op_sub
    1604              :       INTEGER, INTENT(IN)                                :: n
    1605              : 
    1606              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    1607              : 
    1608          482 :       IF (n > 0) THEN
    1609              : 
    1610          482 :          NULLIFY (fm_struct)
    1611              :          CALL cp_fm_struct_create(fm_struct, nrow_global=n, ncol_global=n, &
    1612              :                                   para_env=orbitals%matrix_struct%para_env, &
    1613          482 :                                   context=orbitals%matrix_struct%context)
    1614          482 :          CALL cp_fm_create(op_sub, fm_struct, name="Subspace operator")
    1615          482 :          CALL cp_fm_struct_release(fm_struct)
    1616              : 
    1617              :       END IF
    1618              : 
    1619          482 :    END SUBROUTINE create_subspace_matrix
    1620              : 
    1621              : ! **************************************************************************************************
    1622              : !> \brief computes the electron repulsion integrals using the GPW technology
    1623              : !> \param mos the molecular orbital set within the active subspace
    1624              : !> \param orbitals ...
    1625              : !> \param eri_env ...
    1626              : !> \param qs_env ...
    1627              : !> \param iw ...
    1628              : !> \param restricted ...
    1629              : !> \par History
    1630              : !>      04.2016 created [JGH]
    1631              : ! **************************************************************************************************
    1632          110 :    SUBROUTINE calculate_eri_gpw(mos, orbitals, eri_env, qs_env, iw, restricted)
    1633              : 
    1634              :       TYPE(mo_set_type), DIMENSION(:), INTENT(IN)        :: mos
    1635              :       INTEGER, DIMENSION(:, :), POINTER                  :: orbitals
    1636              :       TYPE(eri_type)                                     :: eri_env
    1637              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1638              :       INTEGER, INTENT(IN)                                :: iw
    1639              :       LOGICAL, INTENT(IN)                                :: restricted
    1640              : 
    1641              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'calculate_eri_gpw'
    1642              : 
    1643              :       INTEGER :: col_local, color, handle, i1, i2, i3, i4, i_multigrid, icount2, intcount, isp, &
    1644              :          isp1, isp2, ispin, iwa1, iwa12, iwa2, iwb1, iwb12, iwb2, iwbs, iwbt, iwfn, n_multigrid, &
    1645              :          ncol_global, ncol_local, nmm, nmo, nmo1, nmo2, nrow_global, nrow_local, nspins, &
    1646              :          number_of_subgroups, nx, row_local, stored_integrals
    1647          110 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: eri_index
    1648          110 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1649              :       LOGICAL                                            :: print1, print2, &
    1650              :                                                             skip_load_balance_distributed
    1651              :       REAL(KIND=dp)                                      :: dvol, erint, pair_int, &
    1652              :                                                             progression_factor, rc, rsize, t1, t2
    1653          110 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eri
    1654          110 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1655              :       TYPE(cell_type), POINTER                           :: cell
    1656              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env, blacs_env_sub
    1657              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    1658          110 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: fm_matrix_pq_rnu, fm_matrix_pq_rs, &
    1659          110 :                                                             fm_mo_coeff_as
    1660              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1661              :       TYPE(dbcsr_p_type)                                 :: mat_munu
    1662          110 :       TYPE(dbcsr_type), ALLOCATABLE, DIMENSION(:)        :: matrix_pq_rnu, mo_coeff_as
    1663              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1664              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1665              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1666          110 :          POINTER                                         :: sab_orb_sub
    1667          110 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1668              :       TYPE(pw_c1d_gs_type)                               :: pot_g, rho_g
    1669              :       TYPE(pw_env_type), POINTER                         :: pw_env_sub
    1670              :       TYPE(pw_poisson_type), POINTER                     :: poisson_env
    1671              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    1672              :       TYPE(pw_r3d_rs_type)                               :: rho_r, wfn_r
    1673              :       TYPE(pw_r3d_rs_type), ALLOCATABLE, &
    1674          110 :          DIMENSION(:, :), TARGET                         :: wfn_a
    1675              :       TYPE(pw_r3d_rs_type), POINTER                      :: wfn1, wfn2, wfn3, wfn4
    1676              :       TYPE(qs_control_type), POINTER                     :: qs_control, qs_control_old
    1677          110 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1678              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    1679              :       TYPE(task_list_type), POINTER                      :: task_list_sub
    1680              : 
    1681          110 :       CALL timeset(routineN, handle)
    1682              : 
    1683          110 :       IF (iw > 0) t1 = m_walltime()
    1684              : 
    1685              :       ! print levels
    1686          208 :       SELECT CASE (eri_env%eri_gpw%print_level)
    1687              :       CASE (silent_print_level)
    1688           98 :          print1 = .FALSE.
    1689           98 :          print2 = .FALSE.
    1690              :       CASE (low_print_level)
    1691            6 :          print1 = .FALSE.
    1692            6 :          print2 = .FALSE.
    1693              :       CASE (medium_print_level)
    1694            6 :          print1 = .TRUE.
    1695            6 :          print2 = .FALSE.
    1696              :       CASE (high_print_level)
    1697            0 :          print1 = .TRUE.
    1698            0 :          print2 = .TRUE.
    1699              :       CASE (debug_print_level)
    1700            0 :          print1 = .TRUE.
    1701          110 :          print2 = .TRUE.
    1702              :       CASE DEFAULT
    1703              :          ! do nothing
    1704              :       END SELECT
    1705              : 
    1706              :       ! Check the input group
    1707          110 :       CALL get_qs_env(qs_env, para_env=para_env, blacs_env=blacs_env)
    1708          110 :       IF (eri_env%eri_gpw%group_size < 1) eri_env%eri_gpw%group_size = para_env%num_pe
    1709          110 :       IF (MOD(para_env%num_pe, eri_env%eri_gpw%group_size) /= 0) THEN
    1710            0 :          CPABORT("Group size must be a divisor of the total number of processes!")
    1711              :       END IF
    1712              :       ! Create a new para_env or reuse the old one
    1713          110 :       IF (eri_env%eri_gpw%group_size == para_env%num_pe) THEN
    1714          104 :          eri_env%para_env_sub => para_env
    1715          104 :          CALL eri_env%para_env_sub%retain()
    1716          104 :          blacs_env_sub => blacs_env
    1717          104 :          CALL blacs_env_sub%retain()
    1718          104 :          number_of_subgroups = 1
    1719          104 :          color = 0
    1720              :       ELSE
    1721            6 :          number_of_subgroups = para_env%num_pe/eri_env%eri_gpw%group_size
    1722            6 :          color = para_env%mepos/eri_env%eri_gpw%group_size
    1723            6 :          ALLOCATE (eri_env%para_env_sub)
    1724            6 :          CALL eri_env%para_env_sub%from_split(para_env, color)
    1725            6 :          NULLIFY (blacs_env_sub)
    1726            6 :          CALL cp_blacs_env_create(blacs_env_sub, eri_env%para_env_sub, BLACS_GRID_SQUARE, .TRUE.)
    1727              :       END IF
    1728          110 :       CALL eri_env%comm_exchange%from_split(para_env, eri_env%para_env_sub%mepos)
    1729              : 
    1730              :       ! This should be done differently! Copied from MP2 code
    1731          110 :       CALL get_qs_env(qs_env, dft_control=dft_control)
    1732          440 :       ALLOCATE (qs_control)
    1733          110 :       qs_control_old => dft_control%qs_control
    1734          110 :       qs_control = qs_control_old
    1735          110 :       dft_control%qs_control => qs_control
    1736          110 :       progression_factor = qs_control%progression_factor
    1737          110 :       n_multigrid = SIZE(qs_control%e_cutoff)
    1738          110 :       nspins = SIZE(mos)
    1739              :       ! In case of ROHF/ROKS, we assume the orbital coefficients in both spin channels to be the same
    1740              :       ! and save operations by calculating ERIs from only one spin channel
    1741          110 :       IF (restricted) nspins = 1
    1742              :       ! Allocate new cutoffs (just in private qs_control, not in qs_control_old)
    1743          330 :       ALLOCATE (qs_control%e_cutoff(n_multigrid))
    1744              : 
    1745          110 :       qs_control%cutoff = eri_env%eri_gpw%cutoff*0.5_dp
    1746          110 :       qs_control%e_cutoff(1) = qs_control%cutoff
    1747          440 :       DO i_multigrid = 2, n_multigrid
    1748              :          qs_control%e_cutoff(i_multigrid) = qs_control%e_cutoff(i_multigrid - 1) &
    1749          440 :                                             /progression_factor
    1750              :       END DO
    1751          110 :       qs_control%relative_cutoff = eri_env%eri_gpw%rel_cutoff*0.5_dp
    1752              : 
    1753              :       ! For now, we will distribute neighbor lists etc. within the global communicator
    1754          110 :       CALL get_qs_env(qs_env, ks_env=ks_env)
    1755              :       CALL create_mat_munu(mat_munu, qs_env, eri_env%eri_gpw%eps_grid, blacs_env_sub, sab_orb_sub=sab_orb_sub, &
    1756          110 :                            do_alloc_blocks_from_nbl=.TRUE., dbcsr_sym_type=dbcsr_type_symmetric)
    1757          110 :       CALL dbcsr_set(mat_munu%matrix, 0.0_dp)
    1758              : 
    1759              :       ! Generate the appropriate pw_env
    1760          110 :       NULLIFY (pw_env_sub)
    1761          110 :       CALL pw_env_create(pw_env_sub)
    1762          110 :       CALL pw_env_rebuild(pw_env_sub, qs_env, external_para_env=eri_env%para_env_sub)
    1763          110 :       CALL pw_env_get(pw_env_sub, auxbas_pw_pool=auxbas_pw_pool, poisson_env=poisson_env)
    1764              : 
    1765              :       ! TODO: maybe we can let `pw_env_rebuild` do what we manually overwrite here?
    1766          110 :       IF (eri_env%eri_gpw%redo_poisson) THEN
    1767              :          ! We need to rebuild the Poisson solver on the fly
    1768          440 :          IF (SUM(eri_env%periodicity) /= 0) THEN
    1769           10 :             poisson_env%parameters%solver = pw_poisson_periodic
    1770              :          ELSE
    1771          100 :             poisson_env%parameters%solver = pw_poisson_analytic
    1772              :          END IF
    1773          440 :          poisson_env%parameters%periodic = eri_env%periodicity
    1774              : 
    1775              :          ! Rebuilds the poisson green (influence) function according
    1776              :          ! to the poisson solver and parameters set so far.
    1777              :          ! Also sets the variable poisson_env%rebuild to .FALSE.
    1778          110 :          CALL pw_poisson_rebuild(poisson_env)
    1779              : 
    1780              :          ! set the cutoff radius for the Greens function in case we use ANALYTIC Poisson solver
    1781          110 :          CALL get_qs_env(qs_env, cell=cell)
    1782          110 :          rc = cell%hmat(1, 1)
    1783          440 :          DO iwa1 = 1, 3
    1784              :             ! TODO: I think this is not the largest possible radius inscribed in the cell
    1785          440 :             rc = MIN(rc, 0.5_dp*cell%hmat(iwa1, iwa1))
    1786              :          END DO
    1787          110 :          poisson_env%green_fft%radius = rc
    1788              : 
    1789              :          ! Overwrite the Greens function with the one we want
    1790          110 :          CALL pw_eri_green_create(poisson_env%green_fft, eri_env)
    1791              : 
    1792          110 :          IF (iw > 0) THEN
    1793           55 :             CALL get_qs_env(qs_env, cell=cell)
    1794          440 :             IF (SUM(cell%perd) /= SUM(eri_env%periodicity)) THEN
    1795            0 :                IF (SUM(eri_env%periodicity) /= 0) THEN
    1796              :                   WRITE (UNIT=iw, FMT="(/,T2,A,T51,A30)") &
    1797            0 :                      "ERI_GPW| Switching Poisson solver to", "PERIODIC"
    1798              :                ELSE
    1799              :                   WRITE (UNIT=iw, FMT="(/,T2,A,T51,A30)") &
    1800            0 :                      "ERI_GPW| Switching Poisson solver to", "ANALYTIC"
    1801              :                END IF
    1802              :             END IF
    1803              :             ! print out the Greens function to check it matches the Poisson solver
    1804           60 :             SELECT CASE (poisson_env%green_fft%method)
    1805              :             CASE (PERIODIC3D)
    1806              :                WRITE (UNIT=iw, FMT="(T2,A,T51,A30)") &
    1807            5 :                   "ERI_GPW| Poisson Greens function", "PERIODIC"
    1808              :             CASE (ANALYTIC0D)
    1809              :                WRITE (UNIT=iw, FMT="(T2,A,T51,A30)") &
    1810           50 :                   "ERI_GPW| Poisson Greens function", "ANALYTIC"
    1811           50 :                WRITE (UNIT=iw, FMT="(T2,A,T71,F10.4)") "ERI_GPW| Poisson cutoff radius", &
    1812          100 :                   poisson_env%green_fft%radius*angstrom
    1813              :             CASE DEFAULT
    1814           55 :                CPABORT("Wrong Greens function setup")
    1815              :             END SELECT
    1816              :          END IF
    1817              :       END IF
    1818              : 
    1819          798 :       ALLOCATE (mo_coeff_as(nspins), fm_mo_coeff_as(nspins))
    1820          234 :       DO ispin = 1, nspins
    1821          372 :          BLOCK
    1822          124 :             REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE :: C, C_active
    1823              :             INTEGER :: nmo
    1824          124 :             TYPE(group_dist_d1_type) :: gd_array
    1825              :             TYPE(cp_fm_type), POINTER :: mo_coeff
    1826          124 :             CALL get_mo_set(mos(ispin), mo_coeff=mo_coeff, nmo=nmo)
    1827          124 :             CALL grep_rows_in_subgroups(para_env, eri_env%para_env_sub, mo_coeff, gd_array, C)
    1828              : 
    1829          496 :             ALLOCATE (C_active(SIZE(C, 1), SIZE(orbitals, 1)))
    1830          498 :             DO i1 = 1, SIZE(orbitals, 1)
    1831         2468 :                C_active(:, i1) = C(:, orbitals(i1, ispin))
    1832              :             END DO
    1833              :             CALL build_dbcsr_from_rows(eri_env%para_env_sub, mo_coeff_as(ispin), &
    1834          124 :                                        C_active, mat_munu%matrix, gd_array, eri_env%eri_gpw%eps_filter)
    1835          124 :             CALL release_group_dist(gd_array)
    1836          496 :             DEALLOCATE (C, C_active)
    1837              :          END BLOCK
    1838              : 
    1839          124 :          CALL dbcsr_get_info(mo_coeff_as(ispin), nfullrows_total=nrow_global, nfullcols_total=ncol_global)
    1840              : 
    1841          124 :          NULLIFY (fm_struct)
    1842              :          CALL cp_fm_struct_create(fm_struct, context=blacs_env_sub, para_env=eri_env%para_env_sub, &
    1843          124 :                                   nrow_global=nrow_global, ncol_global=ncol_global)
    1844          124 :          CALL cp_fm_create(fm_mo_coeff_as(ispin), fm_struct)
    1845          124 :          CALL cp_fm_struct_release(fm_struct)
    1846              : 
    1847          358 :          CALL copy_dbcsr_to_fm(mo_coeff_as(ispin), fm_mo_coeff_as(ispin))
    1848              :       END DO
    1849              : 
    1850          110 :       IF (eri_env%method == eri_method_gpw_ht) THEN
    1851              :          ! We need a task list
    1852           16 :          NULLIFY (task_list_sub)
    1853           16 :          skip_load_balance_distributed = dft_control%qs_control%skip_load_balance_distributed
    1854           16 :          CALL allocate_task_list(task_list_sub)
    1855              :          CALL generate_qs_task_list(ks_env, task_list_sub, basis_type="ORB", &
    1856              :                                     reorder_rs_grid_ranks=.TRUE., &
    1857              :                                     skip_load_balance_distributed=skip_load_balance_distributed, &
    1858           16 :                                     pw_env_external=pw_env_sub, sab_orb_external=sab_orb_sub)
    1859              : 
    1860              :          ! Create sparse matrices carrying the matrix products, Code borrowed from the MP2 GPW method
    1861              :          ! Create equal distributions for them (no sparsity present)
    1862              :          ! We use the routines from mp2 suggesting that one may replicate the grids later for better performance
    1863          112 :          ALLOCATE (matrix_pq_rnu(nspins), fm_matrix_pq_rnu(nspins), fm_matrix_pq_rs(nspins))
    1864           32 :          DO ispin = 1, nspins
    1865           16 :             CALL dbcsr_create(matrix_pq_rnu(ispin), template=mo_coeff_as(ispin))
    1866           16 :             CALL dbcsr_set(matrix_pq_rnu(ispin), 0.0_dp)
    1867              : 
    1868           16 :             CALL dbcsr_get_info(matrix_pq_rnu(ispin), nfullrows_total=nrow_global, nfullcols_total=ncol_global)
    1869              : 
    1870           16 :             NULLIFY (fm_struct)
    1871              :             CALL cp_fm_struct_create(fm_struct, context=blacs_env_sub, para_env=eri_env%para_env_sub, &
    1872           16 :                                      nrow_global=nrow_global, ncol_global=ncol_global)
    1873           16 :             CALL cp_fm_create(fm_matrix_pq_rnu(ispin), fm_struct)
    1874           16 :             CALL cp_fm_struct_release(fm_struct)
    1875              : 
    1876           16 :             NULLIFY (fm_struct)
    1877              :             CALL cp_fm_struct_create(fm_struct, context=blacs_env_sub, para_env=eri_env%para_env_sub, &
    1878           16 :                                      nrow_global=ncol_global, ncol_global=ncol_global)
    1879           16 :             CALL cp_fm_create(fm_matrix_pq_rs(ispin), fm_struct)
    1880           48 :             CALL cp_fm_struct_release(fm_struct)
    1881              :          END DO
    1882              : 
    1883              :          ! Copy the active space of the MOs into DBCSR matrices
    1884              :       END IF
    1885              : 
    1886          110 :       CALL auxbas_pw_pool%create_pw(wfn_r)
    1887          110 :       CALL auxbas_pw_pool%create_pw(rho_g)
    1888              :       CALL get_qs_env(qs_env, qs_kind_set=qs_kind_set, cell=cell, &
    1889          110 :                       particle_set=particle_set, atomic_kind_set=atomic_kind_set)
    1890              : 
    1891              :       ! pre-calculate wavefunctions on reals space grid
    1892          110 :       nspins = SIZE(mos)
    1893              :       ! In case of ROHF/ROKS, we assume the orbital coefficients in both spin channels to be the same
    1894              :       ! and save operations by calculating ERIs from only one spin channel
    1895              :       IF (restricted) nspins = 1
    1896          110 :       IF (eri_env%eri_gpw%store_wfn) THEN
    1897              :          ! pre-calculate wavefunctions on reals space grid
    1898           98 :          rsize = 0.0_dp
    1899           98 :          nmo = 0
    1900          210 :          DO ispin = 1, nspins
    1901          112 :             CALL get_mo_set(mo_set=mos(ispin), nmo=nx)
    1902          112 :             nmo = MAX(nmo, nx)
    1903          546 :             rsize = REAL(SIZE(wfn_r%array), KIND=dp)*nx
    1904              :          END DO
    1905           98 :          IF (print1 .AND. iw > 0) THEN
    1906            3 :             rsize = rsize*8._dp/1000000._dp
    1907            3 :             WRITE (iw, "(T2,'ERI_GPW|',' Store active orbitals on real space grid ',T66,F12.3,' MB')") rsize
    1908              :          END IF
    1909          964 :          ALLOCATE (wfn_a(nmo, nspins))
    1910          210 :          DO ispin = 1, nspins
    1911          112 :             CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, nmo=nmo)
    1912          560 :             DO i1 = 1, SIZE(orbitals, 1)
    1913          350 :                iwfn = orbitals(i1, ispin)
    1914          350 :                CALL auxbas_pw_pool%create_pw(wfn_a(iwfn, ispin))
    1915              :                CALL calculate_wavefunction(mo_coeff, iwfn, wfn_a(iwfn, ispin), rho_g, atomic_kind_set, &
    1916          350 :                                            qs_kind_set, cell, dft_control, particle_set, pw_env_sub)
    1917          462 :                IF (print2 .AND. iw > 0) THEN
    1918            0 :                   WRITE (iw, "(T2,'ERI_GPW|',' Orbital stored ',I4,'  Spin ',i1)") iwfn, ispin
    1919              :                END IF
    1920              :             END DO
    1921              :          END DO
    1922              :       ELSE
    1923              :          ! Even if we do not store all WFNs, we still need containers for the functions to store
    1924           12 :          ALLOCATE (wfn1, wfn2)
    1925           12 :          CALL auxbas_pw_pool%create_pw(wfn1)
    1926           12 :          CALL auxbas_pw_pool%create_pw(wfn2)
    1927           12 :          IF (eri_env%method /= eri_method_gpw_ht) THEN
    1928            6 :             ALLOCATE (wfn3, wfn4)
    1929            6 :             CALL auxbas_pw_pool%create_pw(wfn3)
    1930            6 :             CALL auxbas_pw_pool%create_pw(wfn4)
    1931              :          END IF
    1932              :       END IF
    1933              : 
    1934              :       ! get some of the grids ready
    1935          110 :       CALL auxbas_pw_pool%create_pw(rho_r)
    1936          110 :       CALL auxbas_pw_pool%create_pw(pot_g)
    1937              : 
    1938              :       ! run the FFT once, to set up buffers and to take into account the memory
    1939          110 :       CALL pw_zero(rho_r)
    1940          110 :       CALL pw_transfer(rho_r, rho_g)
    1941          110 :       dvol = rho_r%pw_grid%dvol
    1942              : 
    1943          110 :       IF (iw > 0) THEN
    1944           55 :          CALL m_flush(iw)
    1945              :       END IF
    1946              :       ! calculate the integrals
    1947          110 :       stored_integrals = 0
    1948          234 :       DO isp1 = 1, nspins
    1949          124 :          CALL get_mo_set(mo_set=mos(isp1), nmo=nmo1)
    1950          124 :          nmm = (nmo1*(nmo1 + 1))/2
    1951          608 :          DO i1 = 1, SIZE(orbitals, 1)
    1952          374 :             iwa1 = orbitals(i1, isp1)
    1953          374 :             IF (eri_env%eri_gpw%store_wfn) THEN
    1954          350 :                wfn1 => wfn_a(iwa1, isp1)
    1955              :             ELSE
    1956              :                CALL calculate_wavefunction(fm_mo_coeff_as(isp1), iwa1, wfn1, rho_g, atomic_kind_set, &
    1957           24 :                                            qs_kind_set, cell, dft_control, particle_set, pw_env_sub)
    1958              :             END IF
    1959         1364 :             DO i2 = i1, SIZE(orbitals, 1)
    1960          866 :                iwa2 = orbitals(i2, isp1)
    1961          866 :                iwa12 = csr_idx_to_combined(iwa1, iwa2, nmo1)
    1962              :                ! Skip calculation directly if the pair is not part of our subgroup
    1963          866 :                IF (MOD(iwa12 - 1, eri_env%comm_exchange%num_pe) /= eri_env%comm_exchange%mepos) CYCLE
    1964          857 :                iwa12 = (iwa12 - 1)/eri_env%comm_exchange%num_pe + 1
    1965          857 :                IF (eri_env%eri_gpw%store_wfn) THEN
    1966          827 :                   wfn2 => wfn_a(iwa2, isp1)
    1967              :                ELSE
    1968              :                   CALL calculate_wavefunction(fm_mo_coeff_as(isp1), iwa2, wfn2, rho_g, atomic_kind_set, &
    1969           30 :                                               qs_kind_set, cell, dft_control, particle_set, pw_env_sub)
    1970              :                END IF
    1971              :                ! calculate charge distribution and potential
    1972          857 :                CALL pw_zero(rho_r)
    1973          857 :                CALL pw_multiply(rho_r, wfn1, wfn2)
    1974          857 :                CALL pw_transfer(rho_r, rho_g)
    1975          857 :                CALL pw_poisson_solve(poisson_env, rho_g, pair_int, pot_g)
    1976              : 
    1977              :                ! screening using pair_int
    1978          857 :                IF (pair_int < eri_env%eps_integral) CYCLE
    1979          857 :                CALL pw_transfer(pot_g, rho_r)
    1980              :                !
    1981         2088 :                IF (eri_env%method == eri_method_gpw_ht) THEN
    1982           56 :                   CALL pw_scale(rho_r, dvol)
    1983          112 :                   DO isp2 = isp1, nspins
    1984           56 :                      CALL get_mo_set(mo_set=mos(isp2), nmo=nmo2)
    1985           56 :                      nx = (nmo2*(nmo2 + 1))/2
    1986          280 :                      ALLOCATE (eri(nx), eri_index(nx))
    1987           56 :                      CALL dbcsr_set(mat_munu%matrix, 0.0_dp)
    1988              :                      CALL integrate_v_rspace(rho_r, hmat=mat_munu, qs_env=qs_env, &
    1989              :                                              calculate_forces=.FALSE., compute_tau=.FALSE., gapw=.FALSE., &
    1990           56 :                                              pw_env_external=pw_env_sub, task_list_external=task_list_sub)
    1991              : 
    1992              :                      CALL dbcsr_multiply("N", "N", 1.0_dp, mat_munu%matrix, mo_coeff_as(isp2), &
    1993           56 :                                          0.0_dp, matrix_pq_rnu(isp2), filter_eps=eri_env%eri_gpw%eps_filter)
    1994           56 :                      CALL copy_dbcsr_to_fm(matrix_pq_rnu(isp2), fm_matrix_pq_rnu(isp2))
    1995              : 
    1996           56 :                      CALL cp_fm_get_info(fm_matrix_pq_rnu(isp2), ncol_global=ncol_global, nrow_global=nrow_global)
    1997              : 
    1998              :                      CALL parallel_gemm("T", "N", ncol_global, ncol_global, nrow_global, 0.5_dp, &
    1999              :                                         fm_matrix_pq_rnu(isp2), fm_mo_coeff_as(isp2), &
    2000           56 :                                         0.0_dp, fm_matrix_pq_rs(isp2))
    2001              :                      CALL parallel_gemm("T", "N", ncol_global, ncol_global, nrow_global, 0.5_dp, &
    2002              :                                         fm_mo_coeff_as(isp2), fm_matrix_pq_rnu(isp2), &
    2003           56 :                                         1.0_dp, fm_matrix_pq_rs(isp2))
    2004              : 
    2005              :                      CALL cp_fm_get_info(fm_matrix_pq_rs(isp2), ncol_local=ncol_local, nrow_local=nrow_local, &
    2006           56 :                                          col_indices=col_indices, row_indices=row_indices)
    2007              : 
    2008           56 :                      icount2 = 0
    2009          208 :                      DO col_local = 1, ncol_local
    2010          152 :                         iwb1 = orbitals(col_indices(col_local), isp2)
    2011          152 :                         IF (isp1 == isp2 .AND. iwb1 < iwa1) CYCLE
    2012          366 :                         DO row_local = 1, nrow_local
    2013          190 :                            iwb2 = orbitals(row_indices(row_local), isp2)
    2014          190 :                            IF (iwb2 < iwb1) CYCLE
    2015          114 :                            IF (isp1 == isp2 .AND. iwa1 == iwb1 .AND. iwb2 < iwa2) CYCLE
    2016              : 
    2017           97 :                            iwb12 = csr_idx_to_combined(iwb1, iwb2, nmo2)
    2018           97 :                            erint = fm_matrix_pq_rs(isp2)%local_data(row_local, col_local)
    2019          249 :                            IF (ABS(erint) > eri_env%eps_integral) THEN
    2020           90 :                               icount2 = icount2 + 1
    2021           90 :                               eri(icount2) = erint
    2022           90 :                               eri_index(icount2) = iwb12
    2023              :                            END IF
    2024              :                         END DO
    2025              :                      END DO
    2026           56 :                      stored_integrals = stored_integrals + icount2
    2027              :                      !
    2028           56 :                      isp = (isp1 - 1)*isp2 + (isp2 - isp1 + 1)
    2029           56 :                      CALL update_csr_matrix(eri_env%eri(isp)%csr_mat, icount2, eri, eri_index, iwa12)
    2030              :                      !
    2031          280 :                      DEALLOCATE (eri, eri_index)
    2032              :                   END DO
    2033          801 :                ELSE IF (eri_env%method == eri_method_full_gpw) THEN
    2034         1676 :                   DO isp2 = isp1, nspins
    2035          875 :                      CALL get_mo_set(mo_set=mos(isp2), nmo=nmo2)
    2036          875 :                      nx = (nmo2*(nmo2 + 1))/2
    2037         4375 :                      ALLOCATE (eri(nx), eri_index(nx))
    2038          875 :                      icount2 = 0
    2039          875 :                      iwbs = 1
    2040          875 :                      IF (isp1 == isp2) iwbs = i1
    2041          875 :                      isp = (isp1 - 1)*isp2 + (isp2 - isp1 + 1)
    2042         3658 :                      DO i3 = iwbs, SIZE(orbitals, 1)
    2043         2783 :                         iwb1 = orbitals(i3, isp2)
    2044         2783 :                         IF (eri_env%eri_gpw%store_wfn) THEN
    2045         2758 :                            wfn3 => wfn_a(iwb1, isp2)
    2046              :                         ELSE
    2047              :                            CALL calculate_wavefunction(fm_mo_coeff_as(isp1), iwb1, wfn3, rho_g, atomic_kind_set, &
    2048           25 :                                                        qs_kind_set, cell, dft_control, particle_set, pw_env_sub)
    2049              :                         END IF
    2050         2783 :                         CALL pw_zero(wfn_r)
    2051         2783 :                         CALL pw_multiply(wfn_r, rho_r, wfn3)
    2052         2783 :                         iwbt = i3
    2053         2783 :                         IF (isp1 == isp2 .AND. i1 == i3) iwbt = i2
    2054         9582 :                         DO i4 = iwbt, SIZE(orbitals, 1)
    2055         5924 :                            iwb2 = orbitals(i4, isp2)
    2056         5924 :                            IF (eri_env%eri_gpw%store_wfn) THEN
    2057         5894 :                               wfn4 => wfn_a(iwb2, isp2)
    2058              :                            ELSE
    2059              :                               CALL calculate_wavefunction(fm_mo_coeff_as(isp1), iwb2, wfn4, rho_g, atomic_kind_set, &
    2060           30 :                                                           qs_kind_set, cell, dft_control, particle_set, pw_env_sub)
    2061              :                            END IF
    2062              :                            ! We reduce the amount of communication by collecting the local sums first and sum globally later
    2063         5924 :                            erint = pw_integral_ab(wfn_r, wfn4, local_only=.TRUE.)
    2064         5924 :                            icount2 = icount2 + 1
    2065         5924 :                            eri(icount2) = erint
    2066         8707 :                            eri_index(icount2) = csr_idx_to_combined(iwb1, iwb2, nmo2)
    2067              :                         END DO
    2068              :                      END DO
    2069              :                      ! Now, we sum the integrals globally
    2070          875 :                      CALL eri_env%para_env_sub%sum(eri)
    2071              :                      ! and we reorder the integrals to prevent storing too small integrals
    2072          875 :                      intcount = 0
    2073          875 :                      icount2 = 0
    2074              :                      iwbs = 1
    2075              :                      IF (isp1 == isp2) iwbs = i1
    2076          875 :                      isp = (isp1 - 1)*isp2 + (isp2 - isp1 + 1)
    2077         3658 :                      DO i3 = iwbs, SIZE(orbitals, 1)
    2078         2783 :                         iwb1 = orbitals(i3, isp2)
    2079         2783 :                         iwbt = i3
    2080         2783 :                         IF (isp1 == isp2 .AND. i1 == i3) iwbt = i2
    2081         9582 :                         DO i4 = iwbt, SIZE(orbitals, 1)
    2082         5924 :                            iwb2 = orbitals(i4, isp2)
    2083         5924 :                            intcount = intcount + 1
    2084         5924 :                            erint = eri(intcount)
    2085         8707 :                            IF (ABS(erint) > eri_env%eps_integral) THEN
    2086         5222 :                               IF (MOD(intcount, eri_env%para_env_sub%num_pe) == eri_env%para_env_sub%mepos) THEN
    2087         2613 :                                  icount2 = icount2 + 1
    2088         2613 :                                  eri(icount2) = erint
    2089         2613 :                                  eri_index(icount2) = eri_index(intcount)
    2090              :                               END IF
    2091              :                            END IF
    2092              :                         END DO
    2093              :                      END DO
    2094          875 :                      stored_integrals = stored_integrals + icount2
    2095              :                      !
    2096          875 :                      CALL update_csr_matrix(eri_env%eri(isp)%csr_mat, icount2, eri, eri_index, iwa12)
    2097              :                      !
    2098         2551 :                      DEALLOCATE (eri, eri_index)
    2099              :                   END DO
    2100              :                ELSE
    2101            0 :                   CPABORT("Unknown option")
    2102              :                END IF
    2103              :             END DO
    2104              :          END DO
    2105              :       END DO
    2106              : 
    2107          110 :       IF (print1 .AND. iw > 0) THEN
    2108            3 :          WRITE (iw, "(T2,'ERI_GPW|',' Number of Integrals stored locally',T71,I10)") stored_integrals
    2109              :       END IF
    2110              : 
    2111          110 :       IF (eri_env%eri_gpw%store_wfn) THEN
    2112          210 :          DO ispin = 1, nspins
    2113          560 :             DO i1 = 1, SIZE(orbitals, 1)
    2114          350 :                iwfn = orbitals(i1, ispin)
    2115          462 :                CALL wfn_a(iwfn, ispin)%release()
    2116              :             END DO
    2117              :          END DO
    2118           98 :          DEALLOCATE (wfn_a)
    2119              :       ELSE
    2120           12 :          CALL wfn1%release()
    2121           12 :          CALL wfn2%release()
    2122           12 :          DEALLOCATE (wfn1, wfn2)
    2123           12 :          IF (eri_env%method /= eri_method_gpw_ht) THEN
    2124            6 :             CALL wfn3%release()
    2125            6 :             CALL wfn4%release()
    2126            6 :             DEALLOCATE (wfn3, wfn4)
    2127              :          END IF
    2128              :       END IF
    2129          110 :       CALL auxbas_pw_pool%give_back_pw(wfn_r)
    2130          110 :       CALL auxbas_pw_pool%give_back_pw(rho_g)
    2131          110 :       CALL auxbas_pw_pool%give_back_pw(rho_r)
    2132          110 :       CALL auxbas_pw_pool%give_back_pw(pot_g)
    2133              : 
    2134          110 :       IF (eri_env%method == eri_method_gpw_ht) THEN
    2135           32 :          DO ispin = 1, nspins
    2136           16 :             CALL dbcsr_release(mo_coeff_as(ispin))
    2137           16 :             CALL dbcsr_release(matrix_pq_rnu(ispin))
    2138           16 :             CALL cp_fm_release(fm_matrix_pq_rnu(ispin))
    2139           32 :             CALL cp_fm_release(fm_matrix_pq_rs(ispin))
    2140              :          END DO
    2141           16 :          DEALLOCATE (matrix_pq_rnu, fm_matrix_pq_rnu, fm_matrix_pq_rs)
    2142           16 :          CALL deallocate_task_list(task_list_sub)
    2143              :       END IF
    2144          234 :       DO ispin = 1, nspins
    2145          124 :          CALL dbcsr_release(mo_coeff_as(ispin))
    2146          234 :          CALL cp_fm_release(fm_mo_coeff_as(ispin))
    2147              :       END DO
    2148          110 :       DEALLOCATE (mo_coeff_as, fm_mo_coeff_as)
    2149          110 :       CALL release_neighbor_list_sets(sab_orb_sub)
    2150          110 :       CALL cp_blacs_env_release(blacs_env_sub)
    2151          110 :       CALL dbcsr_release(mat_munu%matrix)
    2152          110 :       DEALLOCATE (mat_munu%matrix)
    2153          110 :       CALL pw_env_release(pw_env_sub)
    2154              :       ! Return to the old qs_control
    2155          110 :       dft_control%qs_control => qs_control_old
    2156          110 :       DEALLOCATE (qs_control%e_cutoff)
    2157          110 :       DEALLOCATE (qs_control)
    2158              : 
    2159              :       ! print out progress
    2160          110 :       IF (iw > 0) THEN
    2161           55 :          t2 = m_walltime()
    2162           55 :          WRITE (iw, '(/,T2,A,T66,F14.2)') "ERI_GPW| ERI calculation took (sec)", t2 - t1
    2163           55 :          CALL m_flush(iw)
    2164              :       END IF
    2165              : 
    2166          110 :       CALL timestop(handle)
    2167              : 
    2168          220 :    END SUBROUTINE calculate_eri_gpw
    2169              : 
    2170              : ! **************************************************************************************************
    2171              : !> \brief Sets the Green's function for the ERI calculation. Here we deal with the G=0 case!
    2172              : !> \param green ...
    2173              : !> \param eri_env ...
    2174              : !> \par History
    2175              : !>      04.2016 created [JGH]
    2176              : !>      08.2025 added support for the LR truncation [SB]
    2177              : ! **************************************************************************************************
    2178          110 :    SUBROUTINE pw_eri_green_create(green, eri_env)
    2179              : 
    2180              :       TYPE(greens_fn_type), INTENT(INOUT)                :: green
    2181              :       TYPE(eri_type)                                     :: eri_env
    2182              : 
    2183              :       COMPLEX(KIND=dp)                                   :: erf_fac_p, z_p
    2184              :       INTEGER                                            :: ig
    2185              :       REAL(KIND=dp)                                      :: cossin_fac, ea, erfcos_fac, exp_prefac, &
    2186              :                                                             g, G0, g2, g3d, ga, Ginf, omega, &
    2187              :                                                             omega2, Rc, Rc2
    2188              : 
    2189              :       ! initialize influence function
    2190              :       ASSOCIATE (gf => green%influence_fn, grid => green%influence_fn%pw_grid)
    2191          120 :          SELECT CASE (green%method)
    2192              :          CASE (PERIODIC3D)
    2193              : 
    2194          116 :             SELECT CASE (eri_env%operator)
    2195              :             CASE (eri_operator_coulomb)
    2196       786435 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2197       786429 :                   g2 = grid%gsq(ig)
    2198       786435 :                   gf%array(ig) = fourpi/g2
    2199              :                END DO
    2200            6 :                IF (grid%have_g0) gf%array(1) = 0.0_dp
    2201              : 
    2202              :             CASE (eri_operator_yukawa)
    2203            0 :                CALL cp_warn(__LOCATION__, "Yukawa operator has not been tested")
    2204            0 :                omega2 = eri_env%omega**2
    2205            0 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2206            0 :                   g2 = grid%gsq(ig)
    2207            0 :                   gf%array(ig) = fourpi/(omega2 + g2)
    2208              :                END DO
    2209            0 :                IF (grid%have_g0) gf%array(1) = fourpi/omega2
    2210              : 
    2211              :             CASE (eri_operator_erf)
    2212            0 :                omega2 = eri_env%omega**2
    2213            0 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2214            0 :                   g2 = grid%gsq(ig)
    2215            0 :                   gf%array(ig) = fourpi/g2*EXP(-0.25_dp*g2/omega2)
    2216              :                END DO
    2217            0 :                IF (grid%have_g0) gf%array(1) = 0.0_dp
    2218              : 
    2219              :             CASE (eri_operator_erfc)
    2220            0 :                omega2 = eri_env%omega**2
    2221            0 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2222            0 :                   g2 = grid%gsq(ig)
    2223            0 :                   gf%array(ig) = fourpi/g2*(1.0_dp - EXP(-0.25_dp*g2/omega2))
    2224              :                END DO
    2225            0 :                IF (grid%have_g0) gf%array(1) = pi/omega2
    2226              : 
    2227              :             CASE (eri_operator_trunc)
    2228            0 :                Rc = eri_env%cutoff_radius
    2229            0 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2230            0 :                   g2 = grid%gsq(ig)
    2231            0 :                   g = SQRT(g2)
    2232              :                   ! Taylor expansion around zero
    2233            0 :                   IF (g*Rc >= 0.005_dp) THEN
    2234            0 :                      gf%array(ig) = fourpi/g2*(1.0_dp - COS(g*Rc))
    2235              :                   ELSE
    2236            0 :                      gf%array(ig) = fourpi/g2*(g*Rc)**2/2.0_dp*(1.0_dp - (g*Rc)**2/12.0_dp)
    2237              :                   END IF
    2238              :                END DO
    2239            0 :                IF (grid%have_g0) gf%array(1) = twopi*Rc**2
    2240              : 
    2241              :             CASE (eri_operator_lr_trunc)
    2242            4 :                omega = eri_env%omega
    2243            4 :                omega2 = omega**2
    2244            4 :                Rc = eri_env%cutoff_radius
    2245            4 :                Rc2 = Rc**2
    2246            4 :                G0 = 0.001_dp ! threshold for the G=0 case
    2247            4 :                Ginf = 20.0_dp  ! threshold for the Taylor exapnsion arounf G=∞
    2248       843752 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2249       843748 :                   g2 = grid%gsq(ig)
    2250       843748 :                   g = SQRT(g2)
    2251       843752 :                   IF (g <= 2.0_dp*G0) THEN
    2252              :                      gf%array(ig) = -pi/omega2*erf(omega*Rc) &
    2253              :                                     + twopi*Rc2*erf(omega*Rc) &
    2254            0 :                                     + 2*rootpi*Rc*EXP(-omega2*Rc2)/omega
    2255       843748 :                   ELSE IF (g >= 2.0_dp*Ginf*omega) THEN
    2256              :                      ! exponential prefactor
    2257         1488 :                      exp_prefac = EXP(-omega2*Rc2)/(rootpi*(omega2*Rc2 + 0.25_dp*g2/omega2))
    2258              :                      ! cos sin factor
    2259         1488 :                      cossin_fac = omega*Rc*COS(g*Rc) - 0.5_dp*g/omega*SIN(g*Rc)
    2260              :                      ! real erf term with cosine
    2261         1488 :                      erfcos_fac = ERF(omega*Rc)*COS(g*Rc)
    2262              :                      ! Combine terms
    2263         1488 :                      gf%array(ig) = fourpi/g2*(-exp_prefac*cossin_fac - erfcos_fac)
    2264              :                   ELSE
    2265              :                      ! exponential prefactor
    2266       842260 :                      exp_prefac = twopi/g2*EXP(-0.25_dp*g2/omega2)
    2267              :                      ! Compute complex arguments for erf
    2268       842260 :                      z_p = CMPLX(omega*Rc, 0.5_dp*g/omega, kind=dp)
    2269              :                      ! Evaluate complex error functions
    2270       842260 :                      erf_fac_p = 2.0_dp*REAL(erfz_fast(z_p))
    2271              :                      ! Real erf term with cosine
    2272       842260 :                      erfcos_fac = fourpi/g2*ERF(omega*Rc)*COS(g*Rc)
    2273              :                      ! Combine terms
    2274       842260 :                      gf%array(ig) = exp_prefac*erf_fac_p - erfcos_fac
    2275              :                   END IF
    2276              :                END DO
    2277            4 :                IF (grid%have_g0) THEN
    2278              :                   gf%array(1) = -pi/omega2*ERF(omega*Rc) &
    2279              :                                 + twopi*Rc2*ERF(omega*Rc) &
    2280            2 :                                 + 2*rootpi*Rc*EXP(-omega2*Rc2)/omega
    2281              :                END IF
    2282              : 
    2283              :             CASE DEFAULT
    2284           10 :                CPABORT("Please specify a valid operator for the periodic Poisson solver")
    2285              :             END SELECT
    2286              : 
    2287              :             ! The analytic Poisson solver simply limits the domain of integration
    2288              :             ! of the Fourier transform to a sphere of radius Rc, rather than integrating
    2289              :             ! over all space (-∞,∞)
    2290              :          CASE (ANALYTIC0D)
    2291              : 
    2292          184 :             SELECT CASE (eri_env%operator)
    2293              :                ! This is identical to the truncated Coulomb operator integrated
    2294              :                ! over all space, when the truncation radius is equal to the radius of
    2295              :                ! the Poisson solver
    2296              :             CASE (eri_operator_coulomb, eri_operator_trunc)
    2297           84 :                IF (eri_env%operator == eri_operator_coulomb) THEN
    2298           84 :                   Rc = green%radius
    2299              :                ELSE
    2300            0 :                   Rc = eri_env%cutoff_radius
    2301              :                END IF
    2302     24765035 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2303     24764951 :                   g2 = grid%gsq(ig)
    2304     24764951 :                   g = SQRT(g2)
    2305              :                   ! Taylor expansion around zero
    2306     24765035 :                   IF (g*Rc >= 0.005_dp) THEN
    2307     24764951 :                      gf%array(ig) = fourpi/g2*(1.0_dp - COS(g*Rc))
    2308              :                   ELSE
    2309            0 :                      gf%array(ig) = fourpi/g2*(g*Rc)**2/2.0_dp*(1.0_dp - (g*Rc)**2/12.0_dp)
    2310              :                   END IF
    2311              :                END DO
    2312           84 :                IF (grid%have_g0) gf%array(1) = twopi*Rc**2
    2313              : 
    2314              :                ! Not tested
    2315              :             CASE (eri_operator_yukawa)
    2316            0 :                CALL cp_warn(__LOCATION__, "Yukawa operator has not been tested")
    2317            0 :                Rc = green%radius
    2318            0 :                omega = eri_env%omega
    2319            0 :                ea = EXP(-omega*Rc)
    2320            0 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2321            0 :                   g2 = grid%gsq(ig)
    2322            0 :                   g = SQRT(g2)
    2323            0 :                   g3d = fourpi/(omega**2 + g2)
    2324            0 :                   gf%array(ig) = g3d*(1.0_dp - ea*(COS(g*Rc) + omega/g*SIN(g*Rc)))
    2325              :                END DO
    2326            0 :                IF (grid%have_g0) gf%array(1) = fourpi/(omega**2)*(1.0_dp - ea*(1.0_dp + omega*Rc))
    2327              : 
    2328              :                ! Long-range Coulomb
    2329              :                ! TODO: this should be equivalent to LR truncated Coulomb from above!
    2330              :             CASE (eri_operator_erf, eri_operator_lr_trunc)
    2331           16 :                IF (eri_env%operator == eri_operator_erf) THEN
    2332           16 :                   Rc = green%radius
    2333              :                ELSE
    2334            0 :                   Rc = eri_env%cutoff_radius
    2335              :                END IF
    2336           16 :                omega2 = eri_env%omega**2
    2337      1728008 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2338      1727992 :                   g2 = grid%gsq(ig)
    2339      1727992 :                   g = SQRT(g2)
    2340      1727992 :                   ga = -0.25_dp*g2/omega2
    2341      1728008 :                   gf%array(ig) = fourpi/g2*EXP(ga)*(1.0_dp - COS(g*Rc))
    2342              :                END DO
    2343           16 :                IF (grid%have_g0) gf%array(1) = twopi*Rc**2
    2344              : 
    2345              :                ! Short-range Coulomb
    2346              :                ! TODO: this should actually be properly derived and see whether it is correct
    2347              :             CASE (eri_operator_erfc)
    2348              :                CALL cp_warn(__LOCATION__, &
    2349            0 :                             "Short-range Coulomb operator may be incorrect with ANALYTIC0D Poisson solver")
    2350            0 :                Rc = green%radius
    2351            0 :                omega2 = eri_env%omega**2
    2352            0 :                DO ig = grid%first_gne0, grid%ngpts_cut_local
    2353            0 :                   g2 = grid%gsq(ig)
    2354            0 :                   g = SQRT(g2)
    2355            0 :                   ga = -0.25_dp*g2/omega2
    2356            0 :                   gf%array(ig) = fourpi/g2*(1.0_dp - EXP(ga))*(1.0_dp - COS(g*Rc))
    2357              :                END DO
    2358            0 :                IF (grid%have_g0) gf%array(1) = pi/omega2
    2359              : 
    2360              :             CASE DEFAULT
    2361          100 :                CPABORT("Unsupported operator")
    2362              :             END SELECT
    2363              : 
    2364              :          CASE DEFAULT
    2365          110 :             CPABORT("Unsupported Poisson solver")
    2366              :          END SELECT
    2367              :       END ASSOCIATE
    2368              : 
    2369          110 :    END SUBROUTINE pw_eri_green_create
    2370              : 
    2371              : ! **************************************************************************************************
    2372              : !> \brief Adds data for a new row to the csr matrix
    2373              : !> \param csr_mat ...
    2374              : !> \param nnz ...
    2375              : !> \param rdat ...
    2376              : !> \param rind ...
    2377              : !> \param irow ...
    2378              : !> \par History
    2379              : !>      04.2016 created [JGH]
    2380              : ! **************************************************************************************************
    2381          931 :    SUBROUTINE update_csr_matrix(csr_mat, nnz, rdat, rind, irow)
    2382              : 
    2383              :       TYPE(dbcsr_csr_type), INTENT(INOUT)                :: csr_mat
    2384              :       INTEGER, INTENT(IN)                                :: nnz
    2385              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: rdat
    2386              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: rind
    2387              :       INTEGER, INTENT(IN)                                :: irow
    2388              : 
    2389              :       INTEGER                                            :: k, nrow, nze, nze_new
    2390              : 
    2391          931 :       IF (irow /= 0) THEN
    2392          931 :          nze = csr_mat%nze_local
    2393          931 :          nze_new = nze + nnz
    2394              :          ! values
    2395          931 :          CALL reallocate(csr_mat%nzval_local%r_dp, 1, nze_new)
    2396         3634 :          csr_mat%nzval_local%r_dp(nze + 1:nze_new) = rdat(1:nnz)
    2397              :          ! col indices
    2398          931 :          CALL reallocate(csr_mat%colind_local, 1, nze_new)
    2399         3634 :          csr_mat%colind_local(nze + 1:nze_new) = rind(1:nnz)
    2400              :          ! rows
    2401          931 :          nrow = csr_mat%nrows_local
    2402          931 :          CALL reallocate(csr_mat%rowptr_local, 1, irow + 1)
    2403         2476 :          csr_mat%rowptr_local(nrow + 1:irow) = nze + 1
    2404          931 :          csr_mat%rowptr_local(irow + 1) = nze_new + 1
    2405              :          ! nzerow
    2406          931 :          CALL reallocate(csr_mat%nzerow_local, 1, irow)
    2407         2476 :          DO k = nrow + 1, irow
    2408         2476 :             csr_mat%nzerow_local(k) = csr_mat%rowptr_local(k + 1) - csr_mat%rowptr_local(k)
    2409              :          END DO
    2410          931 :          csr_mat%nrows_local = irow
    2411          931 :          csr_mat%nze_local = csr_mat%nze_local + nnz
    2412              :       END IF
    2413          931 :       csr_mat%nze_total = csr_mat%nze_total + nnz
    2414          931 :       csr_mat%has_indices = .TRUE.
    2415              : 
    2416          931 :    END SUBROUTINE update_csr_matrix
    2417              : 
    2418              : ! **************************************************************************************************
    2419              : !> \brief Computes and prints the active orbitals on Cube Files
    2420              : !> \param input ...
    2421              : !> \param qs_env the qs_env in which the qs_env lives
    2422              : !> \param mos ...
    2423              : ! **************************************************************************************************
    2424            4 :    SUBROUTINE print_orbital_cubes(input, qs_env, mos)
    2425              :       TYPE(section_vals_type), POINTER                   :: input
    2426              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2427              :       TYPE(mo_set_type), DIMENSION(:), INTENT(IN)        :: mos
    2428              : 
    2429              :       CHARACTER(LEN=default_path_length)                 :: filebody, filename, title
    2430              :       INTEGER                                            :: i, imo, isp, nmo, str(3), unit_nr
    2431            4 :       INTEGER, DIMENSION(:), POINTER                     :: alist, blist, istride
    2432              :       LOGICAL                                            :: do_mo, explicit_a, explicit_b
    2433            4 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2434              :       TYPE(cell_type), POINTER                           :: cell
    2435              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    2436              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2437              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2438              :       TYPE(particle_list_type), POINTER                  :: particles
    2439            4 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2440              :       TYPE(pw_c1d_gs_type)                               :: wf_g
    2441              :       TYPE(pw_env_type), POINTER                         :: pw_env
    2442              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    2443              :       TYPE(pw_r3d_rs_type)                               :: wf_r
    2444            4 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2445              :       TYPE(qs_subsys_type), POINTER                      :: subsys
    2446              :       TYPE(section_vals_type), POINTER                   :: dft_section, scf_input
    2447              : 
    2448            4 :       CALL section_vals_val_get(input, "FILENAME", c_val=filebody)
    2449            4 :       CALL section_vals_val_get(input, "STRIDE", i_vals=istride)
    2450            4 :       IF (SIZE(istride) == 1) THEN
    2451           16 :          str(1:3) = istride(1)
    2452            0 :       ELSE IF (SIZE(istride) == 3) THEN
    2453            0 :          str(1:3) = istride(1:3)
    2454              :       ELSE
    2455            0 :          CPABORT("STRIDE arguments inconsistent")
    2456              :       END IF
    2457            4 :       CALL section_vals_val_get(input, "ALIST", i_vals=alist, explicit=explicit_a)
    2458            4 :       CALL section_vals_val_get(input, "BLIST", i_vals=blist, explicit=explicit_b)
    2459              : 
    2460              :       CALL get_qs_env(qs_env=qs_env, &
    2461              :                       dft_control=dft_control, &
    2462              :                       para_env=para_env, &
    2463              :                       subsys=subsys, &
    2464              :                       atomic_kind_set=atomic_kind_set, &
    2465              :                       qs_kind_set=qs_kind_set, &
    2466              :                       cell=cell, &
    2467              :                       particle_set=particle_set, &
    2468              :                       pw_env=pw_env, &
    2469            4 :                       input=scf_input)
    2470              : 
    2471            4 :       CALL qs_subsys_get(subsys, particles=particles)
    2472              :       !
    2473            4 :       CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    2474            4 :       CALL auxbas_pw_pool%create_pw(wf_r)
    2475            4 :       CALL auxbas_pw_pool%create_pw(wf_g)
    2476              :       !
    2477            4 :       dft_section => section_vals_get_subs_vals(scf_input, "DFT")
    2478              :       !
    2479            8 :       DO isp = 1, SIZE(mos)
    2480            4 :          CALL get_mo_set(mo_set=mos(isp), mo_coeff=mo_coeff, nmo=nmo)
    2481              : 
    2482            4 :          IF (SIZE(mos) > 1) THEN
    2483            0 :             SELECT CASE (isp)
    2484              :             CASE (1)
    2485              :                CALL write_mo_set_to_output_unit(mos(isp), qs_kind_set, particle_set, &
    2486            0 :                                                 dft_section, 4, 0, final_mos=.TRUE., spin="ALPHA")
    2487              :             CASE (2)
    2488              :                CALL write_mo_set_to_output_unit(mos(isp), qs_kind_set, particle_set, &
    2489            0 :                                                 dft_section, 4, 0, final_mos=.TRUE., spin="BETA")
    2490              :             CASE DEFAULT
    2491            0 :                CPABORT("Invalid spin")
    2492              :             END SELECT
    2493              :          ELSE
    2494              :             CALL write_mo_set_to_output_unit(mos(isp), qs_kind_set, particle_set, &
    2495            4 :                                              dft_section, 4, 0, final_mos=.TRUE.)
    2496              :          END IF
    2497              : 
    2498           44 :          DO imo = 1, nmo
    2499           32 :             IF (isp == 1 .AND. explicit_a) THEN
    2500           32 :                IF (alist(1) == -1) THEN
    2501              :                   do_mo = .TRUE.
    2502              :                ELSE
    2503           32 :                   do_mo = .FALSE.
    2504          128 :                   DO i = 1, SIZE(alist)
    2505          128 :                      IF (imo == alist(i)) do_mo = .TRUE.
    2506              :                   END DO
    2507              :                END IF
    2508            0 :             ELSE IF (isp == 2 .AND. explicit_b) THEN
    2509            0 :                IF (blist(1) == -1) THEN
    2510              :                   do_mo = .TRUE.
    2511              :                ELSE
    2512            0 :                   do_mo = .FALSE.
    2513            0 :                   DO i = 1, SIZE(blist)
    2514            0 :                      IF (imo == blist(i)) do_mo = .TRUE.
    2515              :                   END DO
    2516              :                END IF
    2517              :             ELSE
    2518              :                do_mo = .TRUE.
    2519              :             END IF
    2520           32 :             IF (.NOT. do_mo) CYCLE
    2521              :             CALL calculate_wavefunction(mo_coeff, imo, wf_r, wf_g, atomic_kind_set, &
    2522           12 :                                         qs_kind_set, cell, dft_control, particle_set, pw_env)
    2523           12 :             IF (para_env%is_source()) THEN
    2524            6 :                WRITE (filename, '(A,A1,I4.4,A1,I1.1,A)') TRIM(filebody), "_", imo, "_", isp, ".cube"
    2525            6 :                CALL open_file(filename, unit_number=unit_nr, file_status="UNKNOWN", file_action="WRITE")
    2526            6 :                WRITE (title, *) "Active Orbital ", imo, " spin ", isp
    2527              :             ELSE
    2528            6 :                unit_nr = -1
    2529              :             END IF
    2530           12 :             CALL cp_pw_to_cube(wf_r, unit_nr, title, particles=particles, stride=istride)
    2531           16 :             IF (para_env%is_source()) THEN
    2532           26 :                CALL close_file(unit_nr)
    2533              :             END IF
    2534              :          END DO
    2535              :       END DO
    2536              : 
    2537            4 :       CALL auxbas_pw_pool%give_back_pw(wf_r)
    2538            4 :       CALL auxbas_pw_pool%give_back_pw(wf_g)
    2539              : 
    2540            4 :    END SUBROUTINE print_orbital_cubes
    2541              : 
    2542              : ! **************************************************************************************************
    2543              : !> \brief Writes a FCIDUMP file
    2544              : !> \param active_space_env ...
    2545              : !> \param as_input ...
    2546              : !> \param restricted ...
    2547              : !> \param check_reference compare the canonical ROKS determinant with the reference energy
    2548              : !> \par History
    2549              : !>      04.2016 created [JGH]
    2550              : ! **************************************************************************************************
    2551          106 :    SUBROUTINE fcidump(active_space_env, as_input, restricted, check_reference)
    2552              : 
    2553              :       TYPE(active_space_type), POINTER                   :: active_space_env
    2554              :       TYPE(section_vals_type), POINTER                   :: as_input
    2555              :       LOGICAL, INTENT(IN)                                :: restricted, check_reference
    2556              : 
    2557              :       CHARACTER(LEN=*), PARAMETER :: roks_warning = &
    2558              :          "ROKS FCIDUMP spin blocks differ. Check the cell size and the consistency of "// &
    2559              :          "the SCF exchange and active-space ERI operators."
    2560              :       REAL(KIND=dp), PARAMETER                           :: roks_fock_tol = 1.0E-6_dp
    2561              : 
    2562              :       INTEGER                                            :: i, i1, i2, i3, i4, isym, iw, m1, m2, &
    2563              :                                                             ms2, nmo, norb, nspins
    2564              :       REAL(KIND=dp)                                      :: checksum, esub, spin_difference
    2565          106 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: fmat, fock_diff, pmat
    2566              :       TYPE(cp_logger_type), POINTER                      :: logger
    2567              :       TYPE(eri_fcidump_checksum)                         :: eri_checksum
    2568              :       TYPE(eri_fcidump_print)                            :: writer
    2569              : 
    2570          106 :       checksum = 0.0_dp
    2571          106 :       spin_difference = 0.0_dp
    2572              : 
    2573          212 :       logger => cp_get_default_logger()
    2574              :       iw = cp_print_key_unit_nr(logger, as_input, "FCIDUMP", &
    2575          106 :                                 extension=".fcidump", file_status="REPLACE", file_action="WRITE", file_form="FORMATTED")
    2576              :       !
    2577          106 :       nspins = active_space_env%nspins
    2578          106 :       norb = SIZE(active_space_env%active_orbitals, 1)
    2579          106 :       ms2 = active_space_env%multiplicity - 1
    2580          106 :       IF (nspins == 1 .OR. restricted) THEN
    2581              :          ! Closed shell or restricted open-shell
    2582              :          ASSOCIATE (nelec => active_space_env%nelec_active)
    2583              : 
    2584           94 :             IF (iw > 0) THEN
    2585           47 :                WRITE (iw, "(A,A,I4,A,I4,A,I2,A)") "&FCI", " NORB=", norb, ",NELEC=", nelec, ",MS2=", ms2, ","
    2586           47 :                isym = 1
    2587          192 :                WRITE (iw, "(A,1000(I1,','))") "  ORBSYM=", (isym, i=1, norb)
    2588           47 :                isym = 0
    2589           47 :                WRITE (iw, "(A,I1,A)") "  ISYM=", isym, ","
    2590           47 :                IF (restricted) WRITE (iw, "(A,I1,A)") "  UHF=", 0, ","
    2591           47 :                WRITE (iw, "(A)") " /"
    2592              :             END IF
    2593              :             !
    2594              :             ! Print integrals: ERI
    2595           94 :             writer = eri_fcidump_print(iw, 1, 1)
    2596           94 :             IF (check_reference) THEN
    2597            4 :                writer%nalpha = (nelec + ms2)/2
    2598            4 :                writer%nbeta = (nelec - ms2)/2
    2599              :             END IF
    2600              :             CALL active_space_env%eri%eri_foreach(1, active_space_env%active_orbitals, &
    2601           94 :                                                   writer, 1, 1)
    2602           94 :             CALL eri_checksum%set(1, 1)
    2603           94 :             CALL active_space_env%eri%eri_foreach(1, active_space_env%active_orbitals, eri_checksum, 1, 1)
    2604              : 
    2605              :             ! Print integrals: Fij
    2606              :             ! replicate Fock matrix
    2607           94 :             nmo = active_space_env%eri%norb
    2608          376 :             ALLOCATE (fmat(nmo, nmo))
    2609           94 :             CALL replicate_and_symmetrize_matrix(nmo, active_space_env%fock_sub(1), fmat)
    2610           94 :             esub = active_space_env%energy_inactive
    2611           94 :             IF (restricted) THEN
    2612           20 :                ALLOCATE (fock_diff(nmo, nmo), pmat(nmo, nmo))
    2613            4 :                CALL replicate_and_symmetrize_matrix(nmo, active_space_env%fock_sub(2), fock_diff)
    2614           76 :                fock_diff(:, :) = fmat - fock_diff
    2615              :                ASSOCIATE (active => active_space_env%active_orbitals(:, 1))
    2616           56 :                   spin_difference = MAXVAL(ABS(fock_diff(active, active)))
    2617              :                END ASSOCIATE
    2618              :                ! Use one spin-independent operator and preserve the energy at the embedding density.
    2619           76 :                fmat(:, :) = fmat - 0.5_dp*fock_diff
    2620            4 :                CALL replicate_and_symmetrize_matrix(nmo, active_space_env%p_active(1), pmat)
    2621           76 :                esub = esub + 0.5_dp*SUM(fock_diff*pmat)
    2622            4 :                CALL replicate_and_symmetrize_matrix(nmo, active_space_env%p_active(2), pmat)
    2623           76 :                esub = esub - 0.5_dp*SUM(fock_diff*pmat)
    2624            4 :                DEALLOCATE (fock_diff, pmat)
    2625              :             END IF
    2626           94 :             IF (iw > 0) THEN
    2627           47 :                i3 = 0; i4 = 0
    2628          192 :                DO m1 = 1, SIZE(active_space_env%active_orbitals, 1)
    2629          145 :                   i1 = active_space_env%active_orbitals(m1, 1)
    2630          145 :                   IF (m1 <= writer%nalpha) writer%determinant_energy = writer%determinant_energy + fmat(i1, i1)
    2631          145 :                   IF (m1 <= writer%nbeta) writer%determinant_energy = writer%determinant_energy + fmat(i1, i1)
    2632          541 :                   DO m2 = m1, SIZE(active_space_env%active_orbitals, 1)
    2633          349 :                      i2 = active_space_env%active_orbitals(m2, 1)
    2634          349 :                      checksum = checksum + ABS(fmat(i1, i2))
    2635          494 :                      WRITE (iw, "(ES23.16,4I4)") fmat(i1, i2), m1, m2, i3, i4
    2636              :                   END DO
    2637              :                END DO
    2638              :             END IF
    2639           94 :             DEALLOCATE (fmat)
    2640              :             ! Print energy
    2641           94 :             i1 = 0; i2 = 0; i3 = 0; i4 = 0
    2642           94 :             checksum = checksum + ABS(esub)
    2643          188 :             IF (iw > 0) WRITE (iw, "(ES23.16,4I4)") esub, i1, i2, i3, i4
    2644              :          END ASSOCIATE
    2645              : 
    2646              :       ELSE
    2647              :          ASSOCIATE (nelec => active_space_env%nelec_active)
    2648              : 
    2649           12 :             IF (iw > 0) THEN
    2650            6 :                WRITE (iw, "(A,A,I4,A,I4,A,I2,A)") "&FCI", " NORB=", norb, ",NELEC=", nelec, ",MS2=", ms2, ","
    2651            6 :                isym = 1
    2652           21 :                WRITE (iw, "(A,1000(I1,','))") "  ORBSYM=", (isym, i=1, norb)
    2653            6 :                isym = 0
    2654            6 :                WRITE (iw, "(A,I1,A)") "  ISYM=", isym, ","
    2655            6 :                WRITE (iw, "(A,I1,A)") "  UHF=", 1, ","
    2656            6 :                WRITE (iw, "(A)") " /"
    2657              :             END IF
    2658              :             !
    2659              :             ! Print integrals: ERI
    2660              :             ! alpha-alpha
    2661              :             CALL active_space_env%eri%eri_foreach(1, active_space_env%active_orbitals, &
    2662           12 :                                                   eri_fcidump_print(iw, 1, 1), 1, 1)
    2663           12 :             CALL eri_checksum%set(1, 1)
    2664           12 :             CALL active_space_env%eri%eri_foreach(1, active_space_env%active_orbitals, eri_checksum, 1, 1)
    2665              :             ! alpha-beta
    2666              :             CALL active_space_env%eri%eri_foreach(2, active_space_env%active_orbitals, &
    2667           12 :                                                   eri_fcidump_print(iw, 1, norb + 1), 1, 2)
    2668           12 :             CALL eri_checksum%set(1, norb + 1)
    2669           12 :             CALL active_space_env%eri%eri_foreach(2, active_space_env%active_orbitals, eri_checksum, 1, 2)
    2670              :             ! beta-beta
    2671              :             CALL active_space_env%eri%eri_foreach(3, active_space_env%active_orbitals, &
    2672           12 :                                                   eri_fcidump_print(iw, norb + 1, norb + 1), 2, 2)
    2673           12 :             CALL eri_checksum%set(norb + 1, norb + 1)
    2674           12 :             CALL active_space_env%eri%eri_foreach(3, active_space_env%active_orbitals, eri_checksum, 2, 2)
    2675              :             ! Print integrals: Fij
    2676              :             ! alpha
    2677           12 :             nmo = active_space_env%eri%norb
    2678           48 :             ALLOCATE (fmat(nmo, nmo))
    2679           12 :             CALL replicate_and_symmetrize_matrix(nmo, active_space_env%fock_sub(1), fmat)
    2680           12 :             IF (iw > 0) THEN
    2681            6 :                i3 = 0; i4 = 0
    2682           21 :                DO m1 = 1, norb
    2683           15 :                   i1 = active_space_env%active_orbitals(m1, 1)
    2684           48 :                   DO m2 = m1, norb
    2685           27 :                      i2 = active_space_env%active_orbitals(m2, 1)
    2686           27 :                      checksum = checksum + ABS(fmat(i1, i2))
    2687           42 :                      WRITE (iw, "(ES23.16,4I4)") fmat(i1, i2), m1, m2, i3, i4
    2688              :                   END DO
    2689              :                END DO
    2690              :             END IF
    2691           12 :             DEALLOCATE (fmat)
    2692              :             ! beta
    2693           36 :             ALLOCATE (fmat(nmo, nmo))
    2694           12 :             CALL replicate_and_symmetrize_matrix(nmo, active_space_env%fock_sub(2), fmat)
    2695           12 :             IF (iw > 0) THEN
    2696            6 :                i3 = 0; i4 = 0
    2697           21 :                DO m1 = 1, SIZE(active_space_env%active_orbitals, 1)
    2698           15 :                   i1 = active_space_env%active_orbitals(m1, 2)
    2699           48 :                   DO m2 = m1, SIZE(active_space_env%active_orbitals, 1)
    2700           27 :                      i2 = active_space_env%active_orbitals(m2, 2)
    2701           27 :                      checksum = checksum + ABS(fmat(i1, i2))
    2702           42 :                      WRITE (iw, "(ES23.16,4I4)") fmat(i1, i2), m1 + norb, m2 + norb, i3, i4
    2703              :                   END DO
    2704              :                END DO
    2705              :             END IF
    2706           12 :             DEALLOCATE (fmat)
    2707              :             ! Print energy
    2708           12 :             esub = active_space_env%energy_inactive
    2709           12 :             i1 = 0; i2 = 0; i3 = 0; i4 = 0
    2710           12 :             checksum = checksum + ABS(esub)
    2711           24 :             IF (iw > 0) WRITE (iw, "(ES23.16,4I4)") esub, i1, i2, i3, i4
    2712              :          END ASSOCIATE
    2713              :       END IF
    2714              :       !
    2715          106 :       CALL cp_print_key_finished_output(iw, logger, as_input, "FCIDUMP")
    2716              : 
    2717              :       !>>
    2718          106 :       iw = cp_logger_get_default_io_unit(logger)
    2719          106 :       IF (iw > 0) WRITE (iw, '(T4,A,T66,F12.8)') "FCIDUMP| Checksum:", eri_checksum%checksum + checksum
    2720          106 :       IF (restricted) THEN
    2721            4 :          IF (check_reference .AND. writer%unit_nr > 0 .AND. iw > 0) THEN
    2722            2 :             WRITE (iw, '(T4,A,1X,ES23.16)') "FCIDUMP| Reference determinant energy offset [hartree]:", &
    2723            4 :                writer%determinant_energy + esub - active_space_env%energy_ref
    2724              :          END IF
    2725            4 :          IF (iw > 0) WRITE (iw, '(T4,A,1X,ES12.5)') &
    2726            2 :             "FCIDUMP| Max. ROKS spin-block difference [hartree]:", spin_difference
    2727            4 :          IF (spin_difference > roks_fock_tol) THEN
    2728            4 :             CPWARN(roks_warning)
    2729              :          END IF
    2730              :       END IF
    2731              :       !<<
    2732              : 
    2733          212 :    END SUBROUTINE fcidump
    2734              : 
    2735              : ! **************************************************************************************************
    2736              : !> \brief replicate and symmetrize a matrix
    2737              : !> \param norb the number of orbitals
    2738              : !> \param distributed_matrix ...
    2739              : !> \param replicated_matrix ...
    2740              : ! **************************************************************************************************
    2741          462 :    SUBROUTINE replicate_and_symmetrize_matrix(norb, distributed_matrix, replicated_matrix)
    2742              :       INTEGER, INTENT(IN)                                :: norb
    2743              :       TYPE(cp_fm_type), INTENT(IN)                       :: distributed_matrix
    2744              :       REAL(dp), DIMENSION(:, :), INTENT(INOUT)           :: replicated_matrix
    2745              : 
    2746              :       INTEGER                                            :: i1, i2
    2747              :       REAL(dp)                                           :: mval
    2748              : 
    2749        11058 :       replicated_matrix(:, :) = 0.0_dp
    2750         2296 :       DO i1 = 1, norb
    2751         7594 :          DO i2 = i1, norb
    2752         5298 :             CALL cp_fm_get_element(distributed_matrix, i1, i2, mval)
    2753         5298 :             replicated_matrix(i1, i2) = mval
    2754         7132 :             replicated_matrix(i2, i1) = mval
    2755              :          END DO
    2756              :       END DO
    2757          462 :    END SUBROUTINE replicate_and_symmetrize_matrix
    2758              : 
    2759              : ! **************************************************************************************************
    2760              : !> \brief Calculates active space Fock matrix and inactive energy
    2761              : !> \param active_space_env ...
    2762              : !> \param restricted ...
    2763              : !> \par History
    2764              : !>      06.2016 created [JGH]
    2765              : ! **************************************************************************************************
    2766          132 :    SUBROUTINE subspace_fock_matrix(active_space_env, restricted)
    2767              : 
    2768              :       TYPE(active_space_type), POINTER                   :: active_space_env
    2769              :       LOGICAL, INTENT(IN)                                :: restricted
    2770              : 
    2771              :       INTEGER                                            :: i1, i2, is, norb, nspins
    2772              :       REAL(KIND=dp)                                      :: eeri, eref, esub, mval
    2773          132 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: ks_a_mat, ks_a_ref, ks_b_mat, ks_b_ref, &
    2774          132 :                                                             ks_mat, ks_ref, p_a_mat, p_b_mat, p_mat
    2775              :       TYPE(cp_fm_type), POINTER                          :: matrix, mo_coef
    2776              :       TYPE(dbcsr_csr_type), POINTER                      :: eri, eri_aa, eri_ab, eri_bb
    2777              : 
    2778          132 :       eref = active_space_env%energy_ref
    2779          132 :       nspins = active_space_env%nspins
    2780              : 
    2781          132 :       IF (nspins == 1) THEN
    2782           98 :          CALL get_mo_set(active_space_env%mos_active(1), nmo=norb, mo_coeff=mo_coef)
    2783              :          !
    2784              :          ! Loop over ERI, calculate subspace HF energy and Fock matrix
    2785              :          !
    2786              :          ! replicate KS, Core, and P matrices
    2787          784 :          ALLOCATE (ks_mat(norb, norb), ks_ref(norb, norb), p_mat(norb, norb))
    2788           98 :          ks_ref = 0.0_dp
    2789              : 
    2790              :          ! ks_mat contains the KS/Fock matrix (of full density) projected onto the AS MO subspace (f_ref in eq. 19)
    2791           98 :          CALL replicate_and_symmetrize_matrix(norb, active_space_env%ks_sub(1), ks_mat)
    2792           98 :          CALL replicate_and_symmetrize_matrix(norb, active_space_env%p_active(1), p_mat)
    2793              : 
    2794              :          ! compute ks_ref = V_H[rho^A] + V_HFX[rho^A]
    2795           98 :          eri => active_space_env%eri%eri(1)%csr_mat
    2796              :          CALL build_subspace_fock_matrix(active_space_env%active_orbitals, eri, p_mat, ks_ref, &
    2797           98 :                                          active_space_env%eri%comm_exchange)
    2798              : 
    2799              :          ! compute eeri = E_H[rho^A] + E_HFX[rho^A] as
    2800              :          ! eeri = 1/2 * (SUM_pq (V_H[rho^A] + V_HFX[rho^A])_pq * D^A_pq)
    2801         2542 :          eeri = 0.5_dp*SUM(ks_ref*p_mat)
    2802              : 
    2803              :          ! now calculate the inactive energy acoording to eq. 19, that is
    2804              :          ! esub = E^I = E_ref - f_ref .* D^A + E_H[rho^A] + E_HFX[rho^A]
    2805              :          ! where f^ref = ks_mat, which is the KS/Fock matrix in MO basis, transformed previously
    2806              :          ! and is equal to ks_mat = h^0 + V_core + V_H[rho] + V_HFX[rho]
    2807         2542 :          esub = eref - SUM(ks_mat(1:norb, 1:norb)*p_mat(1:norb, 1:norb)) + eeri
    2808              : 
    2809              :          ! reuse ks_mat to store f^I = f^ref - (V_H[rho^A] + V_HFX[rho^A]) according to eq. 20
    2810         2542 :          ks_mat(1:norb, 1:norb) = ks_mat(1:norb, 1:norb) - ks_ref(1:norb, 1:norb)
    2811              :          ! this is now the embedding potential for the AS calculation!
    2812              : 
    2813           98 :          active_space_env%energy_inactive = esub
    2814              : 
    2815           98 :          CALL cp_fm_release(active_space_env%fock_sub)
    2816          392 :          ALLOCATE (active_space_env%fock_sub(nspins))
    2817          196 :          DO is = 1, nspins
    2818           98 :             matrix => active_space_env%ks_sub(is)
    2819              :             CALL cp_fm_create(active_space_env%fock_sub(is), matrix%matrix_struct, &
    2820          196 :                               name="Active Fock operator")
    2821              :          END DO
    2822           98 :          matrix => active_space_env%fock_sub(1)
    2823          594 :          DO i1 = 1, norb
    2824         2542 :             DO i2 = 1, norb
    2825         2046 :                mval = ks_mat(i1, i2)
    2826         2444 :                CALL cp_fm_set_element(matrix, i1, i2, mval)
    2827              :             END DO
    2828              :          END DO
    2829              :       ELSE
    2830              : 
    2831           34 :          CALL get_mo_set(active_space_env%mos_active(1), nmo=norb)
    2832              :          !
    2833              :          ! Loop over ERI, calculate subspace HF energy and Fock matrix
    2834              :          !
    2835              :          ! replicate KS, Core, and P matrices
    2836              :          ALLOCATE (ks_a_mat(norb, norb), ks_b_mat(norb, norb), &
    2837              :               &    ks_a_ref(norb, norb), ks_b_ref(norb, norb), &
    2838          476 :               &     p_a_mat(norb, norb), p_b_mat(norb, norb))
    2839           34 :          ks_a_ref(:, :) = 0.0_dp; ks_b_ref(:, :) = 0.0_dp
    2840              : 
    2841           34 :          CALL replicate_and_symmetrize_matrix(norb, active_space_env%p_active(1), p_a_mat)
    2842           34 :          CALL replicate_and_symmetrize_matrix(norb, active_space_env%p_active(2), p_b_mat)
    2843           34 :          CALL replicate_and_symmetrize_matrix(norb, active_space_env%ks_sub(1), ks_a_mat)
    2844           34 :          CALL replicate_and_symmetrize_matrix(norb, active_space_env%ks_sub(2), ks_b_mat)
    2845              :          !
    2846              :          !
    2847           34 :          IF (restricted) THEN
    2848              :             ! In the restricted case, we use the same ERIs for each spin channel
    2849           14 :             eri_aa => active_space_env%eri%eri(1)%csr_mat
    2850              :             CALL build_subspace_spin_fock_matrix(active_space_env%active_orbitals, eri_aa, eri_aa, p_a_mat, p_b_mat, ks_a_ref, &
    2851              :                                                  tr_mixed_eri=.FALSE., comm_exchange=active_space_env%eri%comm_exchange, &
    2852           14 :                                                  restricted=restricted)
    2853              :             CALL build_subspace_spin_fock_matrix(active_space_env%active_orbitals, eri_aa, eri_aa, p_b_mat, p_a_mat, ks_b_ref, &
    2854              :                                                  tr_mixed_eri=.TRUE., comm_exchange=active_space_env%eri%comm_exchange, &
    2855           14 :                                                  restricted=restricted)
    2856              :          ELSE
    2857           20 :             eri_aa => active_space_env%eri%eri(1)%csr_mat
    2858           20 :             eri_ab => active_space_env%eri%eri(2)%csr_mat
    2859           20 :             eri_bb => active_space_env%eri%eri(3)%csr_mat
    2860              :             CALL build_subspace_spin_fock_matrix(active_space_env%active_orbitals, eri_aa, eri_ab, p_a_mat, p_b_mat, ks_a_ref, &
    2861              :                                                  tr_mixed_eri=.FALSE., comm_exchange=active_space_env%eri%comm_exchange, &
    2862           20 :                                                  restricted=restricted)
    2863              :             CALL build_subspace_spin_fock_matrix(active_space_env%active_orbitals, eri_bb, eri_ab, p_b_mat, p_a_mat, ks_b_ref, &
    2864              :                                                  tr_mixed_eri=.TRUE., comm_exchange=active_space_env%eri%comm_exchange, &
    2865           20 :                                                  restricted=restricted)
    2866              :          END IF
    2867              :          !
    2868              :          ! calculate energy
    2869           34 :          eeri = 0.0_dp
    2870         1460 :          eeri = 0.5_dp*(SUM(ks_a_ref*p_a_mat) + SUM(ks_b_ref*p_b_mat))
    2871         1460 :          esub = eref - SUM(ks_a_mat*p_a_mat) - SUM(ks_b_mat*p_b_mat) + eeri
    2872          730 :          ks_a_mat(:, :) = ks_a_mat(:, :) - ks_a_ref(:, :)
    2873          730 :          ks_b_mat(:, :) = ks_b_mat(:, :) - ks_b_ref(:, :)
    2874              :          !
    2875           34 :          active_space_env%energy_inactive = esub
    2876              :          !
    2877           34 :          CALL cp_fm_release(active_space_env%fock_sub)
    2878          170 :          ALLOCATE (active_space_env%fock_sub(nspins))
    2879          102 :          DO is = 1, nspins
    2880           68 :             matrix => active_space_env%ks_sub(is)
    2881              :             CALL cp_fm_create(active_space_env%fock_sub(is), matrix%matrix_struct, &
    2882          102 :                               name="Active Fock operator")
    2883              :          END DO
    2884              : 
    2885           34 :          matrix => active_space_env%fock_sub(1)
    2886          168 :          DO i1 = 1, norb
    2887          730 :             DO i2 = 1, norb
    2888          562 :                mval = ks_a_mat(i1, i2)
    2889          696 :                CALL cp_fm_set_element(matrix, i1, i2, mval)
    2890              :             END DO
    2891              :          END DO
    2892           34 :          matrix => active_space_env%fock_sub(2)
    2893          202 :          DO i1 = 1, norb
    2894          730 :             DO i2 = 1, norb
    2895          562 :                mval = ks_b_mat(i1, i2)
    2896          696 :                CALL cp_fm_set_element(matrix, i1, i2, mval)
    2897              :             END DO
    2898              :          END DO
    2899              : 
    2900              :       END IF
    2901              : 
    2902          132 :    END SUBROUTINE subspace_fock_matrix
    2903              : 
    2904              : ! **************************************************************************************************
    2905              : !> \brief build subspace fockian
    2906              : !> \param active_orbitals the active orbital indices
    2907              : !> \param eri two electon integrals in MO
    2908              : !> \param p_mat density matrix
    2909              : !> \param ks_ref fockian matrix
    2910              : !> \param comm_exchange ...
    2911              : ! **************************************************************************************************
    2912           98 :    SUBROUTINE build_subspace_fock_matrix(active_orbitals, eri, p_mat, ks_ref, comm_exchange)
    2913              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: active_orbitals
    2914              :       TYPE(dbcsr_csr_type), INTENT(IN)                   :: eri
    2915              :       REAL(dp), DIMENSION(:, :), INTENT(IN)              :: p_mat
    2916              :       REAL(dp), DIMENSION(:, :), INTENT(INOUT)           :: ks_ref
    2917              :       TYPE(mp_comm_type), INTENT(IN)                     :: comm_exchange
    2918              : 
    2919              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_subspace_fock_matrix'
    2920              : 
    2921              :       INTEGER                                            :: handle, i1, i12, i12l, i2, i3, i34, &
    2922              :                                                             i34l, i4, irptr, m1, m2, nindex, &
    2923              :                                                             nmo_total, norb
    2924              :       REAL(dp)                                           :: erint
    2925              :       TYPE(mp_comm_type)                                 :: mp_group
    2926              : 
    2927           98 :       CALL timeset(routineN, handle)
    2928              : 
    2929              :       ! Nothing to do
    2930           98 :       norb = SIZE(active_orbitals, 1)
    2931           98 :       nmo_total = SIZE(p_mat, 1)
    2932           98 :       nindex = (nmo_total*(nmo_total + 1))/2
    2933           98 :       CALL mp_group%set_handle(eri%mp_group%get_handle())
    2934          424 :       DO m1 = 1, norb
    2935          326 :          i1 = active_orbitals(m1, 1)
    2936         1264 :          DO m2 = m1, norb
    2937          840 :             i2 = active_orbitals(m2, 1)
    2938          840 :             i12 = csr_idx_to_combined(i1, i2, nmo_total)
    2939         1166 :             IF (MOD(i12 - 1, comm_exchange%num_pe) == comm_exchange%mepos) THEN
    2940          831 :                i12l = (i12 - 1)/comm_exchange%num_pe + 1
    2941          831 :                irptr = eri%rowptr_local(i12l) - 1
    2942         3430 :                DO i34l = 1, eri%nzerow_local(i12l)
    2943         2599 :                   i34 = eri%colind_local(irptr + i34l)
    2944         2599 :                   CALL csr_idx_from_combined(i34, nmo_total, i3, i4)
    2945         2599 :                   erint = eri%nzval_local%r_dp(irptr + i34l)
    2946              :                   ! Coulomb
    2947         2599 :                   ks_ref(i1, i2) = ks_ref(i1, i2) + erint*p_mat(i3, i4)
    2948         2599 :                   IF (i3 /= i4) THEN
    2949         1608 :                      ks_ref(i1, i2) = ks_ref(i1, i2) + erint*p_mat(i3, i4)
    2950              :                   END IF
    2951         2599 :                   IF (i12 /= i34) THEN
    2952         2179 :                      ks_ref(i3, i4) = ks_ref(i3, i4) + erint*p_mat(i1, i2)
    2953         2179 :                      IF (i1 /= i2) THEN
    2954         1566 :                         ks_ref(i3, i4) = ks_ref(i3, i4) + erint*p_mat(i1, i2)
    2955              :                      END IF
    2956              :                   END IF
    2957              :                   ! Exchange
    2958         2599 :                   erint = -0.5_dp*erint
    2959         2599 :                   ks_ref(i1, i3) = ks_ref(i1, i3) + erint*p_mat(i2, i4)
    2960         2599 :                   IF (i1 /= i2) THEN
    2961         1823 :                      ks_ref(i2, i3) = ks_ref(i2, i3) + erint*p_mat(i1, i4)
    2962              :                   END IF
    2963         2599 :                   IF (i3 /= i4) THEN
    2964         1608 :                      ks_ref(i1, i4) = ks_ref(i1, i4) + erint*p_mat(i2, i3)
    2965              :                   END IF
    2966         2599 :                   IF (i1 /= i2 .AND. i3 /= i4) THEN
    2967         1252 :                      ks_ref(i2, i4) = ks_ref(i2, i4) + erint*p_mat(i1, i3)
    2968              :                   END IF
    2969              :                   ! The stored integral represents both orders of unequal orbital pairs.
    2970         6029 :                   IF (i12 /= i34) THEN
    2971         2179 :                      ks_ref(i3, i1) = ks_ref(i3, i1) + erint*p_mat(i4, i2)
    2972         2179 :                      IF (i1 /= i2) THEN
    2973         1566 :                         ks_ref(i3, i2) = ks_ref(i3, i2) + erint*p_mat(i4, i1)
    2974              :                      END IF
    2975         2179 :                      IF (i3 /= i4) THEN
    2976         1351 :                         ks_ref(i4, i1) = ks_ref(i4, i1) + erint*p_mat(i3, i2)
    2977              :                      END IF
    2978         2179 :                      IF (i1 /= i2 .AND. i3 /= i4) THEN
    2979          995 :                         ks_ref(i4, i2) = ks_ref(i4, i2) + erint*p_mat(i3, i1)
    2980              :                      END IF
    2981              :                   END IF
    2982              :                END DO
    2983              :             END IF
    2984              :          END DO
    2985              :       END DO
    2986              :       !
    2987          424 :       DO m1 = 1, norb
    2988          326 :          i1 = active_orbitals(m1, 1)
    2989         1264 :          DO m2 = m1, norb
    2990          840 :             i2 = active_orbitals(m2, 1)
    2991         1166 :             ks_ref(i2, i1) = ks_ref(i1, i2)
    2992              :          END DO
    2993              :       END DO
    2994         4986 :       CALL mp_group%sum(ks_ref)
    2995              : 
    2996           98 :       CALL timestop(handle)
    2997              : 
    2998           98 :    END SUBROUTINE build_subspace_fock_matrix
    2999              : 
    3000              : ! **************************************************************************************************
    3001              : !> \brief build subspace fockian for unrestricted spins
    3002              : !> \param active_orbitals the active orbital indices
    3003              : !> \param eri_aa two electon integrals in MO with parallel spins
    3004              : !> \param eri_ab two electon integrals in MO with anti-parallel spins
    3005              : !> \param p_a_mat density matrix for up-spin
    3006              : !> \param p_b_mat density matrix for down-spin
    3007              : !> \param ks_a_ref fockian matrix for up-spin
    3008              : !> \param tr_mixed_eri boolean to indicate Coulomb interaction alignment
    3009              : !> \param comm_exchange ...
    3010              : !> \param restricted use the common, eightfold-symmetric ERIs for both spin densities
    3011              : ! **************************************************************************************************
    3012           68 :    SUBROUTINE build_subspace_spin_fock_matrix(active_orbitals, eri_aa, eri_ab, p_a_mat, p_b_mat, ks_a_ref, tr_mixed_eri, &
    3013              :                                               comm_exchange, restricted)
    3014              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: active_orbitals
    3015              :       TYPE(dbcsr_csr_type), INTENT(IN)                   :: eri_aa, eri_ab
    3016              :       REAL(dp), DIMENSION(:, :), INTENT(IN)              :: p_a_mat, p_b_mat
    3017              :       REAL(dp), DIMENSION(:, :), INTENT(INOUT)           :: ks_a_ref
    3018              :       LOGICAL, INTENT(IN)                                :: tr_mixed_eri
    3019              :       TYPE(mp_comm_type), INTENT(IN)                     :: comm_exchange
    3020              :       LOGICAL, INTENT(IN)                                :: restricted
    3021              : 
    3022              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_subspace_spin_fock_matrix'
    3023              : 
    3024              :       INTEGER                                            :: handle, i1, i12, i12l, i2, i3, i34, &
    3025              :                                                             i34l, i4, irptr, m1, m2, nindex, &
    3026              :                                                             nmo_total, norb, spin1, spin2
    3027              :       REAL(dp)                                           :: erint, p12, p34
    3028              :       TYPE(mp_comm_type)                                 :: mp_group
    3029              : 
    3030           68 :       CALL timeset(routineN, handle)
    3031              : 
    3032           68 :       norb = SIZE(active_orbitals, 1)
    3033           68 :       nmo_total = SIZE(p_a_mat, 1)
    3034           68 :       nindex = (nmo_total*(nmo_total + 1))/2
    3035           68 :       IF (tr_mixed_eri) THEN
    3036              :          spin1 = 2
    3037           68 :          spin2 = 1
    3038              :       ELSE
    3039           34 :          spin1 = 1
    3040           34 :          spin2 = 2
    3041              :       END IF
    3042          296 :       DO m1 = 1, norb
    3043          228 :          i1 = active_orbitals(m1, spin1)
    3044          816 :          DO m2 = m1, norb
    3045          520 :             i2 = active_orbitals(m2, spin1)
    3046          520 :             i12 = csr_idx_to_combined(i1, i2, nmo_total)
    3047          748 :             IF (MOD(i12 - 1, comm_exchange%num_pe) == comm_exchange%mepos) THEN
    3048          520 :                i12l = (i12 - 1)/comm_exchange%num_pe + 1
    3049          520 :                irptr = eri_aa%rowptr_local(i12l) - 1
    3050         1779 :                DO i34l = 1, eri_aa%nzerow_local(i12l)
    3051         1259 :                   i34 = eri_aa%colind_local(irptr + i34l)
    3052         1259 :                   CALL csr_idx_from_combined(i34, nmo_total, i3, i4)
    3053         1259 :                   erint = eri_aa%nzval_local%r_dp(irptr + i34l)
    3054              :                   ! Coulomb
    3055         1259 :                   p12 = p_a_mat(i1, i2)
    3056         1259 :                   p34 = p_a_mat(i3, i4)
    3057         1259 :                   IF (restricted) THEN
    3058          668 :                      p12 = p12 + p_b_mat(i1, i2)
    3059          668 :                      p34 = p34 + p_b_mat(i3, i4)
    3060              :                   END IF
    3061         1259 :                   IF (i1 /= i2) p12 = 2.0_dp*p12
    3062         1259 :                   IF (i3 /= i4) p34 = 2.0_dp*p34
    3063              :                   !F_ij += (ij|kl)*d_kl
    3064         1259 :                   ks_a_ref(i1, i2) = ks_a_ref(i1, i2) + erint*p34
    3065         1259 :                   IF (i12 /= i34) THEN
    3066              :                      !F_kl += (ij|kl)*d_ij
    3067          999 :                      ks_a_ref(i3, i4) = ks_a_ref(i3, i4) + erint*p12
    3068              :                   END IF
    3069              :                   ! Exchange
    3070         1259 :                   erint = -1.0_dp*erint
    3071              :                   !F_ik -= (ij|kl)*d_jl
    3072         1259 :                   ks_a_ref(i1, i3) = ks_a_ref(i1, i3) + erint*p_a_mat(i2, i4)
    3073         1259 :                   IF (i1 /= i2) THEN
    3074              :                      !F_jk -= (ij|kl)*d_il
    3075          773 :                      ks_a_ref(i2, i3) = ks_a_ref(i2, i3) + erint*p_a_mat(i1, i4)
    3076              :                   END IF
    3077         1259 :                   IF (i3 /= i4) THEN
    3078              :                      !F_il -= (ij|kl)*d_jk
    3079          688 :                      ks_a_ref(i1, i4) = ks_a_ref(i1, i4) + erint*p_a_mat(i2, i3)
    3080              :                   END IF
    3081         1259 :                   IF (i1 /= i2 .AND. i3 /= i4) THEN
    3082              :                      !F_jl -= (ij|kl)*d_ik
    3083          462 :                      ks_a_ref(i2, i4) = ks_a_ref(i2, i4) + erint*p_a_mat(i1, i3)
    3084              :                   END IF
    3085         3038 :                   IF (i12 /= i34) THEN
    3086          999 :                      ks_a_ref(i3, i1) = ks_a_ref(i3, i1) + erint*p_a_mat(i4, i2)
    3087          999 :                      IF (i1 /= i2) THEN
    3088          627 :                         ks_a_ref(i3, i2) = ks_a_ref(i3, i2) + erint*p_a_mat(i4, i1)
    3089              :                      END IF
    3090          999 :                      IF (i3 /= i4) THEN
    3091          542 :                         ks_a_ref(i4, i1) = ks_a_ref(i4, i1) + erint*p_a_mat(i3, i2)
    3092              :                      END IF
    3093          999 :                      IF (i1 /= i2 .AND. i3 /= i4) THEN
    3094          316 :                         ks_a_ref(i4, i2) = ks_a_ref(i4, i2) + erint*p_a_mat(i3, i1)
    3095              :                      END IF
    3096              :                   END IF
    3097              :                END DO
    3098              :             END IF
    3099              :          END DO
    3100              :       END DO
    3101              :       !
    3102              : 
    3103              :       ! Shared-orbital Coulomb contributions from both spins were included above.
    3104           68 :       IF (.NOT. restricted) THEN
    3105          164 :          DO m1 = 1, norb
    3106          124 :             i1 = active_orbitals(m1, 1)
    3107          432 :             DO m2 = m1, norb
    3108          268 :                i2 = active_orbitals(m2, 1)
    3109          268 :                i12 = csr_idx_to_combined(i1, i2, nmo_total)
    3110          392 :                IF (MOD(i12 - 1, comm_exchange%num_pe) == comm_exchange%mepos) THEN
    3111          268 :                   i12l = (i12 - 1)/comm_exchange%num_pe + 1
    3112          268 :                   irptr = eri_ab%rowptr_local(i12l) - 1
    3113         1310 :                   DO i34l = 1, eri_ab%nzerow_local(i12l)
    3114         1042 :                      i34 = eri_ab%colind_local(irptr + i34l)
    3115         1042 :                      CALL csr_idx_from_combined(i34, nmo_total, i3, i4)
    3116         1042 :                      erint = eri_ab%nzval_local%r_dp(irptr + i34l)
    3117              :                      ! Coulomb
    3118         1310 :                      IF (tr_mixed_eri) THEN
    3119              :                         !F_kl += (kl beta|ij alpha )*d_alpha_ij
    3120          521 :                         ks_a_ref(i3, i4) = ks_a_ref(i3, i4) + erint*p_b_mat(i1, i2)
    3121          521 :                         IF (i1 /= i2) ks_a_ref(i3, i4) = ks_a_ref(i3, i4) + erint*p_b_mat(i1, i2)
    3122              :                      ELSE
    3123              :                         !F_ij += (ij alpha|kl beta )*d_beta_kl
    3124          521 :                         ks_a_ref(i1, i2) = ks_a_ref(i1, i2) + erint*p_b_mat(i3, i4)
    3125          521 :                         IF (i3 /= i4) ks_a_ref(i1, i2) = ks_a_ref(i1, i2) + erint*p_b_mat(i3, i4)
    3126              :                      END IF
    3127              :                   END DO
    3128              :                END IF
    3129              :             END DO
    3130              :          END DO
    3131              :       END IF
    3132              :       !
    3133          296 :       DO m1 = 1, norb
    3134          228 :          i1 = active_orbitals(m1, spin1)
    3135          816 :          DO m2 = m1, norb
    3136          520 :             i2 = active_orbitals(m2, spin1)
    3137          748 :             ks_a_ref(i2, i1) = ks_a_ref(i1, i2)
    3138              :          END DO
    3139              :       END DO
    3140           68 :       CALL mp_group%set_handle(eri_aa%mp_group%get_handle())
    3141         2852 :       CALL mp_group%sum(ks_a_ref)
    3142              : 
    3143           68 :       CALL timestop(handle)
    3144              : 
    3145           68 :    END SUBROUTINE build_subspace_spin_fock_matrix
    3146              : 
    3147              : ! **************************************************************************************************
    3148              : !> \brief Creates a local basis
    3149              : !> \param pro_basis_set ...
    3150              : !> \param zval ...
    3151              : !> \param ishell ...
    3152              : !> \param nshell ...
    3153              : !> \param lnam ...
    3154              : !> \par History
    3155              : !>      05.2016 created [JGH]
    3156              : ! **************************************************************************************************
    3157            0 :    SUBROUTINE create_pro_basis(pro_basis_set, zval, ishell, nshell, lnam)
    3158              :       TYPE(gto_basis_set_type), POINTER                  :: pro_basis_set
    3159              :       INTEGER, INTENT(IN)                                :: zval, ishell
    3160              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: nshell
    3161              :       CHARACTER(len=*), DIMENSION(:), INTENT(IN)         :: lnam
    3162              : 
    3163            0 :       CHARACTER(len=6), DIMENSION(:), POINTER            :: sym
    3164              :       INTEGER                                            :: i, l, nj
    3165              :       INTEGER, DIMENSION(4, 7)                           :: ne
    3166            0 :       INTEGER, DIMENSION(:), POINTER                     :: lq, nq
    3167            0 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: zet
    3168              :       TYPE(sto_basis_set_type), POINTER                  :: sto_basis_set
    3169              : 
    3170            0 :       CPASSERT(.NOT. ASSOCIATED(pro_basis_set))
    3171            0 :       NULLIFY (sto_basis_set)
    3172              : 
    3173              :       ! electronic configuration
    3174            0 :       ne = 0
    3175            0 :       DO l = 1, 4 !lq(1)+1
    3176            0 :          nj = 2*(l - 1) + 1
    3177            0 :          DO i = l, 7 ! nq(1)
    3178            0 :             ne(l, i) = ptable(zval)%e_conv(l - 1) - 2*nj*(i - l)
    3179            0 :             ne(l, i) = MAX(ne(l, i), 0)
    3180            0 :             ne(l, i) = MIN(ne(l, i), 2*nj)
    3181              :          END DO
    3182              :       END DO
    3183            0 :       ALLOCATE (nq(ishell), lq(ishell), zet(ishell), sym(ishell))
    3184            0 :       DO i = 1, ishell
    3185            0 :          nq(i) = nshell(i)
    3186            0 :          SELECT CASE (lnam(i))
    3187              :          CASE ('S', 's')
    3188            0 :             lq(i) = 0
    3189              :          CASE ('P', 'p')
    3190            0 :             lq(i) = 1
    3191              :          CASE ('D', 'd')
    3192            0 :             lq(i) = 2
    3193              :          CASE ('F', 'f')
    3194            0 :             lq(i) = 3
    3195              :          CASE DEFAULT
    3196            0 :             CPABORT("Wrong l QN")
    3197              :          END SELECT
    3198            0 :          sym(i) = lnam(i)
    3199            0 :          zet(i) = srules(zval, ne, nq(1), lq(1))
    3200              :       END DO
    3201            0 :       CALL allocate_sto_basis_set(sto_basis_set)
    3202            0 :       CALL set_sto_basis_set(sto_basis_set, nshell=1, nq=nq, lq=lq, zet=zet, symbol=sym)
    3203            0 :       CALL create_gto_from_sto_basis(sto_basis_set, pro_basis_set, 6)
    3204            0 :       pro_basis_set%norm_type = 2
    3205            0 :       CALL init_orb_basis_set(pro_basis_set)
    3206            0 :       CALL deallocate_sto_basis_set(sto_basis_set)
    3207              : 
    3208            0 :    END SUBROUTINE create_pro_basis
    3209              : 
    3210              : ! **************************************************************************************************
    3211              : !> \brief Update the density matrix in AO basis with the active density contribution
    3212              : !> \param active_space_env the active space environment
    3213              : !> \param rho_ao the density matrix in AO basis
    3214              : ! **************************************************************************************************
    3215           22 :    SUBROUTINE update_density_ao(active_space_env, rho_ao)
    3216              :       TYPE(active_space_type), POINTER                   :: active_space_env
    3217              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: rho_ao
    3218              : 
    3219              :       INTEGER                                            :: ispin, nao, nmo, nspins
    3220              :       TYPE(cp_fm_type)                                   :: R, U
    3221              :       TYPE(cp_fm_type), POINTER                          :: C_active, p_active_mo
    3222              :       TYPE(dbcsr_type), POINTER                          :: p_inactive_ao
    3223           22 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos_active
    3224              : 
    3225              :       ! Transform the AS density matrix P_MO to the atomic orbital basis,
    3226              :       ! this is simply C * P_MO * C^T
    3227           22 :       nspins = active_space_env%nspins
    3228           22 :       mos_active => active_space_env%mos_active
    3229           58 :       DO ispin = 1, nspins
    3230              :          ! size of p_inactive_ao is (nao x nao)
    3231           36 :          p_inactive_ao => active_space_env%pmat_inactive(ispin)%matrix
    3232              : 
    3233              :          ! copy p_inactive_ao to rho_ao
    3234           36 :          CALL dbcsr_copy(rho_ao(ispin)%matrix, p_inactive_ao)
    3235              : 
    3236              :          ! size of p_active_mo is (nmo x nmo)
    3237           36 :          p_active_mo => active_space_env%p_active(ispin)
    3238              : 
    3239              :          ! calculate R = p_mo
    3240           36 :          CALL cp_fm_create(R, p_active_mo%matrix_struct)
    3241           36 :          CALL cp_fm_to_fm(p_active_mo, R)
    3242              : 
    3243              :          ! calculate U = C * p_mo
    3244           36 :          CALL get_mo_set(mos_active(ispin), mo_coeff=C_active, nao=nao, nmo=nmo)
    3245           36 :          CALL cp_fm_create(U, C_active%matrix_struct)
    3246           36 :          CALL parallel_gemm("N", "N", nao, nmo, nmo, 1.0_dp, C_active, R, 0.0_dp, U)
    3247              : 
    3248              :          CALL cp_dbcsr_plus_fm_fm_t(sparse_matrix=rho_ao(ispin)%matrix, &
    3249           36 :                                     matrix_v=U, matrix_g=C_active, ncol=nmo, alpha=1.0_dp)
    3250              : 
    3251           36 :          CALL cp_fm_release(R)
    3252          130 :          CALL cp_fm_release(U)
    3253              :       END DO
    3254              : 
    3255           22 :    END SUBROUTINE update_density_ao
    3256              : 
    3257              : ! **************************************************************************************************
    3258              : !> \brief Print each value on the master node
    3259              : !> \param this object reference
    3260              : !> \param i i-index
    3261              : !> \param j j-index
    3262              : !> \param k k-index
    3263              : !> \param l l-index
    3264              : !> \param val value of the integral at (i,j,k.l)
    3265              : !> \return always true to dump all integrals
    3266              : ! **************************************************************************************************
    3267         4876 :    LOGICAL FUNCTION eri_fcidump_print_func(this, i, j, k, l, val) RESULT(cont)
    3268              :       CLASS(eri_fcidump_print), INTENT(inout) :: this
    3269              :       INTEGER, INTENT(in)                     :: i, j, k, l
    3270              :       REAL(KIND=dp), INTENT(in)               :: val
    3271              : 
    3272              :       ! write to the actual file only on the master
    3273         4876 :       IF (this%unit_nr > 0) THEN
    3274         2438 :          WRITE (this%unit_nr, "(ES23.16,4I4)") val, i + this%bra_start - 1, j + this%bra_start - 1, &
    3275         4876 :               &                                     k + this%ket_start - 1, l + this%ket_start - 1
    3276              :          ! Each spatial integral is emitted once per permutation class.
    3277         2438 :          IF (MAX(i, j, k, l) <= this%nalpha) THEN
    3278           22 :             IF (i == j .AND. k == l) THEN
    3279            7 :                IF (i == k) THEN
    3280            4 :                   IF (i <= this%nbeta) this%determinant_energy = this%determinant_energy + val
    3281              :                ELSE
    3282              :                   this%determinant_energy = this%determinant_energy + &
    3283            7 :                                             MERGE(2, 1, i <= this%nbeta)*MERGE(2, 1, k <= this%nbeta)*val
    3284              :                END IF
    3285           15 :             ELSE IF (i == k .AND. j == l) THEN
    3286            6 :                this%determinant_energy = this%determinant_energy - MERGE(2, 1, MAX(i, j) <= this%nbeta)*val
    3287              :             END IF
    3288              :          END IF
    3289              :       END IF
    3290              : 
    3291         4876 :       cont = .TRUE.
    3292         4876 :    END FUNCTION eri_fcidump_print_func
    3293              : 
    3294              : ! **************************************************************************************************
    3295              : !> \brief checksum each value on the master node
    3296              : !> \param this object reference
    3297              : !> \param i i-index
    3298              : !> \param j j-index
    3299              : !> \param k k-index
    3300              : !> \param l l-index
    3301              : !> \param val value of the integral at (i,j,k.l)
    3302              : !> \return always true to dump all integrals
    3303              : ! **************************************************************************************************
    3304         4876 :    LOGICAL FUNCTION eri_fcidump_checksum_func(this, i, j, k, l, val) RESULT(cont)
    3305              :       CLASS(eri_fcidump_checksum), INTENT(inout) :: this
    3306              :       INTEGER, INTENT(in)                     :: i, j, k, l
    3307              :       REAL(KIND=dp), INTENT(in)               :: val
    3308              :       MARK_USED(i)
    3309              :       MARK_USED(j)
    3310              :       MARK_USED(k)
    3311              :       MARK_USED(l)
    3312              : 
    3313         4876 :       this%checksum = this%checksum + ABS(val)
    3314              : 
    3315         4876 :       cont = .TRUE.
    3316         4876 :    END FUNCTION eri_fcidump_checksum_func
    3317              : 
    3318              : ! **************************************************************************************************
    3319              : !> \brief Compute and print the AS rdm and the natural orbitals occupation numbers
    3320              : !> \param active_space_env active space environment
    3321              : !> \param iw output unit
    3322              : !> \author Stefano Battaglia
    3323              : ! **************************************************************************************************
    3324            6 :    SUBROUTINE print_pmat_noon(active_space_env, iw)
    3325              :       TYPE(active_space_type), POINTER                   :: active_space_env
    3326              :       INTEGER                                            :: iw
    3327              : 
    3328              :       INTEGER                                            :: i1, i2, ii, ispin, jm, m1, m2, &
    3329              :                                                             nmo_active, nspins
    3330            6 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: noon, pmat
    3331              :       TYPE(cp_fm_type), POINTER                          :: p_active
    3332              : 
    3333            6 :       nspins = active_space_env%nspins
    3334            6 :       nmo_active = active_space_env%nmo_active
    3335              : 
    3336           24 :       ALLOCATE (noon(nmo_active, nspins))
    3337           24 :       ALLOCATE (pmat(nmo_active, nmo_active))
    3338              : 
    3339           16 :       DO ispin = 1, nspins
    3340           10 :          p_active => active_space_env%p_active(ispin)
    3341           54 :          noon(:, ispin) = 0.0_dp
    3342           10 :          pmat = 0.0_dp
    3343              : 
    3344           54 :          DO i1 = 1, nmo_active
    3345           44 :             m1 = active_space_env%active_orbitals(i1, ispin)
    3346          254 :             DO i2 = 1, nmo_active
    3347          200 :                m2 = active_space_env%active_orbitals(i2, ispin)
    3348          244 :                CALL cp_fm_get_element(p_active, m1, m2, pmat(i1, i2))
    3349              :             END DO
    3350              :          END DO
    3351              : 
    3352           10 :          IF (iw > 0) THEN
    3353            5 :             WRITE (iw, '(/,T3,A,I2,A)') "Active space density matrix for spin ", ispin
    3354           27 :             DO i1 = 1, nmo_active
    3355           49 :                DO ii = 1, nmo_active, 8
    3356           22 :                   jm = MIN(7, nmo_active - ii)
    3357          144 :                   WRITE (iw, '(T3,6(F9.4))') (pmat(i1, ii + i2), i2=0, jm)
    3358              :                END DO
    3359              :             END DO
    3360              :          END IF
    3361              : 
    3362              :          ! diagonalize the density matrix
    3363           10 :          CALL diamat_all(pmat, noon(:, ispin))
    3364              : 
    3365           16 :          IF (iw > 0) THEN
    3366            5 :             WRITE (iw, '(/,T3,A,I2,A)') "Natural orbitals occupation numbers for spin ", ispin
    3367           10 :             DO i1 = 1, nmo_active, 8
    3368            5 :                jm = MIN(7, nmo_active - i1)
    3369              :                ! noons are stored in ascending order, so reverse-print them
    3370           32 :                WRITE (iw, '(T3,6(F9.4))') (noon(nmo_active - i1 - i2 + 1, ispin), i2=0, jm)
    3371              :             END DO
    3372              :          END IF
    3373              : 
    3374              :       END DO
    3375              : 
    3376            6 :       DEALLOCATE (noon)
    3377            6 :       DEALLOCATE (pmat)
    3378              : 
    3379            6 :    END SUBROUTINE print_pmat_noon
    3380              : 
    3381              : ! **************************************************************************************************
    3382              : !> \brief Run range-separated DFT embedding with the local FCI active-space solver.
    3383              : !> \param qs_env Quickstep environment
    3384              : !> \param active_space_env active-space environment
    3385              : !> \param as_input ACTIVE_SPACE input section
    3386              : ! **************************************************************************************************
    3387            6 :    SUBROUTINE local_fci_embedding(qs_env, active_space_env, as_input)
    3388              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3389              :       TYPE(active_space_type), POINTER                   :: active_space_env
    3390              :       TYPE(section_vals_type), POINTER                   :: as_input
    3391              : 
    3392              :       CHARACTER(len=*), PARAMETER :: routineN = 'local_fci_embedding'
    3393              : 
    3394              :       INTEGER                                            :: handle, iter, iw, max_iter
    3395              :       LOGICAL                                            :: converged, do_scf_embedding
    3396              :       REAL(KIND=dp)                                      :: delta_E, energy_corr, energy_new, &
    3397              :                                                             energy_old, energy_scf, eps_iter, t1, &
    3398              :                                                             t2
    3399            6 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: p_act_mo_a, p_act_mo_b
    3400              :       TYPE(cp_logger_type), POINTER                      :: logger
    3401            6 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: rho_ao
    3402              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3403              :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos_active
    3404              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3405              :       TYPE(qs_energy_type), POINTER                      :: energy
    3406              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    3407              :       TYPE(qs_rho_type), POINTER                         :: rho
    3408              : 
    3409            6 :       CALL timeset(routineN, handle)
    3410              : 
    3411            6 :       t1 = m_walltime()
    3412            6 :       logger => cp_get_default_logger()
    3413            6 :       iw = cp_logger_get_default_io_unit(logger)
    3414              : 
    3415            6 :       CALL get_qs_env(qs_env, para_env=para_env, dft_control=dft_control)
    3416              : 
    3417            6 :       CALL section_vals_val_get(as_input, "SCF_EMBEDDING", l_val=do_scf_embedding)
    3418            6 :       active_space_env%do_scf_embedding = do_scf_embedding
    3419            6 :       CALL section_vals_val_get(as_input, "MAX_ITER", i_val=max_iter)
    3420            6 :       IF (max_iter < 0) CPABORT("Specify a non-negative number of max iterations.")
    3421            6 :       CALL section_vals_val_get(as_input, "EPS_ITER", r_val=eps_iter)
    3422            6 :       IF (eps_iter < 0.0_dp) CPABORT("Specify a non-negative convergence threshold.")
    3423              : 
    3424            6 :       CALL get_qs_env(qs_env, rho=rho, energy=energy, ks_env=ks_env)
    3425            6 :       CALL qs_rho_get(rho, rho_ao=rho_ao)
    3426              : 
    3427            6 :       IF (iw > 0) THEN
    3428              :          WRITE (UNIT=iw, FMT="(/,T2,A,/)") &
    3429            3 :             "RANGE-SEPARATED DFT EMBEDDING WITH LIBFCI SOLVER"
    3430            3 :          WRITE (iw, '(T3,A,T68,I12)') "Max. iterations", max_iter
    3431            3 :          WRITE (iw, '(T3,A,T68,E12.4)') "Conv. threshold", eps_iter
    3432            3 :          WRITE (iw, '(T3,A,T68,A)') "Density mixer", TRIM(active_space_mixing_label(active_space_env))
    3433            3 :          WRITE (iw, '(T3,A,T66,F14.2)') "Mixing alpha", active_space_env%alpha
    3434              :          WRITE (UNIT=iw, FMT="(/,T3,A,T11,A,T21,A,T34,A,T55,A,T75,A,/,T3,A)") &
    3435            3 :             "Iter", "Update", "Time", "Corr. energy", "Total energy", "Change", REPEAT("-", 78)
    3436              :       END IF
    3437              : 
    3438            6 :       iter = 0
    3439            6 :       converged = .FALSE.
    3440            6 :       energy_scf = active_space_env%energy_ref
    3441            6 :       energy_new = energy_scf
    3442            6 :       mos_active => active_space_env%mos_active
    3443              : 
    3444           22 :       DO WHILE (iter < max_iter)
    3445           22 :          iter = iter + 1
    3446              : 
    3447           22 :          IF (active_space_env%nspins == 2) THEN
    3448           14 :             CALL solve_active_space_fci(active_space_env, para_env, p_act_mo_a, p_act_mo_b)
    3449           14 :             active_space_env%energy_total = active_space_env%energy_inactive + active_space_env%energy_active
    3450           14 :             CALL update_active_density(p_act_mo_a, active_space_env, p_act_mo_b)
    3451           14 :             DEALLOCATE (p_act_mo_a, p_act_mo_b)
    3452              :          ELSE
    3453            8 :             CALL solve_active_space_fci(active_space_env, para_env, p_act_mo_a)
    3454            8 :             active_space_env%energy_total = active_space_env%energy_inactive + active_space_env%energy_active
    3455            8 :             CALL update_active_density(p_act_mo_a, active_space_env)
    3456            8 :             DEALLOCATE (p_act_mo_a)
    3457              :          END IF
    3458              : 
    3459           22 :          energy_old = energy_new
    3460           22 :          energy_new = active_space_env%energy_total
    3461           22 :          energy_corr = energy_new - energy_scf
    3462           22 :          delta_E = energy_new - energy_old
    3463              : 
    3464           22 :          t2 = t1
    3465           22 :          t1 = m_walltime()
    3466           22 :          IF (iw > 0) THEN
    3467              :             WRITE (UNIT=iw, &
    3468              :                    FMT="(T3,I4,T11,A,T19,F6.1,T28,F18.10,T49,F18.10,T70,ES11.2)") &
    3469           11 :                iter, TRIM(active_space_mixing_label(active_space_env)), &
    3470           22 :                t1 - t2, energy_corr, energy_new, delta_E
    3471           11 :             CALL m_flush(iw)
    3472              :          END IF
    3473              : 
    3474           22 :          CALL update_density_ao(active_space_env, rho_ao)
    3475           22 :          CALL qs_rho_update_rho(rho, qs_env=qs_env)
    3476           22 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    3477           22 :          CALL evaluate_core_matrix_traces(qs_env)
    3478              :          CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., &
    3479              :                                            just_energy=.FALSE., &
    3480           22 :                                            ext_xc_section=active_space_env%xc_section)
    3481              : 
    3482           22 :          active_space_env%energy_ref = energy%total
    3483           22 :          CALL calculate_operators(mos_active, qs_env, active_space_env)
    3484           22 :          CALL subspace_fock_matrix(active_space_env, dft_control%roks)
    3485              : 
    3486           22 :          IF (.NOT. active_space_env%do_scf_embedding) THEN
    3487            0 :             IF (iw > 0) THEN
    3488              :                WRITE (UNIT=iw, FMT="(/,T3,A,I5,A)") &
    3489            0 :                   "*** one-shot embedding correction finished ***"
    3490              :             END IF
    3491              :             converged = .TRUE.
    3492              :             EXIT
    3493           22 :          ELSE IF (ABS(delta_E) <= eps_iter) THEN
    3494            6 :             IF (iw > 0) THEN
    3495              :                WRITE (UNIT=iw, FMT="(/,T3,A,I5,A)") &
    3496            3 :                   "*** rs-DFT embedding run converged in ", iter, " iteration(s) ***"
    3497              :             END IF
    3498              :             converged = .TRUE.
    3499              :             EXIT
    3500              :          END IF
    3501              :       END DO
    3502              : 
    3503              :       IF (.NOT. converged) THEN
    3504            0 :          IF (iw > 0) THEN
    3505              :             WRITE (UNIT=iw, FMT="(/,T3,A,I5,A)") &
    3506            0 :                "*** rs-DFT embedding did not converged after ", iter, " iteration(s) ***"
    3507              :          END IF
    3508              :       END IF
    3509              : 
    3510            6 :       energy%total = active_space_env%energy_total
    3511              : 
    3512            6 :       IF (iw > 0) THEN
    3513              :          WRITE (UNIT=iw, FMT="(/,T3,A)") &
    3514            3 :             "Final energy contributions:"
    3515              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3516            3 :             "Inactive energy:", active_space_env%energy_inactive
    3517              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3518            3 :             "Active energy:", active_space_env%energy_active
    3519              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3520            3 :             "Correlation energy:", energy_corr
    3521              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3522            3 :             "Total rs-DFT energy:", active_space_env%energy_total
    3523              :       END IF
    3524              : 
    3525            6 :       CALL print_pmat_noon(active_space_env, iw)
    3526            6 :       CALL para_env%sync()
    3527            6 :       CALL timestop(handle)
    3528              : 
    3529           12 :    END SUBROUTINE local_fci_embedding
    3530              : 
    3531              : ! **************************************************************************************************
    3532              : !> \brief ...
    3533              : !> \param qs_env ...
    3534              : !> \param active_space_env ...
    3535              : !> \param as_input ...
    3536              : ! **************************************************************************************************
    3537            0 :    SUBROUTINE rsdft_embedding(qs_env, active_space_env, as_input)
    3538              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3539              :       TYPE(active_space_type), POINTER                   :: active_space_env
    3540              :       TYPE(section_vals_type), POINTER                   :: as_input
    3541              : 
    3542              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'rsdft_embedding'
    3543              :       INTEGER                                            :: handle
    3544              : 
    3545              : #ifdef __NO_SOCKETS
    3546              :       CALL timeset(routineN, handle)
    3547              :       CPABORT("CP2K was compiled with the __NO_SOCKETS option!")
    3548              :       MARK_USED(qs_env)
    3549              :       MARK_USED(active_space_env)
    3550              :       MARK_USED(as_input)
    3551              : #else
    3552              : 
    3553              :       INTEGER                                            :: iw, client_fd, socket_fd, iter, max_iter
    3554              :       LOGICAL                                            :: converged, do_scf_embedding, ionode
    3555              :       REAL(KIND=dp)                                      :: delta_E, energy_corr, energy_new, &
    3556              :                                                             energy_old, energy_scf, eps_iter, t1, t2
    3557              :       TYPE(cp_logger_type), POINTER                      :: logger
    3558            0 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: rho_ao
    3559              :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos_active
    3560              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3561              :       TYPE(qs_energy_type), POINTER                      :: energy
    3562              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    3563              :       TYPE(qs_rho_type), POINTER                         :: rho
    3564              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3565              : 
    3566            0 :       CALL timeset(routineN, handle)
    3567              : 
    3568            0 :       t1 = m_walltime()
    3569              : 
    3570            0 :       logger => cp_get_default_logger()
    3571            0 :       iw = cp_logger_get_default_io_unit(logger)
    3572              : 
    3573            0 :       CALL get_qs_env(qs_env, para_env=para_env, dft_control=dft_control)
    3574            0 :       ionode = para_env%is_source()
    3575              : 
    3576              :       ! get info from the input
    3577            0 :       CALL section_vals_val_get(as_input, "SCF_EMBEDDING", l_val=do_scf_embedding)
    3578            0 :       active_space_env%do_scf_embedding = do_scf_embedding
    3579            0 :       CALL section_vals_val_get(as_input, "MAX_ITER", i_val=max_iter)
    3580            0 :       IF (max_iter < 0) CPABORT("Specify a non-negative number of max iterations.")
    3581            0 :       CALL section_vals_val_get(as_input, "EPS_ITER", r_val=eps_iter)
    3582            0 :       IF (eps_iter < 0.0_dp) CPABORT("Specify a non-negative convergence threshold.")
    3583              : 
    3584              :       ! create the socket and wait for the client to connect
    3585            0 :       CALL initialize_socket(socket_fd, client_fd, as_input, ionode)
    3586            0 :       CALL para_env%sync()
    3587              : 
    3588              :       ! send two-electron integrals to the client
    3589            0 :       CALL send_eri_to_client(client_fd, active_space_env, para_env)
    3590              : 
    3591              :       ! get pointer to density in ao basis
    3592            0 :       CALL get_qs_env(qs_env, rho=rho, energy=energy, ks_env=ks_env)
    3593            0 :       CALL qs_rho_get(rho, rho_ao=rho_ao)
    3594              : 
    3595            0 :       IF (iw > 0) THEN
    3596              :          WRITE (UNIT=iw, FMT="(/,T2,A,/)") &
    3597            0 :             "RANGE-SEPARATED DFT EMBEDDING SELF-CONSISTENT OPTIMIZATION"
    3598              : 
    3599            0 :          WRITE (iw, '(T3,A,T68,I12)') "Max. iterations", max_iter
    3600            0 :          WRITE (iw, '(T3,A,T68,E12.4)') "Conv. threshold", eps_iter
    3601            0 :          WRITE (iw, '(T3,A,T68,A)') "Density mixer", TRIM(active_space_mixing_label(active_space_env))
    3602            0 :          WRITE (iw, '(T3,A,T66,F14.2)') "Mixing alpha", active_space_env%alpha
    3603              : 
    3604              :          WRITE (UNIT=iw, FMT="(/,T3,A,T11,A,T21,A,T34,A,T55,A,T75,A,/,T3,A)") &
    3605            0 :             "Iter", "Update", "Time", "Corr. energy", "Total energy", "Change", REPEAT("-", 78)
    3606              :       END IF
    3607              :       ! TODO: consider using an iteration level
    3608              : 
    3609            0 :       iter = 0
    3610            0 :       converged = .FALSE.
    3611              :       ! store the scf energy
    3612            0 :       energy_scf = active_space_env%energy_ref
    3613            0 :       energy_new = energy_scf
    3614            0 :       mos_active => active_space_env%mos_active
    3615              :       ! CALL set_qs_env(qs_env, active_space=active_space_env)
    3616              : 
    3617              :       ! start the self-consistent embedding loop
    3618            0 :       DO WHILE (iter < max_iter)
    3619            0 :          iter = iter + 1
    3620              : 
    3621              :          ! send V_emb and E_ina to the active space solver and update
    3622              :          ! the active space environment with the new active energy and density
    3623            0 :          CALL send_fock_to_client(client_fd, active_space_env, para_env)
    3624              : 
    3625              :          ! update energies
    3626            0 :          energy_old = energy_new
    3627            0 :          energy_new = active_space_env%energy_total
    3628            0 :          energy_corr = energy_new - energy_scf
    3629            0 :          delta_E = energy_new - energy_old
    3630              : 
    3631              :          ! get timer
    3632            0 :          t2 = t1
    3633            0 :          t1 = m_walltime()
    3634              :          ! print out progress
    3635            0 :          IF ((iw > 0)) THEN
    3636              :             WRITE (UNIT=iw, &
    3637              :                    FMT="(T3,I4,T11,A,T19,F6.1,T28,F18.10,T49,F18.10,T70,ES11.2)") &
    3638            0 :                iter, TRIM(active_space_mixing_label(active_space_env)), &
    3639            0 :                t1 - t2, energy_corr, energy_new, delta_E
    3640            0 :             CALL m_flush(iw)
    3641              :          END IF
    3642              : 
    3643              :          ! update total density in AO basis with the AS contribution
    3644            0 :          CALL update_density_ao(active_space_env, rho_ao) ! rho_ao is updated
    3645              : 
    3646              :          ! calculate F_ks in AO basis (which contains Vxc) with the new density
    3647            0 :          CALL qs_rho_update_rho(rho, qs_env=qs_env) ! updates rho_r and rho_g using rho_ao
    3648            0 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.) ! set flags about the change
    3649              :          ! Re-evaluate the traces between the density matrix and the core Hamiltonians
    3650            0 :          CALL evaluate_core_matrix_traces(qs_env)
    3651              :          ! the ks matrix will be rebuilt so this is fine now
    3652              :          ! CALL set_ks_env(qs_env%ks_env, potential_changed=.FALSE.)
    3653              :          CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., &
    3654              :                                            just_energy=.FALSE., &
    3655            0 :                                            ext_xc_section=active_space_env%xc_section)
    3656              : 
    3657              :          ! update the reference energy
    3658            0 :          active_space_env%energy_ref = energy%total
    3659              : 
    3660              :          ! transform KS/Fock, Vxc and Hcore from AO to MO basis
    3661            0 :          CALL calculate_operators(mos_active, qs_env, active_space_env)
    3662              : 
    3663              :          ! calculate the new inactive energy and embedding potential
    3664            0 :          CALL subspace_fock_matrix(active_space_env, dft_control%roks)
    3665              : 
    3666              :          ! check if it is a one-shot correction
    3667            0 :          IF (.NOT. active_space_env%do_scf_embedding) THEN
    3668            0 :             IF (iw > 0) THEN
    3669              :                WRITE (UNIT=iw, FMT="(/,T3,A,I5,A)") &
    3670            0 :                   "*** one-shot embedding correction finished ***"
    3671              :             END IF
    3672              :             converged = .TRUE.
    3673              :             EXIT
    3674              :             ! check for convergence
    3675            0 :          ELSE IF (ABS(delta_E) <= eps_iter) THEN
    3676            0 :             IF (iw > 0) THEN
    3677              :                WRITE (UNIT=iw, FMT="(/,T3,A,I5,A)") &
    3678            0 :                   "*** rs-DFT embedding run converged in ", iter, " iteration(s) ***"
    3679              :             END IF
    3680              :             converged = .TRUE.
    3681              :             EXIT
    3682              :          END IF
    3683              :       END DO
    3684              : 
    3685              :       IF (.NOT. converged) THEN
    3686            0 :          IF (iw > 0) THEN
    3687              :             WRITE (UNIT=iw, FMT="(/,T3,A,I5,A)") &
    3688            0 :                "*** rs-DFT embedding did not converged after ", iter, " iteration(s) ***"
    3689              :          END IF
    3690              :       END IF
    3691              : 
    3692              :       ! update qs total energy to the final rs-DFT energy
    3693            0 :       energy%total = active_space_env%energy_total
    3694              : 
    3695              :       ! print final energy contributions
    3696            0 :       IF (iw > 0) THEN
    3697              :          WRITE (UNIT=iw, FMT="(/,T3,A)") &
    3698            0 :             "Final energy contributions:"
    3699              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3700            0 :             "Inactive energy:", active_space_env%energy_inactive
    3701              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3702            0 :             "Active energy:", active_space_env%energy_active
    3703              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3704            0 :             "Correlation energy:", energy_corr
    3705              :          WRITE (UNIT=iw, FMT="(T6,A,T56,F20.10)") &
    3706            0 :             "Total rs-DFT energy:", active_space_env%energy_total
    3707              :       END IF
    3708              : 
    3709              :       ! print the AS rdm and the natural orbital occupation numbers
    3710            0 :       CALL print_pmat_noon(active_space_env, iw)
    3711              : 
    3712            0 :       CALL finalize_socket(socket_fd, client_fd, as_input, ionode)
    3713            0 :       CALL para_env%sync()
    3714              : #endif
    3715              : 
    3716            0 :       CALL timestop(handle)
    3717              : 
    3718            0 :    END SUBROUTINE rsdft_embedding
    3719              : 
    3720              : #ifndef __NO_SOCKETS
    3721              : ! **************************************************************************************************
    3722              : !> \brief Creates the socket, spawns the client and connects to it
    3723              : !> \param socket_fd the socket file descriptor
    3724              : !> \param client_fd the client file descriptor
    3725              : !> \param as_input active space inpute section
    3726              : !> \param ionode logical flag indicating if the process is the master
    3727              : ! **************************************************************************************************
    3728            0 :    SUBROUTINE initialize_socket(socket_fd, client_fd, as_input, ionode)
    3729              :       INTEGER, INTENT(OUT)                               :: socket_fd, client_fd
    3730              :       TYPE(section_vals_type), INTENT(IN), POINTER       :: as_input
    3731              :       LOGICAL, INTENT(IN)                                :: ionode
    3732              : 
    3733              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'initialize_socket'
    3734              :       INTEGER, PARAMETER                                 :: backlog = 10
    3735              : 
    3736              :       CHARACTER(len=default_path_length)                 :: hostname
    3737              :       INTEGER                                            :: handle, iw, port, protocol
    3738              :       LOGICAL                                            :: inet
    3739              :       TYPE(cp_logger_type), POINTER                      :: logger
    3740              : 
    3741            0 :       CALL timeset(routineN, handle)
    3742              : 
    3743            0 :       logger => cp_get_default_logger()
    3744            0 :       iw = cp_logger_get_default_io_unit(logger)
    3745              : 
    3746              :       ! protocol == 0 for UNIX, protocol > 0 for INET
    3747            0 :       CALL section_vals_val_get(as_input, "SOCKET%INET", l_val=inet)
    3748            0 :       IF (inet) THEN
    3749            0 :          protocol = 1
    3750              :       ELSE
    3751            0 :          protocol = 0
    3752              :       END IF
    3753            0 :       CALL section_vals_val_get(as_input, "SOCKET%HOST", c_val=hostname)
    3754            0 :       CALL section_vals_val_get(as_input, "SOCKET%PORT", i_val=port)
    3755              : 
    3756            0 :       IF (ionode) THEN
    3757            0 :          CALL open_bind_socket(socket_fd, protocol, port, TRIM(hostname)//C_NULL_CHAR)
    3758            0 :          WRITE (iw, '(/,T2,A,A)') "@SERVER: Created socket with address ", TRIM(hostname)
    3759            0 :          CALL listen_socket(socket_fd, backlog)
    3760              : 
    3761              :          ! wait until a connetion request arrives
    3762            0 :          WRITE (iw, '(T2,A)') "@SERVER: Waiting for requests..."
    3763            0 :          CALL accept_socket(socket_fd, client_fd)
    3764            0 :          WRITE (iw, '(T2,A,I2)') "@SERVER: Accepted socket with fd ", client_fd
    3765              :       END IF
    3766              : 
    3767            0 :       CALL timestop(handle)
    3768              : 
    3769            0 :    END SUBROUTINE initialize_socket
    3770              : 
    3771              : ! **************************************************************************************************
    3772              : !> \brief Closes the connection to the socket and deletes the file
    3773              : !> \param socket_fd the socket file descriptor
    3774              : !> \param client_fd the client file descriptor
    3775              : !> \param as_input active space inpute section
    3776              : !> \param ionode logical flag indicating if the process is the master
    3777              : ! **************************************************************************************************
    3778            0 :    SUBROUTINE finalize_socket(socket_fd, client_fd, as_input, ionode)
    3779              :       INTEGER, INTENT(IN)                                :: socket_fd, client_fd
    3780              :       TYPE(section_vals_type), INTENT(IN), POINTER       :: as_input
    3781              :       LOGICAL, INTENT(IN)                                :: ionode
    3782              : 
    3783              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'finalize_socket'
    3784              :       INTEGER, PARAMETER                                 :: header_len = 12
    3785              : 
    3786              :       CHARACTER(len=default_path_length)                 :: hostname
    3787              :       INTEGER                                            :: handle
    3788              : 
    3789            0 :       CALL timeset(routineN, handle)
    3790              : 
    3791            0 :       CALL section_vals_val_get(as_input, "SOCKET%HOST", c_val=hostname)
    3792              : 
    3793            0 :       IF (ionode) THEN
    3794              :          ! signal the client to quit
    3795            0 :          CALL writebuffer(client_fd, "QUIT        ", header_len)
    3796              :          ! close the connection
    3797            0 :          CALL close_socket(client_fd)
    3798            0 :          CALL close_socket(socket_fd)
    3799              : 
    3800              :          ! delete the socket file
    3801            0 :          IF (file_exists(TRIM(hostname))) THEN
    3802            0 :             CALL remove_socket_file(TRIM(hostname)//C_NULL_CHAR)
    3803              :          END IF
    3804              :       END IF
    3805              : 
    3806            0 :       CALL timestop(handle)
    3807              : 
    3808            0 :    END SUBROUTINE finalize_socket
    3809              : 
    3810              : ! **************************************************************************************************
    3811              : !> \brief Sends the two-electron integrals to the client vie the socket
    3812              : !> \param client_fd the client file descriptor
    3813              : !> \param active_space_env active space environment
    3814              : !> \param para_env parallel environment
    3815              : ! **************************************************************************************************
    3816            0 :    SUBROUTINE send_eri_to_client(client_fd, active_space_env, para_env)
    3817              :       INTEGER, INTENT(IN)                                :: client_fd
    3818              :       TYPE(active_space_type), INTENT(IN), POINTER       :: active_space_env
    3819              :       TYPE(mp_para_env_type), INTENT(IN), POINTER        :: para_env
    3820              : 
    3821              :       CHARACTER(len=*), PARAMETER :: routineN = 'send_eri_to_client'
    3822              :       INTEGER, PARAMETER                                 :: header_len = 12
    3823              : 
    3824              :       CHARACTER(len=default_string_length)               :: header
    3825              :       INTEGER                                            :: handle, iw
    3826              :       LOGICAL                                            :: ionode, restricted_orbitals
    3827            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eri_aa, eri_ab, eri_bb, s_ab
    3828              :       TYPE(cp_logger_type), POINTER                      :: logger
    3829              : 
    3830            0 :       CALL timeset(routineN, handle)
    3831              : 
    3832            0 :       logger => cp_get_default_logger()
    3833            0 :       iw = cp_logger_get_default_io_unit(logger)
    3834            0 :       ionode = para_env%is_source()
    3835            0 :       restricted_orbitals = active_space_env%restricted_orbitals
    3836              : 
    3837            0 :       ALLOCATE (eri_aa(active_space_env%nmo_active**4))
    3838            0 :       CALL eri_to_array(active_space_env%eri, eri_aa, active_space_env%active_orbitals, 1, 1)
    3839            0 :       IF (active_space_env%nspins == 2) THEN
    3840            0 :          ALLOCATE (eri_ab(active_space_env%nmo_active**4))
    3841            0 :          ALLOCATE (eri_bb(active_space_env%nmo_active**4))
    3842            0 :          IF (restricted_orbitals) THEN
    3843            0 :             eri_ab(:) = eri_aa
    3844            0 :             eri_bb(:) = eri_aa
    3845              :          ELSE
    3846            0 :             CALL eri_to_array(active_space_env%eri, eri_ab, active_space_env%active_orbitals, 1, 2)
    3847            0 :             CALL eri_to_array(active_space_env%eri, eri_bb, active_space_env%active_orbitals, 2, 2)
    3848              :          END IF
    3849              :          ! get the overlap_ab matrix into Fortran array
    3850            0 :          ALLOCATE (s_ab(active_space_env%nmo_active**2))
    3851              :          ASSOCIATE (act_indices_a => active_space_env%active_orbitals(:, 1), &
    3852              :                     act_indices_b => active_space_env%active_orbitals(:, 2))
    3853            0 :             CALL subspace_matrix_to_array(active_space_env%sab_sub(1), s_ab, act_indices_a, act_indices_b)
    3854              :          END ASSOCIATE
    3855              :       END IF
    3856              : 
    3857              :       ! ask the status of the client
    3858            0 :       IF (ionode) CALL writebuffer(client_fd, "STATUS      ", header_len)
    3859              :       DO
    3860            0 :          header = ""
    3861            0 :          CALL para_env%sync()
    3862            0 :          IF (ionode) THEN
    3863              :             ! IF (iw > 0) WRITE(iw, *) "@SERVER: Waiting for messages..."
    3864            0 :             CALL readbuffer(client_fd, header, header_len)
    3865              :          END IF
    3866            0 :          CALL para_env%bcast(header, para_env%source)
    3867              : 
    3868              :          ! IF (iw > 0) WRITE(iw, *) "@SERVER: Message from client: ", TRIM(header)
    3869              : 
    3870            0 :          IF (TRIM(header) == "READY") THEN
    3871              :             ! if the client is ready, send the data
    3872            0 :             CALL para_env%sync()
    3873            0 :             IF (ionode) THEN
    3874            0 :                CALL writebuffer(client_fd, "TWOBODY     ", header_len)
    3875            0 :                CALL writebuffer(client_fd, active_space_env%nspins)
    3876            0 :                CALL writebuffer(client_fd, active_space_env%nmo_active)
    3877            0 :                CALL writebuffer(client_fd, active_space_env%nelec_active)
    3878            0 :                CALL writebuffer(client_fd, active_space_env%multiplicity)
    3879              :                ! send the alpha component
    3880            0 :                CALL writebuffer(client_fd, eri_aa, SIZE(eri_aa))
    3881              :                ! send the beta part for unrestricted calculations
    3882            0 :                IF (active_space_env%nspins == 2) THEN
    3883            0 :                   CALL writebuffer(client_fd, eri_ab, SIZE(eri_ab))
    3884            0 :                   CALL writebuffer(client_fd, eri_bb, SIZE(eri_bb))
    3885            0 :                   CALL writebuffer(client_fd, s_ab, SIZE(s_ab))
    3886              :                END IF
    3887              :             END IF
    3888            0 :          ELSE IF (TRIM(header) == "RECEIVED") THEN
    3889              :             EXIT
    3890              :          END IF
    3891              :       END DO
    3892              : 
    3893            0 :       DEALLOCATE (eri_aa)
    3894            0 :       IF (active_space_env%nspins == 2) THEN
    3895            0 :          DEALLOCATE (eri_ab)
    3896            0 :          DEALLOCATE (eri_bb)
    3897            0 :          DEALLOCATE (s_ab)
    3898              :       END IF
    3899              : 
    3900            0 :       CALL para_env%sync()
    3901              : 
    3902            0 :       CALL timestop(handle)
    3903              : 
    3904            0 :    END SUBROUTINE send_eri_to_client
    3905              : 
    3906              : ! **************************************************************************************************
    3907              : !> \brief Sends the one-electron embedding potential and the inactive energy to the client
    3908              : !> \param client_fd the client file descriptor
    3909              : !> \param active_space_env active space environment
    3910              : !> \param para_env parallel environment
    3911              : ! **************************************************************************************************
    3912            0 :    SUBROUTINE send_fock_to_client(client_fd, active_space_env, para_env)
    3913              :       INTEGER, INTENT(IN)                                :: client_fd
    3914              :       TYPE(active_space_type), INTENT(INOUT), POINTER    :: active_space_env
    3915              :       TYPE(mp_para_env_type), INTENT(IN), POINTER        :: para_env
    3916              : 
    3917              :       CHARACTER(len=*), PARAMETER :: routineN = 'send_fock_to_client'
    3918              :       INTEGER, PARAMETER                                 :: header_len = 12
    3919              : 
    3920              :       CHARACTER(len=default_string_length)               :: header
    3921              :       INTEGER                                            :: handle, iw
    3922              :       LOGICAL                                            :: debug, ionode
    3923            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: fock_a, fock_b, p_act_mo_a, p_act_mo_b
    3924              :       TYPE(cp_logger_type), POINTER                      :: logger
    3925              : 
    3926            0 :       CALL timeset(routineN, handle)
    3927              : 
    3928              :       ! Set to .TRUE. to activate debug output
    3929            0 :       debug = .FALSE.
    3930              : 
    3931            0 :       logger => cp_get_default_logger()
    3932            0 :       iw = cp_logger_get_default_io_unit(logger)
    3933            0 :       ionode = para_env%is_source()
    3934              : 
    3935            0 :       ALLOCATE (p_act_mo_a(active_space_env%nmo_active**2))
    3936            0 :       ALLOCATE (fock_a(active_space_env%nmo_active**2))
    3937            0 :       IF (active_space_env%nspins == 2) THEN
    3938            0 :          ALLOCATE (p_act_mo_b(active_space_env%nmo_active**2))
    3939            0 :          ALLOCATE (fock_b(active_space_env%nmo_active**2))
    3940              :       END IF
    3941              : 
    3942              :       ! get the fock matrix into Fortran arrays
    3943              :       ASSOCIATE (act_indices => active_space_env%active_orbitals(:, 1))
    3944            0 :          CALL subspace_matrix_to_array(active_space_env%fock_sub(1), fock_a, act_indices, act_indices)
    3945              :       END ASSOCIATE
    3946              : 
    3947            0 :       IF (active_space_env%nspins == 2) THEN
    3948              :          ASSOCIATE (act_indices => active_space_env%active_orbitals(:, 2))
    3949            0 :             CALL subspace_matrix_to_array(active_space_env%fock_sub(2), fock_b, act_indices, act_indices)
    3950              :          END ASSOCIATE
    3951              :       END IF
    3952              : 
    3953              :       ! ask the status of the client
    3954            0 :       IF (ionode) CALL writebuffer(client_fd, "STATUS      ", header_len)
    3955              :       DO
    3956            0 :          header = ""
    3957              : 
    3958            0 :          CALL para_env%sync()
    3959            0 :          IF (ionode) THEN
    3960              :             IF (debug .AND. iw > 0) WRITE (iw, *) "@SERVER: Waiting for messages..."
    3961            0 :             CALL readbuffer(client_fd, header, header_len)
    3962              :          END IF
    3963            0 :          CALL para_env%bcast(header, para_env%source)
    3964              : 
    3965              :          IF (debug .AND. iw > 0) WRITE (iw, *) "@SERVER: Message from client: ", TRIM(header)
    3966              : 
    3967            0 :          IF (TRIM(header) == "READY") THEN
    3968              :             ! if the client is ready, send the data
    3969            0 :             CALL para_env%sync()
    3970            0 :             IF (ionode) THEN
    3971            0 :                CALL writebuffer(client_fd, "ONEBODY     ", header_len)
    3972            0 :                CALL writebuffer(client_fd, active_space_env%energy_inactive)
    3973              :                ! send the alpha component
    3974            0 :                CALL writebuffer(client_fd, fock_a, SIZE(fock_a))
    3975              :                ! send the beta part for unrestricted calculations
    3976            0 :                IF (active_space_env%nspins == 2) THEN
    3977            0 :                   CALL writebuffer(client_fd, fock_b, SIZE(fock_b))
    3978              :                END IF
    3979              :             END IF
    3980              : 
    3981            0 :          ELSE IF (TRIM(header) == "HAVEDATA") THEN
    3982              :             ! qiskit has data to transfer, let them know we want it and wait for it
    3983            0 :             CALL para_env%sync()
    3984            0 :             IF (ionode) THEN
    3985              :                IF (debug .AND. iw > 0) WRITE (iw, *) "@SERVER: Qiskit has data to transfer"
    3986            0 :                CALL writebuffer(client_fd, "GETDENSITY  ", header_len)
    3987              : 
    3988              :                ! read the active energy and density
    3989            0 :                CALL readbuffer(client_fd, active_space_env%energy_active)
    3990            0 :                CALL readbuffer(client_fd, p_act_mo_a, SIZE(p_act_mo_a))
    3991            0 :                IF (active_space_env%nspins == 2) THEN
    3992            0 :                   CALL readbuffer(client_fd, p_act_mo_b, SIZE(p_act_mo_b))
    3993              :                END IF
    3994              :             END IF
    3995              : 
    3996              :             ! broadcast the data to all processors
    3997            0 :             CALL para_env%bcast(active_space_env%energy_active, para_env%source)
    3998            0 :             CALL para_env%bcast(p_act_mo_a, para_env%source)
    3999            0 :             IF (active_space_env%nspins == 2) THEN
    4000            0 :                CALL para_env%bcast(p_act_mo_b, para_env%source)
    4001              :             END IF
    4002              : 
    4003              :             ! update total and reference energies in active space enviornment
    4004            0 :             active_space_env%energy_total = active_space_env%energy_inactive + active_space_env%energy_active
    4005              : 
    4006              :             ! update the active density matrix in the active space environment
    4007            0 :             IF (active_space_env%nspins == 2) THEN
    4008            0 :                CALL update_active_density(p_act_mo_a, active_space_env, p_act_mo_b)
    4009              :             ELSE
    4010            0 :                CALL update_active_density(p_act_mo_a, active_space_env)
    4011              :             END IF
    4012              : 
    4013              :             ! the non-iterative part is done, we can continue
    4014              :             EXIT
    4015              :          END IF
    4016              : 
    4017              :       END DO
    4018              : 
    4019            0 :       DEALLOCATE (p_act_mo_a)
    4020            0 :       DEALLOCATE (fock_a)
    4021            0 :       IF (active_space_env%nspins == 2) THEN
    4022            0 :          DEALLOCATE (p_act_mo_b)
    4023            0 :          DEALLOCATE (fock_b)
    4024              :       END IF
    4025              : 
    4026            0 :       CALL para_env%sync()
    4027              : 
    4028            0 :       CALL timestop(handle)
    4029              : 
    4030            0 :    END SUBROUTINE send_fock_to_client
    4031              : #endif
    4032              : 
    4033            0 : END MODULE qs_active_space_methods
        

Generated by: LCOV version 2.0-1