source: palm/trunk/SOURCE/init_grid.f90 @ 4457

Last change on this file since 4457 was 4457, checked in by raasch, 4 years ago

ghost point exchange modularized, bugfix for wrong 2d-exchange

  • Property svn:keywords set to Id
File size: 118.4 KB
Line 
1!> @file init_grid.f90
2!------------------------------------------------------------------------------!
3! This file is part of the PALM model system.
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-2020 Leibniz Universitaet Hannover
18!------------------------------------------------------------------------------!
19!
20! Current revisions:
21! -----------------
22!
23!
24! Former revisions:
25! -----------------
26! $Id: init_grid.f90 4457 2020-03-11 14:20:43Z raasch $
27! use statement for exchange horiz added,
28! bugfix for call of exchange horiz 2d
29!
30! 4444 2020-03-05 15:59:50Z raasch
31! bugfix: cpp-directives for serial mode added
32!
33! 4414 2020-02-19 20:16:04Z suehring
34! - Remove deprecated topography arrays nzb_s_inner, nzb_u_inner, etc.
35! - Move initialization of boundary conditions and multigrid into an extra
36!   module interface.
37!
38! 4386 2020-01-27 15:07:30Z Giersch
39! Allocation statements, comments, naming of variables revised and _wp added to
40! real type values
41!
42! 4360 2020-01-07 11:25:50Z suehring
43! Revise error messages for generic tunnel setup.
44!
45! 4346 2019-12-18 11:55:56Z motisi
46! Introduction of wall_flags_total_0, which currently sets bits based on static
47! topography information used in wall_flags_static_0
48!
49! 4340 2019-12-16 08:17:03Z Giersch
50! Topography closed channel flow with symmetric boundaries implemented
51!
52! 4329 2019-12-10 15:46:36Z motisi
53! Renamed wall_flags_0 to wall_flags_static_0
54!
55! 4328 2019-12-09 18:53:04Z suehring
56! Minor change in nzb_max computation. Commentation added.
57!
58! 4314 2019-11-29 10:29:20Z suehring
59! Set additional topography flag 4 to mark topography grid points emerged
60! from the filtering process.
61!
62! 4294 2019-11-13 18:34:16Z suehring
63! Bugfix, always set bit 5 and 6 of wall_flags, indicating terrain- and
64! building surfaces in all  cases, in order to enable terrain-following output
65! also when no land- or urban-surface model is applied.
66!
67! 4265 2019-10-15 16:16:24Z suehring
68! Bugfix for last commit, exchange oro_max variable only when it is allocated
69! (not necessarily the case when topography is input from ASCII file).
70!
71! 4245 2019-09-30 08:40:37Z pavelkrc
72! Store oro_max (building z-offset) in 2D for building surfaces
73!
74! 4189 2019-08-26 16:19:38Z suehring
75! - Add check for proper setting of namelist parameter topography
76! - Set flag to indicate land surfaces in case no topography is provided
77!
78! 4182 2019-08-22 15:20:23Z scharf
79! Corrected "Former revisions" section
80!
81! 4168 2019-08-16 13:50:17Z suehring
82! Pre-calculate topography top index and store it on an array (replaces former
83! functions get_topography_top_index)
84!
85! 4159 2019-08-15 13:31:35Z suehring
86! Revision of topography processing. This was not consistent between 2D and 3D
87! buildings.
88!
89! 4144 2019-08-06 09:11:47Z raasch
90! relational operators .EQ., .NE., etc. replaced by ==, /=, etc.
91!
92! 4115 2019-07-24 12:50:49Z suehring
93! Bugfix in setting near-surface flag 24, inidicating wall-bounded grid points
94!
95! 4110 2019-07-22 17:05:21Z suehring
96! - Separate initialization of advection flags for momentum and scalars.
97! - Change subroutine interface for ws_init_flags_scalar to pass boundary flags
98!
99! 4109 2019-07-22 17:00:34Z suehring
100! Fix bad commit
101!
102! 3926 2019-04-23 12:56:42Z suehring
103! Minor bugfix in building mapping when all building IDs in the model domain
104! are missing
105!
106! 3857 2019-04-03 13:00:16Z knoop
107! In projection of non-building 3D objects onto numerical grid remove
108! dependency on building_type
109!
110! 3763 2019-02-25 17:33:49Z suehring
111! Replace work-around for ghost point exchange of 1-byte arrays with specific
112! routine as already done in other routines
113!
114! 3761 2019-02-25 15:31:42Z raasch
115! unused variables removed
116!
117! 3661 2019-01-08 18:22:50Z suehring
118! Remove setting of nzb_max to nzt at non-cyclic boundary PEs, instead,
119! order degradation of advection scheme is handeled directly in advec_ws
120!
121! 3655 2019-01-07 16:51:22Z knoop
122! Comment added
123!
124! Revision 1.1  1997/08/11 06:17:45  raasch
125! Initial revision (Testversion)
126!
127!
128! Description:
129! -----------------------------------------------------------------------------!
130!> Creating grid depending constants
131!> @todo: Rearrange topo flag list
132!> @todo: reference 3D buildings on top of orography is not tested and may need
133!>        further improvement for steep slopes
134!> @todo: Use more advanced setting of building type at filled holes
135!------------------------------------------------------------------------------!
136 SUBROUTINE init_grid
137
138    USE arrays_3d,                                                             &
139        ONLY:  dd2zu, ddzu, ddzu_pres, ddzw, dzu, dzw, x, xu, y, yv, zu, zw
140
141    USE control_parameters,                                                    &
142        ONLY:  constant_flux_layer, dz, dz_max, dz_stretch_factor,             &
143               dz_stretch_factor_array, dz_stretch_level, dz_stretch_level_end,&
144               dz_stretch_level_end_index, dz_stretch_level_start_index,       &
145               dz_stretch_level_start, ibc_uv_b, message_string,               &
146               number_stretch_level_end,                                       &
147               number_stretch_level_start,                                     &
148               ocean_mode,                                                     &
149               psolver,                                                        &
150               symmetry_flag,                                                  &
151               topography,                                                     &
152               use_surface_fluxes
153
154    USE grid_variables,                                                        &
155        ONLY:  ddx, ddx2, ddy, ddy2, dx, dx2, dy, dy2, zu_s_inner, zw_w_inner
156
157    USE indices,                                                               &
158        ONLY:  nbgp,                                                           &
159               nx,                                                             &
160               nxl,                                                            &
161               nxlg,                                                           &
162               nxr,                                                            &
163               nxrg,                                                           &
164               ny,                                                             &
165               nyn,                                                            &
166               nyng,                                                           &
167               nys,                                                            &
168               nysg,                                                           &
169               nz,                                                             &
170               nzb,                                                            &
171               nzb_diff,                                                       &
172               nzb_max,                                                        &
173               nzt,                                                            &
174               topo_top_ind,                                                   &
175               topo_min_level
176
177    USE kinds
178
179    USE pegrid
180
181#if defined( __parallel )
182    USE vertical_nesting_mod,                                                  &
183        ONLY:  vnested, vnest_init_grid
184#endif
185
186    IMPLICIT NONE
187
188    INTEGER(iwp) ::  i             !< index variable along x
189    INTEGER(iwp) ::  j             !< index variable along y
190    INTEGER(iwp) ::  k             !< index variable along z
191    INTEGER(iwp) ::  k_top         !< topography top index on local PE
192    INTEGER(iwp) ::  n             !< loop variable for stretching
193    INTEGER(iwp) ::  number_dz     !< number of user-specified dz values       
194    INTEGER(iwp) ::  nzb_local_max !< vertical grid index of maximum topography height
195    INTEGER(iwp) ::  nzb_local_min !< vertical grid index of minimum topography height
196
197    INTEGER(iwp), DIMENSION(:,:,:), ALLOCATABLE ::  topo !< input array for 3D topography and dummy array for setting "outer"-flags
198
199    REAL(wp) ::  dz_level_end  !< distance between calculated height level for u/v-grid and user-specified end level for stretching
200    REAL(wp) ::  dz_stretched  !< stretched vertical grid spacing
201   
202    REAL(wp), DIMENSION(:), ALLOCATABLE ::  min_dz_stretch_level_end !< Array that contains all minimum heights where the stretching can end
203
204
205!
206!-- Calculation of horizontal array bounds including ghost layers
207    nxlg = nxl - nbgp
208    nxrg = nxr + nbgp
209    nysg = nys - nbgp
210    nyng = nyn + nbgp
211
212!
213!-- Allocate grid arrays
214    ALLOCATE( x(0:nx) )
215    ALLOCATE( xu(0:nx) )
216   
217    DO i = 0, nx
218       xu(i) = i * dx
219       x(i)  = i * dx + 0.5_wp * dx
220    ENDDO
221
222    ALLOCATE( y(0:ny) )
223    ALLOCATE( yv(0:ny) )
224   
225    DO j = 0, ny
226       yv(j) = j * dy
227       y(j)  = j * dy + 0.5_wp * dy
228    ENDDO
229
230    ALLOCATE( ddzu(1:nzt+1) )
231    ALLOCATE( ddzw(1:nzt+1) )
232    ALLOCATE( dd2zu(1:nzt) )
233    ALLOCATE( dzu(1:nzt+1) )
234    ALLOCATE( dzw(1:nzt+1) )
235    ALLOCATE( zu(nzb:nzt+1) )
236    ALLOCATE( zw(nzb:nzt+1) )
237
238!
239!-- For constructing an appropriate grid, the vertical grid spacing dz has to
240!-- be specified with a non-negative value in the parameter file
241    IF ( dz(1) == -1.0_wp )  THEN
242       message_string = 'missing dz'
243       CALL message( 'init_grid', 'PA0200', 1, 2, 0, 6, 0 ) 
244    ELSEIF ( dz(1) <= 0.0_wp )  THEN
245       WRITE( message_string, * ) 'dz=',dz(1),' <= 0.0'
246       CALL message( 'init_grid', 'PA0201', 1, 2, 0, 6, 0 )
247    ENDIF
248
249!
250!-- Initialize dz_stretch_level_start with the value of dz_stretch_level
251!-- if it was set by the user
252    IF ( dz_stretch_level /= -9999999.9_wp ) THEN
253       dz_stretch_level_start(1) = dz_stretch_level
254    ENDIF
255       
256!
257!-- Determine number of dz values and stretching levels specified by the
258!-- user to allow right controlling of the stretching mechanism and to
259!-- perform error checks. The additional requirement that dz /= dz_max
260!-- for counting number of user-specified dz values is necessary. Otherwise
261!-- restarts would abort if the old stretching mechanism with dz_stretch_level
262!-- is used (Attention: The user is not allowed to specify a dz value equal
263!-- to the default of dz_max = 999.0).
264    number_dz = COUNT( dz /= -1.0_wp .AND. dz /= dz_max)
265    number_stretch_level_start = COUNT( dz_stretch_level_start /=              &
266                                       -9999999.9_wp )
267    number_stretch_level_end = COUNT( dz_stretch_level_end /=                  &
268                                      9999999.9_wp )
269
270!
271!-- The number of specified end levels +1 has to be the same as the number
272!-- of specified dz values
273    IF ( number_dz /= number_stretch_level_end + 1 ) THEN
274       WRITE( message_string, * ) 'The number of values for dz = ',            &
275                                   number_dz, 'has to be the same as& ',       &
276                                   'the number of values for ',                &
277                                   'dz_stretch_level_end + 1 = ',              &
278                                   number_stretch_level_end+1
279          CALL message( 'init_grid', 'PA0156', 1, 2, 0, 6, 0 )
280    ENDIF
281   
282!
283!-- The number of specified start levels has to be the same or one less than
284!-- the number of specified dz values
285    IF ( number_dz /= number_stretch_level_start + 1 .AND.                     &
286         number_dz /= number_stretch_level_start ) THEN
287       WRITE( message_string, * ) 'The number of values for dz = ',            &
288                                   number_dz, 'has to be the same as or one ', &
289                                   'more than& the number of values for ',     &
290                                   'dz_stretch_level_start = ',                &
291                                   number_stretch_level_start
292          CALL message( 'init_grid', 'PA0211', 1, 2, 0, 6, 0 )
293    ENDIF
294   
295!-- The number of specified start levels has to be the same or one more than
296!-- the number of specified end levels
297    IF ( number_stretch_level_start /= number_stretch_level_end + 1 .AND.      &
298         number_stretch_level_start /= number_stretch_level_end ) THEN
299       WRITE( message_string, * ) 'The number of values for ',                 &
300                                  'dz_stretch_level_start = ',                 &
301                                   dz_stretch_level_start, 'has to be the ',   &
302                                   'same or one more than& the number of ',    &
303                                   'values for dz_stretch_level_end = ',       &
304                                   number_stretch_level_end
305          CALL message( 'init_grid', 'PA0216', 1, 2, 0, 6, 0 )
306    ENDIF
307
308!
309!-- Initialize dz for the free atmosphere with the value of dz_max
310    IF ( dz(number_stretch_level_start+1) == -1.0_wp .AND.                     &
311         number_stretch_level_start /= 0 ) THEN
312       dz(number_stretch_level_start+1) = dz_max
313    ENDIF
314       
315!
316!-- Initialize the stretching factor if (infinitely) stretching in the free
317!-- atmosphere is desired (dz_stretch_level_end was not specified for the
318!-- free atmosphere)
319    IF ( number_stretch_level_start == number_stretch_level_end + 1 ) THEN
320       dz_stretch_factor_array(number_stretch_level_start) =                   &
321       dz_stretch_factor
322    ENDIF
323   
324!
325!-- Allocation of arrays for stretching
326    ALLOCATE( min_dz_stretch_level_end(number_stretch_level_start) )
327
328!
329!-- Define the vertical grid levels. Start with atmosphere branch
330    IF ( .NOT. ocean_mode )  THEN
331   
332!
333!--    The stretching region has to be large enough to allow for a smooth
334!--    transition between two different grid spacings. The number 4 is an
335!--    empirical value
336       DO n = 1, number_stretch_level_start
337          min_dz_stretch_level_end(n) = dz_stretch_level_start(n) +            &
338                                        4 * MAX( dz(n),dz(n+1) )
339       ENDDO
340
341       IF ( ANY( min_dz_stretch_level_end(1:number_stretch_level_start) >      &
342                 dz_stretch_level_end(1:number_stretch_level_start) ) ) THEN
343             message_string= 'Each dz_stretch_level_end has to be larger ' //  &
344                             'than its corresponding value for &' //           &
345                             'dz_stretch_level_start + 4*MAX(dz(n),dz(n+1)) '//&
346                             'to allow for smooth grid stretching'
347             CALL message( 'init_grid', 'PA0224', 1, 2, 0, 6, 0 )
348       ENDIF
349       
350!
351!--    Stretching must not be applied within the surface layer
352!--    (first two grid points). For the default case dz_stretch_level_start
353!--    is negative. Therefore the absolut value is checked here.
354       IF ( ANY( ABS( dz_stretch_level_start ) <= dz(1) * 1.5_wp ) ) THEN
355          WRITE( message_string, * ) 'Each dz_stretch_level_start has to be ',&
356                                     'larger than ', dz(1) * 1.5
357             CALL message( 'init_grid', 'PA0226', 1, 2, 0, 6, 0 )
358       ENDIF
359
360!
361!--    The stretching has to start and end on a grid level. Therefore
362!--    user-specified values are mapped to the next lowest level. The 
363!--    calculation of the first level is realized differently just because of
364!--    historical reasons (the advanced/new stretching mechanism was realized 
365!--    in a way that results don't change if the old parameters
366!--    dz_stretch_level, dz_stretch_factor and dz_max are used)
367       IF ( number_stretch_level_start /= 0 ) THEN
368          dz_stretch_level_start(1) = INT( (dz_stretch_level_start(1) -        &
369                                            dz(1)/2.0) / dz(1) )               &
370                                      * dz(1) + dz(1)/2.0
371       ENDIF
372       
373       IF ( number_stretch_level_start > 1 ) THEN
374          DO n = 2, number_stretch_level_start
375             dz_stretch_level_start(n) = INT( dz_stretch_level_start(n) /      &
376                                              dz(n) ) * dz(n)
377          ENDDO
378       ENDIF
379       
380       IF ( number_stretch_level_end /= 0 ) THEN
381          DO n = 1, number_stretch_level_end
382             dz_stretch_level_end(n) = INT( dz_stretch_level_end(n) /          &
383                                            dz(n+1) ) * dz(n+1)
384          ENDDO
385       ENDIF
386
387!
388!--    Determine stretching factor if necessary
389       IF ( number_stretch_level_end >= 1 ) THEN
390          CALL calculate_stretching_factor( number_stretch_level_end )
391       ENDIF
392
393!
394!--    Grid for atmosphere with surface at z=0 (k=0, w-grid).
395!--    First compute the u- and v-levels. In case of dirichlet bc for u and v
396!--    the first u/v- and w-level (k=0) are defined at same height (z=0).
397!--    The second u-level (k=1) corresponds to the top of the
398!--    surface layer. In case of symmetric boundaries (closed channel flow),
399!--    the first grid point is always at z=0.
400       IF ( ibc_uv_b == 0 .OR. ibc_uv_b == 2 .OR.                              & 
401            topography == 'closed_channel' ) THEN
402          zu(0) = 0.0_wp
403       ELSE
404          zu(0) = - dz(1) * 0.5_wp
405       ENDIF
406         
407       zu(1) =   dz(1) * 0.5_wp
408       
409!
410!--    Determine u and v height levels considering the possibility of grid
411!--    stretching in several heights.
412       n = 1
413       dz_stretch_level_start_index = nzt+1
414       dz_stretch_level_end_index = nzt+1
415       dz_stretched = dz(1)
416
417!--    The default value of dz_stretch_level_start is negative, thus the first
418!--    condition is true even if no stretching shall be applied. Hence, the
419!--    second condition is also necessary.
420       DO  k = 2, nzt+1-symmetry_flag
421          IF ( dz_stretch_level_start(n) <= zu(k-1) .AND.                      &
422               dz_stretch_level_start(n) /= -9999999.9_wp ) THEN
423             dz_stretched = dz_stretched * dz_stretch_factor_array(n)
424             
425             IF ( dz(n) > dz(n+1) ) THEN
426                dz_stretched = MAX( dz_stretched, dz(n+1) ) !Restrict dz_stretched to the user-specified (higher) dz
427             ELSE
428                dz_stretched = MIN( dz_stretched, dz(n+1) ) !Restrict dz_stretched to the user-specified (lower) dz
429             ENDIF
430             
431             IF ( dz_stretch_level_start_index(n) == nzt+1 )                         &
432             dz_stretch_level_start_index(n) = k-1
433             
434          ENDIF
435         
436          zu(k) = zu(k-1) + dz_stretched
437         
438!
439!--       Make sure that the stretching ends exactly at dz_stretch_level_end
440          dz_level_end = ABS( zu(k) - dz_stretch_level_end(n) ) 
441         
442          IF ( dz_level_end  < dz(n+1)/3.0 ) THEN
443             zu(k) = dz_stretch_level_end(n)
444             dz_stretched = dz(n+1)
445             dz_stretch_level_end_index(n) = k
446             n = n + 1             
447          ENDIF
448       ENDDO
449       
450!
451!--    If a closed channel flow is simulated, make sure that grid structure is 
452!--    the same for both bottom and top boundary. (Hint: Using a different dz
453!--    at the bottom and at the top makes no sense due to symmetric boundaries
454!--    where dz should be equal. Therefore, different dz at the bottom and top 
455!--    causes an abort (see check_parameters).)
456       IF ( topography == 'closed_channel' ) THEN
457          zu(nzt+1) = zu(nzt) + dz(1) * 0.5_wp
458       ENDIF
459
460!
461!--    Compute the w-levels. They are always staggered half-way between the
462!--    corresponding u-levels. In case of dirichlet bc for u and v at the
463!--    ground the first u- and w-level (k=0) are defined at same height (z=0).
464!--    Per default, the top w-level is extrapolated linearly. In case of
465!--    a closed channel flow, zu(nzt+1) and zw(nzt) must be set explicitely.
466!--    (Hint: Using a different dz at the bottom and at the top makes no sense
467!--    due to symmetric boundaries where dz should be equal. Therefore,
468!--    different dz at the bottom and top causes an abort (see
469!--    check_parameters).)
470       zw(0) = 0.0_wp
471       DO  k = 1, nzt-symmetry_flag
472          zw(k) = ( zu(k) + zu(k+1) ) * 0.5_wp
473       ENDDO
474       IF ( topography == 'closed_channel' ) THEN
475          zw(nzt)   = zw(nzt-1) + dz(1)
476          zw(nzt+1) = zw(nzt) + dz(1)
477       ELSE
478          zw(nzt+1) = zw(nzt) + 2.0_wp * ( zu(nzt+1) - zw(nzt) )
479       ENDIF
480
481    ELSE !ocean branch
482
483!
484!--    The stretching region has to be large enough to allow for a smooth
485!--    transition between two different grid spacings. The number 4 is an
486!--    empirical value
487       DO n = 1, number_stretch_level_start
488          min_dz_stretch_level_end(n) = dz_stretch_level_start(n) -            &
489                                        4 * MAX( dz(n),dz(n+1) )
490       ENDDO
491       
492       IF ( ANY( min_dz_stretch_level_end (1:number_stretch_level_start) <     &
493                 dz_stretch_level_end(1:number_stretch_level_start) ) ) THEN
494             message_string= 'Each dz_stretch_level_end has to be less ' //   &
495                             'than its corresponding value for &' //           &
496                             'dz_stretch_level_start - 4*MAX(dz(n),dz(n+1)) '//&
497                             'to allow for smooth grid stretching'
498             CALL message( 'init_grid', 'PA0224', 1, 2, 0, 6, 0 )
499       ENDIF
500       
501!
502!--    Stretching must not be applied close to the surface (last two grid
503!--    points). For the default case dz_stretch_level_start is negative.
504       IF ( ANY( dz_stretch_level_start >= - dz(1) * 1.5_wp ) ) THEN
505          WRITE( message_string, * ) 'Each dz_stretch_level_start has to be ',&
506                                     'less than ', -dz(1) * 1.5
507             CALL message( 'init_grid', 'PA0226', 1, 2, 0, 6, 0 )
508       ENDIF
509
510!
511!--    The stretching has to start and end on a grid level. Therefore
512!--    user-specified values are mapped to the next highest level. The 
513!--    calculation of the first level is realized differently just because of
514!--    historical reasons (the advanced/new stretching mechanism was realized 
515!--    in a way that results don't change if the old parameters
516!--    dz_stretch_level, dz_stretch_factor and dz_max are used)
517       IF ( number_stretch_level_start /= 0 ) THEN
518          dz_stretch_level_start(1) = INT( (dz_stretch_level_start(1) +        &
519                                            dz(1)/2.0) / dz(1) )               &
520                                      * dz(1) - dz(1)/2.0
521       ENDIF
522       
523       IF ( number_stretch_level_start > 1 ) THEN
524          DO n = 2, number_stretch_level_start
525             dz_stretch_level_start(n) = INT( dz_stretch_level_start(n) /      &
526                                              dz(n) ) * dz(n)
527          ENDDO
528       ENDIF
529       
530       IF ( number_stretch_level_end /= 0 ) THEN
531          DO n = 1, number_stretch_level_end
532             dz_stretch_level_end(n) = INT( dz_stretch_level_end(n) /          &
533                                            dz(n+1) ) * dz(n+1)
534          ENDDO
535       ENDIF
536       
537!
538!--    Determine stretching factor if necessary
539       IF ( number_stretch_level_end >= 1 ) THEN
540          CALL calculate_stretching_factor( number_stretch_level_end )
541       ENDIF
542
543!
544!--    Grid for ocean with free water surface is at k=nzt (w-grid).
545!--    In case of neumann bc at the ground the first first u-level (k=0) lies
546!--    below the first w-level (k=0). In case of dirichlet bc the first u- and
547!--    w-level are defined at same height, but staggered from the second level.
548!--    The second u-level (k=1) corresponds to the top of the surface layer.
549!--    z values are negative starting from z=0 (surface)
550       zu(nzt+1) =   dz(1) * 0.5_wp
551       zu(nzt)   = - dz(1) * 0.5_wp
552
553!
554!--    Determine u and v height levels considering the possibility of grid
555!--    stretching in several heights.
556       n = 1
557       dz_stretch_level_start_index = 0
558       dz_stretch_level_end_index = 0
559       dz_stretched = dz(1)
560
561       DO  k = nzt-1, 0, -1
562         
563          IF ( dz_stretch_level_start(n) >= zu(k+1) ) THEN
564             dz_stretched = dz_stretched * dz_stretch_factor_array(n)
565
566             IF ( dz(n) > dz(n+1) ) THEN
567                dz_stretched = MAX( dz_stretched, dz(n+1) ) !Restrict dz_stretched to the user-specified (higher) dz
568             ELSE
569                dz_stretched = MIN( dz_stretched, dz(n+1) ) !Restrict dz_stretched to the user-specified (lower) dz
570             ENDIF
571             
572             IF ( dz_stretch_level_start_index(n) == 0 )                             &
573             dz_stretch_level_start_index(n) = k+1
574             
575          ENDIF
576         
577          zu(k) = zu(k+1) - dz_stretched
578         
579!
580!--       Make sure that the stretching ends exactly at dz_stretch_level_end
581          dz_level_end = ABS( zu(k) - dz_stretch_level_end(n) ) 
582         
583          IF ( dz_level_end  < dz(n+1)/3.0 ) THEN
584             zu(k) = dz_stretch_level_end(n)
585             dz_stretched = dz(n+1)
586             dz_stretch_level_end_index(n) = k
587             n = n + 1             
588          ENDIF
589       ENDDO
590       
591!
592!--    Compute the w-levels. They are always staggered half-way between the
593!--    corresponding u-levels, except in case of dirichlet bc for u and v
594!--    at the ground. In this case the first u- and w-level are defined at
595!--    same height. The top w-level (nzt+1) is not used but set for
596!--    consistency, since w and all scalar variables are defined up tp nzt+1.
597       zw(nzt+1) = dz(1)
598       zw(nzt)   = 0.0_wp
599       DO  k = 0, nzt
600          zw(k) = ( zu(k) + zu(k+1) ) * 0.5_wp
601       ENDDO
602
603!
604!--    In case of dirichlet bc for u and v the first u- and w-level are defined
605!--    at same height.
606       IF ( ibc_uv_b == 0 ) THEN
607          zu(0) = zw(0)
608       ENDIF
609
610    ENDIF !End of defining the vertical grid levels
611
612!
613!-- Compute grid lengths.
614    DO  k = 1, nzt+1
615       dzu(k)  = zu(k) - zu(k-1)
616       ddzu(k) = 1.0_wp / dzu(k)
617       dzw(k)  = zw(k) - zw(k-1)
618       ddzw(k) = 1.0_wp / dzw(k)
619    ENDDO
620
621    DO  k = 1, nzt
622       dd2zu(k) = 1.0_wp / ( dzu(k) + dzu(k+1) )
623    ENDDO
624   
625!   
626!-- The FFT- SOR-pressure solvers assume grid spacings of a staggered grid
627!-- everywhere. For the actual grid, the grid spacing at the lowest level
628!-- is only dz/2, but should be dz. Therefore, an additional array
629!-- containing with appropriate grid information is created for these
630!-- solvers.
631    IF ( psolver(1:9) /= 'multigrid' )  THEN
632       ALLOCATE( ddzu_pres(1:nzt+1) )
633       ddzu_pres = ddzu
634       ddzu_pres(1) = ddzu_pres(2)  ! change for lowest level
635    ENDIF
636
637!
638!-- Compute the reciprocal values of the horizontal grid lengths.
639    ddx = 1.0_wp / dx
640    ddy = 1.0_wp / dy
641    dx2 = dx * dx
642    dy2 = dy * dy
643    ddx2 = 1.0_wp / dx2
644    ddy2 = 1.0_wp / dy2
645
646!
647!-- Allocate 3D array to set topography
648    ALLOCATE( topo(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
649    topo = 0
650!
651!-- Initialize topography by generic topography or read topography from file. 
652    CALL init_topo( topo )
653!
654!-- Set flags to mask topography on the grid.
655    CALL set_topo_flags( topo )
656
657!
658!-- Determine the maximum level of topography. It is used for
659!-- steering the degradation of order of the applied advection scheme,
660!-- as well in the lpm.
661    k_top = 0
662    DO  i = nxl, nxr
663       DO  j = nys, nyn
664          DO  k = nzb, nzt + 1
665             k_top = MAX( k_top, MERGE( k, 0, .NOT. BTEST( topo(k,j,i), 0 ) ) )
666          ENDDO
667       ENDDO
668    ENDDO
669#if defined( __parallel )
670    CALL MPI_ALLREDUCE( k_top, nzb_max, 1, MPI_INTEGER,                        &
671                        MPI_MAX, comm2d, ierr )
672#else
673    nzb_max = k_top
674#endif
675!
676!-- Increment nzb_max by 1 in order to allow for proper diverengence correction.
677!-- Further, in case topography extents up to the model top, limit to nzt.
678    nzb_max = MIN( nzb_max+1, nzt ) 
679!
680!-- Determine minimum index of topography. Usually, this will be nzb. In case
681!-- there is elevated topography, however, the lowest topography will be higher.
682!-- This index is e.g. used to calculate mean first-grid point atmosphere
683!-- temperature, surface pressure and density, etc. .
684    topo_min_level   = 0
685#if defined( __parallel )
686    CALL MPI_ALLREDUCE( MINVAL( topo_top_ind(nys:nyn,nxl:nxr,0) ),             &
687                        topo_min_level, 1, MPI_INTEGER, MPI_MIN, comm2d, ierr )
688#else
689    topo_min_level = MINVAL( topo_top_ind(nys:nyn,nxl:nxr,0) )
690#endif
691
692!
693!-- Check topography for consistency with model domain. Therefore, use
694!-- maximum and minium topography-top indices. Note, minimum topography top
695!-- index is already calculated. 
696    IF ( TRIM( topography ) /= 'flat' )  THEN
697#if defined( __parallel )
698       CALL MPI_ALLREDUCE( MAXVAL( topo_top_ind(nys:nyn,nxl:nxr,0) ),          &
699                           nzb_local_max, 1, MPI_INTEGER, MPI_MAX, comm2d, ierr )               
700#else
701       nzb_local_max = MAXVAL( topo_top_ind(nys:nyn,nxl:nxr,0) )
702#endif
703       nzb_local_min = topo_min_level
704!
705!--    Consistency checks
706       IF ( nzb_local_min < 0  .OR.  nzb_local_max  > nz + 1 )  THEN
707          WRITE( message_string, * ) 'nzb_local values are outside the',       &
708                                ' model domain',                               &
709                                '&MINVAL( nzb_local ) = ', nzb_local_min,      &
710                                '&MAXVAL( nzb_local ) = ', nzb_local_max
711          CALL message( 'init_grid', 'PA0210', 1, 2, 0, 6, 0 )
712       ENDIF
713    ENDIF
714!
715!-- Define vertical gridpoint from (or to) which on the usual finite difference
716!-- form (which does not use surface fluxes) is applied
717    IF ( constant_flux_layer  .OR.  use_surface_fluxes )  THEN
718       nzb_diff = nzb + 2
719    ELSE
720       nzb_diff = nzb + 1
721    ENDIF
722
723    IF ( TRIM( topography ) /= 'flat' )  THEN
724!
725!--    Allocate and set the arrays containing the topography height (for output
726!--    reasons only).
727       IF ( nxr == nx  .AND.  nyn /= ny )  THEN
728          ALLOCATE( zu_s_inner(nxl:nxr+1,nys:nyn),                             &
729                    zw_w_inner(nxl:nxr+1,nys:nyn) )
730       ELSEIF ( nxr /= nx  .AND.  nyn == ny )  THEN
731          ALLOCATE( zu_s_inner(nxl:nxr,nys:nyn+1),                             &
732                    zw_w_inner(nxl:nxr,nys:nyn+1) )
733       ELSEIF ( nxr == nx  .AND.  nyn == ny )  THEN
734          ALLOCATE( zu_s_inner(nxl:nxr+1,nys:nyn+1),                           &
735                    zw_w_inner(nxl:nxr+1,nys:nyn+1) )
736       ELSE
737          ALLOCATE( zu_s_inner(nxl:nxr,nys:nyn),                               &
738                    zw_w_inner(nxl:nxr,nys:nyn) )
739       ENDIF
740
741       zu_s_inner   = 0.0_wp
742       zw_w_inner   = 0.0_wp
743!
744!--    Determine local topography height on scalar and w-grid. Note, setting
745!--    lateral boundary values is not necessary, realized via wall_flags_static_0
746!--    array. Further, please note that loop bounds are different from
747!--    nxl to nxr and nys to nyn on south and right model boundary, hence,
748!--    use intrinsic lbound and ubound functions to infer array bounds.
749       DO  i = LBOUND(zu_s_inner, 1), UBOUND(zu_s_inner, 1)
750          DO  j = LBOUND(zu_s_inner, 2), UBOUND(zu_s_inner, 2)
751!
752!--          Topography height on scalar grid. Therefore, determine index of
753!--          upward-facing surface element on scalar grid.
754             zu_s_inner(i,j) = zu(topo_top_ind(j,i,0))
755!
756!--          Topography height on w grid. Therefore, determine index of
757!--          upward-facing surface element on w grid.
758             zw_w_inner(i,j) = zw(topo_top_ind(j,i,3))
759          ENDDO
760       ENDDO
761    ENDIF
762
763#if defined( __parallel )
764!
765!-- Vertical nesting: communicate vertical grid level arrays between fine and
766!-- coarse grid
767    IF ( vnested )  CALL vnest_init_grid
768#endif
769
770 END SUBROUTINE init_grid
771
772
773! Description:
774! -----------------------------------------------------------------------------!
775!> Calculation of the stretching factor through an iterative method. Ideas were
776!> taken from the paper "Regional stretched grid generation and its application
777!> to the NCAR RegCM (1999)". Normally, no analytic solution exists because the
778!> system of equations has two variables (r,l) but four requirements
779!> (l=integer, r=[0,88;1,2], Eq(6), Eq(5) starting from index j=1) which
780!> results into an overdetermined system.
781!------------------------------------------------------------------------------!
782 SUBROUTINE calculate_stretching_factor( number_end )
783 
784    USE control_parameters,                                                    &
785        ONLY:  dz, dz_stretch_factor_array,                 &
786               dz_stretch_level_end, dz_stretch_level_start, message_string
787 
788    USE kinds
789   
790    IMPLICIT NONE
791   
792    INTEGER(iwp) ::  iterations  !< number of iterations until stretch_factor_lower/upper_limit is reached 
793    INTEGER(iwp) ::  l_rounded   !< after l_rounded grid levels dz(n) is strechted to dz(n+1) with stretch_factor_2
794    INTEGER(iwp) ::  n           !< loop variable for stretching
795   
796    INTEGER(iwp), INTENT(IN) ::  number_end !< number of user-specified end levels for stretching
797       
798    REAL(wp) ::  delta_l               !< absolute difference between l and l_rounded
799    REAL(wp) ::  delta_stretch_factor  !< absolute difference between stretch_factor_1 and stretch_factor_2
800    REAL(wp) ::  delta_total_new       !< sum of delta_l and delta_stretch_factor for the next iteration (should be as small as possible)
801    REAL(wp) ::  delta_total_old       !< sum of delta_l and delta_stretch_factor for the last iteration
802    REAL(wp) ::  distance              !< distance between dz_stretch_level_start and dz_stretch_level_end (stretching region)
803    REAL(wp) ::  l                     !< value that fulfil Eq. (5) in the paper mentioned above together with stretch_factor_1 exactly
804    REAL(wp) ::  numerator             !< numerator of the quotient
805    REAL(wp) ::  stretch_factor_1      !< stretching factor that fulfil Eq. (5) togehter with l exactly
806    REAL(wp) ::  stretch_factor_2      !< stretching factor that fulfil Eq. (6) togehter with l_rounded exactly
807   
808    REAL(wp) ::  dz_stretch_factor_array_2(9) = 1.08_wp  !< Array that contains all stretch_factor_2 that belongs to stretch_factor_1
809   
810    REAL(wp), PARAMETER ::  stretch_factor_interval = 1.0E-06_wp  !< interval for sampling possible stretching factors
811    REAL(wp), PARAMETER ::  stretch_factor_lower_limit = 0.88_wp  !< lowest possible stretching factor
812    REAL(wp), PARAMETER ::  stretch_factor_upper_limit = 1.12_wp  !< highest possible stretching factor
813 
814 
815    l = 0
816    DO  n = 1, number_end
817   
818       iterations = 1
819       stretch_factor_1 = 1.0_wp 
820       stretch_factor_2 = 1.0_wp
821       delta_total_old = 1.0_wp
822       
823!
824!--    First branch for stretching from rough to fine
825       IF ( dz(n) > dz(n+1) ) THEN
826          DO WHILE ( stretch_factor_1 >= stretch_factor_lower_limit ) 
827             
828             stretch_factor_1 = 1.0_wp - iterations * stretch_factor_interval
829             distance = ABS( dz_stretch_level_end(n) -                         &
830                        dz_stretch_level_start(n) )   
831             numerator = distance*stretch_factor_1/dz(n) +                     &
832                         stretch_factor_1 - distance/dz(n)
833             
834             IF ( numerator > 0.0_wp ) THEN
835                l = LOG( numerator ) / LOG( stretch_factor_1 ) - 1.0_wp
836                l_rounded = NINT( l )
837                delta_l = ABS( l_rounded - l ) / l
838             ENDIF
839             
840             stretch_factor_2 = EXP( LOG( dz(n+1)/dz(n) ) / (l_rounded) )
841             
842             delta_stretch_factor = ABS( stretch_factor_1 -                    &
843                                         stretch_factor_2 ) /                  &
844                                    stretch_factor_2
845             
846             delta_total_new = delta_l + delta_stretch_factor
847
848!
849!--          stretch_factor_1 is taken to guarantee that the stretching
850!--          procedure ends as close as possible to dz_stretch_level_end.
851!--          stretch_factor_2 would guarantee that the stretched dz(n) is
852!--          equal to dz(n+1) after l_rounded grid levels.
853             IF (delta_total_new < delta_total_old) THEN
854                dz_stretch_factor_array(n) = stretch_factor_1
855                dz_stretch_factor_array_2(n) = stretch_factor_2
856                delta_total_old = delta_total_new
857             ENDIF
858             
859             iterations = iterations + 1
860           
861          ENDDO
862
863!
864!--    Second branch for stretching from fine to rough
865       ELSEIF ( dz(n) < dz(n+1) ) THEN
866          DO WHILE ( stretch_factor_1 <= stretch_factor_upper_limit )
867                     
868             stretch_factor_1 = 1.0_wp + iterations * stretch_factor_interval
869             distance = ABS( dz_stretch_level_end(n) -                         &
870                        dz_stretch_level_start(n) ) 
871             numerator = distance*stretch_factor_1/dz(n) +                     &
872                         stretch_factor_1 - distance/dz(n)
873             
874             l = LOG( numerator ) / LOG( stretch_factor_1 ) - 1.0_wp
875             l_rounded = NINT( l )
876             delta_l = ABS( l_rounded - l ) / l
877             
878             stretch_factor_2 = EXP( LOG( dz(n+1)/dz(n) ) / (l_rounded) )
879
880             delta_stretch_factor = ABS( stretch_factor_1 -                    &
881                                        stretch_factor_2 ) /                   &
882                                        stretch_factor_2
883             
884             delta_total_new = delta_l + delta_stretch_factor
885             
886!
887!--          stretch_factor_1 is taken to guarantee that the stretching
888!--          procedure ends as close as possible to dz_stretch_level_end.
889!--          stretch_factor_2 would guarantee that the stretched dz(n) is
890!--          equal to dz(n+1) after l_rounded grid levels.
891             IF (delta_total_new < delta_total_old) THEN
892                dz_stretch_factor_array(n) = stretch_factor_1
893                dz_stretch_factor_array_2(n) = stretch_factor_2
894                delta_total_old = delta_total_new
895             ENDIF
896             
897             iterations = iterations + 1
898          ENDDO
899         
900       ELSE
901          message_string= 'Two adjacent values of dz must be different'
902          CALL message( 'init_grid', 'PA0228', 1, 2, 0, 6, 0 )
903         
904       ENDIF
905
906!
907!--    Check if also the second stretching factor fits into the allowed
908!--    interval. If not, print a warning for the user.
909       IF ( dz_stretch_factor_array_2(n) < stretch_factor_lower_limit .OR.     & 
910            dz_stretch_factor_array_2(n) > stretch_factor_upper_limit ) THEN
911          WRITE( message_string, * ) 'stretch_factor_2 = ',                    &
912                                     dz_stretch_factor_array_2(n), ' which is',&
913                                     ' responsible for exactly reaching& dz =',&
914                                      dz(n+1), 'after a specific amount of',   & 
915                                     ' grid levels& exceeds the upper',        &
916                                     ' limit =', stretch_factor_upper_limit,   &
917                                     ' &or lower limit = ',                    &
918                                     stretch_factor_lower_limit
919          CALL message( 'init_grid', 'PA0499', 0, 1, 0, 6, 0 )
920           
921       ENDIF
922    ENDDO
923       
924 END SUBROUTINE calculate_stretching_factor
925 
926 
927! Description:
928! -----------------------------------------------------------------------------!
929!> Set temporary topography flags and reference buildings on top of underlying
930!> orography.
931!------------------------------------------------------------------------------!
932 SUBROUTINE process_topography( topo_3d )
933
934    USE arrays_3d,                                                             &
935        ONLY:  zu, zw
936
937    USE control_parameters,                                                    &
938        ONLY:  bc_lr_cyc, bc_ns_cyc, message_string, ocean_mode
939
940    USE exchange_horiz_mod,                                                    &
941        ONLY:  exchange_horiz_int, exchange_horiz_2d
942
943    USE indices,                                                               &
944        ONLY:  nbgp, nx, nxl, nxlg, nxr, nxrg, ny, nyn, nyng, nys, nysg, nzb,  &
945               nzt
946
947    USE netcdf_data_input_mod,                                                 &
948        ONLY:  buildings_f, building_id_f, building_type_f, input_pids_static, &
949               terrain_height_f
950
951    USE kinds
952
953    USE pegrid
954
955    IMPLICIT NONE
956
957    INTEGER(iwp) ::  i                !< running index along x-direction
958    INTEGER(iwp) ::  j                !< running index along y-direction
959    INTEGER(iwp) ::  k                !< running index along z-direction with respect to numeric grid
960    INTEGER(iwp) ::  k2               !< running index along z-direction with respect to netcdf grid
961    INTEGER(iwp) ::  nr               !< index variable indication maximum terrain height for respective building ID
962    INTEGER(iwp) ::  num_build        !< counter for number of buildings
963    INTEGER(iwp) ::  topo_top_index   !< orography top index, used to map 3D buildings onto terrain
964
965#if defined( __parallel )
966    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  displace_dum        !< displacements of start addresses, used for MPI_ALLGATHERV
967#endif
968    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  build_ids           !< building IDs on entire model domain
969    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  build_ids_final     !< building IDs on entire model domain, multiple occurences are sorted out
970    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  build_ids_final_tmp !< temporary array used for resizing
971    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  build_ids_l         !< building IDs on local subdomain
972    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  build_ids_l_tmp     !< temporary array used to resize array of building IDs
973
974    INTEGER(iwp), DIMENSION(0:numprocs-1) ::  num_buildings     !< number of buildings with different ID on entire model domain
975    INTEGER(iwp), DIMENSION(0:numprocs-1) ::  num_buildings_l   !< number of buildings with different ID on local subdomain
976
977    INTEGER(iwp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg) ::  topo_3d !< input array for 3D topography and dummy array for setting "outer"-flags
978
979    REAL(wp)                            ::  ocean_offset        !< offset to consider inverse vertical coordinate at topography definition
980    REAL(wp)                            ::  oro_min = 0.0_wp    !< minimum terrain height in entire model domain, used to reference terrain to zero
981    REAL(wp), DIMENSION(:), ALLOCATABLE ::  oro_max             !< maximum terrain height occupied by an building with certain id
982    REAL(wp), DIMENSION(:), ALLOCATABLE ::  oro_max_l           !< maximum terrain height occupied by an building with certain id, on local subdomain
983
984!
985!-- Reference lowest terrain height to zero. In case the minimum terrain height
986!-- is non-zero, all grid points of the lower vertical grid levels might be
987!-- entirely below the surface, meaning a waste of computational resources.
988!-- In order to avoid this, remove the lowest terrain height. Please note,
989!-- in case of a nested run, the global minimum from all parent and childs
990!-- need to be remove to avoid steep edges at the child-domain boundaries.
991    IF ( input_pids_static )  THEN
992   
993#if defined( __parallel ) 
994       CALL MPI_ALLREDUCE( MINVAL( terrain_height_f%var ), oro_min, 1,         &
995                           MPI_REAL, MPI_MIN, MPI_COMM_WORLD, ierr )
996#else
997       oro_min = MINVAL( terrain_height_f%var )
998#endif
999       terrain_height_f%var = terrain_height_f%var - oro_min
1000!                           
1001!--    Give an informative message that terrain height is referenced to zero   
1002       IF ( oro_min > 0.0_wp )  THEN
1003          WRITE( message_string, * ) 'Terrain height was internally shifted '//&
1004                          'downwards by ', oro_min, 'meter(s) to save ' //     &
1005                          'computational resources.'
1006          CALL message( 'init_grid', 'PA0505', 0, 0, 0, 6, 0 )
1007       ENDIF
1008    ENDIF   
1009   
1010!
1011!-- In the following, buildings and orography are further preprocessed
1012!-- before they are mapped on the LES grid.
1013!-- Buildings are mapped on top of the orography by maintaining the roof
1014!-- shape of the building. This can be achieved by referencing building on
1015!-- top of the maximum terrain height within the area occupied by the
1016!-- respective building. As buildings and terrain height are defined PE-wise,
1017!-- parallelization of this referencing is required (a building can be
1018!-- distributed between different PEs). 
1019!-- In a first step, determine the number of buildings with different
1020!-- building id on each PE. In a next step, all building ids are gathered
1021!-- into one array which is present to all PEs. For each building ID,
1022!-- the maximum terrain height occupied by the respective building is
1023!-- computed and distributed to each PE. 
1024!-- Finally, for each building id and its respective reference orography,
1025!-- builidings are mapped on top.   
1026!--
1027!-- First, pre-set topography flags, bit 1 indicates orography, bit 2
1028!-- buildings
1029!-- classify the respective surfaces.
1030    topo_3d          = IBSET( topo_3d, 0 )
1031    topo_3d(nzb,:,:) = IBCLR( topo_3d(nzb,:,:), 0 )
1032!
1033!-- In order to map topography on PALM grid also in case of ocean simulations,
1034!-- pre-calculate an offset value.
1035    ocean_offset = MERGE( zw(0), 0.0_wp, ocean_mode )
1036!
1037!-- Reference buildings on top of orography. This is not necessary
1038!-- if topography is read from ASCII file as no distinction between buildings
1039!-- and terrain height can be made. Moreover, this is also not necessary if
1040!-- urban-surface and land-surface model are used at the same time.
1041    IF ( input_pids_static )  THEN
1042
1043       IF ( buildings_f%from_file )  THEN
1044          num_buildings_l = 0
1045          num_buildings   = 0
1046!
1047!--       Allocate at least one element for building ids and give it an inital
1048!--       negative value that will be overwritten later. This, however, is
1049!--       necessary in case there all IDs in the model domain are fill values.
1050          ALLOCATE( build_ids_l(1) )
1051          build_ids_l = -1 
1052          DO  i = nxl, nxr
1053             DO  j = nys, nyn
1054                IF ( building_id_f%var(j,i) /= building_id_f%fill )  THEN
1055                   IF ( num_buildings_l(myid) > 0 )  THEN
1056                      IF ( ANY( building_id_f%var(j,i) ==  build_ids_l ) )   &
1057                      THEN
1058                         CYCLE
1059                      ELSE
1060                         num_buildings_l(myid) = num_buildings_l(myid) + 1
1061!
1062!--                   Resize array with different local building ids
1063                      ALLOCATE( build_ids_l_tmp(1:SIZE(build_ids_l)) )
1064                      build_ids_l_tmp = build_ids_l
1065                      DEALLOCATE( build_ids_l )
1066                      ALLOCATE( build_ids_l(1:num_buildings_l(myid)) )
1067                      build_ids_l(1:num_buildings_l(myid)-1) =                 &
1068                                  build_ids_l_tmp(1:num_buildings_l(myid)-1)
1069                      build_ids_l(num_buildings_l(myid)) = building_id_f%var(j,i)
1070                      DEALLOCATE( build_ids_l_tmp )
1071                   ENDIF
1072!
1073!--                First occuring building id on PE
1074                   ELSE
1075                      num_buildings_l(myid) = num_buildings_l(myid) + 1
1076                      build_ids_l(1) = building_id_f%var(j,i)
1077                   ENDIF
1078                ENDIF
1079             ENDDO
1080          ENDDO
1081!
1082!--       Determine number of different building ids for the entire domain
1083#if defined( __parallel ) 
1084          CALL MPI_ALLREDUCE( num_buildings_l, num_buildings, numprocs,              &
1085                              MPI_INTEGER, MPI_SUM, comm2d, ierr ) 
1086#else
1087          num_buildings = num_buildings_l
1088#endif
1089!
1090!--       Gather all buildings ids on each PEs.
1091!--       First, allocate array encompassing all building ids in model domain. 
1092          ALLOCATE( build_ids(1:SUM(num_buildings)) )
1093#if defined( __parallel ) 
1094!
1095!--       Allocate array for displacements.
1096!--       As each PE may has a different number of buildings, so that
1097!--       the block sizes send by each PE may not be equal. Hence,
1098!--       information about the respective displacement is required, indicating
1099!--       the respective adress where each MPI-task writes into the receive
1100!--       buffer array 
1101          ALLOCATE( displace_dum(0:numprocs-1) )
1102          displace_dum(0) = 0
1103          DO i = 1, numprocs-1
1104             displace_dum(i) = displace_dum(i-1) + num_buildings(i-1)
1105          ENDDO
1106
1107          CALL MPI_ALLGATHERV( build_ids_l(1:num_buildings_l(myid)),                 &
1108                               num_buildings(myid),                                  &
1109                               MPI_INTEGER,                                          &
1110                               build_ids,                                            &
1111                               num_buildings,                                        &
1112                               displace_dum,                                         & 
1113                               MPI_INTEGER,                                          &
1114                               comm2d, ierr )   
1115
1116          DEALLOCATE( displace_dum )
1117
1118#else
1119          build_ids = build_ids_l
1120#endif
1121
1122!
1123!--       Note, in parallel mode building ids can occure mutliple times, as
1124!--       each PE has send its own ids. Therefore, sort out building ids which
1125!--       appear more than one time.
1126          num_build = 0
1127          DO  nr = 1, SIZE(build_ids)
1128
1129             IF ( ALLOCATED(build_ids_final) )  THEN
1130                IF ( ANY( build_ids(nr) == build_ids_final ) )  THEN
1131                   CYCLE
1132                ELSE
1133                   num_build = num_build + 1
1134!
1135!--                Resize
1136                   ALLOCATE( build_ids_final_tmp(1:num_build) )
1137                   build_ids_final_tmp(1:num_build-1) = build_ids_final(1:num_build-1)
1138                   DEALLOCATE( build_ids_final )
1139                   ALLOCATE( build_ids_final(1:num_build) )
1140                   build_ids_final(1:num_build-1) = build_ids_final_tmp(1:num_build-1)
1141                   build_ids_final(num_build) = build_ids(nr)
1142                   DEALLOCATE( build_ids_final_tmp )
1143                ENDIF             
1144             ELSE
1145                num_build = num_build + 1
1146                ALLOCATE( build_ids_final(1:num_build) )
1147                build_ids_final(num_build) = build_ids(nr)
1148             ENDIF
1149          ENDDO
1150
1151!
1152!--       Determine maximumum terrain height occupied by the respective
1153!--       building and temporalily store on oro_max
1154          ALLOCATE( oro_max_l(1:SIZE(build_ids_final)) )
1155          ALLOCATE( oro_max(1:SIZE(build_ids_final))   )
1156          oro_max_l = 0.0_wp
1157
1158          DO  nr = 1, SIZE(build_ids_final)
1159             oro_max_l(nr) = MAXVAL(                                           &
1160                              MERGE( terrain_height_f%var(nys:nyn,nxl:nxr),    &
1161                                     0.0_wp,                                   &
1162                                     building_id_f%var(nys:nyn,nxl:nxr) ==     &
1163                                     build_ids_final(nr) ) )
1164          ENDDO
1165   
1166#if defined( __parallel )   
1167          IF ( SIZE(build_ids_final) >= 1 ) THEN
1168             CALL MPI_ALLREDUCE( oro_max_l, oro_max, SIZE( oro_max ), MPI_REAL,&
1169                                 MPI_MAX, comm2d, ierr ) 
1170          ENDIF
1171#else
1172          oro_max = oro_max_l
1173#endif
1174!
1175!--       Finally, determine discrete grid height of maximum orography occupied
1176!--       by a building. Use all-or-nothing approach, i.e. if terrain
1177!--       exceeds the scalar level the grid box is fully terrain and the
1178!--       maximum terrain is set to the zw level.
1179!--       terrain or
1180          oro_max_l = 0.0
1181          DO  nr = 1, SIZE(build_ids_final)
1182             DO  k = nzb, nzt
1183                IF ( zu(k) - ocean_offset <= oro_max(nr) )                     &
1184                   oro_max_l(nr) = zw(k) - ocean_offset
1185             ENDDO
1186             oro_max(nr) = oro_max_l(nr)
1187          ENDDO
1188       ENDIF
1189!
1190!--    Allocate array for storing terrain height under buildings
1191       IF ( buildings_f%from_file )  THEN
1192          ALLOCATE( buildings_f%oro_max(nysg:nyng,nxlg:nxrg) )
1193          buildings_f%oro_max = buildings_f%fill1
1194       END IF
1195!
1196!--    Map orography as well as buildings onto grid.
1197       DO  i = nxl, nxr
1198          DO  j = nys, nyn
1199             topo_top_index = 0
1200!
1201!--          Obtain index in global building_id array
1202             IF ( buildings_f%from_file )  THEN
1203                IF ( building_id_f%var(j,i) /= building_id_f%fill )  THEN
1204!
1205!--                Determine index where maximum terrain height occupied by
1206!--                the respective building height is stored.
1207                   nr = MINLOC( ABS( build_ids_final -                         &
1208                                     building_id_f%var(j,i) ), DIM = 1 )
1209!
1210!--                Save grid-indexed oro_max
1211                   buildings_f%oro_max(j,i) = oro_max(nr)
1212                ENDIF
1213             ENDIF
1214             DO  k = nzb, nzt
1215!
1216!--             In a first step, if grid point is below or equal the given
1217!--             terrain height, grid point is flagged to be of type natural.
1218!--             Please note, in case there is also a building which is lower
1219!--             than the vertical grid spacing, initialization of surface
1220!--             attributes will not be correct as given surface information
1221!--             will not be in accordance to the classified grid points.
1222!--             Hence, in this case, also a building flag.
1223                IF ( zu(k) - ocean_offset <= terrain_height_f%var(j,i) )  THEN
1224                   topo_3d(k,j,i) = IBCLR( topo_3d(k,j,i), 0 )
1225                   topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 1 )
1226                   topo_top_index = k ! topo_top_index + 1
1227                ENDIF
1228!
1229!--             Set building grid points. Here, only consider 2D buildings.
1230!--             3D buildings require separate treatment.
1231                IF ( buildings_f%from_file  .AND.  buildings_f%lod == 1 )  THEN
1232!
1233!--                Fill-up the terrain to the level of maximum orography
1234!--                within the building-covered area.
1235                   IF ( building_id_f%var(j,i) /= building_id_f%fill )  THEN
1236!
1237!--                   Note, oro_max is always on zw level                   
1238                      IF ( zu(k) - ocean_offset < oro_max(nr) )  THEN
1239                         topo_3d(k,j,i) = IBCLR( topo_3d(k,j,i), 0 )
1240                         topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 1 )
1241                      ELSEIF ( zu(k) - ocean_offset <=                         &
1242                               oro_max(nr) + buildings_f%var_2d(j,i) )  THEN
1243                         topo_3d(k,j,i) = IBCLR( topo_3d(k,j,i), 0 )
1244                         topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 2 )
1245                      ENDIF
1246                   ENDIF
1247                ENDIF
1248             ENDDO
1249!
1250!--          Special treatment for non grid-resolved buildings. This case,
1251!--          the uppermost terrain grid point is flagged as building as well
1252!--          well, even though no building exists at all. However, the
1253!--          surface element will be identified as urban-surface and the
1254!--          input data provided by the drivers is consistent to the surface
1255!--          classification. Else, all non grid-resolved buildings would vanish
1256!--          and identified as terrain grid points, which, however, won't be
1257!--          consistent with the input data.
1258             IF ( buildings_f%from_file  .AND.  buildings_f%lod == 1 )  THEN
1259                IF ( building_id_f%var(j,i) /= building_id_f%fill )  THEN
1260                   DO  k = nzb, nzt
1261                      IF( zw(k) - ocean_offset == oro_max(nr) )  THEN
1262                         IF ( buildings_f%var_2d(j,i) <= zu(k+1) - zw(k) )  THEN
1263                            topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 2 )
1264                         ENDIF
1265                      ENDIF
1266                   ENDDO
1267                ENDIF
1268             ENDIF
1269!
1270!--          Map 3D buildings onto terrain height. 
1271!--          In case of any slopes, map building on top of maximum terrain
1272!--          height covered by the building. In other words, extend
1273!--          building down to the respective local terrain-surface height.
1274             IF ( buildings_f%from_file  .AND.  buildings_f%lod == 2 )  THEN
1275                IF ( building_id_f%var(j,i) /= building_id_f%fill )  THEN
1276!
1277!--                Extend building down to the terrain surface, i.e. fill-up
1278!--                surface irregularities below a building. Note, oro_max
1279!--                is already a discrete height according to the all-or-nothing
1280!--                approach, i.e. grid box is either topography or atmosphere,
1281!--                terrain top is defined at upper bound of the grid box.
1282!--                Hence, check for zw in this case.
1283!--                Note, do this only for buildings which are surface mounted,
1284!--                i.e. building types 1-6. Below bridges, which are represented
1285!--                exclusively by building type 7, terrain shape should be
1286!--                maintained.
1287                   IF ( building_type_f%from_file )  THEN
1288                      IF ( building_type_f%var(j,i) /= 7 )  THEN
1289                         DO k = topo_top_index + 1, nzt + 1     
1290                            IF ( zu(k) - ocean_offset <= oro_max(nr) )  THEN
1291                               topo_3d(k,j,i) = IBCLR( topo_3d(k,j,i), 0 )
1292                               topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 1 )
1293                            ENDIF
1294                         ENDDO       
1295!                     
1296!--                      After surface irregularities are smoothen, determine
1297!--                      lower start index where building starts.
1298                         DO  k = nzb, nzt
1299                            IF ( zu(k) - ocean_offset <= oro_max(nr) )         &
1300                               topo_top_index = k
1301                         ENDDO
1302                      ENDIF
1303                   ENDIF
1304!
1305!--                Finally, map building on top.
1306                   k2 = 0
1307                   DO k = topo_top_index, nzt + 1
1308                      IF ( k2 <= buildings_f%nz-1 )  THEN
1309                         IF ( buildings_f%var_3d(k2,j,i) == 1 )  THEN
1310                            topo_3d(k,j,i) = IBCLR( topo_3d(k,j,i), 0 )
1311                            topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 2 )
1312                         ENDIF
1313                      ENDIF
1314                      k2 = k2 + 1
1315                   ENDDO
1316                ENDIF
1317             ENDIF
1318          ENDDO
1319       ENDDO
1320!
1321!--    Horizontal exchange the oro_max array, which is required to for
1322!--    initialization of building-surface properties.
1323       IF ( ALLOCATED( buildings_f%oro_max ) )  THEN
1324          CALL exchange_horiz_2d( buildings_f%oro_max(:,:) )
1325       ENDIF
1326!
1327!--    Deallocate temporary arrays required for processing and reading data
1328       IF ( ALLOCATED( oro_max         ) )  DEALLOCATE( oro_max         )
1329       IF ( ALLOCATED( oro_max_l       ) )  DEALLOCATE( oro_max_l       )
1330       IF ( ALLOCATED( build_ids_final ) )  DEALLOCATE( build_ids_final )
1331!
1332!-- Topography input via ASCII format.
1333    ELSE
1334       ocean_offset     = MERGE( zw(0), 0.0_wp, ocean_mode )
1335!
1336!--    Initialize topography bit 0 (indicates obstacle) everywhere to zero
1337!--    and clear all grid points at nzb, where alway a surface is defined.
1338!--    Further, set also bit 1 (indicates terrain) at nzb, which is further
1339!--    used for masked data output and further processing. Note, in the
1340!--    ASCII case no distinction is made between buildings and terrain,
1341!--    so that setting of bit 1 and 2 at the same time has no effect.
1342       topo_3d          = IBSET( topo_3d, 0 )
1343       topo_3d(nzb,:,:) = IBCLR( topo_3d(nzb,:,:), 0 )
1344       topo_3d(nzb,:,:) = IBSET( topo_3d(nzb,:,:), 1 )
1345       DO  i = nxl, nxr
1346          DO  j = nys, nyn
1347             DO  k = nzb, nzt
1348!
1349!--             Flag topography for all grid points which are below
1350!--             the local topography height.
1351!--             Note, each topography is flagged as building.
1352                IF ( zu(k) - ocean_offset <= buildings_f%var_2d(j,i) )  THEN
1353                   topo_3d(k,j,i) = IBCLR( topo_3d(k,j,i), 0 )
1354                   topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 2 ) !indicates building
1355                ENDIF
1356             ENDDO
1357          ENDDO
1358       ENDDO
1359    ENDIF
1360
1361    CALL exchange_horiz_int( topo_3d, nys, nyn, nxl, nxr, nzt, nbgp )
1362
1363    IF ( .NOT. bc_ns_cyc )  THEN
1364       IF ( nys == 0  )  topo_3d(:,-1,:)   = topo_3d(:,0,:)
1365       IF ( nyn == ny )  topo_3d(:,ny+1,:) = topo_3d(:,ny,:)
1366    ENDIF
1367
1368    IF ( .NOT. bc_lr_cyc )  THEN
1369       IF ( nxl == 0  )  topo_3d(:,:,-1)   = topo_3d(:,:,0)
1370       IF ( nxr == nx )  topo_3d(:,:,nx+1) = topo_3d(:,:,nx)         
1371    ENDIF
1372
1373 END SUBROUTINE process_topography
1374
1375
1376! Description:
1377! -----------------------------------------------------------------------------!
1378!> Filter topography, i.e. fill holes resolved by only one grid point. 
1379!> Such holes are suspected to lead to velocity blow-ups as continuity
1380!> equation on discrete grid cannot be fulfilled in such case.
1381!------------------------------------------------------------------------------!
1382 SUBROUTINE filter_topography( topo_3d )
1383
1384    USE control_parameters,                                                    &
1385        ONLY:  bc_lr_cyc, bc_ns_cyc, message_string
1386
1387    USE exchange_horiz_mod,                                                    &
1388        ONLY:  exchange_horiz_int, exchange_horiz_2d_byte, exchange_horiz_2d_int
1389
1390    USE indices,                                                               &
1391        ONLY:  nbgp, nx, nxl, nxlg, nxr, nxrg, ny, nyn, nyng, nys, nysg, nzb, nzt
1392
1393    USE netcdf_data_input_mod,                                                 &
1394        ONLY:  building_id_f, building_type_f 
1395
1396    USE  pegrid
1397
1398    IMPLICIT NONE
1399
1400    LOGICAL      ::  filled = .FALSE. !< flag indicating if holes were filled
1401
1402    INTEGER(iwp) ::  i          !< running index along x-direction
1403    INTEGER(iwp) ::  j          !< running index along y-direction
1404    INTEGER(iwp) ::  k          !< running index along z-direction
1405    INTEGER(iwp) ::  num_hole   !< number of holes (in topography) resolved by only one grid point
1406    INTEGER(iwp) ::  num_hole_l !< number of holes (in topography) resolved by only one grid point on local PE     
1407    INTEGER(iwp) ::  num_wall   !< number of surrounding vertical walls for a single grid point
1408
1409    INTEGER(iwp), DIMENSION(:,:,:), ALLOCATABLE            ::  topo_tmp          !< temporary 3D-topography used to fill holes
1410    INTEGER(iwp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg) ::  topo_3d           !< 3D-topography array merging buildings and orography
1411!
1412!-- Before checking for holes, set lateral boundary conditions for
1413!-- topography. After hole-filling, boundary conditions must be set again.
1414!-- Several iterations are performed, in order to fill holes which might
1415!-- emerge by the filling-algorithm itself.
1416    ALLOCATE( topo_tmp(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
1417    topo_tmp = 0
1418
1419    num_hole = 99999
1420    DO WHILE ( num_hole > 0 )       
1421
1422       num_hole = 0   
1423       CALL exchange_horiz_int( topo_3d, nys, nyn, nxl, nxr, nzt, nbgp )
1424!
1425!--    Exchange also building ID and type. Note, building_type is an one-byte
1426!--    variable.
1427       IF ( building_id_f%from_file )                                          &
1428          CALL exchange_horiz_2d_int( building_id_f%var, nys, nyn, nxl, nxr, nbgp )
1429       IF ( building_type_f%from_file )                                        &
1430          CALL exchange_horiz_2d_byte( building_type_f%var, nys, nyn, nxl, nxr, nbgp )
1431
1432       topo_tmp = topo_3d
1433!
1434!--    In case of non-cyclic lateral boundaries, assume lateral boundary to be
1435!--    a solid wall. Thus, intermediate spaces of one grid point between
1436!--    boundary and some topographic structure will be filled.           
1437       IF ( .NOT. bc_ns_cyc )  THEN
1438          IF ( nys == 0  )  topo_tmp(:,-1,:)   = IBCLR( topo_tmp(:,0,:),  0 )
1439          IF ( nyn == ny )  topo_tmp(:,ny+1,:) = IBCLR( topo_tmp(:,ny,:), 0 )
1440       ENDIF
1441
1442       IF ( .NOT. bc_lr_cyc )  THEN
1443          IF ( nxl == 0  )  topo_tmp(:,:,-1)   = IBCLR( topo_tmp(:,:,0),  0 )
1444          IF ( nxr == nx )  topo_tmp(:,:,nx+1) = IBCLR( topo_tmp(:,:,nx), 0 )         
1445       ENDIF
1446
1447       num_hole_l = 0
1448       DO i = nxl, nxr
1449          DO j = nys, nyn
1450             DO  k = nzb+1, nzt
1451                IF ( BTEST( topo_tmp(k,j,i), 0 ) )  THEN
1452                   num_wall = 0
1453                   IF ( .NOT. BTEST( topo_tmp(k,j-1,i), 0 ) )                  &
1454                      num_wall = num_wall + 1
1455                   IF ( .NOT. BTEST( topo_tmp(k,j+1,i), 0 ) )                  &
1456                      num_wall = num_wall + 1
1457                   IF ( .NOT. BTEST( topo_tmp(k,j,i-1), 0 ) )                  &
1458                      num_wall = num_wall + 1
1459                   IF ( .NOT. BTEST( topo_tmp(k,j,i+1), 0 ) )                  &
1460                      num_wall = num_wall + 1
1461                   IF ( .NOT. BTEST( topo_tmp(k-1,j,i), 0 ) )                  &
1462                      num_wall = num_wall + 1   
1463                   IF ( .NOT. BTEST( topo_tmp(k+1,j,i), 0 ) )                  &
1464                      num_wall = num_wall + 1
1465
1466                   IF ( num_wall >= 4 )  THEN
1467                      num_hole_l     = num_hole_l + 1
1468!
1469!--                   Clear flag 0 and set special flag ( bit 4) to indicate
1470!--                   that new topography point is a result of filtering process.
1471                      topo_3d(k,j,i) = IBCLR( topo_3d(k,j,i), 0 )
1472                      topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 4 )
1473!
1474!--                   If filled grid point is occupied by a building, classify
1475!--                   it as building grid point.
1476                      IF ( building_type_f%from_file )  THEN
1477                         IF ( building_type_f%var(j,i)   /=                    & 
1478                              building_type_f%fill            .OR.             &       
1479                              building_type_f%var(j+1,i) /=                    & 
1480                              building_type_f%fill            .OR.             &               
1481                              building_type_f%var(j-1,i) /=                    &               
1482                              building_type_f%fill            .OR.             &               
1483                              building_type_f%var(j,i+1) /=                    &               
1484                              building_type_f%fill            .OR.             &               
1485                              building_type_f%var(j,i-1) /=                    &               
1486                              building_type_f%fill )  THEN
1487!
1488!--                         Set flag indicating building surfaces
1489                            topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 2 )
1490!
1491!--                         Set building_type and ID at this position if not
1492!--                         already set. This is required for proper
1493!--                         initialization of urban-surface energy balance
1494!--                         solver.
1495                            IF ( building_type_f%var(j,i) ==                   &
1496                                 building_type_f%fill )  THEN
1497
1498                               IF ( building_type_f%var(j+1,i) /=              &
1499                                    building_type_f%fill )  THEN
1500                                  building_type_f%var(j,i) =                   &
1501                                                    building_type_f%var(j+1,i)
1502                                  building_id_f%var(j,i) =                     &
1503                                                    building_id_f%var(j+1,i)
1504                               ELSEIF ( building_type_f%var(j-1,i) /=          &
1505                                        building_type_f%fill )  THEN
1506                                  building_type_f%var(j,i) =                   &
1507                                                    building_type_f%var(j-1,i)
1508                                  building_id_f%var(j,i) =                     &
1509                                                    building_id_f%var(j-1,i)
1510                               ELSEIF ( building_type_f%var(j,i+1) /=          &
1511                                        building_type_f%fill )  THEN
1512                                  building_type_f%var(j,i) =                   &
1513                                                    building_type_f%var(j,i+1)
1514                                  building_id_f%var(j,i) =                     &
1515                                                    building_id_f%var(j,i+1)
1516                               ELSEIF ( building_type_f%var(j,i-1) /=          &
1517                                        building_type_f%fill )  THEN
1518                                  building_type_f%var(j,i) =                   &
1519                                                    building_type_f%var(j,i-1)
1520                                  building_id_f%var(j,i) =                     &
1521                                                    building_id_f%var(j,i-1)
1522                               ENDIF
1523                            ENDIF
1524                         ENDIF
1525                      ENDIF
1526!
1527!--                   If filled grid point is already classified as building
1528!--                   everything is fine, else classify this grid point as
1529!--                   natural type grid point. This case, values for the
1530!--                   surface type are already set.
1531                      IF ( .NOT. BTEST( topo_3d(k,j,i), 2 ) )  THEN
1532                         topo_3d(k,j,i) = IBSET( topo_3d(k,j,i), 1 )
1533                      ENDIF
1534                   ENDIF
1535                ENDIF
1536             ENDDO
1537          ENDDO
1538       ENDDO
1539!
1540!--    Count the total number of holes, required for informative message.
1541#if defined( __parallel )
1542       CALL MPI_ALLREDUCE( num_hole_l, num_hole, 1, MPI_INTEGER, MPI_SUM,      &
1543                           comm2d, ierr )
1544#else
1545       num_hole = num_hole_l
1546#endif   
1547       IF ( num_hole > 0  .AND.  .NOT. filled )  filled = .TRUE.
1548
1549    ENDDO
1550!
1551!-- Create an informative message if any holes were filled.
1552    IF ( filled )  THEN
1553       WRITE( message_string, * ) 'Topography was filtered, i.e. holes ' //    &
1554                                  'resolved by only one grid point '     //    &
1555                                  'were filled during initialization.'
1556       CALL message( 'init_grid', 'PA0430', 0, 0, 0, 6, 0 )
1557    ENDIF
1558
1559    DEALLOCATE( topo_tmp )
1560!
1561!-- Finally, exchange topo_3d array again and if necessary set Neumann boundary
1562!-- condition in case of non-cyclic lateral boundaries.
1563    CALL exchange_horiz_int( topo_3d, nys, nyn, nxl, nxr, nzt, nbgp )
1564
1565    IF ( .NOT. bc_ns_cyc )  THEN
1566       IF ( nys == 0  )  topo_3d(:,-1,:)   = topo_3d(:,0,:)
1567       IF ( nyn == ny )  topo_3d(:,ny+1,:) = topo_3d(:,ny,:)
1568    ENDIF
1569
1570    IF ( .NOT. bc_lr_cyc )  THEN
1571       IF ( nxl == 0  )  topo_3d(:,:,-1)   = topo_3d(:,:,0)
1572       IF ( nxr == nx )  topo_3d(:,:,nx+1) = topo_3d(:,:,nx)         
1573    ENDIF
1574!
1575!-- Exchange building ID and type. Note, building_type is an one-byte variable.
1576    IF ( building_id_f%from_file )                                             &
1577       CALL exchange_horiz_2d_int( building_id_f%var, nys, nyn, nxl, nxr, nbgp )
1578    IF ( building_type_f%from_file )                                           &
1579       CALL exchange_horiz_2d_byte( building_type_f%var, nys, nyn, nxl, nxr, nbgp )
1580
1581 END SUBROUTINE filter_topography
1582
1583
1584! Description:
1585! -----------------------------------------------------------------------------!
1586!> Reads topography information from file or sets generic topography. Moreover,
1587!> all topography-relevant topography arrays are initialized, and grid flags
1588!> are set. 
1589!------------------------------------------------------------------------------!
1590 SUBROUTINE init_topo( topo )
1591
1592    USE arrays_3d,                                                             &
1593        ONLY:  zw
1594       
1595    USE control_parameters,                                                    &
1596        ONLY:  bc_lr_cyc, bc_ns_cyc, building_height, building_length_x,       &
1597               building_length_y, building_wall_left, building_wall_south,     &
1598               canyon_height, canyon_wall_left, canyon_wall_south,             &
1599               canyon_width_x, canyon_width_y, dp_level_ind_b, dz,             &
1600               message_string, topography, topography_grid_convention,         &
1601               tunnel_height, tunnel_length, tunnel_width_x, tunnel_width_y,   &
1602               tunnel_wall_depth
1603         
1604    USE exchange_horiz_mod,                                                    &
1605        ONLY:  exchange_horiz_int
1606
1607    USE grid_variables,                                                        &
1608        ONLY:  dx, dy
1609       
1610    USE indices,                                                               &
1611        ONLY:  nbgp, nx, nxl, nxlg, nxr, nxrg, ny, nyn, nyng, nys, nysg, nz,   &
1612               nzb, nzt
1613   
1614    USE kinds
1615   
1616    USE netcdf_data_input_mod,                                                 &
1617        ONLY:  buildings_f, terrain_height_f 
1618
1619    USE pegrid
1620
1621    IMPLICIT NONE
1622
1623    INTEGER(iwp) ::  bh                !< temporary vertical index of building height
1624    INTEGER(iwp) ::  ngp_bx            !< grid point number of building size along x
1625    INTEGER(iwp) ::  ngp_by            !< grid point number of building size along y
1626    INTEGER(iwp) ::  index_left_bwall  !< index for left building wall
1627    INTEGER(iwp) ::  index_right_bwall !< index for right building wall
1628    INTEGER(iwp) ::  index_north_bwall !< index for north building wall
1629    INTEGER(iwp) ::  index_south_bwall !< index for south building wall
1630    INTEGER(iwp) ::  ch                !< temporary vertical index for canyon height
1631    INTEGER(iwp) ::  ngp_cx            !< grid point number of canyon size along x
1632    INTEGER(iwp) ::  ngp_cy            !< grid point number of canyon size along y
1633    INTEGER(iwp) ::  index_left_cwall  !< index for left canyon wall
1634    INTEGER(iwp) ::  index_right_cwall !< index for right canyon wall
1635    INTEGER(iwp) ::  index_north_cwall !< index for north canyon wall
1636    INTEGER(iwp) ::  index_south_cwall !< index for south canyon wall
1637    INTEGER(iwp) ::  i                 !< index variable along x
1638    INTEGER(iwp) ::  j                 !< index variable along y
1639    INTEGER(iwp) ::  k                 !< index variable along z
1640    INTEGER(iwp) ::  hv_in             !< heavyside function to model inner tunnel surface
1641    INTEGER(iwp) ::  hv_out            !< heavyside function to model outer tunnel surface
1642    INTEGER(iwp) ::  txe_out           !< end position of outer tunnel wall in x
1643    INTEGER(iwp) ::  txs_out           !< start position of outer tunnel wall in x
1644    INTEGER(iwp) ::  tye_out           !< end position of outer tunnel wall in y
1645    INTEGER(iwp) ::  tys_out           !< start position of outer tunnel wall in y
1646    INTEGER(iwp) ::  txe_in            !< end position of inner tunnel wall in x
1647    INTEGER(iwp) ::  txs_in            !< start position of inner tunnel wall in x
1648    INTEGER(iwp) ::  tye_in            !< end position of inner tunnel wall in y
1649    INTEGER(iwp) ::  tys_in            !< start position of inner tunnel wall in y
1650    INTEGER(iwp) ::  td                !< tunnel wall depth
1651    INTEGER(iwp) ::  th                !< height of outer tunnel wall
1652
1653    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  nzb_local         !< index for topography top at cell-center
1654    INTEGER(iwp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg) ::  topo !< input array for 3D topography and dummy array for setting "outer"-flags
1655!
1656!-- Check for correct setting of the namelist parameter topography. If
1657!-- topography information is read from file but topography = 'flat',
1658!-- initialization does not work properly.
1659    IF ( ( buildings_f%from_file  .OR.  terrain_height_f%from_file )  .AND.    &
1660           TRIM( topography ) /= 'read_from_file' )  THEN
1661       message_string =  'If topography information is provided (via ' //      &
1662                         'Netcdf or ASCII input) topography = '        //      &
1663                         '"read_from_file" is required.'
1664       CALL message( 'init_grid', 'PA0437', 1, 2, 0, 6, 0 )     
1665    ENDIF
1666!
1667!-- Set outer and inner index arrays for non-flat topography.
1668!-- Here consistency checks concerning domain size and periodicity are
1669!-- necessary.
1670!-- Within this SELECT CASE structure only nzb_local is initialized
1671!-- individually depending on the chosen topography type, all other index
1672!-- arrays are initialized further below.
1673    SELECT CASE ( TRIM( topography ) )
1674
1675       CASE ( 'flat' )
1676!   
1677!--       Initialilize 3D topography array, used later for initializing flags
1678          topo(nzb+1:nzt+1,:,:) = IBSET( topo(nzb+1:nzt+1,:,:), 0 )
1679         
1680       CASE ( 'closed_channel' )
1681!   
1682!--       Initialilize 3D topography array, used later for initializing flags
1683          topo(nzb+1:nzt,:,:) = IBSET( topo(nzb+1:nzt,:,:), 0 ) 
1684
1685       CASE ( 'single_building' )
1686!
1687!--       Single rectangular building, by default centered in the middle of the
1688!--       total domain
1689          ngp_bx = NINT( building_length_x / dx )
1690          ngp_by = NINT( building_length_y / dy )
1691          bh  = MINLOC( ABS( zw - building_height ), 1 ) - 1
1692          IF ( ABS( zw(bh)   - building_height ) == &
1693               ABS( zw(bh+1) - building_height )    )  bh = bh + 1
1694          IF ( building_wall_left == 9999999.9_wp )  THEN
1695             building_wall_left = ( nx + 1 - ngp_bx ) / 2 * dx
1696          ENDIF
1697          index_left_bwall = NINT( building_wall_left / dx )
1698          index_right_bwall = index_left_bwall + ngp_bx
1699
1700          IF ( building_wall_south == 9999999.9_wp )  THEN
1701              building_wall_south = ( ny + 1 - ngp_by ) / 2 * dy
1702          ENDIF
1703          index_south_bwall = NINT( building_wall_south / dy )
1704          index_north_bwall = index_south_bwall + ngp_by
1705
1706!
1707!--       Building size has to meet some requirements
1708          IF ( ( index_left_bwall < 1 ) .OR. ( index_right_bwall > nx-1 ) .OR. &
1709               ( index_right_bwall < index_left_bwall+3 ) .OR.                 &
1710               ( index_south_bwall < 1 ) .OR. ( index_north_bwall > ny-1 ) .OR.&
1711               ( index_north_bwall < index_south_bwall+3 ) )  THEN
1712             WRITE( message_string, * ) 'inconsistent building parameters:',   &
1713                                      '&index_left_bwall=', index_left_bwall,  &
1714                                      'index_right_bwall=', index_right_bwall, &
1715                                      'index_south_bwall=', index_south_bwall, &
1716                                      'index_north_bwall=', index_north_bwall, &
1717                                      'nx=', nx, 'ny=', ny
1718             CALL message( 'init_grid', 'PA0203', 1, 2, 0, 6, 0 )
1719          ENDIF
1720
1721          ALLOCATE( nzb_local(nysg:nyng,nxlg:nxrg) )
1722          nzb_local = 0
1723!
1724!--       Define the building.
1725          IF ( index_left_bwall <= nxr  .AND.  index_right_bwall >= nxl  .AND. &
1726               index_south_bwall <= nyn  .AND.  index_north_bwall >= nys )     & 
1727             nzb_local(MAX(nys,index_south_bwall):MIN(nyn,index_north_bwall),  &
1728                       MAX(nxl,index_left_bwall):MIN(nxr,index_right_bwall)) = bh
1729!
1730!--       Set bit array on basis of nzb_local
1731          DO  i = nxl, nxr
1732             DO  j = nys, nyn
1733                topo(nzb_local(j,i)+1:nzt+1,j,i) =                             &
1734                                 IBSET( topo(nzb_local(j,i)+1:nzt+1,j,i), 0 ) 
1735             ENDDO
1736          ENDDO
1737       
1738          DEALLOCATE( nzb_local )
1739
1740          CALL exchange_horiz_int( topo, nys, nyn, nxl, nxr, nzt, nbgp )
1741!
1742!--       Set boundary conditions also for flags. Can be interpreted as Neumann
1743!--       boundary conditions for topography.
1744          IF ( .NOT. bc_ns_cyc )  THEN
1745             IF ( nys == 0  )  THEN
1746                DO  i = 1, nbgp     
1747                   topo(:,nys-i,:)   = topo(:,nys,:)
1748                ENDDO
1749             ENDIF
1750             IF ( nyn == ny )  THEN
1751                DO  i = 1, nbgp 
1752                   topo(:,nyn+i,:) = topo(:,nyn,:)
1753                ENDDO
1754             ENDIF
1755          ENDIF
1756          IF ( .NOT. bc_lr_cyc )  THEN
1757             IF ( nxl == 0  )  THEN
1758                DO  i = 1, nbgp   
1759                   topo(:,:,nxl-i)   = topo(:,:,nxl)
1760                ENDDO
1761             ENDIF
1762             IF ( nxr == nx )  THEN
1763                DO  i = 1, nbgp   
1764                   topo(:,:,nxr+i) = topo(:,:,nxr)     
1765                ENDDO
1766             ENDIF     
1767          ENDIF
1768
1769       CASE ( 'single_street_canyon' )
1770!
1771!--       Single quasi-2D street canyon of infinite length in x or y direction.
1772!--       The canyon is centered in the other direction by default.
1773          IF ( canyon_width_x /= 9999999.9_wp )  THEN
1774!
1775!--          Street canyon in y direction
1776             ngp_cx = NINT( canyon_width_x / dx )
1777             IF ( canyon_wall_left == 9999999.9_wp )  THEN
1778                canyon_wall_left = ( nx + 1 - ngp_cx ) / 2 * dx
1779             ENDIF
1780             index_left_cwall= NINT( canyon_wall_left / dx )
1781             index_right_cwall= index_left_cwall+ ngp_cx
1782          ELSEIF ( canyon_width_y /= 9999999.9_wp )  THEN
1783!
1784!--          Street canyon in x direction
1785             ngp_cy = NINT( canyon_width_y / dy )
1786             IF ( canyon_wall_south == 9999999.9_wp )  THEN
1787                canyon_wall_south = ( ny + 1 - ngp_cy ) / 2 * dy
1788             ENDIF
1789             index_south_cwall = NINT( canyon_wall_south / dy )
1790             index_north_cwall = index_south_cwall + ngp_cy
1791     
1792          ELSE
1793             
1794             message_string = 'no street canyon width given'
1795             CALL message( 'init_grid', 'PA0204', 1, 2, 0, 6, 0 )
1796 
1797          ENDIF
1798
1799          ch  = MINLOC( ABS( zw - canyon_height ), 1 ) - 1
1800          IF ( ABS( zw(ch)   - canyon_height ) == &
1801               ABS( zw(ch+1) - canyon_height )    )  ch = ch + 1
1802          dp_level_ind_b = ch
1803!
1804!--       Street canyon size has to meet some requirements
1805          IF ( canyon_width_x /= 9999999.9_wp )  THEN
1806             IF ( ( index_left_cwall< 1 ) .OR. ( index_right_cwall> nx-1 ) .OR.&
1807                  ( ngp_cx < 3 ) .OR. ( ch < 3 ) )  THEN
1808                WRITE( message_string, * ) 'inconsistent canyon parameters:',  &
1809                                           '&index_left_cwall=', index_left_cwall, &
1810                                           ' index_right_cwall=', index_right_cwall, &
1811                                           ' ngp_cx=', ngp_cx,                 &
1812                                           ' ch=', ch, ' nx=', nx, ' ny=', ny
1813                CALL message( 'init_grid', 'PA0205', 1, 2, 0, 6, 0 ) 
1814             ENDIF
1815          ELSEIF ( canyon_width_y /= 9999999.9_wp )  THEN
1816             IF ( ( index_south_cwall < 1 ) .OR.                               &
1817                  ( index_north_cwall > ny-1 ) .OR. ( ngp_cy < 3 ) .OR.        &
1818                  ( ch < 3 ) )  THEN
1819                WRITE( message_string, * ) 'inconsistent canyon parameters:',  &
1820                                           '&index_south_cwall=', index_south_cwall, & 
1821                                           ' index_north_cwall=', index_north_cwall, &
1822                                           ' ngp_cy=', ngp_cy,                 &
1823                                           ' ch=', ch, ' nx=', nx, ' ny=', ny
1824                CALL message( 'init_grid', 'PA0206', 1, 2, 0, 6, 0 ) 
1825             ENDIF
1826          ENDIF
1827          IF ( canyon_width_x /= 9999999.9_wp .AND.                            &                 
1828               canyon_width_y /= 9999999.9_wp )  THEN
1829             message_string = 'inconsistent canyon parameters:' //             &   
1830                              '&street canyon can only be oriented' //         &
1831                              ' either in x- or in y-direction'
1832             CALL message( 'init_grid', 'PA0207', 1, 2, 0, 6, 0 )
1833          ENDIF
1834
1835          ALLOCATE( nzb_local(nysg:nyng,nxlg:nxrg) )
1836          nzb_local = ch
1837          IF ( canyon_width_x /= 9999999.9_wp )  THEN
1838             IF ( index_left_cwall<= nxr  .AND.  index_right_cwall>= nxl )     &
1839                nzb_local(:,MAX(nxl,index_left_cwall+1):MIN(nxr,index_right_cwall-1)) = 0
1840          ELSEIF ( canyon_width_y /= 9999999.9_wp )  THEN
1841             IF ( index_south_cwall <= nyn  .AND.  index_north_cwall >= nys )  &         
1842                nzb_local(MAX(nys,index_south_cwall+1):MIN(nyn,index_north_cwall-1),:) = 0
1843          ENDIF
1844!
1845!--       Set bit array on basis of nzb_local
1846          DO  i = nxl, nxr
1847             DO  j = nys, nyn
1848                topo(nzb_local(j,i)+1:nzt+1,j,i) =                             &
1849                                 IBSET( topo(nzb_local(j,i)+1:nzt+1,j,i), 0 ) 
1850             ENDDO
1851          ENDDO
1852          DEALLOCATE( nzb_local )
1853
1854          CALL exchange_horiz_int( topo, nys, nyn, nxl, nxr, nzt, nbgp )
1855!
1856!--       Set boundary conditions also for flags. Can be interpreted as Neumann
1857!--       boundary conditions for topography.
1858          IF ( .NOT. bc_ns_cyc )  THEN
1859             IF ( nys == 0  )  THEN
1860                DO  i = 1, nbgp     
1861                   topo(:,nys-i,:)   = topo(:,nys,:)
1862                ENDDO
1863             ENDIF
1864             IF ( nyn == ny )  THEN
1865                DO  i = 1, nbgp 
1866                   topo(:,nyn+i,:) = topo(:,nyn,:)
1867                ENDDO
1868             ENDIF
1869          ENDIF
1870          IF ( .NOT. bc_lr_cyc )  THEN
1871             IF ( nxl == 0  )  THEN
1872                DO  i = 1, nbgp   
1873                   topo(:,:,nxl-i)   = topo(:,:,nxl)
1874                ENDDO
1875             ENDIF
1876             IF ( nxr == nx )  THEN
1877                DO  i = 1, nbgp   
1878                   topo(:,:,nxr+i) = topo(:,:,nxr)     
1879                ENDDO
1880             ENDIF     
1881          ENDIF
1882
1883       CASE ( 'tunnel' )
1884
1885!
1886!--       Tunnel height
1887          IF ( tunnel_height == 9999999.9_wp )  THEN
1888             th = zw( INT( 0.2 * nz) )
1889          ELSE
1890             th = tunnel_height
1891          ENDIF
1892!
1893!--       Tunnel-wall depth
1894          IF ( tunnel_wall_depth == 9999999.9_wp )  THEN 
1895             td = MAX ( dx, dy, dz(1) )
1896          ELSE
1897             td = tunnel_wall_depth
1898          ENDIF
1899!
1900!--       Check for tunnel width
1901          IF ( tunnel_width_x == 9999999.9_wp  .AND.                           &
1902               tunnel_width_y == 9999999.9_wp  )  THEN
1903             message_string = 'No tunnel width is given. '
1904             CALL message( 'init_grid', 'PA0280', 1, 2, 0, 6, 0 )
1905          ENDIF
1906          IF ( tunnel_width_x /= 9999999.9_wp  .AND.                           &
1907               tunnel_width_y /= 9999999.9_wp  )  THEN
1908             message_string = 'Inconsistent tunnel parameters:' //             &   
1909                              'tunnel can only be oriented' //                 &
1910                              'either in x- or in y-direction.'
1911             CALL message( 'init_grid', 'PA0281', 1, 2, 0, 6, 0 )
1912          ENDIF
1913!
1914!--       Check for too small tunnel width in x- and y-direction
1915          IF ( tunnel_width_x /= 9999999.9_wp  .AND.                           &   
1916               tunnel_width_x - 2.0_wp * td <= 2.0_wp * dx )  THEN
1917             message_string = 'tunnel_width_x too small'
1918             CALL message( 'init_grid', 'PA0175', 1, 2, 0, 6, 0 )
1919          ENDIF
1920          IF ( tunnel_width_y /= 9999999.9_wp  .AND.                           &
1921               tunnel_width_y - 2.0_wp * td <= 2.0_wp * dy )  THEN
1922             message_string = 'tunnel_width_y too small'
1923             CALL message( 'init_grid', 'PA0455', 1, 2, 0, 6, 0 )
1924          ENDIF
1925!
1926!--       Check for too large tunnel width.
1927!--       Tunnel axis along y.
1928          IF ( tunnel_width_x /= 9999999.9_wp )  THEN
1929             IF ( tunnel_width_x > ( nx + 1 ) * dx )  THEN
1930                message_string = 'tunnel_width_x too large'
1931                CALL message( 'init_grid', 'PA0282', 1, 2, 0, 6, 0 )
1932             ENDIF
1933
1934             txs_out = INT( ( nx + 1 ) * 0.5_wp * dx - tunnel_width_x * 0.5_wp )
1935             txe_out = INT( ( nx + 1 ) * 0.5_wp * dx + tunnel_width_x * 0.5_wp )
1936             txs_in  = INT( ( nx + 1 ) * 0.5_wp * dx -                         &
1937                                      ( tunnel_width_x * 0.5_wp - td ) )
1938             txe_in  = INT( ( nx + 1 ) * 0.5_wp * dx +                         &
1939                                   ( tunnel_width_x * 0.5_wp - td ) )
1940
1941             tys_out = INT( ( ny + 1 ) * 0.5_wp * dy - tunnel_length * 0.5_wp )
1942             tye_out = INT( ( ny + 1 ) * 0.5_wp * dy + tunnel_length * 0.5_wp )
1943             tys_in  = tys_out
1944             tye_in  = tye_out
1945          ENDIF
1946!
1947!--       Tunnel axis along x.
1948          IF ( tunnel_width_y /= 9999999.9_wp )  THEN
1949             IF ( tunnel_width_y > ( ny + 1 ) * dy )  THEN
1950                message_string = 'tunnel_width_y too large'
1951                CALL message( 'init_grid', 'PA0456', 1, 2, 0, 6, 0 )
1952             ENDIF
1953
1954             txs_out = INT( ( nx + 1 ) * 0.5_wp * dx - tunnel_length * 0.5_wp )
1955             txe_out = INT( ( nx + 1 ) * 0.5_wp * dx + tunnel_length * 0.5_wp )
1956             txs_in  = txs_out
1957             txe_in  = txe_out
1958
1959             tys_out = INT( ( ny + 1 ) * 0.5_wp * dy - tunnel_width_y * 0.5_wp )
1960             tye_out = INT( ( ny + 1 ) * 0.5_wp * dy + tunnel_width_y * 0.5_wp )
1961             tys_in  = INT( ( ny + 1 ) * 0.5_wp * dy -                         &
1962                                        ( tunnel_width_y * 0.5_wp - td ) )
1963             tye_in  = INT( ( ny + 1 ) * 0.5_wp * dy +                         &
1964                                     ( tunnel_width_y * 0.5_wp - td ) )
1965          ENDIF
1966
1967          topo = 0
1968          DO  i = nxl, nxr
1969             DO  j = nys, nyn
1970!
1971!--             Use heaviside function to model outer tunnel surface
1972                hv_out = th * 0.5_wp *                                         &
1973                              ( ( SIGN( 1.0_wp, i * dx - txs_out ) + 1.0_wp )  &
1974                              - ( SIGN( 1.0_wp, i * dx - txe_out ) + 1.0_wp ) )
1975
1976                hv_out = hv_out * 0.5_wp *                                     &
1977                            ( ( SIGN( 1.0_wp, j * dy - tys_out ) + 1.0_wp )    &
1978                            - ( SIGN( 1.0_wp, j * dy - tye_out ) + 1.0_wp ) )
1979!   
1980!--             Use heaviside function to model inner tunnel surface
1981                hv_in  = ( th - td ) * 0.5_wp *                                &
1982                                ( ( SIGN( 1.0_wp, i * dx - txs_in ) + 1.0_wp ) &
1983                                - ( SIGN( 1.0_wp, i * dx - txe_in ) + 1.0_wp ) )
1984
1985                hv_in = hv_in * 0.5_wp *                                       &
1986                                ( ( SIGN( 1.0_wp, j * dy - tys_in ) + 1.0_wp ) &
1987                                - ( SIGN( 1.0_wp, j * dy - tye_in ) + 1.0_wp ) )
1988!
1989!--             Set flags at x-y-positions without any tunnel surface
1990                IF ( hv_out - hv_in == 0.0_wp )  THEN
1991                   topo(nzb+1:nzt+1,j,i) = IBSET( topo(nzb+1:nzt+1,j,i), 0 )
1992!
1993!--             Set flags at x-y-positions with tunnel surfaces
1994                ELSE
1995                   DO  k = nzb + 1, nzt + 1
1996!
1997!--                   Inner tunnel
1998                      IF ( hv_out - hv_in == th )  THEN
1999                         IF ( zw(k) <= hv_out )  THEN
2000                            topo(k,j,i) = IBCLR( topo(k,j,i), 0 )
2001                         ELSE
2002                            topo(k,j,i) = IBSET( topo(k,j,i), 0 )
2003                         ENDIF
2004                      ENDIF
2005!
2006!--                   Lateral tunnel walls
2007                      IF ( hv_out - hv_in == td )  THEN
2008                         IF ( zw(k) <= hv_in )  THEN
2009                            topo(k,j,i) = IBSET( topo(k,j,i), 0 )
2010                         ELSEIF ( zw(k) > hv_in  .AND.  zw(k) <= hv_out )  THEN
2011                            topo(k,j,i) = IBCLR( topo(k,j,i), 0 )
2012                         ELSEIF ( zw(k) > hv_out )  THEN
2013                            topo(k,j,i) = IBSET( topo(k,j,i), 0 )
2014                         ENDIF
2015                      ENDIF
2016                   ENDDO
2017                ENDIF
2018             ENDDO
2019          ENDDO
2020
2021          CALL exchange_horiz_int( topo, nys, nyn, nxl, nxr, nzt, nbgp )
2022!
2023!--       Set boundary conditions also for flags. Can be interpreted as Neumann
2024!--       boundary conditions for topography.
2025          IF ( .NOT. bc_ns_cyc )  THEN
2026             IF ( nys == 0  )  THEN
2027                DO  i = 1, nbgp     
2028                   topo(:,nys-i,:)   = topo(:,nys,:)
2029                ENDDO
2030             ENDIF
2031             IF ( nyn == ny )  THEN
2032                DO  i = 1, nbgp 
2033                   topo(:,nyn+i,:) = topo(:,nyn,:)
2034                ENDDO
2035             ENDIF
2036          ENDIF
2037          IF ( .NOT. bc_lr_cyc )  THEN
2038             IF ( nxl == 0  )  THEN
2039                DO  i = 1, nbgp   
2040                   topo(:,:,nxl-i)   = topo(:,:,nxl)
2041                ENDDO
2042             ENDIF
2043             IF ( nxr == nx )  THEN
2044                DO  i = 1, nbgp   
2045                   topo(:,:,nxr+i) = topo(:,:,nxr)     
2046                ENDDO
2047             ENDIF     
2048          ENDIF
2049
2050       CASE ( 'read_from_file' )
2051!
2052!--       Note, topography information have been already read. 
2053!--       If required, further process topography, i.e. reference buildings on
2054!--       top of orography and set temporary 3D topography array, which is
2055!--       used later to set grid flags. Calling of this rouinte is also
2056!--       required in case of ASCII input, even though no distinction between
2057!--       terrain- and building height is made in this case. 
2058          CALL process_topography( topo )
2059!
2060!--       Filter holes resolved by only one grid-point
2061          CALL filter_topography( topo )
2062!
2063!--       Exchange ghost-points, as well as add cyclic or Neumann boundary
2064!--       conditions.
2065          CALL exchange_horiz_int( topo, nys, nyn, nxl, nxr, nzt, nbgp )
2066!
2067!--       Set lateral boundary conditions for topography on all ghost layers
2068          IF ( .NOT. bc_ns_cyc )  THEN
2069             IF ( nys == 0  )  THEN
2070                DO  i = 1, nbgp         
2071                   topo(:,nys-i,:) = topo(:,nys,:)
2072                ENDDO
2073             ENDIF
2074             IF ( nyn == ny )  THEN
2075                DO  i = 1, nbgp         
2076                   topo(:,nyn+i,:) = topo(:,nyn,:)
2077                ENDDO
2078             ENDIF
2079          ENDIF
2080
2081          IF ( .NOT. bc_lr_cyc )  THEN
2082             IF ( nxl == 0  )  THEN
2083                DO  i = 1, nbgp 
2084                   topo(:,:,nxl-i) = topo(:,:,nxl)
2085                ENDDO
2086             ENDIF
2087             IF ( nxr == nx )  THEN
2088                DO  i = 1, nbgp 
2089                   topo(:,:,nxr+i) = topo(:,:,nxr)
2090                ENDDO
2091             ENDIF
2092          ENDIF
2093
2094
2095       CASE DEFAULT
2096!   
2097!--       The DEFAULT case is reached either if the parameter topography
2098!--       contains a wrong character string or if the user has defined a special
2099!--       case in the user interface. There, the subroutine user_init_grid
2100!--       checks which of these two conditions applies.
2101          CALL user_init_grid( topo )
2102          CALL filter_topography( topo )
2103
2104    END SELECT
2105!
2106!-- Consistency checks and index array initialization are only required for
2107!-- non-flat topography.
2108    IF ( TRIM( topography ) /= 'flat' )  THEN
2109!
2110!--    In case of non-flat topography, check whether the convention how to
2111!--    define the topography grid has been set correctly, or whether the default
2112!--    is applicable. If this is not possible, abort.
2113       IF ( TRIM( topography_grid_convention ) == ' ' )  THEN
2114          IF ( TRIM( topography ) /= 'closed_channel' .AND.                    &
2115               TRIM( topography ) /= 'single_building' .AND.                   &
2116               TRIM( topography ) /= 'single_street_canyon' .AND.              &
2117               TRIM( topography ) /= 'tunnel'  .AND.                           &
2118               TRIM( topography ) /= 'read_from_file')  THEN
2119!--          The default value is not applicable here, because it is only valid
2120!--          for the four standard cases 'single_building',
2121!--          'single_street_canyon', 'tunnel' and 'read_from_file'
2122!--          defined in init_grid.
2123             WRITE( message_string, * )                                        &
2124               'The value for "topography_grid_convention" ',                  &
2125               'is not set. Its default value is & only valid for ',           &
2126               '"topography" = ''single_building'', ''tunnel'' ',              &
2127               '''single_street_canyon'', ''closed_channel'' & or ',           &
2128               '''read_from_file''.',                                          &
2129               '& Choose ''cell_edge'' or ''cell_center''.'
2130             CALL message( 'init_grid', 'PA0239', 1, 2, 0, 6, 0 )
2131          ELSE
2132!--          The default value is applicable here.
2133!--          Set convention according to topography.
2134             IF ( TRIM( topography ) == 'single_building' .OR.                 &
2135                  TRIM( topography ) == 'single_street_canyon' )  THEN
2136                topography_grid_convention = 'cell_edge'
2137             ELSEIF ( TRIM( topography ) == 'read_from_file'  .OR.             &
2138                      TRIM( topography ) == 'tunnel')  THEN
2139                topography_grid_convention = 'cell_center'
2140             ENDIF
2141          ENDIF
2142       ELSEIF ( TRIM( topography_grid_convention ) /= 'cell_edge' .AND.        &
2143                TRIM( topography_grid_convention ) /= 'cell_center' )  THEN
2144          WRITE( message_string, * )                                           &
2145            'The value for "topography_grid_convention" is ',                  &
2146            'not recognized.& Choose ''cell_edge'' or ''cell_center''.'
2147          CALL message( 'init_grid', 'PA0240', 1, 2, 0, 6, 0 )
2148       ENDIF
2149
2150
2151       IF ( topography_grid_convention == 'cell_edge' )  THEN
2152!
2153!--       The array nzb_local as defined using the 'cell_edge' convention
2154!--       describes the actual total size of topography which is defined at the
2155!--       cell edges where u=0 on the topography walls in x-direction and v=0
2156!--       on the topography walls in y-direction. However, PALM uses individual
2157!--       arrays nzb_u|v|w|s_inner|outer that are based on nzb_s_inner.
2158!--       Therefore, the extent of topography in nzb_local is now reduced by
2159!--       1dx at the E topography walls and by 1dy at the N topography walls
2160!--       to form the basis for nzb_s_inner.
2161!--       Note, the reverse memory access (i-j instead of j-i) is absolutely
2162!--       required at this point.
2163          DO  j = nys+1, nyn+1
2164             DO  i = nxl-1, nxr
2165                DO  k = nzb, nzt+1
2166                   IF ( BTEST( topo(k,j,i), 0 )  .OR.                          &
2167                        BTEST( topo(k,j,i+1), 0 ) )                            &
2168                       topo(k,j,i) = IBSET( topo(k,j,i), 0 )
2169                ENDDO
2170             ENDDO
2171          ENDDO     
2172          CALL exchange_horiz_int( topo, nys, nyn, nxl, nxr, nzt, nbgp )
2173
2174          DO  i = nxl, nxr+1
2175             DO  j = nys-1, nyn
2176                DO  k = nzb, nzt+1
2177                   IF ( BTEST( topo(k,j,i), 0 )  .OR.                          &
2178                        BTEST( topo(k,j+1,i), 0 ) )                            &
2179                      topo(k,j,i) = IBSET( topo(k,j,i), 0 )
2180                ENDDO
2181             ENDDO
2182          ENDDO 
2183          CALL exchange_horiz_int( topo, nys, nyn, nxl, nxr, nzt, nbgp )
2184   
2185       ENDIF
2186    ENDIF
2187
2188
2189 END SUBROUTINE init_topo
2190
2191 SUBROUTINE set_topo_flags(topo)
2192
2193    USE control_parameters,                                                    &
2194        ONLY:  bc_lr_cyc, bc_ns_cyc, constant_flux_layer,                      &
2195               scalar_advec, topography, use_surface_fluxes, use_top_fluxes
2196
2197    USE exchange_horiz_mod,                                                    &
2198        ONLY:  exchange_horiz_int
2199
2200    USE indices,                                                               &
2201        ONLY:  nbgp, nx, nxl, nxlg, nxr, nxrg, ny, nyn, nyng, nys, nysg, nzb,  &
2202               nzt, topo_top_ind, wall_flags_static_0, wall_flags_total_0
2203
2204    USE kinds
2205
2206    IMPLICIT NONE
2207
2208    INTEGER(iwp) ::  i             !< index variable along x
2209    INTEGER(iwp) ::  ibit          !< integer bit position of topgraphy masking array
2210    INTEGER(iwp) ::  j             !< index variable along y
2211    INTEGER(iwp) ::  k             !< index variable along z
2212
2213    INTEGER(iwp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg) ::  topo !< input array for 3D topography and dummy array for setting "outer"-flags
2214
2215    ALLOCATE( wall_flags_static_0(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
2216    wall_flags_static_0 = 0
2217!
2218!-- Set-up topography flags. First, set flags only for s, u, v and w-grid.
2219!-- Further special flags will be set in following loops.
2220    DO  i = nxl, nxr
2221       DO  j = nys, nyn
2222          DO  k = nzb, nzt+1
2223!
2224!--          scalar grid
2225             IF ( BTEST( topo(k,j,i), 0 ) )                                    &
2226                wall_flags_static_0(k,j,i) = IBSET( wall_flags_static_0(k,j,i), 0 )
2227!
2228!--          u grid
2229             IF ( BTEST( topo(k,j,i),   0 )  .AND.                             &
2230                  BTEST( topo(k,j,i-1), 0 ) )                                  &
2231                wall_flags_static_0(k,j,i) = IBSET( wall_flags_static_0(k,j,i), 1 )
2232!
2233!--          v grid
2234             IF ( BTEST( topo(k,j,i),   0 )  .AND.                             &
2235                  BTEST( topo(k,j-1,i), 0 ) )                                  &
2236                 wall_flags_static_0(k,j,i) = IBSET( wall_flags_static_0(k,j,i), 2 )
2237
2238          ENDDO
2239
2240          DO k = nzb, nzt
2241!
2242!--          w grid
2243             IF ( BTEST( topo(k,j,i),   0 )  .AND.                             &
2244                  BTEST( topo(k+1,j,i), 0 ) )                                  &
2245                wall_flags_static_0(k,j,i) = IBSET( wall_flags_static_0(k,j,i), 3 )
2246          ENDDO
2247         
2248          IF ( topography /= 'closed_channel' ) THEN
2249             wall_flags_static_0(nzt+1,j,i) = IBSET( wall_flags_static_0(nzt+1,j,i), 3 )
2250          ENDIF
2251
2252       ENDDO
2253    ENDDO
2254
2255    CALL exchange_horiz_int( wall_flags_static_0, nys, nyn, nxl, nxr, nzt, nbgp )
2256
2257!
2258!-- Set outer array for scalars to mask near-surface grid points. Note, on
2259!-- basis of flag 24 futher flags will be derived which are used to control
2260!-- production of subgrid TKE production near walls.
2261   
2262    ALLOCATE( wall_flags_total_0(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
2263    wall_flags_total_0 = 0
2264                                   
2265    DO i = nxl, nxr
2266       DO j = nys, nyn
2267          DO k = nzb, nzt+1
2268             wall_flags_total_0(k,j,i) = IOR( wall_flags_total_0(k,j,i), wall_flags_static_0(k,j,i) )
2269          ENDDO
2270       ENDDO
2271    ENDDO
2272   
2273    CALL exchange_horiz_int( wall_flags_total_0, nys, nyn, nxl, nxr, nzt, nbgp )
2274   
2275    DO i = nxl, nxr
2276       DO j = nys, nyn
2277          DO k = nzb, nzt+1
2278             IF ( BTEST( wall_flags_total_0(k,j-1,i), 0 )    .AND.                   &
2279                  BTEST( wall_flags_total_0(k,j+1,i), 0 )    .AND.                   &
2280                  BTEST( wall_flags_total_0(k,j,i-1), 0 )    .AND.                   &
2281                  BTEST( wall_flags_total_0(k,j,i+1), 0 )    .AND.                   &
2282                  BTEST( wall_flags_total_0(k,j-1,i-1), 0 )  .AND.                   &
2283                  BTEST( wall_flags_total_0(k,j+1,i-1), 0 )  .AND.                   &
2284                  BTEST( wall_flags_total_0(k,j-1,i+1), 0 )  .AND.                   &
2285                  BTEST( wall_flags_total_0(k,j+1,i+1), 0 ) )                        &
2286                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 24 )
2287          ENDDO
2288       ENDDO
2289    ENDDO
2290!
2291!-- Set further special flags
2292    DO i = nxl, nxr
2293       DO j = nys, nyn
2294          DO k = nzb, nzt+1
2295!
2296!--          scalar grid, former nzb_diff_s_inner.
2297!--          Note, use this flag also to mask topography in diffusion_u and
2298!--          diffusion_v along the vertical direction. In case of
2299!--          use_surface_fluxes, fluxes are calculated via MOST, else, simple
2300!--          gradient approach is applied. Please note, in case of u- and v-
2301!--          diffuison, a small error is made at edges (on the east side for u,
2302!--          at the north side for v), since topography on scalar grid point
2303!--          is used instead of topography on u/v-grid. As number of topography grid
2304!--          points on uv-grid is different than s-grid, different number of
2305!--          surface elements would be required. In order to avoid this,
2306!--          treat edges (u(k,j,i+1)) simply by a gradient approach, i.e. these
2307!--          points are not masked within diffusion_u. Tests had shown that the
2308!--          effect on the flow is negligible.
2309             IF ( constant_flux_layer  .OR.  use_surface_fluxes )  THEN
2310                IF ( BTEST( wall_flags_total_0(k,j,i), 0 ) )                         &
2311                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 8 )
2312             ELSE
2313                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 8 )
2314             ENDIF
2315
2316          ENDDO
2317!
2318!--       Special flag to control vertical diffusion at model top - former
2319!--       nzt_diff
2320          wall_flags_total_0(:,j,i) = IBSET( wall_flags_total_0(:,j,i), 9 )
2321          IF ( use_top_fluxes )                                                &
2322             wall_flags_total_0(nzt+1,j,i) = IBCLR( wall_flags_total_0(nzt+1,j,i), 9 )
2323
2324
2325          DO k = nzb+1, nzt
2326!
2327!--          Special flag on u grid, former nzb_u_inner + 1, required   
2328!--          for disturb_field and initialization. Do not disturb directly at
2329!--          topography, as well as initialize u with zero one grid point outside
2330!--          of topography.
2331             IF ( BTEST( wall_flags_total_0(k-1,j,i), 1 )  .AND.                     &
2332                  BTEST( wall_flags_total_0(k,j,i),   1 )  .AND.                     &
2333                  BTEST( wall_flags_total_0(k+1,j,i), 1 ) )                          &
2334                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 20 )
2335!
2336!--          Special flag on v grid, former nzb_v_inner + 1, required   
2337!--          for disturb_field and initialization. Do not disturb directly at
2338!--          topography, as well as initialize v with zero one grid point outside
2339!--          of topography.
2340             IF ( BTEST( wall_flags_total_0(k-1,j,i), 2 )  .AND.                     &
2341                  BTEST( wall_flags_total_0(k,j,i),   2 )  .AND.                     &
2342                  BTEST( wall_flags_total_0(k+1,j,i), 2 ) )                          &
2343                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 21 )
2344!
2345!--          Special flag on scalar grid, former nzb_s_inner+1. Used for
2346!--          lpm_sgs_tke
2347             IF ( BTEST( wall_flags_total_0(k,j,i),   0 )  .AND.                     &
2348                  BTEST( wall_flags_total_0(k-1,j,i), 0 )  .AND.                     &
2349                  BTEST( wall_flags_total_0(k+1,j,i), 0 ) )                          &
2350                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 25 )
2351!
2352!--          Special flag on scalar grid, nzb_diff_s_outer - 1, required in
2353!--          in production_e
2354             IF ( constant_flux_layer  .OR.  use_surface_fluxes )  THEN
2355                IF ( BTEST( wall_flags_total_0(k,j,i),   24 )  .AND.                 &
2356                     BTEST( wall_flags_total_0(k-1,j,i), 24 )  .AND.                 &
2357                     BTEST( wall_flags_total_0(k+1,j,i), 0 ) )                       &
2358                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 29 )
2359             ELSE
2360                IF ( BTEST( wall_flags_total_0(k,j,i), 0 ) )                         &
2361                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 29 )
2362             ENDIF
2363!
2364!--          Special flag on scalar grid, nzb_diff_s_outer - 1, required in
2365!--          in production_e
2366             IF ( constant_flux_layer  .OR.  use_surface_fluxes )  THEN
2367                IF ( BTEST( wall_flags_total_0(k,j,i),   0 )  .AND.                  &
2368                     BTEST( wall_flags_total_0(k-1,j,i), 0 )  .AND.                  &
2369                     BTEST( wall_flags_total_0(k+1,j,i), 0 ) )                       &
2370                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 30 )
2371             ELSE
2372                IF ( BTEST( wall_flags_total_0(k,j,i), 0 ) )                         &
2373                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 30 )
2374             ENDIF
2375          ENDDO
2376!
2377!--       Flags indicating downward facing walls
2378          DO k = nzb+1, nzt+1
2379!
2380!--          Scalar grid
2381             IF ( BTEST( wall_flags_total_0(k-1,j,i), 0 )  .AND.                     &
2382            .NOT. BTEST( wall_flags_total_0(k,j,i), 0   ) )                          & 
2383                 wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 13 ) 
2384!
2385!--          Downward facing wall on u grid
2386             IF ( BTEST( wall_flags_total_0(k-1,j,i), 1 )  .AND.                     &
2387            .NOT. BTEST( wall_flags_total_0(k,j,i), 1   ) )                          & 
2388                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 15 )
2389!
2390!--          Downward facing wall on v grid
2391             IF ( BTEST( wall_flags_total_0(k-1,j,i), 2 )  .AND.                     &
2392            .NOT. BTEST( wall_flags_total_0(k,j,i), 2   ) )                          & 
2393                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 17 )
2394!
2395!--          Downward facing wall on w grid
2396             IF ( BTEST( wall_flags_total_0(k-1,j,i), 3 )  .AND.                     &
2397            .NOT. BTEST( wall_flags_total_0(k,j,i), 3 ) )                            & 
2398                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 19 )
2399          ENDDO
2400!
2401!--       Flags indicating upward facing walls
2402          DO k = nzb, nzt
2403!
2404!--          Upward facing wall on scalar grid
2405             IF ( .NOT. BTEST( wall_flags_total_0(k,j,i),   0 )  .AND.               &
2406                        BTEST( wall_flags_total_0(k+1,j,i), 0 ) )                    & 
2407                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 12 )
2408!
2409!--          Upward facing wall on u grid
2410             IF ( .NOT. BTEST( wall_flags_total_0(k,j,i),   1 )  .AND.               &
2411                        BTEST( wall_flags_total_0(k+1,j,i), 1 ) )                    & 
2412                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 14 )
2413
2414!   
2415!--          Upward facing wall on v grid
2416             IF ( .NOT. BTEST( wall_flags_total_0(k,j,i),   2 )  .AND.               &
2417                        BTEST( wall_flags_total_0(k+1,j,i), 2 ) )                    & 
2418                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 16 )
2419   
2420!
2421!--          Upward facing wall on w grid
2422             IF ( .NOT. BTEST( wall_flags_total_0(k,j,i),   3 )  .AND.               &
2423                        BTEST( wall_flags_total_0(k+1,j,i), 3 ) )                    & 
2424                wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 18 )
2425!
2426!--          Special flag on scalar grid, former nzb_s_inner
2427             IF ( BTEST( wall_flags_total_0(k,j,i), 0 )  .OR.                        &
2428                  BTEST( wall_flags_total_0(k,j,i), 12 ) .OR.                        &
2429                  BTEST( wall_flags_total_0(k,j,i), 13 ) )                           &
2430                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 22 )
2431!
2432!--          Special flag on scalar grid, nzb_diff_s_inner - 1, required for
2433!--          flow_statistics
2434             IF ( constant_flux_layer  .OR.  use_surface_fluxes )  THEN
2435                IF ( BTEST( wall_flags_total_0(k,j,i),   0 )  .AND.                  &
2436                     BTEST( wall_flags_total_0(k+1,j,i), 0 ) )                       &
2437                  wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 23 )
2438             ELSE
2439                IF ( BTEST( wall_flags_total_0(k,j,i), 22 ) )                        &
2440                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 23 )
2441             ENDIF
2442   
2443
2444          ENDDO
2445          wall_flags_total_0(nzt+1,j,i) = IBSET( wall_flags_total_0(nzt+1,j,i), 22 )
2446          wall_flags_total_0(nzt+1,j,i) = IBSET( wall_flags_total_0(nzt+1,j,i), 23 )
2447!
2448!--       Set flags indicating that topography is close by in horizontal
2449!--       direction, i.e. flags that infold the topography. These will be used
2450!--       to set advection flags for passive scalars, where due to large
2451!--       gradients near buildings stationary numerical oscillations can produce
2452!--       unrealistically high concentrations. This is only necessary if
2453!--       WS-scheme is applied for scalar advection. Note, these flags will be
2454!--       only used for passive scalars such as chemical species or aerosols.
2455          IF ( scalar_advec == 'ws-scheme' )  THEN
2456             DO k = nzb, nzt
2457                IF ( BTEST( wall_flags_total_0(k,j,i), 0 )  .AND. (                  &
2458                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-3:j+3,i-1), 0 ) )  .OR.&
2459                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-3:j+3,i-2), 0 ) )  .OR.&
2460                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-3:j+3,i-3), 0 ) )  .OR.&
2461                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-3:j+3,i+1), 0 ) )  .OR.&
2462                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-3:j+3,i+2), 0 ) )  .OR.&
2463                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-3:j+3,i+3), 0 ) )  .OR.&
2464                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-1,i-3:i+3), 0 ) )  .OR.&
2465                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-2,i-3:i+3), 0 ) )  .OR.&
2466                     ANY( .NOT. BTEST( wall_flags_total_0(k,j-3,i-3:i+3), 0 ) )  .OR.&
2467                     ANY( .NOT. BTEST( wall_flags_total_0(k,j+1,i-3:i+3), 0 ) )  .OR.&
2468                     ANY( .NOT. BTEST( wall_flags_total_0(k,j+2,i-3:i+3), 0 ) )  .OR.&
2469                     ANY( .NOT. BTEST( wall_flags_total_0(k,j+3,i-3:i+3), 0 ) )      &
2470                                                            ) )                      &
2471                   wall_flags_total_0(k,j,i) = IBSET( wall_flags_total_0(k,j,i), 31 )
2472                     
2473             ENDDO
2474          ENDIF
2475       ENDDO
2476    ENDDO
2477!
2478!-- Finally, set identification flags indicating natural terrain or buildings.
2479!-- Natural terrain grid points. Information on the type of the surface is
2480!-- stored in bit 1 of 3D Integer array topo. However, this bit is only set
2481!-- when topography is read from file. In order to run the land-surface model
2482!-- also without topography information, set bit 1 explicitely in this case.
2483!--
2484!-- Natural terrain grid points
2485!-- If no topography is initialized, the land-surface is at k = nzb.
2486    IF ( TRIM( topography ) /= 'read_from_file' )  THEN
2487       wall_flags_static_0(nzb,:,:) = IBSET( wall_flags_static_0(nzb,:,:), 5 )
2488    ELSE
2489       DO i = nxl, nxr
2490          DO j = nys, nyn
2491             DO k = nzb, nzt+1
2492!         
2493!--             Natural terrain grid point
2494                IF ( BTEST( topo(k,j,i), 1 ) )                                 &
2495                   wall_flags_static_0(k,j,i) = IBSET( wall_flags_static_0(k,j,i), 5 )
2496             ENDDO
2497          ENDDO
2498       ENDDO
2499    ENDIF
2500!
2501!-- Building grid points.
2502    DO i = nxl, nxr
2503       DO j = nys, nyn
2504          DO k = nzb, nzt+1
2505             IF ( BTEST( topo(k,j,i), 2 ) )                                    &
2506                wall_flags_static_0(k,j,i) = IBSET( wall_flags_static_0(k,j,i), 6 )
2507          ENDDO
2508       ENDDO
2509    ENDDO
2510!
2511!-- Set flag 4, indicating new topography grid points due to filtering.
2512    DO i = nxl, nxr
2513       DO j = nys, nyn
2514          DO k = nzb, nzt+1
2515             IF ( BTEST( topo(k,j,i), 4 ) )                                    &
2516                wall_flags_static_0(k,j,i) = IBSET( wall_flags_static_0(k,j,i), 4 )
2517          ENDDO
2518       ENDDO
2519    ENDDO
2520   
2521    CALL exchange_horiz_int( wall_flags_static_0, nys, nyn, nxl, nxr, nzt, nbgp )
2522   
2523    DO i = nxl, nxr
2524       DO j = nys, nyn
2525          DO k = nzb, nzt+1
2526             wall_flags_total_0(k,j,i) = IOR( wall_flags_total_0(k,j,i), wall_flags_static_0(k,j,i) )
2527          ENDDO
2528       ENDDO
2529    ENDDO
2530!
2531!-- Exchange ghost points for wall flags
2532    CALL exchange_horiz_int( wall_flags_total_0, nys, nyn, nxl, nxr, nzt, nbgp )
2533!
2534!-- Set boundary conditions also for flags. Can be interpreted as Neumann
2535!-- boundary conditions for topography.
2536    IF ( .NOT. bc_ns_cyc )  THEN
2537       IF ( nys == 0  )  THEN
2538          DO  i = 1, nbgp     
2539             wall_flags_total_0(:,nys-i,:)   = wall_flags_total_0(:,nys,:)
2540          ENDDO
2541       ENDIF
2542       IF ( nyn == ny )  THEN
2543          DO  i = 1, nbgp 
2544             wall_flags_total_0(:,nyn+i,:) = wall_flags_total_0(:,nyn,:)
2545          ENDDO
2546       ENDIF
2547    ENDIF
2548    IF ( .NOT. bc_lr_cyc )  THEN
2549       IF ( nxl == 0  )  THEN
2550          DO  i = 1, nbgp   
2551             wall_flags_total_0(:,:,nxl-i)   = wall_flags_total_0(:,:,nxl)
2552          ENDDO
2553       ENDIF
2554       IF ( nxr == nx )  THEN
2555          DO  i = 1, nbgp   
2556             wall_flags_total_0(:,:,nxr+i) = wall_flags_total_0(:,:,nxr)     
2557          ENDDO
2558       ENDIF     
2559    ENDIF
2560!
2561!-- Pre-calculate topography top indices (former get_topography_top_index
2562!-- function)
2563    ALLOCATE( topo_top_ind(nysg:nyng,nxlg:nxrg,0:4) )
2564!
2565!-- Uppermost topography index on scalar grid
2566    ibit = 12
2567    topo_top_ind(:,:,0) = MAXLOC(                                              &
2568                                  MERGE( 1, 0,                                 &
2569                                    BTEST( wall_flags_total_0(:,:,:), ibit )   &
2570                                       ), DIM = 1                              &
2571                                ) - 1 
2572!
2573!-- Uppermost topography index on u grid
2574    ibit = 14
2575    topo_top_ind(:,:,1) = MAXLOC(                                              &
2576                                  MERGE( 1, 0,                                 &
2577                                    BTEST( wall_flags_total_0(:,:,:), ibit )   &
2578                                       ), DIM = 1                              &
2579                                ) - 1 
2580!
2581!-- Uppermost topography index on v grid
2582    ibit = 16
2583    topo_top_ind(:,:,2) = MAXLOC(                                              &
2584                                  MERGE( 1, 0,                                 &
2585                                    BTEST( wall_flags_total_0(:,:,:), ibit )   &
2586                                       ), DIM = 1                              &
2587                                ) - 1 
2588!
2589!-- Uppermost topography index on w grid
2590    ibit = 18
2591    topo_top_ind(:,:,3) = MAXLOC(                                              &
2592                                  MERGE( 1, 0,                                 &
2593                                    BTEST( wall_flags_total_0(:,:,:), ibit )   &
2594                                       ), DIM = 1                              &
2595                                ) - 1 
2596!
2597!-- Uppermost topography index on scalar outer grid
2598    ibit = 24
2599    topo_top_ind(:,:,4) = MAXLOC(                                              &
2600                                  MERGE( 1, 0,                                 &
2601                                    BTEST( wall_flags_total_0(:,:,:), ibit )   &
2602                                       ), DIM = 1                              &
2603                                ) - 1
2604
2605 END SUBROUTINE set_topo_flags
2606
2607
2608
2609
Note: See TracBrowser for help on using the repository browser.