(git:2bb242e)
Loading...
Searching...
No Matches
realspace_grid_cube.F
Go to the documentation of this file.
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 Generate Gaussian cube files
10! **************************************************************************************************
12 USE cp_files, ONLY: close_file,&
15 USE kinds, ONLY: dp
16 USE message_passing, ONLY: &
21 USE pw_types, ONLY: pw_r3d_rs_type
22#include "../base/base_uses.f90"
23
24 IMPLICIT NONE
25
26 PRIVATE
27
30
31 CHARACTER(LEN=*), PARAMETER, PRIVATE :: moduleN = 'realspace_grid_cube'
32 INTEGER, PARAMETER, PRIVATE :: cube_entry_len = 14, &
33 cube_num_entries_line = 6
34 CHARACTER(LEN=*), PARAMETER :: cube_value_format = '(1X,ES13.5E3)', &
35 cube_values_format = '(6(1X,ES13.5E3))'
36 CHARACTER(LEN=*), PARAMETER, PRIVATE :: cube_whitespace = ' '//achar(9)//achar(10)//achar(11)//achar(12)//achar(13)
37 CHARACTER(LEN=*), PARAMETER, PRIVATE :: missing_zeff_warning = &
38 "Effective nuclear charges were not supplied; "// &
39 "zeros will be written to the Cube atom records."
40
42 PRIVATE
43 CHARACTER(LEN=:), ALLOCATABLE :: line
44 INTEGER :: pos = 1, length = 0, complete = 0
45 CONTAINS
46 PROCEDURE :: read => cube_read_values
47 END TYPE cube_reader_type
48
49CONTAINS
50
51! **************************************************************************************************
52!> \brief Read whitespace-separated cube values, retaining any unused part of the current record.
53!> \param reader input record and position
54!> \param unit_nr formatted file positioned at the cube data
55!> \param buffer parsed values
56! **************************************************************************************************
57 SUBROUTINE cube_read_values(reader, unit_nr, buffer)
58 CLASS(cube_reader_type), INTENT(INOUT) :: reader
59 INTEGER, INTENT(IN) :: unit_nr
60 REAL(KIND=dp), DIMENSION(:), INTENT(OUT) :: buffer
61
62 CHARACTER(LEN=:), ALLOCATABLE :: longer_line
63 INTEGER :: count, first, nchar, nvalues, readstat
64
65 IF (.NOT. ALLOCATED(reader%line)) ALLOCATE (CHARACTER(LEN=512) :: reader%line)
66 nvalues = 0
67 DO WHILE (nvalues < SIZE(buffer))
68 IF (reader%pos > reader%complete) THEN
69 ! Carry just the unfinished token into the next read, even for a single very long line.
70 reader%line(:reader%length - reader%complete) = reader%line(reader%complete + 1:reader%length)
71 reader%length = reader%length - reader%complete
72 DO
73 IF (reader%length == len(reader%line)) THEN
74 ALLOCATE (CHARACTER(LEN=2*reader%length) :: longer_line)
75 longer_line(:reader%length) = reader%line
76 CALL move_alloc(longer_line, reader%line)
77 END IF
78 READ (unit_nr, '(A)', advance='NO', size=nchar, iostat=readstat) reader%line(reader%length + 1:)
79 IF (readstat > 0) cpabort("Error reading cube data.")
80 reader%length = reader%length + nchar
81 IF (readstat < 0) THEN
82 IF (is_iostat_end(readstat) .AND. reader%length == 0) THEN
83 cpabort("Unexpected end of cube data.")
84 END IF
85 reader%complete = reader%length
86 EXIT
87 END IF
88 reader%complete = scan(reader%line(:reader%length), cube_whitespace, back=.true.)
89 IF (reader%complete > 0) EXIT
90 END DO
91 reader%pos = 1
92 END IF
93
94 first = reader%pos
95 count = cube_value_span(reader%line(:reader%complete), reader%pos, SIZE(buffer) - nvalues)
96 CALL cube_parse_values(reader%line(first:reader%pos - 1), buffer(nvalues + 1:nvalues + count))
97 nvalues = nvalues + count
98 END DO
99
100 END SUBROUTINE cube_read_values
101
102! **************************************************************************************************
103!> \brief Count up to limit values and normalize whitespace for list-directed internal reads.
104!> \param text cube data
105!> \param pos current character, advanced to the next unread value or end
106!> \param limit maximum number of values to consume
107!> \return number of values in the span
108! **************************************************************************************************
109 INTEGER FUNCTION cube_value_span(text, pos, limit) RESULT(count)
110 CHARACTER(LEN=*), INTENT(INOUT) :: text
111 INTEGER, INTENT(INOUT) :: pos
112 INTEGER, INTENT(IN) :: limit
113
114 LOGICAL :: in_value
115
116 count = 0
117 in_value = .false.
118 DO WHILE (pos <= len(text))
119 SELECT CASE (text(pos:pos))
120 CASE (' ', achar(9):achar(13))
121 text(pos:pos) = ' '
122 in_value = .false.
123 CASE DEFAULT
124 IF (.NOT. in_value) THEN
125 IF (count == limit) EXIT
126 count = count + 1
127 in_value = .true.
128 END IF
129 END SELECT
130 pos = pos + 1
131 END DO
132 END FUNCTION cube_value_span
133
134! **************************************************************************************************
135!> \brief Convert a span of whitespace-separated values.
136!> \param text cube data
137!> \param values parsed values
138! **************************************************************************************************
139 SUBROUTINE cube_parse_values(text, values)
140 CHARACTER(LEN=*), INTENT(IN) :: text
141 REAL(KIND=dp), DIMENSION(:), INTENT(OUT) :: values
142
143 INTEGER :: stat
144
145 IF (SIZE(values) == 0) RETURN
146 ! Null values, repeat counts and list terminators would silently alter the grid.
147 IF (scan(text, ',/*;!') /= 0) cpabort("Bad value while reading cube data.")
148 READ (text, *, iostat=stat) values
149 IF (stat /= 0) cpabort("Bad value while reading cube data.")
150 END SUBROUTINE cube_parse_values
151
152! **************************************************************************************************
153!> \brief ...
154!> \param pw ...
155!> \param unit_nr ...
156!> \param title ...
157!> \param particles_r ...
158!> \param particles_z ...
159!> \param particles_zeff ...
160!> \param stride ...
161!> \param max_file_size_mb ...
162!> \param zero_tails ...
163!> \param silent ...
164!> \param mpi_io ...
165! **************************************************************************************************
166 SUBROUTINE pw_to_cube(pw, unit_nr, title, particles_r, particles_z, particles_zeff, &
167 stride, max_file_size_mb, zero_tails, silent, mpi_io)
168 TYPE(pw_r3d_rs_type), INTENT(IN) :: pw
169 INTEGER, INTENT(IN) :: unit_nr
170 CHARACTER(*), INTENT(IN), OPTIONAL :: title
171 REAL(kind=dp), DIMENSION(:, :), INTENT(IN), &
172 OPTIONAL :: particles_r
173 INTEGER, DIMENSION(:), INTENT(IN), OPTIONAL :: particles_z
174 REAL(kind=dp), DIMENSION(:), INTENT(IN), OPTIONAL :: particles_zeff
175 INTEGER, DIMENSION(:), OPTIONAL, POINTER :: stride
176 REAL(kind=dp), INTENT(IN), OPTIONAL :: max_file_size_mb
177 LOGICAL, INTENT(IN), OPTIONAL :: zero_tails, silent, mpi_io
178
179 CHARACTER(LEN=*), PARAMETER :: routinen = 'pw_to_cube'
180
181 INTEGER :: checksum, dest, handle, i, i1, i2, i3, iat, ip, l1, l2, l3, msglen, my_rank, &
182 my_stride(3), np, num_linebreak, num_pe, rank(2), size_of_z, source, tag, u1, u2, u3
183 LOGICAL :: be_silent, my_zero_tails, parallel_write
184 REAL(kind=dp) :: compression_factor, my_max_file_size_mb
185 REAL(kind=dp), ALLOCATABLE, DIMENSION(:) :: buf
186 TYPE(mp_comm_type) :: gid
187 TYPE(mp_file_type) :: mp_unit
188
189 CALL timeset(routinen, handle)
190
191 my_zero_tails = .false.
192 be_silent = .false.
193 parallel_write = .false.
194 my_max_file_size_mb = 0.0_dp
195 IF (PRESENT(zero_tails)) my_zero_tails = zero_tails
196 IF (PRESENT(silent)) be_silent = silent
197 IF (PRESENT(mpi_io)) parallel_write = mpi_io
198 IF (PRESENT(max_file_size_mb)) my_max_file_size_mb = max_file_size_mb
199 cpassert(my_max_file_size_mb >= 0)
200 IF (.NOT. parallel_write .AND. PRESENT(particles_z) .AND. &
201 .NOT. PRESENT(particles_zeff)) THEN
202 cpwarn(missing_zeff_warning)
203 END IF
204
205 my_stride = 1
206 IF (PRESENT(stride)) THEN
207 IF (SIZE(stride) /= 1 .AND. SIZE(stride) /= 3) THEN
208 CALL cp_abort(__location__, "STRIDE keyword can accept only 1 "// &
209 "(the same for X,Y,Z) or 3 values. Correct your input file.")
210 END IF
211 IF (SIZE(stride) == 1) THEN
212 DO i = 1, 3
213 my_stride(i) = stride(1)
214 END DO
215 ELSE
216 my_stride = stride(1:3)
217 END IF
218 END IF
219
220 IF (my_max_file_size_mb > 0) THEN
221 ! Estimate the grid data size from the width of a value in bytes.
222 compression_factor = 1.0e-06_dp*cube_entry_len*product(real(pw%pw_grid%npts, dp))/my_max_file_size_mb
223 my_stride(:) = int(compression_factor**(1.0_dp/3.0_dp)) + 1
224 END IF
225
226 cpassert(my_stride(1) > 0)
227 cpassert(my_stride(2) > 0)
228 cpassert(my_stride(3) > 0)
229
230 IF (.NOT. parallel_write) THEN
231 IF (unit_nr > 0) THEN
232 ! this format seems to work for e.g. molekel and gOpenmol
233 ! latest version of VMD can read non orthorhombic cells
234 WRITE (unit_nr, '(a11)') "-Quickstep-"
235 IF (PRESENT(title)) THEN
236 WRITE (unit_nr, *) trim(title)
237 ELSE
238 WRITE (unit_nr, *) "No Title"
239 END IF
240
241 cpassert(PRESENT(particles_z) .EQV. PRESENT(particles_r))
242 np = 0
243 IF (PRESENT(particles_z)) THEN
244 cpassert(SIZE(particles_z) == SIZE(particles_r, dim=2))
245 ! cube files can only be written for 99999 particles due to a format limitation (I5)
246 ! so we limit the number of particles written.
247 np = min(99999, SIZE(particles_z))
248 END IF
249
250 WRITE (unit_nr, '(I5,3f12.6)') np, 0.0_dp, 0._dp, 0._dp !start of cube
251
252 WRITE (unit_nr, '(I5,3f12.6)') (pw%pw_grid%npts(1) + my_stride(1) - 1)/my_stride(1), &
253 pw%pw_grid%dh(1, 1)*real(my_stride(1), dp), pw%pw_grid%dh(2, 1)*real(my_stride(1), dp), &
254 pw%pw_grid%dh(3, 1)*real(my_stride(1), dp)
255 WRITE (unit_nr, '(I5,3f12.6)') (pw%pw_grid%npts(2) + my_stride(2) - 1)/my_stride(2), &
256 pw%pw_grid%dh(1, 2)*real(my_stride(2), dp), pw%pw_grid%dh(2, 2)*real(my_stride(2), dp), &
257 pw%pw_grid%dh(3, 2)*real(my_stride(2), dp)
258 WRITE (unit_nr, '(I5,3f12.6)') (pw%pw_grid%npts(3) + my_stride(3) - 1)/my_stride(3), &
259 pw%pw_grid%dh(1, 3)*real(my_stride(3), dp), pw%pw_grid%dh(2, 3)*real(my_stride(3), dp), &
260 pw%pw_grid%dh(3, 3)*real(my_stride(3), dp)
261
262 IF (PRESENT(particles_z)) THEN
263 IF (PRESENT(particles_zeff)) THEN
264 DO iat = 1, np
265 WRITE (unit_nr, '(I5,4f12.6)') particles_z(iat), particles_zeff(iat), particles_r(:, iat)
266 END DO
267 ELSE
268 DO iat = 1, np
269 WRITE (unit_nr, '(I5,4f12.6)') particles_z(iat), 0._dp, particles_r(:, iat)
270 END DO
271 END IF
272 END IF
273 END IF
274
275 ! shortcut
276 l1 = pw%pw_grid%bounds(1, 1)
277 l2 = pw%pw_grid%bounds(1, 2)
278 l3 = pw%pw_grid%bounds(1, 3)
279 u1 = pw%pw_grid%bounds(2, 1)
280 u2 = pw%pw_grid%bounds(2, 2)
281 u3 = pw%pw_grid%bounds(2, 3)
282
283 ALLOCATE (buf(l3:u3))
284
285 my_rank = pw%pw_grid%para%group%mepos
286 gid = pw%pw_grid%para%group
287 num_pe = pw%pw_grid%para%group%num_pe
288 tag = 1
289
290 rank (1) = unit_nr
291 rank (2) = my_rank
292 checksum = 0
293 IF (unit_nr > 0) checksum = 1
294
295 CALL gid%sum(checksum)
296 cpassert(checksum == 1)
297
298 CALL gid%maxloc(rank)
299 cpassert(rank(1) > 0)
300
301 dest = rank(2)
302 DO i1 = l1, u1, my_stride(1)
303 DO i2 = l2, u2, my_stride(2)
304
305 ! cycling through the CPUs, check if the current ray (I1,I2) is local to that CPU
306 IF (pw%pw_grid%para%mode /= pw_mode_local) THEN
307 DO ip = 0, num_pe - 1
308 IF (pw%pw_grid%para%bo(1, 1, ip, 1) <= i1 - l1 + 1 .AND. pw%pw_grid%para%bo(2, 1, ip, 1) >= i1 - l1 + 1 .AND. &
309 pw%pw_grid%para%bo(1, 2, ip, 1) <= i2 - l2 + 1 .AND. pw%pw_grid%para%bo(2, 2, ip, 1) >= i2 - l2 + 1) THEN
310 source = ip
311 END IF
312 END DO
313 ELSE
314 source = dest
315 END IF
316
317 IF (source == dest) THEN
318 IF (my_rank == source) THEN
319 buf(:) = pw%array(i1, i2, :)
320 END IF
321 ELSE
322 IF (my_rank == source) THEN
323 buf(:) = pw%array(i1, i2, :)
324 CALL gid%send(buf, dest, tag)
325 END IF
326 IF (my_rank == dest) THEN
327 CALL gid%recv(buf, source, tag)
328 END IF
329 END IF
330
331 IF (unit_nr > 0) THEN
332 IF (my_zero_tails) THEN
333 DO i3 = l3, u3
334 IF (buf(i3) < 1.e-7_dp) buf(i3) = 0.0_dp
335 END DO
336 END IF
337 WRITE (unit_nr, cube_values_format) (buf(i3), i3=l3, u3, my_stride(3))
338 END IF
339
340 ! this double loop generates so many messages that it can overload
341 ! the message passing system, e.g. on XT3
342 ! we therefore put a barrier here that limits the amount of message
343 ! that flies around at any given time.
344 ! if ever this routine becomes a bottleneck, we should go for a
345 ! more complicated rewrite
346 CALL gid%sync()
347
348 END DO
349 END DO
350
351 DEALLOCATE (buf)
352 ELSE
353 size_of_z = ceiling(real(pw%pw_grid%bounds(2, 3) - pw%pw_grid%bounds(1, 3) + 1, dp)/real(my_stride(3), dp))
354 num_linebreak = (size_of_z + cube_num_entries_line - 1)/cube_num_entries_line
355 msglen = (size_of_z*cube_entry_len + num_linebreak)*mpi_character_size
356 CALL mp_unit%set_handle(unit_nr)
357 CALL pw_to_cube_parallel(pw, mp_unit, title, particles_r, particles_z, particles_zeff, &
358 my_stride, my_zero_tails, msglen)
359 END IF
360
361 CALL timestop(handle)
362
363 END SUBROUTINE pw_to_cube
364
365! **************************************************************************************************
366!> \brief Computes the external density on the grid
367!> hacked from external_read_density
368!> \param grid pw to read from cube file
369!> \param filename name of cube file
370!> \param scaling scale values before storing
371!> \param parallel_read ...
372!> \param silent ...
373!> \par History
374!> Created [M.Watkins] (01.2014)
375!> Use blocking, collective MPI read for parallel simulations [Nico Holmberg] (05.2017)
376! **************************************************************************************************
377 SUBROUTINE cube_to_pw(grid, filename, scaling, parallel_read, silent)
378
379 TYPE(pw_r3d_rs_type), INTENT(IN) :: grid
380 CHARACTER(LEN=*), INTENT(IN) :: filename
381 REAL(kind=dp), INTENT(IN) :: scaling
382 LOGICAL, INTENT(IN) :: parallel_read
383 LOGICAL, INTENT(IN), OPTIONAL :: silent
384
385 CHARACTER(LEN=*), PARAMETER :: routinen = 'cube_to_pw'
386
387 INTEGER :: extunit, handle, i, j, my_rank, nat, &
388 ndum, output_unit
389 INTEGER(KIND=file_offset) :: data_position
390 INTEGER, DIMENSION(3) :: lbounds, lbounds_local, npoints, &
391 ubounds, ubounds_local
392 LOGICAL :: be_silent
393 REAL(kind=dp), ALLOCATABLE, DIMENSION(:) :: buffer
394 REAL(kind=dp), DIMENSION(3) :: rdum
395 TYPE(cube_reader_type) :: reader
396 TYPE(mp_comm_type) :: gid
397
398 CALL timeset(routinen, handle)
399
400 output_unit = cp_logger_get_default_io_unit()
401 be_silent = .false.
402 IF (PRESENT(silent)) be_silent = silent
403 gid = grid%pw_grid%para%group
404 my_rank = gid%mepos
405 npoints = grid%pw_grid%npts
406 lbounds = grid%pw_grid%bounds(1, :)
407 ubounds = grid%pw_grid%bounds(2, :)
408 lbounds_local = grid%pw_grid%bounds_local(1, :)
409 ubounds_local = grid%pw_grid%bounds_local(2, :)
410
411 IF (my_rank == 0) THEN
412 IF (output_unit > 0 .AND. .NOT. be_silent) THEN
413 WRITE (output_unit, fmt="(/,T2,A,/,/,T2,A,/)") "Reading the cube file: ", trim(filename)
414 END IF
415 CALL open_file(file_name=filename, file_status="OLD", file_form="FORMATTED", &
416 file_action="READ", file_access="STREAM", unit_number=extunit)
417
418 ! Skip comment lines and read the grid dimensions.
419 READ (extunit, *)
420 READ (extunit, *)
421 READ (extunit, *) nat, rdum
422 DO i = 1, 3
423 READ (extunit, *) ndum, rdum
424 IF ((ndum /= npoints(i) .OR. abs(rdum(i) - grid%pw_grid%dh(i, i)) > 1e-4_dp) .AND. &
425 output_unit > 0) THEN
426 WRITE (output_unit, *) "Restart from density | ERROR! | CUBE FILE NOT COINCIDENT WITH INTERNAL GRID ", i
427 WRITE (output_unit, *) "Restart from density | ", ndum, " DIFFERS FROM ", npoints(i)
428 WRITE (output_unit, *) "Restart from density | ", rdum, " DIFFERS FROM ", grid%pw_grid%dh(i, i)
429 END IF
430 END DO
431 DO i = 1, nat
432 READ (extunit, *)
433 END DO
434 END IF
435
436 IF (parallel_read) THEN
437 IF (my_rank == 0) THEN
438 INQUIRE (unit=extunit, pos=data_position)
439 CALL close_file(unit_number=extunit)
440 END IF
441 CALL gid%bcast(data_position, 0)
442 ! Fortran stream positions start at 1 and MPI file offsets start at 0.
443 CALL cube_to_pw_parallel(grid, filename, scaling, data_position - 1)
444 ELSE
445 ALLOCATE (buffer(lbounds(3):ubounds(3)))
446 DO i = lbounds(1), ubounds(1)
447 DO j = lbounds(2), ubounds(2)
448 IF (my_rank == 0) CALL reader%read(extunit, buffer)
449 CALL gid%bcast(buffer, 0)
450 IF (lbounds_local(1) <= i .AND. i <= ubounds_local(1) .AND. &
451 lbounds_local(2) <= j .AND. j <= ubounds_local(2)) THEN
452 grid%array(i, j, lbounds(3):ubounds(3)) = scaling*buffer
453 END IF
454 END DO
455 END DO
456 IF (my_rank == 0) CALL close_file(unit_number=extunit)
457 END IF
458
459 CALL timestop(handle)
460
461 END SUBROUTINE cube_to_pw
462
463! **************************************************************************************************
464!> \brief Read consecutive file chunks and distribute their values to the owning grid pencils.
465!> \param grid target grid
466!> \param filename name of cube file
467!> \param scaling scale values before storing
468!> \param data_offset byte offset after the cube header
469! **************************************************************************************************
470 SUBROUTINE cube_to_pw_parallel(grid, filename, scaling, data_offset)
471 TYPE(pw_r3d_rs_type), INTENT(IN) :: grid
472 CHARACTER(LEN=*), INTENT(IN) :: filename
473 REAL(kind=dp), INTENT(IN) :: scaling
474 INTEGER(KIND=file_offset), INTENT(IN) :: data_offset
475
476 CHARACTER(LEN=:), ALLOCATABLE :: text
477 INTEGER :: count, dest, i, j, n, np, nz, packed, &
478 pos, rank, received, xhi, xlo
479 INTEGER(KIND=file_offset) :: base, block_size, chunk_end, consumed, &
480 file_size, first, hi, lo, plane, &
481 plane_size, total
482 INTEGER(KIND=file_offset), ALLOCATABLE, &
483 DIMENSION(:) :: counts, offsets
484 INTEGER, ALLOCATABLE, DIMENSION(:) :: rcount, rdispl, scount, sdispl
485 REAL(kind=dp), ALLOCATABLE, DIMENSION(:) :: local, sendbuf, values
486 TYPE(mp_comm_type) :: gid
487 TYPE(mp_file_type) :: file
488
489 gid = grid%pw_grid%para%group
490 rank = gid%mepos
491 np = gid%num_pe
492 nz = grid%pw_grid%npts(3)
493 plane_size = int(grid%pw_grid%npts(2), file_offset)*nz
494 total = grid%pw_grid%ngpts
495 ALLOCATE (offsets(0:np), counts(0:np - 1), local(SIZE(grid%array)))
496 ALLOCATE (rcount(0:np - 1), rdispl(0:np - 1), scount(0:np - 1), sdispl(0:np - 1))
497
498 CALL file%open(groupid=gid, filepath=filename, amode_status=file_amode_rdonly)
499 CALL file%get_size(file_size)
500 ! Read up to 8 MiB per rank per round, extending each chunk to a token boundary.
501 block_size = min(8_file_offset*1024*1024, (file_size - data_offset + np - 1)/np)
502 base = data_offset
503 consumed = 0
504 received = 0
505 DO WHILE (consumed < total)
506 IF (base >= file_size) cpabort("Unexpected end of cube data.")
507 chunk_end = min(file_size, base + (rank + 1)*block_size)
508 offsets(0) = base
509 CALL gid%allgather(cube_chunk_end(file, chunk_end, file_size), offsets(1:))
510 ALLOCATE (CHARACTER(LEN=offsets(rank + 1) - offsets(rank)) :: text)
511 CALL file%read_at_all(offsets(rank), text)
512 pos = 1
513 count = cube_value_span(text, pos, len(text))
514 CALL gid%allgather(int(count, file_offset), counts)
515 ! An appended frame may start in this chunk. Read only the requested grid.
516 first = min(consumed + sum(counts(:rank - 1)), total)
517 n = int(min(int(count, file_offset), total - first))
518 IF (n < count) THEN
519 pos = 1
520 n = cube_value_span(text, pos, n)
521 END IF
522 ALLOCATE (values(n), sendbuf(n))
523 CALL cube_parse_values(text(:pos - 1), values)
524 DEALLOCATE (text)
525
526 ! At fixed x, each destination owns a contiguous run of y and z in file order.
527 xlo = int(first/plane_size) + 1
528 xhi = int((first + n - 1)/plane_size) + 1
529 packed = 0
530 DO dest = 0, np - 1
531 sdispl(dest) = packed
532 associate(bo => grid%pw_grid%para%bo(:, :, dest, 1))
533 DO i = max(bo(1, 1), xlo), min(bo(2, 1), xhi)
534 plane = (i - 1)*plane_size
535 lo = max(first, plane + int(bo(1, 2) - 1, file_offset)*nz)
536 hi = min(first + n, plane + int(bo(2, 2), file_offset)*nz)
537 IF (hi <= lo) cycle
538 sendbuf(packed + 1:packed + hi - lo) = values(lo - first + 1:hi - first)
539 packed = packed + int(hi - lo)
540 END DO
541 END associate
542 scount(dest) = packed - sdispl(dest)
543 END DO
544 CALL gid%alltoall(scount, rcount, 1)
545 rdispl(0) = 0
546 DO i = 1, np - 1
547 rdispl(i) = rdispl(i - 1) + rcount(i - 1)
548 END DO
549 CALL gid%alltoall(sendbuf, scount, sdispl, local(received + 1:), rcount, rdispl)
550 received = received + sum(rcount)
551 consumed = consumed + sum(counts)
552 base = offsets(np)
553 DEALLOCATE (sendbuf, values)
554 END DO
555 CALL file%close()
556 ! Received chunks are already in file order, with z varying fastest.
557 pos = 0
558 associate(bounds => grid%pw_grid%bounds_local)
559 DO i = bounds(1, 1), bounds(2, 1)
560 DO j = bounds(1, 2), bounds(2, 2)
561 grid%array(i, j, :) = scaling*local(pos + 1:pos + nz)
562 pos = pos + nz
563 END DO
564 END DO
565 END associate
566 END SUBROUTINE cube_to_pw_parallel
567
568! **************************************************************************************************
569!> \brief Advance a byte offset to a value separator or EOF.
570!> \param file open cube file
571!> \param offset nominal end of a chunk
572!> \param file_size size in bytes
573!> \return exclusive end offset
574! **************************************************************************************************
575 FUNCTION cube_chunk_end(file, offset, file_size) RESULT(last)
576 TYPE(mp_file_type), INTENT(IN) :: file
577 INTEGER(KIND=file_offset), INTENT(IN) :: offset, file_size
578 INTEGER(KIND=file_offset) :: last
579
580 CHARACTER(LEN=128) :: probe
581 INTEGER :: n, pos
582
583 last = offset
584 DO WHILE (last < file_size)
585 n = int(min(int(len(probe), file_offset), file_size - last))
586 CALL file%read_at(last, probe(:n))
587 pos = scan(probe(:n), cube_whitespace)
588 IF (pos > 0) THEN
589 last = last + pos - 1
590 EXIT
591 END IF
592 last = last + n
593 END DO
594 END FUNCTION cube_chunk_end
595
596! **************************************************************************************************
597!> \brief Writes a realspace potential to a cube file using collective MPI I/O.
598!> \param grid the pw to output to the cube file
599!> \param unit_nr the handle associated with the cube file
600!> \param title title of the cube file
601!> \param particles_r Cartersian coordinates of the system
602!> \param particles_z atomic masses of atoms in the system
603!> \param particles_zeff effective atomic charges of atoms in the system
604!> \param stride every stride(i)th value of the potential is outputted (i=x,y,z)
605!> \param zero_tails flag that determines if small values of the potential should be zeroed
606!> \param msglen the size of each grid slice along z-axis in bytes
607!> \par History
608!> Created [Nico Holmberg] (11.2017)
609! **************************************************************************************************
610 SUBROUTINE pw_to_cube_parallel(grid, unit_nr, title, particles_r, particles_z, particles_zeff, &
611 stride, zero_tails, msglen)
612
613 TYPE(pw_r3d_rs_type), INTENT(IN) :: grid
614 TYPE(mp_file_type), INTENT(IN) :: unit_nr
615 CHARACTER(*), INTENT(IN), OPTIONAL :: title
616 REAL(kind=dp), DIMENSION(:, :), INTENT(IN), &
617 OPTIONAL :: particles_r
618 INTEGER, DIMENSION(:), INTENT(IN), OPTIONAL :: particles_z
619 REAL(kind=dp), DIMENSION(:), INTENT(IN), OPTIONAL :: particles_zeff
620 INTEGER, INTENT(IN) :: stride(3)
621 LOGICAL, INTENT(IN) :: zero_tails
622 INTEGER, INTENT(IN) :: msglen
623
624 INTEGER, PARAMETER :: header_len = 41, header_len_z = 53
625
626 CHARACTER(LEN=cube_entry_len) :: value
627 CHARACTER(LEN=header_len) :: header
628 CHARACTER(LEN=header_len_z) :: header_z
629 INTEGER :: counter, i, islice, j, k, my_rank, np, &
630 nslices
631 INTEGER(KIND=file_offset) :: bof
632 INTEGER(KIND=file_offset), ALLOCATABLE, &
633 DIMENSION(:), TARGET :: displacements
634 INTEGER, ALLOCATABLE, DIMENSION(:), TARGET :: blocklengths
635 INTEGER, DIMENSION(3) :: lbounds, lbounds_local, ubounds, &
636 ubounds_local
637 CHARACTER(LEN=msglen), ALLOCATABLE, DIMENSION(:) :: writebuffer
638 CHARACTER(LEN=msglen) :: tmp
639 LOGICAL :: should_write(2)
640 TYPE(mp_comm_type) :: gid
641 TYPE(mp_file_descriptor_type) :: mp_desc
642
643 !get rs grids and parallel envnment
644 gid = grid%pw_grid%para%group
645 my_rank = grid%pw_grid%para%group%mepos
646 IF (PRESENT(particles_z) .AND. .NOT. PRESENT(particles_zeff)) THEN
647 cpwarn(missing_zeff_warning)
648 END IF
649
650 ! Shortcut
651 lbounds = grid%pw_grid%bounds(1, :)
652 ubounds = grid%pw_grid%bounds(2, :)
653 lbounds_local = grid%pw_grid%bounds_local(1, :)
654 ubounds_local = grid%pw_grid%bounds_local(2, :)
655 ! Determine the number of local z-slices.
656 islice = 1
657 DO i = lbounds(1), ubounds(1), stride(1)
658 should_write(:) = .true.
659 IF (i < lbounds_local(1)) THEN
660 should_write(1) = .false.
661 ELSE IF (i > ubounds_local(1)) THEN
662 EXIT
663 END IF
664 DO j = lbounds(2), ubounds(2), stride(2)
665 should_write(2) = .true.
666 IF (j < lbounds_local(2) .OR. j > ubounds_local(2)) THEN
667 should_write(2) = .false.
668 END IF
669 IF (all(should_write .EQV. .true.)) THEN
670 islice = islice + 1
671 END IF
672 END DO
673 END DO
674 nslices = islice - 1
675 islice = 1
676 ! Determine initial byte offset (0 or EOF if data is appended)
677 CALL unit_nr%get_position(bof)
678 ! Write header information on master process and update byte offset accordingly
679 IF (my_rank == 0) THEN
680 ! this format seems to work for e.g. molekel and gOpenmol
681 ! latest version of VMD can read non orthorhombic cells
682 CALL unit_nr%write_at(bof, "-Quickstep-"//new_line("C"))
683 bof = bof + len("-Quickstep-"//new_line("C"))*mpi_character_size
684 IF (PRESENT(title)) THEN
685 CALL unit_nr%write_at(bof, trim(title)//new_line("C"))
686 bof = bof + len(trim(title)//new_line("C"))*mpi_character_size
687 ELSE
688 CALL unit_nr%write_at(bof, "No Title"//new_line("C"))
689 bof = bof + len("No Title"//new_line("C"))*mpi_character_size
690 END IF
691
692 cpassert(PRESENT(particles_z) .EQV. PRESENT(particles_r))
693 np = 0
694 IF (PRESENT(particles_z)) THEN
695 cpassert(SIZE(particles_z) == SIZE(particles_r, dim=2))
696 ! cube files can only be written for 99999 particles due to a format limitation (I5)
697 ! so we limit the number of particles written.
698 np = min(99999, SIZE(particles_z))
699 END IF
700
701 WRITE (header, '(I5,3f12.6)') np, 0.0_dp, 0._dp, 0._dp !start of cube
702 CALL unit_nr%write_at(bof, header//new_line("C"))
703 bof = bof + len(header//new_line("C"))*mpi_character_size
704
705 WRITE (header, '(I5,3f12.6)') (grid%pw_grid%npts(1) + stride(1) - 1)/stride(1), &
706 grid%pw_grid%dh(1, 1)*real(stride(1), dp), grid%pw_grid%dh(2, 1)*real(stride(1), dp), &
707 grid%pw_grid%dh(3, 1)*real(stride(1), dp)
708 CALL unit_nr%write_at(bof, header//new_line("C"))
709 bof = bof + len(header//new_line("C"))*mpi_character_size
710
711 WRITE (header, '(I5,3f12.6)') (grid%pw_grid%npts(2) + stride(2) - 1)/stride(2), &
712 grid%pw_grid%dh(1, 2)*real(stride(2), dp), grid%pw_grid%dh(2, 2)*real(stride(2), dp), &
713 grid%pw_grid%dh(3, 2)*real(stride(2), dp)
714 CALL unit_nr%write_at(bof, header//new_line("C"))
715 bof = bof + len(header//new_line("C"))*mpi_character_size
716
717 WRITE (header, '(I5,3f12.6)') (grid%pw_grid%npts(3) + stride(3) - 1)/stride(3), &
718 grid%pw_grid%dh(1, 3)*real(stride(3), dp), grid%pw_grid%dh(2, 3)*real(stride(3), dp), &
719 grid%pw_grid%dh(3, 3)*real(stride(3), dp)
720 CALL unit_nr%write_at(bof, header//new_line("C"))
721 bof = bof + len(header//new_line("C"))*mpi_character_size
722
723 IF (PRESENT(particles_z)) THEN
724 IF (PRESENT(particles_zeff)) THEN
725 DO i = 1, np
726 WRITE (header_z, '(I5,4f12.6)') particles_z(i), particles_zeff(i), particles_r(:, i)
727 CALL unit_nr%write_at(bof, header_z//new_line("C"))
728 bof = bof + len(header_z//new_line("C"))*mpi_character_size
729 END DO
730 ELSE
731 DO i = 1, np
732 WRITE (header_z, '(I5,4f12.6)') particles_z(i), 0._dp, particles_r(:, i)
733 CALL unit_nr%write_at(bof, header_z//new_line("C"))
734 bof = bof + len(header_z//new_line("C"))*mpi_character_size
735 END DO
736 END IF
737 END IF
738 END IF
739 ! Sync offset
740 CALL gid%bcast(bof, grid%pw_grid%para%group%source)
741 ! Determine byte offsets for each grid z-slice which are local to a process
742 ! and convert z-slices to cube format compatible strings
743 ALLOCATE (displacements(nslices))
744 displacements = 0
745 ALLOCATE (writebuffer(nslices))
746 writebuffer(:) = ''
747 DO i = lbounds(1), ubounds(1), stride(1)
748 should_write(:) = .true.
749 IF (i < lbounds_local(1)) THEN
750 should_write(1) = .false.
751 ELSE IF (i > ubounds_local(1)) THEN
752 EXIT
753 END IF
754 DO j = lbounds(2), ubounds(2), stride(2)
755 should_write(2) = .true.
756 IF (j < lbounds_local(2) .OR. j > ubounds_local(2)) THEN
757 should_write(2) = .false.
758 END IF
759 IF (all(should_write .EQV. .true.)) THEN
760 IF (islice > nslices) cpabort("Index out of bounds.")
761 displacements(islice) = bof
762 tmp = ''
763 counter = 0
764 DO k = lbounds(3), ubounds(3), stride(3)
765 IF (zero_tails .AND. grid%array(i, j, k) < 1.e-7_dp) THEN
766 WRITE (value, cube_value_format) 0.0_dp
767 ELSE
768 WRITE (value, cube_value_format) grid%array(i, j, k)
769 END IF
770 tmp = trim(tmp)//trim(value)
771 counter = counter + 1
772 IF (modulo(counter, cube_num_entries_line) == 0 .OR. ubounds(3) - k < stride(3)) THEN
773 tmp = trim(tmp)//new_line('C')
774 END IF
775 END DO
776 writebuffer(islice) = tmp
777 islice = islice + 1
778 END IF
779 ! Update global byte offset
780 bof = bof + msglen
781 END DO
782 END DO
783 ! Create indexed MPI type using calculated byte offsets as displacements
784 ! Size of each z-slice is msglen
785 ALLOCATE (blocklengths(nslices))
786 blocklengths(:) = msglen
787 mp_desc = mp_file_type_hindexed_make_chv(nslices, blocklengths, displacements)
788 ! Use the created type as a file view
789 ! NB. The vector 'displacements' contains the absolute offsets of each z-slice i.e.
790 ! they are given relative to the beginning of the file. The global offset to
791 ! set_view must therefore be set to 0
792 bof = 0
793 CALL mp_file_type_set_view_chv(unit_nr, bof, mp_desc)
794 ! Collective write of cube
795 CALL unit_nr%write_all(msglen, nslices, writebuffer, mp_desc)
796 ! Clean up
797 CALL mp_file_type_free(mp_desc)
798 DEALLOCATE (writebuffer)
799 DEALLOCATE (blocklengths, displacements)
800
801 END SUBROUTINE pw_to_cube_parallel
802
803! **************************************************************************************************
804!> \brief Prints a simple grid file: X Y Z value
805!> \param pw ...
806!> \param unit_nr ...
807!> \param stride ...
808!> \param pw2 ...
809!> \par History
810!> Created [Vladimir Rybkin] (08.2018)
811!> \author Vladimir Rybkin
812! **************************************************************************************************
813 SUBROUTINE pw_to_simple_volumetric(pw, unit_nr, stride, pw2)
814 TYPE(pw_r3d_rs_type), INTENT(IN) :: pw
815 INTEGER, INTENT(IN) :: unit_nr
816 INTEGER, DIMENSION(:), INTENT(IN), OPTIONAL :: stride
817 TYPE(pw_r3d_rs_type), INTENT(IN), OPTIONAL :: pw2
818
819 CHARACTER(LEN=*), PARAMETER :: routinen = 'pw_to_simple_volumetric'
820
821 INTEGER :: checksum, dest, handle, i, i1, i2, i3, &
822 ip, l1, l2, l3, my_rank, my_stride(3), &
823 ngrids, npoints, num_pe, rank(2), &
824 source, tag, u1, u2, u3
825 LOGICAL :: double
826 REAL(kind=dp) :: x, y, z
827 REAL(kind=dp), ALLOCATABLE, DIMENSION(:) :: buf, buf2
828 TYPE(mp_comm_type) :: gid
829
830 CALL timeset(routinen, handle)
831
832 ! Check if we write two grids
833 double = .false.
834 IF (PRESENT(pw2)) double = .true.
835
836 my_stride = 1
837 IF (PRESENT(stride)) THEN
838 IF (SIZE(stride) /= 1 .AND. SIZE(stride) /= 3) THEN
839 CALL cp_abort(__location__, "STRIDE keyword can accept only 1 "// &
840 "(the same for X,Y,Z) or 3 values. Correct your input file.")
841 END IF
842 IF (SIZE(stride) == 1) THEN
843 DO i = 1, 3
844 my_stride(i) = stride(1)
845 END DO
846 ELSE
847 my_stride = stride(1:3)
848 END IF
849 cpassert(my_stride(1) > 0)
850 cpassert(my_stride(2) > 0)
851 cpassert(my_stride(3) > 0)
852 END IF
853
854 ! shortcut
855 l1 = pw%pw_grid%bounds(1, 1)
856 l2 = pw%pw_grid%bounds(1, 2)
857 l3 = pw%pw_grid%bounds(1, 3)
858 u1 = pw%pw_grid%bounds(2, 1)
859 u2 = pw%pw_grid%bounds(2, 2)
860 u3 = pw%pw_grid%bounds(2, 3)
861
862 ! Write the header: number of points and number of spins
863 ngrids = 1
864 IF (double) ngrids = 2
865 npoints = ((pw%pw_grid%npts(1) + my_stride(1) - 1)/my_stride(1))* &
866 ((pw%pw_grid%npts(2) + my_stride(2) - 1)/my_stride(1))* &
867 ((pw%pw_grid%npts(3) + my_stride(3) - 1)/my_stride(1))
868 IF (unit_nr > 1) WRITE (unit_nr, '(I7,I5)') npoints, ngrids
869
870 ALLOCATE (buf(l3:u3))
871 IF (double) ALLOCATE (buf2(l3:u3))
872
873 my_rank = pw%pw_grid%para%group%mepos
874 gid = pw%pw_grid%para%group
875 num_pe = pw%pw_grid%para%group%num_pe
876 tag = 1
877
878 rank (1) = unit_nr
879 rank (2) = my_rank
880 checksum = 0
881 IF (unit_nr > 0) checksum = 1
882
883 CALL gid%sum(checksum)
884 cpassert(checksum == 1)
885
886 CALL gid%maxloc(rank)
887 cpassert(rank(1) > 0)
888
889 dest = rank(2)
890 DO i1 = l1, u1, my_stride(1)
891 DO i2 = l2, u2, my_stride(2)
892
893 ! cycling through the CPUs, check if the current ray (I1,I2) is local to that CPU
894 IF (pw%pw_grid%para%mode /= pw_mode_local) THEN
895 DO ip = 0, num_pe - 1
896 IF (pw%pw_grid%para%bo(1, 1, ip, 1) <= i1 - l1 + 1 .AND. pw%pw_grid%para%bo(2, 1, ip, 1) >= i1 - l1 + 1 .AND. &
897 pw%pw_grid%para%bo(1, 2, ip, 1) <= i2 - l2 + 1 .AND. pw%pw_grid%para%bo(2, 2, ip, 1) >= i2 - l2 + 1) THEN
898 source = ip
899 END IF
900 END DO
901 ELSE
902 source = dest
903 END IF
904
905 IF (source == dest) THEN
906 IF (my_rank == source) THEN
907 buf(:) = pw%array(i1, i2, :)
908 IF (double) buf2(:) = pw2%array(i1, i2, :)
909 END IF
910 ELSE
911 IF (my_rank == source) THEN
912 buf(:) = pw%array(i1, i2, :)
913 CALL gid%send(buf, dest, tag)
914 IF (double) THEN
915 buf2(:) = pw2%array(i1, i2, :)
916 CALL gid%send(buf2, dest, tag)
917 END IF
918 END IF
919 IF (my_rank == dest) THEN
920 CALL gid%recv(buf, source, tag)
921 IF (double) CALL gid%recv(buf2, source, tag)
922 END IF
923 END IF
924
925 IF (.NOT. double) THEN
926 DO i3 = l3, u3, my_stride(3)
927 x = pw%pw_grid%dh(1, 1)*i1 + &
928 pw%pw_grid%dh(2, 1)*i2 + &
929 pw%pw_grid%dh(3, 1)*i3
930
931 y = pw%pw_grid%dh(1, 2)*i1 + &
932 pw%pw_grid%dh(2, 2)*i2 + &
933 pw%pw_grid%dh(3, 2)*i3
934
935 z = pw%pw_grid%dh(1, 3)*i1 + &
936 pw%pw_grid%dh(2, 3)*i2 + &
937 pw%pw_grid%dh(3, 3)*i3
938
939 IF (unit_nr > 0) THEN
940 WRITE (unit_nr, '(6(1X,ES12.4E3), 6(1X,ES12.4E3), 6(1X,ES12.4E3), 6(1X,ES12.4E3))') x, y, z, buf(i3)
941 END IF
942 END DO
943
944 ELSE
945
946 DO i3 = l3, u3, my_stride(3)
947 x = pw%pw_grid%dh(1, 1)*i1 + &
948 pw%pw_grid%dh(2, 1)*i2 + &
949 pw%pw_grid%dh(3, 1)*i3
950
951 y = pw%pw_grid%dh(1, 2)*i1 + &
952 pw%pw_grid%dh(2, 2)*i2 + &
953 pw%pw_grid%dh(3, 2)*i3
954
955 z = pw%pw_grid%dh(1, 3)*i1 + &
956 pw%pw_grid%dh(2, 3)*i2 + &
957 pw%pw_grid%dh(3, 3)*i3
958
959 IF (unit_nr > 0) THEN
960 WRITE (unit_nr, '(6(1X,ES12.4E3), 6(1X,ES12.4E3), 6(1X,ES12.4E3), 6(1X,ES12.4E3))') x, y, z, buf(i3), buf2(i3)
961 END IF
962 END DO
963
964 END IF ! Double
965
966 ! this double loop generates so many messages that it can overload
967 ! the message passing system, e.g. on XT3
968 ! we therefore put a barrier here that limits the amount of message
969 ! that flies around at any given time.
970 ! if ever this routine becomes a bottleneck, we should go for a
971 ! more complicated rewrite
972 CALL gid%sync()
973
974 END DO
975 END DO
976
977 DEALLOCATE (buf)
978 IF (double) DEALLOCATE (buf2)
979
980 CALL timestop(handle)
981
982 END SUBROUTINE pw_to_simple_volumetric
983
984END MODULE realspace_grid_cube
static int modulo(int a, int m)
Equivalent of Fortran's MODULO which always returns a positive number. https://gcc....
Definition fft_utils.h:60
Utility routines to open and close files.
Definition cp_files.F:22
subroutine, public open_file(file_name, unit_number, file_status, file_form, file_action, file_position, file_pad, file_access, debug)
Opens a file and returns its logical unit number.
Definition cp_files.F:197
subroutine, public close_file(unit_number, file_status)
Closes an open file given by its logical unit number.
Definition cp_files.F:64
various routines to log and control the output. The idea is that decisions about where to log should ...
integer function, public cp_logger_get_default_io_unit(logger)
returns the unit nr for the ionode (-1 on all other processors) skips as well checks if the procs cal...
Defines the basic variable types.
Definition kinds.F:23
integer, parameter, public dp
Definition kinds.F:34
Interface to the message passing library MPI.
type(mp_file_descriptor_type) function, public mp_file_type_hindexed_make_chv(count, lengths, displs)
Creates an indexed MPI type for arrays of strings using bytes for spacing (hindexed type).
subroutine, public mp_file_type_free(type_descriptor)
Releases the type used for MPI I/O.
integer, parameter, public mpi_character_size
integer, parameter, public file_offset
integer, parameter, public file_amode_rdonly
subroutine, public mp_file_type_set_view_chv(fh, offset, type_descriptor)
Uses a previously created indexed MPI character type to tell the MPI processes how to partition (set_...
integer, parameter, public pw_mode_local
Generate Gaussian cube files.
subroutine, public cube_to_pw(grid, filename, scaling, parallel_read, silent)
Computes the external density on the grid hacked from external_read_density.
character(len= *), parameter, public cube_values_format
subroutine, public pw_to_simple_volumetric(pw, unit_nr, stride, pw2)
Prints a simple grid file: X Y Z value.
character(len= *), parameter, public cube_value_format
subroutine cube_read_values(reader, unit_nr, buffer)
Read whitespace-separated cube values, retaining any unused part of the current record.
subroutine, public pw_to_cube(pw, unit_nr, title, particles_r, particles_z, particles_zeff, stride, max_file_size_mb, zero_tails, silent, mpi_io)
...
void writebuffer(int *psockfd, char *data, int *plen)
Writes to a socket.
Definition sockets.c:212