LCOV - code coverage report
Current view: top level - src - qs_scf_post_gpw.F (source / functions) Hit Total Coverage
Test: CP2K Regtests (git:b8e0b09) Lines: 1344 1521 88.4 %
Date: 2024-08-31 06:31:37 Functions: 23 23 100.0 %

          Line data    Source code
       1             : !--------------------------------------------------------------------------------------------------!
       2             : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3             : !   Copyright 2000-2024 CP2K developers group <https://cp2k.org>                                   !
       4             : !                                                                                                  !
       5             : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6             : !--------------------------------------------------------------------------------------------------!
       7             : 
       8             : ! **************************************************************************************************
       9             : !> \brief Does all kind of post scf calculations for GPW/GAPW
      10             : !> \par History
      11             : !>      Started as a copy from the relevant part of qs_scf
      12             : !>      Start to adapt for k-points [07.2015, JGH]
      13             : !> \author Joost VandeVondele (10.2003)
      14             : ! **************************************************************************************************
      15             : MODULE qs_scf_post_gpw
      16             :    USE admm_types,                      ONLY: admm_type
      17             :    USE admm_utils,                      ONLY: admm_correct_for_eigenvalues,&
      18             :                                               admm_uncorrect_for_eigenvalues
      19             :    USE ai_onecenter,                    ONLY: sg_overlap
      20             :    USE atom_kind_orbitals,              ONLY: calculate_atomic_density
      21             :    USE atomic_kind_types,               ONLY: atomic_kind_type,&
      22             :                                               get_atomic_kind
      23             :    USE basis_set_types,                 ONLY: gto_basis_set_p_type,&
      24             :                                               gto_basis_set_type
      25             :    USE cell_types,                      ONLY: cell_type
      26             :    USE cp_array_utils,                  ONLY: cp_1d_r_p_type
      27             :    USE cp_blacs_env,                    ONLY: cp_blacs_env_type
      28             :    USE cp_control_types,                ONLY: dft_control_type
      29             :    USE cp_dbcsr_api,                    ONLY: dbcsr_add,&
      30             :                                               dbcsr_p_type,&
      31             :                                               dbcsr_type
      32             :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      33             :                                               dbcsr_deallocate_matrix_set
      34             :    USE cp_dbcsr_output,                 ONLY: cp_dbcsr_write_sparse_matrix
      35             :    USE cp_ddapc_util,                   ONLY: get_ddapc
      36             :    USE cp_fm_diag,                      ONLY: choose_eigv_solver
      37             :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      38             :                                               cp_fm_struct_release,&
      39             :                                               cp_fm_struct_type
      40             :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      41             :                                               cp_fm_get_info,&
      42             :                                               cp_fm_init_random,&
      43             :                                               cp_fm_release,&
      44             :                                               cp_fm_to_fm,&
      45             :                                               cp_fm_type
      46             :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      47             :                                               cp_logger_get_default_io_unit,&
      48             :                                               cp_logger_type,&
      49             :                                               cp_to_string
      50             :    USE cp_output_handling,              ONLY: cp_p_file,&
      51             :                                               cp_print_key_finished_output,&
      52             :                                               cp_print_key_should_output,&
      53             :                                               cp_print_key_unit_nr
      54             :    USE cp_realspace_grid_cube,          ONLY: cp_pw_to_cube
      55             :    USE dct,                             ONLY: pw_shrink
      56             :    USE ed_analysis,                     ONLY: edmf_analysis
      57             :    USE et_coupling_types,               ONLY: set_et_coupling_type
      58             :    USE hfx_ri,                          ONLY: print_ri_hfx
      59             :    USE hirshfeld_methods,               ONLY: comp_hirshfeld_charges,&
      60             :                                               comp_hirshfeld_i_charges,&
      61             :                                               create_shape_function,&
      62             :                                               save_hirshfeld_charges,&
      63             :                                               write_hirshfeld_charges
      64             :    USE hirshfeld_types,                 ONLY: create_hirshfeld_type,&
      65             :                                               hirshfeld_type,&
      66             :                                               release_hirshfeld_type,&
      67             :                                               set_hirshfeld_info
      68             :    USE iao_analysis,                    ONLY: iao_wfn_analysis
      69             :    USE iao_types,                       ONLY: iao_env_type,&
      70             :                                               iao_read_input
      71             :    USE input_constants,                 ONLY: &
      72             :         do_loc_both, do_loc_homo, do_loc_jacobi, do_loc_lumo, do_loc_mixed, do_loc_none, &
      73             :         ot_precond_full_all, radius_covalent, radius_user, ref_charge_atomic, ref_charge_mulliken
      74             :    USE input_section_types,             ONLY: section_get_ival,&
      75             :                                               section_get_ivals,&
      76             :                                               section_get_lval,&
      77             :                                               section_get_rval,&
      78             :                                               section_vals_get,&
      79             :                                               section_vals_get_subs_vals,&
      80             :                                               section_vals_type,&
      81             :                                               section_vals_val_get
      82             :    USE kinds,                           ONLY: default_path_length,&
      83             :                                               default_string_length,&
      84             :                                               dp
      85             :    USE kpoint_types,                    ONLY: kpoint_type
      86             :    USE lapack,                          ONLY: lapack_sgesv
      87             :    USE mao_wfn_analysis,                ONLY: mao_analysis
      88             :    USE mathconstants,                   ONLY: pi
      89             :    USE memory_utilities,                ONLY: reallocate
      90             :    USE message_passing,                 ONLY: mp_para_env_type
      91             :    USE minbas_wfn_analysis,             ONLY: minbas_analysis
      92             :    USE molden_utils,                    ONLY: write_mos_molden
      93             :    USE molecule_types,                  ONLY: molecule_type
      94             :    USE mulliken,                        ONLY: mulliken_charges
      95             :    USE orbital_pointers,                ONLY: indso
      96             :    USE particle_list_types,             ONLY: particle_list_type
      97             :    USE particle_types,                  ONLY: particle_type
      98             :    USE physcon,                         ONLY: angstrom,&
      99             :                                               evolt
     100             :    USE population_analyses,             ONLY: lowdin_population_analysis,&
     101             :                                               mulliken_population_analysis
     102             :    USE preconditioner_types,            ONLY: preconditioner_type
     103             :    USE ps_implicit_types,               ONLY: MIXED_BC,&
     104             :                                               MIXED_PERIODIC_BC,&
     105             :                                               NEUMANN_BC,&
     106             :                                               PERIODIC_BC
     107             :    USE pw_env_types,                    ONLY: pw_env_get,&
     108             :                                               pw_env_type
     109             :    USE pw_grids,                        ONLY: get_pw_grid_info
     110             :    USE pw_methods,                      ONLY: pw_axpy,&
     111             :                                               pw_copy,&
     112             :                                               pw_derive,&
     113             :                                               pw_integrate_function,&
     114             :                                               pw_scale,&
     115             :                                               pw_transfer,&
     116             :                                               pw_zero
     117             :    USE pw_poisson_methods,              ONLY: pw_poisson_solve
     118             :    USE pw_poisson_types,                ONLY: pw_poisson_implicit,&
     119             :                                               pw_poisson_type
     120             :    USE pw_pool_types,                   ONLY: pw_pool_p_type,&
     121             :                                               pw_pool_type
     122             :    USE pw_types,                        ONLY: pw_c1d_gs_type,&
     123             :                                               pw_r3d_rs_type
     124             :    USE qs_chargemol,                    ONLY: write_wfx
     125             :    USE qs_collocate_density,            ONLY: calculate_rho_resp_all,&
     126             :                                               calculate_wavefunction
     127             :    USE qs_commutators,                  ONLY: build_com_hr_matrix
     128             :    USE qs_core_energies,                ONLY: calculate_ptrace
     129             :    USE qs_dos,                          ONLY: calculate_dos,&
     130             :                                               calculate_dos_kp
     131             :    USE qs_electric_field_gradient,      ONLY: qs_efg_calc
     132             :    USE qs_elf_methods,                  ONLY: qs_elf_calc
     133             :    USE qs_energy_types,                 ONLY: qs_energy_type
     134             :    USE qs_energy_window,                ONLY: energy_windows
     135             :    USE qs_environment_types,            ONLY: get_qs_env,&
     136             :                                               qs_environment_type,&
     137             :                                               set_qs_env
     138             :    USE qs_epr_hyp,                      ONLY: qs_epr_hyp_calc
     139             :    USE qs_grid_atom,                    ONLY: grid_atom_type
     140             :    USE qs_integral_utils,               ONLY: basis_set_list_setup
     141             :    USE qs_kind_types,                   ONLY: get_qs_kind,&
     142             :                                               qs_kind_type
     143             :    USE qs_ks_methods,                   ONLY: calc_rho_tot_gspace,&
     144             :                                               qs_ks_update_qs_env
     145             :    USE qs_ks_types,                     ONLY: qs_ks_did_change
     146             :    USE qs_loc_dipole,                   ONLY: loc_dipole
     147             :    USE qs_loc_states,                   ONLY: get_localization_info
     148             :    USE qs_loc_types,                    ONLY: qs_loc_env_create,&
     149             :                                               qs_loc_env_release,&
     150             :                                               qs_loc_env_type
     151             :    USE qs_loc_utils,                    ONLY: loc_write_restart,&
     152             :                                               qs_loc_control_init,&
     153             :                                               qs_loc_env_init,&
     154             :                                               qs_loc_init,&
     155             :                                               retain_history
     156             :    USE qs_local_properties,             ONLY: qs_local_energy,&
     157             :                                               qs_local_stress
     158             :    USE qs_mo_io,                        ONLY: write_dm_binary_restart
     159             :    USE qs_mo_methods,                   ONLY: calculate_subspace_eigenvalues,&
     160             :                                               make_mo_eig
     161             :    USE qs_mo_occupation,                ONLY: set_mo_occupation
     162             :    USE qs_mo_types,                     ONLY: get_mo_set,&
     163             :                                               mo_set_type
     164             :    USE qs_moments,                      ONLY: qs_moment_berry_phase,&
     165             :                                               qs_moment_locop
     166             :    USE qs_neighbor_list_types,          ONLY: get_iterator_info,&
     167             :                                               get_neighbor_list_set_p,&
     168             :                                               neighbor_list_iterate,&
     169             :                                               neighbor_list_iterator_create,&
     170             :                                               neighbor_list_iterator_p_type,&
     171             :                                               neighbor_list_iterator_release,&
     172             :                                               neighbor_list_set_p_type
     173             :    USE qs_ot_eigensolver,               ONLY: ot_eigensolver
     174             :    USE qs_pdos,                         ONLY: calculate_projected_dos
     175             :    USE qs_resp,                         ONLY: resp_fit
     176             :    USE qs_rho0_types,                   ONLY: get_rho0_mpole,&
     177             :                                               mpole_rho_atom,&
     178             :                                               rho0_mpole_type
     179             :    USE qs_rho_atom_types,               ONLY: rho_atom_type
     180             :    USE qs_rho_methods,                  ONLY: qs_rho_update_rho
     181             :    USE qs_rho_types,                    ONLY: qs_rho_get,&
     182             :                                               qs_rho_type
     183             :    USE qs_scf_csr_write,                ONLY: write_ks_matrix_csr,&
     184             :                                               write_s_matrix_csr
     185             :    USE qs_scf_output,                   ONLY: qs_scf_write_mos
     186             :    USE qs_scf_types,                    ONLY: ot_method_nr,&
     187             :                                               qs_scf_env_type
     188             :    USE qs_scf_wfn_mix,                  ONLY: wfn_mix
     189             :    USE qs_subsys_types,                 ONLY: qs_subsys_get,&
     190             :                                               qs_subsys_type
     191             :    USE qs_wannier90,                    ONLY: wannier90_interface
     192             :    USE s_square_methods,                ONLY: compute_s_square
     193             :    USE scf_control_types,               ONLY: scf_control_type
     194             :    USE stm_images,                      ONLY: th_stm_image
     195             :    USE transport,                       ONLY: qs_scf_post_transport
     196             :    USE virial_types,                    ONLY: virial_type
     197             :    USE voronoi_interface,               ONLY: entry_voronoi_or_bqb
     198             :    USE xray_diffraction,                ONLY: calculate_rhotot_elec_gspace,&
     199             :                                               xray_diffraction_spectrum
     200             : #include "./base/base_uses.f90"
     201             : 
     202             :    IMPLICIT NONE
     203             :    PRIVATE
     204             : 
     205             :    ! Global parameters
     206             :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_scf_post_gpw'
     207             :    PUBLIC :: scf_post_calculation_gpw, &
     208             :              qs_scf_post_moments, &
     209             :              write_mo_dependent_results, &
     210             :              write_mo_free_results
     211             : 
     212             :    PUBLIC :: make_lumo_gpw
     213             : 
     214             : ! **************************************************************************************************
     215             : 
     216             : CONTAINS
     217             : 
     218             : ! **************************************************************************************************
     219             : !> \brief collects possible post - scf calculations and prints info / computes properties.
     220             : !> \param qs_env the qs_env in which the qs_env lives
     221             : !> \param wf_type ...
     222             : !> \param do_mp2 ...
     223             : !> \par History
     224             : !>      02.2003 created [fawzi]
     225             : !>      10.2004 moved here from qs_scf [Joost VandeVondele]
     226             : !>              started splitting out different subroutines
     227             : !>      10.2015 added header for wave-function correlated methods [Vladimir Rybkin]
     228             : !> \author fawzi
     229             : !> \note
     230             : !>      this function changes mo_eigenvectors and mo_eigenvalues, depending on the print keys.
     231             : !>      In particular, MO_CUBES causes the MOs to be rotated to make them eigenstates of the KS
     232             : !>      matrix, and mo_eigenvalues is updated accordingly. This can, for unconverged wavefunctions,
     233             : !>      change afterwards slightly the forces (hence small numerical differences between MD
     234             : !>      with and without the debug print level). Ideally this should not happen...
     235             : ! **************************************************************************************************
     236        9591 :    SUBROUTINE scf_post_calculation_gpw(qs_env, wf_type, do_mp2)
     237             : 
     238             :       TYPE(qs_environment_type), POINTER                 :: qs_env
     239             :       CHARACTER(6), OPTIONAL                             :: wf_type
     240             :       LOGICAL, OPTIONAL                                  :: do_mp2
     241             : 
     242             :       CHARACTER(len=*), PARAMETER :: routineN = 'scf_post_calculation_gpw'
     243             : 
     244             :       INTEGER :: handle, homo, ispin, min_lumos, n_rep, nchk_nmoloc, nhomo, nlumo, nlumo_stm, &
     245             :          nlumo_tddft, nlumos, nmo, nspins, output_unit, unit_nr
     246        9591 :       INTEGER, DIMENSION(:, :, :), POINTER               :: marked_states
     247             :       LOGICAL :: check_write, compute_lumos, do_homo, do_kpoints, do_mixed, do_mo_cubes, do_stm, &
     248             :          do_wannier_cubes, has_homo, has_lumo, loc_explicit, loc_print_explicit, my_do_mp2, &
     249             :          my_localized_wfn, p_loc, p_loc_homo, p_loc_lumo, p_loc_mixed
     250             :       REAL(dp)                                           :: e_kin
     251             :       REAL(KIND=dp)                                      :: gap, homo_lumo(2, 2), total_zeff_corr
     252        9591 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: mo_eigenvalues
     253             :       TYPE(admm_type), POINTER                           :: admm_env
     254        9591 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     255        9591 :       TYPE(cp_1d_r_p_type), DIMENSION(:), POINTER        :: mixed_evals, occupied_evals, &
     256        9591 :                                                             unoccupied_evals, unoccupied_evals_stm
     257        9591 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: mixed_orbs, occupied_orbs
     258             :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:), &
     259        9591 :          TARGET                                          :: homo_localized, lumo_localized, &
     260        9591 :                                                             mixed_localized
     261        9591 :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: lumo_ptr, mo_loc_history, &
     262        9591 :                                                             unoccupied_orbs, unoccupied_orbs_stm
     263             :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
     264             :       TYPE(cp_logger_type), POINTER                      :: logger
     265        9591 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_rmpv, matrix_p_mp2, matrix_s, &
     266        9591 :                                                             mo_derivs
     267        9591 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: kinetic_m, rho_ao
     268             :       TYPE(dft_control_type), POINTER                    :: dft_control
     269        9591 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     270        9591 :       TYPE(molecule_type), POINTER                       :: molecule_set(:)
     271             :       TYPE(mp_para_env_type), POINTER                    :: para_env
     272             :       TYPE(particle_list_type), POINTER                  :: particles
     273        9591 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     274             :       TYPE(pw_c1d_gs_type)                               :: wf_g
     275             :       TYPE(pw_env_type), POINTER                         :: pw_env
     276        9591 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
     277             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
     278             :       TYPE(pw_r3d_rs_type)                               :: wf_r
     279        9591 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     280             :       TYPE(qs_loc_env_type), POINTER                     :: qs_loc_env_homo, qs_loc_env_lumo, &
     281             :                                                             qs_loc_env_mixed
     282             :       TYPE(qs_rho_type), POINTER                         :: rho
     283             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     284             :       TYPE(qs_subsys_type), POINTER                      :: subsys
     285             :       TYPE(scf_control_type), POINTER                    :: scf_control
     286             :       TYPE(section_vals_type), POINTER                   :: dft_section, input, loc_print_section, &
     287             :                                                             localize_section, print_key, &
     288             :                                                             stm_section
     289             : 
     290        9591 :       CALL timeset(routineN, handle)
     291             : 
     292        9591 :       logger => cp_get_default_logger()
     293        9591 :       output_unit = cp_logger_get_default_io_unit(logger)
     294             : 
     295             :       ! Print out the type of wavefunction to distinguish between SCF and post-SCF
     296        9591 :       my_do_mp2 = .FALSE.
     297        9591 :       IF (PRESENT(do_mp2)) my_do_mp2 = do_mp2
     298        9591 :       IF (PRESENT(wf_type)) THEN
     299         310 :          IF (output_unit > 0) THEN
     300         155 :             WRITE (UNIT=output_unit, FMT='(/,(T1,A))') REPEAT("-", 40)
     301         155 :             WRITE (UNIT=output_unit, FMT='(/,(T3,A,T19,A,T25,A))') "Properties from ", wf_type, " density"
     302         155 :             WRITE (UNIT=output_unit, FMT='(/,(T1,A))') REPEAT("-", 40)
     303             :          END IF
     304             :       END IF
     305             : 
     306             :       ! Writes the data that is already available in qs_env
     307        9591 :       CALL get_qs_env(qs_env, scf_env=scf_env)
     308             : 
     309        9591 :       my_localized_wfn = .FALSE.
     310        9591 :       NULLIFY (admm_env, dft_control, pw_env, auxbas_pw_pool, pw_pools, mos, rho, &
     311        9591 :                mo_coeff, ks_rmpv, matrix_s, qs_loc_env_homo, qs_loc_env_lumo, scf_control, &
     312        9591 :                unoccupied_orbs, mo_eigenvalues, unoccupied_evals, &
     313        9591 :                unoccupied_evals_stm, molecule_set, mo_derivs, &
     314        9591 :                subsys, particles, input, print_key, kinetic_m, marked_states, &
     315        9591 :                mixed_evals, qs_loc_env_mixed)
     316        9591 :       NULLIFY (lumo_ptr, rho_ao)
     317             : 
     318        9591 :       has_homo = .FALSE.
     319        9591 :       has_lumo = .FALSE.
     320        9591 :       p_loc = .FALSE.
     321        9591 :       p_loc_homo = .FALSE.
     322        9591 :       p_loc_lumo = .FALSE.
     323        9591 :       p_loc_mixed = .FALSE.
     324             : 
     325        9591 :       CPASSERT(ASSOCIATED(scf_env))
     326        9591 :       CPASSERT(ASSOCIATED(qs_env))
     327             :       ! Here we start with data that needs a postprocessing...
     328             :       CALL get_qs_env(qs_env, &
     329             :                       dft_control=dft_control, &
     330             :                       molecule_set=molecule_set, &
     331             :                       scf_control=scf_control, &
     332             :                       do_kpoints=do_kpoints, &
     333             :                       input=input, &
     334             :                       subsys=subsys, &
     335             :                       rho=rho, &
     336             :                       pw_env=pw_env, &
     337             :                       particle_set=particle_set, &
     338             :                       atomic_kind_set=atomic_kind_set, &
     339        9591 :                       qs_kind_set=qs_kind_set)
     340        9591 :       CALL qs_subsys_get(subsys, particles=particles)
     341             : 
     342        9591 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao)
     343             : 
     344        9591 :       IF (my_do_mp2) THEN
     345             :          ! Get the HF+MP2 density
     346         310 :          CALL get_qs_env(qs_env, matrix_p_mp2=matrix_p_mp2)
     347         716 :          DO ispin = 1, dft_control%nspins
     348         716 :             CALL dbcsr_add(rho_ao(ispin, 1)%matrix, matrix_p_mp2(ispin)%matrix, 1.0_dp, 1.0_dp)
     349             :          END DO
     350         310 :          CALL qs_rho_update_rho(rho, qs_env=qs_env)
     351         310 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
     352             :          ! In MP2 case update the Hartree potential
     353         310 :          CALL update_hartree_with_mp2(rho, qs_env)
     354             :       END IF
     355             : 
     356        9591 :       CALL write_available_results(qs_env, scf_env)
     357             : 
     358             :       !    **** the kinetic energy
     359        9591 :       IF (cp_print_key_should_output(logger%iter_info, input, &
     360             :                                      "DFT%PRINT%KINETIC_ENERGY") /= 0) THEN
     361          80 :          CALL get_qs_env(qs_env, kinetic_kp=kinetic_m)
     362          80 :          CPASSERT(ASSOCIATED(kinetic_m))
     363          80 :          CPASSERT(ASSOCIATED(kinetic_m(1, 1)%matrix))
     364          80 :          CALL calculate_ptrace(kinetic_m, rho_ao, e_kin, dft_control%nspins)
     365             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%KINETIC_ENERGY", &
     366          80 :                                         extension=".Log")
     367          80 :          IF (unit_nr > 0) THEN
     368          40 :             WRITE (unit_nr, '(T3,A,T55,F25.14)') "Electronic kinetic energy:", e_kin
     369             :          END IF
     370             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
     371          80 :                                            "DFT%PRINT%KINETIC_ENERGY")
     372             :       END IF
     373             : 
     374             :       ! Atomic Charges that require further computation
     375        9591 :       CALL qs_scf_post_charges(input, logger, qs_env)
     376             : 
     377             :       ! Moments of charge distribution
     378        9591 :       CALL qs_scf_post_moments(input, logger, qs_env, output_unit)
     379             : 
     380             :       ! Determine if we need to computer properties using the localized centers
     381        9591 :       dft_section => section_vals_get_subs_vals(input, "DFT")
     382        9591 :       localize_section => section_vals_get_subs_vals(dft_section, "LOCALIZE")
     383        9591 :       loc_print_section => section_vals_get_subs_vals(localize_section, "PRINT")
     384        9591 :       CALL section_vals_get(localize_section, explicit=loc_explicit)
     385        9591 :       CALL section_vals_get(loc_print_section, explicit=loc_print_explicit)
     386             : 
     387             :       ! Print_keys controlled by localization
     388        9591 :       IF (loc_print_explicit) THEN
     389          96 :          print_key => section_vals_get_subs_vals(loc_print_section, "MOLECULAR_DIPOLES")
     390          96 :          p_loc = BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     391          96 :          print_key => section_vals_get_subs_vals(loc_print_section, "TOTAL_DIPOLE")
     392          96 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     393          96 :          print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_CENTERS")
     394          96 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     395          96 :          print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_SPREADS")
     396          96 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     397          96 :          print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_CUBES")
     398          96 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     399          96 :          print_key => section_vals_get_subs_vals(loc_print_section, "MOLECULAR_STATES")
     400          96 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     401          96 :          print_key => section_vals_get_subs_vals(loc_print_section, "MOLECULAR_MOMENTS")
     402          96 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     403             :       ELSE
     404             :          p_loc = .FALSE.
     405             :       END IF
     406        9591 :       IF (loc_explicit) THEN
     407             :          p_loc_homo = (section_get_ival(localize_section, "STATES") == do_loc_homo .OR. &
     408          96 :                        section_get_ival(localize_section, "STATES") == do_loc_both) .AND. p_loc
     409             :          p_loc_lumo = (section_get_ival(localize_section, "STATES") == do_loc_lumo .OR. &
     410          96 :                        section_get_ival(localize_section, "STATES") == do_loc_both) .AND. p_loc
     411          96 :          p_loc_mixed = (section_get_ival(localize_section, "STATES") == do_loc_mixed) .AND. p_loc
     412          96 :          CALL section_vals_val_get(localize_section, "LIST_UNOCCUPIED", n_rep_val=n_rep)
     413             :       ELSE
     414        9495 :          p_loc_homo = .FALSE.
     415        9495 :          p_loc_lumo = .FALSE.
     416        9495 :          p_loc_mixed = .FALSE.
     417        9495 :          n_rep = 0
     418             :       END IF
     419             : 
     420        9591 :       IF (n_rep == 0 .AND. p_loc_lumo) THEN
     421             :          CALL cp_abort(__LOCATION__, "No LIST_UNOCCUPIED was specified, "// &
     422           0 :                        "therefore localization of unoccupied states will be skipped!")
     423           0 :          p_loc_lumo = .FALSE.
     424             :       END IF
     425        9591 :       print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_STATES")
     426        9591 :       p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     427             : 
     428             :       ! Control for STM
     429        9591 :       stm_section => section_vals_get_subs_vals(input, "DFT%PRINT%STM")
     430        9591 :       CALL section_vals_get(stm_section, explicit=do_stm)
     431        9591 :       nlumo_stm = 0
     432        9591 :       IF (do_stm) nlumo_stm = section_get_ival(stm_section, "NLUMO")
     433             : 
     434             :       ! check for CUBES (MOs and WANNIERS)
     435             :       do_mo_cubes = BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%MO_CUBES") &
     436        9591 :                           , cp_p_file)
     437        9591 :       IF (loc_print_explicit) THEN
     438             :          do_wannier_cubes = BTEST(cp_print_key_should_output(logger%iter_info, loc_print_section, &
     439          96 :                                                              "WANNIER_CUBES"), cp_p_file)
     440             :       ELSE
     441             :          do_wannier_cubes = .FALSE.
     442             :       END IF
     443        9591 :       nlumo = section_get_ival(dft_section, "PRINT%MO_CUBES%NLUMO")
     444        9591 :       nhomo = section_get_ival(dft_section, "PRINT%MO_CUBES%NHOMO")
     445        9591 :       nlumo_tddft = 0
     446        9591 :       IF (dft_control%do_tddfpt_calculation) THEN
     447          12 :          nlumo_tddft = section_get_ival(dft_section, "TDDFPT%NLUMO")
     448             :       END IF
     449             : 
     450             :       ! Setup the grids needed to compute a wavefunction given a vector..
     451        9591 :       IF (((do_mo_cubes .OR. do_wannier_cubes) .AND. (nlumo /= 0 .OR. nhomo /= 0)) .OR. p_loc) THEN
     452             :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
     453         208 :                          pw_pools=pw_pools)
     454         208 :          CALL auxbas_pw_pool%create_pw(wf_r)
     455         208 :          CALL auxbas_pw_pool%create_pw(wf_g)
     456             :       END IF
     457             : 
     458        9591 :       IF (dft_control%restricted) THEN
     459             :          !For ROKS usefull only first term
     460          74 :          nspins = 1
     461             :       ELSE
     462        9517 :          nspins = dft_control%nspins
     463             :       END IF
     464             :       !Some info about ROKS
     465        9591 :       IF (dft_control%restricted .AND. (do_mo_cubes .OR. p_loc_homo)) THEN
     466           0 :          CALL cp_abort(__LOCATION__, "Unclear how we define MOs / localization in the restricted case ... ")
     467             :          ! It is possible to obtain Wannier centers for ROKS without rotations for SINGLE OCCUPIED ORBITALS
     468             :       END IF
     469             :       ! Makes the MOs eigenstates, computes eigenvalues, write cubes
     470        9591 :       IF (do_kpoints) THEN
     471         202 :          IF (do_mo_cubes) THEN
     472           2 :             CPWARN("Print MO cubes not implemented for k-point calculations")
     473             :          END IF
     474             :       ELSE
     475             :          CALL get_qs_env(qs_env, &
     476             :                          mos=mos, &
     477        9389 :                          matrix_ks=ks_rmpv)
     478        9389 :          IF ((do_mo_cubes .AND. nhomo /= 0) .OR. do_stm .OR. dft_control%do_tddfpt_calculation) THEN
     479         144 :             CALL get_qs_env(qs_env, mo_derivs=mo_derivs)
     480         144 :             IF (dft_control%do_admm) THEN
     481           0 :                CALL get_qs_env(qs_env, admm_env=admm_env)
     482           0 :                CALL make_mo_eig(mos, nspins, ks_rmpv, scf_control, mo_derivs, admm_env=admm_env)
     483             :             ELSE
     484         144 :                CALL make_mo_eig(mos, nspins, ks_rmpv, scf_control, mo_derivs)
     485             :             END IF
     486         310 :             DO ispin = 1, dft_control%nspins
     487         166 :                CALL get_mo_set(mo_set=mos(ispin), eigenvalues=mo_eigenvalues, homo=homo)
     488         310 :                homo_lumo(ispin, 1) = mo_eigenvalues(homo)
     489             :             END DO
     490             :             has_homo = .TRUE.
     491             :          END IF
     492        9389 :          IF (do_mo_cubes .AND. nhomo /= 0) THEN
     493         268 :             DO ispin = 1, nspins
     494             :                ! Prints the cube files of OCCUPIED ORBITALS
     495             :                CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
     496         142 :                                eigenvalues=mo_eigenvalues, homo=homo, nmo=nmo)
     497             :                CALL qs_scf_post_occ_cubes(input, dft_section, dft_control, logger, qs_env, &
     498         268 :                                           mo_coeff, wf_g, wf_r, particles, homo, ispin)
     499             :             END DO
     500             :          END IF
     501             :       END IF
     502             : 
     503             :       ! Initialize the localization environment, needed e.g. for wannier functions and molecular states
     504             :       ! Gets localization info for the occupied orbs
     505             :       !  - Possibly gets wannier functions
     506             :       !  - Possibly gets molecular states
     507        9591 :       IF (p_loc_homo) THEN
     508          90 :          IF (do_kpoints) THEN
     509           0 :             CPWARN("Localization not implemented for k-point calculations!!")
     510             :          ELSEIF (dft_control%restricted &
     511             :                  .AND. (section_get_ival(localize_section, "METHOD") .NE. do_loc_none) &
     512          90 :                  .AND. (section_get_ival(localize_section, "METHOD") .NE. do_loc_jacobi)) THEN
     513           0 :             CPABORT("ROKS works only with LOCALIZE METHOD NONE or JACOBI")
     514             :          ELSE
     515         376 :             ALLOCATE (occupied_orbs(dft_control%nspins))
     516         376 :             ALLOCATE (occupied_evals(dft_control%nspins))
     517         376 :             ALLOCATE (homo_localized(dft_control%nspins))
     518         196 :             DO ispin = 1, dft_control%nspins
     519             :                CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
     520         106 :                                eigenvalues=mo_eigenvalues)
     521         106 :                occupied_orbs(ispin) = mo_coeff
     522         106 :                occupied_evals(ispin)%array => mo_eigenvalues
     523         106 :                CALL cp_fm_create(homo_localized(ispin), occupied_orbs(ispin)%matrix_struct)
     524         196 :                CALL cp_fm_to_fm(occupied_orbs(ispin), homo_localized(ispin))
     525             :             END DO
     526             : 
     527          90 :             CALL get_qs_env(qs_env, mo_loc_history=mo_loc_history)
     528          90 :             do_homo = .TRUE.
     529             : 
     530         720 :             ALLOCATE (qs_loc_env_homo)
     531          90 :             CALL qs_loc_env_create(qs_loc_env_homo)
     532          90 :             CALL qs_loc_control_init(qs_loc_env_homo, localize_section, do_homo=do_homo)
     533             :             CALL qs_loc_init(qs_env, qs_loc_env_homo, localize_section, homo_localized, do_homo, &
     534          90 :                              do_mo_cubes, mo_loc_history=mo_loc_history)
     535             :             CALL get_localization_info(qs_env, qs_loc_env_homo, localize_section, homo_localized, &
     536          90 :                                        wf_r, wf_g, particles, occupied_orbs, occupied_evals, marked_states)
     537             : 
     538             :             !retain the homo_localized for future use
     539          90 :             IF (qs_loc_env_homo%localized_wfn_control%use_history) THEN
     540          10 :                CALL retain_history(mo_loc_history, homo_localized)
     541          10 :                CALL set_qs_env(qs_env, mo_loc_history=mo_loc_history)
     542             :             END IF
     543             : 
     544             :             !write restart for localization of occupied orbitals
     545             :             CALL loc_write_restart(qs_loc_env_homo, loc_print_section, mos, &
     546          90 :                                    homo_localized, do_homo)
     547          90 :             CALL cp_fm_release(homo_localized)
     548          90 :             DEALLOCATE (occupied_orbs)
     549          90 :             DEALLOCATE (occupied_evals)
     550             :             ! Print Total Dipole if the localization has been performed
     551         180 :             IF (qs_loc_env_homo%do_localize) THEN
     552          74 :                CALL loc_dipole(input, dft_control, qs_loc_env_homo, logger, qs_env)
     553             :             END IF
     554             :          END IF
     555             :       END IF
     556             : 
     557             :       ! Gets the lumos, and eigenvalues for the lumos, and localize them if requested
     558        9591 :       IF (do_kpoints) THEN
     559         202 :          IF (do_mo_cubes .OR. p_loc_lumo) THEN
     560             :             ! nothing at the moment, not implemented
     561           2 :             CPWARN("Localization and MO related output not implemented for k-point calculations!")
     562             :          END IF
     563             :       ELSE
     564        9389 :          IF (nlumo .GT. -1) THEN
     565        9385 :             nlumo = MAX(nlumo, nlumo_tddft)
     566             :          END IF
     567        9389 :          compute_lumos = (do_mo_cubes .OR. dft_control%do_tddfpt_calculation) .AND. nlumo .NE. 0
     568        9389 :          compute_lumos = compute_lumos .OR. p_loc_lumo
     569             : 
     570       20632 :          DO ispin = 1, dft_control%nspins
     571       11243 :             CALL get_mo_set(mo_set=mos(ispin), homo=homo, nmo=nmo)
     572       31811 :             compute_lumos = compute_lumos .AND. homo == nmo
     573             :          END DO
     574             : 
     575        9389 :          IF (do_mo_cubes .AND. .NOT. compute_lumos) THEN
     576             : 
     577          94 :             nlumo = section_get_ival(dft_section, "PRINT%MO_CUBES%NLUMO")
     578         188 :             DO ispin = 1, dft_control%nspins
     579             : 
     580          94 :                CALL get_mo_set(mo_set=mos(ispin), homo=homo, nmo=nmo, eigenvalues=mo_eigenvalues)
     581         188 :                IF (nlumo > nmo - homo) THEN
     582             :                   ! this case not yet implemented
     583             :                ELSE
     584          94 :                   IF (nlumo .EQ. -1) THEN
     585           0 :                      nlumo = nmo - homo
     586             :                   END IF
     587          94 :                   IF (output_unit > 0) WRITE (output_unit, *) " "
     588          94 :                   IF (output_unit > 0) WRITE (output_unit, *) " Lowest eigenvalues of the unoccupied subspace spin ", ispin
     589          94 :                   IF (output_unit > 0) WRITE (output_unit, *) "---------------------------------------------"
     590          94 :                   IF (output_unit > 0) WRITE (output_unit, '(4(1X,1F16.8))') mo_eigenvalues(homo + 1:homo + nlumo)
     591             : 
     592             :                   ! Prints the cube files of UNOCCUPIED ORBITALS
     593          94 :                   CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff)
     594             :                   CALL qs_scf_post_unocc_cubes(input, dft_section, dft_control, logger, qs_env, &
     595          94 :                                                mo_coeff, wf_g, wf_r, particles, nlumo, homo, ispin, lumo=homo + 1)
     596             :                END IF
     597             :             END DO
     598             : 
     599             :          END IF
     600             : 
     601        9357 :          IF (compute_lumos) THEN
     602          44 :             check_write = .TRUE.
     603          44 :             min_lumos = nlumo
     604          44 :             IF (nlumo == 0) check_write = .FALSE.
     605          44 :             IF (p_loc_lumo) THEN
     606           6 :                do_homo = .FALSE.
     607          48 :                ALLOCATE (qs_loc_env_lumo)
     608           6 :                CALL qs_loc_env_create(qs_loc_env_lumo)
     609           6 :                CALL qs_loc_control_init(qs_loc_env_lumo, localize_section, do_homo=do_homo)
     610          98 :                min_lumos = MAX(MAXVAL(qs_loc_env_lumo%localized_wfn_control%loc_states(:, :)), nlumo)
     611             :             END IF
     612             : 
     613         196 :             ALLOCATE (unoccupied_orbs(dft_control%nspins))
     614         196 :             ALLOCATE (unoccupied_evals(dft_control%nspins))
     615          44 :             CALL make_lumo_gpw(qs_env, scf_env, unoccupied_orbs, unoccupied_evals, min_lumos, nlumos)
     616          44 :             lumo_ptr => unoccupied_orbs
     617         108 :             DO ispin = 1, dft_control%nspins
     618          64 :                has_lumo = .TRUE.
     619          64 :                homo_lumo(ispin, 2) = unoccupied_evals(ispin)%array(1)
     620          64 :                CALL get_mo_set(mo_set=mos(ispin), homo=homo)
     621         108 :                IF (check_write) THEN
     622          64 :                   IF (p_loc_lumo .AND. nlumo .NE. -1) nlumos = MIN(nlumo, nlumos)
     623             :                   ! Prints the cube files of UNOCCUPIED ORBITALS
     624             :                   CALL qs_scf_post_unocc_cubes(input, dft_section, dft_control, logger, qs_env, &
     625          64 :                                                unoccupied_orbs(ispin), wf_g, wf_r, particles, nlumos, homo, ispin)
     626             :                END IF
     627             :             END DO
     628             : 
     629             :             ! Save the info for tddfpt calculation
     630          44 :             IF (dft_control%do_tddfpt_calculation) THEN
     631          48 :                ALLOCATE (dft_control%tddfpt_control%lumos_eigenvalues(nlumos, dft_control%nspins))
     632          28 :                DO ispin = 1, dft_control%nspins
     633             :                   dft_control%tddfpt_control%lumos_eigenvalues(1:nlumos, ispin) = &
     634         192 :                      unoccupied_evals(ispin)%array(1:nlumos)
     635             :                END DO
     636          12 :                dft_control%tddfpt_control%lumos => unoccupied_orbs
     637             :             END IF
     638             : 
     639          88 :             IF (p_loc_lumo) THEN
     640          30 :                ALLOCATE (lumo_localized(dft_control%nspins))
     641          18 :                DO ispin = 1, dft_control%nspins
     642          12 :                   CALL cp_fm_create(lumo_localized(ispin), unoccupied_orbs(ispin)%matrix_struct)
     643          18 :                   CALL cp_fm_to_fm(unoccupied_orbs(ispin), lumo_localized(ispin))
     644             :                END DO
     645             :                CALL qs_loc_init(qs_env, qs_loc_env_lumo, localize_section, lumo_localized, do_homo, do_mo_cubes, &
     646           6 :                                 evals=unoccupied_evals)
     647             :                CALL qs_loc_env_init(qs_loc_env_lumo, qs_loc_env_lumo%localized_wfn_control, qs_env, &
     648           6 :                                     loc_coeff=unoccupied_orbs)
     649             :                CALL get_localization_info(qs_env, qs_loc_env_lumo, localize_section, &
     650             :                                           lumo_localized, wf_r, wf_g, particles, &
     651           6 :                                           unoccupied_orbs, unoccupied_evals, marked_states)
     652             :                CALL loc_write_restart(qs_loc_env_lumo, loc_print_section, mos, homo_localized, do_homo, &
     653           6 :                                       evals=unoccupied_evals)
     654           6 :                lumo_ptr => lumo_localized
     655             :             END IF
     656             :          END IF
     657             : 
     658        9389 :          IF (has_homo .AND. has_lumo) THEN
     659          44 :             IF (output_unit > 0) WRITE (output_unit, *) " "
     660         108 :             DO ispin = 1, dft_control%nspins
     661         108 :                IF (.NOT. scf_control%smear%do_smear) THEN
     662          64 :                   gap = homo_lumo(ispin, 2) - homo_lumo(ispin, 1)
     663          64 :                   IF (output_unit > 0) WRITE (output_unit, '(T2,A,F12.6)') &
     664          32 :                      "HOMO - LUMO gap [eV] :", gap*evolt
     665             :                END IF
     666             :             END DO
     667             :          END IF
     668             :       END IF
     669             : 
     670        9591 :       IF (p_loc_mixed) THEN
     671           2 :          IF (do_kpoints) THEN
     672           0 :             CPWARN("Localization not implemented for k-point calculations!!")
     673           2 :          ELSEIF (dft_control%restricted) THEN
     674           0 :             IF (output_unit > 0) WRITE (output_unit, *) &
     675           0 :                " Unclear how we define MOs / localization in the restricted case... skipping"
     676             :          ELSE
     677             : 
     678           8 :             ALLOCATE (mixed_orbs(dft_control%nspins))
     679           8 :             ALLOCATE (mixed_evals(dft_control%nspins))
     680           8 :             ALLOCATE (mixed_localized(dft_control%nspins))
     681           4 :             DO ispin = 1, dft_control%nspins
     682             :                CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
     683           2 :                                eigenvalues=mo_eigenvalues)
     684           2 :                mixed_orbs(ispin) = mo_coeff
     685           2 :                mixed_evals(ispin)%array => mo_eigenvalues
     686           2 :                CALL cp_fm_create(mixed_localized(ispin), mixed_orbs(ispin)%matrix_struct)
     687           4 :                CALL cp_fm_to_fm(mixed_orbs(ispin), mixed_localized(ispin))
     688             :             END DO
     689             : 
     690           2 :             CALL get_qs_env(qs_env, mo_loc_history=mo_loc_history)
     691           2 :             do_homo = .FALSE.
     692           2 :             do_mixed = .TRUE.
     693           2 :             total_zeff_corr = scf_env%sum_zeff_corr
     694          16 :             ALLOCATE (qs_loc_env_mixed)
     695           2 :             CALL qs_loc_env_create(qs_loc_env_mixed)
     696           2 :             CALL qs_loc_control_init(qs_loc_env_mixed, localize_section, do_homo=do_homo, do_mixed=do_mixed)
     697             :             CALL qs_loc_init(qs_env, qs_loc_env_mixed, localize_section, mixed_localized, do_homo, &
     698             :                              do_mo_cubes, mo_loc_history=mo_loc_history, tot_zeff_corr=total_zeff_corr, &
     699           2 :                              do_mixed=do_mixed)
     700             : 
     701           4 :             DO ispin = 1, dft_control%nspins
     702           4 :                CALL cp_fm_get_info(mixed_localized(ispin), ncol_global=nchk_nmoloc)
     703             :             END DO
     704             : 
     705             :             CALL get_localization_info(qs_env, qs_loc_env_mixed, localize_section, mixed_localized, &
     706           2 :                                        wf_r, wf_g, particles, mixed_orbs, mixed_evals, marked_states)
     707             : 
     708             :             !retain the homo_localized for future use
     709           2 :             IF (qs_loc_env_mixed%localized_wfn_control%use_history) THEN
     710           0 :                CALL retain_history(mo_loc_history, mixed_localized)
     711           0 :                CALL set_qs_env(qs_env, mo_loc_history=mo_loc_history)
     712             :             END IF
     713             : 
     714             :             !write restart for localization of occupied orbitals
     715             :             CALL loc_write_restart(qs_loc_env_mixed, loc_print_section, mos, &
     716           2 :                                    mixed_localized, do_homo, do_mixed=do_mixed)
     717           2 :             CALL cp_fm_release(mixed_localized)
     718           2 :             DEALLOCATE (mixed_orbs)
     719           4 :             DEALLOCATE (mixed_evals)
     720             :             ! Print Total Dipole if the localization has been performed
     721             : ! Revisit the formalism later
     722             :             !IF (qs_loc_env_mixed%do_localize) THEN
     723             :             !   CALL loc_dipole(input, dft_control, qs_loc_env_mixed, logger, qs_env)
     724             :             !END IF
     725             :          END IF
     726             :       END IF
     727             : 
     728             :       ! Deallocate grids needed to compute wavefunctions
     729        9591 :       IF (((do_mo_cubes .OR. do_wannier_cubes) .AND. (nlumo /= 0 .OR. nhomo /= 0)) .OR. p_loc) THEN
     730         208 :          CALL auxbas_pw_pool%give_back_pw(wf_r)
     731         208 :          CALL auxbas_pw_pool%give_back_pw(wf_g)
     732             :       END IF
     733             : 
     734             :       ! Destroy the localization environment
     735        9591 :       IF (.NOT. do_kpoints) THEN
     736        9389 :          IF (p_loc_homo) THEN
     737          90 :             CALL qs_loc_env_release(qs_loc_env_homo)
     738          90 :             DEALLOCATE (qs_loc_env_homo)
     739             :          END IF
     740        9389 :          IF (p_loc_lumo) THEN
     741           6 :             CALL qs_loc_env_release(qs_loc_env_lumo)
     742           6 :             DEALLOCATE (qs_loc_env_lumo)
     743             :          END IF
     744        9389 :          IF (p_loc_mixed) THEN
     745           2 :             CALL qs_loc_env_release(qs_loc_env_mixed)
     746           2 :             DEALLOCATE (qs_loc_env_mixed)
     747             :          END IF
     748             :       END IF
     749             : 
     750             :       ! generate a mix of wfns, and write to a restart
     751        9591 :       IF (do_kpoints) THEN
     752             :          ! nothing at the moment, not implemented
     753             :       ELSE
     754        9389 :          CALL get_qs_env(qs_env, matrix_s=matrix_s, para_env=para_env)
     755             :          CALL wfn_mix(mos, particle_set, dft_section, qs_kind_set, para_env, &
     756             :                       output_unit, unoccupied_orbs=lumo_ptr, scf_env=scf_env, &
     757        9389 :                       matrix_s=matrix_s, marked_states=marked_states)
     758             : 
     759        9389 :          IF (p_loc_lumo) CALL cp_fm_release(lumo_localized)
     760             :       END IF
     761        9591 :       IF (ASSOCIATED(marked_states)) THEN
     762          16 :          DEALLOCATE (marked_states)
     763             :       END IF
     764             : 
     765             :       ! This is just a deallocation for printing MO_CUBES or TDDFPT
     766        9591 :       IF (.NOT. do_kpoints) THEN
     767        9389 :          IF (compute_lumos) THEN
     768         108 :             DO ispin = 1, dft_control%nspins
     769          64 :                DEALLOCATE (unoccupied_evals(ispin)%array)
     770         108 :                IF (.NOT. dft_control%do_tddfpt_calculation) THEN
     771          48 :                   CALL cp_fm_release(unoccupied_orbs(ispin))
     772             :                END IF
     773             :             END DO
     774          44 :             DEALLOCATE (unoccupied_evals)
     775          44 :             IF (.NOT. dft_control%do_tddfpt_calculation) THEN
     776          32 :                DEALLOCATE (unoccupied_orbs)
     777             :             END IF
     778             :          END IF
     779             :       END IF
     780             : 
     781             :       !stm images
     782        9591 :       IF (do_stm) THEN
     783           6 :          IF (do_kpoints) THEN
     784           0 :             CPWARN("STM not implemented for k-point calculations!")
     785             :          ELSE
     786           6 :             NULLIFY (unoccupied_orbs_stm, unoccupied_evals_stm)
     787           6 :             IF (nlumo_stm > 0) THEN
     788           8 :                ALLOCATE (unoccupied_orbs_stm(dft_control%nspins))
     789           8 :                ALLOCATE (unoccupied_evals_stm(dft_control%nspins))
     790             :                CALL make_lumo_gpw(qs_env, scf_env, unoccupied_orbs_stm, unoccupied_evals_stm, &
     791           2 :                                   nlumo_stm, nlumos)
     792             :             END IF
     793             : 
     794             :             CALL th_stm_image(qs_env, stm_section, particles, unoccupied_orbs_stm, &
     795           6 :                               unoccupied_evals_stm)
     796             : 
     797           6 :             IF (nlumo_stm > 0) THEN
     798           4 :                DO ispin = 1, dft_control%nspins
     799           4 :                   DEALLOCATE (unoccupied_evals_stm(ispin)%array)
     800             :                END DO
     801           2 :                DEALLOCATE (unoccupied_evals_stm)
     802           2 :                CALL cp_fm_release(unoccupied_orbs_stm)
     803             :             END IF
     804             :          END IF
     805             :       END IF
     806             : 
     807             :       ! Print coherent X-ray diffraction spectrum
     808        9591 :       CALL qs_scf_post_xray(input, dft_section, logger, qs_env, output_unit)
     809             : 
     810             :       ! Calculation of Electric Field Gradients
     811        9591 :       CALL qs_scf_post_efg(input, logger, qs_env)
     812             : 
     813             :       ! Calculation of ET
     814        9591 :       CALL qs_scf_post_et(input, qs_env, dft_control)
     815             : 
     816             :       ! Calculation of EPR Hyperfine Coupling Tensors
     817        9591 :       CALL qs_scf_post_epr(input, logger, qs_env)
     818             : 
     819             :       ! Calculation of properties needed for BASIS_MOLOPT optimizations
     820        9591 :       CALL qs_scf_post_molopt(input, logger, qs_env)
     821             : 
     822             :       ! Calculate ELF
     823        9591 :       CALL qs_scf_post_elf(input, logger, qs_env)
     824             : 
     825             :       ! Use Wannier90 interface
     826        9591 :       CALL wannier90_interface(input, logger, qs_env)
     827             : 
     828        9591 :       IF (my_do_mp2) THEN
     829             :          ! Get everything back
     830         716 :          DO ispin = 1, dft_control%nspins
     831         716 :             CALL dbcsr_add(rho_ao(ispin, 1)%matrix, matrix_p_mp2(ispin)%matrix, 1.0_dp, -1.0_dp)
     832             :          END DO
     833         310 :          CALL qs_rho_update_rho(rho, qs_env=qs_env)
     834         310 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
     835             :       END IF
     836             : 
     837        9591 :       CALL timestop(handle)
     838             : 
     839       19182 :    END SUBROUTINE scf_post_calculation_gpw
     840             : 
     841             : ! **************************************************************************************************
     842             : !> \brief Gets the lumos, and eigenvalues for the lumos
     843             : !> \param qs_env ...
     844             : !> \param scf_env ...
     845             : !> \param unoccupied_orbs ...
     846             : !> \param unoccupied_evals ...
     847             : !> \param nlumo ...
     848             : !> \param nlumos ...
     849             : ! **************************************************************************************************
     850          46 :    SUBROUTINE make_lumo_gpw(qs_env, scf_env, unoccupied_orbs, unoccupied_evals, nlumo, nlumos)
     851             : 
     852             :       TYPE(qs_environment_type), POINTER                 :: qs_env
     853             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     854             :       TYPE(cp_fm_type), DIMENSION(:), INTENT(INOUT)      :: unoccupied_orbs
     855             :       TYPE(cp_1d_r_p_type), DIMENSION(:), POINTER        :: unoccupied_evals
     856             :       INTEGER, INTENT(IN)                                :: nlumo
     857             :       INTEGER, INTENT(OUT)                               :: nlumos
     858             : 
     859             :       CHARACTER(len=*), PARAMETER                        :: routineN = 'make_lumo_gpw'
     860             : 
     861             :       INTEGER                                            :: handle, homo, ispin, n, nao, nmo, &
     862             :                                                             output_unit
     863             :       TYPE(admm_type), POINTER                           :: admm_env
     864             :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
     865             :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct_tmp
     866             :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
     867             :       TYPE(cp_logger_type), POINTER                      :: logger
     868          46 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_rmpv, matrix_s
     869             :       TYPE(dft_control_type), POINTER                    :: dft_control
     870          46 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     871             :       TYPE(mp_para_env_type), POINTER                    :: para_env
     872             :       TYPE(preconditioner_type), POINTER                 :: local_preconditioner
     873             :       TYPE(scf_control_type), POINTER                    :: scf_control
     874             : 
     875          46 :       CALL timeset(routineN, handle)
     876             : 
     877          46 :       NULLIFY (mos, ks_rmpv, scf_control, dft_control, admm_env, para_env, blacs_env)
     878             :       CALL get_qs_env(qs_env, &
     879             :                       mos=mos, &
     880             :                       matrix_ks=ks_rmpv, &
     881             :                       scf_control=scf_control, &
     882             :                       dft_control=dft_control, &
     883             :                       matrix_s=matrix_s, &
     884             :                       admm_env=admm_env, &
     885             :                       para_env=para_env, &
     886          46 :                       blacs_env=blacs_env)
     887             : 
     888          46 :       logger => cp_get_default_logger()
     889          46 :       output_unit = cp_logger_get_default_io_unit(logger)
     890             : 
     891         112 :       DO ispin = 1, dft_control%nspins
     892          66 :          NULLIFY (unoccupied_evals(ispin)%array)
     893             :          ! Always write eigenvalues
     894          66 :          IF (output_unit > 0) WRITE (output_unit, *) " "
     895          66 :          IF (output_unit > 0) WRITE (output_unit, *) " Lowest Eigenvalues of the unoccupied subspace spin ", ispin
     896          66 :          IF (output_unit > 0) WRITE (output_unit, FMT='(1X,A)') "-----------------------------------------------------"
     897          66 :          CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, homo=homo, nao=nao, nmo=nmo)
     898          66 :          CALL cp_fm_get_info(mo_coeff, nrow_global=n)
     899          66 :          nlumos = MAX(1, MIN(nlumo, nao - nmo))
     900          66 :          IF (nlumo == -1) nlumos = nao - nmo
     901         198 :          ALLOCATE (unoccupied_evals(ispin)%array(nlumos))
     902             :          CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=blacs_env, &
     903          66 :                                   nrow_global=n, ncol_global=nlumos)
     904          66 :          CALL cp_fm_create(unoccupied_orbs(ispin), fm_struct_tmp, name="lumos")
     905          66 :          CALL cp_fm_struct_release(fm_struct_tmp)
     906          66 :          CALL cp_fm_init_random(unoccupied_orbs(ispin), nlumos)
     907             : 
     908             :          ! the full_all preconditioner makes not much sense for lumos search
     909          66 :          NULLIFY (local_preconditioner)
     910          66 :          IF (ASSOCIATED(scf_env%ot_preconditioner)) THEN
     911          26 :             local_preconditioner => scf_env%ot_preconditioner(1)%preconditioner
     912             :             ! this one can for sure not be right (as it has to match a given C0)
     913          26 :             IF (local_preconditioner%in_use == ot_precond_full_all) THEN
     914           4 :                NULLIFY (local_preconditioner)
     915             :             END IF
     916             :          END IF
     917             : 
     918             :          ! ** If we do ADMM, we add have to modify the kohn-sham matrix
     919          66 :          IF (dft_control%do_admm) THEN
     920           0 :             CALL admm_correct_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
     921             :          END IF
     922             : 
     923             :          CALL ot_eigensolver(matrix_h=ks_rmpv(ispin)%matrix, matrix_s=matrix_s(1)%matrix, &
     924             :                              matrix_c_fm=unoccupied_orbs(ispin), &
     925             :                              matrix_orthogonal_space_fm=mo_coeff, &
     926             :                              eps_gradient=scf_control%eps_lumos, &
     927             :                              preconditioner=local_preconditioner, &
     928             :                              iter_max=scf_control%max_iter_lumos, &
     929          66 :                              size_ortho_space=nmo)
     930             : 
     931             :          CALL calculate_subspace_eigenvalues(unoccupied_orbs(ispin), ks_rmpv(ispin)%matrix, &
     932             :                                              unoccupied_evals(ispin)%array, scr=output_unit, &
     933          66 :                                              ionode=output_unit > 0)
     934             : 
     935             :          ! ** If we do ADMM, we restore the original kohn-sham matrix
     936         178 :          IF (dft_control%do_admm) THEN
     937           0 :             CALL admm_uncorrect_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
     938             :          END IF
     939             : 
     940             :       END DO
     941             : 
     942          46 :       CALL timestop(handle)
     943             : 
     944          46 :    END SUBROUTINE make_lumo_gpw
     945             : ! **************************************************************************************************
     946             : !> \brief Computes and Prints Atomic Charges with several methods
     947             : !> \param input ...
     948             : !> \param logger ...
     949             : !> \param qs_env the qs_env in which the qs_env lives
     950             : ! **************************************************************************************************
     951        9591 :    SUBROUTINE qs_scf_post_charges(input, logger, qs_env)
     952             :       TYPE(section_vals_type), POINTER                   :: input
     953             :       TYPE(cp_logger_type), POINTER                      :: logger
     954             :       TYPE(qs_environment_type), POINTER                 :: qs_env
     955             : 
     956             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_charges'
     957             : 
     958             :       INTEGER                                            :: handle, print_level, unit_nr
     959             :       LOGICAL                                            :: do_kpoints, print_it
     960             :       TYPE(section_vals_type), POINTER                   :: density_fit_section, print_key
     961             : 
     962        9591 :       CALL timeset(routineN, handle)
     963             : 
     964        9591 :       CALL get_qs_env(qs_env=qs_env, do_kpoints=do_kpoints)
     965             : 
     966             :       ! Mulliken charges require no further computation and are printed from write_mo_free_results
     967             : 
     968             :       ! Compute the Lowdin charges
     969        9591 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%LOWDIN")
     970        9591 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
     971             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%LOWDIN", extension=".lowdin", &
     972          82 :                                         log_filename=.FALSE.)
     973          82 :          print_level = 1
     974          82 :          CALL section_vals_val_get(print_key, "PRINT_GOP", l_val=print_it)
     975          82 :          IF (print_it) print_level = 2
     976          82 :          CALL section_vals_val_get(print_key, "PRINT_ALL", l_val=print_it)
     977          82 :          IF (print_it) print_level = 3
     978          82 :          IF (do_kpoints) THEN
     979           2 :             CPWARN("Lowdin charges not implemented for k-point calculations!")
     980             :          ELSE
     981          80 :             CALL lowdin_population_analysis(qs_env, unit_nr, print_level)
     982             :          END IF
     983          82 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%LOWDIN")
     984             :       END IF
     985             : 
     986             :       ! Compute the RESP charges
     987        9591 :       CALL resp_fit(qs_env)
     988             : 
     989             :       ! Compute the Density Derived Atomic Point charges with the Bloechl scheme
     990        9591 :       print_key => section_vals_get_subs_vals(input, "PROPERTIES%FIT_CHARGE")
     991        9591 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
     992             :          unit_nr = cp_print_key_unit_nr(logger, input, "PROPERTIES%FIT_CHARGE", extension=".Fitcharge", &
     993         102 :                                         log_filename=.FALSE.)
     994         102 :          density_fit_section => section_vals_get_subs_vals(input, "DFT%DENSITY_FITTING")
     995         102 :          CALL get_ddapc(qs_env, .FALSE., density_fit_section, iwc=unit_nr)
     996         102 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "PROPERTIES%FIT_CHARGE")
     997             :       END IF
     998             : 
     999        9591 :       CALL timestop(handle)
    1000             : 
    1001        9591 :    END SUBROUTINE qs_scf_post_charges
    1002             : 
    1003             : ! **************************************************************************************************
    1004             : !> \brief Computes and prints the Cube Files for MO
    1005             : !> \param input ...
    1006             : !> \param dft_section ...
    1007             : !> \param dft_control ...
    1008             : !> \param logger ...
    1009             : !> \param qs_env the qs_env in which the qs_env lives
    1010             : !> \param mo_coeff ...
    1011             : !> \param wf_g ...
    1012             : !> \param wf_r ...
    1013             : !> \param particles ...
    1014             : !> \param homo ...
    1015             : !> \param ispin ...
    1016             : ! **************************************************************************************************
    1017         142 :    SUBROUTINE qs_scf_post_occ_cubes(input, dft_section, dft_control, logger, qs_env, &
    1018             :                                     mo_coeff, wf_g, wf_r, particles, homo, ispin)
    1019             :       TYPE(section_vals_type), POINTER                   :: input, dft_section
    1020             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1021             :       TYPE(cp_logger_type), POINTER                      :: logger
    1022             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1023             :       TYPE(cp_fm_type), INTENT(IN)                       :: mo_coeff
    1024             :       TYPE(pw_c1d_gs_type), INTENT(INOUT)                :: wf_g
    1025             :       TYPE(pw_r3d_rs_type), INTENT(INOUT)                :: wf_r
    1026             :       TYPE(particle_list_type), POINTER                  :: particles
    1027             :       INTEGER, INTENT(IN)                                :: homo, ispin
    1028             : 
    1029             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_occ_cubes'
    1030             : 
    1031             :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube, title
    1032             :       INTEGER                                            :: handle, i, ir, ivector, n_rep, nhomo, &
    1033             :                                                             nlist, unit_nr
    1034         142 :       INTEGER, DIMENSION(:), POINTER                     :: list, list_index
    1035             :       LOGICAL                                            :: append_cube, mpi_io
    1036         142 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1037             :       TYPE(cell_type), POINTER                           :: cell
    1038         142 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1039             :       TYPE(pw_env_type), POINTER                         :: pw_env
    1040         142 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1041             : 
    1042         142 :       CALL timeset(routineN, handle)
    1043             : 
    1044         142 :       NULLIFY (list_index)
    1045             : 
    1046             :       IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%MO_CUBES") &
    1047         142 :                 , cp_p_file) .AND. section_get_lval(dft_section, "PRINT%MO_CUBES%WRITE_CUBE")) THEN
    1048         104 :          nhomo = section_get_ival(dft_section, "PRINT%MO_CUBES%NHOMO")
    1049         104 :          append_cube = section_get_lval(dft_section, "PRINT%MO_CUBES%APPEND")
    1050         104 :          my_pos_cube = "REWIND"
    1051         104 :          IF (append_cube) THEN
    1052           0 :             my_pos_cube = "APPEND"
    1053             :          END IF
    1054         104 :          CALL section_vals_val_get(dft_section, "PRINT%MO_CUBES%HOMO_LIST", n_rep_val=n_rep)
    1055         104 :          IF (n_rep > 0) THEN ! write the cubes of the list
    1056           0 :             nlist = 0
    1057           0 :             DO ir = 1, n_rep
    1058           0 :                NULLIFY (list)
    1059             :                CALL section_vals_val_get(dft_section, "PRINT%MO_CUBES%HOMO_LIST", i_rep_val=ir, &
    1060           0 :                                          i_vals=list)
    1061           0 :                IF (ASSOCIATED(list)) THEN
    1062           0 :                   CALL reallocate(list_index, 1, nlist + SIZE(list))
    1063           0 :                   DO i = 1, SIZE(list)
    1064           0 :                      list_index(i + nlist) = list(i)
    1065             :                   END DO
    1066           0 :                   nlist = nlist + SIZE(list)
    1067             :                END IF
    1068             :             END DO
    1069             :          ELSE
    1070             : 
    1071         104 :             IF (nhomo == -1) nhomo = homo
    1072         104 :             nlist = homo - MAX(1, homo - nhomo + 1) + 1
    1073         312 :             ALLOCATE (list_index(nlist))
    1074         212 :             DO i = 1, nlist
    1075         212 :                list_index(i) = MAX(1, homo - nhomo + 1) + i - 1
    1076             :             END DO
    1077             :          END IF
    1078         212 :          DO i = 1, nlist
    1079         108 :             ivector = list_index(i)
    1080             :             CALL get_qs_env(qs_env=qs_env, &
    1081             :                             atomic_kind_set=atomic_kind_set, &
    1082             :                             qs_kind_set=qs_kind_set, &
    1083             :                             cell=cell, &
    1084             :                             particle_set=particle_set, &
    1085         108 :                             pw_env=pw_env)
    1086             :             CALL calculate_wavefunction(mo_coeff, ivector, wf_r, wf_g, atomic_kind_set, qs_kind_set, &
    1087         108 :                                         cell, dft_control, particle_set, pw_env)
    1088         108 :             WRITE (filename, '(a4,I5.5,a1,I1.1)') "WFN_", ivector, "_", ispin
    1089         108 :             mpi_io = .TRUE.
    1090             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MO_CUBES", extension=".cube", &
    1091             :                                            middle_name=TRIM(filename), file_position=my_pos_cube, log_filename=.FALSE., &
    1092         108 :                                            mpi_io=mpi_io)
    1093         108 :             WRITE (title, *) "WAVEFUNCTION ", ivector, " spin ", ispin, " i.e. HOMO - ", ivector - homo
    1094             :             CALL cp_pw_to_cube(wf_r, unit_nr, title, particles=particles, &
    1095         108 :                                stride=section_get_ivals(dft_section, "PRINT%MO_CUBES%STRIDE"), mpi_io=mpi_io)
    1096         212 :             CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MO_CUBES", mpi_io=mpi_io)
    1097             :          END DO
    1098         104 :          IF (ASSOCIATED(list_index)) DEALLOCATE (list_index)
    1099             :       END IF
    1100             : 
    1101         142 :       CALL timestop(handle)
    1102             : 
    1103         142 :    END SUBROUTINE qs_scf_post_occ_cubes
    1104             : 
    1105             : ! **************************************************************************************************
    1106             : !> \brief Computes and prints the Cube Files for MO
    1107             : !> \param input ...
    1108             : !> \param dft_section ...
    1109             : !> \param dft_control ...
    1110             : !> \param logger ...
    1111             : !> \param qs_env the qs_env in which the qs_env lives
    1112             : !> \param unoccupied_orbs ...
    1113             : !> \param wf_g ...
    1114             : !> \param wf_r ...
    1115             : !> \param particles ...
    1116             : !> \param nlumos ...
    1117             : !> \param homo ...
    1118             : !> \param ispin ...
    1119             : !> \param lumo ...
    1120             : ! **************************************************************************************************
    1121         158 :    SUBROUTINE qs_scf_post_unocc_cubes(input, dft_section, dft_control, logger, qs_env, &
    1122             :                                       unoccupied_orbs, wf_g, wf_r, particles, nlumos, homo, ispin, lumo)
    1123             : 
    1124             :       TYPE(section_vals_type), POINTER                   :: input, dft_section
    1125             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1126             :       TYPE(cp_logger_type), POINTER                      :: logger
    1127             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1128             :       TYPE(cp_fm_type), INTENT(IN)                       :: unoccupied_orbs
    1129             :       TYPE(pw_c1d_gs_type), INTENT(INOUT)                :: wf_g
    1130             :       TYPE(pw_r3d_rs_type), INTENT(INOUT)                :: wf_r
    1131             :       TYPE(particle_list_type), POINTER                  :: particles
    1132             :       INTEGER, INTENT(IN)                                :: nlumos, homo, ispin
    1133             :       INTEGER, INTENT(IN), OPTIONAL                      :: lumo
    1134             : 
    1135             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_unocc_cubes'
    1136             : 
    1137             :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube, title
    1138             :       INTEGER                                            :: handle, ifirst, index_mo, ivector, &
    1139             :                                                             unit_nr
    1140             :       LOGICAL                                            :: append_cube, mpi_io
    1141         158 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1142             :       TYPE(cell_type), POINTER                           :: cell
    1143         158 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1144             :       TYPE(pw_env_type), POINTER                         :: pw_env
    1145         158 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1146             : 
    1147         158 :       CALL timeset(routineN, handle)
    1148             : 
    1149             :       IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%MO_CUBES"), cp_p_file) &
    1150         158 :           .AND. section_get_lval(dft_section, "PRINT%MO_CUBES%WRITE_CUBE")) THEN
    1151         104 :          NULLIFY (qs_kind_set, particle_set, pw_env, cell)
    1152         104 :          append_cube = section_get_lval(dft_section, "PRINT%MO_CUBES%APPEND")
    1153         104 :          my_pos_cube = "REWIND"
    1154         104 :          IF (append_cube) THEN
    1155           0 :             my_pos_cube = "APPEND"
    1156             :          END IF
    1157         104 :          ifirst = 1
    1158         104 :          IF (PRESENT(lumo)) ifirst = lumo
    1159         242 :          DO ivector = ifirst, ifirst + nlumos - 1
    1160             :             CALL get_qs_env(qs_env=qs_env, &
    1161             :                             atomic_kind_set=atomic_kind_set, &
    1162             :                             qs_kind_set=qs_kind_set, &
    1163             :                             cell=cell, &
    1164             :                             particle_set=particle_set, &
    1165         138 :                             pw_env=pw_env)
    1166             :             CALL calculate_wavefunction(unoccupied_orbs, ivector, wf_r, wf_g, atomic_kind_set, &
    1167         138 :                                         qs_kind_set, cell, dft_control, particle_set, pw_env)
    1168             : 
    1169         138 :             IF (ifirst == 1) THEN
    1170         130 :                index_mo = homo + ivector
    1171             :             ELSE
    1172           8 :                index_mo = ivector
    1173             :             END IF
    1174         138 :             WRITE (filename, '(a4,I5.5,a1,I1.1)') "WFN_", index_mo, "_", ispin
    1175         138 :             mpi_io = .TRUE.
    1176             : 
    1177             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MO_CUBES", extension=".cube", &
    1178             :                                            middle_name=TRIM(filename), file_position=my_pos_cube, log_filename=.FALSE., &
    1179         138 :                                            mpi_io=mpi_io)
    1180         138 :             WRITE (title, *) "WAVEFUNCTION ", index_mo, " spin ", ispin, " i.e. LUMO + ", ifirst + ivector - 2
    1181             :             CALL cp_pw_to_cube(wf_r, unit_nr, title, particles=particles, &
    1182         138 :                                stride=section_get_ivals(dft_section, "PRINT%MO_CUBES%STRIDE"), mpi_io=mpi_io)
    1183         242 :             CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MO_CUBES", mpi_io=mpi_io)
    1184             :          END DO
    1185             :       END IF
    1186             : 
    1187         158 :       CALL timestop(handle)
    1188             : 
    1189         158 :    END SUBROUTINE qs_scf_post_unocc_cubes
    1190             : 
    1191             : ! **************************************************************************************************
    1192             : !> \brief Computes and prints electric moments
    1193             : !> \param input ...
    1194             : !> \param logger ...
    1195             : !> \param qs_env the qs_env in which the qs_env lives
    1196             : !> \param output_unit ...
    1197             : ! **************************************************************************************************
    1198       10761 :    SUBROUTINE qs_scf_post_moments(input, logger, qs_env, output_unit)
    1199             :       TYPE(section_vals_type), POINTER                   :: input
    1200             :       TYPE(cp_logger_type), POINTER                      :: logger
    1201             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1202             :       INTEGER, INTENT(IN)                                :: output_unit
    1203             : 
    1204             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_moments'
    1205             : 
    1206             :       CHARACTER(LEN=default_path_length)                 :: filename
    1207             :       INTEGER                                            :: handle, maxmom, reference, unit_nr
    1208             :       LOGICAL                                            :: com_nl, do_kpoints, magnetic, periodic, &
    1209             :                                                             second_ref_point, vel_reprs
    1210       10761 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: ref_point
    1211             :       TYPE(section_vals_type), POINTER                   :: print_key
    1212             : 
    1213       10761 :       CALL timeset(routineN, handle)
    1214             : 
    1215             :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1216       10761 :                                               subsection_name="DFT%PRINT%MOMENTS")
    1217             : 
    1218       10761 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    1219             : 
    1220             :          maxmom = section_get_ival(section_vals=input, &
    1221        1120 :                                    keyword_name="DFT%PRINT%MOMENTS%MAX_MOMENT")
    1222             :          periodic = section_get_lval(section_vals=input, &
    1223        1120 :                                      keyword_name="DFT%PRINT%MOMENTS%PERIODIC")
    1224             :          reference = section_get_ival(section_vals=input, &
    1225        1120 :                                       keyword_name="DFT%PRINT%MOMENTS%REFERENCE")
    1226             :          magnetic = section_get_lval(section_vals=input, &
    1227        1120 :                                      keyword_name="DFT%PRINT%MOMENTS%MAGNETIC")
    1228             :          vel_reprs = section_get_lval(section_vals=input, &
    1229        1120 :                                       keyword_name="DFT%PRINT%MOMENTS%VEL_REPRS")
    1230             :          com_nl = section_get_lval(section_vals=input, &
    1231        1120 :                                    keyword_name="DFT%PRINT%MOMENTS%COM_NL")
    1232             :          second_ref_point = section_get_lval(section_vals=input, &
    1233        1120 :                                              keyword_name="DFT%PRINT%MOMENTS%SECOND_REFERENCE_POINT")
    1234             : 
    1235        1120 :          NULLIFY (ref_point)
    1236        1120 :          CALL section_vals_val_get(input, "DFT%PRINT%MOMENTS%REF_POINT", r_vals=ref_point)
    1237             :          unit_nr = cp_print_key_unit_nr(logger=logger, basis_section=input, &
    1238             :                                         print_key_path="DFT%PRINT%MOMENTS", extension=".dat", &
    1239        1120 :                                         middle_name="moments", log_filename=.FALSE.)
    1240             : 
    1241        1120 :          IF (output_unit > 0) THEN
    1242         570 :             IF (unit_nr /= output_unit) THEN
    1243          33 :                INQUIRE (UNIT=unit_nr, NAME=filename)
    1244             :                WRITE (UNIT=output_unit, FMT="(/,T2,A,2(/,T3,A),/)") &
    1245          33 :                   "MOMENTS", "The electric/magnetic moments are written to file:", &
    1246          66 :                   TRIM(filename)
    1247             :             ELSE
    1248         537 :                WRITE (UNIT=output_unit, FMT="(/,T2,A)") "ELECTRIC/MAGNETIC MOMENTS"
    1249             :             END IF
    1250             :          END IF
    1251             : 
    1252        1120 :          CALL get_qs_env(qs_env, do_kpoints=do_kpoints)
    1253             : 
    1254        1120 :          IF (do_kpoints) THEN
    1255           2 :             CPWARN("Moments not implemented for k-point calculations!")
    1256             :          ELSE
    1257        1118 :             IF (periodic) THEN
    1258         340 :                CALL qs_moment_berry_phase(qs_env, magnetic, maxmom, reference, ref_point, unit_nr)
    1259             :             ELSE
    1260         778 :                CALL qs_moment_locop(qs_env, magnetic, maxmom, reference, ref_point, unit_nr, vel_reprs, com_nl)
    1261             :             END IF
    1262             :          END IF
    1263             : 
    1264             :          CALL cp_print_key_finished_output(unit_nr=unit_nr, logger=logger, &
    1265        1120 :                                            basis_section=input, print_key_path="DFT%PRINT%MOMENTS")
    1266             : 
    1267        1120 :          IF (second_ref_point) THEN
    1268             :             reference = section_get_ival(section_vals=input, &
    1269           0 :                                          keyword_name="DFT%PRINT%MOMENTS%REFERENCE_2")
    1270             : 
    1271           0 :             NULLIFY (ref_point)
    1272           0 :             CALL section_vals_val_get(input, "DFT%PRINT%MOMENTS%REF_POINT_2", r_vals=ref_point)
    1273             :             unit_nr = cp_print_key_unit_nr(logger=logger, basis_section=input, &
    1274             :                                            print_key_path="DFT%PRINT%MOMENTS", extension=".dat", &
    1275           0 :                                            middle_name="moments_refpoint_2", log_filename=.FALSE.)
    1276             : 
    1277           0 :             IF (output_unit > 0) THEN
    1278           0 :                IF (unit_nr /= output_unit) THEN
    1279           0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    1280             :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,2(/,T3,A),/)") &
    1281           0 :                      "MOMENTS", "The electric/magnetic moments for the second reference point are written to file:", &
    1282           0 :                      TRIM(filename)
    1283             :                ELSE
    1284           0 :                   WRITE (UNIT=output_unit, FMT="(/,T2,A)") "ELECTRIC/MAGNETIC MOMENTS"
    1285             :                END IF
    1286             :             END IF
    1287           0 :             IF (do_kpoints) THEN
    1288           0 :                CPWARN("Moments not implemented for k-point calculations!")
    1289             :             ELSE
    1290           0 :                IF (periodic) THEN
    1291           0 :                   CALL qs_moment_berry_phase(qs_env, magnetic, maxmom, reference, ref_point, unit_nr)
    1292             :                ELSE
    1293           0 :                   CALL qs_moment_locop(qs_env, magnetic, maxmom, reference, ref_point, unit_nr, vel_reprs, com_nl)
    1294             :                END IF
    1295             :             END IF
    1296             :             CALL cp_print_key_finished_output(unit_nr=unit_nr, logger=logger, &
    1297           0 :                                               basis_section=input, print_key_path="DFT%PRINT%MOMENTS")
    1298             :          END IF
    1299             : 
    1300             :       END IF
    1301             : 
    1302       10761 :       CALL timestop(handle)
    1303             : 
    1304       10761 :    END SUBROUTINE qs_scf_post_moments
    1305             : 
    1306             : ! **************************************************************************************************
    1307             : !> \brief Computes and prints the X-ray diffraction spectrum.
    1308             : !> \param input ...
    1309             : !> \param dft_section ...
    1310             : !> \param logger ...
    1311             : !> \param qs_env the qs_env in which the qs_env lives
    1312             : !> \param output_unit ...
    1313             : ! **************************************************************************************************
    1314        9591 :    SUBROUTINE qs_scf_post_xray(input, dft_section, logger, qs_env, output_unit)
    1315             : 
    1316             :       TYPE(section_vals_type), POINTER                   :: input, dft_section
    1317             :       TYPE(cp_logger_type), POINTER                      :: logger
    1318             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1319             :       INTEGER, INTENT(IN)                                :: output_unit
    1320             : 
    1321             :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_scf_post_xray'
    1322             : 
    1323             :       CHARACTER(LEN=default_path_length)                 :: filename
    1324             :       INTEGER                                            :: handle, unit_nr
    1325             :       REAL(KIND=dp)                                      :: q_max
    1326             :       TYPE(section_vals_type), POINTER                   :: print_key
    1327             : 
    1328        9591 :       CALL timeset(routineN, handle)
    1329             : 
    1330             :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1331        9591 :                                               subsection_name="DFT%PRINT%XRAY_DIFFRACTION_SPECTRUM")
    1332             : 
    1333        9591 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    1334             :          q_max = section_get_rval(section_vals=dft_section, &
    1335          30 :                                   keyword_name="PRINT%XRAY_DIFFRACTION_SPECTRUM%Q_MAX")
    1336             :          unit_nr = cp_print_key_unit_nr(logger=logger, &
    1337             :                                         basis_section=input, &
    1338             :                                         print_key_path="DFT%PRINT%XRAY_DIFFRACTION_SPECTRUM", &
    1339             :                                         extension=".dat", &
    1340             :                                         middle_name="xrd", &
    1341          30 :                                         log_filename=.FALSE.)
    1342          30 :          IF (output_unit > 0) THEN
    1343          15 :             INQUIRE (UNIT=unit_nr, NAME=filename)
    1344             :             WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
    1345          15 :                "X-RAY DIFFRACTION SPECTRUM"
    1346          15 :             IF (unit_nr /= output_unit) THEN
    1347             :                WRITE (UNIT=output_unit, FMT="(/,T3,A,/,/,T3,A,/)") &
    1348          14 :                   "The coherent X-ray diffraction spectrum is written to the file:", &
    1349          28 :                   TRIM(filename)
    1350             :             END IF
    1351             :          END IF
    1352             :          CALL xray_diffraction_spectrum(qs_env=qs_env, &
    1353             :                                         unit_number=unit_nr, &
    1354          30 :                                         q_max=q_max)
    1355             :          CALL cp_print_key_finished_output(unit_nr=unit_nr, &
    1356             :                                            logger=logger, &
    1357             :                                            basis_section=input, &
    1358          30 :                                            print_key_path="DFT%PRINT%XRAY_DIFFRACTION_SPECTRUM")
    1359             :       END IF
    1360             : 
    1361        9591 :       CALL timestop(handle)
    1362             : 
    1363        9591 :    END SUBROUTINE qs_scf_post_xray
    1364             : 
    1365             : ! **************************************************************************************************
    1366             : !> \brief Computes and prints Electric Field Gradient
    1367             : !> \param input ...
    1368             : !> \param logger ...
    1369             : !> \param qs_env the qs_env in which the qs_env lives
    1370             : ! **************************************************************************************************
    1371        9591 :    SUBROUTINE qs_scf_post_efg(input, logger, qs_env)
    1372             :       TYPE(section_vals_type), POINTER                   :: input
    1373             :       TYPE(cp_logger_type), POINTER                      :: logger
    1374             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1375             : 
    1376             :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_efg'
    1377             : 
    1378             :       INTEGER                                            :: handle
    1379             :       TYPE(section_vals_type), POINTER                   :: print_key
    1380             : 
    1381        9591 :       CALL timeset(routineN, handle)
    1382             : 
    1383             :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1384        9591 :                                               subsection_name="DFT%PRINT%ELECTRIC_FIELD_GRADIENT")
    1385        9591 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), &
    1386             :                 cp_p_file)) THEN
    1387          30 :          CALL qs_efg_calc(qs_env=qs_env)
    1388             :       END IF
    1389             : 
    1390        9591 :       CALL timestop(handle)
    1391             : 
    1392        9591 :    END SUBROUTINE qs_scf_post_efg
    1393             : 
    1394             : ! **************************************************************************************************
    1395             : !> \brief Computes the Electron Transfer Coupling matrix element
    1396             : !> \param input ...
    1397             : !> \param qs_env the qs_env in which the qs_env lives
    1398             : !> \param dft_control ...
    1399             : ! **************************************************************************************************
    1400       19182 :    SUBROUTINE qs_scf_post_et(input, qs_env, dft_control)
    1401             :       TYPE(section_vals_type), POINTER                   :: input
    1402             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1403             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1404             : 
    1405             :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_et'
    1406             : 
    1407             :       INTEGER                                            :: handle, ispin
    1408             :       LOGICAL                                            :: do_et
    1409        9591 :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: my_mos
    1410             :       TYPE(section_vals_type), POINTER                   :: et_section
    1411             : 
    1412        9591 :       CALL timeset(routineN, handle)
    1413             : 
    1414             :       do_et = .FALSE.
    1415        9591 :       et_section => section_vals_get_subs_vals(input, "PROPERTIES%ET_COUPLING")
    1416        9591 :       CALL section_vals_get(et_section, explicit=do_et)
    1417        9591 :       IF (do_et) THEN
    1418          10 :          IF (qs_env%et_coupling%first_run) THEN
    1419          10 :             NULLIFY (my_mos)
    1420          50 :             ALLOCATE (my_mos(dft_control%nspins))
    1421          50 :             ALLOCATE (qs_env%et_coupling%et_mo_coeff(dft_control%nspins))
    1422          30 :             DO ispin = 1, dft_control%nspins
    1423             :                CALL cp_fm_create(matrix=my_mos(ispin), &
    1424             :                                  matrix_struct=qs_env%mos(ispin)%mo_coeff%matrix_struct, &
    1425          20 :                                  name="FIRST_RUN_COEFF"//TRIM(ADJUSTL(cp_to_string(ispin)))//"MATRIX")
    1426             :                CALL cp_fm_to_fm(qs_env%mos(ispin)%mo_coeff, &
    1427          30 :                                 my_mos(ispin))
    1428             :             END DO
    1429          10 :             CALL set_et_coupling_type(qs_env%et_coupling, et_mo_coeff=my_mos)
    1430          10 :             DEALLOCATE (my_mos)
    1431             :          END IF
    1432             :       END IF
    1433             : 
    1434        9591 :       CALL timestop(handle)
    1435             : 
    1436        9591 :    END SUBROUTINE qs_scf_post_et
    1437             : 
    1438             : ! **************************************************************************************************
    1439             : !> \brief compute the electron localization function
    1440             : !>
    1441             : !> \param input ...
    1442             : !> \param logger ...
    1443             : !> \param qs_env ...
    1444             : !> \par History
    1445             : !>      2012-07 Created [MI]
    1446             : ! **************************************************************************************************
    1447        9591 :    SUBROUTINE qs_scf_post_elf(input, logger, qs_env)
    1448             :       TYPE(section_vals_type), POINTER                   :: input
    1449             :       TYPE(cp_logger_type), POINTER                      :: logger
    1450             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1451             : 
    1452             :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_elf'
    1453             : 
    1454             :       CHARACTER(LEN=default_path_length)                 :: filename, mpi_filename, my_pos_cube, &
    1455             :                                                             title
    1456             :       INTEGER                                            :: handle, ispin, output_unit, unit_nr
    1457             :       LOGICAL                                            :: append_cube, gapw, mpi_io
    1458             :       REAL(dp)                                           :: rho_cutoff
    1459             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1460             :       TYPE(particle_list_type), POINTER                  :: particles
    1461             :       TYPE(pw_env_type), POINTER                         :: pw_env
    1462        9591 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
    1463             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    1464        9591 :       TYPE(pw_r3d_rs_type), ALLOCATABLE, DIMENSION(:)    :: elf_r
    1465             :       TYPE(qs_subsys_type), POINTER                      :: subsys
    1466             :       TYPE(section_vals_type), POINTER                   :: elf_section
    1467             : 
    1468        9591 :       CALL timeset(routineN, handle)
    1469        9591 :       output_unit = cp_logger_get_default_io_unit(logger)
    1470             : 
    1471        9591 :       elf_section => section_vals_get_subs_vals(input, "DFT%PRINT%ELF_CUBE")
    1472        9591 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    1473             :                                            "DFT%PRINT%ELF_CUBE"), cp_p_file)) THEN
    1474             : 
    1475          80 :          NULLIFY (dft_control, pw_env, auxbas_pw_pool, pw_pools, particles, subsys)
    1476          80 :          CALL get_qs_env(qs_env, dft_control=dft_control, pw_env=pw_env, subsys=subsys)
    1477          80 :          CALL qs_subsys_get(subsys, particles=particles)
    1478             : 
    1479          80 :          gapw = dft_control%qs_control%gapw
    1480          80 :          IF (.NOT. gapw) THEN
    1481             :             ! allocate
    1482         322 :             ALLOCATE (elf_r(dft_control%nspins))
    1483             :             CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    1484          80 :                             pw_pools=pw_pools)
    1485         162 :             DO ispin = 1, dft_control%nspins
    1486          82 :                CALL auxbas_pw_pool%create_pw(elf_r(ispin))
    1487         162 :                CALL pw_zero(elf_r(ispin))
    1488             :             END DO
    1489             : 
    1490          80 :             IF (output_unit > 0) THEN
    1491             :                WRITE (UNIT=output_unit, FMT="(/,T15,A,/)") &
    1492          40 :                   " ----- ELF is computed on the real space grid -----"
    1493             :             END IF
    1494          80 :             rho_cutoff = section_get_rval(elf_section, "density_cutoff")
    1495          80 :             CALL qs_elf_calc(qs_env, elf_r, rho_cutoff)
    1496             : 
    1497             :             ! write ELF into cube file
    1498          80 :             append_cube = section_get_lval(elf_section, "APPEND")
    1499          80 :             my_pos_cube = "REWIND"
    1500          80 :             IF (append_cube) THEN
    1501           0 :                my_pos_cube = "APPEND"
    1502             :             END IF
    1503             : 
    1504         162 :             DO ispin = 1, dft_control%nspins
    1505          82 :                WRITE (filename, '(a5,I1.1)') "ELF_S", ispin
    1506          82 :                WRITE (title, *) "ELF spin ", ispin
    1507          82 :                mpi_io = .TRUE.
    1508             :                unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%ELF_CUBE", extension=".cube", &
    1509             :                                               middle_name=TRIM(filename), file_position=my_pos_cube, log_filename=.FALSE., &
    1510          82 :                                               mpi_io=mpi_io, fout=mpi_filename)
    1511          82 :                IF (output_unit > 0) THEN
    1512          41 :                   IF (.NOT. mpi_io) THEN
    1513           0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    1514             :                   ELSE
    1515          41 :                      filename = mpi_filename
    1516             :                   END IF
    1517             :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    1518          41 :                      "ELF is written in cube file format to the file:", &
    1519          82 :                      TRIM(filename)
    1520             :                END IF
    1521             : 
    1522             :                CALL cp_pw_to_cube(elf_r(ispin), unit_nr, title, particles=particles, &
    1523          82 :                                   stride=section_get_ivals(elf_section, "STRIDE"), mpi_io=mpi_io)
    1524          82 :                CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%ELF_CUBE", mpi_io=mpi_io)
    1525             : 
    1526         162 :                CALL auxbas_pw_pool%give_back_pw(elf_r(ispin))
    1527             :             END DO
    1528             : 
    1529             :             ! deallocate
    1530          80 :             DEALLOCATE (elf_r)
    1531             : 
    1532             :          ELSE
    1533             :             ! not implemented
    1534           0 :             CPWARN("ELF not implemented for GAPW calculations!!")
    1535             : 
    1536             :          END IF
    1537             : 
    1538             :       END IF ! print key
    1539             : 
    1540        9591 :       CALL timestop(handle)
    1541             : 
    1542       19182 :    END SUBROUTINE qs_scf_post_elf
    1543             : 
    1544             : ! **************************************************************************************************
    1545             : !> \brief computes the condition number of the overlap matrix and
    1546             : !>      prints the value of the total energy. This is needed
    1547             : !>      for BASIS_MOLOPT optimizations
    1548             : !> \param input ...
    1549             : !> \param logger ...
    1550             : !> \param qs_env the qs_env in which the qs_env lives
    1551             : !> \par History
    1552             : !>      2007-07 Created [Joost VandeVondele]
    1553             : ! **************************************************************************************************
    1554        9591 :    SUBROUTINE qs_scf_post_molopt(input, logger, qs_env)
    1555             :       TYPE(section_vals_type), POINTER                   :: input
    1556             :       TYPE(cp_logger_type), POINTER                      :: logger
    1557             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1558             : 
    1559             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_molopt'
    1560             : 
    1561             :       INTEGER                                            :: handle, nao, unit_nr
    1562             :       REAL(KIND=dp)                                      :: S_cond_number
    1563        9591 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenvalues
    1564             :       TYPE(cp_fm_struct_type), POINTER                   :: ao_ao_fmstruct
    1565             :       TYPE(cp_fm_type)                                   :: fm_s, fm_work
    1566             :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1567        9591 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_s
    1568        9591 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1569             :       TYPE(qs_energy_type), POINTER                      :: energy
    1570             :       TYPE(section_vals_type), POINTER                   :: print_key
    1571             : 
    1572        9591 :       CALL timeset(routineN, handle)
    1573             : 
    1574             :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1575        9591 :                                               subsection_name="DFT%PRINT%BASIS_MOLOPT_QUANTITIES")
    1576        9591 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), &
    1577             :                 cp_p_file)) THEN
    1578             : 
    1579          28 :          CALL get_qs_env(qs_env, energy=energy, matrix_s=matrix_s, mos=mos)
    1580             : 
    1581             :          ! set up the two needed full matrices, using mo_coeff as a template
    1582          28 :          CALL get_mo_set(mo_set=mos(1), mo_coeff=mo_coeff, nao=nao)
    1583             :          CALL cp_fm_struct_create(fmstruct=ao_ao_fmstruct, &
    1584             :                                   nrow_global=nao, ncol_global=nao, &
    1585          28 :                                   template_fmstruct=mo_coeff%matrix_struct)
    1586             :          CALL cp_fm_create(fm_s, matrix_struct=ao_ao_fmstruct, &
    1587          28 :                            name="fm_s")
    1588             :          CALL cp_fm_create(fm_work, matrix_struct=ao_ao_fmstruct, &
    1589          28 :                            name="fm_work")
    1590          28 :          CALL cp_fm_struct_release(ao_ao_fmstruct)
    1591          84 :          ALLOCATE (eigenvalues(nao))
    1592             : 
    1593          28 :          CALL copy_dbcsr_to_fm(matrix_s(1)%matrix, fm_s)
    1594          28 :          CALL choose_eigv_solver(fm_s, fm_work, eigenvalues)
    1595             : 
    1596          28 :          CALL cp_fm_release(fm_s)
    1597          28 :          CALL cp_fm_release(fm_work)
    1598             : 
    1599        1048 :          S_cond_number = MAXVAL(ABS(eigenvalues))/MAX(MINVAL(ABS(eigenvalues)), EPSILON(0.0_dp))
    1600             : 
    1601             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%BASIS_MOLOPT_QUANTITIES", &
    1602          28 :                                         extension=".molopt")
    1603             : 
    1604          28 :          IF (unit_nr > 0) THEN
    1605             :             ! please keep this format fixed, needs to be grepable for molopt
    1606             :             ! optimizations
    1607          14 :             WRITE (unit_nr, '(T2,A28,2A25)') "", "Tot. Ener.", "S Cond. Numb."
    1608          14 :             WRITE (unit_nr, '(T2,A28,2E25.17)') "BASIS_MOLOPT_QUANTITIES", energy%total, S_cond_number
    1609             :          END IF
    1610             : 
    1611             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    1612          84 :                                            "DFT%PRINT%BASIS_MOLOPT_QUANTITIES")
    1613             : 
    1614             :       END IF
    1615             : 
    1616        9591 :       CALL timestop(handle)
    1617             : 
    1618       19182 :    END SUBROUTINE qs_scf_post_molopt
    1619             : 
    1620             : ! **************************************************************************************************
    1621             : !> \brief Dumps EPR
    1622             : !> \param input ...
    1623             : !> \param logger ...
    1624             : !> \param qs_env the qs_env in which the qs_env lives
    1625             : ! **************************************************************************************************
    1626        9591 :    SUBROUTINE qs_scf_post_epr(input, logger, qs_env)
    1627             :       TYPE(section_vals_type), POINTER                   :: input
    1628             :       TYPE(cp_logger_type), POINTER                      :: logger
    1629             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1630             : 
    1631             :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_epr'
    1632             : 
    1633             :       INTEGER                                            :: handle
    1634             :       TYPE(section_vals_type), POINTER                   :: print_key
    1635             : 
    1636        9591 :       CALL timeset(routineN, handle)
    1637             : 
    1638             :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1639        9591 :                                               subsection_name="DFT%PRINT%HYPERFINE_COUPLING_TENSOR")
    1640        9591 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), &
    1641             :                 cp_p_file)) THEN
    1642          30 :          CALL qs_epr_hyp_calc(qs_env=qs_env)
    1643             :       END IF
    1644             : 
    1645        9591 :       CALL timestop(handle)
    1646             : 
    1647        9591 :    END SUBROUTINE qs_scf_post_epr
    1648             : 
    1649             : ! **************************************************************************************************
    1650             : !> \brief Interface routine to trigger writing of results available from normal
    1651             : !>        SCF. Can write MO-dependent and MO free results (needed for call from
    1652             : !>        the linear scaling code)
    1653             : !> \param qs_env the qs_env in which the qs_env lives
    1654             : !> \param scf_env ...
    1655             : ! **************************************************************************************************
    1656        9591 :    SUBROUTINE write_available_results(qs_env, scf_env)
    1657             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1658             :       TYPE(qs_scf_env_type), OPTIONAL, POINTER           :: scf_env
    1659             : 
    1660             :       CHARACTER(len=*), PARAMETER :: routineN = 'write_available_results'
    1661             : 
    1662             :       INTEGER                                            :: handle
    1663             : 
    1664        9591 :       CALL timeset(routineN, handle)
    1665             : 
    1666             :       ! those properties that require MOs (not suitable density matrix based methods)
    1667        9591 :       CALL write_mo_dependent_results(qs_env, scf_env)
    1668             : 
    1669             :       ! those that depend only on the density matrix, they should be linear scaling in their implementation
    1670        9591 :       CALL write_mo_free_results(qs_env)
    1671             : 
    1672        9591 :       CALL timestop(handle)
    1673             : 
    1674        9591 :    END SUBROUTINE write_available_results
    1675             : 
    1676             : ! **************************************************************************************************
    1677             : !> \brief Write QS results available if MO's are present (if switched on through the print_keys)
    1678             : !>        Writes only MO dependent results. Split is necessary as ls_scf does not
    1679             : !>        provide MO's
    1680             : !> \param qs_env the qs_env in which the qs_env lives
    1681             : !> \param scf_env ...
    1682             : ! **************************************************************************************************
    1683        9903 :    SUBROUTINE write_mo_dependent_results(qs_env, scf_env)
    1684             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1685             :       TYPE(qs_scf_env_type), OPTIONAL, POINTER           :: scf_env
    1686             : 
    1687             :       CHARACTER(len=*), PARAMETER :: routineN = 'write_mo_dependent_results'
    1688             : 
    1689             :       INTEGER                                            :: handle, homo, ispin, nmo, output_unit
    1690             :       LOGICAL                                            :: all_equal, do_kpoints
    1691             :       REAL(KIND=dp)                                      :: maxocc, s_square, s_square_ideal, &
    1692             :                                                             total_abs_spin_dens
    1693        9903 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: mo_eigenvalues, occupation_numbers
    1694             :       TYPE(admm_type), POINTER                           :: admm_env
    1695        9903 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1696             :       TYPE(cell_type), POINTER                           :: cell
    1697             :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1698             :       TYPE(cp_logger_type), POINTER                      :: logger
    1699        9903 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_rmpv, matrix_s
    1700             :       TYPE(dbcsr_type), POINTER                          :: mo_coeff_deriv
    1701             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1702             :       TYPE(kpoint_type), POINTER                         :: kpoints
    1703        9903 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1704        9903 :       TYPE(molecule_type), POINTER                       :: molecule_set(:)
    1705             :       TYPE(particle_list_type), POINTER                  :: particles
    1706        9903 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1707             :       TYPE(pw_env_type), POINTER                         :: pw_env
    1708        9903 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
    1709             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    1710             :       TYPE(pw_r3d_rs_type)                               :: wf_r
    1711        9903 :       TYPE(pw_r3d_rs_type), DIMENSION(:), POINTER        :: rho_r
    1712             :       TYPE(qs_energy_type), POINTER                      :: energy
    1713        9903 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1714             :       TYPE(qs_rho_type), POINTER                         :: rho
    1715             :       TYPE(qs_subsys_type), POINTER                      :: subsys
    1716             :       TYPE(scf_control_type), POINTER                    :: scf_control
    1717             :       TYPE(section_vals_type), POINTER                   :: dft_section, input, sprint_section
    1718             : 
    1719        9903 :       CALL timeset(routineN, handle)
    1720             : 
    1721        9903 :       NULLIFY (cell, dft_control, pw_env, auxbas_pw_pool, pw_pools, mo_coeff, &
    1722        9903 :                mo_coeff_deriv, mo_eigenvalues, mos, atomic_kind_set, qs_kind_set, &
    1723        9903 :                particle_set, rho, ks_rmpv, matrix_s, scf_control, dft_section, &
    1724        9903 :                molecule_set, input, particles, subsys, rho_r)
    1725             : 
    1726        9903 :       logger => cp_get_default_logger()
    1727        9903 :       output_unit = cp_logger_get_default_io_unit(logger)
    1728             : 
    1729        9903 :       CPASSERT(ASSOCIATED(qs_env))
    1730             :       CALL get_qs_env(qs_env, &
    1731             :                       dft_control=dft_control, &
    1732             :                       molecule_set=molecule_set, &
    1733             :                       atomic_kind_set=atomic_kind_set, &
    1734             :                       particle_set=particle_set, &
    1735             :                       qs_kind_set=qs_kind_set, &
    1736             :                       admm_env=admm_env, &
    1737             :                       scf_control=scf_control, &
    1738             :                       input=input, &
    1739             :                       cell=cell, &
    1740        9903 :                       subsys=subsys)
    1741        9903 :       CALL qs_subsys_get(subsys, particles=particles)
    1742        9903 :       CALL get_qs_env(qs_env, rho=rho)
    1743        9903 :       CALL qs_rho_get(rho, rho_r=rho_r)
    1744             : 
    1745             :       ! k points
    1746        9903 :       CALL get_qs_env(qs_env, do_kpoints=do_kpoints)
    1747             : 
    1748             :       ! Write last MO information to output file if requested
    1749        9903 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    1750        9903 :       IF (.NOT. qs_env%run_rtp) THEN
    1751        9591 :          CALL qs_scf_write_mos(qs_env, scf_env, final_mos=.TRUE.)
    1752        9591 :          IF (.NOT. do_kpoints) THEN
    1753        9389 :             CALL get_qs_env(qs_env, mos=mos, matrix_ks=ks_rmpv)
    1754        9389 :             CALL write_dm_binary_restart(mos, dft_section, ks_rmpv)
    1755        9389 :             sprint_section => section_vals_get_subs_vals(dft_section, "PRINT%MO_MOLDEN")
    1756        9389 :             CALL write_mos_molden(mos, qs_kind_set, particle_set, sprint_section)
    1757             :             ! Write Chargemol .wfx
    1758        9389 :             IF (BTEST(cp_print_key_should_output(logger%iter_info, &
    1759             :                                                  dft_section, "PRINT%CHARGEMOL"), &
    1760             :                       cp_p_file)) THEN
    1761           2 :                CALL write_wfx(qs_env, dft_section)
    1762             :             END IF
    1763             :          END IF
    1764             : 
    1765             :          ! DOS printout after the SCF cycle is completed
    1766        9591 :          IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%DOS") &
    1767             :                    , cp_p_file)) THEN
    1768          42 :             IF (do_kpoints) THEN
    1769           2 :                CALL get_qs_env(qs_env=qs_env, kpoints=kpoints)
    1770           2 :                CALL calculate_dos_kp(kpoints, qs_env, dft_section)
    1771             :             ELSE
    1772          40 :                CALL get_qs_env(qs_env, mos=mos)
    1773          40 :                CALL calculate_dos(mos, dft_section)
    1774             :             END IF
    1775             :          END IF
    1776             : 
    1777             :          ! Print the projected density of states (pDOS) for each atomic kind
    1778        9591 :          IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%PDOS"), &
    1779             :                    cp_p_file)) THEN
    1780          46 :             IF (do_kpoints) THEN
    1781           0 :                CPWARN("Projected density of states (pDOS) is not implemented for k points")
    1782             :             ELSE
    1783             :                CALL get_qs_env(qs_env, &
    1784             :                                mos=mos, &
    1785          46 :                                matrix_ks=ks_rmpv)
    1786          92 :                DO ispin = 1, dft_control%nspins
    1787             :                   ! With ADMM, we have to modify the Kohn-Sham matrix
    1788          46 :                   IF (dft_control%do_admm) THEN
    1789           0 :                      CALL admm_correct_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
    1790             :                   END IF
    1791          46 :                   IF (PRESENT(scf_env)) THEN
    1792          46 :                      IF (scf_env%method == ot_method_nr) THEN
    1793             :                         CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
    1794           8 :                                         eigenvalues=mo_eigenvalues)
    1795           8 :                         IF (ASSOCIATED(qs_env%mo_derivs)) THEN
    1796           8 :                            mo_coeff_deriv => qs_env%mo_derivs(ispin)%matrix
    1797             :                         ELSE
    1798           0 :                            mo_coeff_deriv => NULL()
    1799             :                         END IF
    1800             :                         CALL calculate_subspace_eigenvalues(mo_coeff, ks_rmpv(ispin)%matrix, mo_eigenvalues, &
    1801             :                                                             do_rotation=.TRUE., &
    1802           8 :                                                             co_rotate_dbcsr=mo_coeff_deriv)
    1803           8 :                         CALL set_mo_occupation(mo_set=mos(ispin))
    1804             :                      END IF
    1805             :                   END IF
    1806          46 :                   IF (dft_control%nspins == 2) THEN
    1807             :                      CALL calculate_projected_dos(mos(ispin), atomic_kind_set, &
    1808           0 :                                                   qs_kind_set, particle_set, qs_env, dft_section, ispin=ispin)
    1809             :                   ELSE
    1810             :                      CALL calculate_projected_dos(mos(ispin), atomic_kind_set, &
    1811          46 :                                                   qs_kind_set, particle_set, qs_env, dft_section)
    1812             :                   END IF
    1813             :                   ! With ADMM, we have to undo the modification of the Kohn-Sham matrix
    1814          92 :                   IF (dft_control%do_admm) THEN
    1815           0 :                      CALL admm_uncorrect_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
    1816             :                   END IF
    1817             :                END DO
    1818             :             END IF
    1819             :          END IF
    1820             :       END IF
    1821             : 
    1822             :       ! Integrated absolute spin density and spin contamination ***
    1823        9903 :       IF (dft_control%nspins == 2) THEN
    1824        1942 :          CALL get_qs_env(qs_env, mos=mos)
    1825        1942 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    1826             :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    1827        1942 :                          pw_pools=pw_pools)
    1828        1942 :          CALL auxbas_pw_pool%create_pw(wf_r)
    1829        1942 :          CALL pw_copy(rho_r(1), wf_r)
    1830        1942 :          CALL pw_axpy(rho_r(2), wf_r, alpha=-1._dp)
    1831        1942 :          total_abs_spin_dens = pw_integrate_function(wf_r, oprt="ABS")
    1832        1942 :          IF (output_unit > 0) WRITE (UNIT=output_unit, FMT='(/,(T3,A,T61,F20.10))') &
    1833         994 :             "Integrated absolute spin density  : ", total_abs_spin_dens
    1834        1942 :          CALL auxbas_pw_pool%give_back_pw(wf_r)
    1835             :          !
    1836             :          ! XXX Fix Me XXX
    1837             :          ! should be extended to the case where added MOs are present
    1838             :          ! should be extended to the k-point case
    1839             :          !
    1840        1942 :          IF (do_kpoints) THEN
    1841          26 :             CPWARN("Spin contamination estimate not implemented for k-points.")
    1842             :          ELSE
    1843        1916 :             all_equal = .TRUE.
    1844        5748 :             DO ispin = 1, dft_control%nspins
    1845             :                CALL get_mo_set(mo_set=mos(ispin), &
    1846             :                                occupation_numbers=occupation_numbers, &
    1847             :                                homo=homo, &
    1848             :                                nmo=nmo, &
    1849        3832 :                                maxocc=maxocc)
    1850        5748 :                IF (nmo > 0) THEN
    1851             :                   all_equal = all_equal .AND. &
    1852             :                               (ALL(occupation_numbers(1:homo) == maxocc) .AND. &
    1853       22036 :                                ALL(occupation_numbers(homo + 1:nmo) == 0.0_dp))
    1854             :                END IF
    1855             :             END DO
    1856        1916 :             IF (.NOT. all_equal) THEN
    1857         106 :                IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(T3,A)") &
    1858          53 :                   "WARNING: S**2 computation does not yet treat fractional occupied orbitals"
    1859             :             ELSE
    1860             :                CALL get_qs_env(qs_env=qs_env, &
    1861             :                                matrix_s=matrix_s, &
    1862        1810 :                                energy=energy)
    1863             :                CALL compute_s_square(mos=mos, matrix_s=matrix_s, s_square=s_square, &
    1864        1810 :                                      s_square_ideal=s_square_ideal)
    1865        1810 :                IF (output_unit > 0) WRITE (UNIT=output_unit, FMT='(T3,A,T51,2F15.6)') &
    1866         928 :                   "Ideal and single determinant S**2 : ", s_square_ideal, s_square
    1867        1810 :                energy%s_square = s_square
    1868             :             END IF
    1869             :          END IF
    1870             :       END IF
    1871             : 
    1872        9903 :       CALL timestop(handle)
    1873             : 
    1874        9903 :    END SUBROUTINE write_mo_dependent_results
    1875             : 
    1876             : ! **************************************************************************************************
    1877             : !> \brief Write QS results always available (if switched on through the print_keys)
    1878             : !>        Can be called from ls_scf
    1879             : !> \param qs_env the qs_env in which the qs_env lives
    1880             : ! **************************************************************************************************
    1881       10821 :    SUBROUTINE write_mo_free_results(qs_env)
    1882             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1883             : 
    1884             :       CHARACTER(len=*), PARAMETER :: routineN = 'write_mo_free_results'
    1885             :       CHARACTER(len=1), DIMENSION(3), PARAMETER          :: cdir = (/"x", "y", "z"/)
    1886             : 
    1887             :       CHARACTER(LEN=2)                                   :: element_symbol
    1888             :       CHARACTER(LEN=default_path_length)                 :: filename, mpi_filename, my_pos_cube, &
    1889             :                                                             my_pos_voro
    1890             :       CHARACTER(LEN=default_string_length)               :: name, print_density
    1891             :       INTEGER :: after, handle, i, iat, id, ikind, img, iso, ispin, iw, l, n_rep_hf, natom, nd(3), &
    1892             :          ngto, niso, nkind, np, nr, output_unit, print_level, should_print_bqb, should_print_voro, &
    1893             :          unit_nr, unit_nr_voro
    1894             :       LOGICAL :: append_cube, append_voro, do_hfx, do_kpoints, mpi_io, omit_headers, print_it, &
    1895             :          rho_r_valid, voro_print_txt, write_ks, write_xc, xrd_interface
    1896             :       REAL(KIND=dp)                                      :: norm_factor, q_max, rho_hard, rho_soft, &
    1897             :                                                             rho_total, rho_total_rspace, udvol, &
    1898             :                                                             volume
    1899       10821 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: bfun
    1900       10821 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: aedens, ccdens, ppdens
    1901             :       REAL(KIND=dp), DIMENSION(3)                        :: dr
    1902       10821 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: my_Q0
    1903       10821 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1904             :       TYPE(atomic_kind_type), POINTER                    :: atomic_kind
    1905             :       TYPE(cell_type), POINTER                           :: cell
    1906             :       TYPE(cp_logger_type), POINTER                      :: logger
    1907       10821 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_hr
    1908       10821 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: ks_rmpv, matrix_vxc, rho_ao
    1909             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1910             :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    1911             :       TYPE(iao_env_type)                                 :: iao_env
    1912             :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1913             :       TYPE(particle_list_type), POINTER                  :: particles
    1914       10821 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1915             :       TYPE(pw_c1d_gs_type)                               :: aux_g, rho_elec_gspace
    1916             :       TYPE(pw_c1d_gs_type), POINTER                      :: rho0_s_gs, rho_core
    1917             :       TYPE(pw_env_type), POINTER                         :: pw_env
    1918       10821 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
    1919             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    1920             :       TYPE(pw_r3d_rs_type)                               :: aux_r, rho_elec_rspace, wf_r
    1921       10821 :       TYPE(pw_r3d_rs_type), DIMENSION(:), POINTER        :: rho_r
    1922             :       TYPE(pw_r3d_rs_type), POINTER                      :: mb_rho, v_hartree_rspace, vee
    1923       10821 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1924             :       TYPE(qs_kind_type), POINTER                        :: qs_kind
    1925             :       TYPE(qs_rho_type), POINTER                         :: rho
    1926             :       TYPE(qs_subsys_type), POINTER                      :: subsys
    1927             :       TYPE(rho0_mpole_type), POINTER                     :: rho0_mpole
    1928       10821 :       TYPE(rho_atom_type), DIMENSION(:), POINTER         :: rho_atom_set
    1929             :       TYPE(rho_atom_type), POINTER                       :: rho_atom
    1930             :       TYPE(section_vals_type), POINTER                   :: dft_section, hfx_section, input, &
    1931             :                                                             print_key, print_key_bqb, &
    1932             :                                                             print_key_voro, xc_section
    1933             : 
    1934       10821 :       CALL timeset(routineN, handle)
    1935       10821 :       NULLIFY (cell, dft_control, pw_env, auxbas_pw_pool, pw_pools, hfx_section, &
    1936       10821 :                atomic_kind_set, qs_kind_set, particle_set, rho, ks_rmpv, rho_ao, rho_r, &
    1937       10821 :                dft_section, xc_section, input, particles, subsys, matrix_vxc, v_hartree_rspace, &
    1938       10821 :                vee)
    1939             : 
    1940       10821 :       logger => cp_get_default_logger()
    1941       10821 :       output_unit = cp_logger_get_default_io_unit(logger)
    1942             : 
    1943       10821 :       CPASSERT(ASSOCIATED(qs_env))
    1944             :       CALL get_qs_env(qs_env, &
    1945             :                       atomic_kind_set=atomic_kind_set, &
    1946             :                       qs_kind_set=qs_kind_set, &
    1947             :                       particle_set=particle_set, &
    1948             :                       cell=cell, &
    1949             :                       para_env=para_env, &
    1950             :                       dft_control=dft_control, &
    1951             :                       input=input, &
    1952             :                       do_kpoints=do_kpoints, &
    1953       10821 :                       subsys=subsys)
    1954       10821 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    1955       10821 :       CALL qs_subsys_get(subsys, particles=particles)
    1956             : 
    1957       10821 :       CALL get_qs_env(qs_env, rho=rho)
    1958       10821 :       CALL qs_rho_get(rho, rho_r=rho_r)
    1959             : 
    1960             :       ! Print the total density (electronic + core charge)
    1961       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    1962             :                                            "DFT%PRINT%TOT_DENSITY_CUBE"), cp_p_file)) THEN
    1963          82 :          NULLIFY (rho_core, rho0_s_gs)
    1964          82 :          append_cube = section_get_lval(input, "DFT%PRINT%TOT_DENSITY_CUBE%APPEND")
    1965          82 :          my_pos_cube = "REWIND"
    1966          82 :          IF (append_cube) THEN
    1967           0 :             my_pos_cube = "APPEND"
    1968             :          END IF
    1969             : 
    1970             :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, rho_core=rho_core, &
    1971          82 :                          rho0_s_gs=rho0_s_gs)
    1972             :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    1973          82 :                          pw_pools=pw_pools)
    1974          82 :          CALL auxbas_pw_pool%create_pw(wf_r)
    1975          82 :          IF (dft_control%qs_control%gapw) THEN
    1976           0 :             IF (dft_control%qs_control%gapw_control%nopaw_as_gpw) THEN
    1977           0 :                CALL pw_axpy(rho_core, rho0_s_gs)
    1978           0 :                CALL pw_transfer(rho0_s_gs, wf_r)
    1979           0 :                CALL pw_axpy(rho_core, rho0_s_gs, -1.0_dp)
    1980             :             ELSE
    1981           0 :                CALL pw_transfer(rho0_s_gs, wf_r)
    1982             :             END IF
    1983             :          ELSE
    1984          82 :             CALL pw_transfer(rho_core, wf_r)
    1985             :          END IF
    1986         164 :          DO ispin = 1, dft_control%nspins
    1987         164 :             CALL pw_axpy(rho_r(ispin), wf_r)
    1988             :          END DO
    1989          82 :          filename = "TOTAL_DENSITY"
    1990          82 :          mpi_io = .TRUE.
    1991             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%TOT_DENSITY_CUBE", &
    1992             :                                         extension=".cube", middle_name=TRIM(filename), file_position=my_pos_cube, &
    1993          82 :                                         log_filename=.FALSE., mpi_io=mpi_io)
    1994             :          CALL cp_pw_to_cube(wf_r, unit_nr, "TOTAL DENSITY", &
    1995             :                             particles=particles, &
    1996          82 :                             stride=section_get_ivals(dft_section, "PRINT%TOT_DENSITY_CUBE%STRIDE"), mpi_io=mpi_io)
    1997             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    1998          82 :                                            "DFT%PRINT%TOT_DENSITY_CUBE", mpi_io=mpi_io)
    1999          82 :          CALL auxbas_pw_pool%give_back_pw(wf_r)
    2000             :       END IF
    2001             : 
    2002             :       ! Write cube file with electron density
    2003       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2004             :                                            "DFT%PRINT%E_DENSITY_CUBE"), cp_p_file)) THEN
    2005             :          CALL section_vals_val_get(dft_section, &
    2006             :                                    keyword_name="PRINT%E_DENSITY_CUBE%DENSITY_INCLUDE", &
    2007         150 :                                    c_val=print_density)
    2008             :          print_density = TRIM(print_density)
    2009         150 :          append_cube = section_get_lval(input, "DFT%PRINT%E_DENSITY_CUBE%APPEND")
    2010         150 :          my_pos_cube = "REWIND"
    2011         150 :          IF (append_cube) THEN
    2012           0 :             my_pos_cube = "APPEND"
    2013             :          END IF
    2014             :          ! Write the info on core densities for the interface between cp2k and the XRD code
    2015             :          ! together with the valence density they are used to compute the form factor (Fourier transform)
    2016         150 :          xrd_interface = section_get_lval(input, "DFT%PRINT%E_DENSITY_CUBE%XRD_INTERFACE")
    2017         150 :          IF (xrd_interface) THEN
    2018             :             !cube file only contains soft density (GAPW)
    2019           2 :             IF (dft_control%qs_control%gapw) print_density = "SOFT_DENSITY"
    2020             : 
    2021           2 :             filename = "ELECTRON_DENSITY"
    2022             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2023             :                                            extension=".xrd", middle_name=TRIM(filename), &
    2024           2 :                                            file_position=my_pos_cube, log_filename=.FALSE.)
    2025           2 :             ngto = section_get_ival(input, "DFT%PRINT%E_DENSITY_CUBE%NGAUSS")
    2026           2 :             IF (output_unit > 0) THEN
    2027           1 :                INQUIRE (UNIT=unit_nr, NAME=filename)
    2028             :                WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2029           1 :                   "The electron density (atomic part) is written to the file:", &
    2030           2 :                   TRIM(filename)
    2031             :             END IF
    2032             : 
    2033           2 :             xc_section => section_vals_get_subs_vals(input, "DFT%XC")
    2034           2 :             nkind = SIZE(atomic_kind_set)
    2035           2 :             IF (unit_nr > 0) THEN
    2036           1 :                WRITE (unit_nr, *) "Atomic (core) densities"
    2037           1 :                WRITE (unit_nr, *) "Unit cell"
    2038           1 :                WRITE (unit_nr, FMT="(3F20.12)") cell%hmat(1, 1), cell%hmat(1, 2), cell%hmat(1, 3)
    2039           1 :                WRITE (unit_nr, FMT="(3F20.12)") cell%hmat(2, 1), cell%hmat(2, 2), cell%hmat(2, 3)
    2040           1 :                WRITE (unit_nr, FMT="(3F20.12)") cell%hmat(3, 1), cell%hmat(3, 2), cell%hmat(3, 3)
    2041           1 :                WRITE (unit_nr, *) "Atomic types"
    2042           1 :                WRITE (unit_nr, *) nkind
    2043             :             END IF
    2044             :             ! calculate atomic density and core density
    2045          16 :             ALLOCATE (ppdens(ngto, 2, nkind), aedens(ngto, 2, nkind), ccdens(ngto, 2, nkind))
    2046           6 :             DO ikind = 1, nkind
    2047           4 :                atomic_kind => atomic_kind_set(ikind)
    2048           4 :                qs_kind => qs_kind_set(ikind)
    2049           4 :                CALL get_atomic_kind(atomic_kind, name=name, element_symbol=element_symbol)
    2050             :                CALL calculate_atomic_density(ppdens(:, :, ikind), atomic_kind, qs_kind, ngto, &
    2051           4 :                                              iunit=output_unit, confine=.TRUE.)
    2052             :                CALL calculate_atomic_density(aedens(:, :, ikind), atomic_kind, qs_kind, ngto, &
    2053           4 :                                              iunit=output_unit, allelectron=.TRUE., confine=.TRUE.)
    2054          52 :                ccdens(:, 1, ikind) = aedens(:, 1, ikind)
    2055          52 :                ccdens(:, 2, ikind) = 0._dp
    2056             :                CALL project_function_a(ccdens(1:ngto, 2, ikind), ccdens(1:ngto, 1, ikind), &
    2057           4 :                                        ppdens(1:ngto, 2, ikind), ppdens(1:ngto, 1, ikind), 0)
    2058          52 :                ccdens(:, 2, ikind) = aedens(:, 2, ikind) - ccdens(:, 2, ikind)
    2059           4 :                IF (unit_nr > 0) THEN
    2060           2 :                   WRITE (unit_nr, FMT="(I6,A10,A20)") ikind, TRIM(element_symbol), TRIM(name)
    2061           2 :                   WRITE (unit_nr, FMT="(I6)") ngto
    2062           2 :                   WRITE (unit_nr, *) "   Total density"
    2063          26 :                   WRITE (unit_nr, FMT="(2G24.12)") (aedens(i, 1, ikind), aedens(i, 2, ikind), i=1, ngto)
    2064           2 :                   WRITE (unit_nr, *) "    Core density"
    2065          26 :                   WRITE (unit_nr, FMT="(2G24.12)") (ccdens(i, 1, ikind), ccdens(i, 2, ikind), i=1, ngto)
    2066             :                END IF
    2067           6 :                NULLIFY (atomic_kind)
    2068             :             END DO
    2069             : 
    2070           2 :             IF (dft_control%qs_control%gapw) THEN
    2071           2 :                CALL get_qs_env(qs_env=qs_env, rho_atom_set=rho_atom_set)
    2072             : 
    2073           2 :                IF (unit_nr > 0) THEN
    2074           1 :                   WRITE (unit_nr, *) "Coordinates and GAPW density"
    2075             :                END IF
    2076           2 :                np = particles%n_els
    2077           6 :                DO iat = 1, np
    2078           4 :                   CALL get_atomic_kind(particles%els(iat)%atomic_kind, kind_number=ikind)
    2079           4 :                   CALL get_qs_kind(qs_kind_set(ikind), grid_atom=grid_atom)
    2080           4 :                   rho_atom => rho_atom_set(iat)
    2081           4 :                   IF (ASSOCIATED(rho_atom%rho_rad_h(1)%r_coef)) THEN
    2082           2 :                      nr = SIZE(rho_atom%rho_rad_h(1)%r_coef, 1)
    2083           2 :                      niso = SIZE(rho_atom%rho_rad_h(1)%r_coef, 2)
    2084             :                   ELSE
    2085           2 :                      nr = 0
    2086           2 :                      niso = 0
    2087             :                   END IF
    2088           4 :                   CALL para_env%sum(nr)
    2089           4 :                   CALL para_env%sum(niso)
    2090             : 
    2091          16 :                   ALLOCATE (bfun(nr, niso))
    2092        1840 :                   bfun = 0._dp
    2093           8 :                   DO ispin = 1, dft_control%nspins
    2094           8 :                      IF (ASSOCIATED(rho_atom%rho_rad_h(1)%r_coef)) THEN
    2095         920 :                         bfun(:, :) = bfun + rho_atom%rho_rad_h(ispin)%r_coef - rho_atom%rho_rad_s(ispin)%r_coef
    2096             :                      END IF
    2097             :                   END DO
    2098           4 :                   CALL para_env%sum(bfun)
    2099          52 :                   ccdens(:, 1, ikind) = ppdens(:, 1, ikind)
    2100          52 :                   ccdens(:, 2, ikind) = 0._dp
    2101           4 :                   IF (unit_nr > 0) THEN
    2102           8 :                      WRITE (unit_nr, '(I10,I5,3f12.6)') iat, ikind, particles%els(iat)%r
    2103             :                   END IF
    2104          40 :                   DO iso = 1, niso
    2105          36 :                      l = indso(1, iso)
    2106          36 :                      CALL project_function_b(ccdens(:, 2, ikind), ccdens(:, 1, ikind), bfun(:, iso), grid_atom, l)
    2107          40 :                      IF (unit_nr > 0) THEN
    2108          18 :                         WRITE (unit_nr, FMT="(3I6)") iso, l, ngto
    2109         234 :                         WRITE (unit_nr, FMT="(2G24.12)") (ccdens(i, 1, ikind), ccdens(i, 2, ikind), i=1, ngto)
    2110             :                      END IF
    2111             :                   END DO
    2112          10 :                   DEALLOCATE (bfun)
    2113             :                END DO
    2114             :             ELSE
    2115           0 :                IF (unit_nr > 0) THEN
    2116           0 :                   WRITE (unit_nr, *) "Coordinates"
    2117           0 :                   np = particles%n_els
    2118           0 :                   DO iat = 1, np
    2119           0 :                      CALL get_atomic_kind(particles%els(iat)%atomic_kind, kind_number=ikind)
    2120           0 :                      WRITE (unit_nr, '(I10,I5,3f12.6)') iat, ikind, particles%els(iat)%r
    2121             :                   END DO
    2122             :                END IF
    2123             :             END IF
    2124             : 
    2125           2 :             DEALLOCATE (ppdens, aedens, ccdens)
    2126             : 
    2127             :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2128           2 :                                               "DFT%PRINT%E_DENSITY_CUBE")
    2129             : 
    2130             :          END IF
    2131         150 :          IF (dft_control%qs_control%gapw .AND. print_density == "TOTAL_DENSITY") THEN
    2132             :             ! total density in g-space not implemented for k-points
    2133           4 :             CPASSERT(.NOT. do_kpoints)
    2134             :             ! Print total electronic density
    2135             :             CALL get_qs_env(qs_env=qs_env, &
    2136           4 :                             pw_env=pw_env)
    2137             :             CALL pw_env_get(pw_env=pw_env, &
    2138             :                             auxbas_pw_pool=auxbas_pw_pool, &
    2139           4 :                             pw_pools=pw_pools)
    2140           4 :             CALL auxbas_pw_pool%create_pw(pw=rho_elec_rspace)
    2141           4 :             CALL pw_zero(rho_elec_rspace)
    2142           4 :             CALL auxbas_pw_pool%create_pw(pw=rho_elec_gspace)
    2143           4 :             CALL pw_zero(rho_elec_gspace)
    2144             :             CALL get_pw_grid_info(pw_grid=rho_elec_gspace%pw_grid, &
    2145             :                                   dr=dr, &
    2146           4 :                                   vol=volume)
    2147          16 :             q_max = SQRT(SUM((pi/dr(:))**2))
    2148             :             CALL calculate_rhotot_elec_gspace(qs_env=qs_env, &
    2149             :                                               auxbas_pw_pool=auxbas_pw_pool, &
    2150             :                                               rhotot_elec_gspace=rho_elec_gspace, &
    2151             :                                               q_max=q_max, &
    2152             :                                               rho_hard=rho_hard, &
    2153           4 :                                               rho_soft=rho_soft)
    2154           4 :             rho_total = rho_hard + rho_soft
    2155             :             CALL get_pw_grid_info(pw_grid=rho_elec_gspace%pw_grid, &
    2156           4 :                                   vol=volume)
    2157             :             ! rhotot pw coefficients are by default scaled by grid volume
    2158             :             ! need to undo this to get proper charge from printed cube
    2159           4 :             CALL pw_scale(rho_elec_gspace, 1.0_dp/volume)
    2160             : 
    2161           4 :             CALL pw_transfer(rho_elec_gspace, rho_elec_rspace)
    2162           4 :             rho_total_rspace = pw_integrate_function(rho_elec_rspace, isign=-1)
    2163           4 :             filename = "TOTAL_ELECTRON_DENSITY"
    2164           4 :             mpi_io = .TRUE.
    2165             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2166             :                                            extension=".cube", middle_name=TRIM(filename), &
    2167             :                                            file_position=my_pos_cube, log_filename=.FALSE., mpi_io=mpi_io, &
    2168           4 :                                            fout=mpi_filename)
    2169           4 :             IF (output_unit > 0) THEN
    2170           2 :                IF (.NOT. mpi_io) THEN
    2171           0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    2172             :                ELSE
    2173           2 :                   filename = mpi_filename
    2174             :                END IF
    2175             :                WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2176           2 :                   "The total electron density is written in cube file format to the file:", &
    2177           4 :                   TRIM(filename)
    2178             :                WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    2179           2 :                   "q(max) [1/Angstrom]              :", q_max/angstrom, &
    2180           2 :                   "Soft electronic charge (G-space) :", rho_soft, &
    2181           2 :                   "Hard electronic charge (G-space) :", rho_hard, &
    2182           2 :                   "Total electronic charge (G-space):", rho_total, &
    2183           4 :                   "Total electronic charge (R-space):", rho_total_rspace
    2184             :             END IF
    2185             :             CALL cp_pw_to_cube(rho_elec_rspace, unit_nr, "TOTAL ELECTRON DENSITY", &
    2186             :                                particles=particles, &
    2187           4 :                                stride=section_get_ivals(dft_section, "PRINT%E_DENSITY_CUBE%STRIDE"), mpi_io=mpi_io)
    2188             :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2189           4 :                                               "DFT%PRINT%E_DENSITY_CUBE", mpi_io=mpi_io)
    2190             :             ! Print total spin density for spin-polarized systems
    2191           4 :             IF (dft_control%nspins > 1) THEN
    2192           2 :                CALL pw_zero(rho_elec_gspace)
    2193           2 :                CALL pw_zero(rho_elec_rspace)
    2194             :                CALL calculate_rhotot_elec_gspace(qs_env=qs_env, &
    2195             :                                                  auxbas_pw_pool=auxbas_pw_pool, &
    2196             :                                                  rhotot_elec_gspace=rho_elec_gspace, &
    2197             :                                                  q_max=q_max, &
    2198             :                                                  rho_hard=rho_hard, &
    2199             :                                                  rho_soft=rho_soft, &
    2200           2 :                                                  fsign=-1.0_dp)
    2201           2 :                rho_total = rho_hard + rho_soft
    2202             : 
    2203             :                ! rhotot pw coefficients are by default scaled by grid volume
    2204             :                ! need to undo this to get proper charge from printed cube
    2205           2 :                CALL pw_scale(rho_elec_gspace, 1.0_dp/volume)
    2206             : 
    2207           2 :                CALL pw_transfer(rho_elec_gspace, rho_elec_rspace)
    2208           2 :                rho_total_rspace = pw_integrate_function(rho_elec_rspace, isign=-1)
    2209           2 :                filename = "TOTAL_SPIN_DENSITY"
    2210           2 :                mpi_io = .TRUE.
    2211             :                unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2212             :                                               extension=".cube", middle_name=TRIM(filename), &
    2213             :                                               file_position=my_pos_cube, log_filename=.FALSE., mpi_io=mpi_io, &
    2214           2 :                                               fout=mpi_filename)
    2215           2 :                IF (output_unit > 0) THEN
    2216           1 :                   IF (.NOT. mpi_io) THEN
    2217           0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    2218             :                   ELSE
    2219           1 :                      filename = mpi_filename
    2220             :                   END IF
    2221             :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2222           1 :                      "The total spin density is written in cube file format to the file:", &
    2223           2 :                      TRIM(filename)
    2224             :                   WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    2225           1 :                      "q(max) [1/Angstrom]                    :", q_max/angstrom, &
    2226           1 :                      "Soft part of the spin density (G-space):", rho_soft, &
    2227           1 :                      "Hard part of the spin density (G-space):", rho_hard, &
    2228           1 :                      "Total spin density (G-space)           :", rho_total, &
    2229           2 :                      "Total spin density (R-space)           :", rho_total_rspace
    2230             :                END IF
    2231             :                CALL cp_pw_to_cube(rho_elec_rspace, unit_nr, "TOTAL SPIN DENSITY", &
    2232             :                                   particles=particles, &
    2233           2 :                                   stride=section_get_ivals(dft_section, "PRINT%E_DENSITY_CUBE%STRIDE"), mpi_io=mpi_io)
    2234             :                CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2235           2 :                                                  "DFT%PRINT%E_DENSITY_CUBE", mpi_io=mpi_io)
    2236             :             END IF
    2237           4 :             CALL auxbas_pw_pool%give_back_pw(rho_elec_gspace)
    2238           4 :             CALL auxbas_pw_pool%give_back_pw(rho_elec_rspace)
    2239             : 
    2240         146 :          ELSE IF (print_density == "SOFT_DENSITY" .OR. .NOT. dft_control%qs_control%gapw) THEN
    2241         142 :             IF (dft_control%nspins > 1) THEN
    2242             :                CALL get_qs_env(qs_env=qs_env, &
    2243          48 :                                pw_env=pw_env)
    2244             :                CALL pw_env_get(pw_env=pw_env, &
    2245             :                                auxbas_pw_pool=auxbas_pw_pool, &
    2246          48 :                                pw_pools=pw_pools)
    2247          48 :                CALL auxbas_pw_pool%create_pw(pw=rho_elec_rspace)
    2248          48 :                CALL pw_copy(rho_r(1), rho_elec_rspace)
    2249          48 :                CALL pw_axpy(rho_r(2), rho_elec_rspace)
    2250          48 :                filename = "ELECTRON_DENSITY"
    2251          48 :                mpi_io = .TRUE.
    2252             :                unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2253             :                                               extension=".cube", middle_name=TRIM(filename), &
    2254             :                                               file_position=my_pos_cube, log_filename=.FALSE., mpi_io=mpi_io, &
    2255          48 :                                               fout=mpi_filename)
    2256          48 :                IF (output_unit > 0) THEN
    2257          24 :                   IF (.NOT. mpi_io) THEN
    2258           0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    2259             :                   ELSE
    2260          24 :                      filename = mpi_filename
    2261             :                   END IF
    2262             :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2263          24 :                      "The sum of alpha and beta density is written in cube file format to the file:", &
    2264          48 :                      TRIM(filename)
    2265             :                END IF
    2266             :                CALL cp_pw_to_cube(rho_elec_rspace, unit_nr, "SUM OF ALPHA AND BETA DENSITY", &
    2267             :                                   particles=particles, stride=section_get_ivals(dft_section, "PRINT%E_DENSITY_CUBE%STRIDE"), &
    2268          48 :                                   mpi_io=mpi_io)
    2269             :                CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2270          48 :                                                  "DFT%PRINT%E_DENSITY_CUBE", mpi_io=mpi_io)
    2271          48 :                CALL pw_copy(rho_r(1), rho_elec_rspace)
    2272          48 :                CALL pw_axpy(rho_r(2), rho_elec_rspace, alpha=-1.0_dp)
    2273          48 :                filename = "SPIN_DENSITY"
    2274          48 :                mpi_io = .TRUE.
    2275             :                unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2276             :                                               extension=".cube", middle_name=TRIM(filename), &
    2277             :                                               file_position=my_pos_cube, log_filename=.FALSE., mpi_io=mpi_io, &
    2278          48 :                                               fout=mpi_filename)
    2279          48 :                IF (output_unit > 0) THEN
    2280          24 :                   IF (.NOT. mpi_io) THEN
    2281           0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    2282             :                   ELSE
    2283          24 :                      filename = mpi_filename
    2284             :                   END IF
    2285             :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2286          24 :                      "The spin density is written in cube file format to the file:", &
    2287          48 :                      TRIM(filename)
    2288             :                END IF
    2289             :                CALL cp_pw_to_cube(rho_elec_rspace, unit_nr, "SPIN DENSITY", &
    2290             :                                   particles=particles, &
    2291          48 :                                   stride=section_get_ivals(dft_section, "PRINT%E_DENSITY_CUBE%STRIDE"), mpi_io=mpi_io)
    2292             :                CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2293          48 :                                                  "DFT%PRINT%E_DENSITY_CUBE", mpi_io=mpi_io)
    2294          48 :                CALL auxbas_pw_pool%give_back_pw(rho_elec_rspace)
    2295             :             ELSE
    2296          94 :                filename = "ELECTRON_DENSITY"
    2297          94 :                mpi_io = .TRUE.
    2298             :                unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2299             :                                               extension=".cube", middle_name=TRIM(filename), &
    2300             :                                               file_position=my_pos_cube, log_filename=.FALSE., mpi_io=mpi_io, &
    2301          94 :                                               fout=mpi_filename)
    2302          94 :                IF (output_unit > 0) THEN
    2303          47 :                   IF (.NOT. mpi_io) THEN
    2304           0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    2305             :                   ELSE
    2306          47 :                      filename = mpi_filename
    2307             :                   END IF
    2308             :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2309          47 :                      "The electron density is written in cube file format to the file:", &
    2310          94 :                      TRIM(filename)
    2311             :                END IF
    2312             :                CALL cp_pw_to_cube(rho_r(1), unit_nr, "ELECTRON DENSITY", &
    2313             :                                   particles=particles, &
    2314          94 :                                   stride=section_get_ivals(dft_section, "PRINT%E_DENSITY_CUBE%STRIDE"), mpi_io=mpi_io)
    2315             :                CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2316          94 :                                                  "DFT%PRINT%E_DENSITY_CUBE", mpi_io=mpi_io)
    2317             :             END IF ! nspins
    2318             : 
    2319           4 :          ELSE IF (dft_control%qs_control%gapw .AND. print_density == "TOTAL_HARD_APPROX") THEN
    2320           4 :             CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, rho0_mpole=rho0_mpole, natom=natom)
    2321           4 :             CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, pw_pools=pw_pools)
    2322           4 :             CALL auxbas_pw_pool%create_pw(rho_elec_rspace)
    2323             : 
    2324           4 :             NULLIFY (my_Q0)
    2325          12 :             ALLOCATE (my_Q0(natom))
    2326          16 :             my_Q0 = 0.0_dp
    2327             : 
    2328             :             ! (eta/pi)**3: normalization for 3d gaussian of form exp(-eta*r**2)
    2329           4 :             norm_factor = SQRT((rho0_mpole%zet0_h/pi)**3)
    2330             : 
    2331             :             ! store hard part of electronic density in array
    2332          16 :             DO iat = 1, natom
    2333          34 :                my_Q0(iat) = SUM(rho0_mpole%mp_rho(iat)%Q0(1:dft_control%nspins))*norm_factor
    2334             :             END DO
    2335             :             ! multiply coeff with gaussian and put on realspace grid
    2336             :             ! coeff is the gaussian prefactor, eta the gaussian exponent
    2337           4 :             CALL calculate_rho_resp_all(rho_elec_rspace, coeff=my_Q0, natom=natom, eta=rho0_mpole%zet0_h, qs_env=qs_env)
    2338           4 :             rho_hard = pw_integrate_function(rho_elec_rspace, isign=-1)
    2339             : 
    2340           4 :             rho_soft = 0.0_dp
    2341          10 :             DO ispin = 1, dft_control%nspins
    2342           6 :                CALL pw_axpy(rho_r(ispin), rho_elec_rspace)
    2343          10 :                rho_soft = rho_soft + pw_integrate_function(rho_r(ispin), isign=-1)
    2344             :             END DO
    2345             : 
    2346           4 :             rho_total_rspace = rho_soft + rho_hard
    2347             : 
    2348           4 :             filename = "ELECTRON_DENSITY"
    2349           4 :             mpi_io = .TRUE.
    2350             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2351             :                                            extension=".cube", middle_name=TRIM(filename), &
    2352             :                                            file_position=my_pos_cube, log_filename=.FALSE., mpi_io=mpi_io, &
    2353           4 :                                            fout=mpi_filename)
    2354           4 :             IF (output_unit > 0) THEN
    2355           2 :                IF (.NOT. mpi_io) THEN
    2356           0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    2357             :                ELSE
    2358           2 :                   filename = mpi_filename
    2359             :                END IF
    2360             :                WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2361           2 :                   "The electron density is written in cube file format to the file:", &
    2362           4 :                   TRIM(filename)
    2363             :                WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    2364           2 :                   "Soft electronic charge (R-space) :", rho_soft, &
    2365           2 :                   "Hard electronic charge (R-space) :", rho_hard, &
    2366           4 :                   "Total electronic charge (R-space):", rho_total_rspace
    2367             :             END IF
    2368             :             CALL cp_pw_to_cube(rho_elec_rspace, unit_nr, "ELECTRON DENSITY", &
    2369             :                                particles=particles, stride=section_get_ivals(dft_section, "PRINT%E_DENSITY_CUBE%STRIDE"), &
    2370           4 :                                mpi_io=mpi_io)
    2371             :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2372           4 :                                               "DFT%PRINT%E_DENSITY_CUBE", mpi_io=mpi_io)
    2373             : 
    2374             :             !------------
    2375           4 :             IF (dft_control%nspins > 1) THEN
    2376           8 :             DO iat = 1, natom
    2377           8 :                my_Q0(iat) = (rho0_mpole%mp_rho(iat)%Q0(1) - rho0_mpole%mp_rho(iat)%Q0(2))*norm_factor
    2378             :             END DO
    2379           2 :             CALL pw_zero(rho_elec_rspace)
    2380           2 :             CALL calculate_rho_resp_all(rho_elec_rspace, coeff=my_Q0, natom=natom, eta=rho0_mpole%zet0_h, qs_env=qs_env)
    2381           2 :             rho_hard = pw_integrate_function(rho_elec_rspace, isign=-1)
    2382             : 
    2383           2 :             CALL pw_axpy(rho_r(1), rho_elec_rspace)
    2384           2 :             CALL pw_axpy(rho_r(2), rho_elec_rspace, alpha=-1.0_dp)
    2385             :             rho_soft = pw_integrate_function(rho_r(1), isign=-1) &
    2386           2 :                        - pw_integrate_function(rho_r(2), isign=-1)
    2387             : 
    2388           2 :             rho_total_rspace = rho_soft + rho_hard
    2389             : 
    2390           2 :             filename = "SPIN_DENSITY"
    2391           2 :             mpi_io = .TRUE.
    2392             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%E_DENSITY_CUBE", &
    2393             :                                            extension=".cube", middle_name=TRIM(filename), &
    2394             :                                            file_position=my_pos_cube, log_filename=.FALSE., mpi_io=mpi_io, &
    2395           2 :                                            fout=mpi_filename)
    2396           2 :             IF (output_unit > 0) THEN
    2397           1 :                IF (.NOT. mpi_io) THEN
    2398           0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    2399             :                ELSE
    2400           1 :                   filename = mpi_filename
    2401             :                END IF
    2402             :                WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2403           1 :                   "The spin density is written in cube file format to the file:", &
    2404           2 :                   TRIM(filename)
    2405             :                WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    2406           1 :                   "Soft part of the spin density          :", rho_soft, &
    2407           1 :                   "Hard part of the spin density          :", rho_hard, &
    2408           2 :                   "Total spin density (R-space)           :", rho_total_rspace
    2409             :             END IF
    2410             :             CALL cp_pw_to_cube(rho_elec_rspace, unit_nr, "SPIN DENSITY", &
    2411             :                                particles=particles, &
    2412           2 :                                stride=section_get_ivals(dft_section, "PRINT%E_DENSITY_CUBE%STRIDE"), mpi_io=mpi_io)
    2413             :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2414           2 :                                               "DFT%PRINT%E_DENSITY_CUBE", mpi_io=mpi_io)
    2415             :             END IF ! nspins
    2416           4 :             CALL auxbas_pw_pool%give_back_pw(rho_elec_rspace)
    2417           4 :             DEALLOCATE (my_Q0)
    2418             :          END IF ! print_density
    2419             :       END IF ! print key
    2420             : 
    2421             :       IF (BTEST(cp_print_key_should_output(logger%iter_info, &
    2422       10821 :                                            dft_section, "PRINT%ENERGY_WINDOWS"), cp_p_file) .AND. .NOT. do_kpoints) THEN
    2423          90 :          CALL energy_windows(qs_env)
    2424             :       END IF
    2425             : 
    2426             :       ! Print the hartree potential
    2427       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2428             :                                            "DFT%PRINT%V_HARTREE_CUBE"), cp_p_file)) THEN
    2429             : 
    2430             :          CALL get_qs_env(qs_env=qs_env, &
    2431             :                          pw_env=pw_env, &
    2432         116 :                          v_hartree_rspace=v_hartree_rspace)
    2433         116 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    2434         116 :          CALL auxbas_pw_pool%create_pw(aux_r)
    2435             : 
    2436         116 :          append_cube = section_get_lval(input, "DFT%PRINT%V_HARTREE_CUBE%APPEND")
    2437         116 :          my_pos_cube = "REWIND"
    2438         116 :          IF (append_cube) THEN
    2439           0 :             my_pos_cube = "APPEND"
    2440             :          END IF
    2441         116 :          mpi_io = .TRUE.
    2442         116 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    2443         116 :          CALL pw_env_get(pw_env)
    2444             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%V_HARTREE_CUBE", &
    2445         116 :                                         extension=".cube", middle_name="v_hartree", file_position=my_pos_cube, mpi_io=mpi_io)
    2446         116 :          udvol = 1.0_dp/v_hartree_rspace%pw_grid%dvol
    2447             : 
    2448         116 :          CALL pw_copy(v_hartree_rspace, aux_r)
    2449         116 :          CALL pw_scale(aux_r, udvol)
    2450             : 
    2451             :          CALL cp_pw_to_cube(aux_r, unit_nr, "HARTREE POTENTIAL", particles=particles, &
    2452             :                             stride=section_get_ivals(dft_section, &
    2453         116 :                                                      "PRINT%V_HARTREE_CUBE%STRIDE"), mpi_io=mpi_io)
    2454             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2455         116 :                                            "DFT%PRINT%V_HARTREE_CUBE", mpi_io=mpi_io)
    2456             : 
    2457         116 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    2458             :       END IF
    2459             : 
    2460             :       ! Print the external potential
    2461       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2462             :                                            "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE"), cp_p_file)) THEN
    2463          86 :          IF (dft_control%apply_external_potential) THEN
    2464           4 :             CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, vee=vee)
    2465           4 :             CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    2466           4 :             CALL auxbas_pw_pool%create_pw(aux_r)
    2467             : 
    2468           4 :             append_cube = section_get_lval(input, "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE%APPEND")
    2469           4 :             my_pos_cube = "REWIND"
    2470           4 :             IF (append_cube) THEN
    2471           0 :                my_pos_cube = "APPEND"
    2472             :             END IF
    2473           4 :             mpi_io = .TRUE.
    2474           4 :             CALL pw_env_get(pw_env)
    2475             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE", &
    2476           4 :                                            extension=".cube", middle_name="ext_pot", file_position=my_pos_cube, mpi_io=mpi_io)
    2477             : 
    2478           4 :             CALL pw_copy(vee, aux_r)
    2479             : 
    2480             :             CALL cp_pw_to_cube(aux_r, unit_nr, "EXTERNAL POTENTIAL", particles=particles, &
    2481             :                                stride=section_get_ivals(dft_section, &
    2482           4 :                                                         "PRINT%EXTERNAL_POTENTIAL_CUBE%STRIDE"), mpi_io=mpi_io)
    2483             :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2484           4 :                                               "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE", mpi_io=mpi_io)
    2485             : 
    2486           4 :             CALL auxbas_pw_pool%give_back_pw(aux_r)
    2487             :          END IF
    2488             :       END IF
    2489             : 
    2490             :       ! Print the Electrical Field Components
    2491       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2492             :                                            "DFT%PRINT%EFIELD_CUBE"), cp_p_file)) THEN
    2493             : 
    2494          82 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    2495          82 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    2496          82 :          CALL auxbas_pw_pool%create_pw(aux_r)
    2497          82 :          CALL auxbas_pw_pool%create_pw(aux_g)
    2498             : 
    2499          82 :          append_cube = section_get_lval(input, "DFT%PRINT%EFIELD_CUBE%APPEND")
    2500          82 :          my_pos_cube = "REWIND"
    2501          82 :          IF (append_cube) THEN
    2502           0 :             my_pos_cube = "APPEND"
    2503             :          END IF
    2504             :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, &
    2505          82 :                          v_hartree_rspace=v_hartree_rspace)
    2506          82 :          CALL pw_env_get(pw_env)
    2507          82 :          udvol = 1.0_dp/v_hartree_rspace%pw_grid%dvol
    2508         328 :          DO id = 1, 3
    2509         246 :             mpi_io = .TRUE.
    2510             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%EFIELD_CUBE", &
    2511             :                                            extension=".cube", middle_name="efield_"//cdir(id), file_position=my_pos_cube, &
    2512         246 :                                            mpi_io=mpi_io)
    2513             : 
    2514         246 :             CALL pw_transfer(v_hartree_rspace, aux_g)
    2515         246 :             nd = 0
    2516         246 :             nd(id) = 1
    2517         246 :             CALL pw_derive(aux_g, nd)
    2518         246 :             CALL pw_transfer(aux_g, aux_r)
    2519         246 :             CALL pw_scale(aux_r, udvol)
    2520             : 
    2521             :             CALL cp_pw_to_cube(aux_r, &
    2522             :                                unit_nr, "ELECTRIC FIELD", particles=particles, &
    2523             :                                stride=section_get_ivals(dft_section, &
    2524         246 :                                                         "PRINT%EFIELD_CUBE%STRIDE"), mpi_io=mpi_io)
    2525             :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2526         328 :                                               "DFT%PRINT%EFIELD_CUBE", mpi_io=mpi_io)
    2527             :          END DO
    2528             : 
    2529          82 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    2530          82 :          CALL auxbas_pw_pool%give_back_pw(aux_g)
    2531             :       END IF
    2532             : 
    2533             :       ! Write cube files from the local energy
    2534       10821 :       CALL qs_scf_post_local_energy(input, logger, qs_env)
    2535             : 
    2536             :       ! Write cube files from the local stress tensor
    2537       10821 :       CALL qs_scf_post_local_stress(input, logger, qs_env)
    2538             : 
    2539             :       ! Write cube files from the implicit Poisson solver
    2540       10821 :       CALL qs_scf_post_ps_implicit(input, logger, qs_env)
    2541             : 
    2542             :       ! post SCF Transport
    2543       10821 :       CALL qs_scf_post_transport(qs_env)
    2544             : 
    2545       10821 :       CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%OMIT_HEADERS", l_val=omit_headers)
    2546             :       ! Write the density matrices
    2547       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2548             :                                            "DFT%PRINT%AO_MATRICES/DENSITY"), cp_p_file)) THEN
    2549             :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/DENSITY", &
    2550           4 :                                    extension=".Log")
    2551           4 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    2552           4 :          CALL qs_rho_get(rho, rho_ao_kp=rho_ao)
    2553           4 :          after = MIN(MAX(after, 1), 16)
    2554           8 :          DO ispin = 1, dft_control%nspins
    2555          12 :             DO img = 1, dft_control%nimages
    2556             :                CALL cp_dbcsr_write_sparse_matrix(rho_ao(ispin, img)%matrix, 4, after, qs_env, &
    2557           8 :                                                  para_env, output_unit=iw, omit_headers=omit_headers)
    2558             :             END DO
    2559             :          END DO
    2560             :          CALL cp_print_key_finished_output(iw, logger, input, &
    2561           4 :                                            "DFT%PRINT%AO_MATRICES/DENSITY")
    2562             :       END IF
    2563             : 
    2564             :       ! Write the Kohn-Sham matrices
    2565             :       write_ks = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2566       10821 :                                                   "DFT%PRINT%AO_MATRICES/KOHN_SHAM_MATRIX"), cp_p_file)
    2567             :       write_xc = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2568       10821 :                                                   "DFT%PRINT%AO_MATRICES/MATRIX_VXC"), cp_p_file)
    2569             :       ! we need to update stuff before writing, potentially computing the matrix_vxc
    2570       10821 :       IF (write_ks .OR. write_xc) THEN
    2571           4 :          IF (write_xc) qs_env%requires_matrix_vxc = .TRUE.
    2572           4 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    2573             :          CALL qs_ks_update_qs_env(qs_env, calculate_forces=.FALSE., &
    2574           4 :                                   just_energy=.FALSE.)
    2575           4 :          IF (write_xc) qs_env%requires_matrix_vxc = .FALSE.
    2576             :       END IF
    2577             : 
    2578             :       ! Write the Kohn-Sham matrices
    2579       10821 :       IF (write_ks) THEN
    2580             :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/KOHN_SHAM_MATRIX", &
    2581           4 :                                    extension=".Log")
    2582           4 :          CALL get_qs_env(qs_env=qs_env, matrix_ks_kp=ks_rmpv)
    2583           4 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    2584           4 :          after = MIN(MAX(after, 1), 16)
    2585           8 :          DO ispin = 1, dft_control%nspins
    2586          12 :             DO img = 1, dft_control%nimages
    2587             :                CALL cp_dbcsr_write_sparse_matrix(ks_rmpv(ispin, img)%matrix, 4, after, qs_env, &
    2588           8 :                                                  para_env, output_unit=iw, omit_headers=omit_headers)
    2589             :             END DO
    2590             :          END DO
    2591             :          CALL cp_print_key_finished_output(iw, logger, input, &
    2592           4 :                                            "DFT%PRINT%AO_MATRICES/KOHN_SHAM_MATRIX")
    2593             :       END IF
    2594             : 
    2595             :       ! write csr matrices
    2596             :       ! matrices in terms of the PAO basis will be taken care of in pao_post_scf.
    2597       10821 :       IF (.NOT. dft_control%qs_control%pao) THEN
    2598       10325 :          CALL write_ks_matrix_csr(qs_env, input)
    2599       10325 :          CALL write_s_matrix_csr(qs_env, input)
    2600             :       END IF
    2601             : 
    2602             :       ! write adjacency matrix
    2603       10821 :       CALL write_adjacency_matrix(qs_env, input)
    2604             : 
    2605             :       ! Write the xc matrix
    2606       10821 :       IF (write_xc) THEN
    2607           0 :          CALL get_qs_env(qs_env=qs_env, matrix_vxc_kp=matrix_vxc)
    2608           0 :          CPASSERT(ASSOCIATED(matrix_vxc))
    2609             :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/MATRIX_VXC", &
    2610           0 :                                    extension=".Log")
    2611           0 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    2612           0 :          after = MIN(MAX(after, 1), 16)
    2613           0 :          DO ispin = 1, dft_control%nspins
    2614           0 :             DO img = 1, dft_control%nimages
    2615             :                CALL cp_dbcsr_write_sparse_matrix(matrix_vxc(ispin, img)%matrix, 4, after, qs_env, &
    2616           0 :                                                  para_env, output_unit=iw, omit_headers=omit_headers)
    2617             :             END DO
    2618             :          END DO
    2619             :          CALL cp_print_key_finished_output(iw, logger, input, &
    2620           0 :                                            "DFT%PRINT%AO_MATRICES/MATRIX_VXC")
    2621             :       END IF
    2622             : 
    2623             :       ! Write the [H,r] commutator matrices
    2624       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2625             :                                            "DFT%PRINT%AO_MATRICES/COMMUTATOR_HR"), cp_p_file)) THEN
    2626             :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/COMMUTATOR_HR", &
    2627           0 :                                    extension=".Log")
    2628           0 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    2629           0 :          NULLIFY (matrix_hr)
    2630           0 :          CALL build_com_hr_matrix(qs_env, matrix_hr)
    2631           0 :          after = MIN(MAX(after, 1), 16)
    2632           0 :          DO img = 1, 3
    2633             :             CALL cp_dbcsr_write_sparse_matrix(matrix_hr(img)%matrix, 4, after, qs_env, &
    2634           0 :                                               para_env, output_unit=iw, omit_headers=omit_headers)
    2635             :          END DO
    2636           0 :          CALL dbcsr_deallocate_matrix_set(matrix_hr)
    2637             :          CALL cp_print_key_finished_output(iw, logger, input, &
    2638           0 :                                            "DFT%PRINT%AO_MATRICES/COMMUTATOR_HR")
    2639             :       END IF
    2640             : 
    2641             :       ! Compute the Mulliken charges
    2642       10821 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%MULLIKEN")
    2643       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    2644        4522 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MULLIKEN", extension=".mulliken", log_filename=.FALSE.)
    2645        4522 :          print_level = 1
    2646        4522 :          CALL section_vals_val_get(print_key, "PRINT_GOP", l_val=print_it)
    2647        4522 :          IF (print_it) print_level = 2
    2648        4522 :          CALL section_vals_val_get(print_key, "PRINT_ALL", l_val=print_it)
    2649        4522 :          IF (print_it) print_level = 3
    2650        4522 :          CALL mulliken_population_analysis(qs_env, unit_nr, print_level)
    2651        4522 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MULLIKEN")
    2652             :       END IF
    2653             : 
    2654             :       ! Compute the Hirshfeld charges
    2655       10821 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%HIRSHFELD")
    2656       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    2657             :          ! we check if real space density is available
    2658        4594 :          NULLIFY (rho)
    2659        4594 :          CALL get_qs_env(qs_env=qs_env, rho=rho)
    2660        4594 :          CALL qs_rho_get(rho, rho_r_valid=rho_r_valid)
    2661        4594 :          IF (rho_r_valid) THEN
    2662        4520 :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%HIRSHFELD", extension=".hirshfeld", log_filename=.FALSE.)
    2663        4520 :             CALL hirshfeld_charges(qs_env, print_key, unit_nr)
    2664        4520 :             CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%HIRSHFELD")
    2665             :          END IF
    2666             :       END IF
    2667             : 
    2668             :       ! Do a Voronoi Integration or write a compressed BQB File
    2669       10821 :       print_key_voro => section_vals_get_subs_vals(input, "DFT%PRINT%VORONOI")
    2670       10821 :       print_key_bqb => section_vals_get_subs_vals(input, "DFT%PRINT%E_DENSITY_BQB")
    2671       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key_voro), cp_p_file)) THEN
    2672          24 :          should_print_voro = 1
    2673             :       ELSE
    2674       10797 :          should_print_voro = 0
    2675             :       END IF
    2676       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key_bqb), cp_p_file)) THEN
    2677           2 :          should_print_bqb = 1
    2678             :       ELSE
    2679       10819 :          should_print_bqb = 0
    2680             :       END IF
    2681       10821 :       IF ((should_print_voro /= 0) .OR. (should_print_bqb /= 0)) THEN
    2682             : 
    2683             :          ! we check if real space density is available
    2684          26 :          NULLIFY (rho)
    2685          26 :          CALL get_qs_env(qs_env=qs_env, rho=rho)
    2686          26 :          CALL qs_rho_get(rho, rho_r_valid=rho_r_valid)
    2687          26 :          IF (rho_r_valid) THEN
    2688             : 
    2689          26 :             IF (dft_control%nspins > 1) THEN
    2690             :                CALL get_qs_env(qs_env=qs_env, &
    2691           0 :                                pw_env=pw_env)
    2692             :                CALL pw_env_get(pw_env=pw_env, &
    2693             :                                auxbas_pw_pool=auxbas_pw_pool, &
    2694           0 :                                pw_pools=pw_pools)
    2695           0 :                NULLIFY (mb_rho)
    2696           0 :                ALLOCATE (mb_rho)
    2697           0 :                CALL auxbas_pw_pool%create_pw(pw=mb_rho)
    2698           0 :                CALL pw_copy(rho_r(1), mb_rho)
    2699           0 :                CALL pw_axpy(rho_r(2), mb_rho)
    2700             :                !CALL voronoi_analysis(qs_env, rho_elec_rspace, print_key, unit_nr)
    2701             :             ELSE
    2702          26 :                mb_rho => rho_r(1)
    2703             :                !CALL voronoi_analysis( qs_env, rho_r(1), print_key, unit_nr )
    2704             :             END IF ! nspins
    2705             : 
    2706          26 :             IF (should_print_voro /= 0) THEN
    2707          24 :                CALL section_vals_val_get(print_key_voro, "OUTPUT_TEXT", l_val=voro_print_txt)
    2708          24 :                IF (voro_print_txt) THEN
    2709          24 :                   append_voro = section_get_lval(input, "DFT%PRINT%VORONOI%APPEND")
    2710          24 :                   my_pos_voro = "REWIND"
    2711          24 :                   IF (append_voro) THEN
    2712           0 :                      my_pos_voro = "APPEND"
    2713             :                   END IF
    2714             :                   unit_nr_voro = cp_print_key_unit_nr(logger, input, "DFT%PRINT%VORONOI", extension=".voronoi", &
    2715          24 :                                                       file_position=my_pos_voro, log_filename=.FALSE.)
    2716             :                ELSE
    2717           0 :                   unit_nr_voro = 0
    2718             :                END IF
    2719             :             ELSE
    2720           2 :                unit_nr_voro = 0
    2721             :             END IF
    2722             : 
    2723             :             CALL entry_voronoi_or_bqb(should_print_voro, should_print_bqb, print_key_voro, print_key_bqb, &
    2724          26 :                                       unit_nr_voro, qs_env, mb_rho)
    2725             : 
    2726          26 :             IF (dft_control%nspins > 1) THEN
    2727           0 :                CALL auxbas_pw_pool%give_back_pw(mb_rho)
    2728           0 :                DEALLOCATE (mb_rho)
    2729             :             END IF
    2730             : 
    2731          26 :             IF (unit_nr_voro > 0) THEN
    2732          12 :                CALL cp_print_key_finished_output(unit_nr_voro, logger, input, "DFT%PRINT%VORONOI")
    2733             :             END IF
    2734             : 
    2735             :          END IF
    2736             :       END IF
    2737             : 
    2738             :       ! MAO analysis
    2739       10821 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%MAO_ANALYSIS")
    2740       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    2741          38 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MAO_ANALYSIS", extension=".mao", log_filename=.FALSE.)
    2742          38 :          CALL mao_analysis(qs_env, print_key, unit_nr)
    2743          38 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MAO_ANALYSIS")
    2744             :       END IF
    2745             : 
    2746             :       ! MINBAS analysis
    2747       10821 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%MINBAS_ANALYSIS")
    2748       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    2749          28 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MINBAS_ANALYSIS", extension=".mao", log_filename=.FALSE.)
    2750          28 :          CALL minbas_analysis(qs_env, print_key, unit_nr)
    2751          28 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MINBAS_ANALYSIS")
    2752             :       END IF
    2753             : 
    2754             :       ! IAO analysis
    2755       10821 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%IAO_ANALYSIS")
    2756       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    2757          32 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IAO_ANALYSIS", extension=".iao", log_filename=.FALSE.)
    2758          32 :          CALL iao_read_input(iao_env, print_key, cell)
    2759          32 :          IF (iao_env%do_iao) THEN
    2760           4 :             CALL iao_wfn_analysis(qs_env, iao_env, unit_nr)
    2761             :          END IF
    2762          32 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%IAO_ANALYSIS")
    2763             :       END IF
    2764             : 
    2765             :       ! Energy Decomposition Analysis
    2766       10821 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%ENERGY_DECOMPOSITION_ANALYSIS")
    2767       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    2768             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%ENERGY_DECOMPOSITION_ANALYSIS", &
    2769          58 :                                         extension=".mao", log_filename=.FALSE.)
    2770          58 :          CALL edmf_analysis(qs_env, print_key, unit_nr)
    2771          58 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%ENERGY_DECOMPOSITION_ANALYSIS")
    2772             :       END IF
    2773             : 
    2774             :       ! Print the density in the RI-HFX basis
    2775       10821 :       hfx_section => section_vals_get_subs_vals(input, "DFT%XC%HF")
    2776       10821 :       CALL section_vals_get(hfx_section, explicit=do_hfx)
    2777       10821 :       CALL section_vals_get(hfx_section, n_repetition=n_rep_hf)
    2778       10821 :       IF (do_hfx) THEN
    2779        4382 :          DO i = 1, n_rep_hf
    2780        4382 :             IF (qs_env%x_data(i, 1)%do_hfx_ri) CALL print_ri_hfx(qs_env%x_data(i, 1)%ri_data, qs_env)
    2781             :          END DO
    2782             :       END IF
    2783             : 
    2784       10821 :       CALL timestop(handle)
    2785             : 
    2786       21642 :    END SUBROUTINE write_mo_free_results
    2787             : 
    2788             : ! **************************************************************************************************
    2789             : !> \brief Calculates Hirshfeld charges
    2790             : !> \param qs_env the qs_env where to calculate the charges
    2791             : !> \param input_section the input section for Hirshfeld charges
    2792             : !> \param unit_nr the output unit number
    2793             : ! **************************************************************************************************
    2794        4520 :    SUBROUTINE hirshfeld_charges(qs_env, input_section, unit_nr)
    2795             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2796             :       TYPE(section_vals_type), POINTER                   :: input_section
    2797             :       INTEGER, INTENT(IN)                                :: unit_nr
    2798             : 
    2799             :       INTEGER                                            :: i, iat, ikind, natom, nkind, nspin, &
    2800             :                                                             radius_type, refc, shapef
    2801        4520 :       INTEGER, DIMENSION(:), POINTER                     :: atom_list
    2802             :       LOGICAL                                            :: do_radius, do_sc, paw_atom
    2803             :       REAL(KIND=dp)                                      :: zeff
    2804        4520 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: radii
    2805        4520 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: charges
    2806        4520 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2807             :       TYPE(atomic_kind_type), POINTER                    :: atomic_kind
    2808        4520 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_p, matrix_s
    2809             :       TYPE(dft_control_type), POINTER                    :: dft_control
    2810             :       TYPE(hirshfeld_type), POINTER                      :: hirshfeld_env
    2811             :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2812        4520 :       TYPE(mpole_rho_atom), DIMENSION(:), POINTER        :: mp_rho
    2813        4520 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2814        4520 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2815             :       TYPE(qs_rho_type), POINTER                         :: rho
    2816             :       TYPE(rho0_mpole_type), POINTER                     :: rho0_mpole
    2817             : 
    2818        4520 :       NULLIFY (hirshfeld_env)
    2819        4520 :       NULLIFY (radii)
    2820        4520 :       CALL create_hirshfeld_type(hirshfeld_env)
    2821             :       !
    2822        4520 :       CALL get_qs_env(qs_env, nkind=nkind, natom=natom)
    2823       13560 :       ALLOCATE (hirshfeld_env%charges(natom))
    2824             :       ! input options
    2825        4520 :       CALL section_vals_val_get(input_section, "SELF_CONSISTENT", l_val=do_sc)
    2826        4520 :       CALL section_vals_val_get(input_section, "USER_RADIUS", l_val=do_radius)
    2827        4520 :       CALL section_vals_val_get(input_section, "SHAPE_FUNCTION", i_val=shapef)
    2828        4520 :       CALL section_vals_val_get(input_section, "REFERENCE_CHARGE", i_val=refc)
    2829        4520 :       IF (do_radius) THEN
    2830           0 :          radius_type = radius_user
    2831           0 :          CALL section_vals_val_get(input_section, "ATOMIC_RADII", r_vals=radii)
    2832           0 :          IF (.NOT. SIZE(radii) == nkind) &
    2833             :             CALL cp_abort(__LOCATION__, &
    2834             :                           "Length of keyword HIRSHFELD\ATOMIC_RADII does not "// &
    2835           0 :                           "match number of atomic kinds in the input coordinate file.")
    2836             :       ELSE
    2837        4520 :          radius_type = radius_covalent
    2838             :       END IF
    2839             :       CALL set_hirshfeld_info(hirshfeld_env, shape_function_type=shapef, &
    2840             :                               iterative=do_sc, ref_charge=refc, &
    2841        4520 :                               radius_type=radius_type)
    2842             :       ! shape function
    2843        4520 :       CALL get_qs_env(qs_env, qs_kind_set=qs_kind_set, atomic_kind_set=atomic_kind_set)
    2844             :       CALL create_shape_function(hirshfeld_env, qs_kind_set, atomic_kind_set, &
    2845        4520 :                                  radii_list=radii)
    2846             :       ! reference charges
    2847        4520 :       CALL get_qs_env(qs_env, rho=rho)
    2848        4520 :       CALL qs_rho_get(rho, rho_ao_kp=matrix_p)
    2849        4520 :       nspin = SIZE(matrix_p, 1)
    2850       18080 :       ALLOCATE (charges(natom, nspin))
    2851        4508 :       SELECT CASE (refc)
    2852             :       CASE (ref_charge_atomic)
    2853       12322 :          DO ikind = 1, nkind
    2854        7814 :             CALL get_qs_kind(qs_kind_set(ikind), zeff=zeff)
    2855        7814 :             atomic_kind => atomic_kind_set(ikind)
    2856        7814 :             CALL get_atomic_kind(atomic_kind, atom_list=atom_list)
    2857       39262 :             DO iat = 1, SIZE(atom_list)
    2858       19126 :                i = atom_list(iat)
    2859       26940 :                hirshfeld_env%charges(i) = zeff
    2860             :             END DO
    2861             :          END DO
    2862             :       CASE (ref_charge_mulliken)
    2863          12 :          CALL get_qs_env(qs_env, matrix_s_kp=matrix_s, para_env=para_env)
    2864          12 :          CALL mulliken_charges(matrix_p, matrix_s, para_env, charges)
    2865          48 :          DO iat = 1, natom
    2866         108 :             hirshfeld_env%charges(iat) = SUM(charges(iat, :))
    2867             :          END DO
    2868             :       CASE DEFAULT
    2869        4520 :          CPABORT("Unknown type of reference charge for Hirshfeld partitioning.")
    2870             :       END SELECT
    2871             :       !
    2872       31876 :       charges = 0.0_dp
    2873        4520 :       IF (hirshfeld_env%iterative) THEN
    2874             :          ! Hirshfeld-I charges
    2875          22 :          CALL comp_hirshfeld_i_charges(qs_env, hirshfeld_env, charges, unit_nr)
    2876             :       ELSE
    2877             :          ! Hirshfeld charges
    2878        4498 :          CALL comp_hirshfeld_charges(qs_env, hirshfeld_env, charges)
    2879             :       END IF
    2880        4520 :       CALL get_qs_env(qs_env, particle_set=particle_set, dft_control=dft_control)
    2881        4520 :       IF (dft_control%qs_control%gapw) THEN
    2882             :          ! GAPW: add core charges (rho_hard - rho_soft)
    2883         662 :          CALL get_qs_env(qs_env, rho0_mpole=rho0_mpole)
    2884         662 :          CALL get_rho0_mpole(rho0_mpole, mp_rho=mp_rho)
    2885        2994 :          DO iat = 1, natom
    2886        2332 :             atomic_kind => particle_set(iat)%atomic_kind
    2887        2332 :             CALL get_atomic_kind(atomic_kind, kind_number=ikind)
    2888        2332 :             CALL get_qs_kind(qs_kind_set(ikind), paw_atom=paw_atom)
    2889        2994 :             IF (paw_atom) THEN
    2890        4456 :                charges(iat, 1:nspin) = charges(iat, 1:nspin) + mp_rho(iat)%q0(1:nspin)
    2891             :             END IF
    2892             :          END DO
    2893             :       END IF
    2894             :       !
    2895        4520 :       IF (unit_nr > 0) THEN
    2896             :          CALL write_hirshfeld_charges(charges, hirshfeld_env, particle_set, &
    2897        2274 :                                       qs_kind_set, unit_nr)
    2898             :       END IF
    2899             :       ! Save the charges to the results under the tag [HIRSHFELD-CHARGES]
    2900        4520 :       CALL save_hirshfeld_charges(charges, particle_set, qs_kind_set, qs_env)
    2901             :       !
    2902        4520 :       CALL release_hirshfeld_type(hirshfeld_env)
    2903        4520 :       DEALLOCATE (charges)
    2904             : 
    2905        9040 :    END SUBROUTINE hirshfeld_charges
    2906             : 
    2907             : ! **************************************************************************************************
    2908             : !> \brief ...
    2909             : !> \param ca ...
    2910             : !> \param a ...
    2911             : !> \param cb ...
    2912             : !> \param b ...
    2913             : !> \param l ...
    2914             : ! **************************************************************************************************
    2915           4 :    SUBROUTINE project_function_a(ca, a, cb, b, l)
    2916             :       ! project function cb on ca
    2917             :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: ca
    2918             :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: a, cb, b
    2919             :       INTEGER, INTENT(IN)                                :: l
    2920             : 
    2921             :       INTEGER                                            :: info, n
    2922           4 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: ipiv
    2923           4 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: smat, tmat, v
    2924             : 
    2925           4 :       n = SIZE(ca)
    2926          40 :       ALLOCATE (smat(n, n), tmat(n, n), v(n, 1), ipiv(n))
    2927             : 
    2928           4 :       CALL sg_overlap(smat, l, a, a)
    2929           4 :       CALL sg_overlap(tmat, l, a, b)
    2930        1252 :       v(:, 1) = MATMUL(tmat, cb)
    2931           4 :       CALL lapack_sgesv(n, 1, smat, n, ipiv, v, n, info)
    2932           4 :       CPASSERT(info == 0)
    2933          52 :       ca(:) = v(:, 1)
    2934             : 
    2935           4 :       DEALLOCATE (smat, tmat, v, ipiv)
    2936             : 
    2937           4 :    END SUBROUTINE project_function_a
    2938             : 
    2939             : ! **************************************************************************************************
    2940             : !> \brief ...
    2941             : !> \param ca ...
    2942             : !> \param a ...
    2943             : !> \param bfun ...
    2944             : !> \param grid_atom ...
    2945             : !> \param l ...
    2946             : ! **************************************************************************************************
    2947          36 :    SUBROUTINE project_function_b(ca, a, bfun, grid_atom, l)
    2948             :       ! project function f on ca
    2949             :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: ca
    2950             :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: a, bfun
    2951             :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    2952             :       INTEGER, INTENT(IN)                                :: l
    2953             : 
    2954             :       INTEGER                                            :: i, info, n, nr
    2955          36 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: ipiv
    2956          36 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: afun
    2957          36 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: smat, v
    2958             : 
    2959          36 :       n = SIZE(ca)
    2960          36 :       nr = grid_atom%nr
    2961         360 :       ALLOCATE (smat(n, n), v(n, 1), ipiv(n), afun(nr))
    2962             : 
    2963          36 :       CALL sg_overlap(smat, l, a, a)
    2964         468 :       DO i = 1, n
    2965       22032 :          afun(:) = grid_atom%rad(:)**l*EXP(-a(i)*grid_atom%rad2(:))
    2966       22068 :          v(i, 1) = SUM(afun(:)*bfun(:)*grid_atom%wr(:))
    2967             :       END DO
    2968          36 :       CALL lapack_sgesv(n, 1, smat, n, ipiv, v, n, info)
    2969          36 :       CPASSERT(info == 0)
    2970         468 :       ca(:) = v(:, 1)
    2971             : 
    2972          36 :       DEALLOCATE (smat, v, ipiv, afun)
    2973             : 
    2974          36 :    END SUBROUTINE project_function_b
    2975             : 
    2976             : ! **************************************************************************************************
    2977             : !> \brief Performs printing of cube files from local energy
    2978             : !> \param input input
    2979             : !> \param logger the logger
    2980             : !> \param qs_env the qs_env in which the qs_env lives
    2981             : !> \par History
    2982             : !>      07.2019 created
    2983             : !> \author JGH
    2984             : ! **************************************************************************************************
    2985       10821 :    SUBROUTINE qs_scf_post_local_energy(input, logger, qs_env)
    2986             :       TYPE(section_vals_type), POINTER                   :: input
    2987             :       TYPE(cp_logger_type), POINTER                      :: logger
    2988             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2989             : 
    2990             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_local_energy'
    2991             : 
    2992             :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube
    2993             :       INTEGER                                            :: handle, io_unit, natom, unit_nr
    2994             :       LOGICAL                                            :: append_cube, gapw, gapw_xc, mpi_io
    2995             :       TYPE(dft_control_type), POINTER                    :: dft_control
    2996             :       TYPE(particle_list_type), POINTER                  :: particles
    2997             :       TYPE(pw_env_type), POINTER                         :: pw_env
    2998             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    2999             :       TYPE(pw_r3d_rs_type)                               :: eden
    3000             :       TYPE(qs_subsys_type), POINTER                      :: subsys
    3001             :       TYPE(section_vals_type), POINTER                   :: dft_section
    3002             : 
    3003       10821 :       CALL timeset(routineN, handle)
    3004       10821 :       io_unit = cp_logger_get_default_io_unit(logger)
    3005       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3006             :                                            "DFT%PRINT%LOCAL_ENERGY_CUBE"), cp_p_file)) THEN
    3007          32 :          dft_section => section_vals_get_subs_vals(input, "DFT")
    3008          32 :          CALL get_qs_env(qs_env=qs_env, dft_control=dft_control, natom=natom)
    3009          32 :          gapw = dft_control%qs_control%gapw
    3010          32 :          gapw_xc = dft_control%qs_control%gapw_xc
    3011          32 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, subsys=subsys)
    3012          32 :          CALL qs_subsys_get(subsys, particles=particles)
    3013          32 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3014          32 :          CALL auxbas_pw_pool%create_pw(eden)
    3015             :          !
    3016          32 :          CALL qs_local_energy(qs_env, eden)
    3017             :          !
    3018          32 :          append_cube = section_get_lval(input, "DFT%PRINT%LOCAL_ENERGY_CUBE%APPEND")
    3019          32 :          IF (append_cube) THEN
    3020           0 :             my_pos_cube = "APPEND"
    3021             :          ELSE
    3022          32 :             my_pos_cube = "REWIND"
    3023             :          END IF
    3024          32 :          mpi_io = .TRUE.
    3025             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%LOCAL_ENERGY_CUBE", &
    3026             :                                         extension=".cube", middle_name="local_energy", &
    3027          32 :                                         file_position=my_pos_cube, mpi_io=mpi_io)
    3028             :          CALL cp_pw_to_cube(eden, &
    3029             :                             unit_nr, "LOCAL ENERGY", particles=particles, &
    3030             :                             stride=section_get_ivals(dft_section, &
    3031          32 :                                                      "PRINT%LOCAL_ENERGY_CUBE%STRIDE"), mpi_io=mpi_io)
    3032          32 :          IF (io_unit > 0) THEN
    3033          16 :             INQUIRE (UNIT=unit_nr, NAME=filename)
    3034          16 :             IF (gapw .OR. gapw_xc) THEN
    3035             :                WRITE (UNIT=io_unit, FMT="(/,T3,A,A)") &
    3036           0 :                   "The soft part of the local energy is written to the file: ", TRIM(ADJUSTL(filename))
    3037             :             ELSE
    3038             :                WRITE (UNIT=io_unit, FMT="(/,T3,A,A)") &
    3039          16 :                   "The local energy is written to the file: ", TRIM(ADJUSTL(filename))
    3040             :             END IF
    3041             :          END IF
    3042             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3043          32 :                                            "DFT%PRINT%LOCAL_ENERGY_CUBE", mpi_io=mpi_io)
    3044             :          !
    3045          32 :          CALL auxbas_pw_pool%give_back_pw(eden)
    3046             :       END IF
    3047       10821 :       CALL timestop(handle)
    3048             : 
    3049       10821 :    END SUBROUTINE qs_scf_post_local_energy
    3050             : 
    3051             : ! **************************************************************************************************
    3052             : !> \brief Performs printing of cube files from local energy
    3053             : !> \param input input
    3054             : !> \param logger the logger
    3055             : !> \param qs_env the qs_env in which the qs_env lives
    3056             : !> \par History
    3057             : !>      07.2019 created
    3058             : !> \author JGH
    3059             : ! **************************************************************************************************
    3060       10821 :    SUBROUTINE qs_scf_post_local_stress(input, logger, qs_env)
    3061             :       TYPE(section_vals_type), POINTER                   :: input
    3062             :       TYPE(cp_logger_type), POINTER                      :: logger
    3063             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3064             : 
    3065             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_local_stress'
    3066             : 
    3067             :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube
    3068             :       INTEGER                                            :: handle, io_unit, natom, unit_nr
    3069             :       LOGICAL                                            :: append_cube, gapw, gapw_xc, mpi_io
    3070             :       REAL(KIND=dp)                                      :: beta
    3071             :       TYPE(dft_control_type), POINTER                    :: dft_control
    3072             :       TYPE(particle_list_type), POINTER                  :: particles
    3073             :       TYPE(pw_env_type), POINTER                         :: pw_env
    3074             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    3075             :       TYPE(pw_r3d_rs_type)                               :: stress
    3076             :       TYPE(qs_subsys_type), POINTER                      :: subsys
    3077             :       TYPE(section_vals_type), POINTER                   :: dft_section
    3078             : 
    3079       10821 :       CALL timeset(routineN, handle)
    3080       10821 :       io_unit = cp_logger_get_default_io_unit(logger)
    3081       10821 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3082             :                                            "DFT%PRINT%LOCAL_STRESS_CUBE"), cp_p_file)) THEN
    3083          30 :          dft_section => section_vals_get_subs_vals(input, "DFT")
    3084          30 :          CALL get_qs_env(qs_env=qs_env, dft_control=dft_control, natom=natom)
    3085          30 :          gapw = dft_control%qs_control%gapw
    3086          30 :          gapw_xc = dft_control%qs_control%gapw_xc
    3087          30 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, subsys=subsys)
    3088          30 :          CALL qs_subsys_get(subsys, particles=particles)
    3089          30 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3090          30 :          CALL auxbas_pw_pool%create_pw(stress)
    3091             :          !
    3092             :          ! use beta=0: kinetic energy density in symmetric form
    3093          30 :          beta = 0.0_dp
    3094          30 :          CALL qs_local_stress(qs_env, beta=beta)
    3095             :          !
    3096          30 :          append_cube = section_get_lval(input, "DFT%PRINT%LOCAL_STRESS_CUBE%APPEND")
    3097          30 :          IF (append_cube) THEN
    3098           0 :             my_pos_cube = "APPEND"
    3099             :          ELSE
    3100          30 :             my_pos_cube = "REWIND"
    3101             :          END IF
    3102          30 :          mpi_io = .TRUE.
    3103             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%LOCAL_STRESS_CUBE", &
    3104             :                                         extension=".cube", middle_name="local_stress", &
    3105          30 :                                         file_position=my_pos_cube, mpi_io=mpi_io)
    3106             :          CALL cp_pw_to_cube(stress, &
    3107             :                             unit_nr, "LOCAL STRESS", particles=particles, &
    3108             :                             stride=section_get_ivals(dft_section, &
    3109          30 :                                                      "PRINT%LOCAL_STRESS_CUBE%STRIDE"), mpi_io=mpi_io)
    3110          30 :          IF (io_unit > 0) THEN
    3111          15 :             INQUIRE (UNIT=unit_nr, NAME=filename)
    3112          15 :             WRITE (UNIT=io_unit, FMT="(/,T3,A)") "Write 1/3*Tr(sigma) to cube file"
    3113          15 :             IF (gapw .OR. gapw_xc) THEN
    3114             :                WRITE (UNIT=io_unit, FMT="(T3,A,A)") &
    3115           0 :                   "The soft part of the local stress is written to the file: ", TRIM(ADJUSTL(filename))
    3116             :             ELSE
    3117             :                WRITE (UNIT=io_unit, FMT="(T3,A,A)") &
    3118          15 :                   "The local stress is written to the file: ", TRIM(ADJUSTL(filename))
    3119             :             END IF
    3120             :          END IF
    3121             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3122          30 :                                            "DFT%PRINT%LOCAL_STRESS_CUBE", mpi_io=mpi_io)
    3123             :          !
    3124          30 :          CALL auxbas_pw_pool%give_back_pw(stress)
    3125             :       END IF
    3126             : 
    3127       10821 :       CALL timestop(handle)
    3128             : 
    3129       10821 :    END SUBROUTINE qs_scf_post_local_stress
    3130             : 
    3131             : ! **************************************************************************************************
    3132             : !> \brief Performs printing of cube files related to the implicit Poisson solver
    3133             : !> \param input input
    3134             : !> \param logger the logger
    3135             : !> \param qs_env the qs_env in which the qs_env lives
    3136             : !> \par History
    3137             : !>      03.2016 refactored from write_mo_free_results [Hossein Bani-Hashemian]
    3138             : !> \author Mohammad Hossein Bani-Hashemian
    3139             : ! **************************************************************************************************
    3140       10821 :    SUBROUTINE qs_scf_post_ps_implicit(input, logger, qs_env)
    3141             :       TYPE(section_vals_type), POINTER                   :: input
    3142             :       TYPE(cp_logger_type), POINTER                      :: logger
    3143             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3144             : 
    3145             :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_ps_implicit'
    3146             : 
    3147             :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube
    3148             :       INTEGER                                            :: boundary_condition, handle, i, j, &
    3149             :                                                             n_cstr, n_tiles, unit_nr
    3150             :       LOGICAL :: append_cube, do_cstr_charge_cube, do_dielectric_cube, do_dirichlet_bc_cube, &
    3151             :          has_dirichlet_bc, has_implicit_ps, mpi_io, tile_cubes
    3152             :       TYPE(particle_list_type), POINTER                  :: particles
    3153             :       TYPE(pw_env_type), POINTER                         :: pw_env
    3154             :       TYPE(pw_poisson_type), POINTER                     :: poisson_env
    3155             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    3156             :       TYPE(pw_r3d_rs_type)                               :: aux_r
    3157             :       TYPE(pw_r3d_rs_type), POINTER                      :: dirichlet_tile
    3158             :       TYPE(qs_subsys_type), POINTER                      :: subsys
    3159             :       TYPE(section_vals_type), POINTER                   :: dft_section
    3160             : 
    3161       10821 :       CALL timeset(routineN, handle)
    3162             : 
    3163       10821 :       NULLIFY (pw_env, auxbas_pw_pool, dft_section, particles)
    3164             : 
    3165       10821 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    3166       10821 :       CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, subsys=subsys)
    3167       10821 :       CALL qs_subsys_get(subsys, particles=particles)
    3168       10821 :       CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3169             : 
    3170       10821 :       has_implicit_ps = .FALSE.
    3171       10821 :       CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    3172       10821 :       IF (pw_env%poisson_env%parameters%solver .EQ. pw_poisson_implicit) has_implicit_ps = .TRUE.
    3173             : 
    3174             :       ! Write the dielectric constant into a cube file
    3175             :       do_dielectric_cube = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3176       10821 :                                                             "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE"), cp_p_file)
    3177       10821 :       IF (has_implicit_ps .AND. do_dielectric_cube) THEN
    3178           0 :          append_cube = section_get_lval(input, "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE%APPEND")
    3179           0 :          my_pos_cube = "REWIND"
    3180           0 :          IF (append_cube) THEN
    3181           0 :             my_pos_cube = "APPEND"
    3182             :          END IF
    3183           0 :          mpi_io = .TRUE.
    3184             :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE", &
    3185             :                                         extension=".cube", middle_name="DIELECTRIC_CONSTANT", file_position=my_pos_cube, &
    3186           0 :                                         mpi_io=mpi_io)
    3187           0 :          CALL pw_env_get(pw_env, poisson_env=poisson_env, auxbas_pw_pool=auxbas_pw_pool)
    3188           0 :          CALL auxbas_pw_pool%create_pw(aux_r)
    3189             : 
    3190           0 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    3191           0 :          SELECT CASE (boundary_condition)
    3192             :          CASE (PERIODIC_BC, MIXED_PERIODIC_BC)
    3193           0 :             CALL pw_copy(poisson_env%implicit_env%dielectric%eps, aux_r)
    3194             :          CASE (MIXED_BC, NEUMANN_BC)
    3195             :             CALL pw_shrink(pw_env%poisson_env%parameters%ps_implicit_params%neumann_directions, &
    3196             :                            pw_env%poisson_env%implicit_env%dct_env%dests_shrink, &
    3197             :                            pw_env%poisson_env%implicit_env%dct_env%srcs_shrink, &
    3198             :                            pw_env%poisson_env%implicit_env%dct_env%bounds_local_shftd, &
    3199           0 :                            poisson_env%implicit_env%dielectric%eps, aux_r)
    3200             :          END SELECT
    3201             : 
    3202             :          CALL cp_pw_to_cube(aux_r, unit_nr, "DIELECTRIC CONSTANT", particles=particles, &
    3203             :                             stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE%STRIDE"), &
    3204           0 :                             mpi_io=mpi_io)
    3205             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3206           0 :                                            "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE", mpi_io=mpi_io)
    3207             : 
    3208           0 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    3209             :       END IF
    3210             : 
    3211             :       ! Write Dirichlet constraint charges into a cube file
    3212             :       do_cstr_charge_cube = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3213       10821 :                                                              "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE"), cp_p_file)
    3214             : 
    3215       10821 :       has_dirichlet_bc = .FALSE.
    3216       10821 :       IF (has_implicit_ps) THEN
    3217          88 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    3218          88 :          IF (boundary_condition .EQ. MIXED_PERIODIC_BC .OR. boundary_condition .EQ. MIXED_BC) THEN
    3219          62 :             has_dirichlet_bc = .TRUE.
    3220             :          END IF
    3221             :       END IF
    3222             : 
    3223       10821 :       IF (has_implicit_ps .AND. do_cstr_charge_cube .AND. has_dirichlet_bc) THEN
    3224             :          append_cube = section_get_lval(input, &
    3225           0 :                                         "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE%APPEND")
    3226           0 :          my_pos_cube = "REWIND"
    3227           0 :          IF (append_cube) THEN
    3228           0 :             my_pos_cube = "APPEND"
    3229             :          END IF
    3230           0 :          mpi_io = .TRUE.
    3231             :          unit_nr = cp_print_key_unit_nr(logger, input, &
    3232             :                                         "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE", &
    3233             :                                         extension=".cube", middle_name="dirichlet_cstr_charge", file_position=my_pos_cube, &
    3234           0 :                                         mpi_io=mpi_io)
    3235           0 :          CALL pw_env_get(pw_env, poisson_env=poisson_env, auxbas_pw_pool=auxbas_pw_pool)
    3236           0 :          CALL auxbas_pw_pool%create_pw(aux_r)
    3237             : 
    3238           0 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    3239           0 :          SELECT CASE (boundary_condition)
    3240             :          CASE (MIXED_PERIODIC_BC)
    3241           0 :             CALL pw_copy(poisson_env%implicit_env%cstr_charge, aux_r)
    3242             :          CASE (MIXED_BC)
    3243             :             CALL pw_shrink(pw_env%poisson_env%parameters%ps_implicit_params%neumann_directions, &
    3244             :                            pw_env%poisson_env%implicit_env%dct_env%dests_shrink, &
    3245             :                            pw_env%poisson_env%implicit_env%dct_env%srcs_shrink, &
    3246             :                            pw_env%poisson_env%implicit_env%dct_env%bounds_local_shftd, &
    3247           0 :                            poisson_env%implicit_env%cstr_charge, aux_r)
    3248             :          END SELECT
    3249             : 
    3250             :          CALL cp_pw_to_cube(aux_r, unit_nr, "DIRICHLET CONSTRAINT CHARGE", particles=particles, &
    3251             :                             stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE%STRIDE"), &
    3252           0 :                             mpi_io=mpi_io)
    3253             :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3254           0 :                                            "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE", mpi_io=mpi_io)
    3255             : 
    3256           0 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    3257             :       END IF
    3258             : 
    3259             :       ! Write Dirichlet type constranits into cube files
    3260             :       do_dirichlet_bc_cube = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3261       10821 :                                                               "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE"), cp_p_file)
    3262       10821 :       has_dirichlet_bc = .FALSE.
    3263       10821 :       IF (has_implicit_ps) THEN
    3264          88 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    3265          88 :          IF (boundary_condition .EQ. MIXED_PERIODIC_BC .OR. boundary_condition .EQ. MIXED_BC) THEN
    3266          62 :             has_dirichlet_bc = .TRUE.
    3267             :          END IF
    3268             :       END IF
    3269             : 
    3270       10821 :       IF (has_implicit_ps .AND. has_dirichlet_bc .AND. do_dirichlet_bc_cube) THEN
    3271           0 :          append_cube = section_get_lval(input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%APPEND")
    3272           0 :          my_pos_cube = "REWIND"
    3273           0 :          IF (append_cube) THEN
    3274           0 :             my_pos_cube = "APPEND"
    3275             :          END IF
    3276           0 :          tile_cubes = section_get_lval(input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%TILE_CUBES")
    3277             : 
    3278           0 :          CALL pw_env_get(pw_env, poisson_env=poisson_env, auxbas_pw_pool=auxbas_pw_pool)
    3279           0 :          CALL auxbas_pw_pool%create_pw(aux_r)
    3280           0 :          CALL pw_zero(aux_r)
    3281             : 
    3282           0 :          IF (tile_cubes) THEN
    3283             :             ! one cube file per tile
    3284           0 :             n_cstr = SIZE(poisson_env%implicit_env%contacts)
    3285           0 :             DO j = 1, n_cstr
    3286           0 :                n_tiles = poisson_env%implicit_env%contacts(j)%dirichlet_bc%n_tiles
    3287           0 :                DO i = 1, n_tiles
    3288             :                   filename = "dirichlet_cstr_"//TRIM(ADJUSTL(cp_to_string(j)))// &
    3289           0 :                              "_tile_"//TRIM(ADJUSTL(cp_to_string(i)))
    3290           0 :                   mpi_io = .TRUE.
    3291             :                   unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", &
    3292             :                                                  extension=".cube", middle_name=filename, file_position=my_pos_cube, &
    3293           0 :                                                  mpi_io=mpi_io)
    3294             : 
    3295           0 :                   CALL pw_copy(poisson_env%implicit_env%contacts(j)%dirichlet_bc%tiles(i)%tile%tile_pw, aux_r)
    3296             : 
    3297             :                   CALL cp_pw_to_cube(aux_r, unit_nr, "DIRICHLET TYPE CONSTRAINT", particles=particles, &
    3298             :                                      stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%STRIDE"), &
    3299           0 :                                      mpi_io=mpi_io)
    3300             :                   CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3301           0 :                                                     "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", mpi_io=mpi_io)
    3302             :                END DO
    3303             :             END DO
    3304             :          ELSE
    3305             :             ! a single cube file
    3306           0 :             NULLIFY (dirichlet_tile)
    3307           0 :             ALLOCATE (dirichlet_tile)
    3308           0 :             CALL auxbas_pw_pool%create_pw(dirichlet_tile)
    3309           0 :             CALL pw_zero(dirichlet_tile)
    3310           0 :             mpi_io = .TRUE.
    3311             :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", &
    3312             :                                            extension=".cube", middle_name="DIRICHLET_CSTR", file_position=my_pos_cube, &
    3313           0 :                                            mpi_io=mpi_io)
    3314             : 
    3315           0 :             n_cstr = SIZE(poisson_env%implicit_env%contacts)
    3316           0 :             DO j = 1, n_cstr
    3317           0 :                n_tiles = poisson_env%implicit_env%contacts(j)%dirichlet_bc%n_tiles
    3318           0 :                DO i = 1, n_tiles
    3319           0 :                   CALL pw_copy(poisson_env%implicit_env%contacts(j)%dirichlet_bc%tiles(i)%tile%tile_pw, dirichlet_tile)
    3320           0 :                   CALL pw_axpy(dirichlet_tile, aux_r)
    3321             :                END DO
    3322             :             END DO
    3323             : 
    3324             :             CALL cp_pw_to_cube(aux_r, unit_nr, "DIRICHLET TYPE CONSTRAINT", particles=particles, &
    3325             :                                stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%STRIDE"), &
    3326           0 :                                mpi_io=mpi_io)
    3327             :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3328           0 :                                               "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", mpi_io=mpi_io)
    3329           0 :             CALL auxbas_pw_pool%give_back_pw(dirichlet_tile)
    3330           0 :             DEALLOCATE (dirichlet_tile)
    3331             :          END IF
    3332             : 
    3333           0 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    3334             :       END IF
    3335             : 
    3336       10821 :       CALL timestop(handle)
    3337             : 
    3338       10821 :    END SUBROUTINE qs_scf_post_ps_implicit
    3339             : 
    3340             : !**************************************************************************************************
    3341             : !> \brief write an adjacency (interaction) matrix
    3342             : !> \param qs_env qs environment
    3343             : !> \param input the input
    3344             : !> \author Mohammad Hossein Bani-Hashemian
    3345             : ! **************************************************************************************************
    3346       10821 :    SUBROUTINE write_adjacency_matrix(qs_env, input)
    3347             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3348             :       TYPE(section_vals_type), POINTER                   :: input
    3349             : 
    3350             :       CHARACTER(len=*), PARAMETER :: routineN = 'write_adjacency_matrix'
    3351             : 
    3352             :       INTEGER                                            :: adjm_size, colind, handle, iatom, ikind, &
    3353             :                                                             ind, jatom, jkind, k, natom, nkind, &
    3354             :                                                             output_unit, rowind, unit_nr
    3355       10821 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: interact_adjm
    3356             :       LOGICAL                                            :: do_adjm_write, do_symmetric
    3357             :       TYPE(cp_logger_type), POINTER                      :: logger
    3358       10821 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list_a, basis_set_list_b
    3359             :       TYPE(gto_basis_set_type), POINTER                  :: basis_set_a, basis_set_b
    3360             :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3361             :       TYPE(neighbor_list_iterator_p_type), &
    3362       10821 :          DIMENSION(:), POINTER                           :: nl_iterator
    3363             :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    3364       10821 :          POINTER                                         :: nl
    3365       10821 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    3366             :       TYPE(section_vals_type), POINTER                   :: dft_section
    3367             : 
    3368       10821 :       CALL timeset(routineN, handle)
    3369             : 
    3370       10821 :       NULLIFY (dft_section)
    3371             : 
    3372       10821 :       logger => cp_get_default_logger()
    3373       10821 :       output_unit = cp_logger_get_default_io_unit(logger)
    3374             : 
    3375       10821 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    3376             :       do_adjm_write = BTEST(cp_print_key_should_output(logger%iter_info, dft_section, &
    3377       10821 :                                                        "PRINT%ADJMAT_WRITE"), cp_p_file)
    3378             : 
    3379       10821 :       IF (do_adjm_write) THEN
    3380          28 :          NULLIFY (qs_kind_set, nl_iterator)
    3381          28 :          NULLIFY (basis_set_list_a, basis_set_list_b, basis_set_a, basis_set_b)
    3382             : 
    3383          28 :          CALL get_qs_env(qs_env, qs_kind_set=qs_kind_set, sab_orb=nl, natom=natom, para_env=para_env)
    3384             : 
    3385          28 :          nkind = SIZE(qs_kind_set)
    3386          28 :          CPASSERT(SIZE(nl) .GT. 0)
    3387          28 :          CALL get_neighbor_list_set_p(neighbor_list_sets=nl, symmetric=do_symmetric)
    3388          28 :          CPASSERT(do_symmetric)
    3389         216 :          ALLOCATE (basis_set_list_a(nkind), basis_set_list_b(nkind))
    3390          28 :          CALL basis_set_list_setup(basis_set_list_a, "ORB", qs_kind_set)
    3391          28 :          CALL basis_set_list_setup(basis_set_list_b, "ORB", qs_kind_set)
    3392             : 
    3393          28 :          adjm_size = ((natom + 1)*natom)/2
    3394          84 :          ALLOCATE (interact_adjm(4*adjm_size))
    3395         620 :          interact_adjm = 0
    3396             : 
    3397          28 :          NULLIFY (nl_iterator)
    3398          28 :          CALL neighbor_list_iterator_create(nl_iterator, nl)
    3399        2021 :          DO WHILE (neighbor_list_iterate(nl_iterator) .EQ. 0)
    3400             :             CALL get_iterator_info(nl_iterator, &
    3401             :                                    ikind=ikind, jkind=jkind, &
    3402        1993 :                                    iatom=iatom, jatom=jatom)
    3403             : 
    3404        1993 :             basis_set_a => basis_set_list_a(ikind)%gto_basis_set
    3405        1993 :             IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
    3406        1993 :             basis_set_b => basis_set_list_b(jkind)%gto_basis_set
    3407        1993 :             IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
    3408             : 
    3409             :             ! move everything to the upper triangular part
    3410        1993 :             IF (iatom .LE. jatom) THEN
    3411             :                rowind = iatom
    3412             :                colind = jatom
    3413             :             ELSE
    3414         670 :                rowind = jatom
    3415         670 :                colind = iatom
    3416             :                ! swap the kinds too
    3417             :                ikind = ikind + jkind
    3418         670 :                jkind = ikind - jkind
    3419         670 :                ikind = ikind - jkind
    3420             :             END IF
    3421             : 
    3422             :             ! indexing upper triangular matrix
    3423        1993 :             ind = adjm_size - (natom - rowind + 1)*((natom - rowind + 1) + 1)/2 + colind - rowind + 1
    3424             :             ! convert the upper triangular matrix into a adjm_size x 4 matrix
    3425             :             ! columns are: iatom, jatom, ikind, jkind
    3426        1993 :             interact_adjm((ind - 1)*4 + 1) = rowind
    3427        1993 :             interact_adjm((ind - 1)*4 + 2) = colind
    3428        1993 :             interact_adjm((ind - 1)*4 + 3) = ikind
    3429        1993 :             interact_adjm((ind - 1)*4 + 4) = jkind
    3430             :          END DO
    3431             : 
    3432          28 :          CALL para_env%sum(interact_adjm)
    3433             : 
    3434             :          unit_nr = cp_print_key_unit_nr(logger, dft_section, "PRINT%ADJMAT_WRITE", &
    3435             :                                         extension=".adjmat", file_form="FORMATTED", &
    3436          28 :                                         file_status="REPLACE")
    3437          28 :          IF (unit_nr .GT. 0) THEN
    3438          14 :             WRITE (unit_nr, "(1A,2X,1A,5X,1A,4X,A5,3X,A5)") "#", "iatom", "jatom", "ikind", "jkind"
    3439          88 :             DO k = 1, 4*adjm_size, 4
    3440             :                ! print only the interacting atoms
    3441          88 :                IF (interact_adjm(k) .GT. 0 .AND. interact_adjm(k + 1) .GT. 0) THEN
    3442          74 :                   WRITE (unit_nr, "(I8,2X,I8,3X,I6,2X,I6)") interact_adjm(k:k + 3)
    3443             :                END IF
    3444             :             END DO
    3445             :          END IF
    3446             : 
    3447          28 :          CALL cp_print_key_finished_output(unit_nr, logger, dft_section, "PRINT%ADJMAT_WRITE")
    3448             : 
    3449          28 :          CALL neighbor_list_iterator_release(nl_iterator)
    3450          56 :          DEALLOCATE (basis_set_list_a, basis_set_list_b)
    3451             :       END IF
    3452             : 
    3453       10821 :       CALL timestop(handle)
    3454             : 
    3455       21642 :    END SUBROUTINE write_adjacency_matrix
    3456             : 
    3457             : ! **************************************************************************************************
    3458             : !> \brief Updates Hartree potential with MP2 density. Important for REPEAT charges
    3459             : !> \param rho ...
    3460             : !> \param qs_env ...
    3461             : !> \author Vladimir Rybkin
    3462             : ! **************************************************************************************************
    3463         310 :    SUBROUTINE update_hartree_with_mp2(rho, qs_env)
    3464             :       TYPE(qs_rho_type), POINTER                         :: rho
    3465             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3466             : 
    3467             :       LOGICAL                                            :: use_virial
    3468             :       TYPE(pw_c1d_gs_type)                               :: rho_tot_gspace, v_hartree_gspace
    3469             :       TYPE(pw_c1d_gs_type), POINTER                      :: rho_core
    3470             :       TYPE(pw_env_type), POINTER                         :: pw_env
    3471             :       TYPE(pw_poisson_type), POINTER                     :: poisson_env
    3472             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    3473             :       TYPE(pw_r3d_rs_type), POINTER                      :: v_hartree_rspace
    3474             :       TYPE(qs_energy_type), POINTER                      :: energy
    3475             :       TYPE(virial_type), POINTER                         :: virial
    3476             : 
    3477         310 :       NULLIFY (auxbas_pw_pool, pw_env, poisson_env, energy, rho_core, v_hartree_rspace, virial)
    3478             :       CALL get_qs_env(qs_env, pw_env=pw_env, energy=energy, &
    3479             :                       rho_core=rho_core, virial=virial, &
    3480         310 :                       v_hartree_rspace=v_hartree_rspace)
    3481             : 
    3482         310 :       use_virial = virial%pv_availability .AND. (.NOT. virial%pv_numer)
    3483             : 
    3484             :       IF (.NOT. use_virial) THEN
    3485             : 
    3486             :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    3487         260 :                          poisson_env=poisson_env)
    3488         260 :          CALL auxbas_pw_pool%create_pw(v_hartree_gspace)
    3489         260 :          CALL auxbas_pw_pool%create_pw(rho_tot_gspace)
    3490             : 
    3491         260 :          CALL calc_rho_tot_gspace(rho_tot_gspace, qs_env, rho)
    3492             :          CALL pw_poisson_solve(poisson_env, rho_tot_gspace, energy%hartree, &
    3493         260 :                                v_hartree_gspace, rho_core=rho_core)
    3494             : 
    3495         260 :          CALL pw_transfer(v_hartree_gspace, v_hartree_rspace)
    3496         260 :          CALL pw_scale(v_hartree_rspace, v_hartree_rspace%pw_grid%dvol)
    3497             : 
    3498         260 :          CALL auxbas_pw_pool%give_back_pw(v_hartree_gspace)
    3499         260 :          CALL auxbas_pw_pool%give_back_pw(rho_tot_gspace)
    3500             :       END IF
    3501             : 
    3502         310 :    END SUBROUTINE update_hartree_with_mp2
    3503             : 
    3504             : END MODULE qs_scf_post_gpw

Generated by: LCOV version 1.15