root/trunk/src/states.F90 @ 2905

Revision 2905, 61.3 KB (checked in by acastro, 3 years ago)

I changed the "mag" component of the states data type, by a new "spin"
data type.

The reason is that mag was not providing enough information. It
provided <Sz> and the occupation of the spinor (in a combined way),
but nothing about <Sx> or <Sy>. Now spin is (as it should be) a
three-vector, containing for each state the expectation value of each
one of the spin components.

I had to change a couple of tests, but I was as careful as I could to
make sure that the results did not change; just the presentation.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1!! Copyright (C) 2002-2006 M. Marques, A. Castro, A. Rubio, G. Bertsch
2!!
3!! This program is free software; you can redistribute it and/or modify
4!! it under the terms of the GNU General Public License as published by
5!! the Free Software Foundation; either version 2, or (at your option)
6!! any later version.
7!!
8!! This program is distributed in the hope that it will be useful,
9!! but WITHOUT ANY WARRANTY; without even the implied warranty of
10!! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11!! GNU General Public License for more details.
12!!
13!! You should have received a copy of the GNU General Public License
14!! along with this program; if not, write to the Free Software
15!! Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
16!! 02111-1307, USA.
17!!
18!! $Id$
19
20#include "global.h"
21
22module states_m
23  use crystal_m
24  use datasets_m
25  use functions_m
26  use geometry_m
27  use grid_m
28  use io_m
29  use lib_basic_alg_m
30  use lib_oct_m
31  use lib_oct_parser_m
32  use math_m
33  use mesh_function_m
34  use mesh_m
35  use mpi_m
36  use multicomm_m
37  use output_m
38  use profiling_m
39  use simul_box_m
40  use string_m
41  use varinfo_m
42
43  implicit none
44
45  private
46  public ::                           &
47    states_t,                         &
48    states_dim_t,                     &
49    states_init,                      &
50    states_read_user_def_orbitals,    &
51    states_densities_init,            &
52    states_allocate_wfns,             &
53    states_deallocate_wfns,           &
54    states_null,                      &
55    states_end,                       &
56    states_copy,                      &
57    states_generate_random,           &
58    states_fermi,                     &
59    states_eigenvalues_sum,           &
60    states_write_eigenvalues,         &
61    states_write_dos,                 &
62    states_write_bands,               &
63    states_write_fermi_energy,        &
64    states_degeneracy_matrix,         &
65    states_write_current_flow,        &
66    states_spin_channel,              &
67    states_calc_dens,                 &
68    states_paramagnetic_current,      &
69    kpoints_write_info,               &
70    wfs_are_complex,                  &
71    wfs_are_real,                     &
72    states_dump,                      &
73    assignment(=)
74
75
76  public ::                         &
77    dstates_gram_schmidt,           &
78    zstates_gram_schmidt,           &
79    dstates_dotp,                   &
80    zstates_dotp,                   &
81    dstates_nrm2,                   &
82    zstates_nrm2,                   &
83    dstates_normalize_orbital,      &
84    zstates_normalize_orbital,      &
85    dstates_residue,                &
86    zstates_residue,                &
87    dstates_calc_momentum,          &
88    zstates_calc_momentum,          &
89    dstates_angular_momentum,       &
90    zstates_angular_momentum,       &
91    states_distribute_nodes
92
93  type states_t
94
95    type(states_dim_t), pointer :: d
96    integer :: nst                  ! Number of states in each irreducible subspace
97
98    ! pointers to the wavefunctions
99    FLOAT, pointer :: dpsi(:,:,:,:) ! dpsi(sys%NP_PART, st%d%dim, st%nst, st%d%nik)
100    CMPLX, pointer :: zpsi(:,:,:,:) ! zpsi(sys%NP_PART, st%d%dim, st%nst, st%d%nik)
101
102    ! used for the user defined wavefunctions (they are stored as formula strings)
103    character(len=1024), pointer :: user_def_states(:,:,:) ! (st%d%dim, st%nst, st%d%nik)
104
105    ! the densities and currents (after all we are doing DFT :)
106    FLOAT, pointer :: rho(:,:)      ! rho(gr%m%np_part, st%d%nspin)
107    FLOAT, pointer :: j(:,:,:)      !   j(gr%m%np_part, gr%sb%dim, st%d%nspin)
108
109    FLOAT, pointer :: rho_core(:)   ! core charge for nl core corrections
110
111    FLOAT, pointer :: eigenval(:,:) ! obviously the eigenvalues
112    logical        :: fixed_occ     ! should the occupation numbers be fixed?
113    FLOAT, pointer :: occ(:,:)      ! the occupation numbers
114    FLOAT, pointer :: spin(:, :, :)
115    FLOAT, pointer :: momentum(:, :, :)
116
117    FLOAT :: qtot                   ! (-) The total charge in the system (used in Fermi)
118    FLOAT :: val_charge             ! valence charge
119
120    FLOAT :: el_temp                ! electronic temperature for the Fermi function
121    FLOAT :: ef                     ! the fermi energy
122
123    ! This is stuff needed for the parallelization in states
124    logical :: parallel_in_states   ! am I parallel in states?
125    type(mpi_grp_t) :: mpi_grp   ! the MPI group related to the parallelization in states
126
127    integer :: st_start, st_end     ! needed for some parallel parts
128    integer, pointer :: node(:)     ! To which node belongs each state.
129  end type states_t
130
131  type states_dim_t
132    integer :: wfs_type             ! real (M_REAL) or complex (M_CMPLX) wavefunctions
133    integer :: dim                  ! Dimension of the state (one or two for spinors)
134    integer :: nik                  ! Number of irreducible subspaces
135    integer :: nik_axis(MAX_DIM)    ! Number of kpoints per axis
136    integer :: ispin                ! spin mode (unpolarized, spin polarized, spinors)
137    integer :: nspin                ! dimension of rho (1, 2 or 4)
138    integer :: spin_channels        ! 1 or 2, wether spin is or not considered.
139    logical :: cdft                 ! Are we using Current-DFT or not?
140    FLOAT, pointer :: kpoints(:,:)  ! obviously the kpoints
141    FLOAT, pointer :: kweights(:)   ! weights for the kpoint integrations
142  end type states_dim_t
143
144
145  ! Parameters...
146  integer, public, parameter ::     &
147    UNPOLARIZED    = 1,             &
148    SPIN_POLARIZED = 2,             &
149    SPINORS        = 3
150
151  interface assignment (=)
152    module procedure states_copy
153  end interface
154
155  interface dstates_gram_schmidt
156    module procedure dstates_gram_schmidt1, dstates_gram_schmidt2
157  end interface
158
159  interface zstates_gram_schmidt
160    module procedure zstates_gram_schmidt1, zstates_gram_schmidt2
161  end interface
162
163contains
164
165  ! ---------------------------------------------------------
166  subroutine states_null(st)
167    type(states_t), intent(inout) :: st
168    call push_sub('states.states_null')
169
170    nullify(st%dpsi, st%zpsi, st%rho, st%j, st%rho_core, st%eigenval)
171    nullify(st%occ, st%spin, st%momentum, st%node, st%user_def_states)
172
173    nullify(st%d)
174    ALLOCATE(st%d, 1)
175    nullify(st%d%kpoints, st%d%kweights)
176
177    ! By default, calculations use real wave-functions
178    st%d%wfs_type = M_REAL
179
180    call pop_sub()
181  end subroutine states_null
182
183
184  ! ---------------------------------------------------------
185  subroutine states_init(st, gr, geo)
186    type(states_t),    intent(inout) :: st
187    type(grid_t),      intent(in)    :: gr
188    type(geometry_t),  intent(in)    :: geo
189
190
191    FLOAT :: excess_charge, r
192    integer :: nempty, i, j
193    C_POINTER :: blk
194
195    call push_sub('states.states_init')
196
197    call states_null(st)
198
199    !%Variable SpinComponents
200    !%Type integer
201    !%Default unpolarized
202    !%Section States
203    !%Description
204    !% The calculations may be done in three different ways: spin-restricted (TD)DFT (i.e., doubly
205    !% occupied "closed shells"), spin-unsrestricted or "spin-polarized" (TD)DFT (i.e. we have two
206    !% electronic systes, one with spin up and one with spin down), or making use of two-component
207    !% spinors.
208    !%Option unpolarized 1
209    !% Spin-restricted calculations.
210    !%Option polarized 2
211    !%Option spin_polarized 2
212    !% Spin unrestricted, also know as spin-DFT, SDFT. This mode will double the number of wave
213    !% functions will double the number of wave-functions necessary for a spin-unpolarised
214    !% calculation.
215    !%Option non_collinear 3
216    !%Option spinors 3
217    !% The spin-orbitals are two-component spinors. This effectively allows the spin-density to
218    !% arrange non-collinearly - i.e. the magnetization vector is allowed to take different
219    !% directions in different points.
220    !%End
221    call loct_parse_int(check_inp('SpinComponents'), UNPOLARIZED, st%d%ispin)
222    if(.not.varinfo_valid_option('SpinComponents', st%d%ispin)) call input_error('SpinComponents')
223    call messages_print_var_option(stdout, 'SpinComponents', st%d%ispin)
224    ! Use of Spinors requires complex wave-functions
225    if (st%d%ispin == SPINORS) st%d%wfs_type = M_CMPLX
226
227
228    !%Variable ExcessCharge
229    !%Type float
230    !%Default 0.0
231    !%Section States
232    !%Description
233    !% The net charge of the system. A negative value means that we are adding
234    !% electrons, while a positive value means we are taking electrons
235    !% from the system.
236    !%End
237    call loct_parse_float(check_inp('ExcessCharge'), M_ZERO, excess_charge)
238
239
240    !%Variable ExtraStates
241    !%Type integer
242    !%Default 0
243    !%Section States
244    !%Description
245    !% The number of states is in principle calculated considering the minimum
246    !% numbers of states necessary to hold the electrons present in the system.
247    !% The number of electrons is
248    !% in turn calculated considering the nature of the species supplied in the
249    !% <tt>Species</tt> block, and the value of the <tt>ExcessCharge</tt> variable.
250    !% However, one may command <tt>octopus</tt> to put more states, which is necessary if one wants to
251    !% use fractional occupational numbers, either fixed from the origin through
252    !% the <tt>Occupations</tt> block or by prescribing
253    !% an electronic temperature with <tt>ElectronicTemperature</tt>.
254    !%
255    !% Note that this number is unrelated to <tt>CalculationMode == unocc</tt>.
256    !%End
257    call loct_parse_int(check_inp('ExtraStates'), 0, nempty)
258    if (nempty < 0) then
259      write(message(1), '(a,i5,a)') "Input: '", nempty, "' is not a valid ExtraStates"
260      message(2) = '(0 <= ExtraStates)'
261      call write_fatal(2)
262    end if
263
264    call geometry_val_charge(geo, st%val_charge)
265    st%qtot = -(st%val_charge + excess_charge)
266
267    select case(st%d%ispin)
268    case(UNPOLARIZED)
269      st%d%dim = 1
270      st%nst = int(st%qtot/2)
271      if(st%nst*2 < st%qtot) st%nst = st%nst + 1
272      st%nst = st%nst + nempty
273      st%d%nspin = 1
274      st%d%spin_channels = 1
275    case(SPIN_POLARIZED)
276      st%d%dim = 1
277      st%nst = int(st%qtot/2)
278      if(st%nst*2 < st%qtot) st%nst = st%nst + 1
279      st%nst = st%nst + nempty
280      st%d%nik = st%d%nik*2
281      st%d%nspin = 2
282      st%d%spin_channels = 2
283    case(SPINORS)
284      st%d%dim = 2
285      st%nst = int(st%qtot)
286      if(st%nst < st%qtot) st%nst = st%nst + 1
287      st%nst = st%nst + nempty
288      st%d%nspin = 4
289      st%d%spin_channels = 2
290    end select
291
292    ! current
293    call loct_parse_logical(check_inp('CurrentDFT'), .false., st%d%cdft)
294    if (st%d%cdft) then
295      ! Use of CDFT requires complex wave-functions
296      st%d%wfs_type = M_CMPLX
297
298      if(st%d%ispin == SPINORS) then
299        message(1) = "Sorry, Current DFT not working yet for spinors"
300        call write_fatal(1)
301      end if
302      message(1) = "Info: Using Current DFT"
303      call write_info(1)
304    end if
305
306    ! For non-periodic systems this should just return the Gamma point
307    call states_choose_kpoints(st%d, gr%sb, geo)
308
309    ! Periodic systems require complex wave-functions
310    if(simul_box_is_periodic(gr%sb)) st%d%wfs_type = M_CMPLX
311
312
313    ! we now allocate some arrays
314    ALLOCATE(st%occ     (st%nst, st%d%nik),      st%nst*st%d%nik)
315    ALLOCATE(st%eigenval(st%nst, st%d%nik),      st%nst*st%d%nik)
316    ALLOCATE(st%momentum(3, st%nst, st%d%nik), 3*st%nst*st%d%nik)
317    ! allocate space for formula strings that define user defined states
318    ALLOCATE(st%user_def_states(st%d%dim, st%nst, st%d%nik), st%d%dim*st%nst*st%d%nik)
319    if(st%d%ispin == SPINORS) then
320      ALLOCATE(st%spin(3, st%nst, st%d%nik), st%nst*st%d%nik*3)
321    end if
322
323    ! initially we mark all 'formulas' as undefined
324    st%user_def_states(1:st%d%dim, 1:st%nst, 1:st%d%nik) = 'undefined'
325
326    !%Variable Occupations
327    !%Type block
328    !%Section States
329    !%Description
330    !% The occupation numbers of the orbitals can be fixed through the use of this
331    !% variable. For example:
332    !%
333    !% <tt>%Occupations
334    !% <br>&nbsp;&nbsp;2.0 | 2.0 | 2.0 | 2.0 | 2.0
335    !% <br>%</tt>
336    !%
337    !% would fix the occupations of the five states to <i>2.0</i>. There must be
338    !% as many columns as states in the calculation. If <tt>SpinComponents == polarized</tt>
339    !% this block should contain two lines, one for each spin channel.
340    !% This variable is very useful when dealing with highly symmetric small systems
341    !% (like an open shell atom), for it allows us to fix the occupation numbers
342    !% of degenerate states in order to help <tt>octopus</tt> to converge. This is to
343    !% be used in conjuction with <tt>ExtraStates</tt>. For example, to calculate the
344    !% carbon atom, one would do:
345    !%
346    !% <tt>ExtraStates = 2
347    !% <br>%Occupations
348    !% <br>&nbsp;&nbsp;2 | 2/3 | 2/3 | 2/3
349    !% <br>%</tt>
350    !%End
351    occ_fix: if(loct_parse_block(check_inp('Occupations'), blk)==0) then
352      ! read in occupations
353      st%fixed_occ = .true.
354
355      do i = 1, st%d%nik
356        do j = 1, st%nst
357          call loct_parse_block_float(blk, i-1, j-1, st%occ(j, i))
358        end do
359      end do
360      call loct_parse_block_end(blk)
361    else
362      st%fixed_occ = .false.
363
364      ! first guess for occupation...paramagnetic configuration
365      if(st%d%ispin == UNPOLARIZED) then
366        r = M_TWO
367      else
368        r = M_ONE
369      end if
370      st%occ  = M_ZERO
371      st%qtot = M_ZERO
372
373      do j = 1, st%nst
374        do i = 1, st%d%nik
375          st%occ(j, i) = min(r, -(st%val_charge + excess_charge) - st%qtot)
376          st%qtot = st%qtot + st%occ(j, i)
377
378        end do
379      end do
380
381      !%Variable ElectronicTemperature
382      !%Type float
383      !%Default 0.0
384      !%Section States
385      !%Description
386      !% If <tt>Occupations</tt> is not set, <tt>ElectronicTemperature</tt> is the
387      !% temperature in the Fermi-Dirac function used to distribute the electrons
388      !% among the existing states.
389      !%End
390      call loct_parse_float(check_inp('ElectronicTemperature'), M_ZERO, st%el_temp)
391      st%el_temp = st%el_temp * units_inp%energy%factor
392    end if occ_fix
393
394    st%st_start = 1; st%st_end = st%nst
395    ALLOCATE(st%node(st%nst), st%nst)
396    st%node(1:st%nst) = 0
397
398    call mpi_grp_init(st%mpi_grp, -1)
399    st%parallel_in_states = .false.
400
401    nullify(st%dpsi, st%zpsi)
402
403    call pop_sub()
404  end subroutine states_init
405
406
407  ! ---------------------------------------------------------
408  ! Allocates the KS wavefunctions defined within an states_t
409  ! structure.
410  subroutine states_allocate_wfns(st, m, wfs_type)
411    type(states_t), intent(inout) :: st
412    type(mesh_t),    intent(in)    :: m
413    integer, optional, intent(in) :: wfs_type
414
415    integer :: n
416
417    call push_sub('states.states_allocate_wfns')
418
419    if (present(wfs_type)) then
420      ASSERT(wfs_type == M_REAL .or. wfs_type == M_CMPLX)
421      st%d%wfs_type = wfs_type
422    end if
423
424    n = m%np_part * st%d%dim * (st%st_end-st%st_start+1) * st%d%nik
425    if (st%d%wfs_type == M_REAL) then
426      ALLOCATE(st%dpsi(m%np_part, st%d%dim, st%st_start:st%st_end, st%d%nik), n)
427      st%dpsi = M_ZERO
428    else
429      ALLOCATE(st%zpsi(m%np_part, st%d%dim, st%st_start:st%st_end, st%d%nik), n)
430      st%zpsi = M_Z0
431    end if
432
433    call pop_sub()
434  end subroutine states_allocate_wfns
435
436
437  ! ---------------------------------------------------------
438  ! Deallocates the KS wavefunctions defined within an states_t
439  ! structure.
440  subroutine states_deallocate_wfns(st)
441    type(states_t), intent(inout) :: st
442
443    call push_sub('states.states_deallocate_wfns')
444
445    if (st%d%wfs_type == M_REAL) then
446      deallocate(st%dpsi); nullify(st%dpsi)
447    else
448      deallocate(st%zpsi); nullify(st%zpsi)
449    end if
450   
451    call pop_sub()
452  end subroutine states_deallocate_wfns
453
454
455  ! ---------------------------------------------------------
456  ! the routine reads formulas for user defined wavefunctions
457  ! from the input file and fills the respective orbitals
458  subroutine states_read_user_def_orbitals(mesh, st)
459    type(mesh_t),      intent(in) :: mesh
460    type(states_t), intent(inout) :: st   
461
462    C_POINTER :: blk
463    integer   :: ip, id, is, ik, nstates, ncols, ierr
464    integer   :: ib, idim, inst, inik, input_format
465    FLOAT     :: x(MAX_DIM), r, psi_re, psi_im
466    character(len=150) :: filename
467
468    integer, parameter ::      &
469      state_from_formula  = 4, &
470      state_from_file     = 5
471
472    call push_sub('td.read_user_def_states')
473
474    !%Variable UserDefinedStates
475    !%Type block
476    !%Section States
477    !%Description
478    !% Instead of using the ground state as initial state for
479    !% time propagations it might be interesting in some cases
480    !% to specify alternative states. Similar to user defined
481    !% potentials this block allows to specify formulas for
482    !% the orbitals at t=0.
483    !%
484    !% Example:
485    !%
486    !% <tt>%UserDefinedStates
487    !% <br>&nbsp;&nbsp; 1 | 1 | 1 |  "exp(-r^2)*exp(-i*0.2*x)"
488    !% <br>%</tt>
489    !%
490    !% The first column specifies the component of the spinor,
491    !% the second column the number of the state and the third
492    !% contains kpoint and spin quantum numbers. Finally column
493    !% four contains a formula for the correspondig orbital.
494    !%
495    !% Alternatively, if the block UserDefinedStates has 5 columns
496    !% the state can be read from a file
497    !%
498    !% <tt>%UserDefinedStates
499    !% <br>&nbsp;&nbsp; 1 | 1 | 1 | file_format | "/path/to/file"
500    !% <br>%</tt>
501    !%
502    !% The integer in column 4 defines the file format (currently
503    !% not implemented, so simply use 0 there) and column 5 contains
504    !% the filename.
505    !%
506    !% Octopus reads first the ground state orbitals from
507    !% the restart_gs directory. Only the states that are
508    !% specified in the above block will be overwritten with
509    !% the given analytical expression for the orbital.
510    !%
511    !%End
512    if(loct_parse_block(check_inp('UserDefinedStates'), blk) == 0) then
513
514      call messages_print_stress(stdout, trim('Substitution of orbitals'))
515
516      ! find out how many lines (i.e. states) the block has
517      nstates = loct_parse_block_n(blk)
518
519      ! read all lines
520      do ib = 1, nstates
521        call loct_parse_block_int(blk, ib-1, 0, idim)
522        call loct_parse_block_int(blk, ib-1, 1, inst)
523        call loct_parse_block_int(blk, ib-1, 2, inik)
524
525        ! find out how many columns this line has
526        ncols = loct_parse_block_cols(blk, ib-1)
527
528        ! loop over all states
529        do id = 1, st%d%dim
530          do is = 1, st%nst
531            do ik = 1, st%d%nik   
532             
533              ! does the block entry match and is this node responsible?
534              if(.not.(id.eq.idim .and. is.eq.inst .and. ik.eq.inik    &
535                .and. st%st_start.le.is .and. st%st_end.ge.is) ) cycle
536             
537              select case(ncols)
538
539              case(state_from_formula) ! if 4 colums are given we got a formula
540                ! parse formula string
541                call loct_parse_block_string(                            &
542                  blk, ib-1, 3, st%user_def_states(id, is, ik))
543               
544                write(message(1), '(a,3i5)') 'Substituting state of orbital with k, ist, dim = ', ik, is, id
545                write(message(2), '(2a)') '  with the expression:'
546                write(message(3), '(2a)') '  ',trim(st%user_def_states(id, is, ik))
547                call write_info(3)
548               
549                ! convert to C string
550                call conv_to_C_string(st%user_def_states(id, is, ik))
551               
552                ! fill states with user defined formulas
553                do ip = 1, mesh%np
554                  x = mesh%x(ip, :)
555                  r = sqrt(sum(x(:)**2))
556                 
557                  ! parse user defined expressions
558                  call loct_parse_expression(psi_re, psi_im,             &
559                    x(1), x(2), x(3), r, M_ZERO, st%user_def_states(id, is, ik))
560                  ! fill state
561                  st%zpsi(ip, id, is, ik) = psi_re + M_zI*psi_im
562                end do
563
564              case(state_from_file) ! if 5 colums are given we have to read from a file
565                ! first read the file format (format is not used at the moment; for flexibility
566                ! this could be added at a later point)
567                call loct_parse_block_int(blk, ib-1, 3, input_format)               
568                ! then read the filename
569                call loct_parse_block_string(blk, ib-1, 4, filename)
570
571                write(message(1), '(a,3i5)') 'Substituting state of orbital with k, ist, dim = ', ik, is, id
572                write(message(2), '(2a)') '  with data from file:'
573                write(message(3), '(2a)') '  ',trim(filename)
574                call write_info(3)
575
576                ! finally read the state
577                call zinput_function(filename, mesh, st%zpsi(:, id, is, ik), ierr, .true.)
578
579              end select
580
581              ! normalize orbital
582              call zstates_normalize_orbital(mesh, st%d%dim, st%zpsi(:,:, is, ik))
583             
584            end do
585          end do
586        end do
587       
588      end do
589
590      call loct_parse_block_end(blk)
591      call messages_print_stress(stdout)
592     
593    else
594      message(1) = '"UserDefinesStates" has to be specified as block.'
595      call write_fatal(1)
596    end if
597
598    call pop_sub()
599  end subroutine states_read_user_def_orbitals
600
601
602  ! ---------------------------------------------------------
603  subroutine states_densities_init(st, gr, geo)
604    type(states_t),    intent(inout) :: st
605    type(grid_t),      intent(in)    :: gr
606    type(geometry_t),  intent(in)    :: geo
607    call push_sub('states.states_densities_init')
608
609    ! allocate arrays for charge and current densities
610    ALLOCATE(st%rho(NP_PART, st%d%nspin), NP_PART*st%d%nspin)
611    ALLOCATE(st%j(NP_PART, NDIM, st%d%nspin), NP_PART*NDIM*st%d%nspin)
612    st%rho = M_ZERO
613    st%j   = M_ZERO
614    if(geo%nlcc) ALLOCATE(st%rho_core(gr%m%np), gr%m%np)
615
616    call pop_sub()
617  end subroutine states_densities_init
618
619
620  ! ---------------------------------------------------------
621  subroutine states_copy(stout, stin)
622    type(states_t), intent(inout) :: stout
623    type(states_t), intent(in)  :: stin
624
625    integer :: i, j, k, l
626
627    call states_null(stout)
628
629    stout%d%wfs_type = stin%d%wfs_type
630    stout%d%dim = stin%d%dim
631    stout%d%nik = stin%d%nik
632    stout%d%nik_axis(1:MAX_DIM) = stout%d%nik_axis(1:MAX_DIM)
633    stout%d%ispin = stin%d%ispin
634    stout%d%nspin = stin%d%nspin
635    stout%d%spin_channels = stin%d%spin_channels
636    stout%d%cdft = stin%d%cdft
637    stout%nst           = stin%nst
638    stout%qtot = stin%qtot
639    stout%el_temp = stin%el_temp
640    stout%ef = stin%ef
641    stout%st_start = stin%st_start
642    stout%st_end = stin%st_end
643    if(associated(stin%dpsi)) then
644      i = size(stin%dpsi, 1)*stin%d%dim*(stin%st_end-stin%st_start+1)*stin%d%nik
645      ALLOCATE(stout%dpsi(size(stin%dpsi, 1), stin%d%dim, stin%st_start:stin%st_end, stin%d%nik), i)
646      stout%dpsi = stin%dpsi
647    end if
648    if(associated(stin%zpsi)) then
649      i = size(stin%zpsi, 1)*stin%d%dim*(stin%st_end-stin%st_start+1)*stin%d%nik
650      ALLOCATE(stout%zpsi(size(stin%zpsi, 1), stin%d%dim, stin%st_start:stin%st_end, stin%d%nik), i)
651      stout%zpsi = stin%zpsi
652    end if
653    if(associated(stin%user_def_states)) then
654      j = size(stin%user_def_states, 1)
655      k = size(stin%user_def_states, 2)
656      l = size(stin%user_def_states, 3)
657      i = j*k*l
658      ALLOCATE(stout%user_def_states(j, k, l), i)
659      stout%user_def_states = stin%user_def_states
660    end if
661    if(associated(stin%rho)) then
662      i = size(stin%rho, 1)*size(stin%rho, 2)
663      ALLOCATE(stout%rho(size(stin%rho, 1), size(stin%rho, 2)), i)
664      stout%rho = stin%rho
665    end if
666    if(associated(stin%j)) then
667      i = size(stin%j, 1)*size(stin%j, 2)*size(stin%j, 3)
668      ALLOCATE(stout%j(size(stin%j, 1), size(stin%j, 2), size(stin%j, 3)), i)
669      stout%j = stin%j
670    end if
671    if(associated(stin%rho_core)) then
672      i = size(stin%rho_core, 1)
673      ALLOCATE(stout%rho_core(size(stin%rho_core, 1)), i)
674      stout%rho_core = stin%rho_core
675    end if
676    if(associated(stin%eigenval)) then
677      i = (stin%st_end-stin%st_start)*stin%d%nik
678      ALLOCATE(stout%eigenval(stin%st_start:stin%st_end, stin%d%nik), i)
679      stout%eigenval = stin%eigenval
680    end if
681    stout%fixed_occ = stin%fixed_occ
682    if(associated(stin%occ)) then
683      i = size(stin%occ, 1)*size(stin%occ, 2)
684      ALLOCATE(stout%occ(size(stin%occ, 1), size(stin%occ, 2)), i)
685      stout%occ = stin%occ
686    end if
687    if(associated(stin%spin)) then
688      i = size(stin%spin, 1)*size(stin%spin, 2)*size(stin%spin, 3)
689      ALLOCATE(stout%spin(size(stin%spin, 1), size(stin%spin, 2), size(stin%spin, 3)), i)
690      stout%spin = stin%spin
691    end if
692    if(associated(stin%momentum)) then
693      i = size(stin%momentum, 1)*size(stin%momentum, 2)*size(stin%momentum, 3)
694      ALLOCATE(stout%momentum(size(stin%momentum, 1), size(stin%momentum, 2), size(stin%momentum, 3)), i)
695      stout%momentum = stin%momentum
696    end if
697    if(associated(stin%d%kpoints)) then
698      i = size(stin%d%kpoints, 1)*size(stin%d%kpoints, 2)
699      ALLOCATE(stout%d%kpoints(size(stin%d%kpoints, 1), size(stin%d%kpoints, 2)), i)
700      stout%d%kpoints = stin%d%kpoints
701    end if
702    if(associated(stin%d%kweights)) then
703      i = size(stin%d%kweights, 1)
704      ALLOCATE(stout%d%kweights(size(stin%d%kweights, 1)), i)
705      stout%d%kweights = stin%d%kweights
706    end if
707    if(associated(stin%node)) then
708      i = size(stin%node)
709      ALLOCATE(stout%node(size(stin%node)), i)
710      stout%node = stin%node
711    end if
712  end subroutine states_copy
713
714
715  ! ---------------------------------------------------------
716  subroutine states_end(st)
717    type(states_t), intent(inout) :: st
718
719    call push_sub('states.states_end')
720
721    if(associated(st%rho)) then
722      deallocate(st%rho, st%occ, st%eigenval, st%momentum, st%node)
723      nullify   (st%rho, st%occ, st%eigenval, st%momentum, st%node)
724    end if
725 
726    if(associated(st%j)) then
727      deallocate(st%j)
728      nullify(st%j)
729    end if
730
731    if(associated(st%rho_core)) then
732      deallocate(st%rho_core)
733      nullify(st%rho_core)
734    end if
735
736    if(st%d%ispin==SPINORS .and. associated(st%spin)) then
737      deallocate(st%spin); nullify(st%spin)
738    end if
739
740    if(associated(st%dpsi)) then
741      deallocate(st%dpsi); nullify(st%dpsi)
742    end if
743
744    if(associated(st%zpsi)) then
745      deallocate(st%zpsi); nullify(st%zpsi)
746    end if
747
748    if(associated(st%d%kpoints)) then
749      deallocate(st%d%kpoints); nullify(st%d%kpoints)
750    end if
751
752    if(associated(st%d%kweights)) then
753      deallocate(st%d%kweights); nullify(st%d%kweights)
754    end if
755
756    if(associated(st%user_def_states)) then
757      deallocate(st%user_def_states); nullify(st%user_def_states)
758    end if
759
760    call pop_sub()
761  end subroutine states_end
762
763
764  ! ---------------------------------------------------------
765  ! Calculates the new density out the wavefunctions and
766  ! occupations...
767  subroutine states_calc_dens(st, np, rho)
768    type(states_t), intent(in)  :: st
769    integer,        intent(in)  :: np
770    FLOAT,          intent(out) :: rho(:,:)
771
772    integer :: i, ik, p, sp
773    CMPLX   :: c
774
775#ifdef HAVE_MPI
776    FLOAT,  allocatable :: reduce_rho(:)
777#endif
778
779    call push_sub('states.states_calc_dens')
780
781    if(st%d%ispin == SPIN_POLARIZED) then
782      sp = 2
783    else
784      sp = 1
785    end if
786
787    rho = M_ZERO
788    do ik = 1, st%d%nik, sp
789      do p  = st%st_start, st%st_end
790
791        do i = 1, np
792
793          if (st%d%wfs_type == M_REAL) then
794            rho(i, 1) = rho(i, 1) + st%d%kweights(ik)  *st%occ(p, ik)*abs(st%dpsi(i, 1, p, ik))**2
795          else
796            rho(i, 1) = rho(i, 1) + st%d%kweights(ik)  *st%occ(p, ik)*abs(st%zpsi(i, 1, p, ik))**2
797          end if
798          select case(st%d%ispin)
799
800          case(SPIN_POLARIZED)
801            if (st%d%wfs_type == M_REAL) then
802              rho(i, 2) = rho(i, 2) + st%d%kweights(ik+1)*st%occ(p, ik+1)*abs(st%dpsi(i, 1, p, ik+1))**2
803            else
804              rho(i, 2) = rho(i, 2) + st%d%kweights(ik+1)*st%occ(p, ik+1)*abs(st%zpsi(i, 1, p, ik+1))**2
805            end if
806          case(SPINORS) ! in this case wave-functions are always complex
807            rho(i, 2) = rho(i, 2) + st%d%kweights(ik)  *st%occ(p, ik)*abs(st%zpsi(i, 2, p, ik))**2
808
809            c = st%d%kweights(ik)*st%occ(p, ik) * st%zpsi(i, 1, p, ik) * conjg(st%zpsi(i, 2, p, ik))
810            rho(i, 3) = rho(i, 3) + real(c, REAL_PRECISION)
811            rho(i, 4) = rho(i, 4) + aimag(c)
812          end select
813
814        end do
815      end do
816    end do
817
818#ifdef HAVE_MPI
819    ! reduce density
820    if(st%parallel_in_states) then
821      ALLOCATE(reduce_rho(1:np), np)
822      do i = 1, st%d%nspin
823        call MPI_Allreduce(rho(1, i), reduce_rho(1), np, &
824           MPI_FLOAT, MPI_SUM, st%mpi_grp%comm, mpi_err)
825        rho(1:np, i) = reduce_rho(1:np)
826      end do
827      deallocate(reduce_rho)
828    end if
829#endif
830
831    call pop_sub()
832  end subroutine states_calc_dens
833
834
835  ! ---------------------------------------------------------
836  ! generate a hydrogen s-wavefunction around a random point
837  subroutine states_generate_random(st, m, ist_start_, ist_end_)
838    type(states_t), intent(inout) :: st
839    type(mesh_t),   intent(in)    :: m
840    integer, optional, intent(in) :: ist_start_, ist_end_
841
842    integer :: ist, ik, id, ist_start, ist_end
843
844    call push_sub('states.states_generate_random')
845
846    ist_start = 1
847    if(present(ist_start_)) ist_start = ist_start_
848    ist_end = st%nst
849    if(present(ist_end_)) ist_end = ist_end_
850
851    do ik = 1, st%d%nik
852      do ist = ist_start, ist_end
853        do id = 1, st%d%dim
854          if (st%d%wfs_type == M_REAL) then
855            call dmf_random(m, st%dpsi(:, id, ist, ik))
856          else
857            call zmf_random(m, st%zpsi(:, id, ist, ik))
858          end if
859        end do
860        st%eigenval(ist, ik) = M_ZERO
861      end do
862      ! Do not orthonormalize if we have parallelization in states.
863      if(.not.st%parallel_in_states) then
864        if (st%d%wfs_type == M_REAL) then
865          call dstates_gram_schmidt(ist_end, m, st%d%dim, st%dpsi(:,:,1:ist_end,ik), start = ist_start)
866        else
867          call zstates_gram_schmidt(ist_end, m, st%d%dim, st%zpsi(:,:,1:ist_end,ik), start = ist_start)
868        end if
869      end if
870    end do
871
872    call pop_sub()
873  end subroutine states_generate_random
874
875
876  ! ---------------------------------------------------------
877  subroutine states_fermi(st, m)
878    type(states_t), intent(inout) :: st
879    type(mesh_t),   intent(in)    :: m
880
881    ! Local variables
882    integer :: ie, ik, iter
883    integer, parameter :: nitmax = 200
884    FLOAT :: drange, t, emin, emax, sumq
885    FLOAT, parameter :: tol = CNST(1.0e-10)
886    logical :: conv
887
888    call push_sub('states.fermi')
889
890    if(st%fixed_occ) then ! nothing to do
891      ! Calculate magnetizations...
892      if(st%d%ispin == SPINORS) then
893        do ik = 1, st%d%nik
894          do ie = 1, st%nst
895            if (st%d%wfs_type == M_REAL) then
896              write(message(1),'(a)') 'Internal error in states_fermi'
897              call write_fatal(1)
898            else
899              st%spin(1:3, ie, ik) = state_spin(m, st%zpsi(:, :, ie, ik))
900            end if
901          end do
902        end do
903      end if
904      call pop_sub()
905      return
906    end if
907
908    ! Initializations
909    emin = minval(st%eigenval)
910    emax = maxval(st%eigenval)
911
912    if(st%d%ispin == SPINORS) then
913      sumq = real(st%nst, REAL_PRECISION)
914    else
915      sumq = M_TWO*st%nst
916    end if
917
918    t = max(st%el_temp, CNST(1.0e-6))
919    st%ef = emax
920
921    conv = .true.
922    if (abs(sumq - st%qtot) > tol) conv = .false.
923    if (conv) then ! all orbitals are full; nothing to be done
924      st%occ = M_TWO/st%d%spin_channels!st%d%nspin
925      ! Calculate magnetizations...
926      if(st%d%ispin == SPINORS) then
927        do ik = 1, st%d%nik
928          do ie = 1, st%nst
929            st%spin(1:3, ie, ik) = state_spin(m, st%zpsi(:, :, ie, ik))
930          end do
931        end do
932      end if
933      call pop_sub()
934      return
935    end if
936
937    if (sumq < st%qtot) then ! not enough states
938      message(1) = 'Fermi: Not enough states'
939      write(message(2),'(6x,a,f12.6,a,f12.6)')'(total charge = ', st%qtot, &
940        ' max charge = ', sumq
941      call write_fatal(2)
942    end if
943
944    drange = t*sqrt(-log(tol*CNST(.01)))
945
946    emin = emin - drange
947    emax = emax + drange
948
949    do iter = 1, nitmax
950      st%ef = M_HALF*(emin + emax)
951      sumq  = M_ZERO
952
953      do ik = 1, st%d%nik
954        do ie =1, st%nst
955          sumq = sumq + st%d%kweights(ik)/st%d%spin_channels * & !st%d%nspin * &
956            stepf((st%eigenval(ie, ik) - st%ef)/t)
957        end do
958      end do
959
960      conv = .true.
961      if(abs(sumq - st%qtot) > tol) conv = .false.
962      if(conv) exit
963
964      if(sumq <= st%qtot ) emin = st%ef
965      if(sumq >= st%qtot ) emax = st%ef
966    end do
967
968    if(iter == nitmax) then
969      message(1) = 'Fermi: did not converge'
970      call write_fatal(1)
971    end if
972
973    do ik = 1, st%d%nik
974      do ie = 1, st%nst
975        st%occ(ie, ik) = stepf((st%eigenval(ie, ik) - st%ef)/t)/st%d%spin_channels!st%d%nspin
976      end do
977    end do
978
979    ! Calculate magnetizations...
980    if(st%d%ispin == SPINORS) then
981      do ik = 1, st%d%nik
982        do ie = 1, st%nst
983          st%spin(1:3, ie, ik) = state_spin(m, st%zpsi(:, :, ie, ik))
984        end do
985      end do
986    end if
987
988    call pop_sub()
989  end subroutine states_fermi
990
991
992  ! ---------------------------------------------------------
993  ! function to calculate the eigenvalues sum using occupations as weights
994  function states_eigenvalues_sum(st, x) result(e)
995    type(states_t), intent(in)  :: st
996    FLOAT                       :: e
997    FLOAT, optional, intent(in) :: x(:, :)
998
999    integer :: ik
1000#ifdef HAVE_MPI
1001    FLOAT :: s
1002#endif
1003
1004    e = M_ZERO
1005    do ik = 1, st%d%nik
1006      if(present(x)) then
1007        e = e + st%d%kweights(ik) * sum(st%occ(st%st_start:st%st_end, ik)* &
1008          x(st%st_start:st%st_end, ik))
1009      else
1010        e = e + st%d%kweights(ik) * sum(st%occ(st%st_start:st%st_end, ik)* &
1011          st%eigenval(st%st_start:st%st_end, ik))
1012      end if
1013    end do
1014
1015#ifdef HAVE_MPI
1016    if(st%parallel_in_states) then
1017      call MPI_Allreduce(e, s, 1, MPI_FLOAT, MPI_SUM, st%mpi_grp%comm, mpi_err)
1018      e = s
1019    end if
1020#endif
1021
1022  end function states_eigenvalues_sum
1023
1024
1025  ! ---------------------------------------------------------
1026  subroutine states_write_eigenvalues(iunit, nst, st, sb, error)
1027    integer,           intent(in) :: iunit, nst
1028    type(states_t),    intent(in) :: st
1029    type(simul_box_t), intent(in) :: sb
1030    FLOAT,             intent(in), optional :: error(nst, st%d%nik)
1031
1032    integer ik, j, ns, is
1033    FLOAT :: o
1034    character(len=80) tmp_str(MAX_DIM), cspin
1035
1036    call push_sub('states.states_write_eigenvalues')
1037
1038    ns = 1
1039    if(st%d%nspin == 2) ns = 2
1040
1041    message(1) = 'Eigenvalues [' // trim(units_out%energy%abbrev) // ']'
1042    call write_info(1, iunit)
1043    if (st%d%nik > ns) then
1044      message(1) = 'Kpoints [' // trim(units_out%length%abbrev) // '^-1]'
1045      call write_info(1, iunit)
1046    end if
1047
1048    if(.not.mpi_grp_is_root(mpi_world)) return
1049
1050    do ik = 1, st%d%nik, ns
1051      if(st%d%nik > ns) then
1052        write(message(1), '(a,i4,3(a,f12.6),a)') '#k =',ik,', k = (',  &
1053          st%d%kpoints(1, ik)*units_out%length%factor, ',',            &
1054          st%d%kpoints(2, ik)*units_out%length%factor, ',',            &
1055          st%d%kpoints(3, ik)*units_out%length%factor, ')'
1056        call write_info(1, iunit)
1057      end if
1058
1059      if(present(error)) then
1060        if(st%d%ispin .eq. SPINORS) then
1061          write(message(1), '(a4,1x,a5,1x,a12,1x,a12,2x,a4,4x,a4,4x,a4,5x,a5)')   &
1062            '#st',' Spin',' Eigenvalue', 'Occupation ', '<Sx>', '<Sy>', '<Sz>', 'Error'
1063        else
1064          write(message(1), '(a4,1x,a5,1x,a12,4x,a12,1x,a10)')   &
1065            '#st',' Spin',' Eigenvalue', 'Occupation ', 'Error'
1066        end if
1067      else
1068        if(st%d%ispin .eq. SPINORS) then
1069          write(message(1), '(a4,1x,a5,1x,a12,1x,a12,2x,a4,4x,a4,4x,a4)')   &
1070            '#st',' Spin',' Eigenvalue', 'Occupation ', '<Sx>', '<Sy>', '<Sz>'
1071        else
1072          write(message(1), '(a4,1x,a5,1x,a12,4x,a12,1x)')       &
1073            '#st',' Spin',' Eigenvalue', 'Occupation '
1074        end if
1075      end if
1076      call write_info(1, iunit)
1077
1078      do j = 1, nst
1079        do is = 0, ns-1
1080          if(j > st%nst) then
1081            o = M_ZERO
1082          else
1083            o = st%occ(j, ik+is)
1084          end if
1085
1086          if(is.eq.0) cspin = 'up'
1087          if(is.eq.1) cspin = 'dn'
1088          if(st%d%ispin.eq.UNPOLARIZED.or.st%d%ispin.eq.SPINORS) cspin = '--'
1089
1090          write(tmp_str(1), '(i4,3x,a2)') j, trim(cspin)
1091          if(simul_box_is_periodic(sb)) then
1092            if(st%d%ispin == SPINORS) then
1093              write(tmp_str(2), '(1x,f12.6,3x,4f5.2)') &
1094                (st%eigenval(j, ik)-st%ef)/units_out%energy%factor, o, st%spin(1:3, j, ik)
1095              if(present(error)) write(tmp_str(3), '(a7,es7.1,a1)')'      (', error(j, ik+is), ')'
1096            else
1097              write(tmp_str(2), '(1x,f12.6,3x,f12.6)') &
1098                (st%eigenval(j, ik+is))/units_out%energy%factor, o
1099              if(present(error)) write(tmp_str(3), '(a7,es7.1,a1)')'      (', error(j, ik), ')'
1100            end if
1101          else
1102            if(st%d%ispin == SPINORS) then
1103              write(tmp_str(2), '(1x,f12.6,5x,f5.2,3x,3f8.4)') &
1104                st%eigenval(j, ik)/units_out%energy%factor, o, st%spin(1:3, j, ik)
1105              if(present(error)) write(tmp_str(3), '(a3,es7.1,a1)')'  (', error(j, ik+is), ')'
1106            else
1107              write(tmp_str(2), '(1x,f12.6,3x,f12.6)') &
1108                st%eigenval(j, ik+is)/units_out%energy%factor, o
1109              if(present(error)) write(tmp_str(3), '(a7,es7.1,a1)')'      (', error(j, ik), ')'
1110            end if
1111          end if
1112          if(present(error)) then
1113            message(1) = trim(tmp_str(1))//trim(tmp_str(2))//trim(tmp_str(3))
1114          else
1115            message(1) = trim(tmp_str(1))//trim(tmp_str(2))
1116          end if
1117          call write_info(1, iunit)
1118        end do
1119      end do
1120    end do
1121
1122    call pop_sub()
1123  end subroutine states_write_eigenvalues
1124
1125
1126  ! ---------------------------------------------------------
1127  subroutine states_write_bands(dir, nst, st, sb)
1128    character(len=*),  intent(in) :: dir   
1129    integer,           intent(in) :: nst
1130    type(states_t),    intent(in) :: st
1131    type(simul_box_t), intent(in) :: sb
1132
1133    integer :: i, ik, j, ns, is
1134    integer, allocatable :: iunit(:)
1135    FLOAT   :: factor(MAX_DIM)
1136    logical :: grace_mode, gnuplot_mode
1137    character(len=80) :: filename   
1138
1139    call push_sub('states.states_write_bands')
1140
1141    if(.not.mpi_grp_is_root(mpi_world)) return
1142
1143    !%Variable OutputBandsGnuplotMode
1144    !%Type logical
1145    !%Default no
1146    !%Section Output
1147    !%Description
1148    !% The band file will be written in gnuplot friendly format
1149    !%End
1150    call loct_parse_logical(check_inp('OutputBandsGnuplotMode'), .true., gnuplot_mode)
1151
1152    !%Variable OutputBandsGraceMode
1153    !%Type logical
1154    !%Default no
1155    !%Section Output
1156    !%Description
1157    !% The band file will be written in grace friendly format
1158    !%End
1159    call loct_parse_logical(check_inp('OutputBandsGraceMode'), .false., grace_mode)
1160
1161    ! shortcuts
1162    ns = 1
1163    if(st%d%nspin == 2) ns = 2
1164
1165    ALLOCATE(iunit(0:ns-1), ns)
1166
1167    ! define the scaling factor to output k_i/G_i, instead of k_i
1168    do i = 1, MAX_DIM
1169      factor(i) = M_ONE
1170      if (sb%klat(i,i) /= M_ZERO) factor(i) = sb%klat(i,i)     
1171    end do
1172
1173    if (gnuplot_mode) then
1174      do is = 0, ns-1
1175        if (ns.gt.1) then
1176          write(filename, '(a,i1.1,a)') 'bands-gp-', is+1,'.dat'
1177        else
1178          write(filename, '(a)') 'bands-gp.dat'
1179        end if
1180        iunit(is) = io_open(trim(dir)//'/'//trim(filename), action='write')   
1181        ! write header
1182        write(iunit(is), '(a, i6)') '# kx ky kz (unscaled), kx ky kz (scaled), bands:', nst
1183      end do
1184
1185      ! output bands in gnuplot format
1186      do j = 1, nst
1187        do ik = 1, st%d%nik, ns
1188          do is = 0, ns-1
1189            write(iunit(is), '(1x,6f14.8,3x,f14.8)')            &
1190              st%d%kpoints(1:MAX_DIM, ik+is),                   & ! unscaled
1191              st%d%kpoints(1:MAX_DIM, ik+is)/factor(1:MAX_DIM), & ! scaled
1192              st%eigenval(j, ik+is)/units_out%energy%factor
1193          end do
1194        end do
1195        do is = 0, ns-1
1196          write(iunit(is), '(a)') ''
1197        end do
1198      end do
1199      do is = 0, ns-1
1200        call io_close(iunit(is))
1201      end do
1202    end if
1203
1204    if (grace_mode) then
1205      do is = 0, ns-1
1206        if (ns.gt.1) then
1207          write(filename, '(a,i1.1,a)') 'bands-grace-', is+1,'.dat'
1208        else
1209          write(filename, '(a)') 'bands-grace.dat'
1210        end if
1211        iunit(is) = io_open(trim(dir)//'/'//trim(filename), action='write')   
1212        ! write header
1213        write(iunit(is), '(a, i6)') '# kx ky kz (unscaled), kx ky kz (scaled), bands:', nst
1214      end do
1215
1216      ! output bands in xmgrace format, i.e.:
1217      ! k_x, k_y, k_z, e_1, e_2, ..., e_n
1218      do ik = 1, st%d%nik, ns
1219        do is = 0, ns-1
1220          write(iunit(is), '(1x,6f14.8,3x,16384f14.8)')         &
1221            st%d%kpoints(1:MAX_DIM, ik+is),                     & ! unscaled
1222            st%d%kpoints(1:MAX_DIM, ik+is)/factor(1:MAX_DIM),   & ! scaled
1223            (st%eigenval(j, ik+is)/units_out%energy%factor, j = 1, nst)
1224        end do
1225      end do
1226      do is = 0, ns-1
1227        call io_close(iunit(is))
1228      end do       
1229    end if
1230
1231    deallocate(iunit)
1232
1233    call pop_sub()
1234  end subroutine states_write_bands
1235
1236
1237  ! ---------------------------------------------------------
1238  subroutine states_write_dos(dir, st)
1239    character(len=*), intent(in) :: dir
1240    type(states_t),   intent(in) :: st
1241
1242    integer :: ie, ik, ist, epoints, is, ns
1243    integer, allocatable :: iunit(:)
1244    FLOAT   :: emin, emax, de, gamma, energy
1245    FLOAT   :: evalmax, evalmin, tdos, eextend
1246    FLOAT, allocatable :: dos(:,:,:)
1247    character(len=64)  :: filename
1248
1249    call push_sub('states.states_write_dos')
1250
1251    evalmin = minval(st%eigenval/units_out%energy%factor)
1252    evalmax = maxval(st%eigenval/units_out%energy%factor)
1253    ! we extend the energy mesh by this amount
1254    eextend  = (evalmax - evalmin) / M_FOUR
1255
1256    !%Variable DOSEnergyMin
1257    !%Type float
1258    !%Default
1259    !%Section Output
1260    !%Description
1261    !% Lower bound for the energy mesh of the DOS
1262    !%End
1263    call loct_parse_float(check_inp('DOSEnergyMin'), evalmin - eextend, emin)
1264
1265    !%Variable DOSEnergyMax
1266    !%Type float
1267    !%Default
1268    !%Section Output
1269    !%Description
1270    !% Upper bound for the energy mesh of the DOS
1271    !%End
1272    call loct_parse_float(check_inp('DOSEnergyMax'), evalmax + eextend, emax)
1273
1274    !%Variable DOSEnergyPoints
1275    !%Type integer
1276    !%Default 500
1277    !%Section Output
1278    !%Description
1279    !% Determines how many energy points octopus should use for
1280    !% the DOS energy grid
1281    !%End
1282    call loct_parse_int(check_inp('DOSEnergyPoints'), 500, epoints)
1283
1284    !%Variable DOSGamma
1285    !%Type float
1286    !%Default
1287    !%Section Output
1288    !%Description
1289    !% Determines the width of the Lorentzian which is used to sum
1290    !% up the DOS sum
1291    !%End
1292    call loct_parse_float(check_inp('DOSGamma'), &
1293      CNST(0.008)/units_out%energy%factor, gamma)
1294
1295    ! spacing for energy mesh
1296    de = (emax - emin) / (epoints - 1)
1297
1298    ! shortcuts
1299    ns = 1
1300    if(st%d%nspin == 2) ns = 2
1301
1302    ! space for state dependent DOS
1303    ALLOCATE(dos(epoints, st%nst, 0:ns-1), epoints*st%nst*ns)
1304    ALLOCATE(iunit(0:ns-1), ns)   
1305
1306    ! compute band/spin resolved density of states
1307    do ist = 1, st%nst
1308
1309      do is = 0, ns-1
1310        if (ns.gt.1) then
1311          write(filename, '(a,i4.4,a,i1.1,a)') 'dos-', ist, '-', is+1,'.dat'
1312        else
1313          write(filename, '(a,i4.4,a)') 'dos-', ist, '.dat'
1314        end if
1315        iunit(is) = io_open(trim(dir)//'/'//trim(filename), action='write')   
1316        ! write header
1317        write(iunit(is), '(a)') '# energy, band resolved DOS'
1318      end do
1319     
1320      do ie = 1, epoints
1321        energy = emin + (ie - 1) * de
1322        dos(ie, ist, :) = M_ZERO
1323        ! sum up Lorentzians
1324        do ik = 1, st%d%nik, ns
1325          do is = 0, ns-1
1326            dos(ie, ist, is) = dos(ie, ist, is) + st%d%kweights(ik+is) * M_ONE/M_Pi * &
1327              gamma / ( (energy - st%eigenval(ist, ik+is)/units_out%energy%factor)**2 + gamma**2 )
1328          end do
1329        end do
1330        do is = 0, ns-1
1331          write(message(1), '(2f12.6)') energy, dos(ie, ist, is)
1332          call write_info(1, iunit(is))
1333        end do
1334      end do
1335
1336      do is = 0, ns-1
1337        call io_close(iunit(is))
1338      end do
1339    end do
1340
1341    ! for spin polarized calculations also output spin resolved tdos
1342    if(st%d%nspin .gt. 1) then   
1343      do is = 0, ns-1
1344        write(filename, '(a,i1.1,a)') 'total-dos-', is+1,'.dat'
1345        iunit(is) = io_open(trim(dir)//'/'//trim(filename), action='write')   
1346        ! write header
1347        write(iunit(is), '(a)') '# energy, total DOS (spin resolved)'
1348
1349        do ie = 1, epoints
1350          energy = emin + (ie - 1) * de
1351          tdos = M_ZERO
1352          do ist = 1, st%nst
1353            tdos = tdos + dos(ie, ist, is)
1354          end do
1355          write(message(1), '(2f12.6)') energy, tdos
1356          call write_info(1, iunit(is))
1357        end do
1358
1359        call io_close(iunit(is))
1360      end do
1361    end if
1362
1363
1364    iunit(0) = io_open(trim(dir)//'/'//'total-dos.dat', action='write')   
1365
1366    ! compute total density of states
1367    do ie = 1, epoints
1368      energy = emin + (ie - 1) * de
1369      tdos = M_ZERO
1370      do ist = 1, st%nst
1371        do is = 0, ns-1
1372          tdos = tdos + dos(ie, ist, is)
1373        end do
1374      end do
1375      write(message(1), '(2f12.6)') energy, tdos
1376      call write_info(1, iunit(0))
1377    end do
1378
1379    call io_close(iunit(0))
1380
1381    deallocate(iunit, dos)
1382
1383    call pop_sub()
1384  end subroutine states_write_dos
1385
1386
1387  ! ---------------------------------------------------------
1388  subroutine states_write_fermi_energy(dir, st, m, sb)
1389    character(len=*),  intent(in) :: dir
1390    type(states_t), intent(inout) :: st
1391    type(mesh_t),      intent(in) :: m
1392    type(simul_box_t), intent(in) :: sb
1393
1394    integer :: iunit, i
1395    FLOAT :: scale, maxdos
1396    FLOAT :: factor(MAX_DIM)
1397
1398    call push_sub('states.states_write_fermi_energy')
1399
1400    call states_fermi(st, m)
1401   
1402    iunit = io_open(trim(dir)//'/'//'bands-efermi.dat', action='write')   
1403
1404    scale = units_out%energy%factor
1405
1406    ! define the scaling factor to output k_i/G_i, instead of k_i
1407    do i = 1, MAX_DIM
1408      factor(i) = M_ONE
1409      if (sb%klat(i,i) /= M_ZERO) factor(i) = sb%klat(i,i)
1410    end do
1411
1412    ! write fermi energy in a format that can be used together
1413    ! with bands.dat
1414    write(message(1), '(a)') '# Fermi energy in a format compatible with bands-gp.dat'
1415
1416    write(message(2), '(7f12.6)')          &
1417      minval(st%d%kpoints(1,:)),           &
1418      minval(st%d%kpoints(2,:)),           &
1419      minval(st%d%kpoints(3,:)),           &
1420      minval(st%d%kpoints(1,:)/factor(1)), &
1421      minval(st%d%kpoints(2,:)/factor(2)), &
1422      minval(st%d%kpoints(3,:)/factor(3)), &
1423      st%ef/scale
1424
1425    ! Gamma point
1426    write(message(3), '(7f12.6)')          &
1427      (M_ZERO, i = 1, 6),                  &
1428      st%ef/scale
1429   
1430    write(message(4), '(7f12.6)')          &
1431      maxval(st%d%kpoints(1,:)),           &
1432      maxval(st%d%kpoints(2,:)),           &
1433      maxval(st%d%kpoints(3,:)),           &
1434      maxval(st%d%kpoints(1,:)/factor(1)), &
1435      maxval(st%d%kpoints(2,:)/factor(2)), &
1436      maxval(st%d%kpoints(3,:)/factor(3)), &
1437      st%ef/scale
1438
1439    call write_info(4, iunit)
1440    call io_close(iunit)
1441
1442    ! now we write the same information so that it can be used
1443    ! together with total-dos.dat
1444    iunit = io_open(trim(dir)//'/'//'total-dos-efermi.dat', action='write')   
1445
1446    write(message(1), '(a)') '# Fermi energy in a format compatible with total-dos.dat'   
1447   
1448    ! this is the maximum that tdos can reach
1449    maxdos = sum(st%d%kweights) * st%nst
1450
1451    write(message(2), '(4f12.6)') st%ef/scale, M_ZERO
1452    write(message(3), '(4f12.6)') st%ef/scale, maxdos
1453
1454    call write_info(3, iunit)
1455    call io_close(iunit)
1456
1457    call pop_sub()
1458  end subroutine states_write_fermi_energy
1459
1460
1461  ! -------------------------------------------------------
1462  subroutine states_degeneracy_matrix(st)
1463    type(states_t), intent(in) :: st
1464
1465    integer :: is, js, inst, inik, dsize, iunit
1466    integer, allocatable :: eindex(:,:), sindex(:)
1467    integer, allocatable :: degeneracy_matrix(:, :)
1468    FLOAT,   allocatable :: eigenval_sorted(:)
1469    FLOAT :: degen_thres, evis, evjs
1470
1471    call push_sub('states.states_degeneracy_matrix')
1472
1473    ALLOCATE(eigenval_sorted(st%nst*st%d%nik),   st%nst*st%d%nik)
1474    ALLOCATE(         sindex(st%nst*st%d%nik),   st%nst*st%d%nik)
1475    ALLOCATE(      eindex(2, st%nst*st%d%nik), 2*st%nst*st%d%nik)
1476    dsize = st%nst*st%d%nik * st%nst*st%d%nik
1477    ALLOCATE(degeneracy_matrix(st%nst*st%d%nik, st%nst*st%d%nik), dsize)
1478   
1479    ! convert double index "inst, inik" to single index "is"
1480    ! and keep mapping array
1481    is = 1
1482    do inst = 1, st%nst
1483      do inik = 1, st%d%nik
1484        eigenval_sorted(is) = st%eigenval(inst, inik)       
1485        eindex(1, is) = inst
1486        eindex(2, is) = inik
1487        is = is + 1
1488      end do
1489    end do
1490   
1491    ! sort eigenvalues
1492    call sort(eigenval_sorted, sindex)
1493
1494    !%Variable DegeneracyMatrixThreshold
1495    !%Type float
1496    !%Default 1e-5
1497    !%Section States
1498    !%Description
1499    !% A state j with energy E_j will be considered degenerate with a state
1500    !% with energy E_i, if  E_i - threshold < E_j < E_i + threshold.
1501    !%End
1502    call loct_parse_float(check_inp('DegeneracyMatrixThreshold'), CNST(1e-5), degen_thres)   
1503
1504    ! setup degeneracy matrix. the matrix summarizes the degeneracy relations
1505    ! among the states
1506    degeneracy_matrix = 0
1507
1508    do is = 1, st%nst*st%d%nik
1509      do js = 1, st%nst*st%d%nik
1510
1511        ! a state is always degenerate to itself
1512        if ( is.eq.js ) cycle
1513
1514        evis = st%eigenval(eindex(1, sindex(is)), eindex(2, sindex(is)))
1515        evjs = st%eigenval(eindex(1, sindex(js)), eindex(2, sindex(js)))
1516
1517        ! is evjs in the "evis plus minus threshold" bracket?
1518        if( (evjs.gt.evis - degen_thres).and.(evjs.lt.evis + degen_thres) ) then
1519          ! mark forward scattering states with +1 and backward scattering
1520          ! states with -1
1521          degeneracy_matrix(is, js) = &
1522            sign(M_ONE, st%momentum(1, eindex(1, sindex(js)), eindex(2, sindex(js))))
1523        end if
1524
1525      end do
1526    end do
1527
1528    if(mpi_grp_is_root(mpi_world)) then
1529
1530      ! write matrix to "tmp/restart_gs" directory
1531      iunit = io_open('tmp/restart_gs/degeneracy_matrix', action='write', is_tmp = .true.)   
1532
1533      write(iunit, '(a)') '# index  kx ky kz  eigenvalue  degeneracy matrix'
1534
1535      do is = 1, st%nst*st%d%nik
1536        write(iunit, '(i6,4e24.16,32767i3)') is, st%d%kpoints(:, eindex(2, sindex(is))), &
1537          eigenval_sorted(is), (degeneracy_matrix(is, js), js = 1, st%nst*st%d%nik)
1538      end do
1539   
1540      call io_close(iunit)
1541   
1542      ! write index vectors to "tmp/restart_gs" directory
1543      iunit = io_open('tmp/restart_gs/index_vectors', action='write', is_tmp = .true.)   
1544     
1545      write(iunit, '(a)') '# index  sindex  eindex1 eindex2'
1546
1547      do is = 1, st%nst*st%d%nik
1548        write(iunit,'(4i6)') is, sindex(is), eindex(1, sindex(is)), eindex(2, sindex(is))
1549      end do
1550   
1551      call io_close(iunit)
1552    end if
1553
1554    deallocate(eigenval_sorted, sindex, eindex)
1555    deallocate(degeneracy_matrix)
1556   
1557    call pop_sub()
1558  end subroutine states_degeneracy_matrix
1559
1560
1561  ! -------------------------------------------------------
1562  ! WARNING: This subouroutine probably should not be here, but
1563  ! in states_output. Also, the current flow probably should be
1564  ! calculated during td runs.
1565  subroutine states_write_current_flow(dir, st, gr)
1566    character(len=*),  intent(in)    :: dir   
1567    type(states_t),    intent(inout) :: st
1568    type(grid_t),      intent(inout) :: gr
1569
1570    C_POINTER :: blk
1571    integer :: iunit, i, k
1572    type(mesh_plane_t) :: plane
1573    type(mesh_line_t) :: line
1574    FLOAT :: flow
1575    FLOAT, allocatable :: j(:, :)
1576
1577    call push_sub('states.states_write_current_flows')
1578
1579    if(loct_parse_block(check_inp('CurrentThroughPlane'), blk).ne.0) then
1580      call pop_sub(); return
1581    end if
1582
1583    select case(NDIM)
1584    case(3)
1585
1586      !%Variable CurrentThroughPlane
1587      !%Type block
1588      !%Section States
1589      !%Description
1590      !% At the end of the ground state calculation, the code may calculate
1591      !% the steady current that the obtained ground state electronic state
1592      !% transverses a user-defined portion of a plane....
1593      !%
1594      !% In the 2D case, the current flow should be calculated through a line.
1595      !%
1596      !% Example (3D):
1597      !%
1598      !% <tt>%CurrentThroughPlane
1599      !% <br>&nbsp;&nbsp; 0.0 | 0.0 | 0.0
1600      !% <br>&nbsp;&nbsp; 0.0 | 1.0 | 0.0
1601      !% <br>&nbsp;&nbsp; 0.0 | 0.0 | 1.0
1602      !% <br>&nbsp;&nbsp; 0.2
1603      !% <br>&nbsp;&nbsp; 0 | 50
1604      !% <br>&nbsp;&nbsp; -50 | 50
1605      !% <br>%</tt>
1606      !%
1607      !% Example (2D):
1608      !%
1609      !% <tt>%CurrentThroughPlane
1610      !% <br>&nbsp;&nbsp; 0.0 | 0.0
1611      !% <br>&nbsp;&nbsp; 1.0 | 0.0
1612      !% <br>&nbsp;&nbsp; 0.2
1613      !% <br>&nbsp;&nbsp; 0 | 50
1614      !% <br>%</tt>
1615      !%
1616      !%End
1617
1618      call loct_parse_block_float(blk, 0, 0, plane%origin(1))
1619      call loct_parse_block_float(blk, 0, 1, plane%origin(2))
1620      call loct_parse_block_float(blk, 0, 2, plane%origin(3))
1621      call loct_parse_block_float(blk, 1, 0, plane%u(1))
1622      call loct_parse_block_float(blk, 1, 1, plane%u(2))
1623      call loct_parse_block_float(blk, 1, 2, plane%u(3))
1624      call loct_parse_block_float(blk, 2, 0, plane%v(1))
1625      call loct_parse_block_float(blk, 2, 1, plane%v(2))
1626      call loct_parse_block_float(blk, 2, 2, plane%v(3))
1627      call loct_parse_block_float(blk, 3, 0, plane%spacing)
1628      call loct_parse_block_int(blk, 4, 0, plane%nu)
1629      call loct_parse_block_int(blk, 4, 1, plane%mu)
1630      call loct_parse_block_int(blk, 5, 0, plane%nv)
1631      call loct_parse_block_int(blk, 5, 1, plane%mv)
1632
1633      plane%n(1) = plane%u(2)*plane%v(3) - plane%u(3)*plane%v(2)
1634      plane%n(2) = plane%u(3)*plane%v(1) - plane%u(1)*plane%v(3)
1635      plane%n(3) = plane%u(1)*plane%v(2) - plane%u(2)*plane%v(1)
1636
1637      iunit = io_open(trim(dir)//'/'//'current-flow', action='write')
1638
1639      write(iunit,'(a)')       '# Plane:'
1640      write(iunit,'(a,3f9.5)') '# u = ', plane%u(1), plane%u(2), plane%u(3)
1641      write(iunit,'(a,3f9.5)') '# v = ', plane%v(1), plane%v(2), plane%v(3)
1642      write(iunit,'(a,3f9.5)') '# n = ', plane%n(1), plane%n(2), plane%n(3)
1643      write(iunit,'(a, f9.5)') '# spacing = ', plane%spacing
1644      write(iunit,'(a,2i4)')   '# nu, mu = ', plane%nu, plane%mu
1645      write(iunit,'(a,2i4)')   '# nv, mv = ', plane%nv, plane%mv
1646
1647    case(2)
1648
1649      call loct_parse_block_float(blk, 0, 0, line%origin(1))
1650      call loct_parse_block_float(blk, 0, 1, line%origin(2))
1651      call loct_parse_block_float(blk, 1, 0, line%u(1))
1652      call loct_parse_block_float(blk, 1, 1, line%u(2))
1653      call loct_parse_block_float(blk, 2, 0, line%spacing)
1654      call loct_parse_block_int(blk, 3, 0, line%nu)
1655      call loct_parse_block_int(blk, 3, 1, line%mu)
1656
1657      line%n(1) = -line%u(2)
1658      line%n(2) =  line%u(1)
1659
1660      iunit = io_open(trim(dir)//'/'//'current-flow', action='write')
1661
1662      write(iunit,'(a)')       '# Line:'
1663      write(iunit,'(a,2f9.5)') '# u = ', line%u(1), line%u(2)
1664      write(iunit,'(a,2f9.5)') '# n = ', line%n(1), line%n(2)
1665      write(iunit,'(a, f9.5)') '# spacing = ', line%spacing
1666      write(iunit,'(a,2i4)')   '# nu, mu = ', line%nu, line%mu
1667
1668    end select
1669
1670    call states_paramagnetic_current(gr, st, st%j)
1671
1672    ALLOCATE(j(NP, MAX_DIM), NP*MAX_DIM)
1673
1674    do k = 1, NDIM
1675      do i = 1, NP
1676        j(i, k) = sum(st%j(i, k, :))
1677      end do
1678    end do
1679
1680    select case(NDIM)
1681      case(3); flow = mf_surface_integral (gr%m, j, plane)
1682      case(2); flow = mf_line_integral (gr%m, j, line)
1683    end select
1684
1685    write(iunit,'(a,e20.12)') '# Flow = ', flow
1686
1687    deallocate(j)
1688    call io_close(iunit)
1689    call pop_sub()
1690  end subroutine states_write_current_flow
1691
1692
1693  ! -------------------------------------------------------
1694  integer function states_spin_channel(ispin, ik, dim)
1695    integer, intent(in) :: ispin, ik, dim
1696
1697    ASSERT(ispin >= UNPOLARIZED .or. ispin <= SPINORS)
1698    ASSERT(ik > 0)
1699    ASSERT(dim==1 .or. dim==2)
1700    ASSERT(.not.(ispin.ne.3 .and. dim==2))
1701
1702    select case(ispin)
1703    case(1); states_spin_channel = 1
1704    case(2); states_spin_channel = mod(ik+1, 2)+1
1705    case(3); states_spin_channel = dim
1706    case default; states_spin_channel = -1
1707    end select
1708
1709  end function states_spin_channel
1710
1711
1712  ! ---------------------------------------------------------
1713  subroutine states_distribute_nodes(st, mc)
1714    type(states_t),    intent(inout) :: st
1715    type(multicomm_t), intent(in)    :: mc
1716
1717#ifdef HAVE_MPI
1718    integer :: sn, sn1, r, j, k, i, ii, st_start, st_end
1719#endif
1720
1721    ! defaults
1722    st%node(:)  = 0
1723    st%st_start = 1
1724    st%st_end   = st%nst
1725    st%parallel_in_states = .false.
1726    call mpi_grp_init(st%mpi_grp, -1)
1727
1728#if defined(HAVE_MPI)
1729    if(multicomm_strategy_is_parallel(mc, P_STRATEGY_STATES)) then
1730
1731      st%parallel_in_states = .true.
1732      call mpi_grp_init(st%mpi_grp, mc%group_comm(P_STRATEGY_STATES))
1733
1734      if(st%nst < st%mpi_grp%size) then
1735        message(1) = "Have more processors than necessary"
1736        write(message(2),'(i4,a,i4,a)') st%mpi_grp%size, " processors and ", st%nst, " states."
1737        call write_fatal(2)
1738      end if
1739
1740      do k = 0, st%mpi_grp%size-1
1741        i = st%nst / st%mpi_grp%size
1742        ii = st%nst - i*st%mpi_grp%size
1743        if(ii > 0 .and. k < ii) then
1744          i = i + 1
1745          st_start = k*i + 1
1746          st_end = st_start + i - 1
1747        else
1748          st_end = st%nst - (st%mpi_grp%size - k - 1)*i
1749          st_start = st_end - i + 1
1750        end if
1751        write(message(1),'(a,i4,a,i4,a,i4)') 'Info: Nodes in states-group ', k,&
1752                                             ' will manage states', st_start, " - ", st_end
1753        call write_info(1)
1754        if(st%mpi_grp%rank .eq. k) then
1755          st%st_start = st_start
1756          st%st_end = st_end
1757        endif
1758      end do
1759
1760      sn  = st%nst/st%mpi_grp%size
1761      sn1 = sn + 1
1762      r  = mod(st%nst, st%mpi_grp%size)
1763      do j = 1, r
1764        st%node((j-1)*sn1+1:j*sn1) = j - 1
1765      end do
1766      k = sn1*r
1767      call MPI_Barrier(st%mpi_grp%comm, mpi_err)
1768      do j = 1, st%mpi_grp%size - r
1769        st%node(k+(j-1)*sn+1:k+j*sn) = r + j - 1
1770      end do
1771    end if
1772#endif
1773
1774  end subroutine states_distribute_nodes
1775
1776
1777  ! ---------------------------------------------------------
1778  logical function wfs_are_complex(st) result (wac)
1779    type(states_t),    intent(in) :: st
1780    wac = (st%d%wfs_type == M_CMPLX)
1781  end function wfs_are_complex
1782
1783
1784  ! ---------------------------------------------------------
1785  logical function wfs_are_real(st) result (war)
1786    type(states_t),    intent(in) :: st
1787    war = (st%d%wfs_type == M_REAL)
1788  end function wfs_are_real
1789
1790
1791  ! ---------------------------------------------------------
1792  subroutine states_dump(st, iunit)
1793    type(states_t), intent(in) :: st
1794     integer,       intent(in) :: iunit
1795
1796     call push_sub('states.states_dump')
1797     
1798     write(iunit, '(a20,1i10)')  'nst=                ', st%nst
1799     write(iunit, '(a20,1i10)')  'dim=                ', st%d%dim
1800     write(iunit, '(a20,1i10)')  'nik=                ', st%d%nik
1801
1802     call pop_sub()
1803  end subroutine states_dump
1804
1805
1806  ! ---------------------------------------------------------
1807  ! This routine (obviously) assumes complex wave-functions
1808  subroutine states_paramagnetic_current(gr, st, jp)
1809    type(grid_t),   intent(inout) :: gr
1810    type(states_t), intent(inout) :: st
1811    FLOAT,          intent(out)   :: jp(:,:,:)  ! (NP, NDIM, st%d%nspin)
1812
1813    integer :: ik, p, sp, k
1814    CMPLX, allocatable :: grad(:,:)
1815#ifdef  HAVE_MPI
1816    FLOAT, allocatable :: red(:,:,:)
1817#endif
1818
1819    call push_sub('states.states_paramagnetic_current')
1820
1821    ASSERT(st%d%wfs_type == M_CMPLX)
1822
1823    if(st%d%ispin == SPIN_POLARIZED) then
1824      sp = 2
1825    else
1826      sp = 1
1827    end if
1828
1829    jp = M_ZERO
1830    ALLOCATE(grad(NP_PART, NDIM), NP_PART*NDIM)
1831
1832    do ik = 1, st%d%nik, sp
1833      do p  = st%st_start, st%st_end
1834        call zf_gradient(gr%sb, gr%f_der, st%zpsi(:, 1, p, ik), grad)
1835
1836        ! spin-up density
1837        do k = 1, NDIM
1838          jp(1:NP, k, 1) = jp(1:NP, k, 1) + st%d%kweights(ik)*st%occ(p, ik)       &
1839            * aimag(conjg(st%zpsi(1:NP, 1, p, ik)) * grad(1:NP, k))
1840        end do
1841
1842        ! spin-down density
1843        if(st%d%ispin == SPIN_POLARIZED) then
1844          call zf_gradient(gr%sb, gr%f_der, st%zpsi(:, 1, p, ik+1), grad)
1845
1846          do k = 1, NDIM
1847            jp(1:NP, k, 2) = jp(1:NP, k, 2) + st%d%kweights(ik+1)*st%occ(p, ik+1) &
1848              * aimag(conjg(st%zpsi(1:NP, 1, p, ik+1)) * grad(1:NP, k))
1849          end do
1850
1851          ! WARNING: the next lines DO NOT work properly
1852        else if(st%d%ispin == SPINORS) then ! off-diagonal densities
1853          call zf_gradient(gr%sb, gr%f_der, st%zpsi(:, 2, p, ik), grad)
1854
1855          do k = 1, NDIM
1856            jp(1:NP, k, 2) = jp(1:NP, k, 2) + st%d%kweights(ik)*st%occ(p, ik)     &
1857              * aimag(conjg(st%zpsi(1:NP, 2, p, ik)) * grad(1:NP, k))
1858          end do
1859        end if
1860
1861      end do
1862    end do
1863    deallocate(grad)
1864
1865#if defined(HAVE_MPI)
1866    if(st%parallel_in_states) then
1867      ALLOCATE(red(NP_PART, NDIM, st%d%nspin), NP_PART*NDIM*st%d%nspin)
1868      call MPI_Allreduce(jp(1, 1, 1), red(1, 1, 1), NP*NDIM*st%d%nspin,       &
1869        MPI_FLOAT, MPI_SUM, st%mpi_grp%comm, mpi_err)
1870      jp = red
1871      deallocate(red)
1872    end if
1873#endif
1874
1875    call pop_sub()
1876  end subroutine states_paramagnetic_current
1877
1878
1879  ! ---------------------------------------------------------
1880  function state_spin(m, f1) result(s)
1881    FLOAT, dimension(3) :: s
1882    type(mesh_t), intent(in) :: m
1883    CMPLX,  intent(in) :: f1(:, :)
1884
1885    CMPLX :: z
1886
1887    call push_sub('states.zstate_spin')
1888
1889    z = zmf_dotp(m, f1(:, 1) , f1(:, 2))
1890
1891    s(1) = M_TWO * z
1892    s(2) = M_TWO * aimag(z)
1893    s(3) = zmf_dotp(m, f1(:, 1), f1(:, 1)) - zmf_dotp(m, f1(:, 2), f1(:, 2))
1894    s = s * M_HALF ! spin is half the sigma matrix.
1895
1896    call pop_sub()
1897  end function state_spin
1898
1899
1900#include "states_kpoints.F90"
1901
1902#include "undef.F90"
1903#include "real.F90"
1904#include "states_inc.F90"
1905
1906#include "undef.F90"
1907#include "complex.F90"
1908#include "states_inc.F90"
1909#include "undef.F90"
1910
1911end module states_m
1912
1913!! Local Variables:
1914!! mode: f90
1915!! coding: utf-8
1916!! End:
Note: See TracBrowser for help on using the browser.