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

Last change on this file since 4358 was 4356, checked in by suehring, 4 years ago

Bugfix in message calls for local checks; error messages in init_grid slightly revised; bugfix in time_integration (uninitialized emission time index); read_restart_data (change from J.Resler): use dynamic array allocation rather than automatic arrays to avoid problems with stack memory

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