source: palm/trunk/SOURCE/random_generator_parallel_mod.f90 @ 2172

Last change on this file since 2172 was 2172, checked in by knoop, 7 years ago

Bugfix: parallel random number generator

  • Property svn:keywords set to Id
File size: 18.4 KB
Line 
1!> @file random_generator_parallel_mod.f90
2!------------------------------------------------------------------------------!
3! This file is part of PALM.
4!
5! PALM is free software: you can redistribute it and/or modify it under the
6! terms of the GNU General Public License as published by the Free Software
7! Foundation, either version 3 of the License, or (at your option) any later
8! version.
9!
10! PALM is distributed in the hope that it will be useful, but WITHOUT ANY
11! WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12! A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13!
14! You should have received a copy of the GNU General Public License along with
15! PALM. If not, see <http://www.gnu.org/licenses/>.
16!
17! Copyright 1997-2017 Leibniz Universitaet Hannover
18!------------------------------------------------------------------------------!
19!
20! Current revisions:
21! -----------------
22! Bugfix: added global initialization routine and removed global array
23!
24! Former revisions:
25! -----------------
26! $Id: random_generator_parallel_mod.f90 2172 2017-03-08 15:55:25Z knoop $
27!
28! 2144 2017-02-07 15:32:45Z knoop
29! Bugfix: compile time parameter replacement prevented
30!
31! 2000 2016-08-20 18:09:15Z knoop
32! Forced header and separation lines into 80 columns
33!
34! 1850 2016-04-08 13:29:27Z maronga
35! Module renamed
36!
37!
38! 1682 2015-10-07 23:56:08Z knoop
39! Code annotations made doxygen readable
40!
41! 1400 2014-05-09 14:03:54Z knoop
42! Initial revision
43!
44!
45! Description:
46! ------------
47!> This module contains and supports the random number generating routine ran_parallel.
48!> ran_parallel returns a uniform random deviate between 0.0 and 1.0
49!> (exclusive of the end point values).
50!> Additionally it provides the generator with five integer for use as initial state space.
51!> The first tree integers (iran, jran, kran) are maintained as non negative values,
52!> while the last two (mran, nran) have 32-bit nonzero values.
53!> Also provided by this module is support for initializing or reinitializing
54!> the state space to a desired standard sequence number, hashing the initial
55!> values to random values, and allocating and deallocating the internal workspace
56!> Random number generator, produces numbers equally distributed in interval
57!>
58!> This routine is taken from the "numerical recipies vol. 2"
59!------------------------------------------------------------------------------!
60MODULE random_generator_parallel
61 
62
63   USE kinds
64   
65   IMPLICIT NONE
66   
67   PRIVATE
68   PUBLIC random_number_parallel, random_seed_parallel, random_dummy,          &
69          id_random_array, seq_random_array, init_parallel_random_generator
70   
71   INTEGER(isp), SAVE :: lenran=0             !<
72   INTEGER(isp), SAVE :: seq=0                !<
73   INTEGER(isp), SAVE :: iran0                !<
74   INTEGER(isp), SAVE :: jran0                !<
75   INTEGER(isp), SAVE :: kran0                !<
76   INTEGER(isp), SAVE :: mran0                !<
77   INTEGER(isp), SAVE :: nran0                !<
78   INTEGER(isp), SAVE :: rans                 !<
79   
80   INTEGER(isp), DIMENSION(:, :), POINTER, SAVE :: ranseeds   !<
81   
82   INTEGER(isp), DIMENSION(:), POINTER, SAVE :: iran   !<
83   INTEGER(isp), DIMENSION(:), POINTER, SAVE :: jran   !<
84   INTEGER(isp), DIMENSION(:), POINTER, SAVE :: kran   !<
85   INTEGER(isp), DIMENSION(:), POINTER, SAVE :: mran   !<
86   INTEGER(isp), DIMENSION(:), POINTER, SAVE :: nran   !<
87   INTEGER(isp), DIMENSION(:), POINTER, SAVE :: ranv   !<
88   
89   
90   
91   INTEGER(isp), DIMENSION(:,:), ALLOCATABLE   ::  id_random_array    !<
92   INTEGER(isp), DIMENSION(:,:,:), ALLOCATABLE ::  seq_random_array   !<
93   
94   REAL(wp), SAVE :: amm   !<
95   
96   REAL(wp) :: random_dummy=0.0   !<
97   
98   INTERFACE init_parallel_random_generator
99      MODULE PROCEDURE init_parallel_random_generator
100   END INTERFACE
101   
102   INTERFACE random_number_parallel
103      MODULE PROCEDURE ran0_s
104   END INTERFACE
105   
106   INTERFACE random_seed_parallel
107      MODULE PROCEDURE random_seed_parallel
108   END INTERFACE
109   
110   INTERFACE ran_hash
111      MODULE PROCEDURE ran_hash_v
112   END INTERFACE
113   
114   INTERFACE reallocate
115      MODULE PROCEDURE reallocate_iv,reallocate_im
116   END INTERFACE
117   
118   INTERFACE arth
119      MODULE PROCEDURE arth_i
120   END INTERFACE
121
122 CONTAINS
123 
124!------------------------------------------------------------------------------!
125! Description:
126! ------------
127!> Initialize the parallel random number generator for a specific subdomain
128!------------------------------------------------------------------------------!
129   SUBROUTINE init_parallel_random_generator(nx, ny, nys, nyn, nxl, nxr)
130
131      USE kinds
132
133      USE control_parameters,                                                  &
134          ONLY: ensemble_member_nr
135
136      IMPLICIT NONE
137
138      INTEGER(isp), INTENT(IN) ::  nx    !<
139      INTEGER(isp), INTENT(IN) ::  ny    !<
140      INTEGER(isp), INTENT(IN) ::  nys   !<
141      INTEGER(isp), INTENT(IN) ::  nyn   !<
142      INTEGER(isp), INTENT(IN) ::  nxl   !<
143      INTEGER(isp), INTENT(IN) ::  nxr   !<
144
145      INTEGER(iwp) ::  i   !<
146      INTEGER(iwp) ::  j   !<
147
148!--   Allocate ID-array and state-space-array
149      ALLOCATE ( seq_random_array(5,nys:nyn,nxl:nxr) )
150      ALLOCATE ( id_random_array(nys:nyn,nxl:nxr) )
151      seq_random_array = 0
152      id_random_array  = 0
153
154!--       Asigning an ID to every vertical gridpoint column
155!--       dependig on the ensemble run number.
156          DO i=nxl, nxr
157             DO j=nys, nyn
158                id_random_array(j,i) = j*(nx+1.0_wp) + i + 1.0_wp + 1E6 * &
159                                       ( ensemble_member_nr - 1000 )
160             ENDDO
161          ENDDO
162!--       Initializing with random_seed_parallel for every vertical
163!--       gridpoint column.
164          random_dummy=0
165          DO i = nxl, nxr
166             DO j = nys, nyn
167                CALL random_seed_parallel (random_sequence=id_random_array(j, i))
168                CALL random_number_parallel (random_dummy)
169                CALL random_seed_parallel (get=seq_random_array(:, j, i))
170             ENDDO
171          ENDDO
172
173   END SUBROUTINE init_parallel_random_generator
174 
175!------------------------------------------------------------------------------!
176! Description:
177! ------------
178!> Lagged Fibonacci generator combined with a Marsaglia shiftsequence.
179!> Returns as harvest a uniform random deviate between 0.0 and 1.0 (exclusive of the end point values).
180!> This generator has the same calling and initialization conventions as Fortran 90's random_number routine.
181!> Use random_seed_parallel to initialize or reinitialize to a particular sequence.
182!> The period of this generator is about 2.0 x 10^28, and it fully vectorizes.
183!> Validity of the integer model assumed by this generator is tested at initialization.
184!------------------------------------------------------------------------------!
185   SUBROUTINE ran0_s(harvest)
186
187      USE kinds
188     
189      IMPLICIT NONE
190     
191      REAL(wp), INTENT(OUT) :: harvest   !<
192     
193      IF  (lenran < 1) CALL ran_init(1)  !- Initialization routine in ran_state.
194     
195      !- Update Fibonacci generator, which has period p^2 + p + 1, p = 2^31 - 69.
196      rans = iran0 - kran0   
197     
198      IF  (rans < 0) rans = rans + 2147483579_isp
199     
200      iran0 = jran0
201      jran0 = kran0
202      kran0 = rans
203     
204      nran0 = ieor( nran0, ishft (nran0, 13) ) !- Update Marsaglia shift sequence with period 2^32 - 1.
205      nran0 = ieor( nran0, ishft (nran0, -17) )
206      nran0 = ieor( nran0, ishft (nran0, 5) )
207     
208      rans  = ieor( nran0, rans )   !- Combine the generators.
209     
210      harvest = amm * merge( rans, not(rans), rans < 0 ) !- Make the result positive definite (note that amm is negative).
211     
212   END SUBROUTINE ran0_s
213
214!------------------------------------------------------------------------------!
215! Description:
216! ------------
217!> Initialize or reinitialize the random generator state space to vectors of size length.
218!> The saved variable seq is hashed (via calls to the module routine ran_hash)
219!> to create unique starting seeds, different for each vector component.
220!------------------------------------------------------------------------------!
221   SUBROUTINE ran_init( length )
222   
223      USE kinds
224     
225      IMPLICIT NONE
226     
227      INTEGER(isp), INTENT(IN) ::  length   !<
228   
229      INTEGER(isp) ::  hg    !<
230      INTEGER(isp) ::  hgm   !<
231      INTEGER(isp) ::  hgng  !<
232     
233      INTEGER(isp) ::  new   !<
234      INTEGER(isp) ::  j     !<
235      INTEGER(isp) ::  hgt   !<
236     
237      IF ( length < lenran ) RETURN !- Simply return if enough space is already allocated.
238     
239      hg=huge(1_isp)
240      hgm=-hg
241      hgng=hgm-1
242      hgt = hg
243     
244      !- The following lines check that kind value isp is in fact a 32-bit integer
245      !- with the usual properties that we expect it to have (under negation and wrap-around addition).
246      !- If all of these tests are satisfied, then the routines that use this module are portable,
247      !- even though they go beyond Fortran 90's integer model.
248     
249      IF  ( hg /= 2147483647 ) CALL ran_error('ran_init: arith assump 1 fails')
250      IF  ( hgng >= 0 )        CALL ran_error('ran_init: arith assump 2 fails')
251      IF  ( hgt+1 /= hgng )    CALL ran_error('ran_init: arith assump 3 fails')
252      IF  ( not(hg) >= 0 )     CALL ran_error('ran_init: arith assump 4 fails')
253      IF  ( not(hgng) < 0 )    CALL ran_error('ran_init: arith assump 5 fails')
254      IF  ( hg+hgng >= 0 )     CALL ran_error('ran_init: arith assump 6 fails')
255      IF  ( not(-1_isp) < 0 )  CALL ran_error('ran_init: arith assump 7 fails')
256      IF  ( not(0_isp) >= 0 )  CALL ran_error('ran_init: arith assump 8 fails')
257      IF  ( not(1_isp) >= 0 )  CALL ran_error('ran_init: arith assump 9 fails')
258     
259      IF  ( lenran > 0) THEN                          !- Reallocate space, or ...
260     
261         ranseeds => reallocate( ranseeds, length, 5)
262         ranv => reallocate( ranv, length-1)
263         new = lenran+1
264         
265      ELSE                                            !- allocate space.
266     
267         ALLOCATE(ranseeds(length,5))
268         ALLOCATE(ranv(length-1))
269         new = 1   !- Index of first location not yet initialized.
270         amm = nearest(1.0_wp,-1.0_wp)/hgng
271         !- Use of nearest is to ensure that returned random deviates are strictly lessthan 1.0.
272         IF  (amm*hgng >= 1.0 .or. amm*hgng <= 0.0)                            &
273            CALL ran_error('ran_init: arith assump 10 fails')
274           
275      END IF 
276     
277      !- Set starting values, unique by seq and vector component.
278      ranseeds(new:,1) = seq
279      ranseeds(new:,2:5)=spread(arth(new,1,size(ranseeds(new:,1))),2,4)
280     
281      DO j=1,4   !- Hash them.
282         CALL ran_hash(ranseeds(new:,j), ranseeds(new:,j+1))
283      END DO
284     
285      WHERE (ranseeds (new: ,1:3) < 0)                                         & 
286         ranseeds(new: ,1:3)=not(ranseeds(new: ,1:3))  !- Enforce nonnegativity.
287         
288      WHERE (ranseeds(new: ,4:5) == 0) ranseeds(new: ,4:5)=1 !- Enforce nonzero.
289     
290      IF  (new == 1) THEN !- Set scalar seeds.
291     
292         iran0 = ranseeds(1,1)
293         jran0 = ranseeds(1,2)
294         kran0 = ranseeds(1,3)
295         mran0 = ranseeds(1,4)
296         nran0 = ranseeds(1,5)
297         rans  = nran0
298         
299      END IF
300     
301      IF  (length > 1) THEN   !- Point to vector seeds.
302     
303         iran => ranseeds(2:,1)
304         jran => ranseeds(2:,2)
305         kran => ranseeds(2:,3)
306         mran => ranseeds(2:,4)
307         nran => ranseeds(2:,5)
308         ranv = nran
309         
310      END IF
311     
312      lenran = length
313     
314   END SUBROUTINE ran_init
315
316!------------------------------------------------------------------------------!
317! Description:
318! ------------
319!> User interface to release the workspace used by the random number routines.
320!------------------------------------------------------------------------------!
321   SUBROUTINE ran_deallocate
322   
323      IF  ( lenran > 0 ) THEN
324     
325         DEALLOCATE(ranseeds, ranv)
326         NULLIFY(ranseeds, ranv, iran, jran, kran, mran, nran)
327         lenran = 0
328         
329      END IF
330     
331   END SUBROUTINE ran_deallocate
332
333!------------------------------------------------------------------------------!
334! Description:
335! ------------
336!> User interface for seeding the random number routines.
337!> Syntax is exactly like Fortran 90's random_seed routine,
338!> with one additional argument keyword: random_sequence, set to any integer
339!> value, causes an immediate new initialization, seeded by that integer.
340!------------------------------------------------------------------------------!
341   SUBROUTINE random_seed_parallel( random_sequence, state_size, put, get )
342   
343      IMPLICIT NONE
344     
345      INTEGER(isp), OPTIONAL, INTENT(IN)  ::  random_sequence   !<
346      INTEGER(isp), OPTIONAL, INTENT(OUT) ::  state_size        !<
347     
348      INTEGER(isp), DIMENSION(:), OPTIONAL, INTENT(IN)  ::  put   !<
349      INTEGER(isp), DIMENSION(:), OPTIONAL, INTENT(OUT) ::  get   !<
350     
351      IF  ( present(state_size) ) THEN
352     
353         state_size = 5 * lenran
354         
355      ELSE IF  ( present(put) ) THEN
356     
357         IF  ( lenran == 0 ) RETURN
358         
359         ranseeds = reshape( put,shape(ranseeds) )
360         
361         WHERE (ranseeds(:,1:3) < 0) ranseeds(: ,1:3) = not(ranseeds(: ,1:3))
362         !- Enforce nonnegativity and nonzero conditions on any user-supplied seeds.
363         
364         WHERE (ranseeds(:,4:5) == 0) ranseeds(:,4:5) = 1
365         
366         iran0 = ranseeds(1,1)
367         jran0 = ranseeds(1,2)
368         kran0 = ranseeds(1,3)
369         mran0 = ranseeds(1,4)
370         nran0 = ranseeds(1,5)
371         
372      ELSE IF  ( present(get) ) THEN
373     
374         IF  (lenran == 0) RETURN
375         
376         ranseeds(1,1:5) = (/ iran0,jran0,kran0,mran0,nran0 /)
377         get = reshape( ranseeds, shape(get) )
378         
379      ELSE IF  ( present(random_sequence) ) THEN
380     
381         CALL ran_deallocate
382         seq = random_sequence
383         
384      END IF
385     
386   END SUBROUTINE random_seed_parallel
387
388!------------------------------------------------------------------------------!
389! Description:
390! ------------
391!> DES-like hashing of two 32-bit integers, using shifts,
392!> xor's, and adds to make the internal nonlinear function.
393!------------------------------------------------------------------------------!
394   SUBROUTINE ran_hash_v( il, ir )
395   
396      IMPLICIT NONE
397     
398      INTEGER(isp), DIMENSION(:), INTENT(INOUT) ::  il   !<
399      INTEGER(isp), DIMENSION(:), INTENT(INOUT) ::  ir   !<
400     
401      INTEGER(isp), DIMENSION(size(il)) ::  is   !<
402     
403      INTEGER(isp) :: j   !<
404     
405      DO j=1,4
406     
407         is = ir
408         ir = ieor( ir, ishft(ir,5) ) + 1422217823
409         ir = ieor( ir, ishft(ir,-16) ) + 1842055030
410         ir = ieor( ir, ishft(ir,9) ) + 80567781
411         ir = ieor( il, ir )
412         il = is
413      END DO
414     
415   END SUBROUTINE ran_hash_v
416
417!------------------------------------------------------------------------------!
418! Description:
419! ------------
420!> User interface to process error-messages
421!> produced by the random_number_parallel module
422!------------------------------------------------------------------------------!
423   SUBROUTINE ran_error(string)
424   
425      CHARACTER(LEN=*), INTENT(IN) ::  string   !<
426     
427      write (*,*) 'Error in module random_number_parallel: ',string
428     
429      STOP 'Program terminated by ran_error'
430     
431   END SUBROUTINE ran_error
432
433!------------------------------------------------------------------------------!
434! Description:
435! ------------
436!> Reallocates the generators state space "ranseeds" to vectors of size length.
437!------------------------------------------------------------------------------!
438   FUNCTION reallocate_iv( p, n )
439   
440      INTEGER(isp), DIMENSION(:), POINTER ::  p               !<
441      INTEGER(isp), DIMENSION(:), POINTER ::  reallocate_iv   !<
442     
443      INTEGER(isp), INTENT(IN) ::  n   !<
444     
445      INTEGER(isp) ::  nold   !<
446      INTEGER(isp) ::  ierr   !<
447     
448      ALLOCATE(reallocate_iv(n),stat=ierr)
449     
450      IF (ierr /= 0) CALL                                                      &
451         ran_error('reallocate_iv: problem in attempt to allocate memory')
452         
453      IF (.not. associated(p)) RETURN
454     
455      nold = size(p)
456     
457      reallocate_iv(1:min(nold,n)) = p(1:min(nold,n))
458     
459      DEALLOCATE(p)
460     
461   END FUNCTION reallocate_iv
462   
463   FUNCTION reallocate_im( p, n, m )
464   
465      INTEGER(isp), DIMENSION(:,:), POINTER ::  p               !<
466      INTEGER(isp), DIMENSION(:,:), POINTER ::  reallocate_im   !<
467     
468      INTEGER(isp), INTENT(IN) ::  m   !<
469      INTEGER(isp), INTENT(IN) ::  n   !<
470     
471      INTEGER(isp) ::  mold   !<
472      INTEGER(isp) ::  nold   !<
473      INTEGER(isp) ::  ierr   !<
474     
475      ALLOCATE(reallocate_im(n,m),stat=ierr)
476     
477      IF (ierr /= 0) CALL                                                      &
478         ran_error('reallocate_im: problem in attempt to allocate memory')
479         
480      IF (.not. associated(p)) RETURN
481     
482      nold = size(p,1)
483      mold = size(p,2)
484     
485      reallocate_im(1:min(nold,n),1:min(mold,m)) =                             &
486         p(1:min(nold,n),1:min(mold,m))
487         
488      DEALLOCATE(p)
489     
490   END FUNCTION reallocate_im
491
492!------------------------------------------------------------------------------!
493! Description:
494! ------------
495!> Reallocates the generators state space "ranseeds" to vectors of size length.
496!------------------------------------------------------------------------------!
497   FUNCTION arth_i(first,increment,n)
498   
499      INTEGER(isp), INTENT(IN) ::  first       !<
500      INTEGER(isp), INTENT(IN) ::  increment   !<
501      INTEGER(isp), INTENT(IN) ::  n           !<
502     
503      INTEGER(isp), DIMENSION(n) ::  arth_i    !<
504     
505      INTEGER(isp) ::  k      !<
506      INTEGER(isp) ::  k2     !<
507      INTEGER(isp) ::  temp   !<
508     
509      INTEGER(isp), PARAMETER ::  npar_arth=16   !<
510      INTEGER(isp), PARAMETER ::  npar2_arth=8   !<
511     
512      IF (n > 0) arth_i(1) = first
513     
514      IF (n <= npar_arth) THEN
515     
516         DO k=2,n
517            arth_i(k) = arth_i(k-1)+increment
518         END DO
519         
520      ELSE
521     
522         DO k=2,npar2_arth
523            arth_i(k) = arth_i(k-1) + increment
524         END DO
525         
526         temp = increment * npar2_arth
527         k = npar2_arth
528         
529         DO
530            IF (k >= n) EXIT
531            k2 = k + k
532            arth_i(k+1:min(k2,n)) = temp + arth_i(1:min(k,n-k))
533            temp = temp + temp
534            k = k2
535         END DO
536         
537      END IF
538     
539   END FUNCTION arth_i
540
541END MODULE random_generator_parallel
Note: See TracBrowser for help on using the repository browser.