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

Generated by: LCOV version 1.15