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

Generated by: LCOV version 2.0-1