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

Last change on this file since 4507 was 4507, checked in by gronemeier, 4 years ago

netcdf_data_input_mod:

  • bugfix: check terrain height for fill values directly after reading (PA0550)
  • changes:
    • remove check for negative zt (PA0551)
    • add reference height from input file to PALM reference height (origin_z)

init_grid:

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