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

Last change on this file since 3580 was 3538, checked in by suehring, 5 years ago

Remove unnecessary double masking of topography in advection and buoyancy terms

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