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

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

last changes documented

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