LCOV - code coverage report
Current view: top level - src - qs_scf_post_gpw.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:cb5d5fc) Lines: 86.6 % 1631 1413
Test Date: 2026-04-24 07:01:27 Functions: 97.1 % 34 33

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

Generated by: LCOV version 2.0-1