LCOV - code coverage report
Current view: top level - src - qs_scf_post_gpw.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:591cf04) Lines: 90.5 % 1755 1589
Test Date: 2026-09-21 02:17:57 Functions: 97.2 % 36 35

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief 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 casino_utils,                    ONLY: write_casino
      26              :    USE cell_types,                      ONLY: cell_type
      27              :    USE commutator_rpnl,                 ONLY: build_com_mom_nl
      28              :    USE cp_array_utils,                  ONLY: cp_1d_r_p_type
      29              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_type
      30              :    USE cp_control_types,                ONLY: dft_control_type,&
      31              :                                               rtp_control_type
      32              :    USE cp_dbcsr_api,                    ONLY: dbcsr_add,&
      33              :                                               dbcsr_create,&
      34              :                                               dbcsr_p_type,&
      35              :                                               dbcsr_scale,&
      36              :                                               dbcsr_set,&
      37              :                                               dbcsr_type,&
      38              :                                               dbcsr_type_antisymmetric
      39              :    USE cp_dbcsr_contrib,                ONLY: dbcsr_checksum
      40              :    USE cp_dbcsr_cp2k_link,              ONLY: cp_dbcsr_alloc_block_from_nbl
      41              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      42              :                                               dbcsr_allocate_matrix_set,&
      43              :                                               dbcsr_deallocate_matrix_set
      44              :    USE cp_dbcsr_output,                 ONLY: cp_dbcsr_write_sparse_matrix
      45              :    USE cp_ddapc_util,                   ONLY: get_ddapc
      46              :    USE cp_fm_diag,                      ONLY: choose_eigv_solver
      47              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      48              :                                               cp_fm_struct_release,&
      49              :                                               cp_fm_struct_type
      50              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      51              :                                               cp_fm_get_info,&
      52              :                                               cp_fm_init_random,&
      53              :                                               cp_fm_release,&
      54              :                                               cp_fm_to_fm,&
      55              :                                               cp_fm_type
      56              :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      57              :                                               cp_logger_get_default_io_unit,&
      58              :                                               cp_logger_type,&
      59              :                                               cp_to_string
      60              :    USE cp_output_handling,              ONLY: cp_iter_string,&
      61              :                                               cp_p_file,&
      62              :                                               cp_print_key_finished_output,&
      63              :                                               cp_print_key_should_output,&
      64              :                                               cp_print_key_unit_nr
      65              :    USE cp_output_handling_openpmd,      ONLY: cp_openpmd_close_iterations,&
      66              :                                               cp_openpmd_print_key_finished_output,&
      67              :                                               cp_openpmd_print_key_unit_nr
      68              :    USE cp_realspace_grid_cube,          ONLY: cp_pw_to_cube
      69              :    USE cp_realspace_grid_openpmd,       ONLY: cp_pw_to_openpmd
      70              :    USE cp_result_methods,               ONLY: get_results
      71              :    USE cp_result_types,                 ONLY: cp_result_type
      72              :    USE dct,                             ONLY: pw_shrink
      73              :    USE ed_analysis,                     ONLY: edmf_analysis
      74              :    USE eeq_method,                      ONLY: eeq_print
      75              :    USE et_coupling_types,               ONLY: set_et_coupling_type
      76              :    USE gapw_gspace_reconstruction,      ONLY: calculate_rhotot_elec_gspace
      77              :    USE hfx_ri,                          ONLY: print_ri_hfx
      78              :    USE hirshfeld_methods,               ONLY: comp_hirshfeld_charges,&
      79              :                                               comp_hirshfeld_i_charges,&
      80              :                                               create_shape_function,&
      81              :                                               save_hirshfeld_charges,&
      82              :                                               write_hirshfeld_charges
      83              :    USE hirshfeld_types,                 ONLY: create_hirshfeld_type,&
      84              :                                               hirshfeld_type,&
      85              :                                               release_hirshfeld_type,&
      86              :                                               set_hirshfeld_info
      87              :    USE iao_analysis,                    ONLY: iao_wfn_analysis
      88              :    USE iao_types,                       ONLY: iao_env_type,&
      89              :                                               iao_read_input
      90              :    USE input_constants,                 ONLY: &
      91              :         do_loc_both, do_loc_homo, do_loc_jacobi, do_loc_lumo, do_loc_mixed, do_loc_none, &
      92              :         moments_format_trajectory, ot_precond_full_all, ot_precond_full_all_covariant, &
      93              :         radius_covalent, radius_user, ref_charge_atomic, ref_charge_mulliken
      94              :    USE input_section_types,             ONLY: section_get_ival,&
      95              :                                               section_get_ivals,&
      96              :                                               section_get_lval,&
      97              :                                               section_get_rval,&
      98              :                                               section_vals_get,&
      99              :                                               section_vals_get_subs_vals,&
     100              :                                               section_vals_type,&
     101              :                                               section_vals_val_get
     102              :    USE kinds,                           ONLY: default_path_length,&
     103              :                                               default_string_length,&
     104              :                                               dp
     105              :    USE kpoint_mo_dump,                  ONLY: write_kpoint_mo_data
     106              :    USE kpoint_types,                    ONLY: kpoint_type
     107              :    USE localized_moments,               ONLY: calculate_kg_moments
     108              :    USE mao_wfn_analysis,                ONLY: mao_analysis
     109              :    USE mathconstants,                   ONLY: pi
     110              :    USE memory_utilities,                ONLY: reallocate
     111              :    USE message_passing,                 ONLY: mp_para_env_type
     112              :    USE minbas_wfn_analysis,             ONLY: minbas_analysis
     113              :    USE molden_utils,                    ONLY: write_mos_molden
     114              :    USE molecule_types,                  ONLY: molecule_type
     115              :    USE mulliken,                        ONLY: mulliken_charges
     116              :    USE orbital_pointers,                ONLY: indso
     117              :    USE particle_list_types,             ONLY: particle_list_type
     118              :    USE particle_types,                  ONLY: particle_type
     119              :    USE physcon,                         ONLY: a_bohr,&
     120              :                                               angstrom,&
     121              :                                               debye,&
     122              :                                               evolt
     123              :    USE population_analyses,             ONLY: lowdin_population_analysis,&
     124              :                                               mulliken_population_analysis
     125              :    USE preconditioner_types,            ONLY: preconditioner_type
     126              :    USE ps_implicit_types,               ONLY: MIXED_BC,&
     127              :                                               MIXED_PERIODIC_BC,&
     128              :                                               NEUMANN_BC,&
     129              :                                               PERIODIC_BC
     130              :    USE pw_env_types,                    ONLY: pw_env_get,&
     131              :                                               pw_env_type
     132              :    USE pw_grids,                        ONLY: get_pw_grid_info
     133              :    USE pw_methods,                      ONLY: pw_axpy,&
     134              :                                               pw_copy,&
     135              :                                               pw_derive,&
     136              :                                               pw_integrate_function,&
     137              :                                               pw_scale,&
     138              :                                               pw_transfer,&
     139              :                                               pw_zero
     140              :    USE pw_poisson_methods,              ONLY: pw_poisson_solve
     141              :    USE pw_poisson_types,                ONLY: pw_poisson_implicit,&
     142              :                                               pw_poisson_type
     143              :    USE pw_pool_types,                   ONLY: pw_pool_p_type,&
     144              :                                               pw_pool_type
     145              :    USE pw_types,                        ONLY: pw_c1d_gs_type,&
     146              :                                               pw_r3d_rs_type
     147              :    USE qs_chargemol,                    ONLY: write_wfx
     148              :    USE qs_charges_types,                ONLY: qs_charges_type
     149              :    USE qs_collocate_density,            ONLY: calculate_rho_resp_all,&
     150              :                                               calculate_wavefunction
     151              :    USE qs_core_energies,                ONLY: calculate_ptrace
     152              :    USE qs_dos,                          ONLY: calculate_dos,&
     153              :                                               calculate_dos_kp
     154              :    USE qs_dos_utils,                    ONLY: get_dos_pdos_flags
     155              :    USE qs_electric_field_gradient,      ONLY: qs_efg_calc
     156              :    USE qs_elf_methods,                  ONLY: qs_elf_calc
     157              :    USE qs_energy_types,                 ONLY: qs_energy_type
     158              :    USE qs_energy_window,                ONLY: energy_windows
     159              :    USE qs_environment_types,            ONLY: get_qs_env,&
     160              :                                               qs_environment_type,&
     161              :                                               set_qs_env
     162              :    USE qs_epr_hyp,                      ONLY: qs_epr_hyp_calc
     163              :    USE qs_fod,                          ONLY: qs_scf_post_fod
     164              :    USE qs_grid_atom,                    ONLY: grid_atom_type
     165              :    USE qs_integral_utils,               ONLY: basis_set_list_setup
     166              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
     167              :                                               qs_kind_type
     168              :    USE qs_ks_methods,                   ONLY: calc_rho_tot_gspace,&
     169              :                                               qs_ks_update_qs_env
     170              :    USE qs_ks_types,                     ONLY: qs_ks_did_change
     171              :    USE qs_kubo_transport,               ONLY: qs_scf_post_kubo_transport
     172              :    USE qs_loc_dipole,                   ONLY: loc_dipole
     173              :    USE qs_loc_states,                   ONLY: get_localization_info
     174              :    USE qs_loc_types,                    ONLY: qs_loc_env_create,&
     175              :                                               qs_loc_env_release,&
     176              :                                               qs_loc_env_type
     177              :    USE qs_loc_utils,                    ONLY: loc_write_restart,&
     178              :                                               qs_loc_control_init,&
     179              :                                               qs_loc_env_init,&
     180              :                                               qs_loc_init,&
     181              :                                               retain_history
     182              :    USE qs_local_properties,             ONLY: qs_local_energy,&
     183              :                                               qs_local_stress
     184              :    USE qs_mo_io,                        ONLY: write_dm_binary_restart
     185              :    USE qs_mo_methods,                   ONLY: calculate_subspace_eigenvalues,&
     186              :                                               make_mo_eig
     187              :    USE qs_mo_occupation,                ONLY: set_mo_occupation
     188              :    USE qs_mo_types,                     ONLY: get_mo_set,&
     189              :                                               mo_set_type
     190              :    USE qs_moments,                      ONLY: qs_moment_berry_phase,&
     191              :                                               qs_moment_kpoints,&
     192              :                                               qs_moment_locop
     193              :    USE qs_neighbor_list_types,          ONLY: get_iterator_info,&
     194              :                                               get_neighbor_list_set_p,&
     195              :                                               neighbor_list_iterate,&
     196              :                                               neighbor_list_iterator_create,&
     197              :                                               neighbor_list_iterator_p_type,&
     198              :                                               neighbor_list_iterator_release,&
     199              :                                               neighbor_list_set_p_type
     200              :    USE qs_operators_ao,                 ONLY: build_lin_mom_matrix
     201              :    USE qs_ot_eigensolver,               ONLY: ot_eigensolver
     202              :    USE qs_pdos,                         ONLY: calculate_projected_dos,&
     203              :                                               calculate_projected_dos_kp
     204              :    USE qs_resp,                         ONLY: resp_fit
     205              :    USE qs_rho0_types,                   ONLY: get_rho0_mpole,&
     206              :                                               mpole_rho_atom,&
     207              :                                               rho0_mpole_type
     208              :    USE qs_rho_atom_types,               ONLY: rho_atom_type
     209              :    USE qs_rho_methods,                  ONLY: qs_rho_update_rho
     210              :    USE qs_rho_types,                    ONLY: qs_rho_get,&
     211              :                                               qs_rho_type
     212              :    USE qs_scf_csr_write,                ONLY: write_hcore_matrix_csr,&
     213              :                                               write_ks_matrix_csr,&
     214              :                                               write_p_matrix_csr,&
     215              :                                               write_s_matrix_csr
     216              :    USE qs_scf_output,                   ONLY: qs_scf_write_mos
     217              :    USE qs_scf_types,                    ONLY: ot_method_nr,&
     218              :                                               qs_scf_env_type
     219              :    USE qs_scf_wfn_mix,                  ONLY: wfn_mix
     220              :    USE qs_subsys_types,                 ONLY: qs_subsys_get,&
     221              :                                               qs_subsys_type
     222              :    USE qs_wannier90,                    ONLY: wannier90_interface
     223              :    USE s_square_methods,                ONLY: compute_s_square
     224              :    USE scf_control_types,               ONLY: scf_control_type
     225              :    USE stm_images,                      ONLY: th_stm_image
     226              :    USE transport,                       ONLY: qs_scf_post_transport
     227              :    USE trexio_utils,                    ONLY: write_trexio
     228              :    USE virial_types,                    ONLY: virial_type
     229              :    USE voronoi_interface,               ONLY: entry_voronoi_or_bqb
     230              :    USE xray_diffraction,                ONLY: xray_diffraction_spectrum
     231              : #include "./base/base_uses.f90"
     232              : 
     233              :    IMPLICIT NONE
     234              :    PRIVATE
     235              : 
     236              :    ! Global parameters
     237              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_scf_post_gpw'
     238              :    PUBLIC :: make_lumo_gpw, &
     239              :              scf_post_calculation_gpw, &
     240              :              qs_scf_post_moments, &
     241              :              write_mo_dependent_results, &
     242              :              write_mo_free_results
     243              : 
     244              :    CHARACTER(len=*), PARAMETER :: &
     245              :       str_mo_cubes = "PRINT%MO_CUBES", &
     246              :       str_mo_openpmd = "PRINT%MO_OPENPMD", &
     247              :       str_elf_cubes = "PRINT%ELF_CUBE", &
     248              :       str_elf_openpmd = "PRINT%ELF_OPENPMD", &
     249              :       str_e_density_cubes = "PRINT%E_DENSITY_CUBE", &
     250              :       str_e_density_openpmd = "PRINT%E_DENSITY_OPENPMD"
     251              : 
     252              :    INTEGER, PARAMETER :: grid_output_cubes = 1, grid_output_openpmd = 2
     253              : 
     254              :    REAL(kind=dp), DIMENSION(7), PARAMETER :: openpmd_unit_dimension_density = &
     255              :                                              [-3, 0, 0, 0, 0, 0, 0]
     256              :    REAL(kind=dp), DIMENSION(7), PARAMETER :: openpmd_unit_dimension_dimensionless = &
     257              :                                              [0, 0, 0, 0, 0, 0, 0]
     258              :    REAL(kind=dp), DIMENSION(7), PARAMETER :: openpmd_unit_dimension_wavefunction = &
     259              :                                              [-1.5_dp, 0.0_dp, 0.0_dp, 0.0_dp, 0.0_dp, 0.0_dp, 0.0_dp]
     260              :    REAL(kind=dp), PARAMETER :: openpmd_unit_si_density = a_bohr**(-3)
     261              :    REAL(kind=dp), PARAMETER :: openpmd_unit_si_dimensionless = 1.0_dp
     262              :    REAL(kind=dp), PARAMETER :: openpmd_unit_si_wavefunction = a_bohr**(-1.5_dp)
     263              : 
     264              :    ! Generic information on whether a certain output section has been activated
     265              :    ! or not, and on whether it has been activated in the Cube or openPMD variant.
     266              :    ! Create with function cube_or_openpmd(), see there for further details.
     267              :    TYPE cp_section_key
     268              :       CHARACTER(len=default_string_length) :: relative_section_key = "" ! e.g. PRINT%MO_CUBES
     269              :       CHARACTER(len=default_string_length) :: absolute_section_key = "" ! e.g. DFT%PRINT%MO_CUBES
     270              :       CHARACTER(len=7) :: format_name = "" ! 'openPMD' or 'Cube', for logging
     271              :       INTEGER :: grid_output = -1 ! either 1 for grid_output_cubes or 2 for grid_output_openpmd
     272              :       LOGICAL :: do_output = .FALSE.
     273              :    CONTAINS
     274              :       ! Open a file as either Cube or openPMD
     275              :       PROCEDURE, PUBLIC :: print_key_unit_nr => cp_forward_print_key_unit_nr
     276              :       ! Write either to the Cube or openPMD file
     277              :       PROCEDURE, PUBLIC :: write_pw => cp_forward_write_pw
     278              :       ! Close either the Cube or openPMD file
     279              :       PROCEDURE, PUBLIC :: print_key_finished_output => cp_forward_print_key_finished_output
     280              :       ! Helpers
     281              :       PROCEDURE, PUBLIC :: do_openpmd => cp_section_key_do_openpmd
     282              :       PROCEDURE, PUBLIC :: do_cubes => cp_section_key_do_cubes
     283              :       PROCEDURE, PUBLIC :: concat_to_relative => cp_section_key_concat_to_relative
     284              :       PROCEDURE, PUBLIC :: concat_to_absolute => cp_section_key_concat_to_absolute
     285              :    END TYPE cp_section_key
     286              : 
     287              : CONTAINS
     288              : 
     289              : ! **************************************************************************************************
     290              : !> \brief Collects the effective core charge for every atom in a QS environment
     291              : !> \param qs_env the QS environment
     292              : !> \param zcharge effective core charges ordered by atom index
     293              : ! **************************************************************************************************
     294        14063 :    SUBROUTINE get_effective_core_charges(qs_env, zcharge)
     295              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     296              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
     297              :          INTENT(OUT)                                     :: zcharge
     298              : 
     299              :       INTEGER                                            :: iat, iatom, ikind, nat, natom, nkind
     300              :       REAL(KIND=dp)                                      :: zeff
     301        14063 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     302        14063 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     303              : 
     304              :       CALL get_qs_env(qs_env, atomic_kind_set=atomic_kind_set, qs_kind_set=qs_kind_set, &
     305        14063 :                       nkind=nkind, natom=natom)
     306        42189 :       ALLOCATE (zcharge(natom))
     307        38671 :       DO ikind = 1, nkind
     308        24608 :          CALL get_qs_kind(qs_kind_set(ikind), zeff=zeff)
     309        24608 :          CALL get_atomic_kind(atomic_kind_set(ikind), natom=nat)
     310        91298 :          DO iatom = 1, nat
     311        52627 :             iat = atomic_kind_set(ikind)%atom_list(iatom)
     312        77235 :             zcharge(iat) = zeff
     313              :          END DO
     314              :       END DO
     315        14063 :    END SUBROUTINE get_effective_core_charges
     316              : 
     317              : ! **************************************************************************************************
     318              : !> \brief Append `extend_by` to the absolute path of the base section.
     319              : !> \param self ...
     320              : !> \param extend_by ...
     321              : !> \return ...
     322              : ! **************************************************************************************************
     323          310 :    FUNCTION cp_section_key_concat_to_absolute(self, extend_by) RESULT(res)
     324              :       CLASS(cp_section_key), INTENT(IN) :: self
     325              :       CHARACTER(*), INTENT(IN) :: extend_by
     326              :       CHARACTER(len=default_string_length) :: res
     327              : 
     328          310 :       IF (LEN(TRIM(extend_by)) > 0 .AND. extend_by(1:1) == "%") THEN
     329          310 :          res = TRIM(self%absolute_section_key)//TRIM(extend_by)
     330              :       ELSE
     331            0 :          res = TRIM(self%absolute_section_key)//"%"//TRIM(extend_by)
     332              :       END IF
     333          310 :    END FUNCTION cp_section_key_concat_to_absolute
     334              : 
     335              : ! **************************************************************************************************
     336              : !> \brief Append `extend_by` to the relative path (e.g. without DFT%) of the base section.
     337              : !> \param self ...
     338              : !> \param extend_by ...
     339              : !> \return ...
     340              : ! **************************************************************************************************
     341        26118 :    FUNCTION cp_section_key_concat_to_relative(self, extend_by) RESULT(res)
     342              :       CLASS(cp_section_key), INTENT(IN) :: self
     343              :       CHARACTER(*), INTENT(IN) :: extend_by
     344              :       CHARACTER(len=default_string_length) :: res
     345              : 
     346        26118 :       IF (LEN(TRIM(extend_by)) > 0 .AND. extend_by(1:1) == "%") THEN
     347        26118 :          res = TRIM(self%relative_section_key)//TRIM(extend_by)
     348              :       ELSE
     349            0 :          res = TRIM(self%relative_section_key)//"%"//TRIM(extend_by)
     350              :       END IF
     351        26118 :    END FUNCTION cp_section_key_concat_to_relative
     352              : 
     353              : ! **************************************************************************************************
     354              : !> \brief Is Cube output active for the current base section?
     355              : !> \param self ...
     356              : !> \return ...
     357              : ! **************************************************************************************************
     358          692 :    FUNCTION cp_section_key_do_cubes(self) RESULT(res)
     359              :       CLASS(cp_section_key) :: self
     360              :       LOGICAL :: res
     361              : 
     362          692 :       res = self%do_output .AND. self%grid_output == grid_output_cubes
     363          692 :    END FUNCTION cp_section_key_do_cubes
     364              : 
     365              : ! **************************************************************************************************
     366              : !> \brief Is openPMD output active for the current base section?
     367              : !> \param self ...
     368              : !> \return ...
     369              : ! **************************************************************************************************
     370          692 :    FUNCTION cp_section_key_do_openpmd(self) RESULT(res)
     371              :       CLASS(cp_section_key) :: self
     372              :       LOGICAL :: res
     373              : 
     374          692 :       res = self%do_output .AND. self%grid_output == grid_output_openpmd
     375          692 :    END FUNCTION cp_section_key_do_openpmd
     376              : 
     377              : ! **************************************************************************************************
     378              : !> \brief Forwards to either `cp_print_key_unit_nr` or `cp_openpmd_print_key_unit_nr`,
     379              : !>        depending on the configuration of the current base section.
     380              : !>        Opens either a Cube or openPMD output file
     381              : !> \param self ...
     382              : !> \param logger ...
     383              : !> \param basis_section ...
     384              : !> \param print_key_path ...
     385              : !> \param extension ...
     386              : !> \param middle_name ...
     387              : !> \param local ...
     388              : !> \param log_filename ...
     389              : !> \param ignore_should_output ...
     390              : !> \param file_form ...
     391              : !> \param file_position ...
     392              : !> \param file_action ...
     393              : !> \param file_status ...
     394              : !> \param do_backup ...
     395              : !> \param on_file ...
     396              : !> \param is_new_file ...
     397              : !> \param mpi_io ...
     398              : !> \param fout ...
     399              : !> \param openpmd_basename ...
     400              : !> \param openpmd_unit_dimension ...
     401              : !> \param openpmd_unit_si ...
     402              : !> \param sim_time ...
     403              : !> \return ...
     404              : ! **************************************************************************************************
     405          552 :    FUNCTION cp_forward_print_key_unit_nr( &
     406              :       self, &
     407              :       logger, &
     408              :       basis_section, &
     409              :       print_key_path, &
     410              :       extension, &
     411              :       middle_name, &
     412              :       local, &
     413              :       log_filename, &
     414              :       ignore_should_output, &
     415              :       file_form, &
     416              :       file_position, &
     417              :       file_action, &
     418              :       file_status, &
     419              :       do_backup, &
     420              :       on_file, &
     421              :       is_new_file, &
     422              :       mpi_io, &
     423              :       fout, &
     424              :       openpmd_basename, &
     425              :       openpmd_unit_dimension, &
     426              :       openpmd_unit_si, &
     427              :       sim_time) RESULT(res)
     428              : 
     429              :       CLASS(cp_section_key), INTENT(IN)                  :: self
     430              :       TYPE(cp_logger_type), POINTER                      :: logger
     431              :       TYPE(section_vals_type), INTENT(IN)                :: basis_section
     432              :       CHARACTER(len=*), INTENT(IN), OPTIONAL             :: print_key_path
     433              :       CHARACTER(len=*), INTENT(IN)                       :: extension
     434              :       CHARACTER(len=*), INTENT(IN), OPTIONAL             :: middle_name
     435              :       LOGICAL, INTENT(IN), OPTIONAL                      :: local, log_filename, ignore_should_output
     436              :       CHARACTER(len=*), INTENT(IN), OPTIONAL             :: file_form, file_position, file_action, &
     437              :                                                             file_status
     438              :       LOGICAL, INTENT(IN), OPTIONAL                      :: do_backup, on_file
     439              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: is_new_file
     440              :       LOGICAL, INTENT(INOUT), OPTIONAL                   :: mpi_io
     441              :       CHARACTER(len=default_path_length), INTENT(OUT), &
     442              :          OPTIONAL                                        :: fout
     443              :       CHARACTER(len=*), INTENT(IN), OPTIONAL             :: openpmd_basename
     444              :       REAL(kind=dp), DIMENSION(7), OPTIONAL, INTENT(IN)  :: openpmd_unit_dimension
     445              :       REAL(kind=dp), OPTIONAL, INTENT(IN)                :: openpmd_unit_si
     446              :       REAL(kind=dp), OPTIONAL, INTENT(IN)                :: sim_time
     447              :       INTEGER                                            :: res
     448              : 
     449          552 :       IF (self%grid_output == grid_output_cubes) THEN
     450              :          res = cp_print_key_unit_nr( &
     451              :                logger, basis_section, print_key_path, extension=extension, &
     452              :                middle_name=middle_name, local=local, log_filename=log_filename, &
     453              :                ignore_should_output=ignore_should_output, file_form=file_form, &
     454              :                file_position=file_position, file_action=file_action, &
     455              :                file_status=file_status, do_backup=do_backup, on_file=on_file, &
     456         2466 :                is_new_file=is_new_file, mpi_io=mpi_io, fout=fout)
     457              :       ELSE
     458              :          res = cp_openpmd_print_key_unit_nr( &
     459              :                logger, &
     460              :                basis_section, &
     461              :                print_key_path, &
     462              :                middle_name=middle_name, &
     463              :                ignore_should_output=ignore_should_output, &
     464              :                mpi_io=mpi_io, &
     465              :                fout=fout, &
     466              :                openpmd_basename=openpmd_basename, &
     467              :                openpmd_unit_dimension=openpmd_unit_dimension, &
     468              :                openpmd_unit_si=openpmd_unit_si, &
     469            0 :                sim_time=sim_time)
     470              :       END IF
     471          552 :    END FUNCTION cp_forward_print_key_unit_nr
     472              : 
     473              : ! **************************************************************************************************
     474              : !> \brief Forwards to either `cp_pw_to_cube` or `cp_pw_to_openpmd`,
     475              : !>        depending on the configuration of the current base section.
     476              : !>        Writes data to either a Cube or an openPMD file.
     477              : !> \param self ...
     478              : !> \param pw ...
     479              : !> \param unit_nr ...
     480              : !> \param title ...
     481              : !> \param particles ...
     482              : !> \param zeff ...
     483              : !> \param stride ...
     484              : !> \param max_file_size_mb ...
     485              : !> \param zero_tails ...
     486              : !> \param silent ...
     487              : !> \param mpi_io ...
     488              : ! **************************************************************************************************
     489          552 :    SUBROUTINE cp_forward_write_pw( &
     490              :       self, &
     491              :       pw, &
     492              :       unit_nr, &
     493              :       title, &
     494              :       particles, &
     495          552 :       zeff, &
     496              :       stride, &
     497              :       max_file_size_mb, &
     498              :       zero_tails, &
     499              :       silent, &
     500              :       mpi_io &
     501              :       )
     502              :       CLASS(cp_section_key), INTENT(IN)                  :: self
     503              :       TYPE(pw_r3d_rs_type), INTENT(IN)                   :: pw
     504              :       INTEGER, INTENT(IN)                                :: unit_nr
     505              :       CHARACTER(*), INTENT(IN), OPTIONAL                 :: title
     506              :       TYPE(particle_list_type), POINTER                  :: particles
     507              :       INTEGER, DIMENSION(:), OPTIONAL, POINTER           :: stride
     508              :       REAL(KIND=dp), INTENT(IN), OPTIONAL                :: max_file_size_mb
     509              :       LOGICAL, INTENT(IN), OPTIONAL                      :: zero_tails, silent, mpi_io
     510              :       REAL(KIND=dp), DIMENSION(:), OPTIONAL              :: zeff
     511              : 
     512          552 :       IF (self%grid_output == grid_output_cubes) THEN
     513          552 :          CALL cp_pw_to_cube(pw, unit_nr, title, particles, zeff, stride, max_file_size_mb, zero_tails, silent, mpi_io)
     514              :       ELSE
     515            0 :          CALL cp_pw_to_openpmd(pw, unit_nr, title, particles, zeff, stride, zero_tails, silent, mpi_io)
     516              :       END IF
     517          552 :    END SUBROUTINE cp_forward_write_pw
     518              : 
     519              : ! **************************************************************************************************
     520              : !> \brief Forwards to either `cp_print_key_finished_output` or `cp_openpmd_print_key_finished_output`,
     521              : !>        depending on the configuration of the current base section.
     522              : !>        Closes either a Cube file or a reference to a section within an openPMD file.
     523              : !> \param self ...
     524              : !> \param unit_nr ...
     525              : !> \param logger ...
     526              : !> \param basis_section ...
     527              : !> \param print_key_path ...
     528              : !> \param local ...
     529              : !> \param ignore_should_output ...
     530              : !> \param on_file ...
     531              : !> \param mpi_io ...
     532              : ! **************************************************************************************************
     533          552 :    SUBROUTINE cp_forward_print_key_finished_output(self, unit_nr, logger, basis_section, &
     534              :                                                    print_key_path, local, ignore_should_output, on_file, &
     535              :                                                    mpi_io)
     536              :       CLASS(cp_section_key), INTENT(IN)                  :: self
     537              :       INTEGER, INTENT(INOUT)                             :: unit_nr
     538              :       TYPE(cp_logger_type), POINTER                      :: logger
     539              :       TYPE(section_vals_type), INTENT(IN)                :: basis_section
     540              :       CHARACTER(len=*), INTENT(IN), OPTIONAL             :: print_key_path
     541              :       LOGICAL, INTENT(IN), OPTIONAL                      :: local, ignore_should_output, on_file, &
     542              :                                                             mpi_io
     543              : 
     544          552 :       IF (self%grid_output == grid_output_cubes) THEN
     545          552 :      CALL cp_print_key_finished_output(unit_nr, logger, basis_section, print_key_path, local, ignore_should_output, on_file, mpi_io)
     546              :       ELSE
     547            0 :       CALL cp_openpmd_print_key_finished_output(unit_nr, logger, basis_section, print_key_path, local, ignore_should_output, mpi_io)
     548              :       END IF
     549          552 :    END SUBROUTINE cp_forward_print_key_finished_output
     550              : 
     551              :    !
     552              : ! **************************************************************************************************
     553              : !> \brief Decides if a particular output routine will write to openPMD, to Cube or to none.
     554              : !>        Writing to both is not supported.
     555              : !>        The distinction between Cube and openPMD output works such that the output configuration
     556              : !>        sections exist as duplicates: E.g. for DFT%PRINT%MO_CUBES,
     557              : !>        there additionally exists DFT%PRINT%MO_OPENPMD.
     558              : !>        The internal base configuration for such sections is identical; additionally there
     559              : !>        exist format-specific options such as APPEND for Cube or OPENPMD_CFG_FILE for openPMD.
     560              : !>        The routines in this file alternate between using relative section paths without the
     561              : !>        %DFT prefix (e.g. PRINT%MO_CUBES) or absolute section paths with the %DF% prefix
     562              : !>        (e.g. DFT%PRINT%MO_CUBES). Call this routine with the relative paths.
     563              : !> \param input ...
     564              : !> \param str_cubes ...
     565              : !> \param str_openpmd ...
     566              : !> \param logger ...
     567              : !> \return ...
     568              : ! **************************************************************************************************
     569        38357 :    FUNCTION cube_or_openpmd(input, str_cubes, str_openpmd, logger) RESULT(res)
     570              :       TYPE(section_vals_type), POINTER                   :: input
     571              :       CHARACTER(len=*), INTENT(IN)                       :: str_cubes, str_openpmd
     572              :       TYPE(cp_logger_type), POINTER                      :: logger
     573              :       TYPE(cp_section_key)                               :: res
     574              : 
     575              :       LOGICAL                                            :: do_cubes, do_openpmd
     576              : 
     577              :       do_cubes = BTEST(cp_print_key_should_output( &
     578              :                        logger%iter_info, input, &
     579        38357 :                        "DFT%"//TRIM(ADJUSTL(str_cubes))), cp_p_file)
     580              :       do_openpmd = BTEST(cp_print_key_should_output( &
     581              :                          logger%iter_info, input, &
     582        38357 :                          "DFT%"//TRIM(ADJUSTL(str_openpmd))), cp_p_file)
     583              :       ! Having Cube and openPMD output both active should be theoretically possible.
     584              :       ! It would require some extra handling for the unit_nr return values.
     585              :       ! (e.g. returning the Cube unit_nr and internally storing the associated openPMD unit_nr).
     586        38357 :       CPASSERT(.NOT. (do_cubes .AND. do_openpmd))
     587        38357 :       res%do_output = do_cubes .OR. do_openpmd
     588        38357 :       IF (do_openpmd) THEN
     589            0 :          res%grid_output = grid_output_openpmd
     590            0 :          res%relative_section_key = TRIM(ADJUSTL(str_openpmd))
     591            0 :          res%format_name = "openPMD"
     592              :       ELSE
     593        38357 :          res%grid_output = grid_output_cubes
     594        38357 :          res%relative_section_key = TRIM(ADJUSTL(str_cubes))
     595        38357 :          res%format_name = "Cube"
     596              :       END IF
     597        38357 :       res%absolute_section_key = "DFT%"//TRIM(ADJUSTL(res%relative_section_key))
     598        38357 :    END FUNCTION cube_or_openpmd
     599              : 
     600              : ! **************************************************************************************************
     601              : !> \brief This section key is named WRITE_CUBE for Cube which does not make much sense
     602              : !>        for openPMD, so this key name has to be distinguished.
     603              : !> \param grid_output ...
     604              : !> \return ...
     605              : ! **************************************************************************************************
     606          296 :    FUNCTION section_key_do_write(grid_output) RESULT(res)
     607              :       INTEGER, INTENT(IN)                                :: grid_output
     608              :       CHARACTER(len=32)                                  :: res
     609              : 
     610          296 :       IF (grid_output == grid_output_cubes) THEN
     611          296 :          res = "%WRITE_CUBE"
     612            0 :       ELSE IF (grid_output == grid_output_openpmd) THEN
     613            0 :          res = "%WRITE_OPENPMD"
     614              :       END IF
     615          296 :    END FUNCTION section_key_do_write
     616              : 
     617              : ! **************************************************************************************************
     618              : !> \brief Prints the output message for density file writing
     619              : !> \param output_unit Unit number for output
     620              : !> \param prefix The message prefix (e.g., "The total electron density")
     621              : !> \param e_density_section Section key containing grid_output and format_name
     622              : !> \param filename The actual filename or pattern used
     623              : ! **************************************************************************************************
     624          105 :    SUBROUTINE print_density_output_message(output_unit, prefix, e_density_section, filename)
     625              :       INTEGER, INTENT(IN)                                :: output_unit
     626              :       CHARACTER(len=*), INTENT(IN)                       :: prefix
     627              :       TYPE(cp_section_key), INTENT(IN)                   :: e_density_section
     628              :       CHARACTER(len=*), INTENT(IN)                       :: filename
     629              : 
     630          105 :       IF (e_density_section%grid_output == grid_output_openpmd) THEN
     631              :          WRITE (UNIT=output_unit, FMT="(/,T2,A)") &
     632              :             TRIM(prefix)//" is written in " &
     633              :             //e_density_section%format_name &
     634            0 :             //" file format to the file / file pattern:", &
     635            0 :             TRIM(filename)
     636              :       ELSE
     637              :          WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
     638              :             TRIM(prefix)//" is written in " &
     639              :             //e_density_section%format_name &
     640          105 :             //" file format to the file:", &
     641          210 :             TRIM(filename)
     642              :       END IF
     643          105 :    END SUBROUTINE print_density_output_message
     644              : 
     645              : ! **************************************************************************************************
     646              : !> \brief collects possible post - scf calculations and prints info / computes properties.
     647              : !> \param qs_env the qs_env in which the qs_env lives
     648              : !> \param wf_type ...
     649              : !> \param do_mp2 ...
     650              : !> \par History
     651              : !>      02.2003 created [fawzi]
     652              : !>      10.2004 moved here from qs_scf [Joost VandeVondele]
     653              : !>              started splitting out different subroutines
     654              : !>      10.2015 added header for wave-function correlated methods [Vladimir Rybkin]
     655              : !> \author fawzi
     656              : !> \note
     657              : !>      this function changes mo_eigenvectors and mo_eigenvalues, depending on the print keys.
     658              : !>      In particular, MO_CUBES causes the MOs to be rotated to make them eigenstates of the KS
     659              : !>      matrix, and mo_eigenvalues is updated accordingly. This can, for unconverged wavefunctions,
     660              : !>      change afterwards slightly the forces (hence small numerical differences between MD
     661              : !>      with and without the debug print level). Ideally this should not happen...
     662              : ! **************************************************************************************************
     663        12331 :    SUBROUTINE scf_post_calculation_gpw(qs_env, wf_type, do_mp2)
     664              : 
     665              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     666              :       CHARACTER(6), OPTIONAL                             :: wf_type
     667              :       LOGICAL, OPTIONAL                                  :: do_mp2
     668              : 
     669              :       CHARACTER(len=*), PARAMETER :: routineN = 'scf_post_calculation_gpw', &
     670              :          warning_cube_kpoint = "Print MO cubes not implemented for k-point calculations", &
     671              :          warning_openpmd_kpoint = "Writing to openPMD not implemented for k-point calculations"
     672              : 
     673              :       INTEGER                                            :: handle, homo, ispin, min_lumos, n_rep, &
     674              :                                                             nchk_nmoloc, nhomo, nlumo, nlumo_stm, &
     675              :                                                             nlumos, nmo, nspins, output_unit, &
     676              :                                                             unit_nr
     677        12331 :       INTEGER, DIMENSION(:, :, :), POINTER               :: marked_states
     678              :       LOGICAL :: check_write, compute_lumos, do_homo, do_kpoints, do_mixed, do_stm, &
     679              :          do_wannier_cubes, has_homo, has_lumo, loc_explicit, loc_print_explicit, my_do_mp2, &
     680              :          my_localized_wfn, p_loc, p_loc_homo, p_loc_lumo, p_loc_mixed
     681              :       REAL(dp)                                           :: e_kin
     682              :       REAL(KIND=dp)                                      :: gap, homo_lumo(2, 2), total_zeff_corr
     683        12331 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: mo_eigenvalues
     684              :       TYPE(admm_type), POINTER                           :: admm_env
     685        12331 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     686        12331 :       TYPE(cp_1d_r_p_type), DIMENSION(:), POINTER        :: mixed_evals, occupied_evals, &
     687        12331 :                                                             unoccupied_evals, unoccupied_evals_stm
     688        12331 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: mixed_orbs, occupied_orbs
     689              :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:), &
     690        12331 :          TARGET                                          :: homo_localized, lumo_localized, &
     691        12331 :                                                             mixed_localized
     692        12331 :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: lumo_ptr, mo_loc_history, &
     693        12331 :                                                             unoccupied_orbs, unoccupied_orbs_stm
     694              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
     695              :       TYPE(cp_logger_type), POINTER                      :: logger
     696              :       TYPE(cp_section_key)                               :: mo_section
     697        12331 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_rmpv, matrix_p_mp2, matrix_s, &
     698        12331 :                                                             mo_derivs
     699        12331 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: kinetic_m, rho_ao
     700              :       TYPE(dft_control_type), POINTER                    :: dft_control
     701        12331 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     702        12331 :       TYPE(molecule_type), POINTER                       :: molecule_set(:)
     703              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     704              :       TYPE(particle_list_type), POINTER                  :: particles
     705        12331 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     706              :       TYPE(pw_c1d_gs_type)                               :: wf_g
     707              :       TYPE(pw_env_type), POINTER                         :: pw_env
     708        12331 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
     709              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
     710              :       TYPE(pw_r3d_rs_type)                               :: wf_r
     711        12331 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     712              :       TYPE(qs_loc_env_type), POINTER                     :: qs_loc_env_homo, qs_loc_env_lumo, &
     713              :                                                             qs_loc_env_mixed
     714              :       TYPE(qs_rho_type), POINTER                         :: rho
     715              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     716              :       TYPE(qs_subsys_type), POINTER                      :: subsys
     717              :       TYPE(rtp_control_type), POINTER                    :: rtp_control
     718              :       TYPE(scf_control_type), POINTER                    :: scf_control
     719              :       TYPE(section_vals_type), POINTER                   :: dft_section, input, loc_print_section, &
     720              :                                                             localize_section, print_key, &
     721              :                                                             stm_section
     722              : 
     723        12331 :       CALL timeset(routineN, handle)
     724              : 
     725        12331 :       logger => cp_get_default_logger()
     726        12331 :       output_unit = cp_logger_get_default_io_unit(logger)
     727              : 
     728              :       ! Print out the type of wavefunction to distinguish between SCF and post-SCF
     729        12331 :       my_do_mp2 = .FALSE.
     730        12331 :       IF (PRESENT(do_mp2)) my_do_mp2 = do_mp2
     731        12331 :       IF (PRESENT(wf_type)) THEN
     732          328 :          IF (output_unit > 0) THEN
     733          164 :             WRITE (UNIT=output_unit, FMT='(/,(T1,A))') REPEAT("-", 40)
     734          164 :             WRITE (UNIT=output_unit, FMT='(/,(T3,A,T19,A,T25,A))') "Properties from ", wf_type, " density"
     735          164 :             WRITE (UNIT=output_unit, FMT='(/,(T1,A))') REPEAT("-", 40)
     736              :          END IF
     737              :       END IF
     738              : 
     739              :       ! Writes the data that is already available in qs_env
     740        12331 :       CALL get_qs_env(qs_env, scf_env=scf_env)
     741              : 
     742        12331 :       my_localized_wfn = .FALSE.
     743        12331 :       NULLIFY (admm_env, dft_control, pw_env, auxbas_pw_pool, pw_pools, mos, rho, &
     744        12331 :                mo_coeff, ks_rmpv, matrix_s, qs_loc_env_homo, qs_loc_env_lumo, scf_control, &
     745        12331 :                unoccupied_orbs, mo_eigenvalues, unoccupied_evals, &
     746        12331 :                unoccupied_evals_stm, molecule_set, mo_derivs, &
     747        12331 :                subsys, particles, input, print_key, kinetic_m, marked_states, &
     748        12331 :                mixed_evals, qs_loc_env_mixed)
     749        12331 :       NULLIFY (lumo_ptr, rho_ao)
     750              : 
     751        12331 :       has_homo = .FALSE.
     752        12331 :       has_lumo = .FALSE.
     753        12331 :       p_loc = .FALSE.
     754        12331 :       p_loc_homo = .FALSE.
     755        12331 :       p_loc_lumo = .FALSE.
     756        12331 :       p_loc_mixed = .FALSE.
     757              : 
     758        12331 :       CPASSERT(ASSOCIATED(scf_env))
     759        12331 :       CPASSERT(ASSOCIATED(qs_env))
     760              :       ! Here we start with data that needs a postprocessing...
     761              :       CALL get_qs_env(qs_env, &
     762              :                       dft_control=dft_control, &
     763              :                       molecule_set=molecule_set, &
     764              :                       scf_control=scf_control, &
     765              :                       do_kpoints=do_kpoints, &
     766              :                       input=input, &
     767              :                       subsys=subsys, &
     768              :                       rho=rho, &
     769              :                       pw_env=pw_env, &
     770              :                       particle_set=particle_set, &
     771              :                       atomic_kind_set=atomic_kind_set, &
     772        12331 :                       qs_kind_set=qs_kind_set)
     773        12331 :       rtp_control => dft_control%rtp_control
     774        12331 :       CALL qs_subsys_get(subsys, particles=particles)
     775              : 
     776        12331 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao)
     777              : 
     778        12331 :       IF (my_do_mp2) THEN
     779              :          ! Get the HF+MP2 density
     780          322 :          CALL get_qs_env(qs_env, matrix_p_mp2=matrix_p_mp2)
     781          742 :          DO ispin = 1, dft_control%nspins
     782          742 :             CALL dbcsr_add(rho_ao(ispin, 1)%matrix, matrix_p_mp2(ispin)%matrix, 1.0_dp, 1.0_dp)
     783              :          END DO
     784          322 :          CALL qs_rho_update_rho(rho, qs_env=qs_env)
     785          322 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
     786              :          ! In MP2 case update the Hartree potential
     787          322 :          CALL update_hartree_with_mp2(rho, qs_env)
     788              :       END IF
     789              : 
     790        12331 :       CALL write_available_results(qs_env, scf_env)
     791              : 
     792              :       !    **** the kinetic energy
     793        12331 :       IF (cp_print_key_should_output(logger%iter_info, input, &
     794              :                                      "DFT%PRINT%KINETIC_ENERGY") /= 0) THEN
     795           80 :          CALL get_qs_env(qs_env, kinetic_kp=kinetic_m)
     796           80 :          CPASSERT(ASSOCIATED(kinetic_m))
     797           80 :          CPASSERT(ASSOCIATED(kinetic_m(1, 1)%matrix))
     798           80 :          CALL calculate_ptrace(kinetic_m, rho_ao, e_kin, dft_control%nspins)
     799              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%KINETIC_ENERGY", &
     800           80 :                                         extension=".Log")
     801           80 :          IF (unit_nr > 0) THEN
     802           40 :             WRITE (unit_nr, '(T3,A,T55,F25.14)') "Electronic kinetic energy:", e_kin
     803              :          END IF
     804              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
     805           80 :                                            "DFT%PRINT%KINETIC_ENERGY")
     806              :       END IF
     807              : 
     808              :       ! Atomic Charges that require further computation
     809        12331 :       CALL qs_scf_post_charges(input, logger, qs_env)
     810              : 
     811              :       ! Moments of charge distribution
     812        12331 :       CALL qs_scf_post_moments(input, logger, qs_env, output_unit)
     813              : 
     814        12331 :       CALL qs_scf_post_fod(input, logger, qs_env, output_unit)
     815              : 
     816              :       ! Determine if we need to computer properties using the localized centers
     817        12331 :       dft_section => section_vals_get_subs_vals(input, "DFT")
     818        12331 :       localize_section => section_vals_get_subs_vals(dft_section, "LOCALIZE")
     819        12331 :       loc_print_section => section_vals_get_subs_vals(localize_section, "PRINT")
     820        12331 :       CALL section_vals_get(localize_section, explicit=loc_explicit)
     821        12331 :       CALL section_vals_get(loc_print_section, explicit=loc_print_explicit)
     822              : 
     823              :       ! Print_keys controlled by localization
     824        12331 :       IF (loc_print_explicit) THEN
     825          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "MOLECULAR_DIPOLES")
     826          100 :          p_loc = BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     827          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "TOTAL_DIPOLE")
     828          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     829          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_CENTERS")
     830          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     831          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_SPREADS")
     832          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     833          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_CUBES")
     834          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     835          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "MOLECULAR_STATES")
     836          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     837          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "MOLECULAR_MOMENTS")
     838          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     839          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "LOCALIZED_MOMENTS")
     840          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     841          100 :          print_key => section_vals_get_subs_vals(loc_print_section, "WANNIER_STATES")
     842          100 :          p_loc = p_loc .OR. BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)
     843              :       ELSE
     844              :          p_loc = .FALSE.
     845              :       END IF
     846        12331 :       IF (loc_explicit) THEN
     847              :          p_loc_homo = (section_get_ival(localize_section, "STATES") == do_loc_homo .OR. &
     848          100 :                        section_get_ival(localize_section, "STATES") == do_loc_both) .AND. p_loc
     849              :          p_loc_lumo = (section_get_ival(localize_section, "STATES") == do_loc_lumo .OR. &
     850          100 :                        section_get_ival(localize_section, "STATES") == do_loc_both) .AND. p_loc
     851          100 :          p_loc_mixed = (section_get_ival(localize_section, "STATES") == do_loc_mixed) .AND. p_loc
     852          100 :          CALL section_vals_val_get(localize_section, "LIST_UNOCCUPIED", n_rep_val=n_rep)
     853              :       ELSE
     854        12231 :          p_loc_homo = .FALSE.
     855        12231 :          p_loc_lumo = .FALSE.
     856        12231 :          p_loc_mixed = .FALSE.
     857        12231 :          n_rep = 0
     858              :       END IF
     859              : 
     860        12331 :       IF (n_rep == 0 .AND. p_loc_lumo) THEN
     861              :          CALL cp_abort(__LOCATION__, "No LIST_UNOCCUPIED was specified, "// &
     862            0 :                        "therefore localization of unoccupied states will be skipped!")
     863            0 :          p_loc_lumo = .FALSE.
     864              :       END IF
     865              : 
     866              :       ! Control for STM
     867        12331 :       stm_section => section_vals_get_subs_vals(input, "DFT%PRINT%STM")
     868        12331 :       CALL section_vals_get(stm_section, explicit=do_stm)
     869        12331 :       nlumo_stm = 0
     870        12331 :       IF (do_stm) nlumo_stm = section_get_ival(stm_section, "NLUMO")
     871              : 
     872              :       ! check for CUBES or openPMD (MOs and WANNIERS)
     873        12331 :       mo_section = cube_or_openpmd(input, str_mo_cubes, str_mo_openpmd, logger)
     874              : 
     875        12331 :       IF (loc_print_explicit) THEN
     876              :          do_wannier_cubes = BTEST(cp_print_key_should_output(logger%iter_info, loc_print_section, &
     877          100 :                                                              "WANNIER_CUBES"), cp_p_file)
     878              :       ELSE
     879              :          do_wannier_cubes = .FALSE.
     880              :       END IF
     881        12331 :       nlumo = section_get_ival(dft_section, mo_section%concat_to_relative("%NLUMO"))
     882        12331 :       nhomo = section_get_ival(dft_section, mo_section%concat_to_relative("%NHOMO"))
     883              : 
     884              :       ! Setup the grids needed to compute a wavefunction given a vector..
     885        12331 :       IF (((mo_section%do_output .OR. do_wannier_cubes) .AND. (nlumo /= 0 .OR. nhomo /= 0)) .OR. p_loc) THEN
     886              :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
     887          216 :                          pw_pools=pw_pools)
     888          216 :          CALL auxbas_pw_pool%create_pw(wf_r)
     889          216 :          CALL auxbas_pw_pool%create_pw(wf_g)
     890              :       END IF
     891              : 
     892        12331 :       IF (dft_control%restricted) THEN
     893              :          !For ROKS useful only first term
     894           80 :          nspins = 1
     895              :       ELSE
     896        12251 :          nspins = dft_control%nspins
     897              :       END IF
     898              :       !Some info about ROKS
     899        12331 :       IF (dft_control%restricted .AND. (mo_section%do_output .OR. p_loc_homo)) THEN
     900            0 :          CALL cp_abort(__LOCATION__, "Unclear how we define MOs / localization in the restricted case ... ")
     901              :          ! It is possible to obtain Wannier centers for ROKS without rotations for SINGLE OCCUPIED ORBITALS
     902              :       END IF
     903              :       ! Makes the MOs eigenstates, computes eigenvalues, write cubes
     904        12331 :       IF (do_kpoints) THEN
     905          692 :          CPWARN_IF(mo_section%do_cubes(), warning_cube_kpoint)
     906          692 :          CPWARN_IF(mo_section%do_openpmd(), warning_openpmd_kpoint)
     907              :       ELSE
     908              :          CALL get_qs_env(qs_env, &
     909              :                          mos=mos, &
     910        11639 :                          matrix_ks=ks_rmpv)
     911        11639 :          IF ((mo_section%do_output .AND. nhomo /= 0) .OR. do_stm) THEN
     912          136 :             CALL get_qs_env(qs_env, mo_derivs=mo_derivs)
     913          136 :             IF (dft_control%do_admm) THEN
     914            0 :                CALL get_qs_env(qs_env, admm_env=admm_env)
     915            0 :                CALL make_mo_eig(mos, nspins, ks_rmpv, scf_control, mo_derivs, admm_env=admm_env)
     916              :             ELSE
     917          136 :                IF (dft_control%hairy_probes) THEN
     918            0 :                   scf_control%smear%do_smear = .FALSE.
     919              :                   CALL make_mo_eig(mos, dft_control%nspins, ks_rmpv, scf_control, mo_derivs, &
     920              :                                    hairy_probes=dft_control%hairy_probes, &
     921            0 :                                    probe=dft_control%probe)
     922              :                ELSE
     923          136 :                   CALL make_mo_eig(mos, dft_control%nspins, ks_rmpv, scf_control, mo_derivs)
     924              :                END IF
     925              :             END IF
     926          292 :             DO ispin = 1, dft_control%nspins
     927          156 :                CALL get_mo_set(mo_set=mos(ispin), eigenvalues=mo_eigenvalues, homo=homo)
     928          292 :                homo_lumo(ispin, 1) = mo_eigenvalues(homo)
     929              :             END DO
     930              :             has_homo = .TRUE.
     931              :          END IF
     932        11639 :          IF (mo_section%do_output .AND. nhomo /= 0) THEN
     933          278 :             DO ispin = 1, nspins
     934              :                ! Prints the cube files of OCCUPIED ORBITALS
     935              :                CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
     936          148 :                                eigenvalues=mo_eigenvalues, homo=homo, nmo=nmo)
     937              :                CALL qs_scf_post_occ_cubes(input, dft_section, dft_control, logger, qs_env, &
     938          278 :                                           mo_coeff, wf_g, wf_r, particles, homo, ispin, mo_section)
     939              :             END DO
     940              :          END IF
     941              :       END IF
     942              : 
     943              :       ! Initialize the localization environment, needed e.g. for wannier functions and molecular states
     944              :       ! Gets localization info for the occupied orbs
     945              :       !  - Possibly gets wannier functions
     946              :       !  - Possibly gets molecular states
     947        12331 :       IF (p_loc_homo) THEN
     948           94 :          IF (do_kpoints) THEN
     949            0 :             CPWARN("Localization not implemented for k-point calculations!")
     950              :          ELSE IF (dft_control%restricted &
     951              :                   .AND. (section_get_ival(localize_section, "METHOD") /= do_loc_none) &
     952           94 :                   .AND. (section_get_ival(localize_section, "METHOD") /= do_loc_jacobi)) THEN
     953            0 :             CPABORT("ROKS works only with LOCALIZE METHOD NONE or JACOBI")
     954              :          ELSE
     955          392 :             ALLOCATE (occupied_orbs(dft_control%nspins))
     956          392 :             ALLOCATE (occupied_evals(dft_control%nspins))
     957          392 :             ALLOCATE (homo_localized(dft_control%nspins))
     958          204 :             DO ispin = 1, dft_control%nspins
     959              :                CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
     960          110 :                                eigenvalues=mo_eigenvalues)
     961          110 :                occupied_orbs(ispin) = mo_coeff
     962          110 :                occupied_evals(ispin)%array => mo_eigenvalues
     963          110 :                CALL cp_fm_create(homo_localized(ispin), occupied_orbs(ispin)%matrix_struct)
     964          204 :                CALL cp_fm_to_fm(occupied_orbs(ispin), homo_localized(ispin))
     965              :             END DO
     966              : 
     967           94 :             CALL get_qs_env(qs_env, mo_loc_history=mo_loc_history)
     968           94 :             do_homo = .TRUE.
     969              : 
     970          752 :             ALLOCATE (qs_loc_env_homo)
     971           94 :             CALL qs_loc_env_create(qs_loc_env_homo)
     972           94 :             CALL qs_loc_control_init(qs_loc_env_homo, localize_section, do_homo=do_homo)
     973              :             CALL qs_loc_init(qs_env, qs_loc_env_homo, localize_section, homo_localized, do_homo, &
     974           94 :                              mo_section%do_output, mo_loc_history=mo_loc_history)
     975              :             CALL get_localization_info(qs_env, qs_loc_env_homo, localize_section, homo_localized, &
     976           94 :                                        wf_r, wf_g, particles, occupied_orbs, occupied_evals, marked_states)
     977              : 
     978              :             !retain the homo_localized for future use
     979           94 :             IF (qs_loc_env_homo%localized_wfn_control%use_history) THEN
     980           10 :                CALL retain_history(mo_loc_history, homo_localized)
     981           10 :                CALL set_qs_env(qs_env, mo_loc_history=mo_loc_history)
     982              :             END IF
     983              : 
     984              :             !write restart for localization of occupied orbitals
     985              :             CALL loc_write_restart(qs_loc_env_homo, loc_print_section, mos, &
     986           94 :                                    homo_localized, do_homo)
     987           94 :             CALL cp_fm_release(homo_localized)
     988           94 :             DEALLOCATE (occupied_orbs)
     989           94 :             DEALLOCATE (occupied_evals)
     990              :             ! Print Total Dipole if the localization has been performed
     991          188 :             IF (qs_loc_env_homo%do_localize) THEN
     992           78 :                CALL loc_dipole(input, dft_control, qs_loc_env_homo, logger, qs_env)
     993              :             END IF
     994              :          END IF
     995              :       END IF
     996              : 
     997              :       ! Gets the lumos, and eigenvalues for the lumos, and localize them if requested
     998        12331 :       IF (do_kpoints) THEN
     999          692 :          IF (mo_section%do_output .OR. p_loc_lumo) THEN
    1000              :             ! nothing at the moment, not implemented
    1001            2 :             CPWARN("Localization and MO related output not implemented for k-point calculations!")
    1002              :          END IF
    1003              :       ELSE
    1004        11639 :          compute_lumos = mo_section%do_output .AND. nlumo /= 0
    1005        11639 :          compute_lumos = compute_lumos .OR. p_loc_lumo
    1006              : 
    1007        25680 :          DO ispin = 1, dft_control%nspins
    1008        14041 :             CALL get_mo_set(mo_set=mos(ispin), homo=homo, nmo=nmo)
    1009        39673 :             compute_lumos = compute_lumos .AND. homo == nmo
    1010              :          END DO
    1011              : 
    1012        11639 :          IF (mo_section%do_output .AND. .NOT. compute_lumos) THEN
    1013              : 
    1014           98 :             nlumo = section_get_ival(dft_section, mo_section%concat_to_relative("%NLUMO"))
    1015          198 :             DO ispin = 1, dft_control%nspins
    1016              : 
    1017          100 :                CALL get_mo_set(mo_set=mos(ispin), homo=homo, nmo=nmo, eigenvalues=mo_eigenvalues)
    1018          198 :                IF (nlumo > nmo - homo) THEN
    1019              :                   ! this case not yet implemented
    1020              :                ELSE
    1021          100 :                   IF (nlumo == -1) THEN
    1022            0 :                      nlumo = nmo - homo
    1023              :                   END IF
    1024          100 :                   IF (output_unit > 0) WRITE (output_unit, *) " "
    1025          100 :                   IF (output_unit > 0) WRITE (output_unit, *) " Lowest eigenvalues of the unoccupied subspace spin ", ispin
    1026          100 :                   IF (output_unit > 0) WRITE (output_unit, *) "---------------------------------------------"
    1027          107 :                   IF (output_unit > 0) WRITE (output_unit, '(4(1X,1F16.8))') mo_eigenvalues(homo + 1:homo + nlumo)
    1028              : 
    1029              :                   ! Prints the cube files of UNOCCUPIED ORBITALS
    1030          100 :                   CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff)
    1031              :                   CALL qs_scf_post_unocc_cubes(input, dft_section, dft_control, logger, qs_env, &
    1032          100 :                                           mo_coeff, wf_g, wf_r, particles, nlumo, homo, ispin, lumo=homo + 1, mo_section=mo_section)
    1033              :                END IF
    1034              :             END DO
    1035              : 
    1036              :          END IF
    1037              : 
    1038        11607 :          IF (compute_lumos) THEN
    1039           32 :             check_write = .TRUE.
    1040           32 :             min_lumos = nlumo
    1041           32 :             IF (nlumo == 0) check_write = .FALSE.
    1042           32 :             IF (p_loc_lumo) THEN
    1043            6 :                do_homo = .FALSE.
    1044           48 :                ALLOCATE (qs_loc_env_lumo)
    1045            6 :                CALL qs_loc_env_create(qs_loc_env_lumo)
    1046            6 :                CALL qs_loc_control_init(qs_loc_env_lumo, localize_section, do_homo=do_homo)
    1047           98 :                min_lumos = MAX(MAXVAL(qs_loc_env_lumo%localized_wfn_control%loc_states(:, :)), nlumo)
    1048              :             END IF
    1049              : 
    1050          144 :             ALLOCATE (unoccupied_orbs(dft_control%nspins))
    1051          144 :             ALLOCATE (unoccupied_evals(dft_control%nspins))
    1052           32 :             CALL make_lumo_gpw(qs_env, scf_env, unoccupied_orbs, unoccupied_evals, min_lumos, nlumos)
    1053           32 :             lumo_ptr => unoccupied_orbs
    1054           80 :             DO ispin = 1, dft_control%nspins
    1055           48 :                has_lumo = .TRUE.
    1056           48 :                homo_lumo(ispin, 2) = unoccupied_evals(ispin)%array(1)
    1057           48 :                CALL get_mo_set(mo_set=mos(ispin), homo=homo)
    1058           80 :                IF (check_write) THEN
    1059           48 :                   IF (p_loc_lumo .AND. nlumo /= -1) nlumos = MIN(nlumo, nlumos)
    1060              :                   ! Prints the cube files of UNOCCUPIED ORBITALS
    1061              :                   CALL qs_scf_post_unocc_cubes(input, dft_section, dft_control, logger, qs_env, &
    1062           48 :                                           unoccupied_orbs(ispin), wf_g, wf_r, particles, nlumos, homo, ispin, mo_section=mo_section)
    1063              :                END IF
    1064              :             END DO
    1065              : 
    1066           64 :             IF (p_loc_lumo) THEN
    1067           30 :                ALLOCATE (lumo_localized(dft_control%nspins))
    1068           18 :                DO ispin = 1, dft_control%nspins
    1069           12 :                   CALL cp_fm_create(lumo_localized(ispin), unoccupied_orbs(ispin)%matrix_struct)
    1070           18 :                   CALL cp_fm_to_fm(unoccupied_orbs(ispin), lumo_localized(ispin))
    1071              :                END DO
    1072              :                CALL qs_loc_init(qs_env, qs_loc_env_lumo, localize_section, lumo_localized, do_homo, mo_section%do_output, &
    1073            6 :                                 evals=unoccupied_evals)
    1074              :                CALL qs_loc_env_init(qs_loc_env_lumo, qs_loc_env_lumo%localized_wfn_control, qs_env, &
    1075            6 :                                     loc_coeff=unoccupied_orbs)
    1076              :                CALL get_localization_info(qs_env, qs_loc_env_lumo, localize_section, &
    1077              :                                           lumo_localized, wf_r, wf_g, particles, &
    1078            6 :                                           unoccupied_orbs, unoccupied_evals, marked_states)
    1079              :                CALL loc_write_restart(qs_loc_env_lumo, loc_print_section, mos, homo_localized, do_homo, &
    1080            6 :                                       evals=unoccupied_evals)
    1081            6 :                lumo_ptr => lumo_localized
    1082              :             END IF
    1083              :          END IF
    1084              : 
    1085           32 :          IF (has_homo .AND. has_lumo) THEN
    1086           32 :             IF (output_unit > 0) WRITE (output_unit, *) " "
    1087           80 :             DO ispin = 1, dft_control%nspins
    1088           80 :                IF (.NOT. scf_control%smear%do_smear) THEN
    1089           48 :                   gap = homo_lumo(ispin, 2) - homo_lumo(ispin, 1)
    1090           48 :                   IF (output_unit > 0) WRITE (output_unit, '(T2,A,F12.6)') &
    1091           24 :                      "HOMO - LUMO gap [eV] :", gap*evolt
    1092              :                END IF
    1093              :             END DO
    1094              :          END IF
    1095              :       END IF
    1096              : 
    1097        12331 :       IF (p_loc_mixed) THEN
    1098            2 :          IF (do_kpoints) THEN
    1099            0 :             CPWARN("Localization not implemented for k-point calculations!")
    1100            2 :          ELSE IF (dft_control%restricted) THEN
    1101            0 :             IF (output_unit > 0) WRITE (output_unit, *) &
    1102            0 :                " Unclear how we define MOs / localization in the restricted case... skipping"
    1103              :          ELSE
    1104              : 
    1105            8 :             ALLOCATE (mixed_orbs(dft_control%nspins))
    1106            8 :             ALLOCATE (mixed_evals(dft_control%nspins))
    1107            8 :             ALLOCATE (mixed_localized(dft_control%nspins))
    1108            4 :             DO ispin = 1, dft_control%nspins
    1109              :                CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
    1110            2 :                                eigenvalues=mo_eigenvalues)
    1111            2 :                mixed_orbs(ispin) = mo_coeff
    1112            2 :                mixed_evals(ispin)%array => mo_eigenvalues
    1113            2 :                CALL cp_fm_create(mixed_localized(ispin), mixed_orbs(ispin)%matrix_struct)
    1114            4 :                CALL cp_fm_to_fm(mixed_orbs(ispin), mixed_localized(ispin))
    1115              :             END DO
    1116              : 
    1117            2 :             CALL get_qs_env(qs_env, mo_loc_history=mo_loc_history)
    1118            2 :             do_homo = .FALSE.
    1119            2 :             do_mixed = .TRUE.
    1120            2 :             total_zeff_corr = scf_env%sum_zeff_corr
    1121           16 :             ALLOCATE (qs_loc_env_mixed)
    1122            2 :             CALL qs_loc_env_create(qs_loc_env_mixed)
    1123            2 :             CALL qs_loc_control_init(qs_loc_env_mixed, localize_section, do_homo=do_homo, do_mixed=do_mixed)
    1124              :             CALL qs_loc_init(qs_env, qs_loc_env_mixed, localize_section, mixed_localized, do_homo, &
    1125              :                              mo_section%do_output, mo_loc_history=mo_loc_history, tot_zeff_corr=total_zeff_corr, &
    1126            2 :                              do_mixed=do_mixed)
    1127              : 
    1128            4 :             DO ispin = 1, dft_control%nspins
    1129            4 :                CALL cp_fm_get_info(mixed_localized(ispin), ncol_global=nchk_nmoloc)
    1130              :             END DO
    1131              : 
    1132              :             CALL get_localization_info(qs_env, qs_loc_env_mixed, localize_section, mixed_localized, &
    1133            2 :                                        wf_r, wf_g, particles, mixed_orbs, mixed_evals, marked_states)
    1134              : 
    1135              :             !retain the homo_localized for future use
    1136            2 :             IF (qs_loc_env_mixed%localized_wfn_control%use_history) THEN
    1137            0 :                CALL retain_history(mo_loc_history, mixed_localized)
    1138            0 :                CALL set_qs_env(qs_env, mo_loc_history=mo_loc_history)
    1139              :             END IF
    1140              : 
    1141              :             !write restart for localization of occupied orbitals
    1142              :             CALL loc_write_restart(qs_loc_env_mixed, loc_print_section, mos, &
    1143            2 :                                    mixed_localized, do_homo, do_mixed=do_mixed)
    1144            2 :             CALL cp_fm_release(mixed_localized)
    1145            2 :             DEALLOCATE (mixed_orbs)
    1146            4 :             DEALLOCATE (mixed_evals)
    1147              :          END IF
    1148              :       END IF
    1149              : 
    1150              :       ! Deallocate grids needed to compute wavefunctions
    1151        12331 :       IF (((mo_section%do_output .OR. do_wannier_cubes) .AND. (nlumo /= 0 .OR. nhomo /= 0)) .OR. p_loc) THEN
    1152          216 :          CALL auxbas_pw_pool%give_back_pw(wf_r)
    1153          216 :          CALL auxbas_pw_pool%give_back_pw(wf_g)
    1154              :       END IF
    1155              : 
    1156              :       ! Destroy the localization environment
    1157        12331 :       IF (.NOT. do_kpoints) THEN
    1158        11639 :          IF (p_loc_homo) THEN
    1159           94 :             CALL qs_loc_env_release(qs_loc_env_homo)
    1160           94 :             DEALLOCATE (qs_loc_env_homo)
    1161              :          END IF
    1162        11639 :          IF (p_loc_lumo) THEN
    1163            6 :             CALL qs_loc_env_release(qs_loc_env_lumo)
    1164            6 :             DEALLOCATE (qs_loc_env_lumo)
    1165              :          END IF
    1166        11639 :          IF (p_loc_mixed) THEN
    1167            2 :             CALL qs_loc_env_release(qs_loc_env_mixed)
    1168            2 :             DEALLOCATE (qs_loc_env_mixed)
    1169              :          END IF
    1170              :       END IF
    1171              : 
    1172              :       ! generate a mix of wfns, and write to a restart
    1173        12331 :       IF (do_kpoints) THEN
    1174              :          ! nothing at the moment, not implemented
    1175              :       ELSE
    1176        11639 :          CALL get_qs_env(qs_env, matrix_s=matrix_s, para_env=para_env)
    1177              :          CALL wfn_mix(mos, particle_set, dft_section, qs_kind_set, para_env, &
    1178              :                       output_unit, unoccupied_orbs=lumo_ptr, scf_env=scf_env, &
    1179        11639 :                       matrix_s=matrix_s, marked_states=marked_states)
    1180              : 
    1181        11639 :          IF (p_loc_lumo) CALL cp_fm_release(lumo_localized)
    1182              :       END IF
    1183        12331 :       IF (ASSOCIATED(marked_states)) THEN
    1184           16 :          DEALLOCATE (marked_states)
    1185              :       END IF
    1186              : 
    1187              :       ! This is just a deallocation for printing MO_CUBES or TDDFPT
    1188        12331 :       IF (.NOT. do_kpoints) THEN
    1189        11639 :          IF (compute_lumos) THEN
    1190           80 :             DO ispin = 1, dft_control%nspins
    1191           48 :                DEALLOCATE (unoccupied_evals(ispin)%array)
    1192           80 :                CALL cp_fm_release(unoccupied_orbs(ispin))
    1193              :             END DO
    1194           32 :             DEALLOCATE (unoccupied_evals)
    1195           32 :             DEALLOCATE (unoccupied_orbs)
    1196              :          END IF
    1197              :       END IF
    1198              : 
    1199              :       !stm images
    1200        12331 :       IF (do_stm) THEN
    1201            6 :          IF (do_kpoints) THEN
    1202            0 :             CPWARN("STM not implemented for k-point calculations!")
    1203              :          ELSE
    1204            6 :             NULLIFY (unoccupied_orbs_stm, unoccupied_evals_stm)
    1205            6 :             IF (nlumo_stm > 0) THEN
    1206            8 :                ALLOCATE (unoccupied_orbs_stm(dft_control%nspins))
    1207            8 :                ALLOCATE (unoccupied_evals_stm(dft_control%nspins))
    1208              :                CALL make_lumo_gpw(qs_env, scf_env, unoccupied_orbs_stm, unoccupied_evals_stm, &
    1209            2 :                                   nlumo_stm, nlumos)
    1210              :             END IF
    1211              : 
    1212              :             CALL th_stm_image(qs_env, stm_section, particles, unoccupied_orbs_stm, &
    1213            6 :                               unoccupied_evals_stm)
    1214              : 
    1215            6 :             IF (nlumo_stm > 0) THEN
    1216            4 :                DO ispin = 1, dft_control%nspins
    1217            4 :                   DEALLOCATE (unoccupied_evals_stm(ispin)%array)
    1218              :                END DO
    1219            2 :                DEALLOCATE (unoccupied_evals_stm)
    1220            2 :                CALL cp_fm_release(unoccupied_orbs_stm)
    1221              :             END IF
    1222              :          END IF
    1223              :       END IF
    1224              : 
    1225              :       ! Print coherent X-ray diffraction spectrum
    1226        12331 :       CALL qs_scf_post_xray(input, dft_section, logger, qs_env, output_unit)
    1227              : 
    1228              :       ! Calculation of Electric Field Gradients
    1229        12331 :       CALL qs_scf_post_efg(input, logger, qs_env)
    1230              : 
    1231              :       ! Calculation of ET
    1232        12331 :       CALL qs_scf_post_et(input, qs_env, dft_control)
    1233              : 
    1234              :       ! Calculation of EPR Hyperfine Coupling Tensors
    1235        12331 :       CALL qs_scf_post_epr(input, logger, qs_env)
    1236              : 
    1237              :       ! Calculation of properties needed for BASIS_MOLOPT optimizations
    1238        12331 :       CALL qs_scf_post_molopt(input, logger, qs_env)
    1239              : 
    1240              :       ! Calculate ELF
    1241        12331 :       CALL qs_scf_post_elf(input, logger, qs_env)
    1242              : 
    1243              :       ! Use Wannier90 interface
    1244        12331 :       CALL wannier90_interface(input, logger, qs_env)
    1245              : 
    1246        12331 :       IF (my_do_mp2) THEN
    1247              :          ! Get everything back
    1248          742 :          DO ispin = 1, dft_control%nspins
    1249          742 :             CALL dbcsr_add(rho_ao(ispin, 1)%matrix, matrix_p_mp2(ispin)%matrix, 1.0_dp, -1.0_dp)
    1250              :          END DO
    1251          322 :          CALL qs_rho_update_rho(rho, qs_env=qs_env)
    1252          322 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    1253              :       END IF
    1254              : 
    1255        12331 :       CALL cp_openpmd_close_iterations()
    1256              : 
    1257        12331 :       CALL timestop(handle)
    1258              : 
    1259        24662 :    END SUBROUTINE scf_post_calculation_gpw
    1260              : 
    1261              : ! **************************************************************************************************
    1262              : !> \brief Gets the LUMOs and their eigenvalues for all spin channels.
    1263              : !> \param qs_env ...
    1264              : !> \param scf_env ...
    1265              : !> \param unoccupied_orbs ...
    1266              : !> \param unoccupied_evals ...
    1267              : !> \param nlumo ...
    1268              : !> \param nlumos ...
    1269              : ! **************************************************************************************************
    1270           36 :    SUBROUTINE make_lumo_gpw(qs_env, scf_env, unoccupied_orbs, unoccupied_evals, nlumo, nlumos)
    1271              : 
    1272              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1273              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1274              :       TYPE(cp_fm_type), DIMENSION(:), INTENT(INOUT)      :: unoccupied_orbs
    1275              :       TYPE(cp_1d_r_p_type), DIMENSION(:), POINTER        :: unoccupied_evals
    1276              :       INTEGER, INTENT(IN)                                :: nlumo
    1277              :       INTEGER, INTENT(OUT)                               :: nlumos
    1278              : 
    1279              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'make_lumo_gpw'
    1280              : 
    1281              :       INTEGER                                            :: handle, homo, ispin, n, nao, nmo, &
    1282              :                                                             output_unit
    1283              :       TYPE(admm_type), POINTER                           :: admm_env
    1284              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
    1285              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct_tmp
    1286              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1287              :       TYPE(cp_logger_type), POINTER                      :: logger
    1288           36 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_rmpv, matrix_s
    1289              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1290           36 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1291              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1292              :       TYPE(preconditioner_type), POINTER                 :: local_preconditioner
    1293              :       TYPE(scf_control_type), POINTER                    :: scf_control
    1294              : 
    1295           36 :       CALL timeset(routineN, handle)
    1296              : 
    1297           36 :       NULLIFY (ks_rmpv, matrix_s, scf_control, dft_control, admm_env, para_env, blacs_env, mos)
    1298              :       CALL get_qs_env(qs_env, &
    1299              :                       matrix_ks=ks_rmpv, &
    1300              :                       matrix_s=matrix_s, &
    1301              :                       scf_control=scf_control, &
    1302              :                       dft_control=dft_control, &
    1303              :                       admm_env=admm_env, &
    1304              :                       para_env=para_env, &
    1305              :                       blacs_env=blacs_env, &
    1306           36 :                       mos=mos)
    1307              : 
    1308           36 :       logger => cp_get_default_logger()
    1309           36 :       output_unit = cp_logger_get_default_io_unit(logger)
    1310              : 
    1311           88 :       DO ispin = 1, dft_control%nspins
    1312           52 :          NULLIFY (unoccupied_evals(ispin)%array)
    1313           52 :          IF (output_unit > 0) WRITE (output_unit, *) " "
    1314           52 :          IF (output_unit > 0) WRITE (output_unit, *) &
    1315           26 :             " Using OT eigensolver for additional unoccupied orbitals spin ", ispin
    1316           52 :          IF (output_unit > 0) WRITE (output_unit, *) &
    1317           26 :             " Lowest Eigenvalues of the unoccupied subspace spin ", ispin
    1318           52 :          IF (output_unit > 0) WRITE (output_unit, FMT='(1X,A)') "-----------------------------------------------------"
    1319           52 :          CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, homo=homo, nao=nao, nmo=nmo)
    1320           52 :          CALL cp_fm_get_info(mo_coeff, nrow_global=n)
    1321           52 :          nlumos = MAX(1, MIN(nlumo, nao - nmo))
    1322           52 :          IF (nlumo == -1) nlumos = nao - nmo
    1323          156 :          ALLOCATE (unoccupied_evals(ispin)%array(nlumos))
    1324              :          CALL cp_fm_struct_create(fm_struct_tmp, para_env=para_env, context=blacs_env, &
    1325           52 :                                   nrow_global=n, ncol_global=nlumos)
    1326           52 :          CALL cp_fm_create(unoccupied_orbs(ispin), fm_struct_tmp, name="lumos")
    1327           52 :          CALL cp_fm_struct_release(fm_struct_tmp)
    1328           52 :          CALL cp_fm_init_random(unoccupied_orbs(ispin), nlumos)
    1329              : 
    1330              :          ! FULL_ALL has column-dependent occupied-state weights and cannot be reused here.
    1331           52 :          NULLIFY (local_preconditioner)
    1332           52 :          IF (ASSOCIATED(scf_env)) THEN
    1333           52 :             IF (ASSOCIATED(scf_env%ot_preconditioner)) THEN
    1334           28 :                local_preconditioner => scf_env%ot_preconditioner(1)%preconditioner
    1335           28 :                IF (local_preconditioner%in_use == ot_precond_full_all .OR. &
    1336              :                    local_preconditioner%in_use == ot_precond_full_all_covariant) THEN
    1337            4 :                   NULLIFY (local_preconditioner)
    1338              :                END IF
    1339              :             END IF
    1340              :          END IF
    1341              : 
    1342              :          ! If we do ADMM, we add have to modify the Kohn-Sham matrix
    1343           52 :          IF (dft_control%do_admm) THEN
    1344            0 :             CALL admm_correct_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
    1345              :          END IF
    1346              : 
    1347              :          CALL ot_eigensolver(matrix_h=ks_rmpv(ispin)%matrix, matrix_s=matrix_s(1)%matrix, &
    1348              :                              matrix_c_fm=unoccupied_orbs(ispin), &
    1349              :                              matrix_orthogonal_space_fm=mo_coeff, &
    1350              :                              eps_gradient=scf_control%eps_lumos, &
    1351              :                              preconditioner=local_preconditioner, &
    1352              :                              iter_max=scf_control%max_iter_lumos, &
    1353           52 :                              size_ortho_space=nmo)
    1354              : 
    1355              :          CALL calculate_subspace_eigenvalues(unoccupied_orbs(ispin), ks_rmpv(ispin)%matrix, &
    1356              :                                              unoccupied_evals(ispin)%array, scr=output_unit, &
    1357           52 :                                              ionode=output_unit > 0)
    1358              : 
    1359              :          ! If we do ADMM, we restore the original Kohn-Sham matrix
    1360          140 :          IF (dft_control%do_admm) THEN
    1361            0 :             CALL admm_uncorrect_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
    1362              :          END IF
    1363              : 
    1364              :       END DO
    1365              : 
    1366           36 :       CALL timestop(handle)
    1367              : 
    1368           36 :    END SUBROUTINE make_lumo_gpw
    1369              : 
    1370              : ! **************************************************************************************************
    1371              : !> \brief Computes and Prints Atomic Charges with several methods
    1372              : !> \param input ...
    1373              : !> \param logger ...
    1374              : !> \param qs_env the qs_env in which the qs_env lives
    1375              : ! **************************************************************************************************
    1376        12331 :    SUBROUTINE qs_scf_post_charges(input, logger, qs_env)
    1377              :       TYPE(section_vals_type), POINTER                   :: input
    1378              :       TYPE(cp_logger_type), POINTER                      :: logger
    1379              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1380              : 
    1381              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_charges'
    1382              : 
    1383              :       INTEGER                                            :: handle, print_level, unit_nr
    1384              :       LOGICAL                                            :: do_kpoints, print_it
    1385              :       TYPE(section_vals_type), POINTER                   :: density_fit_section, print_key
    1386              : 
    1387        12331 :       CALL timeset(routineN, handle)
    1388              : 
    1389        12331 :       CALL get_qs_env(qs_env=qs_env, do_kpoints=do_kpoints)
    1390              : 
    1391              :       ! Mulliken charges require no further computation and are printed from write_mo_free_results
    1392              : 
    1393              :       ! Compute the Lowdin charges
    1394        12331 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%LOWDIN")
    1395        12331 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    1396              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%LOWDIN", extension=".lowdin", &
    1397           92 :                                         log_filename=.FALSE.)
    1398           92 :          print_level = 1
    1399           92 :          CALL section_vals_val_get(print_key, "PRINT_GOP", l_val=print_it)
    1400           92 :          IF (print_it) print_level = 2
    1401           92 :          CALL section_vals_val_get(print_key, "PRINT_ALL", l_val=print_it)
    1402           92 :          IF (print_it) print_level = 3
    1403           92 :          CALL lowdin_population_analysis(qs_env, unit_nr, print_level)
    1404           92 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%LOWDIN")
    1405              :       END IF
    1406              : 
    1407              :       ! Compute the RESP charges
    1408        12331 :       CALL resp_fit(qs_env)
    1409              : 
    1410              :       ! Compute the Density Derived Atomic Point charges with the Bloechl scheme
    1411        12331 :       print_key => section_vals_get_subs_vals(input, "PROPERTIES%FIT_CHARGE")
    1412        12331 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    1413              :          unit_nr = cp_print_key_unit_nr(logger, input, "PROPERTIES%FIT_CHARGE", extension=".Fitcharge", &
    1414          102 :                                         log_filename=.FALSE.)
    1415          102 :          density_fit_section => section_vals_get_subs_vals(input, "DFT%DENSITY_FITTING")
    1416          102 :          CALL get_ddapc(qs_env, .FALSE., density_fit_section, iwc=unit_nr)
    1417          102 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "PROPERTIES%FIT_CHARGE")
    1418              :       END IF
    1419              : 
    1420        12331 :       CALL timestop(handle)
    1421              : 
    1422        12331 :    END SUBROUTINE qs_scf_post_charges
    1423              : 
    1424              : ! **************************************************************************************************
    1425              : !> \brief Computes and prints the Cube Files for MO
    1426              : !> \param input ...
    1427              : !> \param dft_section ...
    1428              : !> \param dft_control ...
    1429              : !> \param logger ...
    1430              : !> \param qs_env the qs_env in which the qs_env lives
    1431              : !> \param mo_coeff ...
    1432              : !> \param wf_g ...
    1433              : !> \param wf_r ...
    1434              : !> \param particles ...
    1435              : !> \param homo ...
    1436              : !> \param ispin ...
    1437              : !> \param mo_section ...
    1438              : ! **************************************************************************************************
    1439          148 :    SUBROUTINE qs_scf_post_occ_cubes(input, dft_section, dft_control, logger, qs_env, &
    1440              :                                     mo_coeff, wf_g, wf_r, particles, homo, ispin, mo_section)
    1441              :       TYPE(section_vals_type), POINTER                   :: input, dft_section
    1442              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1443              :       TYPE(cp_logger_type), POINTER                      :: logger
    1444              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1445              :       TYPE(cp_fm_type), INTENT(IN)                       :: mo_coeff
    1446              :       TYPE(pw_c1d_gs_type), INTENT(INOUT)                :: wf_g
    1447              :       TYPE(pw_r3d_rs_type), INTENT(INOUT)                :: wf_r
    1448              :       TYPE(particle_list_type), POINTER                  :: particles
    1449              :       INTEGER, INTENT(IN)                                :: homo, ispin
    1450              :       TYPE(cp_section_key)                               :: mo_section
    1451              : 
    1452              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_occ_cubes'
    1453              : 
    1454              :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube, title
    1455              :       INTEGER                                            :: handle, i, ir, ivector, n_rep, nhomo, &
    1456              :                                                             nlist, unit_nr
    1457          148 :       INTEGER, DIMENSION(:), POINTER                     :: list, list_index
    1458              :       LOGICAL                                            :: append_cube, mpi_io
    1459          148 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: zcharge
    1460          148 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1461              :       TYPE(cell_type), POINTER                           :: cell
    1462          148 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1463              :       TYPE(pw_env_type), POINTER                         :: pw_env
    1464          148 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1465              : 
    1466          148 :       CALL timeset(routineN, handle)
    1467              : 
    1468              : #ifndef __OPENPMD
    1469              :       ! Error should usually be caught earlier as PRINT%MO_OPENPMD is not added to the input section
    1470              :       ! if openPMD is not activated
    1471          148 :       CPASSERT(mo_section%grid_output /= grid_output_openpmd)
    1472              : #endif
    1473              : 
    1474          148 :       NULLIFY (list_index)
    1475              : 
    1476              :       IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, mo_section%relative_section_key) &
    1477          148 :  , cp_p_file) .AND. section_get_lval(dft_section, mo_section%concat_to_relative(section_key_do_write(mo_section%grid_output)))) THEN
    1478          110 :          CALL get_effective_core_charges(qs_env, zcharge)
    1479          110 :          nhomo = section_get_ival(dft_section, mo_section%concat_to_relative("%NHOMO"))
    1480              :          ! For openPMD, refer to access modes instead of APPEND key
    1481          110 :          IF (mo_section%grid_output == grid_output_cubes) THEN
    1482          110 :             append_cube = section_get_lval(dft_section, mo_section%concat_to_relative("%APPEND"))
    1483              :          END IF
    1484          110 :          my_pos_cube = "REWIND"
    1485          110 :          IF (append_cube) THEN
    1486            0 :             my_pos_cube = "APPEND"
    1487              :          END IF
    1488          110 :          CALL section_vals_val_get(dft_section, mo_section%concat_to_relative("%HOMO_LIST"), n_rep_val=n_rep)
    1489          110 :          IF (n_rep > 0) THEN ! write the cubes of the list
    1490            0 :             nlist = 0
    1491            0 :             DO ir = 1, n_rep
    1492            0 :                NULLIFY (list)
    1493              :                CALL section_vals_val_get(dft_section, mo_section%concat_to_relative("%HOMO_LIST"), i_rep_val=ir, &
    1494            0 :                                          i_vals=list)
    1495            0 :                IF (ASSOCIATED(list)) THEN
    1496            0 :                   CALL reallocate(list_index, 1, nlist + SIZE(list))
    1497            0 :                   DO i = 1, SIZE(list)
    1498            0 :                      list_index(i + nlist) = list(i)
    1499              :                   END DO
    1500            0 :                   nlist = nlist + SIZE(list)
    1501              :                END IF
    1502              :             END DO
    1503              :          ELSE
    1504              : 
    1505          110 :             IF (nhomo == -1) nhomo = homo
    1506          110 :             nlist = homo - MAX(1, homo - nhomo + 1) + 1
    1507          330 :             ALLOCATE (list_index(nlist))
    1508          224 :             DO i = 1, nlist
    1509          224 :                list_index(i) = MAX(1, homo - nhomo + 1) + i - 1
    1510              :             END DO
    1511              :          END IF
    1512          224 :          DO i = 1, nlist
    1513          114 :             ivector = list_index(i)
    1514              :             CALL get_qs_env(qs_env=qs_env, &
    1515              :                             atomic_kind_set=atomic_kind_set, &
    1516              :                             qs_kind_set=qs_kind_set, &
    1517              :                             cell=cell, &
    1518              :                             particle_set=particle_set, &
    1519          114 :                             pw_env=pw_env)
    1520              :             CALL calculate_wavefunction(mo_coeff, ivector, wf_r, wf_g, atomic_kind_set, qs_kind_set, &
    1521          114 :                                         cell, dft_control, particle_set, pw_env)
    1522          114 :             WRITE (filename, '(a4,I5.5,a1,I1.1)') "WFN_", ivector, "_", ispin
    1523          114 :             mpi_io = .TRUE.
    1524              : 
    1525              :             unit_nr = mo_section%print_key_unit_nr( &
    1526              :                       logger, &
    1527              :                       input, &
    1528              :                       mo_section%absolute_section_key, &
    1529              :                       extension=".cube", &
    1530              :                       middle_name=TRIM(filename), &
    1531              :                       file_position=my_pos_cube, &
    1532              :                       log_filename=.FALSE., &
    1533              :                       mpi_io=mpi_io, &
    1534              :                       openpmd_basename="dft-mo", &
    1535              :                       openpmd_unit_dimension=openpmd_unit_dimension_wavefunction, &
    1536              :                       openpmd_unit_si=openpmd_unit_si_wavefunction, &
    1537          114 :                       sim_time=qs_env%sim_time)
    1538          114 :             WRITE (title, *) "WAVEFUNCTION ", ivector, " spin ", ispin, " i.e. HOMO - ", ivector - homo
    1539              :             CALL mo_section%write_pw(wf_r, unit_nr, title, particles=particles, zeff=zcharge, &
    1540              :                                      stride=section_get_ivals(dft_section, mo_section%concat_to_relative("%STRIDE")), &
    1541              :                                      max_file_size_mb=section_get_rval(dft_section, "PRINT%MO_CUBES%MAX_FILE_SIZE_MB"), &
    1542          114 :                                      mpi_io=mpi_io)
    1543          224 :             CALL mo_section%print_key_finished_output(unit_nr, logger, input, mo_section%absolute_section_key, mpi_io=mpi_io)
    1544              :          END DO
    1545          110 :          IF (ASSOCIATED(list_index)) DEALLOCATE (list_index)
    1546          258 :          DEALLOCATE (zcharge)
    1547              :       END IF
    1548              : 
    1549          148 :       CALL timestop(handle)
    1550              : 
    1551          296 :    END SUBROUTINE qs_scf_post_occ_cubes
    1552              : 
    1553              : ! **************************************************************************************************
    1554              : !> \brief Computes and prints the Cube Files for MO
    1555              : !> \param input ...
    1556              : !> \param dft_section ...
    1557              : !> \param dft_control ...
    1558              : !> \param logger ...
    1559              : !> \param qs_env the qs_env in which the qs_env lives
    1560              : !> \param unoccupied_orbs ...
    1561              : !> \param wf_g ...
    1562              : !> \param wf_r ...
    1563              : !> \param particles ...
    1564              : !> \param nlumos ...
    1565              : !> \param homo ...
    1566              : !> \param ispin ...
    1567              : !> \param lumo ...
    1568              : !> \param mo_section ...
    1569              : ! **************************************************************************************************
    1570          148 :    SUBROUTINE qs_scf_post_unocc_cubes(input, dft_section, dft_control, logger, qs_env, &
    1571              :                                       unoccupied_orbs, wf_g, wf_r, particles, nlumos, homo, ispin, lumo, mo_section)
    1572              : 
    1573              :       TYPE(section_vals_type), POINTER                   :: input, dft_section
    1574              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1575              :       TYPE(cp_logger_type), POINTER                      :: logger
    1576              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1577              :       TYPE(cp_fm_type), INTENT(IN)                       :: unoccupied_orbs
    1578              :       TYPE(pw_c1d_gs_type), INTENT(INOUT)                :: wf_g
    1579              :       TYPE(pw_r3d_rs_type), INTENT(INOUT)                :: wf_r
    1580              :       TYPE(particle_list_type), POINTER                  :: particles
    1581              :       INTEGER, INTENT(IN)                                :: nlumos, homo, ispin
    1582              :       INTEGER, INTENT(IN), OPTIONAL                      :: lumo
    1583              :       TYPE(cp_section_key)                               :: mo_section
    1584              : 
    1585              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_unocc_cubes'
    1586              : 
    1587              :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube, title
    1588              :       INTEGER                                            :: handle, ifirst, index_mo, ivector, &
    1589              :                                                             unit_nr
    1590              :       LOGICAL                                            :: append_cube, mpi_io
    1591          148 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: zcharge
    1592          148 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1593              :       TYPE(cell_type), POINTER                           :: cell
    1594          148 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1595              :       TYPE(pw_env_type), POINTER                         :: pw_env
    1596          148 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1597              : 
    1598          148 :       CALL timeset(routineN, handle)
    1599              : 
    1600              : #ifndef __OPENPMD
    1601              :       ! Error should usually be caught earlier as PRINT%MO_OPENPMD is not added to the input section
    1602              :       ! if openPMD is not activated
    1603          148 :       CPASSERT(mo_section%grid_output /= grid_output_openpmd)
    1604              : #endif
    1605              : 
    1606              :       IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, mo_section%relative_section_key), cp_p_file) &
    1607          148 :           .AND. section_get_lval(dft_section, mo_section%concat_to_relative(section_key_do_write(mo_section%grid_output)))) THEN
    1608          110 :          CALL get_effective_core_charges(qs_env, zcharge)
    1609          110 :          NULLIFY (qs_kind_set, particle_set, pw_env, cell)
    1610              :          ! For openPMD, refer to access modes instead of APPEND key
    1611          110 :          IF (mo_section%grid_output == grid_output_cubes) THEN
    1612          110 :             append_cube = section_get_lval(dft_section, mo_section%concat_to_relative("%APPEND"))
    1613              :          END IF
    1614          110 :          my_pos_cube = "REWIND"
    1615          110 :          IF (append_cube) THEN
    1616            0 :             my_pos_cube = "APPEND"
    1617              :          END IF
    1618          110 :          ifirst = 1
    1619          110 :          IF (PRESENT(lumo)) ifirst = lumo
    1620          254 :          DO ivector = ifirst, ifirst + nlumos - 1
    1621              :             CALL get_qs_env(qs_env=qs_env, &
    1622              :                             atomic_kind_set=atomic_kind_set, &
    1623              :                             qs_kind_set=qs_kind_set, &
    1624              :                             cell=cell, &
    1625              :                             particle_set=particle_set, &
    1626          144 :                             pw_env=pw_env)
    1627              :             CALL calculate_wavefunction(unoccupied_orbs, ivector, wf_r, wf_g, atomic_kind_set, &
    1628          144 :                                         qs_kind_set, cell, dft_control, particle_set, pw_env)
    1629              : 
    1630          144 :             IF (ifirst == 1) THEN
    1631          130 :                index_mo = homo + ivector
    1632              :             ELSE
    1633           14 :                index_mo = ivector
    1634              :             END IF
    1635          144 :             WRITE (filename, '(a4,I5.5,a1,I1.1)') "WFN_", index_mo, "_", ispin
    1636          144 :             mpi_io = .TRUE.
    1637              : 
    1638              :             unit_nr = mo_section%print_key_unit_nr( &
    1639              :                       logger, &
    1640              :                       input, &
    1641              :                       mo_section%absolute_section_key, &
    1642              :                       extension=".cube", &
    1643              :                       middle_name=TRIM(filename), &
    1644              :                       file_position=my_pos_cube, &
    1645              :                       log_filename=.FALSE., &
    1646              :                       mpi_io=mpi_io, &
    1647              :                       openpmd_basename="dft-mo", &
    1648              :                       openpmd_unit_dimension=openpmd_unit_dimension_wavefunction, &
    1649              :                       openpmd_unit_si=openpmd_unit_si_wavefunction, &
    1650          144 :                       sim_time=qs_env%sim_time)
    1651          144 :             WRITE (title, *) "WAVEFUNCTION ", index_mo, " spin ", ispin, " i.e. LUMO + ", ifirst + ivector - 2
    1652              :             CALL mo_section%write_pw(wf_r, unit_nr, title, particles=particles, zeff=zcharge, &
    1653              :                                      stride=section_get_ivals(dft_section, mo_section%concat_to_relative("%STRIDE")), &
    1654              :                                      max_file_size_mb=section_get_rval(dft_section, "PRINT%MO_CUBES%MAX_FILE_SIZE_MB"), &
    1655          144 :                                      mpi_io=mpi_io)
    1656          254 :             CALL mo_section%print_key_finished_output(unit_nr, logger, input, mo_section%absolute_section_key, mpi_io=mpi_io)
    1657              : 
    1658              :          END DO
    1659          258 :          DEALLOCATE (zcharge)
    1660              :       END IF
    1661              : 
    1662          148 :       CALL timestop(handle)
    1663              : 
    1664          296 :    END SUBROUTINE qs_scf_post_unocc_cubes
    1665              : 
    1666              : ! **************************************************************************************************
    1667              : !> \brief Computes and prints electric moments
    1668              : !> \param input ...
    1669              : !> \param logger ...
    1670              : !> \param qs_env the qs_env in which the qs_env lives
    1671              : !> \param output_unit ...
    1672              : ! **************************************************************************************************
    1673        13635 :    SUBROUTINE qs_scf_post_moments(input, logger, qs_env, output_unit)
    1674              :       TYPE(section_vals_type), POINTER                   :: input
    1675              :       TYPE(cp_logger_type), POINTER                      :: logger
    1676              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1677              :       INTEGER, INTENT(IN)                                :: output_unit
    1678              : 
    1679              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_moments'
    1680              : 
    1681              :       CHARACTER(LEN=default_path_length)                 :: filename
    1682              :       INTEGER                                            :: handle, max_nmo, maxmom, moments_format, &
    1683              :                                                             moments_unit_nr, reference, unit_nr
    1684              :       LOGICAL                                            :: com_nl, do_kg, do_kpoints, magnetic, &
    1685              :                                                             new_file, periodic, second_ref_point, &
    1686              :                                                             vel_reprs
    1687        13635 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: ref_point
    1688              :       TYPE(section_vals_type), POINTER                   :: print_key
    1689              : 
    1690        13635 :       CALL timeset(routineN, handle)
    1691              : 
    1692              :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1693        13635 :                                               subsection_name="DFT%PRINT%MOMENTS")
    1694              : 
    1695        13635 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    1696              : 
    1697              :          maxmom = section_get_ival(section_vals=input, &
    1698         1570 :                                    keyword_name="DFT%PRINT%MOMENTS%MAX_MOMENT")
    1699              :          moments_format = section_get_ival(section_vals=input, &
    1700         1570 :                                            keyword_name="DFT%PRINT%MOMENTS%FORMAT")
    1701              :          periodic = section_get_lval(section_vals=input, &
    1702         1570 :                                      keyword_name="DFT%PRINT%MOMENTS%PERIODIC")
    1703              :          reference = section_get_ival(section_vals=input, &
    1704         1570 :                                       keyword_name="DFT%PRINT%MOMENTS%REFERENCE")
    1705              :          magnetic = section_get_lval(section_vals=input, &
    1706         1570 :                                      keyword_name="DFT%PRINT%MOMENTS%MAGNETIC")
    1707              :          vel_reprs = section_get_lval(section_vals=input, &
    1708         1570 :                                       keyword_name="DFT%PRINT%MOMENTS%VEL_REPRS")
    1709              :          com_nl = section_get_lval(section_vals=input, &
    1710         1570 :                                    keyword_name="DFT%PRINT%MOMENTS%COM_NL")
    1711              :          second_ref_point = section_get_lval(section_vals=input, &
    1712         1570 :                                              keyword_name="DFT%PRINT%MOMENTS%SECOND_REFERENCE_POINT")
    1713              :          do_kg = section_get_lval(section_vals=input, &
    1714         1570 :                                   keyword_name="DFT%PRINT%MOMENTS%KG")
    1715              :          max_nmo = section_get_ival(section_vals=input, &
    1716         1570 :                                     keyword_name="DFT%PRINT%MOMENTS%MAX_NMO")
    1717              : 
    1718         1570 :          NULLIFY (ref_point)
    1719         1570 :          CALL section_vals_val_get(input, "DFT%PRINT%MOMENTS%REF_POINT", r_vals=ref_point)
    1720              :          unit_nr = cp_print_key_unit_nr(logger=logger, basis_section=input, &
    1721              :                                         print_key_path="DFT%PRINT%MOMENTS", extension=".dat", &
    1722              :                                         middle_name="moments", log_filename=.FALSE., &
    1723         1570 :                                         is_new_file=new_file)
    1724              : 
    1725         1570 :          IF (output_unit > 0) THEN
    1726          795 :             IF (unit_nr /= output_unit) THEN
    1727           49 :                INQUIRE (UNIT=unit_nr, NAME=filename)
    1728              :                WRITE (UNIT=output_unit, FMT="(/,T2,A,2(/,T3,A),/)") &
    1729           49 :                   "MOMENTS", "The electric/magnetic moments are written to file:", &
    1730           98 :                   TRIM(filename)
    1731          746 :             ELSE IF (moments_format /= moments_format_trajectory) THEN
    1732          743 :                WRITE (UNIT=output_unit, FMT="(/,T2,A)") "ELECTRIC/MAGNETIC MOMENTS"
    1733              :             END IF
    1734              :          END IF
    1735              : 
    1736         1570 :          CALL get_qs_env(qs_env, do_kpoints=do_kpoints)
    1737              : 
    1738         1570 :          IF (moments_format == moments_format_trajectory) THEN
    1739            6 :             IF (do_kpoints) THEN
    1740            0 :                CPABORT("MOMENTS FORMAT TRAJECTORY is not available for k-point calculations.")
    1741              :             END IF
    1742            6 :             IF (maxmom /= 1) CPABORT("MOMENTS FORMAT TRAJECTORY requires MAX_MOMENT 1.")
    1743            6 :             IF (magnetic) CPABORT("MOMENTS FORMAT TRAJECTORY does not support MAGNETIC moments.")
    1744            6 :             IF (vel_reprs) CPABORT("MOMENTS FORMAT TRAJECTORY does not support VEL_REPRS.")
    1745            6 :             IF (do_kg) CPABORT("MOMENTS FORMAT TRAJECTORY does not support KG moments.")
    1746            6 :             moments_unit_nr = -1
    1747              :          ELSE
    1748         1564 :             moments_unit_nr = unit_nr
    1749              :          END IF
    1750              : 
    1751         1570 :          IF (do_kpoints) THEN
    1752           10 :             CALL qs_moment_kpoints(qs_env, maxmom, reference, ref_point, max_nmo, moments_unit_nr)
    1753              :          ELSE
    1754         1560 :             IF (periodic) THEN
    1755          478 :                CALL qs_moment_berry_phase(qs_env, magnetic, maxmom, reference, ref_point, moments_unit_nr)
    1756              :             ELSE
    1757         1082 :                CALL qs_moment_locop(qs_env, magnetic, maxmom, reference, ref_point, moments_unit_nr, vel_reprs, com_nl)
    1758              :             END IF
    1759         1560 :             IF (do_kg) THEN
    1760            0 :                CALL calculate_kg_moments(qs_env, moments_unit_nr, maxmom, magnetic, vel_reprs, com_nl)
    1761              :             END IF
    1762              :          END IF
    1763         1570 :          IF (moments_format == moments_format_trajectory) THEN
    1764            6 :             CALL write_moments_trajectory(unit_nr, logger, qs_env, periodic, new_file, "MOMENTS|")
    1765              :          END IF
    1766              : 
    1767              :          CALL cp_print_key_finished_output(unit_nr=unit_nr, logger=logger, &
    1768         1570 :                                            basis_section=input, print_key_path="DFT%PRINT%MOMENTS")
    1769              : 
    1770         1570 :          IF (second_ref_point) THEN
    1771              :             reference = section_get_ival(section_vals=input, &
    1772            0 :                                          keyword_name="DFT%PRINT%MOMENTS%REFERENCE_2")
    1773              : 
    1774            0 :             NULLIFY (ref_point)
    1775            0 :             CALL section_vals_val_get(input, "DFT%PRINT%MOMENTS%REF_POINT_2", r_vals=ref_point)
    1776              :             unit_nr = cp_print_key_unit_nr(logger=logger, basis_section=input, &
    1777              :                                            print_key_path="DFT%PRINT%MOMENTS", extension=".dat", &
    1778              :                                            middle_name="moments_refpoint_2", log_filename=.FALSE., &
    1779            0 :                                            is_new_file=new_file)
    1780              : 
    1781            0 :             IF (output_unit > 0) THEN
    1782            0 :                IF (unit_nr /= output_unit) THEN
    1783            0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    1784              :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,2(/,T3,A),/)") &
    1785            0 :                      "MOMENTS", "The electric/magnetic moments for the second reference point are written to file:", &
    1786            0 :                      TRIM(filename)
    1787            0 :                ELSE IF (moments_format /= moments_format_trajectory) THEN
    1788            0 :                   WRITE (UNIT=output_unit, FMT="(/,T2,A)") "ELECTRIC/MAGNETIC MOMENTS"
    1789              :                END IF
    1790              :             END IF
    1791            0 :             IF (moments_format /= moments_format_trajectory) moments_unit_nr = unit_nr
    1792            0 :             IF (do_kpoints) THEN
    1793            0 :                CALL qs_moment_kpoints(qs_env, maxmom, reference, ref_point, max_nmo, moments_unit_nr)
    1794              :             ELSE
    1795            0 :                IF (periodic) THEN
    1796            0 :                   CALL qs_moment_berry_phase(qs_env, magnetic, maxmom, reference, ref_point, moments_unit_nr)
    1797              :                ELSE
    1798              :                   CALL qs_moment_locop(qs_env, magnetic, maxmom, reference, ref_point, &
    1799            0 :                                        moments_unit_nr, vel_reprs, com_nl)
    1800              :                END IF
    1801              :             END IF
    1802            0 :             IF (moments_format == moments_format_trajectory) THEN
    1803            0 :                CALL write_moments_trajectory(unit_nr, logger, qs_env, periodic, new_file, "MOMENTS_REF2|")
    1804              :             END IF
    1805              :             CALL cp_print_key_finished_output(unit_nr=unit_nr, logger=logger, &
    1806            0 :                                               basis_section=input, print_key_path="DFT%PRINT%MOMENTS")
    1807              :          END IF
    1808              : 
    1809              :       END IF
    1810              : 
    1811        13635 :       CALL timestop(handle)
    1812              : 
    1813        13635 :    END SUBROUTINE qs_scf_post_moments
    1814              : 
    1815              : ! **************************************************************************************************
    1816              : !> \brief Writes one machine-readable electric-dipole record for the current iteration.
    1817              : !> \param unit_nr output unit
    1818              : !> \param logger logger carrying the current iteration levels
    1819              : !> \param qs_env quantum environment containing the dipole result and cell
    1820              : !> \param periodic whether the Berry-phase operator was used
    1821              : !> \param new_file whether the output file has just been created
    1822              : !> \param label record label
    1823              : ! **************************************************************************************************
    1824            6 :    SUBROUTINE write_moments_trajectory(unit_nr, logger, qs_env, periodic, new_file, label)
    1825              :       INTEGER, INTENT(IN)                                :: unit_nr
    1826              :       TYPE(cp_logger_type), POINTER                      :: logger
    1827              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1828              :       LOGICAL, INTENT(IN)                                :: periodic, new_file
    1829              :       CHARACTER(LEN=*), INTENT(IN)                       :: label
    1830              : 
    1831              :       CHARACTER(LEN=default_string_length)               :: description, iter
    1832              :       REAL(KIND=dp), DIMENSION(3)                        :: dipole
    1833              :       TYPE(cell_type), POINTER                           :: cell
    1834              :       TYPE(cp_result_type), POINTER                      :: results
    1835              : 
    1836            6 :       IF (unit_nr <= 0) RETURN
    1837              : 
    1838            3 :       NULLIFY (cell, results)
    1839            3 :       CALL get_qs_env(qs_env, cell=cell, results=results)
    1840            3 :       description = "[DIPOLE]"
    1841            3 :       CALL get_results(results=results, description=description, values=dipole)
    1842              : 
    1843            3 :       IF (new_file) THEN
    1844            0 :          IF (periodic) THEN
    1845              :             WRITE (unit_nr, "(A)") "# "//TRIM(label)// &
    1846              :                " iter_level dipole_x dipole_y dipole_z dipole_norm cell_xx cell_xy cell_xz"// &
    1847            0 :                " cell_yx cell_yy cell_yz cell_zx cell_zy cell_zz [Debye]"
    1848              :          ELSE
    1849              :             WRITE (unit_nr, "(A)") "# "//TRIM(label)// &
    1850            0 :                " iter_level dipole_x dipole_y dipole_z dipole_norm [Debye]"
    1851              :          END IF
    1852              :       END IF
    1853              : 
    1854            3 :       iter = cp_iter_string(logger%iter_info)
    1855            3 :       IF (periodic) THEN
    1856            3 :          WRITE (unit_nr, "(1X,A,1X,A15,13(1X,ES18.10))") TRIM(label), iter(1:15), &
    1857           21 :             dipole*debye, SQRT(SUM(dipole**2))*debye, &
    1858           33 :             cell%hmat(1, :)*debye, cell%hmat(2, :)*debye, cell%hmat(3, :)*debye
    1859              :       ELSE
    1860            0 :          WRITE (unit_nr, "(1X,A,1X,A15,4(1X,ES18.10))") TRIM(label), iter(1:15), &
    1861            0 :             dipole*debye, SQRT(SUM(dipole**2))*debye
    1862              :       END IF
    1863              : 
    1864              :    END SUBROUTINE write_moments_trajectory
    1865              : 
    1866              : ! **************************************************************************************************
    1867              : !> \brief Computes and prints the X-ray diffraction spectrum.
    1868              : !> \param input ...
    1869              : !> \param dft_section ...
    1870              : !> \param logger ...
    1871              : !> \param qs_env the qs_env in which the qs_env lives
    1872              : !> \param output_unit ...
    1873              : ! **************************************************************************************************
    1874        12331 :    SUBROUTINE qs_scf_post_xray(input, dft_section, logger, qs_env, output_unit)
    1875              : 
    1876              :       TYPE(section_vals_type), POINTER                   :: input, dft_section
    1877              :       TYPE(cp_logger_type), POINTER                      :: logger
    1878              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1879              :       INTEGER, INTENT(IN)                                :: output_unit
    1880              : 
    1881              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_scf_post_xray'
    1882              : 
    1883              :       CHARACTER(LEN=default_path_length)                 :: filename
    1884              :       INTEGER                                            :: handle, unit_nr
    1885              :       REAL(KIND=dp)                                      :: q_max
    1886              :       TYPE(section_vals_type), POINTER                   :: print_key
    1887              : 
    1888        12331 :       CALL timeset(routineN, handle)
    1889              : 
    1890              :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1891        12331 :                                               subsection_name="DFT%PRINT%XRAY_DIFFRACTION_SPECTRUM")
    1892              : 
    1893        12331 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    1894              :          q_max = section_get_rval(section_vals=dft_section, &
    1895           30 :                                   keyword_name="PRINT%XRAY_DIFFRACTION_SPECTRUM%Q_MAX")
    1896              :          unit_nr = cp_print_key_unit_nr(logger=logger, &
    1897              :                                         basis_section=input, &
    1898              :                                         print_key_path="DFT%PRINT%XRAY_DIFFRACTION_SPECTRUM", &
    1899              :                                         extension=".dat", &
    1900              :                                         middle_name="xrd", &
    1901           30 :                                         log_filename=.FALSE.)
    1902           30 :          IF (output_unit > 0) THEN
    1903           15 :             INQUIRE (UNIT=unit_nr, NAME=filename)
    1904              :             WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
    1905           15 :                "X-RAY DIFFRACTION SPECTRUM"
    1906           15 :             IF (unit_nr /= output_unit) THEN
    1907              :                WRITE (UNIT=output_unit, FMT="(/,T3,A,/,/,T3,A,/)") &
    1908           14 :                   "The coherent X-ray diffraction spectrum is written to the file:", &
    1909           28 :                   TRIM(filename)
    1910              :             END IF
    1911              :          END IF
    1912              :          CALL xray_diffraction_spectrum(qs_env=qs_env, &
    1913              :                                         unit_number=unit_nr, &
    1914           30 :                                         q_max=q_max)
    1915              :          CALL cp_print_key_finished_output(unit_nr=unit_nr, &
    1916              :                                            logger=logger, &
    1917              :                                            basis_section=input, &
    1918           30 :                                            print_key_path="DFT%PRINT%XRAY_DIFFRACTION_SPECTRUM")
    1919              :       END IF
    1920              : 
    1921        12331 :       CALL timestop(handle)
    1922              : 
    1923        12331 :    END SUBROUTINE qs_scf_post_xray
    1924              : 
    1925              : ! **************************************************************************************************
    1926              : !> \brief Computes and prints Electric Field Gradient
    1927              : !> \param input ...
    1928              : !> \param logger ...
    1929              : !> \param qs_env the qs_env in which the qs_env lives
    1930              : ! **************************************************************************************************
    1931        12331 :    SUBROUTINE qs_scf_post_efg(input, logger, qs_env)
    1932              :       TYPE(section_vals_type), POINTER                   :: input
    1933              :       TYPE(cp_logger_type), POINTER                      :: logger
    1934              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1935              : 
    1936              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_efg'
    1937              : 
    1938              :       INTEGER                                            :: handle
    1939              :       TYPE(section_vals_type), POINTER                   :: print_key
    1940              : 
    1941        12331 :       CALL timeset(routineN, handle)
    1942              : 
    1943              :       print_key => section_vals_get_subs_vals(section_vals=input, &
    1944        12331 :                                               subsection_name="DFT%PRINT%ELECTRIC_FIELD_GRADIENT")
    1945        12331 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), &
    1946              :                 cp_p_file)) THEN
    1947           30 :          CALL qs_efg_calc(qs_env=qs_env)
    1948              :       END IF
    1949              : 
    1950        12331 :       CALL timestop(handle)
    1951              : 
    1952        12331 :    END SUBROUTINE qs_scf_post_efg
    1953              : 
    1954              : ! **************************************************************************************************
    1955              : !> \brief Computes the Electron Transfer Coupling matrix element
    1956              : !> \param input ...
    1957              : !> \param qs_env the qs_env in which the qs_env lives
    1958              : !> \param dft_control ...
    1959              : ! **************************************************************************************************
    1960        24662 :    SUBROUTINE qs_scf_post_et(input, qs_env, dft_control)
    1961              :       TYPE(section_vals_type), POINTER                   :: input
    1962              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1963              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1964              : 
    1965              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_et'
    1966              : 
    1967              :       INTEGER                                            :: handle, ispin
    1968              :       LOGICAL                                            :: do_et
    1969        12331 :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: my_mos
    1970              :       TYPE(section_vals_type), POINTER                   :: et_section
    1971              : 
    1972        12331 :       CALL timeset(routineN, handle)
    1973              : 
    1974              :       do_et = .FALSE.
    1975        12331 :       et_section => section_vals_get_subs_vals(input, "PROPERTIES%ET_COUPLING")
    1976        12331 :       CALL section_vals_get(et_section, explicit=do_et)
    1977        12331 :       IF (do_et) THEN
    1978           10 :          IF (qs_env%et_coupling%first_run) THEN
    1979           10 :             NULLIFY (my_mos)
    1980           50 :             ALLOCATE (my_mos(dft_control%nspins))
    1981           50 :             ALLOCATE (qs_env%et_coupling%et_mo_coeff(dft_control%nspins))
    1982           30 :             DO ispin = 1, dft_control%nspins
    1983              :                CALL cp_fm_create(matrix=my_mos(ispin), &
    1984              :                                  matrix_struct=qs_env%mos(ispin)%mo_coeff%matrix_struct, &
    1985           20 :                                  name="FIRST_RUN_COEFF"//TRIM(ADJUSTL(cp_to_string(ispin)))//"MATRIX")
    1986              :                CALL cp_fm_to_fm(qs_env%mos(ispin)%mo_coeff, &
    1987           30 :                                 my_mos(ispin))
    1988              :             END DO
    1989           10 :             CALL set_et_coupling_type(qs_env%et_coupling, et_mo_coeff=my_mos)
    1990           10 :             DEALLOCATE (my_mos)
    1991              :          END IF
    1992              :       END IF
    1993              : 
    1994        12331 :       CALL timestop(handle)
    1995              : 
    1996        12331 :    END SUBROUTINE qs_scf_post_et
    1997              : 
    1998              : ! **************************************************************************************************
    1999              : !> \brief compute the electron localization function
    2000              : !>
    2001              : !> \param input ...
    2002              : !> \param logger ...
    2003              : !> \param qs_env ...
    2004              : !> \par History
    2005              : !>      2012-07 Created [MI]
    2006              : ! **************************************************************************************************
    2007        12331 :    SUBROUTINE qs_scf_post_elf(input, logger, qs_env)
    2008              :       TYPE(section_vals_type), POINTER                   :: input
    2009              :       TYPE(cp_logger_type), POINTER                      :: logger
    2010              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2011              : 
    2012              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_elf'
    2013              : 
    2014              :       CHARACTER(LEN=default_path_length)                 :: filename, mpi_filename, my_pos_cube, &
    2015              :                                                             title
    2016              :       INTEGER                                            :: handle, ispin, output_unit, unit_nr
    2017              :       LOGICAL                                            :: append_cube, gapw, mpi_io
    2018              :       REAL(dp)                                           :: rho_cutoff
    2019        12331 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: zcharge
    2020              :       TYPE(cp_section_key)                               :: elf_section_key
    2021              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2022              :       TYPE(particle_list_type), POINTER                  :: particles
    2023              :       TYPE(pw_env_type), POINTER                         :: pw_env
    2024        12331 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
    2025              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    2026        12331 :       TYPE(pw_r3d_rs_type), ALLOCATABLE, DIMENSION(:)    :: elf_r
    2027              :       TYPE(qs_subsys_type), POINTER                      :: subsys
    2028              :       TYPE(section_vals_type), POINTER                   :: elf_section
    2029              : 
    2030        12331 :       CALL timeset(routineN, handle)
    2031        12331 :       output_unit = cp_logger_get_default_io_unit(logger)
    2032              : 
    2033        12331 :       elf_section_key = cube_or_openpmd(input, str_elf_cubes, str_elf_openpmd, logger)
    2034              : 
    2035        12331 :       elf_section => section_vals_get_subs_vals(input, elf_section_key%absolute_section_key)
    2036        12331 :       IF (elf_section_key%do_output) THEN
    2037              : 
    2038           82 :          NULLIFY (dft_control, pw_env, auxbas_pw_pool, pw_pools, particles, subsys)
    2039           82 :          CALL get_qs_env(qs_env, dft_control=dft_control, pw_env=pw_env, subsys=subsys)
    2040           82 :          CALL qs_subsys_get(subsys, particles=particles)
    2041              : 
    2042           82 :          gapw = dft_control%qs_control%gapw
    2043           82 :          IF (.NOT. gapw) THEN
    2044              :             ! allocate
    2045          330 :             ALLOCATE (elf_r(dft_control%nspins))
    2046              :             CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    2047           82 :                             pw_pools=pw_pools)
    2048          166 :             DO ispin = 1, dft_control%nspins
    2049           84 :                CALL auxbas_pw_pool%create_pw(elf_r(ispin))
    2050          166 :                CALL pw_zero(elf_r(ispin))
    2051              :             END DO
    2052              : 
    2053           82 :             IF (output_unit > 0) THEN
    2054              :                WRITE (UNIT=output_unit, FMT="(/,T15,A,/)") &
    2055           41 :                   " ----- ELF is computed on the real space grid -----"
    2056              :             END IF
    2057           82 :             rho_cutoff = section_get_rval(elf_section, "density_cutoff")
    2058           82 :             CALL qs_elf_calc(qs_env, elf_r, rho_cutoff)
    2059           82 :             CALL get_effective_core_charges(qs_env, zcharge)
    2060              : 
    2061              :             ! write ELF into cube file
    2062              : 
    2063              :             ! For openPMD, refer to access modes instead of APPEND key
    2064           82 :             IF (elf_section_key%grid_output == grid_output_cubes) THEN
    2065           82 :                append_cube = section_get_lval(elf_section, "APPEND")
    2066              :             END IF
    2067           82 :             my_pos_cube = "REWIND"
    2068           82 :             IF (append_cube) THEN
    2069            0 :                my_pos_cube = "APPEND"
    2070              :             END IF
    2071              : 
    2072          166 :             DO ispin = 1, dft_control%nspins
    2073           84 :                WRITE (filename, '(a5,I1.1)') "ELF_S", ispin
    2074           84 :                WRITE (title, *) "ELF spin ", ispin
    2075           84 :                mpi_io = .TRUE.
    2076              :                unit_nr = elf_section_key%print_key_unit_nr( &
    2077              :                          logger, &
    2078              :                          input, &
    2079              :                          elf_section_key%absolute_section_key, &
    2080              :                          extension=".cube", &
    2081              :                          middle_name=TRIM(filename), &
    2082              :                          file_position=my_pos_cube, &
    2083              :                          log_filename=.FALSE., &
    2084              :                          mpi_io=mpi_io, &
    2085              :                          fout=mpi_filename, &
    2086              :                          openpmd_basename="dft-elf", &
    2087              :                          openpmd_unit_dimension=openpmd_unit_dimension_dimensionless, &
    2088              :                          openpmd_unit_si=openpmd_unit_si_dimensionless, &
    2089           84 :                          sim_time=qs_env%sim_time)
    2090           84 :                IF (output_unit > 0) THEN
    2091           42 :                   IF (.NOT. mpi_io) THEN
    2092            0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    2093              :                   ELSE
    2094           42 :                      filename = mpi_filename
    2095              :                   END IF
    2096              :                   WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2097           42 :                      "ELF is written in "//elf_section_key%format_name//" file format to the file:", &
    2098           84 :                      TRIM(filename)
    2099              :                END IF
    2100              : 
    2101              :                CALL elf_section_key%write_pw(elf_r(ispin), unit_nr, title, particles=particles, zeff=zcharge, &
    2102           84 :                                              stride=section_get_ivals(elf_section, "STRIDE"), mpi_io=mpi_io)
    2103              :                CALL elf_section_key%print_key_finished_output( &
    2104              :                   unit_nr, &
    2105              :                   logger, &
    2106              :                   input, &
    2107              :                   elf_section_key%absolute_section_key, &
    2108           84 :                   mpi_io=mpi_io)
    2109              : 
    2110          166 :                CALL auxbas_pw_pool%give_back_pw(elf_r(ispin))
    2111              :             END DO
    2112              : 
    2113              :             ! deallocate
    2114           82 :             DEALLOCATE (elf_r, zcharge)
    2115              : 
    2116              :          ELSE
    2117              :             ! not implemented
    2118            0 :             CPWARN("ELF not implemented for GAPW calculations!")
    2119              :          END IF
    2120              : 
    2121              :       END IF ! print key
    2122              : 
    2123        12331 :       CALL timestop(handle)
    2124              : 
    2125        24662 :    END SUBROUTINE qs_scf_post_elf
    2126              : 
    2127              : ! **************************************************************************************************
    2128              : !> \brief computes the condition number of the overlap matrix and
    2129              : !>      prints the value of the total energy. This is needed
    2130              : !>      for BASIS_MOLOPT optimizations
    2131              : !> \param input ...
    2132              : !> \param logger ...
    2133              : !> \param qs_env the qs_env in which the qs_env lives
    2134              : !> \par History
    2135              : !>      2007-07 Created [Joost VandeVondele]
    2136              : ! **************************************************************************************************
    2137        12331 :    SUBROUTINE qs_scf_post_molopt(input, logger, qs_env)
    2138              :       TYPE(section_vals_type), POINTER                   :: input
    2139              :       TYPE(cp_logger_type), POINTER                      :: logger
    2140              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2141              : 
    2142              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_molopt'
    2143              : 
    2144              :       INTEGER                                            :: handle, nao, unit_nr
    2145              :       REAL(KIND=dp)                                      :: S_cond_number
    2146        12331 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenvalues
    2147              :       TYPE(cp_fm_struct_type), POINTER                   :: ao_ao_fmstruct
    2148              :       TYPE(cp_fm_type)                                   :: fm_s, fm_work
    2149              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    2150        12331 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_s
    2151        12331 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    2152              :       TYPE(qs_energy_type), POINTER                      :: energy
    2153              :       TYPE(section_vals_type), POINTER                   :: print_key
    2154              : 
    2155        12331 :       CALL timeset(routineN, handle)
    2156              : 
    2157              :       print_key => section_vals_get_subs_vals(section_vals=input, &
    2158        12331 :                                               subsection_name="DFT%PRINT%BASIS_MOLOPT_QUANTITIES")
    2159        12331 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), &
    2160              :                 cp_p_file)) THEN
    2161              : 
    2162           28 :          CALL get_qs_env(qs_env, energy=energy, matrix_s=matrix_s, mos=mos)
    2163              : 
    2164              :          ! set up the two needed full matrices, using mo_coeff as a template
    2165           28 :          CALL get_mo_set(mo_set=mos(1), mo_coeff=mo_coeff, nao=nao)
    2166              :          CALL cp_fm_struct_create(fmstruct=ao_ao_fmstruct, &
    2167              :                                   nrow_global=nao, ncol_global=nao, &
    2168           28 :                                   template_fmstruct=mo_coeff%matrix_struct)
    2169              :          CALL cp_fm_create(fm_s, matrix_struct=ao_ao_fmstruct, &
    2170           28 :                            name="fm_s")
    2171              :          CALL cp_fm_create(fm_work, matrix_struct=ao_ao_fmstruct, &
    2172           28 :                            name="fm_work")
    2173           28 :          CALL cp_fm_struct_release(ao_ao_fmstruct)
    2174           84 :          ALLOCATE (eigenvalues(nao))
    2175              : 
    2176           28 :          CALL copy_dbcsr_to_fm(matrix_s(1)%matrix, fm_s)
    2177           28 :          CALL choose_eigv_solver(fm_s, fm_work, eigenvalues)
    2178              : 
    2179           28 :          CALL cp_fm_release(fm_s)
    2180           28 :          CALL cp_fm_release(fm_work)
    2181              : 
    2182          992 :          S_cond_number = MAXVAL(ABS(eigenvalues))/MAX(MINVAL(ABS(eigenvalues)), EPSILON(0.0_dp))
    2183              : 
    2184              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%BASIS_MOLOPT_QUANTITIES", &
    2185           28 :                                         extension=".molopt")
    2186              : 
    2187           28 :          IF (unit_nr > 0) THEN
    2188              :             ! please keep this format fixed, needs to be grepable for molopt
    2189              :             ! optimizations
    2190           14 :             WRITE (unit_nr, '(T2,A28,2A25)') "", "Tot. Ener.", "S Cond. Numb."
    2191           14 :             WRITE (unit_nr, '(T2,A28,2E25.17)') "BASIS_MOLOPT_QUANTITIES", energy%total, S_cond_number
    2192              :          END IF
    2193              : 
    2194              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2195           84 :                                            "DFT%PRINT%BASIS_MOLOPT_QUANTITIES")
    2196              : 
    2197              :       END IF
    2198              : 
    2199        12331 :       CALL timestop(handle)
    2200              : 
    2201        24662 :    END SUBROUTINE qs_scf_post_molopt
    2202              : 
    2203              : ! **************************************************************************************************
    2204              : !> \brief Dumps EPR
    2205              : !> \param input ...
    2206              : !> \param logger ...
    2207              : !> \param qs_env the qs_env in which the qs_env lives
    2208              : ! **************************************************************************************************
    2209        12331 :    SUBROUTINE qs_scf_post_epr(input, logger, qs_env)
    2210              :       TYPE(section_vals_type), POINTER                   :: input
    2211              :       TYPE(cp_logger_type), POINTER                      :: logger
    2212              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2213              : 
    2214              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'qs_scf_post_epr'
    2215              : 
    2216              :       INTEGER                                            :: handle
    2217              :       TYPE(section_vals_type), POINTER                   :: print_key
    2218              : 
    2219        12331 :       CALL timeset(routineN, handle)
    2220              : 
    2221              :       print_key => section_vals_get_subs_vals(section_vals=input, &
    2222        12331 :                                               subsection_name="DFT%PRINT%HYPERFINE_COUPLING_TENSOR")
    2223        12331 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), &
    2224              :                 cp_p_file)) THEN
    2225           30 :          CALL qs_epr_hyp_calc(qs_env=qs_env)
    2226              :       END IF
    2227              : 
    2228        12331 :       CALL timestop(handle)
    2229              : 
    2230        12331 :    END SUBROUTINE qs_scf_post_epr
    2231              : 
    2232              : ! **************************************************************************************************
    2233              : !> \brief Interface routine to trigger writing of results available from normal
    2234              : !>        SCF. Can write MO-dependent and MO free results (needed for call from
    2235              : !>        the linear scaling code)
    2236              : !> \param qs_env the qs_env in which the qs_env lives
    2237              : !> \param scf_env ...
    2238              : ! **************************************************************************************************
    2239        12331 :    SUBROUTINE write_available_results(qs_env, scf_env)
    2240              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2241              :       TYPE(qs_scf_env_type), OPTIONAL, POINTER           :: scf_env
    2242              : 
    2243              :       CHARACTER(len=*), PARAMETER :: routineN = 'write_available_results'
    2244              : 
    2245              :       INTEGER                                            :: handle
    2246              : 
    2247        12331 :       CALL timeset(routineN, handle)
    2248              : 
    2249              :       ! those properties that require MOs (not suitable density matrix based methods)
    2250        12331 :       CALL write_mo_dependent_results(qs_env, scf_env)
    2251              : 
    2252              :       ! those that depend only on the density matrix, they should be linear scaling in their implementation
    2253        12331 :       CALL write_mo_free_results(qs_env)
    2254              : 
    2255        12331 :       CALL timestop(handle)
    2256              : 
    2257        12331 :    END SUBROUTINE write_available_results
    2258              : 
    2259              : ! **************************************************************************************************
    2260              : !> \brief Write QS results available if MO's are present (if switched on through the print_keys)
    2261              : !>        Writes only MO dependent results. Split is necessary as ls_scf does not
    2262              : !>        provide MO's
    2263              : !> \param qs_env the qs_env in which the qs_env lives
    2264              : !> \param scf_env ...
    2265              : ! **************************************************************************************************
    2266        12679 :    SUBROUTINE write_mo_dependent_results(qs_env, scf_env)
    2267              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2268              :       TYPE(qs_scf_env_type), OPTIONAL, POINTER           :: scf_env
    2269              : 
    2270              :       CHARACTER(len=*), PARAMETER :: routineN = 'write_mo_dependent_results'
    2271              : 
    2272              :       INTEGER                                            :: handle, homo, ispin, nlumo_dos, &
    2273              :                                                             nlumo_molden, nlumo_required, nlumos, &
    2274              :                                                             nmo, output_unit
    2275              :       LOGICAL                                            :: all_equal, defer_molden, do_curve, &
    2276              :                                                             do_dos, do_kpoints, do_pdos, &
    2277              :                                                             do_projected_dos, explicit
    2278              :       REAL(KIND=dp)                                      :: maxocc, s_square, s_square_ideal, &
    2279              :                                                             total_abs_spin_dens, total_spin_dens
    2280        12679 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: mo_eigenvalues, occupation_numbers
    2281              :       TYPE(admm_type), POINTER                           :: admm_env
    2282        12679 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2283              :       TYPE(cell_type), POINTER                           :: cell
    2284        12679 :       TYPE(cp_1d_r_p_type), DIMENSION(:), POINTER        :: unoccupied_evals
    2285        12679 :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: unoccupied_orbs
    2286              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    2287              :       TYPE(cp_logger_type), POINTER                      :: logger
    2288        12679 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_rmpv, matrix_s
    2289              :       TYPE(dbcsr_type), POINTER                          :: mo_coeff_deriv
    2290              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2291        12679 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    2292        12679 :       TYPE(molecule_type), POINTER                       :: molecule_set(:)
    2293              :       TYPE(particle_list_type), POINTER                  :: particles
    2294        12679 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2295              :       TYPE(pw_env_type), POINTER                         :: pw_env
    2296        12679 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
    2297              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    2298              :       TYPE(pw_r3d_rs_type)                               :: wf_r
    2299        12679 :       TYPE(pw_r3d_rs_type), DIMENSION(:), POINTER        :: rho_r
    2300              :       TYPE(qs_charges_type), POINTER                     :: qs_charges
    2301              :       TYPE(qs_energy_type), POINTER                      :: energy
    2302        12679 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2303              :       TYPE(qs_rho_type), POINTER                         :: rho
    2304              :       TYPE(qs_subsys_type), POINTER                      :: subsys
    2305              :       TYPE(scf_control_type), POINTER                    :: scf_control
    2306              :       TYPE(section_vals_type), POINTER                   :: casino_section, dft_section, &
    2307              :                                                             dos_section, input, sprint_section, &
    2308              :                                                             trexio_section
    2309              : 
    2310              : ! TYPE(kpoint_type), POINTER                         :: kpoints
    2311              : 
    2312        12679 :       CALL timeset(routineN, handle)
    2313              : 
    2314        12679 :       NULLIFY (cell, dft_control, pw_env, auxbas_pw_pool, pw_pools, mo_coeff, &
    2315        12679 :                mo_coeff_deriv, mo_eigenvalues, mos, atomic_kind_set, qs_kind_set, &
    2316        12679 :                particle_set, rho, ks_rmpv, matrix_s, scf_control, dft_section, &
    2317        12679 :                molecule_set, input, particles, subsys, rho_r, unoccupied_orbs, &
    2318        12679 :                unoccupied_evals, casino_section, dos_section)
    2319              : 
    2320        12679 :       logger => cp_get_default_logger()
    2321        12679 :       output_unit = cp_logger_get_default_io_unit(logger)
    2322              : 
    2323        12679 :       CPASSERT(ASSOCIATED(qs_env))
    2324              :       CALL get_qs_env(qs_env, &
    2325              :                       dft_control=dft_control, &
    2326              :                       molecule_set=molecule_set, &
    2327              :                       atomic_kind_set=atomic_kind_set, &
    2328              :                       particle_set=particle_set, &
    2329              :                       qs_kind_set=qs_kind_set, &
    2330              :                       admm_env=admm_env, &
    2331              :                       scf_control=scf_control, &
    2332              :                       input=input, &
    2333              :                       cell=cell, &
    2334        12679 :                       subsys=subsys)
    2335        12679 :       CALL qs_subsys_get(subsys, particles=particles)
    2336        12679 :       CALL get_qs_env(qs_env, rho=rho)
    2337        12679 :       CALL qs_rho_get(rho, rho_r=rho_r)
    2338              : 
    2339              :       ! k points
    2340        12679 :       CALL get_qs_env(qs_env, do_kpoints=do_kpoints)
    2341              : 
    2342              :       ! Write last MO information to output file if requested
    2343        12679 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    2344        12679 :       IF (.NOT. qs_env%run_rtp) THEN
    2345        12331 :          CALL qs_scf_write_mos(qs_env, scf_env, final_mos=.TRUE.)
    2346        12331 :          trexio_section => section_vals_get_subs_vals(dft_section, "PRINT%TREXIO")
    2347        12331 :          CALL section_vals_get(trexio_section, explicit=explicit)
    2348        12331 :          IF (explicit) THEN
    2349           10 :             CALL write_trexio(qs_env, trexio_section)
    2350              :          END IF
    2351        12331 :          casino_section => section_vals_get_subs_vals(dft_section, "PRINT%CASINO")
    2352        12331 :          CALL section_vals_get(casino_section, explicit=explicit)
    2353        12331 :          IF (explicit) THEN
    2354           10 :             CALL write_casino(qs_env, casino_section)
    2355              :          END IF
    2356        12331 :          sprint_section => section_vals_get_subs_vals(dft_section, "PRINT%MO_MOLDEN")
    2357        12331 :          defer_molden = .FALSE.
    2358        12331 :          IF (.NOT. do_kpoints) THEN
    2359        11639 :             CALL get_qs_env(qs_env, mos=mos, matrix_ks=ks_rmpv)
    2360        11639 :             CALL write_dm_binary_restart(mos, dft_section, ks_rmpv)
    2361              :             ! Check if molden write should be deferred for OT unoccupied orbitals
    2362        11639 :             CALL section_vals_val_get(sprint_section, "NLUMO", i_val=nlumo_molden)
    2363        11639 :             IF (nlumo_molden /= 0 .AND. PRESENT(scf_env)) THEN
    2364            0 :                IF (scf_env%method == ot_method_nr) defer_molden = .TRUE.
    2365              :             END IF
    2366              :             IF (.NOT. defer_molden) THEN
    2367              :                CALL write_mos_molden(mos, qs_kind_set, particle_set, sprint_section, cell=cell, &
    2368        11639 :                                      qs_env=qs_env, calc_energies=.TRUE.)
    2369              :             END IF
    2370              :             ! Write Chargemol .wfx
    2371        11639 :             IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%CHARGEMOL"), &
    2372              :                       cp_p_file)) THEN
    2373            2 :                CALL write_wfx(qs_env, dft_section)
    2374              :             END IF
    2375              :          ELSE
    2376          692 :             IF (BTEST(cp_print_key_should_output(logger%iter_info, sprint_section, ""), cp_p_file)) THEN
    2377            0 :                CPWARN("Molden format output is not possible for k-point calculations.")
    2378              :             END IF
    2379          692 :             IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%CHARGEMOL"), &
    2380              :                       cp_p_file)) THEN
    2381            0 :                CPWARN("Chargemol .wfx format output is not possible for k-point calculations.")
    2382              :             END IF
    2383              :          END IF
    2384              : 
    2385              :          ! K-point MO wavefunction dump
    2386        12331 :          IF (BTEST(cp_print_key_should_output(logger%iter_info, dft_section, "PRINT%MO_KP"), &
    2387              :                    cp_p_file)) THEN
    2388            0 :             IF (do_kpoints) THEN
    2389              :                CALL write_kpoint_mo_data(qs_env, &
    2390            0 :                                          section_vals_get_subs_vals(input, "DFT%PRINT%MO_KP"))
    2391              :             ELSE
    2392            0 :                CPWARN("MO_KP is only available for k-point calculations, ignored for Gamma-only")
    2393              :             END IF
    2394              :          END IF
    2395              : 
    2396        12331 :          dos_section => section_vals_get_subs_vals(dft_section, "PRINT%DOS")
    2397        12331 :          do_dos = BTEST(cp_print_key_should_output(logger%iter_info, dos_section), cp_p_file)
    2398        12331 :          CALL get_dos_pdos_flags(dos_section, do_dos, do_projected_dos, do_pdos, do_curve)
    2399              : 
    2400              :          ! For OT calculations, collect the largest request for additional unoccupied
    2401              :          ! orbitals among DOS, PDOS, and Molden, and generate them only once.
    2402        12331 :          nlumo_required = 0
    2403        12331 :          IF (.NOT. do_kpoints .AND. PRESENT(scf_env)) THEN
    2404        11639 :             IF (scf_env%method == ot_method_nr) THEN
    2405         4509 :                IF (do_dos) THEN
    2406            8 :                   CALL section_vals_val_get(dft_section, "PRINT%DOS%NLUMO", i_val=nlumo_dos)
    2407            8 :                   IF (nlumo_dos == -1) THEN
    2408            0 :                      nlumo_required = -1
    2409              :                   ELSE IF (nlumo_required /= -1) THEN
    2410            8 :                      nlumo_required = MAX(nlumo_required, nlumo_dos)
    2411              :                   END IF
    2412              :                END IF
    2413              : 
    2414         4509 :                IF (defer_molden) THEN
    2415            0 :                   IF (nlumo_molden == -1) THEN
    2416            0 :                      nlumo_required = -1
    2417            0 :                   ELSE IF (nlumo_required /= -1) THEN
    2418            0 :                      nlumo_required = MAX(nlumo_required, nlumo_molden)
    2419              :                   END IF
    2420              :                END IF
    2421         4509 :                IF (nlumo_required /= 0) THEN
    2422            8 :                   ALLOCATE (unoccupied_orbs(dft_control%nspins))
    2423            8 :                   ALLOCATE (unoccupied_evals(dft_control%nspins))
    2424              :                   CALL make_lumo_gpw(qs_env, scf_env, unoccupied_orbs, unoccupied_evals, &
    2425            2 :                                      nlumo_required, nlumos)
    2426              :                END IF
    2427              : 
    2428         4509 :                IF (do_dos .OR. do_projected_dos) THEN
    2429           16 :                   DO ispin = 1, dft_control%nspins
    2430              :                      ! With ADMM, temporarily modify the Kohn-Sham matrix while updating the
    2431              :                      ! eigenvalues and rotating the occupied OT subspace.
    2432            8 :                      IF (dft_control%do_admm) THEN
    2433            0 :                         CALL admm_correct_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
    2434              :                      END IF
    2435              :                      CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, &
    2436            8 :                                      eigenvalues=mo_eigenvalues)
    2437            8 :                      IF (ASSOCIATED(qs_env%mo_derivs)) THEN
    2438            8 :                         mo_coeff_deriv => qs_env%mo_derivs(ispin)%matrix
    2439              :                      ELSE
    2440            0 :                         mo_coeff_deriv => NULL()
    2441              :                      END IF
    2442              :                      CALL calculate_subspace_eigenvalues(mo_coeff, ks_rmpv(ispin)%matrix, mo_eigenvalues, &
    2443              :                                                          do_rotation=.TRUE., &
    2444            8 :                                                          co_rotate_dbcsr=mo_coeff_deriv)
    2445            8 :                      CALL set_mo_occupation(mo_set=mos(ispin))
    2446         4517 :                      IF (dft_control%do_admm) THEN
    2447            0 :                         CALL admm_uncorrect_for_eigenvalues(ispin, admm_env, ks_rmpv(ispin)%matrix)
    2448              :                      END IF
    2449              :                   END DO
    2450              :                END IF
    2451              :             END IF
    2452              :          END IF
    2453              : 
    2454        12331 :          IF (defer_molden) THEN
    2455            0 :             IF (ASSOCIATED(unoccupied_orbs)) THEN
    2456            0 :                IF (output_unit > 0) THEN
    2457              :                   WRITE (output_unit, '(/,T2,A,I6,A)') &
    2458            0 :                      "MO_MOLDEN| Writing ", nlumos, " unoccupied orbitals to molden file"
    2459              :                END IF
    2460              :                CALL write_mos_molden(mos, qs_kind_set, particle_set, sprint_section, cell=cell, &
    2461              :                                      unoccupied_orbs=unoccupied_orbs, &
    2462              :                                      unoccupied_evals=unoccupied_evals, &
    2463            0 :                                      qs_env=qs_env, calc_energies=.TRUE.)
    2464              :             END IF
    2465              :          END IF
    2466              : 
    2467              :          ! DOS printout after the SCF cycle is completed
    2468        12331 :          IF (do_dos) THEN
    2469           64 :             IF (do_kpoints) THEN
    2470            4 :                CALL calculate_dos_kp(qs_env, dft_section)
    2471            4 :                IF (do_curve) CALL calculate_dos_kp(qs_env, dft_section, write_curve_output=.TRUE.)
    2472              :             ELSE
    2473           60 :                CALL get_qs_env(qs_env, mos=mos)
    2474           60 :                IF (ASSOCIATED(unoccupied_evals)) THEN
    2475              :                   CALL calculate_dos(mos, dft_section, unoccupied_evals=unoccupied_evals, &
    2476            2 :                                      smearing_enabled=dft_control%smear)
    2477            2 :                   IF (do_curve) CALL calculate_dos(mos, dft_section, unoccupied_evals=unoccupied_evals, &
    2478            0 :                                                    smearing_enabled=dft_control%smear, write_curve_output=.TRUE.)
    2479              :                ELSE
    2480           58 :                   CALL calculate_dos(mos, dft_section, smearing_enabled=dft_control%smear)
    2481           58 :                   IF (do_curve) CALL calculate_dos(mos, dft_section, smearing_enabled=dft_control%smear, &
    2482            0 :                                                    write_curve_output=.TRUE.)
    2483              :                END IF
    2484              :             END IF
    2485              :          END IF
    2486              : 
    2487              :          ! Print projected density-of-states outputs
    2488        12331 :          IF (do_projected_dos) THEN
    2489           22 :             IF (do_kpoints) THEN
    2490              :                CALL calculate_projected_dos_kp(qs_env, dft_section, pdos_print_key="PRINT%DOS", &
    2491            2 :                                                write_pdos=do_pdos, write_pdos_curve=do_curve)
    2492              :             ELSE
    2493              :                CALL get_qs_env(qs_env, &
    2494              :                                mos=mos, &
    2495           20 :                                matrix_ks=ks_rmpv)
    2496           40 :                DO ispin = 1, dft_control%nspins
    2497           40 :                   IF (dft_control%nspins == 2) THEN
    2498            0 :                      IF (ASSOCIATED(unoccupied_orbs)) THEN
    2499              :                         CALL calculate_projected_dos(mos(ispin), atomic_kind_set, &
    2500              :                                                      qs_kind_set, particle_set, qs_env, dft_section, ispin=ispin, &
    2501              :                                                      unoccupied_orbs=unoccupied_orbs(ispin), &
    2502              :                                                      unoccupied_evals=unoccupied_evals(ispin), &
    2503            0 :                                                      pdos_print_key="PRINT%DOS", write_pdos=do_pdos, write_pdos_curve=do_curve)
    2504              :                      ELSE
    2505              :                         CALL calculate_projected_dos(mos(ispin), atomic_kind_set, &
    2506              :                                                      qs_kind_set, particle_set, qs_env, dft_section, ispin=ispin, &
    2507            0 :                                                      pdos_print_key="PRINT%DOS", write_pdos=do_pdos, write_pdos_curve=do_curve)
    2508              :                      END IF
    2509              :                   ELSE
    2510           20 :                      IF (ASSOCIATED(unoccupied_orbs)) THEN
    2511              :                         CALL calculate_projected_dos(mos(ispin), atomic_kind_set, &
    2512              :                                                      qs_kind_set, particle_set, qs_env, dft_section, &
    2513              :                                                      unoccupied_orbs=unoccupied_orbs(ispin), &
    2514              :                                                      unoccupied_evals=unoccupied_evals(ispin), &
    2515            2 :                                                      pdos_print_key="PRINT%DOS", write_pdos=do_pdos, write_pdos_curve=do_curve)
    2516              :                      ELSE
    2517              :                         CALL calculate_projected_dos(mos(ispin), atomic_kind_set, &
    2518              :                                                      qs_kind_set, particle_set, qs_env, dft_section, &
    2519           18 :                                                      pdos_print_key="PRINT%DOS", write_pdos=do_pdos, write_pdos_curve=do_curve)
    2520              :                      END IF
    2521              :                   END IF
    2522              :                END DO
    2523              :             END IF
    2524              :          END IF
    2525        12331 :          IF (ASSOCIATED(unoccupied_orbs)) THEN
    2526            4 :             DO ispin = 1, dft_control%nspins
    2527            2 :                DEALLOCATE (unoccupied_evals(ispin)%array)
    2528            4 :                CALL cp_fm_release(unoccupied_orbs(ispin))
    2529              :             END DO
    2530            2 :             DEALLOCATE (unoccupied_evals)
    2531            2 :             DEALLOCATE (unoccupied_orbs)
    2532              :          END IF
    2533              :       END IF
    2534              : 
    2535              :       ! Integrated absolute spin density and spin contamination ***
    2536        12679 :       IF (dft_control%nspins == 2) THEN
    2537         2558 :          total_spin_dens = 0.0_dp
    2538         2558 :          total_abs_spin_dens = 0.0_dp
    2539         2558 :          IF (dft_control%qs_control%gapw) THEN
    2540          368 :             CALL get_qs_env(qs_env, qs_charges=qs_charges)
    2541              :             total_spin_dens = qs_charges%total_rho_hard_spin - &
    2542          368 :                               qs_charges%total_rho_soft_spin
    2543              :             total_abs_spin_dens = qs_charges%total_rho_hard_abs_spin - &
    2544          368 :                                   qs_charges%total_rho_soft_abs_spin
    2545              :          END IF
    2546         2558 :          CALL get_qs_env(qs_env, mos=mos)
    2547         2558 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    2548              :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    2549         2558 :                          pw_pools=pw_pools)
    2550         2558 :          CALL auxbas_pw_pool%create_pw(wf_r)
    2551         2558 :          CALL pw_copy(rho_r(1), wf_r)
    2552         2558 :          CALL pw_axpy(rho_r(2), wf_r, alpha=-1._dp)
    2553         2558 :          total_spin_dens = total_spin_dens + pw_integrate_function(wf_r)
    2554         2558 :          IF (output_unit > 0) WRITE (UNIT=output_unit, FMT='(/,(T3,A,T61,F20.10))') &
    2555         1302 :             "Integrated spin density: ", total_spin_dens
    2556         2558 :          total_abs_spin_dens = total_abs_spin_dens + pw_integrate_function(wf_r, oprt="ABS")
    2557         2558 :          IF (output_unit > 0) WRITE (UNIT=output_unit, FMT='((T3,A,T61,F20.10))') &
    2558         1302 :             "Integrated absolute spin density: ", total_abs_spin_dens
    2559         2558 :          CALL auxbas_pw_pool%give_back_pw(wf_r)
    2560              :          !
    2561              :          ! XXX Fix Me XXX
    2562              :          ! should be extended to the case where added MOs are present
    2563              :          ! should be extended to the k-point case
    2564              :          !
    2565         2558 :          IF (.NOT. do_kpoints) THEN
    2566         2472 :             all_equal = .TRUE.
    2567         7416 :             DO ispin = 1, dft_control%nspins
    2568              :                CALL get_mo_set(mo_set=mos(ispin), &
    2569              :                                occupation_numbers=occupation_numbers, &
    2570              :                                homo=homo, &
    2571              :                                nmo=nmo, &
    2572         4944 :                                maxocc=maxocc)
    2573         7416 :                IF (nmo > 0) THEN
    2574              :                   all_equal = all_equal .AND. &
    2575              :                               (ALL(occupation_numbers(1:homo) == maxocc) .AND. &
    2576        26502 :                                ALL(occupation_numbers(homo + 1:nmo) == 0.0_dp))
    2577              :                END IF
    2578              :             END DO
    2579         2472 :             IF (all_equal) THEN
    2580              :                CALL get_qs_env(qs_env=qs_env, &
    2581              :                                matrix_s=matrix_s, &
    2582         2352 :                                energy=energy)
    2583              :                CALL compute_s_square(mos=mos, matrix_s=matrix_s, s_square=s_square, &
    2584         2352 :                                      s_square_ideal=s_square_ideal)
    2585         2352 :                IF (output_unit > 0) WRITE (UNIT=output_unit, FMT='(T3,A,T51,2F15.6)') &
    2586         1199 :                   "Ideal and single determinant S**2 : ", s_square_ideal, s_square
    2587         2352 :                energy%s_square = s_square
    2588              :             END IF
    2589              :          END IF
    2590              :       END IF
    2591              : 
    2592        12679 :       CALL timestop(handle)
    2593              : 
    2594        12679 :    END SUBROUTINE write_mo_dependent_results
    2595              : 
    2596              : ! **************************************************************************************************
    2597              : !> \brief Write QS results always available (if switched on through the print_keys)
    2598              : !>        Can be called from ls_scf
    2599              : !> \param qs_env the qs_env in which the qs_env lives
    2600              : ! **************************************************************************************************
    2601        13695 :    SUBROUTINE write_mo_free_results(qs_env)
    2602              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2603              : 
    2604              :       CHARACTER(len=*), PARAMETER :: routineN = 'write_mo_free_results'
    2605              :       CHARACTER(len=1), DIMENSION(3), PARAMETER          :: cdir = ["x", "y", "z"]
    2606              : 
    2607              :       CHARACTER(LEN=2)                                   :: element_symbol
    2608              :       CHARACTER(LEN=default_path_length)                 :: filename, mpi_filename, my_pos_cube, &
    2609              :                                                             my_pos_voro
    2610              :       CHARACTER(LEN=default_string_length)               :: name, print_density
    2611              :       INTEGER :: after, handle, i, iat, id, ikind, img, iso, ispin, iw, l, n_rep_hf, natom, nd(3), &
    2612              :          ngto, niso, nkind, np, nr, output_unit, print_level, should_print_bqb, should_print_voro, &
    2613              :          unit_nr, unit_nr_voro
    2614              :       LOGICAL :: append_cube, append_voro, do_hfx, do_kpoints, mpi_io, omit_headers, print_it, &
    2615              :          rho_r_valid, voro_print_txt, write_ks, write_xc, xrd_interface
    2616              :       REAL(KIND=dp)                                      :: norm_factor, q_max, rho_hard, rho_soft, &
    2617              :                                                             rho_total, rho_total_rspace, udvol, &
    2618              :                                                             volume
    2619        13695 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: zcharge
    2620        13695 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: bfun
    2621        13695 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: aedens, ccdens, ppdens
    2622              :       REAL(KIND=dp), DIMENSION(3)                        :: checksum_hr, dr
    2623        13695 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: my_Q0
    2624        13695 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2625              :       TYPE(atomic_kind_type), POINTER                    :: atomic_kind
    2626              :       TYPE(cell_type), POINTER                           :: cell
    2627              :       TYPE(cp_logger_type), POINTER                      :: logger
    2628              :       TYPE(cp_section_key)                               :: e_density_section
    2629        13695 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_hr
    2630        13695 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: ks_rmpv, matrix_s, matrix_vxc, rho_ao
    2631              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2632              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    2633              :       TYPE(iao_env_type)                                 :: iao_env
    2634              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2635              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    2636        13695 :          POINTER                                         :: sab_orb, sap_ppnl
    2637              :       TYPE(particle_list_type), POINTER                  :: particles
    2638        13695 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2639              :       TYPE(pw_c1d_gs_type)                               :: aux_g, rho_elec_gspace
    2640              :       TYPE(pw_c1d_gs_type), POINTER                      :: rho0_s_gs, rho_core, rhoz_cneo_s_gs
    2641              :       TYPE(pw_env_type), POINTER                         :: pw_env
    2642        13695 :       TYPE(pw_pool_p_type), DIMENSION(:), POINTER        :: pw_pools
    2643              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    2644              :       TYPE(pw_r3d_rs_type)                               :: aux_r, rho_elec_rspace, wf_r
    2645        13695 :       TYPE(pw_r3d_rs_type), DIMENSION(:), POINTER        :: rho_r
    2646              :       TYPE(pw_r3d_rs_type), POINTER                      :: mb_rho, v_hartree_rspace, vee
    2647        13695 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2648              :       TYPE(qs_kind_type), POINTER                        :: qs_kind
    2649              :       TYPE(qs_rho_type), POINTER                         :: rho
    2650              :       TYPE(qs_subsys_type), POINTER                      :: subsys
    2651              :       TYPE(rho0_mpole_type), POINTER                     :: rho0_mpole
    2652        13695 :       TYPE(rho_atom_type), DIMENSION(:), POINTER         :: rho_atom_set
    2653              :       TYPE(rho_atom_type), POINTER                       :: rho_atom
    2654              :       TYPE(section_vals_type), POINTER                   :: dft_section, hfx_section, input, &
    2655              :                                                             print_key, print_key_bqb, &
    2656              :                                                             print_key_voro, xc_section
    2657              : 
    2658        13695 :       CALL timeset(routineN, handle)
    2659        13695 :       NULLIFY (cell, dft_control, pw_env, auxbas_pw_pool, pw_pools, hfx_section, &
    2660        13695 :                atomic_kind_set, qs_kind_set, particle_set, rho, ks_rmpv, rho_ao, rho_r, &
    2661        13695 :                dft_section, xc_section, input, particles, subsys, matrix_vxc, v_hartree_rspace, &
    2662        13695 :                vee, matrix_hr, matrix_s, sab_orb, sap_ppnl)
    2663              : 
    2664        13695 :       logger => cp_get_default_logger()
    2665        13695 :       output_unit = cp_logger_get_default_io_unit(logger)
    2666              : 
    2667        13695 :       CPASSERT(ASSOCIATED(qs_env))
    2668              :       CALL get_qs_env(qs_env, &
    2669              :                       atomic_kind_set=atomic_kind_set, &
    2670              :                       qs_kind_set=qs_kind_set, &
    2671              :                       nkind=nkind, &
    2672              :                       natom=natom, &
    2673              :                       particle_set=particle_set, &
    2674              :                       cell=cell, &
    2675              :                       para_env=para_env, &
    2676              :                       dft_control=dft_control, &
    2677              :                       input=input, &
    2678              :                       do_kpoints=do_kpoints, &
    2679              :                       subsys=subsys, &
    2680              :                       matrix_s_kp=matrix_s, &
    2681              :                       sab_orb=sab_orb, &
    2682        13695 :                       sap_ppnl=sap_ppnl)
    2683        13695 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    2684        13695 :       CALL qs_subsys_get(subsys, particles=particles)
    2685              : 
    2686        13695 :       CALL get_qs_env(qs_env, rho=rho)
    2687        13695 :       CALL qs_rho_get(rho, rho_r=rho_r)
    2688              : 
    2689        13695 :       CALL get_effective_core_charges(qs_env, zcharge)
    2690              : 
    2691              :       ! Print the total density (electronic + core charge)
    2692        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    2693              :                                            "DFT%PRINT%TOT_DENSITY_CUBE"), cp_p_file)) THEN
    2694           82 :          NULLIFY (rho_core, rho0_s_gs, rhoz_cneo_s_gs)
    2695           82 :          append_cube = section_get_lval(input, "DFT%PRINT%TOT_DENSITY_CUBE%APPEND")
    2696           82 :          my_pos_cube = "REWIND"
    2697           82 :          IF (append_cube) THEN
    2698            0 :             my_pos_cube = "APPEND"
    2699              :          END IF
    2700              : 
    2701              :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, rho_core=rho_core, &
    2702           82 :                          rho0_s_gs=rho0_s_gs, rhoz_cneo_s_gs=rhoz_cneo_s_gs)
    2703              :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    2704           82 :                          pw_pools=pw_pools)
    2705           82 :          CALL auxbas_pw_pool%create_pw(wf_r)
    2706           82 :          IF (dft_control%qs_control%gapw) THEN
    2707            0 :             IF (dft_control%qs_control%gapw_control%nopaw_as_gpw) THEN
    2708            0 :                CALL pw_axpy(rho_core, rho0_s_gs)
    2709            0 :                IF (ASSOCIATED(rhoz_cneo_s_gs)) THEN
    2710            0 :                   CALL pw_axpy(rhoz_cneo_s_gs, rho0_s_gs)
    2711              :                END IF
    2712            0 :                CALL pw_transfer(rho0_s_gs, wf_r)
    2713            0 :                CALL pw_axpy(rho_core, rho0_s_gs, -1.0_dp)
    2714            0 :                IF (ASSOCIATED(rhoz_cneo_s_gs)) THEN
    2715            0 :                   CALL pw_axpy(rhoz_cneo_s_gs, rho0_s_gs, -1.0_dp)
    2716              :                END IF
    2717              :             ELSE
    2718            0 :                IF (ASSOCIATED(rhoz_cneo_s_gs)) THEN
    2719            0 :                   CALL pw_axpy(rhoz_cneo_s_gs, rho0_s_gs)
    2720              :                END IF
    2721            0 :                CALL pw_transfer(rho0_s_gs, wf_r)
    2722            0 :                IF (ASSOCIATED(rhoz_cneo_s_gs)) THEN
    2723            0 :                   CALL pw_axpy(rhoz_cneo_s_gs, rho0_s_gs, -1.0_dp)
    2724              :                END IF
    2725              :             END IF
    2726              :          ELSE
    2727           82 :             CALL pw_transfer(rho_core, wf_r)
    2728              :          END IF
    2729          164 :          DO ispin = 1, dft_control%nspins
    2730          164 :             CALL pw_axpy(rho_r(ispin), wf_r)
    2731              :          END DO
    2732           82 :          filename = "TOTAL_DENSITY"
    2733           82 :          mpi_io = .TRUE.
    2734              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%TOT_DENSITY_CUBE", &
    2735              :                                         extension=".cube", middle_name=TRIM(filename), file_position=my_pos_cube, &
    2736           82 :                                         log_filename=.FALSE., mpi_io=mpi_io)
    2737              :          CALL cp_pw_to_cube(wf_r, unit_nr, "TOTAL DENSITY", &
    2738              :                             particles=particles, zeff=zcharge, &
    2739              :                             stride=section_get_ivals(dft_section, "PRINT%TOT_DENSITY_CUBE%STRIDE"), &
    2740              :                             max_file_size_mb=section_get_rval(dft_section, "PRINT%TOT_DENSITY_CUBE%MAX_FILE_SIZE_MB"), &
    2741           82 :                             mpi_io=mpi_io)
    2742              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2743           82 :                                            "DFT%PRINT%TOT_DENSITY_CUBE", mpi_io=mpi_io)
    2744           82 :          CALL auxbas_pw_pool%give_back_pw(wf_r)
    2745              :       END IF
    2746              : 
    2747        13695 :       e_density_section = cube_or_openpmd(input, str_e_density_cubes, str_e_density_openpmd, logger)
    2748              : 
    2749              :       ! Write cube file with electron density
    2750        13695 :       IF (e_density_section%do_output) THEN
    2751              :          CALL section_vals_val_get(dft_section, &
    2752              :                                    keyword_name=e_density_section%concat_to_relative("%DENSITY_INCLUDE"), &
    2753          154 :                                    c_val=print_density)
    2754              :          print_density = TRIM(print_density)
    2755              :          ! For openPMD, refer to access modes instead of APPEND key
    2756          154 :          IF (e_density_section%grid_output == grid_output_cubes) THEN
    2757          154 :             append_cube = section_get_lval(input, e_density_section%concat_to_absolute("%APPEND"))
    2758              :          END IF
    2759          154 :          my_pos_cube = "REWIND"
    2760          154 :          IF (append_cube) THEN
    2761            0 :             my_pos_cube = "APPEND"
    2762              :          END IF
    2763              :          ! Write the info on core densities for the interface between cp2k and the XRD code
    2764              :          ! together with the valence density they are used to compute the form factor (Fourier transform)
    2765          154 :          IF (e_density_section%grid_output == grid_output_cubes) THEN
    2766          154 :             xrd_interface = section_get_lval(input, e_density_section%concat_to_absolute("%XRD_INTERFACE"))
    2767              :          ELSE
    2768              :             ! Unimplemented for openPMD, since this does not use the regular routines
    2769              :             xrd_interface = .FALSE.
    2770              :          END IF
    2771              : 
    2772          154 :          IF (xrd_interface) THEN
    2773              :             !cube file only contains soft density (GAPW)
    2774            2 :             IF (dft_control%qs_control%gapw) print_density = "SOFT_DENSITY"
    2775              : 
    2776            2 :             filename = "ELECTRON_DENSITY"
    2777              :             unit_nr = cp_print_key_unit_nr(logger, input, e_density_section%absolute_section_key, &
    2778              :                                            extension=".xrd", middle_name=TRIM(filename), &
    2779            2 :                                            file_position=my_pos_cube, log_filename=.FALSE.)
    2780            2 :             ngto = section_get_ival(input, e_density_section%concat_to_absolute("%NGAUSS"))
    2781            2 :             IF (output_unit > 0) THEN
    2782            1 :                INQUIRE (UNIT=unit_nr, NAME=filename)
    2783              :                WRITE (UNIT=output_unit, FMT="(/,T2,A,/,/,T2,A)") &
    2784            1 :                   "The electron density (atomic part) is written to the file:", &
    2785            2 :                   TRIM(filename)
    2786              :             END IF
    2787              : 
    2788            2 :             xc_section => section_vals_get_subs_vals(input, "DFT%XC")
    2789            2 :             nkind = SIZE(atomic_kind_set)
    2790            2 :             IF (unit_nr > 0) THEN
    2791            1 :                WRITE (unit_nr, *) "Atomic (core) densities"
    2792            1 :                WRITE (unit_nr, *) "Unit cell"
    2793            1 :                WRITE (unit_nr, FMT="(3F20.12)") cell%hmat(1, 1), cell%hmat(1, 2), cell%hmat(1, 3)
    2794            1 :                WRITE (unit_nr, FMT="(3F20.12)") cell%hmat(2, 1), cell%hmat(2, 2), cell%hmat(2, 3)
    2795            1 :                WRITE (unit_nr, FMT="(3F20.12)") cell%hmat(3, 1), cell%hmat(3, 2), cell%hmat(3, 3)
    2796            1 :                WRITE (unit_nr, *) "Atomic types"
    2797            1 :                WRITE (unit_nr, *) nkind
    2798              :             END IF
    2799              :             ! calculate atomic density and core density
    2800           16 :             ALLOCATE (ppdens(ngto, 2, nkind), aedens(ngto, 2, nkind), ccdens(ngto, 2, nkind))
    2801            6 :             DO ikind = 1, nkind
    2802            4 :                atomic_kind => atomic_kind_set(ikind)
    2803            4 :                qs_kind => qs_kind_set(ikind)
    2804            4 :                CALL get_atomic_kind(atomic_kind, name=name, element_symbol=element_symbol)
    2805              :                CALL calculate_atomic_density(ppdens(:, :, ikind), atomic_kind, qs_kind, ngto, &
    2806            4 :                                              iunit=output_unit, confine=.TRUE.)
    2807              :                CALL calculate_atomic_density(aedens(:, :, ikind), atomic_kind, qs_kind, ngto, &
    2808            4 :                                              iunit=output_unit, allelectron=.TRUE., confine=.TRUE.)
    2809           52 :                ccdens(:, 1, ikind) = aedens(:, 1, ikind)
    2810           52 :                ccdens(:, 2, ikind) = 0._dp
    2811              :                CALL project_function_a(ccdens(1:ngto, 2, ikind), ccdens(1:ngto, 1, ikind), &
    2812            4 :                                        ppdens(1:ngto, 2, ikind), ppdens(1:ngto, 1, ikind), 0)
    2813           52 :                ccdens(:, 2, ikind) = aedens(:, 2, ikind) - ccdens(:, 2, ikind)
    2814            4 :                IF (unit_nr > 0) THEN
    2815            2 :                   WRITE (unit_nr, FMT="(I6,A10,A20)") ikind, TRIM(element_symbol), TRIM(name)
    2816            2 :                   WRITE (unit_nr, FMT="(I6)") ngto
    2817            2 :                   WRITE (unit_nr, *) "   Total density"
    2818           26 :                   WRITE (unit_nr, FMT="(2G24.12)") (aedens(i, 1, ikind), aedens(i, 2, ikind), i=1, ngto)
    2819            2 :                   WRITE (unit_nr, *) "    Core density"
    2820           26 :                   WRITE (unit_nr, FMT="(2G24.12)") (ccdens(i, 1, ikind), ccdens(i, 2, ikind), i=1, ngto)
    2821              :                END IF
    2822            6 :                NULLIFY (atomic_kind)
    2823              :             END DO
    2824              : 
    2825            2 :             IF (dft_control%qs_control%gapw) THEN
    2826            2 :                CALL get_qs_env(qs_env=qs_env, rho_atom_set=rho_atom_set)
    2827              : 
    2828            2 :                IF (unit_nr > 0) THEN
    2829            1 :                   WRITE (unit_nr, *) "Coordinates and GAPW density"
    2830              :                END IF
    2831            2 :                np = particles%n_els
    2832            6 :                DO iat = 1, np
    2833            4 :                   CALL get_atomic_kind(particles%els(iat)%atomic_kind, kind_number=ikind)
    2834            4 :                   CALL get_qs_kind(qs_kind_set(ikind), grid_atom=grid_atom)
    2835            4 :                   rho_atom => rho_atom_set(iat)
    2836            4 :                   IF (ASSOCIATED(rho_atom%rho_rad_h(1)%r_coef)) THEN
    2837            2 :                      nr = SIZE(rho_atom%rho_rad_h(1)%r_coef, 1)
    2838            2 :                      niso = SIZE(rho_atom%rho_rad_h(1)%r_coef, 2)
    2839              :                   ELSE
    2840            2 :                      nr = 0
    2841            2 :                      niso = 0
    2842              :                   END IF
    2843            4 :                   CALL para_env%sum(nr)
    2844            4 :                   CALL para_env%sum(niso)
    2845              : 
    2846           16 :                   ALLOCATE (bfun(nr, niso))
    2847            4 :                   bfun = 0._dp
    2848            8 :                   DO ispin = 1, dft_control%nspins
    2849            8 :                      IF (ASSOCIATED(rho_atom%rho_rad_h(1)%r_coef)) THEN
    2850          920 :                         bfun(:, :) = bfun + rho_atom%rho_rad_h(ispin)%r_coef - rho_atom%rho_rad_s(ispin)%r_coef
    2851              :                      END IF
    2852              :                   END DO
    2853            4 :                   CALL para_env%sum(bfun)
    2854           52 :                   ccdens(:, 1, ikind) = ppdens(:, 1, ikind)
    2855           52 :                   ccdens(:, 2, ikind) = 0._dp
    2856            4 :                   IF (unit_nr > 0) THEN
    2857            8 :                      WRITE (unit_nr, '(I10,I5,3f12.6)') iat, ikind, particles%els(iat)%r
    2858              :                   END IF
    2859           40 :                   DO iso = 1, niso
    2860           36 :                      l = indso(1, iso)
    2861           36 :                      CALL project_function_b(ccdens(:, 2, ikind), ccdens(:, 1, ikind), bfun(:, iso), grid_atom, l)
    2862           40 :                      IF (unit_nr > 0) THEN
    2863           18 :                         WRITE (unit_nr, FMT="(3I6)") iso, l, ngto
    2864          234 :                         WRITE (unit_nr, FMT="(2G24.12)") (ccdens(i, 1, ikind), ccdens(i, 2, ikind), i=1, ngto)
    2865              :                      END IF
    2866              :                   END DO
    2867           10 :                   DEALLOCATE (bfun)
    2868              :                END DO
    2869              :             ELSE
    2870            0 :                IF (unit_nr > 0) THEN
    2871            0 :                   WRITE (unit_nr, *) "Coordinates"
    2872            0 :                   np = particles%n_els
    2873            0 :                   DO iat = 1, np
    2874            0 :                      CALL get_atomic_kind(particles%els(iat)%atomic_kind, kind_number=ikind)
    2875            0 :                      WRITE (unit_nr, '(I10,I5,3f12.6)') iat, ikind, particles%els(iat)%r
    2876              :                   END DO
    2877              :                END IF
    2878              :             END IF
    2879              : 
    2880            2 :             DEALLOCATE (ppdens, aedens, ccdens)
    2881              : 
    2882              :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    2883            2 :                                               e_density_section%absolute_section_key)
    2884              : 
    2885              :          END IF
    2886          154 :          IF (dft_control%qs_control%gapw .AND. print_density == "TOTAL_DENSITY") THEN
    2887              :             ! total density in g-space not implemented for k-points
    2888            8 :             CPASSERT(.NOT. do_kpoints)
    2889              :             ! Print total electronic density
    2890              :             CALL get_qs_env(qs_env=qs_env, &
    2891            8 :                             pw_env=pw_env)
    2892              :             CALL pw_env_get(pw_env=pw_env, &
    2893              :                             auxbas_pw_pool=auxbas_pw_pool, &
    2894            8 :                             pw_pools=pw_pools)
    2895            8 :             CALL auxbas_pw_pool%create_pw(pw=rho_elec_rspace)
    2896            8 :             CALL pw_zero(rho_elec_rspace)
    2897            8 :             CALL auxbas_pw_pool%create_pw(pw=rho_elec_gspace)
    2898            8 :             CALL pw_zero(rho_elec_gspace)
    2899              :             CALL get_pw_grid_info(pw_grid=rho_elec_gspace%pw_grid, &
    2900              :                                   dr=dr, &
    2901            8 :                                   vol=volume)
    2902           32 :             q_max = SQRT(SUM((pi/dr(:))**2))
    2903              :             CALL calculate_rhotot_elec_gspace(qs_env=qs_env, &
    2904              :                                               auxbas_pw_pool=auxbas_pw_pool, &
    2905              :                                               rhotot_elec_gspace=rho_elec_gspace, &
    2906              :                                               q_max=q_max, &
    2907              :                                               rho_hard=rho_hard, &
    2908            8 :                                               rho_soft=rho_soft)
    2909            8 :             rho_total = rho_hard + rho_soft
    2910              :             CALL get_pw_grid_info(pw_grid=rho_elec_gspace%pw_grid, &
    2911            8 :                                   vol=volume)
    2912              :             ! rhotot pw coefficients are by default scaled by grid volume
    2913              :             ! need to undo this to get proper charge from printed cube
    2914            8 :             CALL pw_scale(rho_elec_gspace, 1.0_dp/volume)
    2915              : 
    2916            8 :             CALL pw_transfer(rho_elec_gspace, rho_elec_rspace)
    2917            8 :             rho_total_rspace = pw_integrate_function(rho_elec_rspace, isign=-1)
    2918            8 :             filename = "TOTAL_ELECTRON_DENSITY"
    2919            8 :             mpi_io = .TRUE.
    2920              :             unit_nr = e_density_section%print_key_unit_nr( &
    2921              :                       logger, &
    2922              :                       input, &
    2923              :                       e_density_section%absolute_section_key, &
    2924              :                       extension=".cube", &
    2925              :                       middle_name=TRIM(filename), &
    2926              :                       file_position=my_pos_cube, &
    2927              :                       log_filename=.FALSE., &
    2928              :                       mpi_io=mpi_io, &
    2929              :                       fout=mpi_filename, &
    2930              :                       openpmd_basename="dft-total-electron-density", &
    2931              :                       openpmd_unit_dimension=openpmd_unit_dimension_density, &
    2932              :                       openpmd_unit_si=openpmd_unit_si_density, &
    2933            8 :                       sim_time=qs_env%sim_time)
    2934            8 :             IF (output_unit > 0) THEN
    2935            4 :                IF (.NOT. mpi_io) THEN
    2936            0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    2937              :                ELSE
    2938            4 :                   filename = mpi_filename
    2939              :                END IF
    2940              :                CALL print_density_output_message(output_unit, "The total electron density", &
    2941            4 :                                                  e_density_section, filename)
    2942              :                WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    2943            4 :                   "q(max) [1/Angstrom]              :", q_max/angstrom, &
    2944            4 :                   "Soft electronic charge (G-space) :", rho_soft, &
    2945            4 :                   "Hard electronic charge (G-space) :", rho_hard, &
    2946            4 :                   "Total electronic charge (G-space):", rho_total, &
    2947            8 :                   "Total electronic charge (R-space):", rho_total_rspace
    2948              :             END IF
    2949              :             CALL e_density_section%write_pw(rho_elec_rspace, unit_nr, "TOTAL ELECTRON DENSITY", &
    2950              :                                             particles=particles, zeff=zcharge, &
    2951            8 :                               stride=section_get_ivals(dft_section, e_density_section%concat_to_relative("%STRIDE")), mpi_io=mpi_io)
    2952              :             CALL e_density_section%print_key_finished_output(unit_nr, logger, input, &
    2953            8 :                                                              e_density_section%absolute_section_key, mpi_io=mpi_io)
    2954              :             ! Print total spin density for spin-polarized systems
    2955            8 :             IF (dft_control%nspins > 1) THEN
    2956            6 :                CALL pw_zero(rho_elec_gspace)
    2957            6 :                CALL pw_zero(rho_elec_rspace)
    2958              :                CALL calculate_rhotot_elec_gspace(qs_env=qs_env, &
    2959              :                                                  auxbas_pw_pool=auxbas_pw_pool, &
    2960              :                                                  rhotot_elec_gspace=rho_elec_gspace, &
    2961              :                                                  q_max=q_max, &
    2962              :                                                  rho_hard=rho_hard, &
    2963              :                                                  rho_soft=rho_soft, &
    2964            6 :                                                  fsign=-1.0_dp)
    2965            6 :                rho_total = rho_hard + rho_soft
    2966              : 
    2967              :                ! rhotot pw coefficients are by default scaled by grid volume
    2968              :                ! need to undo this to get proper charge from printed cube
    2969            6 :                CALL pw_scale(rho_elec_gspace, 1.0_dp/volume)
    2970              : 
    2971            6 :                CALL pw_transfer(rho_elec_gspace, rho_elec_rspace)
    2972            6 :                rho_total_rspace = pw_integrate_function(rho_elec_rspace, isign=-1)
    2973            6 :                filename = "TOTAL_SPIN_DENSITY"
    2974            6 :                mpi_io = .TRUE.
    2975              :                unit_nr = e_density_section%print_key_unit_nr( &
    2976              :                          logger, &
    2977              :                          input, &
    2978              :                          e_density_section%absolute_section_key, &
    2979              :                          extension=".cube", &
    2980              :                          middle_name=TRIM(filename), &
    2981              :                          file_position=my_pos_cube, &
    2982              :                          log_filename=.FALSE., &
    2983              :                          mpi_io=mpi_io, &
    2984              :                          fout=mpi_filename, &
    2985              :                          openpmd_basename="dft-total-spin-density", &
    2986              :                          openpmd_unit_dimension=openpmd_unit_dimension_density, &
    2987              :                          openpmd_unit_si=openpmd_unit_si_density, &
    2988            6 :                          sim_time=qs_env%sim_time)
    2989            6 :                IF (output_unit > 0) THEN
    2990            3 :                   IF (.NOT. mpi_io .AND. e_density_section%grid_output == grid_output_cubes) THEN
    2991            0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    2992              :                   ELSE
    2993            3 :                      filename = mpi_filename
    2994              :                   END IF
    2995              :                   CALL print_density_output_message(output_unit, "The total spin density", &
    2996            3 :                                                     e_density_section, filename)
    2997              :                   WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    2998            3 :                      "q(max) [1/Angstrom]                    :", q_max/angstrom, &
    2999            3 :                      "Soft part of the spin density (G-space):", rho_soft, &
    3000            3 :                      "Hard part of the spin density (G-space):", rho_hard, &
    3001            3 :                      "Total spin density (G-space)           :", rho_total, &
    3002            6 :                      "Total spin density (R-space)           :", rho_total_rspace
    3003              :                END IF
    3004              :                CALL e_density_section%write_pw(rho_elec_rspace, unit_nr, "TOTAL SPIN DENSITY", &
    3005              :                                                particles=particles, zeff=zcharge, &
    3006            6 :                               stride=section_get_ivals(dft_section, e_density_section%concat_to_relative("%STRIDE")), mpi_io=mpi_io)
    3007              :                CALL e_density_section%print_key_finished_output(unit_nr, logger, input, &
    3008            6 :                                                                 e_density_section%absolute_section_key, mpi_io=mpi_io)
    3009              :             END IF
    3010            8 :             CALL auxbas_pw_pool%give_back_pw(rho_elec_gspace)
    3011            8 :             CALL auxbas_pw_pool%give_back_pw(rho_elec_rspace)
    3012              : 
    3013          146 :          ELSE IF (print_density == "SOFT_DENSITY" .OR. .NOT. dft_control%qs_control%gapw) THEN
    3014          142 :             IF (dft_control%nspins > 1) THEN
    3015              :                CALL get_qs_env(qs_env=qs_env, &
    3016           48 :                                pw_env=pw_env)
    3017              :                CALL pw_env_get(pw_env=pw_env, &
    3018              :                                auxbas_pw_pool=auxbas_pw_pool, &
    3019           48 :                                pw_pools=pw_pools)
    3020           48 :                CALL auxbas_pw_pool%create_pw(pw=rho_elec_rspace)
    3021           48 :                CALL pw_copy(rho_r(1), rho_elec_rspace)
    3022           48 :                CALL pw_axpy(rho_r(2), rho_elec_rspace)
    3023           48 :                filename = "ELECTRON_DENSITY"
    3024           48 :                mpi_io = .TRUE.
    3025              :                unit_nr = e_density_section%print_key_unit_nr( &
    3026              :                          logger, &
    3027              :                          input, &
    3028              :                          e_density_section%absolute_section_key, &
    3029              :                          extension=".cube", &
    3030              :                          middle_name=TRIM(filename), &
    3031              :                          file_position=my_pos_cube, &
    3032              :                          log_filename=.FALSE., &
    3033              :                          mpi_io=mpi_io, &
    3034              :                          fout=mpi_filename, &
    3035              :                          openpmd_basename="dft-electron-density", &
    3036              :                          openpmd_unit_dimension=openpmd_unit_dimension_density, &
    3037              :                          openpmd_unit_si=openpmd_unit_si_density, &
    3038           48 :                          sim_time=qs_env%sim_time)
    3039           48 :                IF (output_unit > 0) THEN
    3040           24 :                   IF (.NOT. mpi_io .AND. e_density_section%grid_output == grid_output_cubes) THEN
    3041            0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    3042              :                   ELSE
    3043           24 :                      filename = mpi_filename
    3044              :                   END IF
    3045              :                   CALL print_density_output_message(output_unit, "The sum of alpha and beta density", &
    3046           24 :                                                     e_density_section, filename)
    3047              :                END IF
    3048              :                CALL e_density_section%write_pw(rho_elec_rspace, unit_nr, "SUM OF ALPHA AND BETA DENSITY", &
    3049              :         particles=particles, zeff=zcharge, stride=section_get_ivals(dft_section, e_density_section%concat_to_relative("%STRIDE")), &
    3050           48 :                                                mpi_io=mpi_io)
    3051              :                CALL e_density_section%print_key_finished_output(unit_nr, logger, input, &
    3052           48 :                                                                 e_density_section%absolute_section_key, mpi_io=mpi_io)
    3053           48 :                CALL pw_copy(rho_r(1), rho_elec_rspace)
    3054           48 :                CALL pw_axpy(rho_r(2), rho_elec_rspace, alpha=-1.0_dp)
    3055           48 :                filename = "SPIN_DENSITY"
    3056           48 :                mpi_io = .TRUE.
    3057              :                unit_nr = e_density_section%print_key_unit_nr( &
    3058              :                          logger, &
    3059              :                          input, &
    3060              :                          e_density_section%absolute_section_key, &
    3061              :                          extension=".cube", &
    3062              :                          middle_name=TRIM(filename), &
    3063              :                          file_position=my_pos_cube, &
    3064              :                          log_filename=.FALSE., &
    3065              :                          mpi_io=mpi_io, &
    3066              :                          fout=mpi_filename, &
    3067              :                          openpmd_basename="dft-spin-density", &
    3068              :                          openpmd_unit_dimension=openpmd_unit_dimension_density, &
    3069              :                          openpmd_unit_si=openpmd_unit_si_density, &
    3070           48 :                          sim_time=qs_env%sim_time)
    3071           48 :                IF (output_unit > 0) THEN
    3072           24 :                   IF (.NOT. mpi_io .AND. e_density_section%grid_output == grid_output_cubes) THEN
    3073            0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    3074              :                   ELSE
    3075           24 :                      filename = mpi_filename
    3076              :                   END IF
    3077              :                   CALL print_density_output_message(output_unit, "The spin density", &
    3078           24 :                                                     e_density_section, filename)
    3079              :                END IF
    3080              :                CALL e_density_section%write_pw(rho_elec_rspace, unit_nr, "SPIN DENSITY", &
    3081              :                                                particles=particles, zeff=zcharge, &
    3082           48 :                               stride=section_get_ivals(dft_section, e_density_section%concat_to_relative("%STRIDE")), mpi_io=mpi_io)
    3083              :                CALL e_density_section%print_key_finished_output(unit_nr, logger, input, &
    3084           48 :                                                                 e_density_section%absolute_section_key, mpi_io=mpi_io)
    3085           48 :                CALL auxbas_pw_pool%give_back_pw(rho_elec_rspace)
    3086              :             ELSE
    3087           94 :                filename = "ELECTRON_DENSITY"
    3088           94 :                mpi_io = .TRUE.
    3089              :                unit_nr = e_density_section%print_key_unit_nr( &
    3090              :                          logger, &
    3091              :                          input, &
    3092              :                          e_density_section%absolute_section_key, &
    3093              :                          extension=".cube", &
    3094              :                          middle_name=TRIM(filename), &
    3095              :                          file_position=my_pos_cube, &
    3096              :                          log_filename=.FALSE., &
    3097              :                          mpi_io=mpi_io, &
    3098              :                          fout=mpi_filename, &
    3099              :                          openpmd_basename="dft-electron-density", &
    3100              :                          openpmd_unit_dimension=openpmd_unit_dimension_density, &
    3101              :                          openpmd_unit_si=openpmd_unit_si_density, &
    3102           94 :                          sim_time=qs_env%sim_time)
    3103           94 :                IF (output_unit > 0) THEN
    3104           47 :                   IF (.NOT. mpi_io .AND. e_density_section%grid_output == grid_output_cubes) THEN
    3105            0 :                      INQUIRE (UNIT=unit_nr, NAME=filename)
    3106              :                   ELSE
    3107           47 :                      filename = mpi_filename
    3108              :                   END IF
    3109              :                   CALL print_density_output_message(output_unit, "The electron density", &
    3110           47 :                                                     e_density_section, filename)
    3111              :                END IF
    3112              :                CALL e_density_section%write_pw(rho_r(1), unit_nr, "ELECTRON DENSITY", &
    3113              :                                                particles=particles, zeff=zcharge, &
    3114           94 :                               stride=section_get_ivals(dft_section, e_density_section%concat_to_relative("%STRIDE")), mpi_io=mpi_io)
    3115              :                CALL e_density_section%print_key_finished_output(unit_nr, logger, input, &
    3116           94 :                                                                 e_density_section%absolute_section_key, mpi_io=mpi_io)
    3117              :             END IF ! nspins
    3118              : 
    3119            4 :          ELSE IF (dft_control%qs_control%gapw .AND. print_density == "TOTAL_HARD_APPROX") THEN
    3120            4 :             CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, rho0_mpole=rho0_mpole, natom=natom)
    3121            4 :             CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, pw_pools=pw_pools)
    3122            4 :             CALL auxbas_pw_pool%create_pw(rho_elec_rspace)
    3123              : 
    3124            4 :             NULLIFY (my_Q0)
    3125           12 :             ALLOCATE (my_Q0(natom))
    3126           16 :             my_Q0 = 0.0_dp
    3127              : 
    3128              :             ! (eta/pi)**3: normalization for 3d gaussian of form exp(-eta*r**2)
    3129            4 :             norm_factor = SQRT((rho0_mpole%zet0_h/pi)**3)
    3130              : 
    3131              :             ! store hard part of electronic density in array
    3132           16 :             DO iat = 1, natom
    3133           34 :                my_Q0(iat) = SUM(rho0_mpole%mp_rho(iat)%Q0(1:dft_control%nspins))*norm_factor
    3134              :             END DO
    3135              :             ! multiply coeff with gaussian and put on realspace grid
    3136              :             ! coeff is the gaussian prefactor, eta the gaussian exponent
    3137            4 :             CALL calculate_rho_resp_all(rho_elec_rspace, coeff=my_Q0, natom=natom, eta=rho0_mpole%zet0_h, qs_env=qs_env)
    3138            4 :             rho_hard = pw_integrate_function(rho_elec_rspace, isign=-1)
    3139              : 
    3140            4 :             rho_soft = 0.0_dp
    3141           10 :             DO ispin = 1, dft_control%nspins
    3142            6 :                CALL pw_axpy(rho_r(ispin), rho_elec_rspace)
    3143           10 :                rho_soft = rho_soft + pw_integrate_function(rho_r(ispin), isign=-1)
    3144              :             END DO
    3145              : 
    3146            4 :             rho_total_rspace = rho_soft + rho_hard
    3147              : 
    3148            4 :             filename = "ELECTRON_DENSITY"
    3149            4 :             mpi_io = .TRUE.
    3150              :             unit_nr = e_density_section%print_key_unit_nr( &
    3151              :                       logger, &
    3152              :                       input, &
    3153              :                       e_density_section%absolute_section_key, &
    3154              :                       extension=".cube", &
    3155              :                       middle_name=TRIM(filename), &
    3156              :                       file_position=my_pos_cube, &
    3157              :                       log_filename=.FALSE., &
    3158              :                       mpi_io=mpi_io, &
    3159              :                       fout=mpi_filename, &
    3160              :                       openpmd_basename="dft-electron-density", &
    3161              :                       openpmd_unit_dimension=openpmd_unit_dimension_density, &
    3162              :                       openpmd_unit_si=openpmd_unit_si_density, &
    3163            4 :                       sim_time=qs_env%sim_time)
    3164            4 :             IF (output_unit > 0) THEN
    3165            2 :                IF (.NOT. mpi_io .AND. e_density_section%grid_output == grid_output_cubes) THEN
    3166            0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    3167              :                ELSE
    3168            2 :                   filename = mpi_filename
    3169              :                END IF
    3170              :                CALL print_density_output_message(output_unit, "The electron density", &
    3171            2 :                                                  e_density_section, filename)
    3172              :                WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    3173            2 :                   "Soft electronic charge (R-space) :", rho_soft, &
    3174            2 :                   "Hard electronic charge (R-space) :", rho_hard, &
    3175            4 :                   "Total electronic charge (R-space):", rho_total_rspace
    3176              :             END IF
    3177              :             CALL e_density_section%write_pw(rho_elec_rspace, unit_nr, "ELECTRON DENSITY", &
    3178              :         particles=particles, zeff=zcharge, stride=section_get_ivals(dft_section, e_density_section%concat_to_relative("%STRIDE")), &
    3179            4 :                                             mpi_io=mpi_io)
    3180              :             CALL e_density_section%print_key_finished_output(unit_nr, logger, input, &
    3181            4 :                                                              e_density_section%absolute_section_key, mpi_io=mpi_io)
    3182              : 
    3183              :             !------------
    3184            4 :             IF (dft_control%nspins > 1) THEN
    3185            8 :             DO iat = 1, natom
    3186            8 :                my_Q0(iat) = (rho0_mpole%mp_rho(iat)%Q0(1) - rho0_mpole%mp_rho(iat)%Q0(2))*norm_factor
    3187              :             END DO
    3188            2 :             CALL pw_zero(rho_elec_rspace)
    3189            2 :             CALL calculate_rho_resp_all(rho_elec_rspace, coeff=my_Q0, natom=natom, eta=rho0_mpole%zet0_h, qs_env=qs_env)
    3190            2 :             rho_hard = pw_integrate_function(rho_elec_rspace, isign=-1)
    3191              : 
    3192            2 :             CALL pw_axpy(rho_r(1), rho_elec_rspace)
    3193            2 :             CALL pw_axpy(rho_r(2), rho_elec_rspace, alpha=-1.0_dp)
    3194              :             rho_soft = pw_integrate_function(rho_r(1), isign=-1) &
    3195            2 :                        - pw_integrate_function(rho_r(2), isign=-1)
    3196              : 
    3197            2 :             rho_total_rspace = rho_soft + rho_hard
    3198              : 
    3199            2 :             filename = "SPIN_DENSITY"
    3200            2 :             mpi_io = .TRUE.
    3201              :             unit_nr = e_density_section%print_key_unit_nr( &
    3202              :                       logger, &
    3203              :                       input, &
    3204              :                       e_density_section%absolute_section_key, &
    3205              :                       extension=".cube", &
    3206              :                       middle_name=TRIM(filename), &
    3207              :                       file_position=my_pos_cube, &
    3208              :                       log_filename=.FALSE., &
    3209              :                       mpi_io=mpi_io, &
    3210              :                       fout=mpi_filename, &
    3211              :                       openpmd_basename="dft-spin-density", &
    3212              :                       openpmd_unit_dimension=openpmd_unit_dimension_density, &
    3213              :                       openpmd_unit_si=openpmd_unit_si_density, &
    3214            2 :                       sim_time=qs_env%sim_time)
    3215            2 :             IF (output_unit > 0) THEN
    3216            1 :                IF (.NOT. mpi_io .AND. e_density_section%grid_output == grid_output_cubes) THEN
    3217            0 :                   INQUIRE (UNIT=unit_nr, NAME=filename)
    3218              :                ELSE
    3219            1 :                   filename = mpi_filename
    3220              :                END IF
    3221              :                CALL print_density_output_message(output_unit, "The spin density", &
    3222            1 :                                                  e_density_section, filename)
    3223              :                WRITE (UNIT=output_unit, FMT="(/,(T2,A,F20.10))") &
    3224            1 :                   "Soft part of the spin density          :", rho_soft, &
    3225            1 :                   "Hard part of the spin density          :", rho_hard, &
    3226            2 :                   "Total spin density (R-space)           :", rho_total_rspace
    3227              :             END IF
    3228              :             CALL e_density_section%write_pw(rho_elec_rspace, unit_nr, "SPIN DENSITY", &
    3229              :                                             particles=particles, zeff=zcharge, &
    3230            2 :                               stride=section_get_ivals(dft_section, e_density_section%concat_to_relative("%STRIDE")), mpi_io=mpi_io)
    3231              :             CALL e_density_section%print_key_finished_output(unit_nr, logger, input, &
    3232            2 :                                                              e_density_section%absolute_section_key, mpi_io=mpi_io)
    3233              :             END IF ! nspins
    3234            4 :             CALL auxbas_pw_pool%give_back_pw(rho_elec_rspace)
    3235            4 :             DEALLOCATE (my_Q0)
    3236              :          END IF ! print_density
    3237              :       END IF ! print key
    3238              : 
    3239              :       IF (BTEST(cp_print_key_should_output(logger%iter_info, &
    3240        13695 :                                            dft_section, "PRINT%ENERGY_WINDOWS"), cp_p_file) .AND. .NOT. do_kpoints) THEN
    3241           90 :          CALL energy_windows(qs_env)
    3242              :       END IF
    3243              : 
    3244              :       ! Print the hartree potential
    3245        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3246              :                                            "DFT%PRINT%V_HARTREE_CUBE"), cp_p_file)) THEN
    3247              : 
    3248              :          CALL get_qs_env(qs_env=qs_env, &
    3249              :                          pw_env=pw_env, &
    3250          114 :                          v_hartree_rspace=v_hartree_rspace)
    3251          114 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3252          114 :          CALL auxbas_pw_pool%create_pw(aux_r)
    3253              : 
    3254          114 :          append_cube = section_get_lval(input, "DFT%PRINT%V_HARTREE_CUBE%APPEND")
    3255          114 :          my_pos_cube = "REWIND"
    3256          114 :          IF (append_cube) THEN
    3257            0 :             my_pos_cube = "APPEND"
    3258              :          END IF
    3259          114 :          mpi_io = .TRUE.
    3260          114 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    3261          114 :          CALL pw_env_get(pw_env)
    3262              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%V_HARTREE_CUBE", &
    3263          114 :                                         extension=".cube", middle_name="v_hartree", file_position=my_pos_cube, mpi_io=mpi_io)
    3264          114 :          udvol = 1.0_dp/v_hartree_rspace%pw_grid%dvol
    3265              : 
    3266          114 :          CALL pw_copy(v_hartree_rspace, aux_r)
    3267          114 :          CALL pw_scale(aux_r, udvol)
    3268              : 
    3269              :          CALL cp_pw_to_cube(aux_r, unit_nr, "HARTREE POTENTIAL", particles=particles, zeff=zcharge, &
    3270              :                             stride=section_get_ivals(dft_section, "PRINT%V_HARTREE_CUBE%STRIDE"), &
    3271              :                             max_file_size_mb=section_get_rval(dft_section, "PRINT%V_HARTREE_CUBE%MAX_FILE_SIZE_MB"), &
    3272          114 :                             mpi_io=mpi_io)
    3273              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3274          114 :                                            "DFT%PRINT%V_HARTREE_CUBE", mpi_io=mpi_io)
    3275              : 
    3276          114 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    3277              :       END IF
    3278              : 
    3279              :       ! Print the external potential
    3280        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3281              :                                            "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE"), cp_p_file)) THEN
    3282           86 :          IF (dft_control%apply_external_potential) THEN
    3283            4 :             CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, vee=vee)
    3284            4 :             CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3285            4 :             CALL auxbas_pw_pool%create_pw(aux_r)
    3286              : 
    3287            4 :             append_cube = section_get_lval(input, "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE%APPEND")
    3288            4 :             my_pos_cube = "REWIND"
    3289            4 :             IF (append_cube) THEN
    3290            0 :                my_pos_cube = "APPEND"
    3291              :             END IF
    3292            4 :             mpi_io = .TRUE.
    3293            4 :             CALL pw_env_get(pw_env)
    3294              :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE", &
    3295            4 :                                            extension=".cube", middle_name="ext_pot", file_position=my_pos_cube, mpi_io=mpi_io)
    3296              : 
    3297            4 :             CALL pw_copy(vee, aux_r)
    3298              : 
    3299              :             CALL cp_pw_to_cube(aux_r, unit_nr, "EXTERNAL POTENTIAL", particles=particles, zeff=zcharge, &
    3300              :                                stride=section_get_ivals(dft_section, "PRINT%EXTERNAL_POTENTIAL_CUBE%STRIDE"), &
    3301              :                                max_file_size_mb=section_get_rval(dft_section, "PRINT%EXTERNAL_POTENTIAL_CUBE%MAX_FILE_SIZE_MB"), &
    3302            4 :                                mpi_io=mpi_io)
    3303              :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3304            4 :                                               "DFT%PRINT%EXTERNAL_POTENTIAL_CUBE", mpi_io=mpi_io)
    3305              : 
    3306            4 :             CALL auxbas_pw_pool%give_back_pw(aux_r)
    3307              :          END IF
    3308              :       END IF
    3309              : 
    3310              :       ! Print the Electrical Field Components
    3311        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3312              :                                            "DFT%PRINT%EFIELD_CUBE"), cp_p_file)) THEN
    3313              : 
    3314           82 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    3315           82 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3316           82 :          CALL auxbas_pw_pool%create_pw(aux_r)
    3317           82 :          CALL auxbas_pw_pool%create_pw(aux_g)
    3318              : 
    3319           82 :          append_cube = section_get_lval(input, "DFT%PRINT%EFIELD_CUBE%APPEND")
    3320           82 :          my_pos_cube = "REWIND"
    3321           82 :          IF (append_cube) THEN
    3322            0 :             my_pos_cube = "APPEND"
    3323              :          END IF
    3324              :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, &
    3325           82 :                          v_hartree_rspace=v_hartree_rspace)
    3326           82 :          CALL pw_env_get(pw_env)
    3327           82 :          udvol = 1.0_dp/v_hartree_rspace%pw_grid%dvol
    3328          328 :          DO id = 1, 3
    3329          246 :             mpi_io = .TRUE.
    3330              :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%EFIELD_CUBE", &
    3331              :                                            extension=".cube", middle_name="efield_"//cdir(id), file_position=my_pos_cube, &
    3332          246 :                                            mpi_io=mpi_io)
    3333              : 
    3334          246 :             CALL pw_transfer(v_hartree_rspace, aux_g)
    3335          246 :             nd = 0
    3336          246 :             nd(id) = 1
    3337          246 :             CALL pw_derive(aux_g, nd)
    3338          246 :             CALL pw_transfer(aux_g, aux_r)
    3339          246 :             CALL pw_scale(aux_r, udvol)
    3340              : 
    3341              :             CALL cp_pw_to_cube(aux_r, unit_nr, "ELECTRIC FIELD", particles=particles, zeff=zcharge, &
    3342              :                                stride=section_get_ivals(dft_section, "PRINT%EFIELD_CUBE%STRIDE"), &
    3343              :                                max_file_size_mb=section_get_rval(dft_section, "PRINT%EFIELD_CUBE%MAX_FILE_SIZE_MB"), &
    3344          246 :                                mpi_io=mpi_io)
    3345              :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3346          328 :                                               "DFT%PRINT%EFIELD_CUBE", mpi_io=mpi_io)
    3347              :          END DO
    3348              : 
    3349           82 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    3350           82 :          CALL auxbas_pw_pool%give_back_pw(aux_g)
    3351              :       END IF
    3352              : 
    3353              :       ! Write cube files from the local energy
    3354        13695 :       CALL qs_scf_post_local_energy(input, logger, qs_env)
    3355              : 
    3356              :       ! Write cube files from the local stress tensor
    3357        13695 :       CALL qs_scf_post_local_stress(input, logger, qs_env)
    3358              : 
    3359              :       ! Write cube files from the implicit Poisson solver
    3360        13695 :       CALL qs_scf_post_ps_implicit(input, logger, qs_env)
    3361              : 
    3362              :       ! post SCF finite-volume Kubo transport
    3363        13695 :       CALL qs_scf_post_kubo_transport(qs_env)
    3364              : 
    3365              :       ! post SCF Transport
    3366        13695 :       CALL qs_scf_post_transport(qs_env)
    3367              : 
    3368        13695 :       CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%OMIT_HEADERS", l_val=omit_headers)
    3369              :       ! Write the density matrices
    3370        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3371              :                                            "DFT%PRINT%AO_MATRICES/DENSITY"), cp_p_file)) THEN
    3372              :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/DENSITY", &
    3373            4 :                                    extension=".Log")
    3374            4 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    3375            4 :          CALL qs_rho_get(rho, rho_ao_kp=rho_ao)
    3376            4 :          after = MIN(MAX(after, 1), 16)
    3377            8 :          DO ispin = 1, dft_control%nspins
    3378           12 :             DO img = 1, dft_control%nimages
    3379              :                CALL cp_dbcsr_write_sparse_matrix(rho_ao(ispin, img)%matrix, 4, after, qs_env, &
    3380            8 :                                                  para_env, output_unit=iw, omit_headers=omit_headers)
    3381              :             END DO
    3382              :          END DO
    3383              :          CALL cp_print_key_finished_output(iw, logger, input, &
    3384            4 :                                            "DFT%PRINT%AO_MATRICES/DENSITY")
    3385              :       END IF
    3386              : 
    3387              :       ! Write the Kohn-Sham matrices
    3388              :       write_ks = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3389        13695 :                                                   "DFT%PRINT%AO_MATRICES/KOHN_SHAM_MATRIX"), cp_p_file)
    3390              :       write_xc = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3391        13695 :                                                   "DFT%PRINT%AO_MATRICES/MATRIX_VXC"), cp_p_file)
    3392              :       ! we need to update stuff before writing, potentially computing the matrix_vxc
    3393        13695 :       IF (write_ks .OR. write_xc) THEN
    3394            4 :          IF (write_xc) qs_env%requires_matrix_vxc = .TRUE.
    3395            4 :          CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    3396              :          CALL qs_ks_update_qs_env(qs_env, calculate_forces=.FALSE., &
    3397            4 :                                   just_energy=.FALSE.)
    3398            4 :          IF (write_xc) qs_env%requires_matrix_vxc = .FALSE.
    3399              :       END IF
    3400              : 
    3401              :       ! Write the Kohn-Sham matrices
    3402        13695 :       IF (write_ks) THEN
    3403              :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/KOHN_SHAM_MATRIX", &
    3404            4 :                                    extension=".Log")
    3405            4 :          CALL get_qs_env(qs_env=qs_env, matrix_ks_kp=ks_rmpv)
    3406            4 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    3407            4 :          after = MIN(MAX(after, 1), 16)
    3408            8 :          DO ispin = 1, dft_control%nspins
    3409           12 :             DO img = 1, dft_control%nimages
    3410              :                CALL cp_dbcsr_write_sparse_matrix(ks_rmpv(ispin, img)%matrix, 4, after, qs_env, &
    3411            8 :                                                  para_env, output_unit=iw, omit_headers=omit_headers)
    3412              :             END DO
    3413              :          END DO
    3414              :          CALL cp_print_key_finished_output(iw, logger, input, &
    3415            4 :                                            "DFT%PRINT%AO_MATRICES/KOHN_SHAM_MATRIX")
    3416              :       END IF
    3417              : 
    3418              :       ! write csr matrices
    3419              :       ! matrices in terms of the PAO basis will be taken care of in pao_post_scf.
    3420        13695 :       IF (.NOT. dft_control%qs_control%pao) THEN
    3421        13183 :          CALL write_ks_matrix_csr(qs_env, input)
    3422        13183 :          CALL write_s_matrix_csr(qs_env, input)
    3423        13183 :          CALL write_hcore_matrix_csr(qs_env, input)
    3424        13183 :          CALL write_p_matrix_csr(qs_env, input)
    3425              :       END IF
    3426              : 
    3427              :       ! write adjacency matrix
    3428        13695 :       CALL write_adjacency_matrix(qs_env, input)
    3429              : 
    3430              :       ! Write the xc matrix
    3431        13695 :       IF (write_xc) THEN
    3432            0 :          CALL get_qs_env(qs_env=qs_env, matrix_vxc_kp=matrix_vxc)
    3433            0 :          CPASSERT(ASSOCIATED(matrix_vxc))
    3434              :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/MATRIX_VXC", &
    3435            0 :                                    extension=".Log")
    3436            0 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    3437            0 :          after = MIN(MAX(after, 1), 16)
    3438            0 :          DO ispin = 1, dft_control%nspins
    3439            0 :             DO img = 1, dft_control%nimages
    3440              :                CALL cp_dbcsr_write_sparse_matrix(matrix_vxc(ispin, img)%matrix, 4, after, qs_env, &
    3441            0 :                                                  para_env, output_unit=iw, omit_headers=omit_headers)
    3442              :             END DO
    3443              :          END DO
    3444              :          CALL cp_print_key_finished_output(iw, logger, input, &
    3445            0 :                                            "DFT%PRINT%AO_MATRICES/MATRIX_VXC")
    3446              :       END IF
    3447              : 
    3448              :       ! Write the [H,r] commutator matrices
    3449        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3450              :                                            "DFT%PRINT%AO_MATRICES/COMMUTATOR_HR"), cp_p_file)) THEN
    3451              :          iw = cp_print_key_unit_nr(logger, input, "DFT%PRINT%AO_MATRICES/COMMUTATOR_HR", &
    3452            2 :                                    extension=".Log")
    3453            2 :          CALL section_vals_val_get(input, "DFT%PRINT%AO_MATRICES%NDIGITS", i_val=after)
    3454            2 :          NULLIFY (matrix_hr)
    3455            2 :          CALL dbcsr_allocate_matrix_set(matrix_hr, 3)
    3456            8 :          DO img = 1, 3
    3457            6 :             ALLOCATE (matrix_hr(img)%matrix)
    3458              :             CALL dbcsr_create(matrix_hr(img)%matrix, template=matrix_s(1, 1)%matrix, &
    3459            6 :                               name="COMMUTATOR", matrix_type=dbcsr_type_antisymmetric)
    3460            6 :             CALL cp_dbcsr_alloc_block_from_nbl(matrix_hr(img)%matrix, sab_orb)
    3461            8 :             CALL dbcsr_set(matrix_hr(img)%matrix, 0._dp)
    3462              :          END DO
    3463              : 
    3464              :          CALL build_com_mom_nl(qs_kind_set, sab_orb, sap_ppnl, dft_control%qs_control%eps_ppnl, &
    3465            2 :                                particle_set, cell, matrix_rv=matrix_hr)
    3466            2 :          CALL build_lin_mom_matrix(qs_env, matrix_hr)
    3467            8 :          DO img = 1, 3
    3468            6 :             CALL dbcsr_scale(matrix_hr(img)%matrix, alpha_scalar=-1._dp)
    3469            8 :             checksum_hr(img) = dbcsr_checksum(matrix_hr(img)%matrix)
    3470              :          END DO
    3471            2 :          IF (output_unit > 0) THEN
    3472            1 :             WRITE (output_unit, '(T2,A,E23.16)') 'COMMUTATOR_HR| CheckSum X =', checksum_hr(1)
    3473            1 :             WRITE (output_unit, '(T2,A,E23.16)') 'COMMUTATOR_HR| CheckSum Y =', checksum_hr(2)
    3474            1 :             WRITE (output_unit, '(T2,A,E23.16)') 'COMMUTATOR_HR| CheckSum Z =', checksum_hr(3)
    3475              :          END IF
    3476            2 :          after = MIN(MAX(after, 1), 16)
    3477            8 :          DO img = 1, 3
    3478              :             CALL cp_dbcsr_write_sparse_matrix(matrix_hr(img)%matrix, 4, after, qs_env, &
    3479            8 :                                               para_env, output_unit=iw, omit_headers=omit_headers)
    3480              :          END DO
    3481            2 :          CALL dbcsr_deallocate_matrix_set(matrix_hr)
    3482              :          CALL cp_print_key_finished_output(iw, logger, input, &
    3483            2 :                                            "DFT%PRINT%AO_MATRICES/COMMUTATOR_HR")
    3484              :       END IF
    3485              : 
    3486              :       ! Compute the Mulliken charges
    3487        13695 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%MULLIKEN")
    3488        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    3489         5348 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MULLIKEN", extension=".mulliken", log_filename=.FALSE.)
    3490         5348 :          print_level = 1
    3491         5348 :          CALL section_vals_val_get(print_key, "PRINT_GOP", l_val=print_it)
    3492         5348 :          IF (print_it) print_level = 2
    3493         5348 :          CALL section_vals_val_get(print_key, "PRINT_ALL", l_val=print_it)
    3494         5348 :          IF (print_it) print_level = 3
    3495         5348 :          CALL mulliken_population_analysis(qs_env, unit_nr, print_level)
    3496         5348 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MULLIKEN")
    3497              :       END IF
    3498              : 
    3499              :       ! Compute the Hirshfeld charges
    3500        13695 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%HIRSHFELD")
    3501        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    3502              :          ! we check if real space density is available
    3503         5430 :          NULLIFY (rho)
    3504         5430 :          CALL get_qs_env(qs_env=qs_env, rho=rho)
    3505         5430 :          CALL qs_rho_get(rho, rho_r_valid=rho_r_valid)
    3506         5430 :          IF (rho_r_valid) THEN
    3507         5356 :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%HIRSHFELD", extension=".hirshfeld", log_filename=.FALSE.)
    3508         5356 :             CALL hirshfeld_charges(qs_env, print_key, unit_nr)
    3509         5356 :             CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%HIRSHFELD")
    3510              :          END IF
    3511              :       END IF
    3512              : 
    3513              :       ! Compute EEQ charges
    3514        13695 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%EEQ_CHARGES")
    3515        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    3516           30 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%EEQ_CHARGES", extension=".eeq", log_filename=.FALSE.)
    3517           30 :          print_level = 1
    3518           30 :          CALL eeq_print(qs_env, unit_nr, print_level, ext=.FALSE.)
    3519           30 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MULLIKEN")
    3520              :       END IF
    3521              : 
    3522              :       ! Do a Voronoi Integration or write a compressed BQB File
    3523        13695 :       print_key_voro => section_vals_get_subs_vals(input, "DFT%PRINT%VORONOI")
    3524        13695 :       print_key_bqb => section_vals_get_subs_vals(input, "DFT%PRINT%E_DENSITY_BQB")
    3525        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key_voro), cp_p_file)) THEN
    3526           24 :          should_print_voro = 1
    3527              :       ELSE
    3528        13671 :          should_print_voro = 0
    3529              :       END IF
    3530        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key_bqb), cp_p_file)) THEN
    3531            2 :          should_print_bqb = 1
    3532              :       ELSE
    3533        13693 :          should_print_bqb = 0
    3534              :       END IF
    3535        13695 :       IF ((should_print_voro /= 0) .OR. (should_print_bqb /= 0)) THEN
    3536              : 
    3537              :          ! we check if real space density is available
    3538           26 :          NULLIFY (rho)
    3539           26 :          CALL get_qs_env(qs_env=qs_env, rho=rho)
    3540           26 :          CALL qs_rho_get(rho, rho_r_valid=rho_r_valid)
    3541           26 :          IF (rho_r_valid) THEN
    3542              : 
    3543           26 :             IF (dft_control%nspins > 1) THEN
    3544              :                CALL get_qs_env(qs_env=qs_env, &
    3545            0 :                                pw_env=pw_env)
    3546              :                CALL pw_env_get(pw_env=pw_env, &
    3547              :                                auxbas_pw_pool=auxbas_pw_pool, &
    3548            0 :                                pw_pools=pw_pools)
    3549            0 :                NULLIFY (mb_rho)
    3550            0 :                ALLOCATE (mb_rho)
    3551            0 :                CALL auxbas_pw_pool%create_pw(pw=mb_rho)
    3552            0 :                CALL pw_copy(rho_r(1), mb_rho)
    3553            0 :                CALL pw_axpy(rho_r(2), mb_rho)
    3554              :                !CALL voronoi_analysis(qs_env, rho_elec_rspace, print_key, unit_nr)
    3555              :             ELSE
    3556           26 :                mb_rho => rho_r(1)
    3557              :                !CALL voronoi_analysis( qs_env, rho_r(1), print_key, unit_nr )
    3558              :             END IF ! nspins
    3559              : 
    3560           26 :             IF (should_print_voro /= 0) THEN
    3561           24 :                CALL section_vals_val_get(print_key_voro, "OUTPUT_TEXT", l_val=voro_print_txt)
    3562           24 :                IF (voro_print_txt) THEN
    3563           24 :                   append_voro = section_get_lval(input, "DFT%PRINT%VORONOI%APPEND")
    3564           24 :                   my_pos_voro = "REWIND"
    3565           24 :                   IF (append_voro) THEN
    3566            0 :                      my_pos_voro = "APPEND"
    3567              :                   END IF
    3568              :                   unit_nr_voro = cp_print_key_unit_nr(logger, input, "DFT%PRINT%VORONOI", extension=".voronoi", &
    3569           24 :                                                       file_position=my_pos_voro, log_filename=.FALSE.)
    3570              :                ELSE
    3571            0 :                   unit_nr_voro = 0
    3572              :                END IF
    3573              :             ELSE
    3574            2 :                unit_nr_voro = 0
    3575              :             END IF
    3576              : 
    3577              :             CALL entry_voronoi_or_bqb(should_print_voro, should_print_bqb, print_key_voro, print_key_bqb, &
    3578           26 :                                       unit_nr_voro, qs_env, mb_rho)
    3579              : 
    3580           26 :             IF (dft_control%nspins > 1) THEN
    3581            0 :                CALL auxbas_pw_pool%give_back_pw(mb_rho)
    3582            0 :                DEALLOCATE (mb_rho)
    3583              :             END IF
    3584              : 
    3585           26 :             IF (unit_nr_voro > 0) THEN
    3586           12 :                CALL cp_print_key_finished_output(unit_nr_voro, logger, input, "DFT%PRINT%VORONOI")
    3587              :             END IF
    3588              : 
    3589              :          END IF
    3590              :       END IF
    3591              : 
    3592              :       ! MAO analysis
    3593        13695 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%MAO_ANALYSIS")
    3594        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    3595           38 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MAO_ANALYSIS", extension=".mao", log_filename=.FALSE.)
    3596           38 :          CALL mao_analysis(qs_env, print_key, unit_nr)
    3597           38 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MAO_ANALYSIS")
    3598              :       END IF
    3599              : 
    3600              :       ! MINBAS analysis
    3601        13695 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%MINBAS_ANALYSIS")
    3602        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    3603           28 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%MINBAS_ANALYSIS", extension=".mao", log_filename=.FALSE.)
    3604           28 :          CALL minbas_analysis(qs_env, print_key, unit_nr)
    3605           28 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%MINBAS_ANALYSIS")
    3606              :       END IF
    3607              : 
    3608              :       ! IAO analysis
    3609        13695 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%IAO_ANALYSIS")
    3610        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    3611           34 :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IAO_ANALYSIS", extension=".iao", log_filename=.FALSE.)
    3612           34 :          CALL iao_read_input(iao_env, print_key, cell)
    3613           34 :          IF (particle_set(1)%fragment_index /= 0) iao_env%do_fragments = .TRUE.
    3614           34 :          IF (iao_env%do_iao) THEN
    3615            6 :             CALL iao_wfn_analysis(qs_env, iao_env, unit_nr)
    3616              :          END IF
    3617           34 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%IAO_ANALYSIS")
    3618              :       END IF
    3619              : 
    3620              :       ! Energy Decomposition Analysis
    3621        13695 :       print_key => section_vals_get_subs_vals(input, "DFT%PRINT%ENERGY_DECOMPOSITION_ANALYSIS")
    3622        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, print_key), cp_p_file)) THEN
    3623              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%ENERGY_DECOMPOSITION_ANALYSIS", &
    3624           58 :                                         extension=".mao", log_filename=.FALSE.)
    3625           58 :          CALL edmf_analysis(qs_env, print_key, unit_nr)
    3626           58 :          CALL cp_print_key_finished_output(unit_nr, logger, input, "DFT%PRINT%ENERGY_DECOMPOSITION_ANALYSIS")
    3627              :       END IF
    3628              : 
    3629              :       ! Print the density in the RI-HFX basis
    3630        13695 :       hfx_section => section_vals_get_subs_vals(input, "DFT%XC%HF")
    3631        13695 :       CALL section_vals_get(hfx_section, explicit=do_hfx)
    3632        13695 :       CALL section_vals_get(hfx_section, n_repetition=n_rep_hf)
    3633        13695 :       IF (do_hfx) THEN
    3634         5238 :          DO i = 1, n_rep_hf
    3635         5238 :             IF (qs_env%x_data(i, 1)%do_hfx_ri) CALL print_ri_hfx(qs_env%x_data(i, 1)%ri_data, qs_env)
    3636              :          END DO
    3637              :       END IF
    3638              : 
    3639        13695 :       DEALLOCATE (zcharge)
    3640              : 
    3641        13695 :       CALL timestop(handle)
    3642              : 
    3643        27390 :    END SUBROUTINE write_mo_free_results
    3644              : 
    3645              : ! **************************************************************************************************
    3646              : !> \brief Calculates Hirshfeld charges
    3647              : !> \param qs_env the qs_env where to calculate the charges
    3648              : !> \param input_section the input section for Hirshfeld charges
    3649              : !> \param unit_nr the output unit number
    3650              : ! **************************************************************************************************
    3651         5356 :    SUBROUTINE hirshfeld_charges(qs_env, input_section, unit_nr)
    3652              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3653              :       TYPE(section_vals_type), POINTER                   :: input_section
    3654              :       INTEGER, INTENT(IN)                                :: unit_nr
    3655              : 
    3656              :       INTEGER                                            :: i, iat, ikind, natom, nkind, nspin, &
    3657              :                                                             radius_type, refc, shapef
    3658         5356 :       INTEGER, DIMENSION(:), POINTER                     :: atom_list
    3659              :       LOGICAL                                            :: do_radius, do_sc, paw_atom
    3660              :       REAL(KIND=dp)                                      :: zeff
    3661         5356 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: radii
    3662         5356 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: charges
    3663         5356 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    3664              :       TYPE(atomic_kind_type), POINTER                    :: atomic_kind
    3665         5356 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_p, matrix_s
    3666              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3667              :       TYPE(hirshfeld_type), POINTER                      :: hirshfeld_env
    3668              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3669         5356 :       TYPE(mpole_rho_atom), DIMENSION(:), POINTER        :: mp_rho
    3670         5356 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    3671         5356 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    3672              :       TYPE(qs_rho_type), POINTER                         :: rho
    3673              :       TYPE(rho0_mpole_type), POINTER                     :: rho0_mpole
    3674              : 
    3675         5356 :       NULLIFY (hirshfeld_env)
    3676         5356 :       NULLIFY (radii)
    3677         5356 :       CALL create_hirshfeld_type(hirshfeld_env)
    3678              :       !
    3679         5356 :       CALL get_qs_env(qs_env, nkind=nkind, natom=natom)
    3680        16068 :       ALLOCATE (hirshfeld_env%charges(natom))
    3681              :       ! input options
    3682         5356 :       CALL section_vals_val_get(input_section, "SELF_CONSISTENT", l_val=do_sc)
    3683         5356 :       CALL section_vals_val_get(input_section, "USER_RADIUS", l_val=do_radius)
    3684         5356 :       CALL section_vals_val_get(input_section, "SHAPE_FUNCTION", i_val=shapef)
    3685         5356 :       CALL section_vals_val_get(input_section, "REFERENCE_CHARGE", i_val=refc)
    3686         5356 :       IF (do_radius) THEN
    3687            0 :          radius_type = radius_user
    3688            0 :          CALL section_vals_val_get(input_section, "ATOMIC_RADII", r_vals=radii)
    3689            0 :          IF (.NOT. SIZE(radii) == nkind) THEN
    3690              :             CALL cp_abort(__LOCATION__, &
    3691              :                           "Length of keyword HIRSHFELD\ATOMIC_RADII does not "// &
    3692            0 :                           "match number of atomic kinds in the input coordinate file.")
    3693              :          END IF
    3694              :       ELSE
    3695         5356 :          radius_type = radius_covalent
    3696              :       END IF
    3697              :       CALL set_hirshfeld_info(hirshfeld_env, shape_function_type=shapef, &
    3698              :                               iterative=do_sc, ref_charge=refc, &
    3699         5356 :                               radius_type=radius_type)
    3700              :       ! shape function
    3701         5356 :       CALL get_qs_env(qs_env, qs_kind_set=qs_kind_set, atomic_kind_set=atomic_kind_set)
    3702              :       CALL create_shape_function(hirshfeld_env, qs_kind_set, atomic_kind_set, &
    3703         5356 :                                  radii_list=radii)
    3704              :       ! reference charges
    3705         5356 :       CALL get_qs_env(qs_env, rho=rho)
    3706         5356 :       CALL qs_rho_get(rho, rho_ao_kp=matrix_p)
    3707         5356 :       nspin = SIZE(matrix_p, 1)
    3708        21424 :       ALLOCATE (charges(natom, nspin))
    3709         5344 :       SELECT CASE (refc)
    3710              :       CASE (ref_charge_atomic)
    3711        14552 :          DO ikind = 1, nkind
    3712         9208 :             CALL get_qs_kind(qs_kind_set(ikind), zeff=zeff)
    3713         9208 :             atomic_kind => atomic_kind_set(ikind)
    3714         9208 :             CALL get_atomic_kind(atomic_kind, atom_list=atom_list)
    3715        46076 :             DO iat = 1, SIZE(atom_list)
    3716        22316 :                i = atom_list(iat)
    3717        31524 :                hirshfeld_env%charges(i) = zeff
    3718              :             END DO
    3719              :          END DO
    3720              :       CASE (ref_charge_mulliken)
    3721           12 :          CALL get_qs_env(qs_env, matrix_s_kp=matrix_s, para_env=para_env)
    3722           12 :          CALL mulliken_charges(matrix_p, matrix_s, para_env, charges)
    3723           48 :          DO iat = 1, natom
    3724          108 :             hirshfeld_env%charges(iat) = SUM(charges(iat, :))
    3725              :          END DO
    3726              :       CASE DEFAULT
    3727         5356 :          CPABORT("Unknown type of reference charge for Hirshfeld partitioning.")
    3728              :       END SELECT
    3729              :       !
    3730        36986 :       charges = 0.0_dp
    3731         5356 :       IF (hirshfeld_env%iterative) THEN
    3732              :          ! Hirshfeld-I charges
    3733           22 :          CALL comp_hirshfeld_i_charges(qs_env, hirshfeld_env, charges, unit_nr)
    3734              :       ELSE
    3735              :          ! Hirshfeld charges
    3736         5334 :          CALL comp_hirshfeld_charges(qs_env, hirshfeld_env, charges)
    3737              :       END IF
    3738         5356 :       CALL get_qs_env(qs_env, particle_set=particle_set, dft_control=dft_control)
    3739         5356 :       IF (dft_control%qs_control%gapw) THEN
    3740              :          ! GAPW: add core charges (rho_hard - rho_soft)
    3741          964 :          CALL get_qs_env(qs_env, rho0_mpole=rho0_mpole)
    3742          964 :          CALL get_rho0_mpole(rho0_mpole, mp_rho=mp_rho)
    3743         4012 :          DO iat = 1, natom
    3744         3048 :             atomic_kind => particle_set(iat)%atomic_kind
    3745         3048 :             CALL get_atomic_kind(atomic_kind, kind_number=ikind)
    3746         3048 :             CALL get_qs_kind(qs_kind_set(ikind), paw_atom=paw_atom)
    3747         4012 :             IF (paw_atom) THEN
    3748         5684 :                charges(iat, 1:nspin) = charges(iat, 1:nspin) + mp_rho(iat)%q0(1:nspin)
    3749              :             END IF
    3750              :          END DO
    3751              :       END IF
    3752              :       !
    3753         5356 :       IF (unit_nr > 0) THEN
    3754              :          CALL write_hirshfeld_charges(charges, hirshfeld_env, particle_set, &
    3755         2693 :                                       qs_kind_set, unit_nr)
    3756              :       END IF
    3757              :       ! Save the charges to the results under the tag [HIRSHFELD-CHARGES]
    3758         5356 :       CALL save_hirshfeld_charges(charges, particle_set, qs_kind_set, qs_env)
    3759              :       !
    3760         5356 :       CALL release_hirshfeld_type(hirshfeld_env)
    3761         5356 :       DEALLOCATE (charges)
    3762              : 
    3763        10712 :    END SUBROUTINE hirshfeld_charges
    3764              : 
    3765              : ! **************************************************************************************************
    3766              : !> \brief ...
    3767              : !> \param ca ...
    3768              : !> \param a ...
    3769              : !> \param cb ...
    3770              : !> \param b ...
    3771              : !> \param l ...
    3772              : ! **************************************************************************************************
    3773            4 :    SUBROUTINE project_function_a(ca, a, cb, b, l)
    3774              :       ! project function cb on ca
    3775              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: ca
    3776              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: a, cb, b
    3777              :       INTEGER, INTENT(IN)                                :: l
    3778              : 
    3779              :       INTEGER                                            :: info, n
    3780            4 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: ipiv
    3781            4 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: smat, tmat, v
    3782              : 
    3783            4 :       n = SIZE(ca)
    3784           40 :       ALLOCATE (smat(n, n), tmat(n, n), v(n, 1), ipiv(n))
    3785              : 
    3786            4 :       CALL sg_overlap(smat, l, a, a)
    3787            4 :       CALL sg_overlap(tmat, l, a, b)
    3788         1252 :       v(:, 1) = MATMUL(tmat, cb)
    3789            4 :       CALL dgesv(n, 1, smat, n, ipiv, v, n, info)
    3790            4 :       CPASSERT(info == 0)
    3791           52 :       ca(:) = v(:, 1)
    3792              : 
    3793            4 :       DEALLOCATE (smat, tmat, v, ipiv)
    3794              : 
    3795            4 :    END SUBROUTINE project_function_a
    3796              : 
    3797              : ! **************************************************************************************************
    3798              : !> \brief ...
    3799              : !> \param ca ...
    3800              : !> \param a ...
    3801              : !> \param bfun ...
    3802              : !> \param grid_atom ...
    3803              : !> \param l ...
    3804              : ! **************************************************************************************************
    3805           36 :    SUBROUTINE project_function_b(ca, a, bfun, grid_atom, l)
    3806              :       ! project function f on ca
    3807              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: ca
    3808              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: a, bfun
    3809              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    3810              :       INTEGER, INTENT(IN)                                :: l
    3811              : 
    3812              :       INTEGER                                            :: i, info, n, nr
    3813           36 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: ipiv
    3814           36 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: afun
    3815           36 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: smat, v
    3816              : 
    3817           36 :       n = SIZE(ca)
    3818           36 :       nr = grid_atom%nr
    3819          360 :       ALLOCATE (smat(n, n), v(n, 1), ipiv(n), afun(nr))
    3820              : 
    3821           36 :       CALL sg_overlap(smat, l, a, a)
    3822          468 :       DO i = 1, n
    3823        22032 :          afun(:) = grid_atom%rad(:)**l*EXP(-a(i)*grid_atom%rad2(:))
    3824        22068 :          v(i, 1) = SUM(afun(:)*bfun(:)*grid_atom%wr(:))
    3825              :       END DO
    3826           36 :       CALL dgesv(n, 1, smat, n, ipiv, v, n, info)
    3827           36 :       CPASSERT(info == 0)
    3828          468 :       ca(:) = v(:, 1)
    3829              : 
    3830           36 :       DEALLOCATE (smat, v, ipiv, afun)
    3831              : 
    3832           36 :    END SUBROUTINE project_function_b
    3833              : 
    3834              : ! **************************************************************************************************
    3835              : !> \brief Performs printing of cube files from local energy
    3836              : !> \param input input
    3837              : !> \param logger the logger
    3838              : !> \param qs_env the qs_env in which the qs_env lives
    3839              : !> \par History
    3840              : !>      07.2019 created
    3841              : !> \author JGH
    3842              : ! **************************************************************************************************
    3843        13695 :    SUBROUTINE qs_scf_post_local_energy(input, logger, qs_env)
    3844              :       TYPE(section_vals_type), POINTER                   :: input
    3845              :       TYPE(cp_logger_type), POINTER                      :: logger
    3846              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3847              : 
    3848              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_local_energy'
    3849              : 
    3850              :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube
    3851              :       INTEGER                                            :: handle, io_unit, natom, unit_nr
    3852              :       LOGICAL                                            :: append_cube, gapw, gapw_xc, mpi_io
    3853        13695 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: zcharge
    3854              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3855              :       TYPE(particle_list_type), POINTER                  :: particles
    3856              :       TYPE(pw_env_type), POINTER                         :: pw_env
    3857              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    3858              :       TYPE(pw_r3d_rs_type)                               :: eden
    3859              :       TYPE(qs_subsys_type), POINTER                      :: subsys
    3860              :       TYPE(section_vals_type), POINTER                   :: dft_section
    3861              : 
    3862        13695 :       CALL timeset(routineN, handle)
    3863        13695 :       io_unit = cp_logger_get_default_io_unit(logger)
    3864        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3865              :                                            "DFT%PRINT%LOCAL_ENERGY_CUBE"), cp_p_file)) THEN
    3866           34 :          dft_section => section_vals_get_subs_vals(input, "DFT")
    3867           34 :          CALL get_qs_env(qs_env=qs_env, dft_control=dft_control, natom=natom)
    3868           34 :          gapw = dft_control%qs_control%gapw
    3869           34 :          gapw_xc = dft_control%qs_control%gapw_xc
    3870           34 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, subsys=subsys)
    3871           34 :          CALL qs_subsys_get(subsys, particles=particles)
    3872           34 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3873           34 :          CALL auxbas_pw_pool%create_pw(eden)
    3874              :          !
    3875           34 :          CALL qs_local_energy(qs_env, eden)
    3876           34 :          CALL get_effective_core_charges(qs_env, zcharge)
    3877              :          !
    3878           34 :          append_cube = section_get_lval(input, "DFT%PRINT%LOCAL_ENERGY_CUBE%APPEND")
    3879           34 :          IF (append_cube) THEN
    3880            0 :             my_pos_cube = "APPEND"
    3881              :          ELSE
    3882           34 :             my_pos_cube = "REWIND"
    3883              :          END IF
    3884           34 :          mpi_io = .TRUE.
    3885              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%LOCAL_ENERGY_CUBE", &
    3886              :                                         extension=".cube", middle_name="local_energy", &
    3887           34 :                                         file_position=my_pos_cube, mpi_io=mpi_io)
    3888              :          CALL cp_pw_to_cube(eden, unit_nr, "LOCAL ENERGY", particles=particles, zeff=zcharge, &
    3889              :                             stride=section_get_ivals(dft_section, "PRINT%LOCAL_ENERGY_CUBE%STRIDE"), &
    3890              :                             max_file_size_mb=section_get_rval(dft_section, "PRINT%LOCAL_ENERGY_CUBE%MAX_FILE_SIZE_MB"), &
    3891           34 :                             mpi_io=mpi_io)
    3892           34 :          IF (io_unit > 0) THEN
    3893           17 :             INQUIRE (UNIT=unit_nr, NAME=filename)
    3894           17 :             IF (gapw .OR. gapw_xc) THEN
    3895              :                WRITE (UNIT=io_unit, FMT="(/,T3,A,A)") &
    3896            1 :                   "The soft part of the local energy is written to the file: ", TRIM(ADJUSTL(filename))
    3897              :             ELSE
    3898              :                WRITE (UNIT=io_unit, FMT="(/,T3,A,A)") &
    3899           16 :                   "The local energy is written to the file: ", TRIM(ADJUSTL(filename))
    3900              :             END IF
    3901              :          END IF
    3902              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3903           34 :                                            "DFT%PRINT%LOCAL_ENERGY_CUBE", mpi_io=mpi_io)
    3904              :          !
    3905           34 :          CALL auxbas_pw_pool%give_back_pw(eden)
    3906           34 :          DEALLOCATE (zcharge)
    3907              :       END IF
    3908        13695 :       CALL timestop(handle)
    3909              : 
    3910        27390 :    END SUBROUTINE qs_scf_post_local_energy
    3911              : 
    3912              : ! **************************************************************************************************
    3913              : !> \brief Performs printing of cube files from local energy
    3914              : !> \param input input
    3915              : !> \param logger the logger
    3916              : !> \param qs_env the qs_env in which the qs_env lives
    3917              : !> \par History
    3918              : !>      07.2019 created
    3919              : !> \author JGH
    3920              : ! **************************************************************************************************
    3921        13695 :    SUBROUTINE qs_scf_post_local_stress(input, logger, qs_env)
    3922              :       TYPE(section_vals_type), POINTER                   :: input
    3923              :       TYPE(cp_logger_type), POINTER                      :: logger
    3924              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3925              : 
    3926              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_local_stress'
    3927              : 
    3928              :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube
    3929              :       INTEGER                                            :: handle, io_unit, natom, unit_nr
    3930              :       LOGICAL                                            :: append_cube, gapw, gapw_xc, mpi_io
    3931              :       REAL(KIND=dp)                                      :: beta
    3932        13695 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: zcharge
    3933              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3934              :       TYPE(particle_list_type), POINTER                  :: particles
    3935              :       TYPE(pw_env_type), POINTER                         :: pw_env
    3936              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    3937              :       TYPE(pw_r3d_rs_type)                               :: stress
    3938              :       TYPE(qs_subsys_type), POINTER                      :: subsys
    3939              :       TYPE(section_vals_type), POINTER                   :: dft_section
    3940              : 
    3941        13695 :       CALL timeset(routineN, handle)
    3942        13695 :       io_unit = cp_logger_get_default_io_unit(logger)
    3943        13695 :       IF (BTEST(cp_print_key_should_output(logger%iter_info, input, &
    3944              :                                            "DFT%PRINT%LOCAL_STRESS_CUBE"), cp_p_file)) THEN
    3945              :          CALL cp_warn(__LOCATION__, &
    3946           30 :                       "LOCAL_STRESS_CUBE uses the existing experimental local stress implementation")
    3947           30 :          dft_section => section_vals_get_subs_vals(input, "DFT")
    3948           30 :          CALL get_qs_env(qs_env=qs_env, dft_control=dft_control, natom=natom)
    3949           30 :          gapw = dft_control%qs_control%gapw
    3950           30 :          gapw_xc = dft_control%qs_control%gapw_xc
    3951           30 :          CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, subsys=subsys)
    3952           30 :          CALL qs_subsys_get(subsys, particles=particles)
    3953           30 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    3954           30 :          CALL auxbas_pw_pool%create_pw(stress)
    3955              :          !
    3956              :          ! use beta=0: kinetic energy density in symmetric form
    3957           30 :          beta = 0.0_dp
    3958           30 :          CALL qs_local_stress(qs_env, beta=beta)
    3959           30 :          CALL get_effective_core_charges(qs_env, zcharge)
    3960              :          !
    3961           30 :          append_cube = section_get_lval(input, "DFT%PRINT%LOCAL_STRESS_CUBE%APPEND")
    3962           30 :          IF (append_cube) THEN
    3963            0 :             my_pos_cube = "APPEND"
    3964              :          ELSE
    3965           30 :             my_pos_cube = "REWIND"
    3966              :          END IF
    3967           30 :          mpi_io = .TRUE.
    3968              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%LOCAL_STRESS_CUBE", &
    3969              :                                         extension=".cube", middle_name="local_stress", &
    3970           30 :                                         file_position=my_pos_cube, mpi_io=mpi_io)
    3971              :          CALL cp_pw_to_cube(stress, unit_nr, "LOCAL STRESS", particles=particles, zeff=zcharge, &
    3972              :                             stride=section_get_ivals(dft_section, "PRINT%LOCAL_STRESS_CUBE%STRIDE"), &
    3973              :                             max_file_size_mb=section_get_rval(dft_section, "PRINT%LOCAL_STRESS_CUBE%MAX_FILE_SIZE_MB"), &
    3974           30 :                             mpi_io=mpi_io)
    3975           30 :          IF (io_unit > 0) THEN
    3976           15 :             INQUIRE (UNIT=unit_nr, NAME=filename)
    3977           15 :             WRITE (UNIT=io_unit, FMT="(/,T3,A)") "Write 1/3*Tr(sigma) to cube file"
    3978           15 :             IF (gapw .OR. gapw_xc) THEN
    3979              :                WRITE (UNIT=io_unit, FMT="(T3,A,A)") &
    3980            0 :                   "The soft part of the local stress is written to the file: ", TRIM(ADJUSTL(filename))
    3981              :             ELSE
    3982              :                WRITE (UNIT=io_unit, FMT="(T3,A,A)") &
    3983           15 :                   "The local stress is written to the file: ", TRIM(ADJUSTL(filename))
    3984              :             END IF
    3985              :          END IF
    3986              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    3987           30 :                                            "DFT%PRINT%LOCAL_STRESS_CUBE", mpi_io=mpi_io)
    3988              :          !
    3989           30 :          CALL auxbas_pw_pool%give_back_pw(stress)
    3990           30 :          DEALLOCATE (zcharge)
    3991              :       END IF
    3992              : 
    3993        13695 :       CALL timestop(handle)
    3994              : 
    3995        27390 :    END SUBROUTINE qs_scf_post_local_stress
    3996              : 
    3997              : ! **************************************************************************************************
    3998              : !> \brief Performs printing of cube files related to the implicit Poisson solver
    3999              : !> \param input input
    4000              : !> \param logger the logger
    4001              : !> \param qs_env the qs_env in which the qs_env lives
    4002              : !> \par History
    4003              : !>      03.2016 refactored from write_mo_free_results [Hossein Bani-Hashemian]
    4004              : !> \author Mohammad Hossein Bani-Hashemian
    4005              : ! **************************************************************************************************
    4006        13695 :    SUBROUTINE qs_scf_post_ps_implicit(input, logger, qs_env)
    4007              :       TYPE(section_vals_type), POINTER                   :: input
    4008              :       TYPE(cp_logger_type), POINTER                      :: logger
    4009              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4010              : 
    4011              :       CHARACTER(len=*), PARAMETER :: routineN = 'qs_scf_post_ps_implicit'
    4012              : 
    4013              :       CHARACTER(LEN=default_path_length)                 :: filename, my_pos_cube
    4014              :       INTEGER                                            :: boundary_condition, handle, i, j, &
    4015              :                                                             n_cstr, n_tiles, unit_nr
    4016              :       LOGICAL :: append_cube, do_cstr_charge_cube, do_dielectric_cube, do_dirichlet_bc_cube, &
    4017              :          has_dirichlet_bc, has_implicit_ps, mpi_io, tile_cubes
    4018        13695 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: zcharge
    4019              :       TYPE(particle_list_type), POINTER                  :: particles
    4020              :       TYPE(pw_env_type), POINTER                         :: pw_env
    4021              :       TYPE(pw_poisson_type), POINTER                     :: poisson_env
    4022              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    4023              :       TYPE(pw_r3d_rs_type)                               :: aux_r
    4024              :       TYPE(pw_r3d_rs_type), POINTER                      :: dirichlet_tile
    4025              :       TYPE(qs_subsys_type), POINTER                      :: subsys
    4026              :       TYPE(section_vals_type), POINTER                   :: dft_section
    4027              : 
    4028        13695 :       CALL timeset(routineN, handle)
    4029              : 
    4030        13695 :       NULLIFY (pw_env, auxbas_pw_pool, dft_section, particles)
    4031              : 
    4032        13695 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    4033        13695 :       CALL get_qs_env(qs_env=qs_env, pw_env=pw_env, subsys=subsys)
    4034        13695 :       CALL qs_subsys_get(subsys, particles=particles)
    4035        13695 :       CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    4036              : 
    4037        13695 :       has_implicit_ps = .FALSE.
    4038        13695 :       CALL get_qs_env(qs_env=qs_env, pw_env=pw_env)
    4039        13695 :       IF (pw_env%poisson_env%parameters%solver == pw_poisson_implicit) has_implicit_ps = .TRUE.
    4040              : 
    4041              :       ! Write the dielectric constant into a cube file
    4042              :       do_dielectric_cube = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    4043        13695 :                                                             "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE"), cp_p_file)
    4044        13695 :       IF (has_implicit_ps .AND. do_dielectric_cube) THEN
    4045            2 :          IF (.NOT. ALLOCATED(zcharge)) CALL get_effective_core_charges(qs_env, zcharge)
    4046            2 :          append_cube = section_get_lval(input, "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE%APPEND")
    4047            2 :          my_pos_cube = "REWIND"
    4048            2 :          IF (append_cube) THEN
    4049            0 :             my_pos_cube = "APPEND"
    4050              :          END IF
    4051            2 :          mpi_io = .TRUE.
    4052              :          unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE", &
    4053              :                                         extension=".cube", middle_name="DIELECTRIC_CONSTANT", file_position=my_pos_cube, &
    4054            2 :                                         mpi_io=mpi_io)
    4055            2 :          CALL pw_env_get(pw_env, poisson_env=poisson_env, auxbas_pw_pool=auxbas_pw_pool)
    4056            2 :          CALL auxbas_pw_pool%create_pw(aux_r)
    4057              : 
    4058            2 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    4059            2 :          SELECT CASE (boundary_condition)
    4060              :          CASE (PERIODIC_BC, MIXED_PERIODIC_BC)
    4061            2 :             CALL pw_copy(poisson_env%implicit_env%dielectric%eps, aux_r)
    4062              :          CASE (MIXED_BC, NEUMANN_BC)
    4063              :             CALL pw_shrink(pw_env%poisson_env%parameters%ps_implicit_params%neumann_directions, &
    4064              :                            pw_env%poisson_env%implicit_env%dct_env%dests_shrink, &
    4065              :                            pw_env%poisson_env%implicit_env%dct_env%srcs_shrink, &
    4066              :                            pw_env%poisson_env%implicit_env%dct_env%bounds_local_shftd, &
    4067            2 :                            poisson_env%implicit_env%dielectric%eps, aux_r)
    4068              :          END SELECT
    4069              : 
    4070              :          CALL cp_pw_to_cube(aux_r, unit_nr, "DIELECTRIC CONSTANT", particles=particles, zeff=zcharge, &
    4071              :                             stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE%STRIDE"), &
    4072              :                         max_file_size_mb=section_get_rval(dft_section, "PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE%MAX_FILE_SIZE_MB"), &
    4073            2 :                             mpi_io=mpi_io)
    4074              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    4075            2 :                                            "DFT%PRINT%IMPLICIT_PSOLVER%DIELECTRIC_CUBE", mpi_io=mpi_io)
    4076              : 
    4077            2 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    4078              :       END IF
    4079              : 
    4080              :       ! Write Dirichlet constraint charges into a cube file
    4081              :       do_cstr_charge_cube = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    4082        13695 :                                                              "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE"), cp_p_file)
    4083              : 
    4084        13695 :       has_dirichlet_bc = .FALSE.
    4085        13695 :       IF (has_implicit_ps) THEN
    4086           86 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    4087           86 :          IF (boundary_condition == MIXED_PERIODIC_BC .OR. boundary_condition == MIXED_BC) THEN
    4088           60 :             has_dirichlet_bc = .TRUE.
    4089              :          END IF
    4090              :       END IF
    4091              : 
    4092           86 :       IF (has_implicit_ps .AND. do_cstr_charge_cube .AND. has_dirichlet_bc) THEN
    4093            2 :          IF (.NOT. ALLOCATED(zcharge)) CALL get_effective_core_charges(qs_env, zcharge)
    4094              :          append_cube = section_get_lval(input, &
    4095            2 :                                         "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE%APPEND")
    4096            2 :          my_pos_cube = "REWIND"
    4097            2 :          IF (append_cube) THEN
    4098            0 :             my_pos_cube = "APPEND"
    4099              :          END IF
    4100            2 :          mpi_io = .TRUE.
    4101              :          unit_nr = cp_print_key_unit_nr(logger, input, &
    4102              :                                         "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE", &
    4103              :                                         extension=".cube", middle_name="dirichlet_cstr_charge", file_position=my_pos_cube, &
    4104            2 :                                         mpi_io=mpi_io)
    4105            2 :          CALL pw_env_get(pw_env, poisson_env=poisson_env, auxbas_pw_pool=auxbas_pw_pool)
    4106            2 :          CALL auxbas_pw_pool%create_pw(aux_r)
    4107              : 
    4108            2 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    4109            2 :          SELECT CASE (boundary_condition)
    4110              :          CASE (MIXED_PERIODIC_BC)
    4111            2 :             CALL pw_copy(poisson_env%implicit_env%cstr_charge, aux_r)
    4112              :          CASE (MIXED_BC)
    4113              :             CALL pw_shrink(pw_env%poisson_env%parameters%ps_implicit_params%neumann_directions, &
    4114              :                            pw_env%poisson_env%implicit_env%dct_env%dests_shrink, &
    4115              :                            pw_env%poisson_env%implicit_env%dct_env%srcs_shrink, &
    4116              :                            pw_env%poisson_env%implicit_env%dct_env%bounds_local_shftd, &
    4117            2 :                            poisson_env%implicit_env%cstr_charge, aux_r)
    4118              :          END SELECT
    4119              : 
    4120              :          CALL cp_pw_to_cube(aux_r, unit_nr, "DIRICHLET CONSTRAINT CHARGE", particles=particles, zeff=zcharge, &
    4121              :                             stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE%STRIDE"), &
    4122              :              max_file_size_mb=section_get_rval(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE%MAX_FILE_SIZE_MB"), &
    4123            2 :                             mpi_io=mpi_io)
    4124              :          CALL cp_print_key_finished_output(unit_nr, logger, input, &
    4125            2 :                                            "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_CSTR_CHARGE_CUBE", mpi_io=mpi_io)
    4126              : 
    4127            2 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    4128              :       END IF
    4129              : 
    4130              :       ! Write Dirichlet type constranits into cube files
    4131              :       do_dirichlet_bc_cube = BTEST(cp_print_key_should_output(logger%iter_info, input, &
    4132        13695 :                                                               "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE"), cp_p_file)
    4133        13695 :       has_dirichlet_bc = .FALSE.
    4134        13695 :       IF (has_implicit_ps) THEN
    4135           86 :          boundary_condition = pw_env%poisson_env%parameters%ps_implicit_params%boundary_condition
    4136           86 :          IF (boundary_condition == MIXED_PERIODIC_BC .OR. boundary_condition == MIXED_BC) THEN
    4137              :             has_dirichlet_bc = .TRUE.
    4138              :          END IF
    4139              :       END IF
    4140              : 
    4141           60 :       IF (has_implicit_ps .AND. has_dirichlet_bc .AND. do_dirichlet_bc_cube) THEN
    4142            2 :          IF (.NOT. ALLOCATED(zcharge)) CALL get_effective_core_charges(qs_env, zcharge)
    4143            2 :          append_cube = section_get_lval(input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%APPEND")
    4144            2 :          my_pos_cube = "REWIND"
    4145            2 :          IF (append_cube) THEN
    4146            0 :             my_pos_cube = "APPEND"
    4147              :          END IF
    4148            2 :          tile_cubes = section_get_lval(input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%TILE_CUBES")
    4149              : 
    4150            2 :          CALL pw_env_get(pw_env, poisson_env=poisson_env, auxbas_pw_pool=auxbas_pw_pool)
    4151            2 :          CALL auxbas_pw_pool%create_pw(aux_r)
    4152            2 :          CALL pw_zero(aux_r)
    4153              : 
    4154            2 :          IF (tile_cubes) THEN
    4155              :             ! one cube file per tile
    4156            0 :             n_cstr = SIZE(poisson_env%implicit_env%contacts)
    4157            0 :             DO j = 1, n_cstr
    4158            0 :                n_tiles = poisson_env%implicit_env%contacts(j)%dirichlet_bc%n_tiles
    4159            0 :                DO i = 1, n_tiles
    4160              :                   filename = "dirichlet_cstr_"//TRIM(ADJUSTL(cp_to_string(j)))// &
    4161            0 :                              "_tile_"//TRIM(ADJUSTL(cp_to_string(i)))
    4162            0 :                   mpi_io = .TRUE.
    4163              :                   unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", &
    4164              :                                                  extension=".cube", middle_name=filename, file_position=my_pos_cube, &
    4165            0 :                                                  mpi_io=mpi_io)
    4166              : 
    4167            0 :                   CALL pw_copy(poisson_env%implicit_env%contacts(j)%dirichlet_bc%tiles(i)%tile%tile_pw, aux_r)
    4168              : 
    4169              :                   CALL cp_pw_to_cube(aux_r, unit_nr, "DIRICHLET TYPE CONSTRAINT", particles=particles, zeff=zcharge, &
    4170              :                                      stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%STRIDE"), &
    4171              :                       max_file_size_mb=section_get_rval(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%MAX_FILE_SIZE_MB"), &
    4172            0 :                                      mpi_io=mpi_io)
    4173              :                   CALL cp_print_key_finished_output(unit_nr, logger, input, &
    4174            0 :                                                     "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", mpi_io=mpi_io)
    4175              :                END DO
    4176              :             END DO
    4177              :          ELSE
    4178              :             ! a single cube file
    4179            2 :             NULLIFY (dirichlet_tile)
    4180            2 :             ALLOCATE (dirichlet_tile)
    4181            2 :             CALL auxbas_pw_pool%create_pw(dirichlet_tile)
    4182            2 :             CALL pw_zero(dirichlet_tile)
    4183            2 :             mpi_io = .TRUE.
    4184              :             unit_nr = cp_print_key_unit_nr(logger, input, "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", &
    4185              :                                            extension=".cube", middle_name="DIRICHLET_CSTR", file_position=my_pos_cube, &
    4186            2 :                                            mpi_io=mpi_io)
    4187              : 
    4188            2 :             n_cstr = SIZE(poisson_env%implicit_env%contacts)
    4189            6 :             DO j = 1, n_cstr
    4190            4 :                n_tiles = poisson_env%implicit_env%contacts(j)%dirichlet_bc%n_tiles
    4191           10 :                DO i = 1, n_tiles
    4192            4 :                   CALL pw_copy(poisson_env%implicit_env%contacts(j)%dirichlet_bc%tiles(i)%tile%tile_pw, dirichlet_tile)
    4193            8 :                   CALL pw_axpy(dirichlet_tile, aux_r)
    4194              :                END DO
    4195              :             END DO
    4196              : 
    4197              :             CALL cp_pw_to_cube(aux_r, unit_nr, "DIRICHLET TYPE CONSTRAINT", particles=particles, zeff=zcharge, &
    4198              :                                stride=section_get_ivals(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%STRIDE"), &
    4199              :                       max_file_size_mb=section_get_rval(dft_section, "PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE%MAX_FILE_SIZE_MB"), &
    4200            2 :                                mpi_io=mpi_io)
    4201              :             CALL cp_print_key_finished_output(unit_nr, logger, input, &
    4202            2 :                                               "DFT%PRINT%IMPLICIT_PSOLVER%DIRICHLET_BC_CUBE", mpi_io=mpi_io)
    4203            2 :             CALL auxbas_pw_pool%give_back_pw(dirichlet_tile)
    4204            2 :             DEALLOCATE (dirichlet_tile)
    4205              :          END IF
    4206              : 
    4207            2 :          CALL auxbas_pw_pool%give_back_pw(aux_r)
    4208              :       END IF
    4209              : 
    4210        13695 :       CALL timestop(handle)
    4211              : 
    4212        27390 :    END SUBROUTINE qs_scf_post_ps_implicit
    4213              : 
    4214              : !**************************************************************************************************
    4215              : !> \brief write an adjacency (interaction) matrix
    4216              : !> \param qs_env qs environment
    4217              : !> \param input the input
    4218              : !> \author Mohammad Hossein Bani-Hashemian
    4219              : ! **************************************************************************************************
    4220        13695 :    SUBROUTINE write_adjacency_matrix(qs_env, input)
    4221              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4222              :       TYPE(section_vals_type), POINTER                   :: input
    4223              : 
    4224              :       CHARACTER(len=*), PARAMETER :: routineN = 'write_adjacency_matrix'
    4225              : 
    4226              :       INTEGER                                            :: adjm_size, colind, handle, iatom, ikind, &
    4227              :                                                             ind, jatom, jkind, k, natom, nkind, &
    4228              :                                                             output_unit, rowind, unit_nr
    4229        13695 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: interact_adjm
    4230              :       LOGICAL                                            :: do_adjm_write, do_symmetric
    4231              :       TYPE(cp_logger_type), POINTER                      :: logger
    4232        13695 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list_a, basis_set_list_b
    4233              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set_a, basis_set_b
    4234              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    4235              :       TYPE(neighbor_list_iterator_p_type), &
    4236        13695 :          DIMENSION(:), POINTER                           :: nl_iterator
    4237              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    4238        13695 :          POINTER                                         :: nl
    4239        13695 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    4240              :       TYPE(section_vals_type), POINTER                   :: dft_section
    4241              : 
    4242        13695 :       CALL timeset(routineN, handle)
    4243              : 
    4244        13695 :       NULLIFY (dft_section)
    4245              : 
    4246        13695 :       logger => cp_get_default_logger()
    4247        13695 :       output_unit = cp_logger_get_default_io_unit(logger)
    4248              : 
    4249        13695 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    4250              :       do_adjm_write = BTEST(cp_print_key_should_output(logger%iter_info, dft_section, &
    4251        13695 :                                                        "PRINT%ADJMAT_WRITE"), cp_p_file)
    4252              : 
    4253        13695 :       IF (do_adjm_write) THEN
    4254           28 :          NULLIFY (qs_kind_set, nl_iterator)
    4255           28 :          NULLIFY (basis_set_list_a, basis_set_list_b, basis_set_a, basis_set_b)
    4256              : 
    4257           28 :          CALL get_qs_env(qs_env, qs_kind_set=qs_kind_set, sab_orb=nl, natom=natom, para_env=para_env)
    4258              : 
    4259           28 :          nkind = SIZE(qs_kind_set)
    4260           28 :          CPASSERT(SIZE(nl) > 0)
    4261           28 :          CALL get_neighbor_list_set_p(neighbor_list_sets=nl, symmetric=do_symmetric)
    4262           28 :          CPASSERT(do_symmetric)
    4263          216 :          ALLOCATE (basis_set_list_a(nkind), basis_set_list_b(nkind))
    4264           28 :          CALL basis_set_list_setup(basis_set_list_a, "ORB", qs_kind_set)
    4265           28 :          CALL basis_set_list_setup(basis_set_list_b, "ORB", qs_kind_set)
    4266              : 
    4267           28 :          adjm_size = ((natom + 1)*natom)/2
    4268           84 :          ALLOCATE (interact_adjm(4*adjm_size))
    4269           28 :          interact_adjm = 0
    4270              : 
    4271           28 :          NULLIFY (nl_iterator)
    4272           28 :          CALL neighbor_list_iterator_create(nl_iterator, nl)
    4273         2021 :          DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    4274              :             CALL get_iterator_info(nl_iterator, &
    4275              :                                    ikind=ikind, jkind=jkind, &
    4276         1993 :                                    iatom=iatom, jatom=jatom)
    4277              : 
    4278         1993 :             basis_set_a => basis_set_list_a(ikind)%gto_basis_set
    4279         1993 :             IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
    4280         1993 :             basis_set_b => basis_set_list_b(jkind)%gto_basis_set
    4281         1993 :             IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
    4282              : 
    4283              :             ! move everything to the upper triangular part
    4284         1993 :             IF (iatom <= jatom) THEN
    4285              :                rowind = iatom
    4286              :                colind = jatom
    4287              :             ELSE
    4288          670 :                rowind = jatom
    4289          670 :                colind = iatom
    4290              :                ! swap the kinds too
    4291              :                ikind = ikind + jkind
    4292          670 :                jkind = ikind - jkind
    4293          670 :                ikind = ikind - jkind
    4294              :             END IF
    4295              : 
    4296              :             ! indexing upper triangular matrix
    4297         1993 :             ind = adjm_size - (natom - rowind + 1)*((natom - rowind + 1) + 1)/2 + colind - rowind + 1
    4298              :             ! convert the upper triangular matrix into a adjm_size x 4 matrix
    4299              :             ! columns are: iatom, jatom, ikind, jkind
    4300         1993 :             interact_adjm((ind - 1)*4 + 1) = rowind
    4301         1993 :             interact_adjm((ind - 1)*4 + 2) = colind
    4302         1993 :             interact_adjm((ind - 1)*4 + 3) = ikind
    4303         1993 :             interact_adjm((ind - 1)*4 + 4) = jkind
    4304              :          END DO
    4305              : 
    4306           28 :          CALL para_env%sum(interact_adjm)
    4307              : 
    4308              :          unit_nr = cp_print_key_unit_nr(logger, dft_section, "PRINT%ADJMAT_WRITE", &
    4309              :                                         extension=".adjmat", file_form="FORMATTED", &
    4310           28 :                                         file_status="REPLACE")
    4311           28 :          IF (unit_nr > 0) THEN
    4312           14 :             WRITE (unit_nr, "(1A,2X,1A,5X,1A,4X,A5,3X,A5)") "#", "iatom", "jatom", "ikind", "jkind"
    4313           88 :             DO k = 1, 4*adjm_size, 4
    4314              :                ! print only the interacting atoms
    4315           88 :                IF (interact_adjm(k) > 0 .AND. interact_adjm(k + 1) > 0) THEN
    4316           74 :                   WRITE (unit_nr, "(I8,2X,I8,3X,I6,2X,I6)") interact_adjm(k:k + 3)
    4317              :                END IF
    4318              :             END DO
    4319              :          END IF
    4320              : 
    4321           28 :          CALL cp_print_key_finished_output(unit_nr, logger, dft_section, "PRINT%ADJMAT_WRITE")
    4322              : 
    4323           28 :          CALL neighbor_list_iterator_release(nl_iterator)
    4324           56 :          DEALLOCATE (basis_set_list_a, basis_set_list_b)
    4325              :       END IF
    4326              : 
    4327        13695 :       CALL timestop(handle)
    4328              : 
    4329        27390 :    END SUBROUTINE write_adjacency_matrix
    4330              : 
    4331              : ! **************************************************************************************************
    4332              : !> \brief Updates Hartree potential with MP2 density. Important for REPEAT charges
    4333              : !> \param rho ...
    4334              : !> \param qs_env ...
    4335              : !> \author Vladimir Rybkin
    4336              : ! **************************************************************************************************
    4337          322 :    SUBROUTINE update_hartree_with_mp2(rho, qs_env)
    4338              :       TYPE(qs_rho_type), POINTER                         :: rho
    4339              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4340              : 
    4341              :       LOGICAL                                            :: use_virial
    4342              :       TYPE(pw_c1d_gs_type)                               :: rho_tot_gspace, v_hartree_gspace
    4343              :       TYPE(pw_c1d_gs_type), POINTER                      :: rho_core
    4344              :       TYPE(pw_env_type), POINTER                         :: pw_env
    4345              :       TYPE(pw_poisson_type), POINTER                     :: poisson_env
    4346              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    4347              :       TYPE(pw_r3d_rs_type), POINTER                      :: v_hartree_rspace
    4348              :       TYPE(qs_energy_type), POINTER                      :: energy
    4349              :       TYPE(virial_type), POINTER                         :: virial
    4350              : 
    4351          322 :       NULLIFY (auxbas_pw_pool, pw_env, poisson_env, energy, rho_core, v_hartree_rspace, virial)
    4352              :       CALL get_qs_env(qs_env, pw_env=pw_env, energy=energy, &
    4353              :                       rho_core=rho_core, virial=virial, &
    4354          322 :                       v_hartree_rspace=v_hartree_rspace)
    4355              : 
    4356          322 :       use_virial = virial%pv_availability .AND. (.NOT. virial%pv_numer)
    4357              : 
    4358              :       IF (.NOT. use_virial) THEN
    4359              : 
    4360              :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, &
    4361          268 :                          poisson_env=poisson_env)
    4362          268 :          CALL auxbas_pw_pool%create_pw(v_hartree_gspace)
    4363          268 :          CALL auxbas_pw_pool%create_pw(rho_tot_gspace)
    4364              : 
    4365          268 :          CALL calc_rho_tot_gspace(rho_tot_gspace, qs_env, rho)
    4366              :          CALL pw_poisson_solve(poisson_env, rho_tot_gspace, energy%hartree, &
    4367          268 :                                v_hartree_gspace, rho_core=rho_core)
    4368              : 
    4369          268 :          CALL pw_transfer(v_hartree_gspace, v_hartree_rspace)
    4370          268 :          CALL pw_scale(v_hartree_rspace, v_hartree_rspace%pw_grid%dvol)
    4371              : 
    4372          268 :          CALL auxbas_pw_pool%give_back_pw(v_hartree_gspace)
    4373          268 :          CALL auxbas_pw_pool%give_back_pw(rho_tot_gspace)
    4374              :       END IF
    4375              : 
    4376          322 :    END SUBROUTINE update_hartree_with_mp2
    4377              : 
    4378            0 : END MODULE qs_scf_post_gpw
        

Generated by: LCOV version 2.0-1