source: palm/trunk/SOURCE/urban_surface_mod.f90 @ 2512

Last change on this file since 2512 was 2512, checked in by raasch, 7 years ago

upper bounds of cross section and 3d output changed from nx+1,ny+1 to nx,ny; no output if redundant ghost layer data to NetCDF files

  • Property svn:keywords set to Id
File size: 264.6 KB
Line 
1!> @file urban_surface_mod.f90
2!--------------------------------------------------------------------------------!
3! This file is part of PALM.
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 2015-2017 Czech Technical University in Prague
18! Copyright 1997-2017 Leibniz Universitaet Hannover
19!--------------------------------------------------------------------------------!
20!
21! Current revisions:
22! ------------------
23!
24!
25! Former revisions:
26! -----------------
27! $Id: urban_surface_mod.f90 2512 2017-10-04 08:26:59Z raasch $
28! upper bounds of 3d output changed from nx+1,ny+1 to nx,ny
29! no output of ghost layer data
30!
31! 2350 2017-08-15 11:48:26Z kanani
32! Bugfix and error message for nopointer version.
33! Additional "! defined(__nopointer)" as workaround to enable compilation of
34! nopointer version.
35!
36! 2318 2017-07-20 17:27:44Z suehring
37! Get topography top index via Function call
38!
39! 2317 2017-07-20 17:27:19Z suehring
40! Bugfix: adjust output of shf. Added support for spinups
41!
42! 2287 2017-06-15 16:46:30Z suehring
43! Bugfix in determination topography-top index
44!
45! 2269 2017-06-09 11:57:32Z suehring
46! Enable restart runs with different number of PEs
47! Bugfixes nopointer branch
48!
49! 2258 2017-06-08 07:55:13Z suehring
50! Bugfix, add pre-preprocessor directives to enable non-parrallel mode
51!
52! 2233 2017-05-30 18:08:54Z suehring
53!
54! 2232 2017-05-30 17:47:52Z suehring
55! Adjustments according to new surface-type structure. Remove usm_wall_heat_flux;
56! insteat, heat fluxes are directly applied in diffusion_s.
57!
58! 2213 2017-04-24 15:10:35Z kanani
59! Removal of output quantities usm_lad and usm_canopy_hr
60!
61! 2209 2017-04-19 09:34:46Z kanani
62! cpp switch __mpi3 removed,
63! minor formatting,
64! small bugfix for division by zero (Krc)
65!
66! 2113 2017-01-12 13:40:46Z kanani
67! cpp switch __mpi3 added for MPI-3 standard code (Ketelsen)
68!
69! 2071 2016-11-17 11:22:14Z maronga
70! Small bugfix (Resler)
71!
72! 2031 2016-10-21 15:11:58Z knoop
73! renamed variable rho to rho_ocean
74!
75! 2024 2016-10-12 16:42:37Z kanani
76! Bugfixes in deallocation of array plantt and reading of csf/csfsurf,
77! optimization of MPI-RMA operations,
78! declaration of pcbl as integer,
79! renamed usm_radnet -> usm_rad_net, usm_canopy_khf -> usm_canopy_hr,
80! splitted arrays svf -> svf & csf, svfsurf -> svfsurf & csfsurf,
81! use of new control parameter varnamelength,
82! added output variables usm_rad_ressw, usm_rad_reslw,
83! minor formatting changes,
84! minor optimizations.
85!
86! 2011 2016-09-19 17:29:57Z kanani
87! Major reformatting according to PALM coding standard (comments, blanks,
88! alphabetical ordering, etc.),
89! removed debug_prints,
90! removed auxiliary SUBROUTINE get_usm_info, instead, USM flag urban_surface is
91! defined in MODULE control_parameters (modules.f90) to avoid circular
92! dependencies,
93! renamed canopy_heat_flux to pc_heating_rate, as meaning of quantity changed.
94!
95! 2007 2016-08-24 15:47:17Z kanani
96! Initial revision
97!
98!
99! Description:
100! ------------
101! 2016/6/9 - Initial version of the USM (Urban Surface Model)
102!            authors: Jaroslav Resler, Pavel Krc
103!                     (Czech Technical University in Prague and Institute of
104!                      Computer Science of the Czech Academy of Sciences, Prague)
105!            with contributions: Michal Belda, Nina Benesova, Ondrej Vlcek
106!            partly inspired by PALM LSM (B. Maronga)
107!            parameterizations of Ra checked with TUF3D (E. S. Krayenhoff)
108!> Module for Urban Surface Model (USM)
109!> The module includes:
110!>    1. radiation model with direct/diffuse radiation, shading, reflections
111!>       and integration with plant canopy
112!>    2. wall and wall surface model
113!>    3. surface layer energy balance
114!>    4. anthropogenic heat (only from transportation so far)
115!>    5. necessary auxiliary subroutines (reading inputs, writing outputs,
116!>       restart simulations, ...)
117!> It also make use of standard radiation and integrates it into
118!> urban surface model.
119!>
120!> Further work:
121!> -------------
122!> 1. Reduce number of shape view factors by merging factors for distant surfaces
123!>    under shallow angles. Idea: Iteratively select the smallest shape view
124!>    factor by value (among all sources and targets) which has a similarly
125!>    oriented source neighbor (or near enough) SVF and merge them by adding
126!>    value of the smaller SVF to the larger one and deleting the smaller one.
127!>    This will allow for better scaling at higher resolutions.
128!>
129!> 2. Remove global arrays surfouts, surfoutl and only keep track of radiosity
130!>    from surfaces that are visible from local surfaces (i.e. there is a SVF
131!>    where target is local). To do that, radiosity will be exchanged after each
132!>    reflection step using MPI_Alltoall instead of current MPI_Allgather.
133!>
134!> 3. Temporarily large values of surface heat flux can be observed, up to
135!>    1.2 Km/s, which seem to be not realistic.
136!>
137!> @todo Revise flux conversion in energy-balance solver
138!> @todo Bugfixing in nopointer branch
139!> @todo Check optimizations for RMA operations
140!> @todo Alternatives for MPI_WIN_ALLOCATE? (causes problems with openmpi)
141!> @todo Check for load imbalances in CPU measures, e.g. for exchange_horiz_prog
142!>       factor 3 between min and max time
143!------------------------------------------------------------------------------!
144 MODULE urban_surface_mod
145
146#if ! defined( __nopointer )
147    USE arrays_3d,                                                             &
148        ONLY:  zu, pt, pt_1, pt_2, p, u, v, w, hyp, tend
149#endif
150
151    USE cloud_parameters,                                                      &
152        ONLY:  cp, r_d
153
154    USE constants,                                                             &
155        ONLY:  pi
156   
157    USE control_parameters,                                                    &
158        ONLY:  coupling_start_time, dz, topography, dt_3d,                     &
159               intermediate_timestep_count, initializing_actions,              &
160               intermediate_timestep_count_max, simulated_time, end_time,      &
161               timestep_scheme, tsc, coupling_char, io_blocks, io_group,       &
162               message_string, time_since_reference_point, surface_pressure,   &
163               g, pt_surface, large_scale_forcing, lsf_surf, spinup,           &
164               spinup_pt_mean, spinup_time, time_do3d, dt_do3d,                &
165               average_count_3d, varnamelength, urban_surface
166
167    USE cpulog,                                                                &
168        ONLY:  cpu_log, log_point, log_point_s
169     
170    USE grid_variables,                                                        &
171        ONLY:  dx, dy, ddx, ddy, ddx2, ddy2
172   
173    USE indices,                                                               &
174        ONLY:  nx, ny, nnx, nny, nnz, nxl, nxlg, nxr, nxrg, nyn, nyng, nys,    &
175               nysg, nzb, nzt, nbgp, wall_flags_0
176
177    USE, INTRINSIC :: iso_c_binding 
178
179    USE kinds
180             
181    USE pegrid
182   
183    USE plant_canopy_model_mod,                                                &
184        ONLY:  plant_canopy, pch_index,                                        &
185               pc_heating_rate, lad_s
186   
187    USE radiation_model_mod,                                                   &
188        ONLY:  radiation, calc_zenith, zenith, day_init, time_utc_init,        &
189               rad_net, rad_sw_in, rad_lw_in, rad_sw_out, rad_lw_out,          &
190               sigma_sb, sun_direction, sun_dir_lat, sun_dir_lon,              &
191               force_radiation_call
192
193    USE statistics,                                                            &
194        ONLY:  hom, statistic_regions
195
196    USE surface_mod
197
198               
199
200    IMPLICIT NONE
201
202!-- configuration parameters (they can be setup in PALM config)
203    LOGICAL                                        ::  split_diffusion_radiation = .TRUE. !< split direct and diffusion dw radiation
204                                                                                          !< (.F. in case the radiation model already does it)   
205    LOGICAL                                        ::  usm_energy_balance_land = .TRUE.   !< flag parameter indicating wheather the energy balance is calculated for land and roofs
206    LOGICAL                                        ::  usm_energy_balance_wall = .TRUE.   !< flag parameter indicating wheather the energy balance is calculated for land and roofs
207    LOGICAL                                        ::  usm_material_model = .TRUE.        !< flag parameter indicating wheather the  model of heat in materials is used
208    LOGICAL                                        ::  usm_anthropogenic_heat = .FALSE.   !< flag parameter indicating wheather the anthropogenic heat sources (e.g.transportation) are used
209    LOGICAL                                        ::  force_radiation_call_l = .FALSE.   !< flag parameter for unscheduled radiation model calls
210    LOGICAL                                        ::  mrt_factors = .FALSE.              !< whether to generate MRT factor files during init
211    LOGICAL                                        ::  write_svf_on_init = .FALSE.
212    LOGICAL                                        ::  read_svf_on_init = .FALSE.
213    LOGICAL                                        ::  usm_lad_rma = .TRUE.               !< use MPI RMA to access LAD for raytracing (instead of global array)
214   
215    INTEGER(iwp)                                   ::  nrefsteps = 0                      !< number of reflection steps to perform
216   
217    INTEGER(iwp)                                   ::  land_category = 2                  !< default category for land surface
218    INTEGER(iwp)                                   ::  wall_category = 2                  !< default category for wall surface over pedestrian zone
219    INTEGER(iwp)                                   ::  pedestrant_category = 2            !< default category for wall surface in pedestrian zone
220    INTEGER(iwp)                                   ::  roof_category = 2                  !< default category for root surface
221    REAL(wp)                                       ::  roof_height_limit = 4._wp          !< height for distinguish between land surfaces and roofs
222
223    REAL(wp), PARAMETER                            ::  ext_coef = 0.6_wp                  !< extinction coefficient (a.k.a. alpha)
224    REAL(wp)                                       ::  ra_horiz_coef = 5.0_wp             !< mysterious coefficient for correction of overestimation
225                                                                                          !< of r_a for horizontal surfaces -> TODO
226   
227!-- parameters of urban surface model
228    INTEGER(iwp), PARAMETER                        ::  usm_version_len = 10               !< length of identification string of usm version
229    CHARACTER(usm_version_len), PARAMETER          ::  usm_version = 'USM v. 1.0'         !< identification of version of binary svf and restart files
230    INTEGER(iwp), PARAMETER                        ::  svf_code_len = 15                  !< length of code for verification of the end of svf file
231    CHARACTER(svf_code_len), PARAMETER             ::  svf_code = '*** end svf ***'       !< code for verification of the end of svf file
232    INTEGER(iwp)                                   ::  nzu                                !< number of layers of urban surface (will be calculated)
233    INTEGER(iwp)                                   ::  nzub,nzut                          !< bottom and top layer of urban surface (will be calculated)
234    INTEGER(iwp), PARAMETER                        ::  nzut_free = 3                      !< number of free layers in urban surface layer above top of buildings
235    INTEGER(iwp), PARAMETER                        ::  ndsvf = 2                          !< number of dimensions of real values in SVF
236    INTEGER(iwp), PARAMETER                        ::  idsvf = 2                          !< number of dimensions of integer values in SVF
237    INTEGER(iwp), PARAMETER                        ::  ndcsf = 2                          !< number of dimensions of real values in CSF
238    INTEGER(iwp), PARAMETER                        ::  idcsf = 2                          !< number of dimensions of integer values in CSF
239    INTEGER(iwp), PARAMETER                        ::  kdcsf = 4                          !< number of dimensions of integer values in CSF calculation array
240    INTEGER(iwp), PARAMETER                        ::  id = 1                             !< position of d-index in surfl and surf
241    INTEGER(iwp), PARAMETER                        ::  iz = 2                             !< position of k-index in surfl and surf
242    INTEGER(iwp), PARAMETER                        ::  iy = 3                             !< position of j-index in surfl and surf
243    INTEGER(iwp), PARAMETER                        ::  ix = 4                             !< position of i-index in surfl and surf
244    INTEGER(iwp), PARAMETER                        ::  iroof = 0                          !< 0 - index of ground or roof
245    INTEGER(iwp), PARAMETER                        ::  isouth = 1                         !< 1 - index of south facing wall
246    INTEGER(iwp), PARAMETER                        ::  inorth = 2                         !< 2 - index of north facing wall
247    INTEGER(iwp), PARAMETER                        ::  iwest  = 3                         !< 3 - index of west facing wall
248    INTEGER(iwp), PARAMETER                        ::  ieast  = 4                         !< 4 - index of east facing wall
249    INTEGER(iwp), PARAMETER                        ::  isky = 5                           !< 5 - index of top border of the urban surface layer ("urban sky")
250    INTEGER(iwp), PARAMETER                        ::  inorthb = 6                        !< 6 - index of free north border of the domain (south facing)
251    INTEGER(iwp), PARAMETER                        ::  isouthb = 7                        !< 7 - index of north south border of the domain (north facing)
252    INTEGER(iwp), PARAMETER                        ::  ieastb  = 8                        !< 8 - index of east border of the domain (west facing)
253    INTEGER(iwp), PARAMETER                        ::  iwestb  = 9                        !< 9 - index of wast border of the domain (east facing)
254    INTEGER(iwp), DIMENSION(0:9), PARAMETER        ::  idir = (/0,0,0,-1,1,0,0,0,-1,1/)   !< surface normal direction x indices
255    INTEGER(iwp), DIMENSION(0:9), PARAMETER        ::  jdir = (/0,-1,1,0,0,0,-1,1,0,0/)   !< surface normal direction y indices
256    INTEGER(iwp), DIMENSION(0:9), PARAMETER        ::  kdir = (/1,0,0,0,0,-1,0,0,0,0/)    !< surface normal direction z indices
257    REAL(wp), DIMENSION(1:4)                       ::  ddxy2                              !< 1/dx^2 or 1/dy^2 (in surface normal direction)
258    INTEGER(iwp), DIMENSION(1:4,6:9)               ::  ijdb                               !< start and end of the local domain border coordinates (set in code)
259    LOGICAL, DIMENSION(6:9)                        ::  isborder                           !< is PE on the border of the domain in four corresponding directions
260                                                                                          !< parameter but set in the code
261
262!-- indices and sizes of urban surface model
263    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE      ::  surfl            !< coordinates of i-th local surface in local grid - surfl[:,k] = [d, z, y, x]
264    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE      ::  surf             !< coordinates of i-th surface in grid - surf[:,k] = [d, z, y, x]
265    INTEGER(iwp)                                   ::  nsurfl           !< number of all surfaces in local processor
266    INTEGER(iwp), DIMENSION(:), ALLOCATABLE        ::  nsurfs           !< array of number of all surfaces in individual processors
267    INTEGER(iwp)                                   ::  startsky         !< start index of block of sky
268    INTEGER(iwp)                                   ::  endsky           !< end index of block of sky
269    INTEGER(iwp)                                   ::  nskys            !< number of sky surfaces in local processor
270    INTEGER(iwp)                                   ::  startland        !< start index of block of land and roof surfaces
271    INTEGER(iwp)                                   ::  endland          !< end index of block of land and roof surfaces
272    INTEGER(iwp)                                   ::  nlands           !< number of land and roof surfaces in local processor
273    INTEGER(iwp)                                   ::  startwall        !< start index of block of wall surfaces
274    INTEGER(iwp)                                   ::  endwall          !< end index of block of wall surfaces
275    INTEGER(iwp)                                   ::  nwalls           !< number of wall surfaces in local processor
276    INTEGER(iwp)                                   ::  startenergy      !< start index of block of real surfaces (land, walls and roofs)
277    INTEGER(iwp)                                   ::  endenergy        !< end index of block of real surfaces (land, walls and roofs)
278    INTEGER(iwp)                                   ::  nenergy          !< number of real surfaces in local processor
279    INTEGER(iwp)                                   ::  nsurf            !< global number of surfaces in index array of surfaces (nsurf = Σproc nsurfs)
280    INTEGER(iwp), DIMENSION(:), ALLOCATABLE        ::  surfstart        !< starts of blocks of surfaces for individual processors in array surf
281                                                                        !< respective block for particular processor is surfstart[iproc]+1 : surfstart[iproc+1]
282    INTEGER(iwp)                                   ::  nsvfl            !< number of svf for local processor
283    INTEGER(iwp)                                   ::  ncsfl            !< no. of csf in local processor
284                                                                        !< needed only during calc_svf but must be here because it is
285                                                                        !< shared between subroutines usm_calc_svf and usm_raytrace
286
287!-- type for calculation of svf
288    TYPE t_svf
289        INTEGER(iwp)                               :: isurflt           !<
290        INTEGER(iwp)                               :: isurfs            !<
291        REAL(wp)                                   :: rsvf              !<
292        REAL(wp)                                   :: rtransp           !<
293    END TYPE
294
295!-- type for calculation of csf
296    TYPE t_csf
297        INTEGER(iwp)                               :: ip                !<
298        INTEGER(iwp)                               :: itx               !<
299        INTEGER(iwp)                               :: ity               !<
300        INTEGER(iwp)                               :: itz               !<
301        INTEGER(iwp)                               :: isurfs            !<
302        REAL(wp)                                   :: rsvf              !<
303        REAL(wp)                                   :: rtransp           !<
304    END TYPE
305!
306!-- Type for surface temperatures at vertical walls. Is not necessary for horizontal walls.
307    TYPE t_surf_vertical
308       REAL(wp), DIMENSION(:), ALLOCATABLE         :: t
309    END TYPE t_surf_vertical
310!
311!-- Type for wall temperatures at vertical walls. Is not necessary for horizontal walls.
312    TYPE t_wall_vertical
313       REAL(wp), DIMENSION(:,:), ALLOCATABLE       :: t
314    END TYPE t_wall_vertical
315
316!-- arrays for calculation of svf and csf
317    TYPE(t_svf), DIMENSION(:), POINTER             ::  asvf             !< pointer to growing svc array
318    TYPE(t_csf), DIMENSION(:), POINTER             ::  acsf             !< pointer to growing csf array
319    TYPE(t_svf), DIMENSION(:), ALLOCATABLE, TARGET ::  asvf1, asvf2     !< realizations of svf array
320    TYPE(t_csf), DIMENSION(:), ALLOCATABLE, TARGET ::  acsf1, acsf2     !< realizations of csf array
321    INTEGER(iwp)                                   ::  nsvfla           !< dimmension of array allocated for storage of svf in local processor
322    INTEGER(iwp)                                   ::  ncsfla           !< dimmension of array allocated for storage of csf in local processor
323    INTEGER(iwp)                                   ::  msvf, mcsf       !< mod for swapping the growing array
324    INTEGER(iwp), PARAMETER                        ::  gasize = 10000   !< initial size of growing arrays
325!-- temporary arrays for calculation of csf in raytracing
326    INTEGER(iwp)                                   ::  maxboxesg        !< max number of boxes ray can cross in the domain
327    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE      ::  boxes            !< coordinates of gridboxes being crossed by ray
328    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  crlens           !< array of crossing lengths of ray for particular grid boxes
329    INTEGER(iwp), DIMENSION(:), ALLOCATABLE        ::  lad_ip           !< array of numbers of process where lad is stored
330#if defined( __parallel )
331    INTEGER(kind=MPI_ADDRESS_KIND), &
332                  DIMENSION(:), ALLOCATABLE        ::  lad_disp         !< array of displaycements of lad in local array of proc lad_ip
333#endif
334    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  lad_s_ray        !< array of received lad_s for appropriate gridboxes crossed by ray
335
336!-- arrays storing the values of USM
337    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE      ::  svfsurf          !< svfsurf[:,isvf] = index of source and target surface for svf[isvf]
338    REAL(wp), DIMENSION(:,:), ALLOCATABLE          ::  svf              !< array of shape view factors+direct irradiation factors for local surfaces
339    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfins          !< array of sw radiation falling to local surface after i-th reflection
340    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinl          !< array of lw radiation for local surface after i-th reflection
341   
342                                                                        !< Inward radiation is also valid for virtual surfaces (radiation leaving domain)
343    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinsw         !< array of sw radiation falling to local surface including radiation from reflections
344    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinlw         !< array of lw radiation falling to local surface including radiation from reflections
345    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinswdir      !< array of direct sw radiation falling to local surface
346    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinswdif      !< array of diffuse sw radiation from sky and model boundary falling to local surface
347    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinlwdif      !< array of diffuse lw radiation from sky and model boundary falling to local surface
348   
349                                                                        !< Outward radiation is only valid for nonvirtual surfaces
350    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfoutsl        !< array of reflected sw radiation for local surface in i-th reflection
351    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfoutll        !< array of reflected + emitted lw radiation for local surface in i-th reflection
352    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfouts         !< array of reflected sw radiation for all surfaces in i-th reflection
353    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfoutl         !< array of reflected + emitted lw radiation for all surfaces in i-th reflection
354    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfoutsw        !< array of total sw radiation outgoing from nonvirtual surfaces surfaces after all reflection
355    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfoutlw        !< array of total lw radiation outgoing from nonvirtual surfaces surfaces after all reflection
356    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfhf           !< array of total radiation flux incoming to minus outgoing from local surface
357    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  rad_net_l        !< local copy of rad_net (net radiation at surface)
358
359!-- arrays for time averages
360    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  rad_net_av       !< average of rad_net_l
361    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinsw_av      !< average of sw radiation falling to local surface including radiation from reflections
362    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinlw_av      !< average of lw radiation falling to local surface including radiation from reflections
363    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinswdir_av   !< average of direct sw radiation falling to local surface
364    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinswdif_av   !< average of diffuse sw radiation from sky and model boundary falling to local surface
365    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinlwdif_av   !< average of diffuse lw radiation from sky and model boundary falling to local surface
366    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinswref_av   !< average of sw radiation falling to surface from reflections
367    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinlwref_av   !< average of lw radiation falling to surface from reflections
368    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfoutsw_av     !< average of total sw radiation outgoing from nonvirtual surfaces surfaces after all reflection
369    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfoutlw_av     !< average of total lw radiation outgoing from nonvirtual surfaces surfaces after all reflection
370    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfins_av       !< average of array of residua of sw radiation absorbed in surface after last reflection
371    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfinl_av       !< average of array of residua of lw radiation absorbed in surface after last reflection
372    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  surfhf_av        !< average of total radiation flux incoming to minus outgoing from local surface 
373   
374!-- block variables needed for calculation of the plant canopy model inside the urban surface model
375    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE      ::  csfsurf          !< csfsurf[:,icsf] = index of target surface and csf grid index for csf[icsf]
376    REAL(wp), DIMENSION(:,:), ALLOCATABLE          ::  csf              !< array of plant canopy sink fators + direct irradiation factors (transparency)
377                                                                        !< for local surfaces
378    INTEGER(wp), DIMENSION(:,:), ALLOCATABLE       ::  pcbl             !< k,j,i coordinates of l-th local plant canopy box pcbl[:,l] = [k, j, i]
379    INTEGER(iwp), DIMENSION(:,:,:), ALLOCATABLE    ::  gridpcbl         !< index of local pcb[k,j,i]
380    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  pcbinsw          !< array of absorbed sw radiation for local plant canopy box
381    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  pcbinlw          !< array of absorbed lw radiation for local plant canopy box
382    INTEGER(iwp)                                   ::  npcbl            !< number of the plant canopy gridboxes in local processor
383    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE      ::  pch              !< heights of the plant canopy
384    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE      ::  pct              !< top layer of the plant canopy
385    REAL(wp), DIMENSION(:,:,:), POINTER            ::  usm_lad          !< subset of lad_s within urban surface, transformed to plain Z coordinate
386    REAL(wp), DIMENSION(:), POINTER                ::  usm_lad_g        !< usm_lad globalized (used to avoid MPI RMA calls in raytracing)
387    REAL(wp)                                       ::  prototype_lad    !< prototype leaf area density for computing effective optical depth
388    INTEGER(iwp), DIMENSION(:), ALLOCATABLE        ::  nzterr, plantt   !< temporary global arrays for raytracing
389   
390!-- radiation related arrays (it should be better in interface of radiation module of PALM
391    REAL(wp), DIMENSION(:,:), ALLOCATABLE          ::  rad_sw_in_dir    !< direct sw radiation
392    REAL(wp), DIMENSION(:,:), ALLOCATABLE          ::  rad_sw_in_diff   !< diffusion sw radiation
393    REAL(wp), DIMENSION(:,:), ALLOCATABLE          ::  rad_lw_in_diff   !< diffusion lw radiation
394
395!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
396!-- anthropogenic heat sources
397!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
398    REAL(wp), DIMENSION(:,:), ALLOCATABLE          ::  aheat             !< daily average of anthropogenic heat (W/m2)
399    REAL(wp), DIMENSION(:), ALLOCATABLE            ::  aheatprof         !< diurnal profile of anthropogenic heat
400
401!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
402!-- wall surface model
403!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
404!-- wall surface model constants
405    INTEGER(iwp), PARAMETER                        :: nzb_wall = 0       !< inner side of the wall model (to be switched)
406    INTEGER(iwp), PARAMETER                        :: nzt_wall = 3       !< outer side of the wall model (to be switched)
407    INTEGER(iwp), PARAMETER                        :: nzw = 4            !< number of wall layers (fixed for now)
408
409    REAL(wp), DIMENSION(nzb_wall:nzt_wall)         :: zwn_default = (/0.0242_wp, 0.0969_wp, 0.346_wp, 1.0_wp /)
410                                                                         !< normalized soil, wall and roof layer depths (m/m)
411                                                                       
412    REAL(wp)                                       ::   wall_inner_temperature = 296.0_wp    !< temperature of the inner wall surface (~23 degrees C) (K)
413    REAL(wp)                                       ::   roof_inner_temperature = 296.0_wp    !< temperature of the inner roof surface (~23 degrees C) (K)
414    REAL(wp)                                       ::   soil_inner_temperature = 283.0_wp    !< temperature of the deep soil (~10 degrees C) (K)
415
416!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
417!-- surface and material model variables for walls, ground, roofs
418!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
419    REAL(wp), DIMENSION(:), ALLOCATABLE            :: zwn                !< normalized wall layer depths (m)
420
421#if defined( __nopointer )
422    REAL(wp), DIMENSION(:), ALLOCATABLE, TARGET    :: t_surf_h           !< wall surface temperature (K) at horizontal walls
423    REAL(wp), DIMENSION(:), ALLOCATABLE, TARGET    :: t_surf_h_p         !< progn. wall surface temperature (K) at horizontal walls
424
425    TYPE(t_surf_vertical), DIMENSION(0:3), TARGET  ::  t_surf_v
426    TYPE(t_surf_vertical), DIMENSION(0:3), TARGET  ::  t_surf_v_p
427#else
428    REAL(wp), DIMENSION(:), POINTER                :: t_surf_h
429    REAL(wp), DIMENSION(:), POINTER                :: t_surf_h_p 
430
431    REAL(wp), DIMENSION(:), ALLOCATABLE, TARGET    :: t_surf_h_1
432    REAL(wp), DIMENSION(:), ALLOCATABLE, TARGET    :: t_surf_h_2
433
434    TYPE(t_surf_vertical), DIMENSION(:), POINTER ::  t_surf_v
435    TYPE(t_surf_vertical), DIMENSION(:), POINTER ::  t_surf_v_p
436
437    TYPE(t_surf_vertical), DIMENSION(0:3), TARGET  :: t_surf_v_1
438    TYPE(t_surf_vertical), DIMENSION(0:3), TARGET  :: t_surf_v_2
439#endif
440    REAL(wp), DIMENSION(:), ALLOCATABLE, TARGET    :: t_surf_av          !< average of wall surface temperature (K)
441
442!-- Temporal tendencies for time stepping           
443    REAL(wp), DIMENSION(:), ALLOCATABLE            :: tt_surface_m       !< surface temperature tendency (K)
444
445!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
446!-- Energy balance variables
447!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
448!-- parameters of the land, roof and wall surfaces
449    REAL(wp), DIMENSION(:), ALLOCATABLE            :: albedo_surf        !< albedo of the surface
450!-- parameters of the wall surfaces
451    REAL(wp), DIMENSION(:), ALLOCATABLE            :: emiss_surf         !< emissivity of the wall surface
452
453#if defined( __nopointer )
454    REAL(wp), DIMENSION(:,:), ALLOCATABLE, TARGET    :: t_wall_h             !< Wall temperature (K)
455    REAL(wp), DIMENSION(:,:), ALLOCATABLE, TARGET    :: t_wall_h_av          !< Average of t_wall
456    REAL(wp), DIMENSION(:,:), ALLOCATABLE, TARGET    :: t_wall_h_p           !< Prog. wall temperature (K)
457
458    TYPE(t_wall_vertical), DIMENSION(0:3), TARGET  :: t_wall_v             !< Wall temperature (K)
459    TYPE(t_wall_vertical), DIMENSION(0:3), TARGET  :: t_wall_v_av          !< Average of t_wall
460    TYPE(t_wall_vertical), DIMENSION(0:3), TARGET  :: t_wall_v_p           !< Prog. wall temperature (K)
461#else
462    REAL(wp), DIMENSION(:,:), POINTER                :: t_wall_h, t_wall_h_p
463    REAL(wp), DIMENSION(:,:), ALLOCATABLE, TARGET    :: t_wall_h_av, t_wall_h_1, t_wall_h_2
464
465    TYPE(t_wall_vertical), DIMENSION(:), POINTER   :: t_wall_v, t_wall_v_p
466    TYPE(t_wall_vertical), DIMENSION(0:3), TARGET  :: t_wall_v_av, t_wall_v_1, t_wall_v_2
467#endif
468
469!-- Wall temporal tendencies for time stepping
470    REAL(wp), DIMENSION(:,:), ALLOCATABLE          :: tt_wall_m          !< t_wall prognostic array
471
472!-- Surface and material parameters classes (surface_type)
473!-- albedo, emissivity, lambda_surf, roughness, thickness, volumetric heat capacity, thermal conductivity
474    INTEGER(iwp)                                   :: n_surface_types      !< number of the wall type categories
475    INTEGER(iwp), PARAMETER                        :: n_surface_params = 8 !< number of parameters for each type of the wall
476    INTEGER(iwp), PARAMETER                        :: ialbedo  = 1         !< albedo of the surface
477    INTEGER(iwp), PARAMETER                        :: iemiss   = 2         !< emissivity of the surface
478    INTEGER(iwp), PARAMETER                        :: ilambdas = 3         !< heat conductivity λS between air and surface ( W m−2 K−1 )
479    INTEGER(iwp), PARAMETER                        :: irough   = 4         !< roughness relative to concrete
480    INTEGER(iwp), PARAMETER                        :: icsurf   = 5         !< Surface skin layer heat capacity (J m−2 K−1 )
481    INTEGER(iwp), PARAMETER                        :: ithick   = 6         !< thickness of the surface (wall, roof, land)  ( m )
482    INTEGER(iwp), PARAMETER                        :: irhoC    = 7         !< volumetric heat capacity rho*C of the material ( J m−3 K−1 )
483    INTEGER(iwp), PARAMETER                        :: ilambdah = 8         !< thermal conductivity λH of the wall (W m−1 K−1 )
484    CHARACTER(12), DIMENSION(:), ALLOCATABLE       :: surface_type_names   !< names of wall types (used only for reports)
485    INTEGER(iwp), DIMENSION(:), ALLOCATABLE        :: surface_type_codes   !< codes of wall types
486    REAL(wp), DIMENSION(:,:), ALLOCATABLE          :: surface_params       !< parameters of wall types
487   
488    CHARACTER(len=*), PARAMETER                    :: svf_file_name='usm_svf'
489   
490!-- interfaces of subroutines accessed from outside of this module
491    INTERFACE usm_check_data_output
492       MODULE PROCEDURE usm_check_data_output
493    END INTERFACE usm_check_data_output
494   
495    INTERFACE usm_check_parameters
496       MODULE PROCEDURE usm_check_parameters
497    END INTERFACE usm_check_parameters
498   
499    INTERFACE usm_data_output_3d
500       MODULE PROCEDURE usm_data_output_3d
501    END INTERFACE usm_data_output_3d
502   
503    INTERFACE usm_define_netcdf_grid
504       MODULE PROCEDURE usm_define_netcdf_grid
505    END INTERFACE usm_define_netcdf_grid
506
507    INTERFACE usm_init_urban_surface
508       MODULE PROCEDURE usm_init_urban_surface
509    END INTERFACE usm_init_urban_surface
510
511    INTERFACE usm_material_heat_model
512       MODULE PROCEDURE usm_material_heat_model
513    END INTERFACE usm_material_heat_model
514   
515    INTERFACE usm_parin
516       MODULE PROCEDURE usm_parin
517    END INTERFACE usm_parin
518
519    INTERFACE usm_radiation
520       MODULE PROCEDURE usm_radiation
521    END INTERFACE usm_radiation
522   
523    INTERFACE usm_read_restart_data 
524       MODULE PROCEDURE usm_read_restart_data
525    END INTERFACE usm_read_restart_data
526
527    INTERFACE usm_surface_energy_balance
528       MODULE PROCEDURE usm_surface_energy_balance
529    END INTERFACE usm_surface_energy_balance
530   
531    INTERFACE usm_swap_timelevel
532       MODULE PROCEDURE usm_swap_timelevel
533    END INTERFACE usm_swap_timelevel
534       
535    INTERFACE usm_write_restart_data
536       MODULE PROCEDURE usm_write_restart_data
537    END INTERFACE usm_write_restart_data
538   
539    SAVE
540
541    PRIVATE 
542   
543!-- Public parameters, constants and initial values
544    PUBLIC split_diffusion_radiation,                                          &
545           usm_anthropogenic_heat, usm_material_model, mrt_factors,            &
546           usm_check_parameters,                                               &
547           usm_energy_balance_land, usm_energy_balance_wall, nrefsteps,        &
548           usm_init_urban_surface, usm_radiation, usm_read_restart_data,       &
549           usm_surface_energy_balance, usm_material_heat_model,                &
550           usm_swap_timelevel, usm_check_data_output, usm_average_3d_data,     &
551           usm_data_output_3d, usm_define_netcdf_grid, usm_parin,              &
552           usm_write_restart_data,                                             &
553           nzub, nzut, ra_horiz_coef, usm_lad_rma,                             &
554           land_category, pedestrant_category, wall_category, roof_category,   &
555           write_svf_on_init, read_svf_on_init
556
557
558 CONTAINS
559
560 
561!------------------------------------------------------------------------------!
562! Description:
563! ------------
564!> This subroutine creates the necessary indices of the urban surfaces
565!> and plant canopy and it allocates the needed arrays for USM
566!------------------------------------------------------------------------------!
567    SUBROUTINE usm_allocate_urban_surface
568   
569        IMPLICIT NONE
570       
571        INTEGER(iwp) :: i, j, k, d, l, ir, jr, ids, m
572        INTEGER(iwp) :: k_topo     !< vertical index indicating topography top for given (j,i)
573        INTEGER(iwp) :: k_topo2    !< vertical index indicating topography top for given (j,i)
574        INTEGER(iwp) :: nzubl, nzutl, isurf, ipcgb
575        INTEGER(iwp) :: procid
576
577       
578
579       
580!--     auxiliary vars
581        ddxy2 = (/ddy2,ddy2,ddx2,ddx2/)      !< 1/dx^2 or 1/dy^2 (in surface normal direction)
582       
583        CALL location_message( '', .TRUE. )
584        CALL location_message( '    allocation of needed arrays', .TRUE. )
585!
586!--     Find nzub, nzut, nzu via wall_flag_0 array (nzb_s_inner will be
587!--     removed later). The following contruct finds the lowest / largest index
588!--     for any upward-facing wall (see bit 12).
589        nzubl = MINVAL(                                                        &
590                    MAXLOC(                                                    &
591                          MERGE( 1, 0,                                         &
592                                 BTEST( wall_flags_0(:,nys:nyn,nxl:nxr), 12 )  &
593                               ), DIM = 1                                      &
594                          ) - 1                                                & 
595                            )
596        nzutl = MAXVAL(                                                        &
597                   MAXLOC(                                                     &
598                          MERGE( 1, 0,                                         &
599                                 BTEST( wall_flags_0(:,nys:nyn,nxl:nxr), 12 )  &
600                               ), DIM = 1                                      &
601                          ) - 1                                                &
602                            )
603        nzubl = max(nzubl,nzb)
604
605       
606        IF ( plant_canopy )  THEN
607!--         allocate needed arrays
608            ALLOCATE( pct(nys:nyn,nxl:nxr) )
609            ALLOCATE( pch(nys:nyn,nxl:nxr) )
610
611!--         calculate plant canopy height
612            npcbl = 0
613            pct = 0.0_wp
614            pch = 0.0_wp
615            DO i = nxl, nxr
616                DO j = nys, nyn
617!
618!--                 Find topography top index
619                    k_topo = get_topography_top_index( j, i, 's' )
620
621                    DO k = nzt+1, 0, -1
622                        IF ( lad_s(k,j,i) /= 0.0_wp )  THEN
623!--                         we are at the top of the pcs
624                            pct(j,i) = k + k_topo
625                            pch(j,i) = k
626                            npcbl = npcbl + pch(j,i)
627                            EXIT
628                        ENDIF
629                    ENDDO
630                ENDDO
631            ENDDO
632           
633            nzutl = max(nzutl, maxval(pct))
634!--         code of plant canopy model uses parameter pch_index
635!--         we need to setup it here to right value
636!--         (pch_index, lad_s and other arrays in PCM are defined flat)
637            pch_index = maxval(pch)
638
639            prototype_lad = maxval(lad_s) * .9_wp  !< better be *1.0 if lad is either 0 or maxval(lad) everywhere
640            IF ( prototype_lad <= 0._wp ) prototype_lad = .3_wp
641            !WRITE(message_string, '(a,f6.3)') 'Precomputing effective box optical ' &
642            !    // 'depth using prototype leaf area density = ', prototype_lad
643            !CALL message('usm_init_urban_surface', 'PA0520', 0, 0, -1, 6, 0)
644        ENDIF
645       
646        nzutl = min(nzutl+nzut_free, nzt)
647                 
648#if defined( __parallel )
649        CALL MPI_AllReduce(nzubl,nzub,1,MPI_INTEGER,MPI_MIN,comm2d,ierr);
650        CALL MPI_AllReduce(nzutl,nzut,1,MPI_INTEGER,MPI_MAX,comm2d,ierr);
651#else
652        nzub = nzubl
653        nzut = nzutl
654#endif
655
656!--     global number of urban layers
657        nzu = nzut - nzub + 1
658       
659!--     allocate urban surfaces grid
660!--     calc number of surfaces in local proc
661        CALL location_message( '    calculation of indices for surfaces', .TRUE. )
662        nsurfl = 0
663!
664!--     Number of land- and roof surfaces. Note, since horizontal surface elements
665!--     are already counted in surface_mod, in case be simply reused here.
666        startland = 1
667        nsurfl    = surf_usm_h%ns
668        endland   = nsurfl
669        nlands    = endland-startland+1
670
671!
672!--     Number of vertical surfaces. As vertical surfaces are already
673!--     counted in surface mod, it can be reused here.
674        startwall = nsurfl+1
675        nsurfl = nsurfl + surf_usm_v(0)%ns + surf_usm_v(1)%ns +        &
676                          surf_usm_v(2)%ns + surf_usm_v(3)%ns 
677        endwall = nsurfl
678        nwalls = endwall-startwall+1
679
680       
681!--     range of energy balance surfaces  ! will be treated separately by surf_usm_h and surf_usm_v
682        nenergy = 0
683        IF ( usm_energy_balance_land )  THEN
684            startenergy = startland
685            nenergy = nenergy + nlands
686        ELSE
687            startenergy = startwall
688        ENDIF
689        IF ( usm_energy_balance_wall )  THEN
690            endenergy = endwall
691            nenergy = nenergy + nwalls
692        ELSE
693            endenergy = endland
694        ENDIF
695
696!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
697!--     block of virtual surfaces
698!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
699!--     calculate sky surfaces  ! not used so far!
700        startsky = nsurfl+1
701        nsurfl = nsurfl+(nxr-nxl+1)*(nyn-nys+1)
702        endsky = nsurfl
703        nskys = endsky-startsky+1
704       
705!--     border flags
706#if defined( __parallel )
707        isborder = (/ north_border_pe, south_border_pe, right_border_pe, left_border_pe /)
708#else
709        isborder = (/.TRUE.,.TRUE.,.TRUE.,.TRUE./)
710#endif
711!--     fill array of the limits of the local domain borders
712        ijdb = RESHAPE( (/ nxl,nxr,nyn,nyn,nxl,nxr,nys,nys,nxr,nxr,nys,nyn,nxl,nxl,nys,nyn /), (/4, 4/) )
713!--     calulation of the free borders of the domain
714        DO  ids = 6,9
715           IF ( isborder(ids) )  THEN
716!--           free border of the domain in direction ids
717              DO  i = ijdb(1,ids), ijdb(2,ids)
718                 DO  j = ijdb(3,ids), ijdb(4,ids)
719
720                    k_topo  = get_topography_top_index( j, i, 's' )
721                    k_topo2 = get_topography_top_index( j-jdir(ids), i-idir(ids), 's' )
722
723                    k = nzut - MAX( k_topo, k_topo2 )
724                    nsurfl = nsurfl + k
725                 ENDDO
726              ENDDO
727           ENDIF
728        ENDDO
729       
730!--     fill gridpcbl and pcbl
731        IF ( plant_canopy )  THEN
732            ALLOCATE( pcbl(iz:ix, 1:npcbl) )
733            ALLOCATE( gridpcbl(nzub:nzut,nys:nyn,nxl:nxr) )
734            gridpcbl(:,:,:) = 0
735            ipcgb = 0
736            DO i = nxl, nxr
737                DO j = nys, nyn
738!
739!--                 Find topography top index
740                    k_topo = get_topography_top_index( j, i, 's' )
741
742                    DO k = k_topo + 1, pct(j,i)
743                        ipcgb = ipcgb + 1
744                        gridpcbl(k,j,i) = ipcgb
745                        pcbl(:,ipcgb) = (/ k, j, i /)
746                    ENDDO
747                ENDDO
748            ENDDO
749
750            ALLOCATE( pcbinsw( 1:npcbl ) )
751            ALLOCATE( pcbinlw( 1:npcbl ) )
752        ENDIF
753
754!--     fill surfl
755        ALLOCATE(surfl(5,nsurfl))
756        isurf = 0
757       
758!--     add land surfaces or roofs
759        DO i = nxl, nxr
760            DO j = nys, nyn
761               DO  m = surf_usm_h%start_index(j,i), surf_usm_h%end_index(j,i)
762                  k = surf_usm_h%k(m)
763
764                  isurf = isurf + 1
765                  surfl(:,isurf) = (/iroof,k,j,i,m/)
766               ENDDO
767            ENDDO
768        ENDDO
769
770!--     add walls
771        DO i = nxl, nxr
772            DO j = nys, nyn
773               l = 0
774               DO  m = surf_usm_v(l)%start_index(j,i), surf_usm_v(l)%end_index(j,i)
775                  k = surf_usm_v(l)%k(m)
776
777                  isurf          = isurf + 1
778                  surfl(:,isurf) = (/2,k,j,i,m/)
779               ENDDO
780               l = 1
781               DO  m = surf_usm_v(l)%start_index(j,i), surf_usm_v(l)%end_index(j,i)
782                  k = surf_usm_v(l)%k(m)
783
784                  isurf          = isurf + 1
785                  surfl(:,isurf) = (/1,k,j,i,m/)
786               ENDDO
787               l = 2
788               DO  m = surf_usm_v(l)%start_index(j,i), surf_usm_v(l)%end_index(j,i)
789                  k = surf_usm_v(l)%k(m)
790
791                  isurf          = isurf + 1
792                  surfl(:,isurf) = (/4,k,j,i,m/)
793               ENDDO
794               l = 3
795               DO  m = surf_usm_v(l)%start_index(j,i), surf_usm_v(l)%end_index(j,i)
796                  k = surf_usm_v(l)%k(m)
797
798                  isurf          = isurf + 1
799                  surfl(:,isurf) = (/3,k,j,i,m/)
800               ENDDO
801            ENDDO
802        ENDDO
803
804!--     add sky
805        DO i = nxl, nxr
806            DO j = nys, nyn
807                isurf = isurf + 1
808                k = nzut
809                surfl(:,isurf) = (/isky,k,j,i,-1/)
810            ENDDO
811        ENDDO
812       
813!--     calulation of the free borders of the domain
814        DO ids = 6,9
815            IF ( isborder(ids) )  THEN
816!--             free border of the domain in direction ids
817                DO i = ijdb(1,ids), ijdb(2,ids)
818                    DO j = ijdb(3,ids), ijdb(4,ids)
819                        k_topo  = get_topography_top_index( j, i, 's' )
820                        k_topo2 = get_topography_top_index( j-jdir(ids), i-idir(ids), 's' )
821
822                        DO k = MAX(k_topo,k_topo2)+1, nzut
823                            isurf = isurf + 1
824                            surfl(:,isurf) = (/ids,k,j,i,-1/)
825                        ENDDO
826                    ENDDO
827                ENDDO
828            ENDIF
829        ENDDO
830       
831!--     global array surf of indices of surfaces and displacement index array surfstart
832        ALLOCATE(nsurfs(0:numprocs-1))
833       
834#if defined( __parallel )
835        CALL MPI_Allgather(nsurfl,1,MPI_INTEGER,nsurfs,1,MPI_INTEGER,comm2d,ierr)
836#else
837        nsurfs(0) = nsurfl
838#endif
839        ALLOCATE(surfstart(0:numprocs))
840        k = 0
841        DO i=0,numprocs-1
842            surfstart(i) = k
843            k = k+nsurfs(i)
844        ENDDO
845        surfstart(numprocs) = k
846        nsurf = k
847        ALLOCATE(surf(5,nsurf))
848       
849#if defined( __parallel )
850        CALL MPI_AllGatherv(surfl, nsurfl*5, MPI_INTEGER, surf, nsurfs*5, surfstart*5, MPI_INTEGER, comm2d, ierr)
851#else
852        surf = surfl
853#endif
854       
855!--
856!--     allocation of the arrays for direct and diffusion radiation
857        CALL location_message( '    allocation of radiation arrays', .TRUE. )
858!--     rad_sw_in, rad_lw_in are computed in radiation model,
859!--     splitting of direct and diffusion part is done
860!--     in usm_calc_diffusion_radiation for now
861        ALLOCATE( rad_sw_in_dir(nysg:nyng,nxlg:nxrg) )
862        ALLOCATE( rad_sw_in_diff(nysg:nyng,nxlg:nxrg) )
863        ALLOCATE( rad_lw_in_diff(nysg:nyng,nxlg:nxrg) )
864       
865!--     allocate radiation arrays
866        ALLOCATE( surfins(nsurfl) )
867        ALLOCATE( surfinl(nsurfl) )
868        ALLOCATE( surfinsw(nsurfl) )
869        ALLOCATE( surfinlw(nsurfl) )
870        ALLOCATE( surfinswdir(nsurfl) )
871        ALLOCATE( surfinswdif(nsurfl) )
872        ALLOCATE( surfinlwdif(nsurfl) )
873        ALLOCATE( surfoutsl(startenergy:endenergy) )
874        ALLOCATE( surfoutll(startenergy:endenergy) )
875        ALLOCATE( surfoutsw(startenergy:endenergy) )
876        ALLOCATE( surfoutlw(startenergy:endenergy) )
877        ALLOCATE( surfouts(nsurf) ) !TODO: global surfaces without virtual
878        ALLOCATE( surfoutl(nsurf) ) !TODO: global surfaces without virtual
879
880
881
882!
883!--     Allocate radiation arrays which are part of the new data type.
884!--     For horizontal surfaces.
885        ALLOCATE( surf_usm_h%surfhf(1:surf_usm_h%ns)    )
886        ALLOCATE( surf_usm_h%rad_net_l(1:surf_usm_h%ns) )
887!
888!--  New
889        ALLOCATE( surf_usm_h%rad_in_sw(1:surf_usm_h%ns)  )
890        ALLOCATE( surf_usm_h%rad_out_sw(1:surf_usm_h%ns) )
891        ALLOCATE( surf_usm_h%rad_in_lw(1:surf_usm_h%ns)  )
892        ALLOCATE( surf_usm_h%rad_out_lw(1:surf_usm_h%ns) )
893!
894!--     For vertical surfaces
895        DO  l = 0, 3
896           ALLOCATE( surf_usm_v(l)%surfhf(1:surf_usm_v(l)%ns)    )
897           ALLOCATE( surf_usm_v(l)%rad_net_l(1:surf_usm_v(l)%ns) )
898           ALLOCATE( surf_usm_v(l)%rad_in_sw(1:surf_usm_v(l)%ns)  )
899           ALLOCATE( surf_usm_v(l)%rad_out_sw(1:surf_usm_v(l)%ns) )
900           ALLOCATE( surf_usm_v(l)%rad_in_lw(1:surf_usm_v(l)%ns)  )
901           ALLOCATE( surf_usm_v(l)%rad_out_lw(1:surf_usm_v(l)%ns) )
902        ENDDO
903
904!--     Wall surface model
905!--     allocate arrays for wall surface model and define pointers
906       
907!--     allocate array of wall types and wall parameters
908        ALLOCATE ( surf_usm_h%surface_types(1:surf_usm_h%ns) )
909        DO  l = 0, 3
910           ALLOCATE( surf_usm_v(l)%surface_types(1:surf_usm_v(l)%ns) )
911        ENDDO
912       
913!--     broadband albedo of the land, roof and wall surface
914!--     for domain border and sky set artifically to 1.0
915!--     what allows us to calculate heat flux leaving over
916!--     side and top borders of the domain
917        ALLOCATE ( albedo_surf(nsurfl) )
918        albedo_surf = 1.0_wp
919        ALLOCATE ( surf_usm_h%albedo_surf(1:surf_usm_h%ns) )
920        DO  l = 0, 3
921           ALLOCATE( surf_usm_v(l)%albedo_surf(1:surf_usm_v(l)%ns) )
922        ENDDO
923       
924!--     wall and roof surface parameters. First for horizontal surfaces
925        ALLOCATE ( emiss_surf(startenergy:endenergy) )
926
927        ALLOCATE ( surf_usm_h%isroof_surf(1:surf_usm_h%ns)    )
928        ALLOCATE ( surf_usm_h%emiss_surf(1:surf_usm_h%ns)     )
929        ALLOCATE ( surf_usm_h%lambda_surf(1:surf_usm_h%ns)    )
930        ALLOCATE ( surf_usm_h%c_surface(1:surf_usm_h%ns)      )
931        ALLOCATE ( surf_usm_h%roughness_wall(1:surf_usm_h%ns) )
932!
933!--     For vertical surfaces.
934        DO  l = 0, 3
935           ALLOCATE ( surf_usm_v(l)%emiss_surf(1:surf_usm_v(l)%ns)     )
936           ALLOCATE ( surf_usm_v(l)%lambda_surf(1:surf_usm_v(l)%ns)    )
937           ALLOCATE ( surf_usm_v(l)%c_surface(1:surf_usm_v(l)%ns)      )
938           ALLOCATE ( surf_usm_v(l)%roughness_wall(1:surf_usm_v(l)%ns) )
939        ENDDO
940       
941!--     allocate wall and roof material parameters. First for horizontal surfaces
942        ALLOCATE ( surf_usm_h%thickness_wall(1:surf_usm_h%ns)               )
943        ALLOCATE ( surf_usm_h%lambda_h(nzb_wall:nzt_wall,1:surf_usm_h%ns)   )
944        ALLOCATE ( surf_usm_h%rho_c_wall(nzb_wall:nzt_wall,1:surf_usm_h%ns) )
945!
946!--     For vertical surfaces.
947        DO  l = 0, 3
948           ALLOCATE ( surf_usm_v(l)%thickness_wall(1:surf_usm_v(l)%ns)               )
949           ALLOCATE ( surf_usm_v(l)%lambda_h(nzb_wall:nzt_wall,1:surf_usm_v(l)%ns)   )
950           ALLOCATE ( surf_usm_v(l)%rho_c_wall(nzb_wall:nzt_wall,1:surf_usm_v(l)%ns) )
951        ENDDO
952
953!--     allocate wall and roof layers sizes. For horizontal surfaces.
954        ALLOCATE ( zwn(nzb_wall:nzt_wall) )
955        ALLOCATE ( surf_usm_h%dz_wall(nzb_wall:nzt_wall+1,1:surf_usm_h%ns)     )
956        ALLOCATE ( surf_usm_h%ddz_wall(nzb_wall:nzt_wall+1,1:surf_usm_h%ns)    )
957        ALLOCATE ( surf_usm_h%dz_wall_stag(nzb_wall:nzt_wall,1:surf_usm_h%ns)  )
958        ALLOCATE ( surf_usm_h%ddz_wall_stag(nzb_wall:nzt_wall,1:surf_usm_h%ns) )
959        ALLOCATE ( surf_usm_h%zw(nzb_wall:nzt_wall,1:surf_usm_h%ns)            )
960!
961!--     For vertical surfaces.
962        DO  l = 0, 3
963           ALLOCATE ( surf_usm_v(l)%dz_wall(nzb_wall:nzt_wall+1,1:surf_usm_v(l)%ns)     )
964           ALLOCATE ( surf_usm_v(l)%ddz_wall(nzb_wall:nzt_wall+1,1:surf_usm_v(l)%ns)    )
965           ALLOCATE ( surf_usm_v(l)%dz_wall_stag(nzb_wall:nzt_wall,1:surf_usm_v(l)%ns)  )
966           ALLOCATE ( surf_usm_v(l)%ddz_wall_stag(nzb_wall:nzt_wall,1:surf_usm_v(l)%ns) )
967           ALLOCATE ( surf_usm_v(l)%zw(nzb_wall:nzt_wall,1:surf_usm_v(l)%ns)            )
968        ENDDO
969
970!--     allocate wall and roof temperature arrays, for horizontal walls
971#if defined( __nopointer )
972        IF ( .NOT. ALLOCATED( t_surf_h ) )                                     &
973           ALLOCATE ( t_surf_h(1:surf_usm_h%ns) )
974        IF ( .NOT. ALLOCATED( t_surf_h_p ) )                                   &
975           ALLOCATE ( t_surf_h_p(1:surf_usm_h%ns) )
976        IF ( .NOT. ALLOCATED( t_wall_h ) )                                     &           
977           ALLOCATE ( t_wall_h(nzb_wall:nzt_wall+1,1:surf_usm_h%ns) ) 
978        IF ( .NOT. ALLOCATED( t_wall_h_p ) )                                   &           
979           ALLOCATE ( t_wall_h_p(nzb_wall:nzt_wall+1,1:surf_usm_h%ns) ) 
980#else
981!
982!--     Allocate if required. Note, in case of restarts, some of these arrays
983!--     might be already allocated.
984        IF ( .NOT. ALLOCATED( t_surf_h_1 ) )                                   &
985           ALLOCATE ( t_surf_h_1(1:surf_usm_h%ns) )
986        IF ( .NOT. ALLOCATED( t_surf_h_2 ) )                                   &
987           ALLOCATE ( t_surf_h_2(1:surf_usm_h%ns) )
988        IF ( .NOT. ALLOCATED( t_wall_h_1 ) )                                   &           
989           ALLOCATE ( t_wall_h_1(nzb_wall:nzt_wall+1,1:surf_usm_h%ns) ) 
990        IF ( .NOT. ALLOCATED( t_wall_h_2 ) )                                   &           
991           ALLOCATE ( t_wall_h_2(nzb_wall:nzt_wall+1,1:surf_usm_h%ns) )         
992!           
993!--     initial assignment of the pointers
994        t_wall_h    => t_wall_h_1;    t_wall_h_p    => t_wall_h_2
995        t_surf_h => t_surf_h_1; t_surf_h_p => t_surf_h_2           
996#endif
997
998!--     allocate wall and roof temperature arrays, for vertical walls if required
999#if defined( __nopointer )
1000        DO  l = 0, 3
1001           IF ( .NOT. ALLOCATED( t_surf_v(l)%t ) )                             &
1002              ALLOCATE ( t_surf_v(l)%t(1:surf_usm_v(l)%ns) )
1003           IF ( .NOT. ALLOCATED( t_surf_v_p(l)%t ) )                           &
1004              ALLOCATE ( t_surf_v_p(l)%t(1:surf_usm_v(l)%ns) )
1005           IF ( .NOT. ALLOCATED( t_wall_v(l)%t ) )                             &
1006              ALLOCATE ( t_wall_v(l)%t(nzb_wall:nzt_wall+1,1:surf_usm_v(l)%ns) )
1007           IF ( .NOT. ALLOCATED( t_wall_v_p(l)%t ) )                           &                 
1008              ALLOCATE ( t_wall_v_p(l)%t(nzb_wall:nzt_wall+1,1:surf_usm_v(l)%ns) )
1009        ENDDO
1010#else
1011!
1012!--     Allocate if required. Note, in case of restarts, some of these arrays
1013!--     might be already allocated.
1014        DO  l = 0, 3
1015           IF ( .NOT. ALLOCATED( t_surf_v_1(l)%t ) )                           &
1016              ALLOCATE ( t_surf_v_1(l)%t(1:surf_usm_v(l)%ns) )
1017           IF ( .NOT. ALLOCATED( t_surf_v_2(l)%t ) )                           &
1018              ALLOCATE ( t_surf_v_2(l)%t(1:surf_usm_v(l)%ns) )
1019           IF ( .NOT. ALLOCATED( t_wall_v_1(l)%t ) )                           &           
1020              ALLOCATE ( t_wall_v_1(l)%t(nzb_wall:nzt_wall+1,1:surf_usm_v(l)%ns) ) 
1021           IF ( .NOT. ALLOCATED( t_wall_v_2(l)%t ) )                           &           
1022              ALLOCATE ( t_wall_v_2(l)%t(nzb_wall:nzt_wall+1,1:surf_usm_v(l)%ns) ) 
1023        ENDDO
1024!
1025!--     initial assignment of the pointers
1026        t_wall_v    => t_wall_v_1;    t_wall_v_p    => t_wall_v_2
1027        t_surf_v => t_surf_v_1; t_surf_v_p => t_surf_v_2
1028#endif
1029!
1030!--     Allocate intermediate timestep arrays. For horizontal surfaces.
1031        ALLOCATE ( surf_usm_h%tt_surface_m(1:surf_usm_h%ns)                  )
1032        ALLOCATE ( surf_usm_h%tt_wall_m(nzb_wall:nzt_wall+1,1:surf_usm_h%ns) )
1033!
1034!--     Set inital values for prognostic quantities
1035        IF ( ALLOCATED( surf_usm_h%tt_surface_m ) )  surf_usm_h%tt_surface_m = 0.0_wp
1036        IF ( ALLOCATED( surf_usm_h%tt_wall_m    ) )  surf_usm_h%tt_wall_m    = 0.0_wp
1037!
1038!--     Now, for vertical surfaces
1039        DO  l = 0, 3
1040           ALLOCATE ( surf_usm_v(l)%tt_surface_m(1:surf_usm_v(l)%ns)                  )
1041           ALLOCATE ( surf_usm_v(l)%tt_wall_m(nzb_wall:nzt_wall+1,1:surf_usm_v(l)%ns) )
1042           IF ( ALLOCATED( surf_usm_v(l)%tt_surface_m ) )  surf_usm_v(l)%tt_surface_m = 0.0_wp
1043           IF ( ALLOCATED( surf_usm_v(l)%tt_wall_m    ) )  surf_usm_v(l)%tt_wall_m    = 0.0_wp
1044        ENDDO
1045
1046!--     allocate wall heat flux output array and set initial values. For horizontal surfaces
1047!         ALLOCATE ( surf_usm_h%wshf(1:surf_usm_h%ns)    )  !can be removed
1048        ALLOCATE ( surf_usm_h%wshf_eb(1:surf_usm_h%ns) )
1049        ALLOCATE ( surf_usm_h%wghf_eb(1:surf_usm_h%ns) )
1050        IF ( ALLOCATED( surf_usm_h%wshf    ) )  surf_usm_h%wshf    = 0.0_wp
1051        IF ( ALLOCATED( surf_usm_h%wshf_eb ) )  surf_usm_h%wshf_eb = 0.0_wp
1052        IF ( ALLOCATED( surf_usm_h%wghf_eb ) )  surf_usm_h%wghf_eb = 0.0_wp
1053!
1054!--     Now, for vertical surfaces
1055        DO  l = 0, 3
1056!            ALLOCATE ( surf_usm_v(l)%wshf(1:surf_usm_v(l)%ns)    )    ! can be removed
1057           ALLOCATE ( surf_usm_v(l)%wshf_eb(1:surf_usm_v(l)%ns) )
1058           ALLOCATE ( surf_usm_v(l)%wghf_eb(1:surf_usm_v(l)%ns) )
1059           IF ( ALLOCATED( surf_usm_v(l)%wshf    ) )  surf_usm_v(l)%wshf    = 0.0_wp
1060           IF ( ALLOCATED( surf_usm_v(l)%wshf_eb ) )  surf_usm_v(l)%wshf_eb = 0.0_wp
1061           IF ( ALLOCATED( surf_usm_v(l)%wghf_eb ) )  surf_usm_v(l)%wghf_eb = 0.0_wp
1062        ENDDO
1063       
1064    END SUBROUTINE usm_allocate_urban_surface
1065
1066
1067
1068!------------------------------------------------------------------------------!
1069! Description:
1070! ------------
1071!> Sum up and time-average urban surface output quantities as well as allocate
1072!> the array necessary for storing the average.
1073!------------------------------------------------------------------------------!
1074    SUBROUTINE usm_average_3d_data( mode, variable )
1075
1076        IMPLICIT NONE
1077
1078        CHARACTER (len=*), INTENT(IN) ::  mode
1079        CHARACTER (len=*), INTENT(IN) :: variable
1080 
1081        INTEGER(iwp)                                       :: i, j, k, l, m, ids, iwl,istat
1082        CHARACTER (len=varnamelength)                      :: var, surfid
1083        INTEGER(iwp), PARAMETER                            :: nd = 5
1084        CHARACTER(len=6), DIMENSION(0:nd-1), PARAMETER     :: dirname = (/ '_roof ', '_south', '_north', '_west ', '_east ' /)
1085
1086!--     find the real name of the variable
1087        var = TRIM(variable)
1088        DO i = 0, nd-1
1089            k = len(TRIM(var))
1090            j = len(TRIM(dirname(i)))
1091            IF ( var(k-j+1:k) == dirname(i) )  THEN
1092                ids = i
1093                var = var(:k-j)
1094                EXIT
1095            ENDIF
1096        ENDDO
1097        IF ( ids == -1 )  THEN
1098            var = TRIM(variable)
1099        ENDIF
1100        IF ( var(1:11) == 'usm_t_wall_'  .AND.  len(TRIM(var)) >= 12 )  THEN
1101!--          wall layers
1102            READ(var(12:12), '(I1)', iostat=istat ) iwl
1103            IF ( istat == 0  .AND.  iwl >= nzb_wall  .AND.  iwl <= nzt_wall )  THEN
1104                var = var(1:10)
1105            ELSE
1106!--             wrong wall layer index
1107                RETURN
1108            ENDIF
1109        ENDIF
1110
1111        IF ( mode == 'allocate' )  THEN
1112           
1113           SELECT CASE ( TRIM( var ) )
1114               
1115                CASE ( 'usm_rad_net' )
1116!--                 array of complete radiation balance
1117                    IF ( .NOT.  ALLOCATED(surf_usm_h%rad_net_av) )  THEN
1118                        ALLOCATE( surf_usm_h%rad_net_av(1:surf_usm_h%ns) )
1119                        surf_usm_h%rad_net_av = 0.0_wp
1120                    ENDIF
1121                    DO  l = 0, 3
1122                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%rad_net_av) )  THEN
1123                           ALLOCATE( surf_usm_v(l)%rad_net_av(1:surf_usm_v(l)%ns) )
1124                           surf_usm_v(l)%rad_net_av = 0.0_wp
1125                       ENDIF
1126                    ENDDO
1127                   
1128                CASE ( 'usm_rad_insw' )
1129!--                 array of sw radiation falling to surface after i-th reflection
1130                    IF ( .NOT.  ALLOCATED(surf_usm_h%surfinsw_av) )  THEN
1131                        ALLOCATE( surf_usm_h%surfinsw_av(1:surf_usm_h%ns) )
1132                        surf_usm_h%surfinsw_av = 0.0_wp
1133                    ENDIF
1134                    DO  l = 0, 3
1135                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%surfinsw_av) )  THEN
1136                           ALLOCATE( surf_usm_v(l)%surfinsw_av(1:surf_usm_v(l)%ns) )
1137                           surf_usm_v(l)%surfinsw_av = 0.0_wp
1138                       ENDIF
1139                    ENDDO
1140                                   
1141                CASE ( 'usm_rad_inlw' )
1142!--                 array of lw radiation falling to surface after i-th reflection
1143                    IF ( .NOT.  ALLOCATED(surf_usm_h%surfinlw_av) )  THEN
1144                        ALLOCATE( surf_usm_h%surfinlw_av(1:surf_usm_h%ns) )
1145                        surf_usm_h%surfinlw_av = 0.0_wp
1146                    ENDIF
1147                    DO  l = 0, 3
1148                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%surfinlw_av) )  THEN
1149                           ALLOCATE( surf_usm_v(l)%surfinlw_av(1:surf_usm_v(l)%ns) )
1150                           surf_usm_v(l)%surfinlw_av = 0.0_wp
1151                       ENDIF
1152                    ENDDO
1153
1154                CASE ( 'usm_rad_inswdir' )
1155!--                 array of direct sw radiation falling to surface from sun
1156                    IF ( .NOT.  ALLOCATED(surfinswdir_av) )  THEN
1157                        ALLOCATE( surfinswdir_av(startenergy:endenergy) )
1158                        surfinswdir_av = 0.0_wp
1159                    ENDIF
1160
1161                CASE ( 'usm_rad_inswdif' )
1162!--                 array of difusion sw radiation falling to surface from sky and borders of the domain
1163                    IF ( .NOT.  ALLOCATED(surfinswdif_av) )  THEN
1164                        ALLOCATE( surfinswdif_av(startenergy:endenergy) )
1165                        surfinswdif_av = 0.0_wp
1166                    ENDIF
1167
1168                CASE ( 'usm_rad_inswref' )
1169!--                 array of sw radiation falling to surface from reflections
1170                    IF ( .NOT.  ALLOCATED(surfinswref_av) )  THEN
1171                        ALLOCATE( surfinswref_av(startenergy:endenergy) )
1172                        surfinswref_av = 0.0_wp
1173                    ENDIF
1174
1175                CASE ( 'usm_rad_inlwdif' )
1176!--                 array of sw radiation falling to surface after i-th reflection
1177                   IF ( .NOT.  ALLOCATED(surfinlwdif_av) )  THEN
1178                        ALLOCATE( surfinlwdif_av(startenergy:endenergy) )
1179                        surfinlwdif_av = 0.0_wp
1180                    ENDIF
1181
1182                CASE ( 'usm_rad_inlwref' )
1183!--                 array of lw radiation falling to surface from reflections
1184                    IF ( .NOT.  ALLOCATED(surfinlwref_av) )  THEN
1185                        ALLOCATE( surfinlwref_av(startenergy:endenergy) )
1186                        surfinlwref_av = 0.0_wp
1187                    ENDIF
1188
1189                CASE ( 'usm_rad_outsw' )
1190!--                 array of sw radiation emitted from surface after i-th reflection
1191                    IF ( .NOT.  ALLOCATED(surfoutsw_av) )  THEN
1192                        ALLOCATE( surfoutsw_av(startenergy:endenergy) )
1193                        surfoutsw_av = 0.0_wp
1194                    ENDIF
1195
1196                CASE ( 'usm_rad_outlw' )
1197!--                 array of lw radiation emitted from surface after i-th reflection
1198                    IF ( .NOT.  ALLOCATED(surfoutlw_av) )  THEN
1199                        ALLOCATE( surfoutlw_av(startenergy:endenergy) )
1200                        surfoutlw_av = 0.0_wp
1201                    ENDIF
1202                CASE ( 'usm_rad_ressw' )
1203!--                 array of residua of sw radiation absorbed in surface after last reflection
1204                    IF ( .NOT.  ALLOCATED(surfins_av) )  THEN
1205                        ALLOCATE( surfins_av(startenergy:endenergy) )
1206                        surfins_av = 0.0_wp
1207                    ENDIF
1208                                   
1209                CASE ( 'usm_rad_reslw' )
1210!--                 array of residua of lw radiation absorbed in surface after last reflection
1211                    IF ( .NOT.  ALLOCATED(surfinl_av) )  THEN
1212                        ALLOCATE( surfinl_av(startenergy:endenergy) )
1213                        surfinl_av = 0.0_wp
1214                    ENDIF
1215                                   
1216                CASE ( 'usm_rad_hf' )
1217!--                 array of heat flux from radiation for surfaces after i-th reflection
1218                    IF ( .NOT.  ALLOCATED(surf_usm_h%surfhf_av) )  THEN
1219                        ALLOCATE( surf_usm_h%surfhf_av(1:surf_usm_h%ns) )
1220                        surf_usm_h%surfhf_av = 0.0_wp
1221                    ENDIF
1222                    DO  l = 0, 3
1223                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%surfhf_av) )  THEN
1224                           ALLOCATE( surf_usm_v(l)%surfhf_av(1:surf_usm_v(l)%ns) )
1225                           surf_usm_v(l)%surfhf_av = 0.0_wp
1226                       ENDIF
1227                    ENDDO
1228
1229                CASE ( 'usm_wshf' )
1230!--                 array of sensible heat flux from surfaces
1231!--                 land surfaces
1232                    IF ( .NOT.  ALLOCATED(surf_usm_h%wshf_eb_av) )  THEN
1233                        ALLOCATE( surf_usm_h%wshf_eb_av(1:surf_usm_h%ns) )
1234                        surf_usm_h%wshf_eb_av = 0.0_wp
1235                    ENDIF
1236                    DO  l = 0, 3
1237                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%wshf_eb_av) )  THEN
1238                           ALLOCATE( surf_usm_v(l)%wshf_eb_av(1:surf_usm_v(l)%ns) )
1239                           surf_usm_v(l)%wshf_eb_av = 0.0_wp
1240                       ENDIF
1241                    ENDDO
1242
1243                CASE ( 'usm_wghf' )
1244!--                 array of heat flux from ground (wall, roof, land)
1245                    IF ( .NOT.  ALLOCATED(surf_usm_h%wghf_eb_av) )  THEN
1246                        ALLOCATE( surf_usm_h%wghf_eb_av(1:surf_usm_h%ns) )
1247                        surf_usm_h%wghf_eb_av = 0.0_wp
1248                    ENDIF
1249                    DO  l = 0, 3
1250                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%wghf_eb_av) )  THEN
1251                           ALLOCATE( surf_usm_v(l)%wghf_eb_av(1:surf_usm_v(l)%ns) )
1252                           surf_usm_v(l)%wghf_eb_av = 0.0_wp
1253                       ENDIF
1254                    ENDDO
1255
1256                CASE ( 'usm_t_surf' )
1257!--                 surface temperature for surfaces
1258                    IF ( .NOT.  ALLOCATED(surf_usm_h%t_surf_av) )  THEN
1259                        ALLOCATE( surf_usm_h%t_surf_av(1:surf_usm_h%ns) )
1260                        surf_usm_h%t_surf_av = 0.0_wp
1261                    ENDIF
1262                    DO  l = 0, 3
1263                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%t_surf_av) )  THEN
1264                           ALLOCATE( surf_usm_v(l)%t_surf_av(1:surf_usm_v(l)%ns) )
1265                           surf_usm_v(l)%t_surf_av = 0.0_wp
1266                       ENDIF
1267                    ENDDO
1268
1269                CASE ( 'usm_t_wall' )
1270!--                 wall temperature for iwl layer of walls and land
1271                    IF ( .NOT.  ALLOCATED(surf_usm_h%t_wall_av) )  THEN
1272                        ALLOCATE( surf_usm_h%t_wall_av(nzb_wall:nzt_wall,1:surf_usm_h%ns) )
1273                        surf_usm_h%t_wall_av = 0.0_wp
1274                    ENDIF
1275                    DO  l = 0, 3
1276                       IF ( .NOT.  ALLOCATED(surf_usm_v(l)%t_wall_av) )  THEN
1277                           ALLOCATE( surf_usm_v(l)%t_wall_av(nzb_wall:nzt_wall,1:surf_usm_v(l)%ns) )
1278                           surf_usm_v(l)%t_wall_av = 0.0_wp
1279                       ENDIF
1280                    ENDDO
1281
1282               CASE DEFAULT
1283                   CONTINUE
1284
1285           END SELECT
1286
1287        ELSEIF ( mode == 'sum' )  THEN
1288           
1289           SELECT CASE ( TRIM( var ) )
1290               
1291                CASE ( 'usm_rad_net' )
1292!--                 array of complete radiation balance
1293                    DO  m = 1, surf_usm_h%ns
1294                       surf_usm_h%rad_net_av(m) =                              &
1295                                          surf_usm_h%rad_net_av(m) +           &
1296                                          surf_usm_h%rad_net_l(m)
1297                    ENDDO
1298                    DO  l = 0, 3
1299                       DO  m = 1, surf_usm_v(l)%ns
1300                          surf_usm_v(l)%rad_net_av(m) =                        &
1301                                          surf_usm_v(l)%rad_net_av(m) +        &
1302                                          surf_usm_v(l)%rad_net_l(m)
1303                       ENDDO
1304                    ENDDO
1305                   
1306                CASE ( 'usm_rad_insw' )
1307!--                 array of sw radiation falling to surface after i-th reflection
1308                    DO l = startenergy, endenergy
1309                        IF ( surfl(id,l) == ids )  THEN
1310                            surfinsw_av(l) = surfinsw_av(l) + surfinsw(l)
1311                        ENDIF
1312                    ENDDO
1313                             
1314                CASE ( 'usm_rad_inlw' )
1315!--                 array of lw radiation falling to surface after i-th reflection
1316                    DO l = startenergy, endenergy
1317                        IF ( surfl(id,l) == ids )  THEN
1318                            surfinlw_av(l) = surfinlw_av(l) + surfinlw(l)
1319                        ENDIF
1320                    ENDDO
1321                   
1322                CASE ( 'usm_rad_inswdir' )
1323!--                 array of direct sw radiation falling to surface from sun
1324                    DO l = startenergy, endenergy
1325                        IF ( surfl(id,l) == ids )  THEN
1326                            surfinswdir_av(l) = surfinswdir_av(l) + surfinswdir(l)
1327                        ENDIF
1328                    ENDDO
1329                   
1330                CASE ( 'usm_rad_inswdif' )
1331!--                 array of difusion sw radiation falling to surface from sky and borders of the domain
1332                    DO l = startenergy, endenergy
1333                        IF ( surfl(id,l) == ids )  THEN
1334                            surfinswdif_av(l) = surfinswdif_av(l) + surfinswdif(l)
1335                        ENDIF
1336                    ENDDO
1337                   
1338                CASE ( 'usm_rad_inswref' )
1339!--                 array of sw radiation falling to surface from reflections
1340                    DO l = startenergy, endenergy
1341                        IF ( surfl(id,l) == ids )  THEN
1342                            surfinswref_av(l) = surfinswref_av(l) + surfinsw(l) - &
1343                                                surfinswdir(l) - surfinswdif(l)
1344                        ENDIF
1345                    ENDDO
1346
1347                   
1348                CASE ( 'usm_rad_inlwdif' )
1349!--                 array of sw radiation falling to surface after i-th reflection
1350                    DO l = startenergy, endenergy
1351                        IF ( surfl(id,l) == ids )  THEN
1352                            surfinswref_av(l) = surfinswref_av(l) + surfinsw(l) - &
1353                                                surfinswdir(l) - surfinswdif(l)
1354                        ENDIF
1355                    ENDDO
1356!                     
1357                CASE ( 'usm_rad_inlwref' )
1358!--                 array of lw radiation falling to surface from reflections
1359                    DO l = startenergy, endenergy
1360                        IF ( surfl(id,l) == ids )  THEN
1361                            surfinlwdif_av(l) = surfinlwdif_av(l) + surfinlwdif(l)
1362                        ENDIF
1363                    ENDDO
1364                   
1365                CASE ( 'usm_rad_outsw' )
1366!--                 array of sw radiation emitted from surface after i-th reflection
1367                    DO l = startenergy, endenergy
1368                        IF ( surfl(id,l) == ids )  THEN
1369                            surfinlwref_av(l) = surfinlwref_av(l) + &
1370                                                surfinlw(l) - surfinlwdif(l)
1371                        ENDIF
1372                    ENDDO
1373                   
1374                CASE ( 'usm_rad_outlw' )
1375!--                 array of lw radiation emitted from surface after i-th reflection
1376                    DO l = startenergy, endenergy
1377                        IF ( surfl(id,l) == ids )  THEN
1378                            surfoutsw_av(l) = surfoutsw_av(l) + surfoutsw(l)
1379                        ENDIF
1380                    ENDDO
1381                   
1382                CASE ( 'usm_rad_ressw' )
1383!--                 array of residua of sw radiation absorbed in surface after last reflection
1384                    DO l = startenergy, endenergy
1385                        IF ( surfl(id,l) == ids )  THEN
1386                            surfoutlw_av(l) = surfoutlw_av(l) + surfoutlw(l)
1387                        ENDIF
1388                    ENDDO
1389                                   
1390                CASE ( 'usm_rad_reslw' )
1391!--                 array of residua of lw radiation absorbed in surface after last reflection
1392                    DO l = startenergy, endenergy
1393                        IF ( surfl(id,l) == ids )  THEN
1394                            surfins_av(l) = surfins_av(l) + surfins(l)
1395                        ENDIF
1396                    ENDDO
1397                   
1398                CASE ( 'usm_rad_hf' )
1399!--                 array of heat flux from radiation for surfaces after i-th reflection
1400                    DO  m = 1, surf_usm_h%ns
1401                       surf_usm_h%surfhf_av(m) =                               &
1402                                          surf_usm_h%surfhf_av(m) +            &
1403                                          surf_usm_h%surfhf(m)
1404                    ENDDO
1405                    DO  l = 0, 3
1406                       DO  m = 1, surf_usm_v(l)%ns
1407                          surf_usm_v(l)%surfhf_av(m) =                         &
1408                                          surf_usm_v(l)%surfhf_av(m) +         &
1409                                          surf_usm_v(l)%surfhf(m)
1410                       ENDDO
1411                    ENDDO
1412                   
1413                CASE ( 'usm_wshf' )
1414!--                 array of sensible heat flux from surfaces (land, roof, wall)
1415                    DO  m = 1, surf_usm_h%ns
1416                       surf_usm_h%wshf_eb_av(m) =                              &
1417                                          surf_usm_h%wshf_eb_av(m) +           &
1418                                          surf_usm_h%wshf_eb(m)
1419                    ENDDO
1420                    DO  l = 0, 3
1421                       DO  m = 1, surf_usm_v(l)%ns
1422                          surf_usm_v(l)%wshf_eb_av(m) =                        &
1423                                          surf_usm_v(l)%wshf_eb_av(m) +        &
1424                                          surf_usm_v(l)%wshf_eb(m)
1425                       ENDDO
1426                    ENDDO
1427                   
1428                CASE ( 'usm_wghf' )
1429!--                 array of heat flux from ground (wall, roof, land)
1430                    DO  m = 1, surf_usm_h%ns
1431                       surf_usm_h%wghf_eb_av(m) =                              &
1432                                          surf_usm_h%wghf_eb_av(m) +           &
1433                                          surf_usm_h%wghf_eb(m)
1434                    ENDDO
1435                    DO  l = 0, 3
1436                       DO  m = 1, surf_usm_v(l)%ns
1437                          surf_usm_v(l)%wghf_eb_av(m) =                        &
1438                                          surf_usm_v(l)%wghf_eb_av(m) +        &
1439                                          surf_usm_v(l)%wghf_eb(m)
1440                       ENDDO
1441                    ENDDO
1442                   
1443                CASE ( 'usm_t_surf' )
1444!--                 surface temperature for surfaces
1445                    DO  m = 1, surf_usm_h%ns
1446                       surf_usm_h%t_surf_av(m) =                               & 
1447                                          surf_usm_h%t_surf_av(m) +            &
1448                                          t_surf_h(m)
1449                    ENDDO
1450                    DO  l = 0, 3
1451                       DO  m = 1, surf_usm_v(l)%ns
1452                          surf_usm_v(l)%t_surf_av(m) =                         &
1453                                          surf_usm_v(l)%t_surf_av(m) +         &
1454                                          t_surf_v(l)%t(m)
1455                       ENDDO
1456                    ENDDO
1457                   
1458                CASE ( 'usm_t_wall' )
1459!--                 wall temperature for  iwl layer of walls and land
1460                    DO  m = 1, surf_usm_h%ns
1461                       surf_usm_h%t_wall_av(iwl,m) =                           &
1462                                          surf_usm_h%t_wall_av(iwl,m) +        &
1463                                          t_wall_h(iwl,m)
1464                    ENDDO
1465                    DO  l = 0, 3
1466                       DO  m = 1, surf_usm_v(l)%ns
1467                          surf_usm_v(l)%t_wall_av(iwl,m) =                     &
1468                                          surf_usm_v(l)%t_wall_av(iwl,m) +     &
1469                                          t_wall_v(l)%t(iwl,m)
1470                       ENDDO
1471                    ENDDO
1472                   
1473                CASE DEFAULT
1474                    CONTINUE
1475
1476           END SELECT
1477
1478        ELSEIF ( mode == 'average' )  THEN
1479           
1480           SELECT CASE ( TRIM( var ) )
1481               
1482                CASE ( 'usm_rad_net' )
1483!--                 array of complete radiation balance
1484                    DO  m = 1, surf_usm_h%ns
1485                       surf_usm_h%rad_net_av(m) =                              &
1486                                          surf_usm_h%rad_net_av(m) /           &
1487                                          REAL( average_count_3d, kind=wp )
1488                    ENDDO
1489                    DO  l = 0, 3
1490                       DO  m = 1, surf_usm_v(l)%ns
1491                          surf_usm_v(l)%rad_net_av(m) =                        &
1492                                          surf_usm_v(l)%rad_net_av(m) /        &
1493                                          REAL( average_count_3d, kind=wp )
1494                       ENDDO
1495                    ENDDO
1496                   
1497                CASE ( 'usm_rad_insw' )
1498!--                 array of sw radiation falling to surface after i-th reflection
1499                    DO l = startenergy, endenergy
1500                        IF ( surfl(id,l) == ids )  THEN
1501                            surfinsw_av(l) = surfinsw_av(l) / REAL( average_count_3d, kind=wp )
1502                        ENDIF
1503                    ENDDO
1504                             
1505                CASE ( 'usm_rad_inlw' )
1506!--                 array of lw radiation falling to surface after i-th reflection
1507                    DO l = startenergy, endenergy
1508                        IF ( surfl(id,l) == ids )  THEN
1509                            surfinlw_av(l) = surfinlw_av(l) / REAL( average_count_3d, kind=wp )
1510                        ENDIF
1511                    ENDDO
1512                   
1513                CASE ( 'usm_rad_inswdir' )
1514!--                 array of direct sw radiation falling to surface from sun
1515                    DO l = startenergy, endenergy
1516                        IF ( surfl(id,l) == ids )  THEN
1517                            surfinswdir_av(l) = surfinswdir_av(l) / REAL( average_count_3d, kind=wp )
1518                        ENDIF
1519                    ENDDO
1520                   
1521                CASE ( 'usm_rad_inswdif' )
1522!--                 array of difusion sw radiation falling to surface from sky and borders of the domain
1523                    DO l = startenergy, endenergy
1524                        IF ( surfl(id,l) == ids )  THEN
1525                            surfinswdif_av(l) = surfinswdif_av(l) / REAL( average_count_3d, kind=wp )
1526                        ENDIF
1527                    ENDDO
1528                   
1529                CASE ( 'usm_rad_inswref' )
1530!--                 array of sw radiation falling to surface from reflections
1531                    DO l = startenergy, endenergy
1532                        IF ( surfl(id,l) == ids )  THEN
1533                            surfinswref_av(l) = surfinswref_av(l) / REAL( average_count_3d, kind=wp )
1534                        ENDIF
1535                    ENDDO
1536                   
1537                CASE ( 'usm_rad_inlwdif' )
1538!--                 array of sw radiation falling to surface after i-th reflection
1539                    DO l = startenergy, endenergy
1540                        IF ( surfl(id,l) == ids )  THEN
1541                            surfinlwdif_av(l) = surfinlwdif_av(l) / REAL( average_count_3d, kind=wp )
1542                        ENDIF
1543                    ENDDO
1544                   
1545                CASE ( 'usm_rad_inlwref' )
1546!--                 array of lw radiation falling to surface from reflections
1547                    DO l = startenergy, endenergy
1548                        IF ( surfl(id,l) == ids )  THEN
1549                            surfinlwref_av(l) = surfinlwref_av(l) / REAL( average_count_3d, kind=wp )
1550                        ENDIF
1551                    ENDDO
1552                   
1553                CASE ( 'usm_rad_outsw' )
1554!--                 array of sw radiation emitted from surface after i-th reflection
1555                    DO l = startenergy, endenergy
1556                        IF ( surfl(id,l) == ids )  THEN
1557                            surfoutsw_av(l) = surfoutsw_av(l) / REAL( average_count_3d, kind=wp )
1558                        ENDIF
1559                    ENDDO
1560                   
1561                CASE ( 'usm_rad_outlw' )
1562!--                 array of lw radiation emitted from surface after i-th reflection
1563                    DO l = startenergy, endenergy
1564                        IF ( surfl(id,l) == ids )  THEN
1565                            surfoutlw_av(l) = surfoutlw_av(l) / REAL( average_count_3d, kind=wp )
1566                        ENDIF
1567                    ENDDO
1568                   
1569                CASE ( 'usm_rad_ressw' )
1570!--                 array of residua of sw radiation absorbed in surface after last reflection
1571                    DO l = startenergy, endenergy
1572                        IF ( surfl(id,l) == ids )  THEN
1573                            surfins_av(l) = surfins_av(l) / REAL( average_count_3d, kind=wp )
1574                        ENDIF
1575                    ENDDO
1576                                   
1577                CASE ( 'usm_rad_reslw' )
1578!--                 array of residua of lw radiation absorbed in surface after last reflection
1579                    DO l = startenergy, endenergy
1580                        IF ( surfl(id,l) == ids )  THEN
1581                            surfinl_av(l) = surfinl_av(l) / REAL( average_count_3d, kind=wp )
1582                        ENDIF
1583                    ENDDO
1584                   
1585                CASE ( 'usm_rad_hf' )
1586!--                 array of heat flux from radiation for surfaces after i-th reflection
1587                    DO  m = 1, surf_usm_h%ns
1588                       surf_usm_h%surfhf_av(m) =                               &
1589                                          surf_usm_h%surfhf_av(m) /            &
1590                                          REAL( average_count_3d, kind=wp )
1591                    ENDDO
1592                    DO  l = 0, 3
1593                       DO  m = 1, surf_usm_v(l)%ns
1594                          surf_usm_v(l)%surfhf_av(m) =                         &
1595                                          surf_usm_v(l)%surfhf_av(m) /         &
1596                                          REAL( average_count_3d, kind=wp )
1597                       ENDDO
1598                    ENDDO
1599                   
1600                CASE ( 'usm_wshf' )
1601!--                 array of sensible heat flux from surfaces (land, roof, wall)
1602                    DO  m = 1, surf_usm_h%ns
1603                       surf_usm_h%wshf_eb_av(m) =                              &
1604                                          surf_usm_h%wshf_eb_av(m) /           &
1605                                          REAL( average_count_3d, kind=wp )
1606                    ENDDO
1607                    DO  l = 0, 3
1608                       DO  m = 1, surf_usm_v(l)%ns
1609                          surf_usm_v(l)%wshf_eb_av(m) =                        &
1610                                          surf_usm_v(l)%wshf_eb_av(m) /        &
1611                                          REAL( average_count_3d, kind=wp )
1612                       ENDDO
1613                    ENDDO
1614                   
1615                CASE ( 'usm_wghf' )
1616!--                 array of heat flux from ground (wall, roof, land)
1617                    DO  m = 1, surf_usm_h%ns
1618                       surf_usm_h%wghf_eb_av(m) =                              &
1619                                          surf_usm_h%wghf_eb_av(m) /           &
1620                                          REAL( average_count_3d, kind=wp )
1621                    ENDDO
1622                    DO  l = 0, 3
1623                       DO  m = 1, surf_usm_v(l)%ns
1624                          surf_usm_v(l)%wghf_eb_av(m) =                        &
1625                                          surf_usm_v(l)%wghf_eb_av(m) /        &
1626                                          REAL( average_count_3d, kind=wp )
1627                       ENDDO
1628                    ENDDO
1629                   
1630                CASE ( 'usm_t_surf' )
1631!--                 surface temperature for surfaces
1632                    DO  m = 1, surf_usm_h%ns
1633                       surf_usm_h%t_surf_av(m) =                               & 
1634                                          surf_usm_h%t_surf_av(m) /            &
1635                                          REAL( average_count_3d, kind=wp )
1636                    ENDDO
1637                    DO  l = 0, 3
1638                       DO  m = 1, surf_usm_v(l)%ns
1639                          surf_usm_v(l)%t_surf_av(m) =                         &
1640                                          surf_usm_v(l)%t_surf_av(m) /         &
1641                                          REAL( average_count_3d, kind=wp )
1642                       ENDDO
1643                    ENDDO
1644                   
1645                CASE ( 'usm_t_wall' )
1646!--                 wall temperature for  iwl layer of walls and land
1647                    DO  m = 1, surf_usm_h%ns
1648                       surf_usm_h%t_wall_av(iwl,m) =                           &
1649                                          surf_usm_h%t_wall_av(iwl,m) /        &
1650                                          REAL( average_count_3d, kind=wp )
1651                    ENDDO
1652                    DO  l = 0, 3
1653                       DO  m = 1, surf_usm_v(l)%ns
1654                          surf_usm_v(l)%t_wall_av(iwl,m) =                     &
1655                                          surf_usm_v(l)%t_wall_av(iwl,m) /     &
1656                                          REAL( average_count_3d, kind=wp )
1657                       ENDDO
1658                    ENDDO
1659
1660           END SELECT
1661
1662        ENDIF
1663
1664    END SUBROUTINE usm_average_3d_data
1665
1666
1667!------------------------------------------------------------------------------!
1668!> Calculates radiation absorbed by box with given size and LAD.
1669!>
1670!> Simulates resol**2 rays (by equally spacing a bounding horizontal square
1671!> conatining all possible rays that would cross the box) and calculates
1672!> average transparency per ray. Returns fraction of absorbed radiation flux
1673!> and area for which this fraction is effective.
1674!------------------------------------------------------------------------------!
1675    PURE SUBROUTINE usm_box_absorb(boxsize, resol, dens, uvec, area, absorb)
1676        IMPLICIT NONE
1677
1678        REAL(wp), DIMENSION(3), INTENT(in) :: &
1679            boxsize, &      !< z, y, x size of box in m
1680            uvec            !< z, y, x unit vector of incoming flux
1681        INTEGER(iwp), INTENT(in) :: &
1682            resol           !< No. of rays in x and y dimensions
1683        REAL(wp), INTENT(in) :: &
1684            dens            !< box density (e.g. Leaf Area Density)
1685        REAL(wp), INTENT(out) :: &
1686            area, &         !< horizontal area for flux absorbtion
1687            absorb          !< fraction of absorbed flux
1688        REAL(wp) :: &
1689            xshift, yshift, &
1690            xmin, xmax, ymin, ymax, &
1691            xorig, yorig, &
1692            dx1, dy1, dz1, dx2, dy2, dz2, &
1693            crdist, &
1694            transp
1695        INTEGER(iwp) :: &
1696            i, j
1697
1698        xshift = uvec(3) / uvec(1) * boxsize(1)
1699        xmin = min(0._wp, -xshift)
1700        xmax = boxsize(3) + max(0._wp, -xshift)
1701        yshift = uvec(2) / uvec(1) * boxsize(1)
1702        ymin = min(0._wp, -yshift)
1703        ymax = boxsize(2) + max(0._wp, -yshift)
1704
1705        transp = 0._wp
1706        DO i = 1, resol
1707            xorig = xmin + (xmax-xmin) * (i-.5_wp) / resol
1708            DO j = 1, resol
1709                yorig = ymin + (ymax-ymin) * (j-.5_wp) / resol
1710
1711                dz1 = 0._wp
1712                dz2 = boxsize(1)/uvec(1)
1713
1714                IF ( uvec(2) > 0._wp )  THEN
1715                    dy1 = -yorig             / uvec(2) !< crossing with y=0
1716                    dy2 = (boxsize(2)-yorig) / uvec(2) !< crossing with y=boxsize(2)
1717                ELSE IF ( uvec(2) < 0._wp )  THEN
1718                    dy1 = (boxsize(2)-yorig) / uvec(2) !< crossing with y=boxsize(2)
1719                    dy2 = -yorig             / uvec(2) !< crossing with y=0
1720                ELSE !uvec(2)==0
1721                    dy1 = -huge(1._wp)
1722                    dy2 = huge(1._wp)
1723                ENDIF
1724
1725                IF ( uvec(3) > 0._wp )  THEN
1726                    dx1 = -xorig             / uvec(3) !< crossing with x=0
1727                    dx2 = (boxsize(3)-xorig) / uvec(3) !< crossing with x=boxsize(3)
1728                ELSE IF ( uvec(3) < 0._wp )  THEN
1729                    dx1 = (boxsize(3)-xorig) / uvec(3) !< crossing with x=boxsize(3)
1730                    dx2 = -xorig             / uvec(3) !< crossing with x=0
1731                ELSE !uvec(1)==0
1732                    dx1 = -huge(1._wp)
1733                    dx2 = huge(1._wp)
1734                ENDIF
1735
1736                crdist = max(0._wp, (min(dz2, dy2, dx2) - max(dz1, dy1, dx1)))
1737                transp = transp + exp(-ext_coef * dens * crdist)
1738            ENDDO
1739        ENDDO
1740        transp = transp / resol**2
1741        area = (boxsize(3)+xshift)*(boxsize(2)+yshift)
1742        absorb = 1._wp - transp
1743       
1744    END SUBROUTINE usm_box_absorb
1745   
1746   
1747!------------------------------------------------------------------------------!
1748! Description:
1749! ------------
1750!> This subroutine splits direct and diffusion dw radiation
1751!> It sould not be called in case the radiation model already does it
1752!> It follows <CITATION>
1753!------------------------------------------------------------------------------!
1754    SUBROUTINE usm_calc_diffusion_radiation 
1755   
1756        REAL(wp), PARAMETER                          ::  sol_const = 1367.0_wp   !< solar conbstant
1757        REAL(wp), PARAMETER                          :: lowest_solarUp = 0.1_wp  !< limit the sun elevation to protect stability of the calculation
1758        INTEGER(iwp)                                 :: i, j
1759        REAL(wp), PARAMETER                          ::  year_seconds = 86400._wp * 365._wp
1760        REAL(wp)                                     ::  year_angle              !< angle
1761        REAL(wp)                                     ::  etr                     !< extraterestrial radiation
1762        REAL(wp)                                     ::  corrected_solarUp       !< corrected solar up radiation
1763        REAL(wp)                                     ::  horizontalETR           !< horizontal extraterestrial radiation
1764        REAL(wp)                                     ::  clearnessIndex          !< clearness index
1765        REAL(wp)                                     ::  diff_frac               !< diffusion fraction of the radiation
1766
1767       
1768!--     Calculate current day and time based on the initial values and simulation time
1769        year_angle = ((day_init*86400) + time_utc_init+time_since_reference_point) &
1770                       / year_seconds * 2.0_wp * pi
1771       
1772        etr = sol_const * (1.00011_wp +                                            &
1773                          0.034221_wp * cos(year_angle) +                          &
1774                          0.001280_wp * sin(year_angle) +                          &
1775                          0.000719_wp * cos(2.0_wp * year_angle) +                 &
1776                          0.000077_wp * sin(2.0_wp * year_angle))
1777       
1778!--   
1779!--     Under a very low angle, we keep extraterestrial radiation at
1780!--     the last small value, therefore the clearness index will be pushed
1781!--     towards 0 while keeping full continuity.
1782!--   
1783        IF ( zenith(0) <= lowest_solarUp )  THEN
1784            corrected_solarUp = lowest_solarUp
1785        ELSE
1786            corrected_solarUp = zenith(0)
1787        ENDIF
1788       
1789        horizontalETR = etr * corrected_solarUp
1790       
1791        DO i = nxlg, nxrg
1792            DO j = nysg, nyng
1793                clearnessIndex = rad_sw_in(0,j,i) / horizontalETR
1794                diff_frac = 1.0_wp / (1.0_wp + exp(-5.0033_wp + 8.6025_wp * clearnessIndex))
1795                rad_sw_in_diff(j,i) = rad_sw_in(0,j,i) * diff_frac
1796                rad_sw_in_dir(j,i)  = rad_sw_in(0,j,i) * (1.0_wp - diff_frac)
1797                rad_lw_in_diff(j,i) = rad_lw_in(0,j,i)
1798            ENDDO
1799        ENDDO
1800       
1801    END SUBROUTINE usm_calc_diffusion_radiation
1802   
1803
1804!------------------------------------------------------------------------------!
1805! Description:
1806! ------------
1807!> Calculates shape view factors SVF and plant sink canopy factors PSCF
1808!> !!!!!DESCRIPTION!!!!!!!!!!
1809!------------------------------------------------------------------------------!
1810    SUBROUTINE usm_calc_svf
1811   
1812        IMPLICIT NONE
1813       
1814        INTEGER(iwp)                                :: i, j, k, l, d, ip, jp
1815        INTEGER(iwp)                                :: isvf, ksvf, icsf, kcsf, npcsfl, isvf_surflt, imrtt, imrtf
1816        INTEGER(iwp)                                :: sd, td, ioln, iproc
1817        REAL(wp),     DIMENSION(0:9)                :: facearea
1818        INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE   :: nzterrl, planthl
1819        REAL(wp),     DIMENSION(:,:), ALLOCATABLE   :: csflt, pcsflt
1820        INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE   :: kcsflt,kpcsflt
1821        INTEGER(iwp), DIMENSION(:), ALLOCATABLE     :: icsflt,dcsflt,ipcsflt,dpcsflt
1822        REAL(wp), DIMENSION(3)                      :: uv
1823        LOGICAL                                     :: visible
1824        REAL(wp), DIMENSION(3)                      :: sa, ta          !< real coordinates z,y,x of source and target
1825        REAL(wp)                                    :: transparency, rirrf, sqdist, svfsum
1826        INTEGER(iwp)                                :: isurflt, isurfs, isurflt_prev
1827        INTEGER(iwp)                                :: itx, ity, itz
1828        CHARACTER(len=7)                            :: pid_char = ''
1829        INTEGER(iwp)                                :: win_lad, minfo
1830        REAL(wp), DIMENSION(:,:,:), POINTER         :: lad_s_rma       !< fortran pointer, but lower bounds are 1
1831        TYPE(c_ptr)                                 :: lad_s_rma_p     !< allocated c pointer
1832#if defined( __parallel )
1833        INTEGER(kind=MPI_ADDRESS_KIND)              :: size_lad_rma
1834#endif
1835!   
1836!--     calculation of the SVF
1837        CALL location_message( '    calculation of SVF and CSF', .TRUE. )
1838!
1839!--     precalculate face areas for different face directions using normal vector
1840        DO d = 0, 9
1841            facearea(d) = 1._wp
1842            IF ( idir(d) == 0 ) facearea(d) = facearea(d) * dx
1843            IF ( jdir(d) == 0 ) facearea(d) = facearea(d) * dy
1844            IF ( kdir(d) == 0 ) facearea(d) = facearea(d) * dz
1845        ENDDO
1846
1847!--     initialize variables and temporary arrays for calculation of svf and csf
1848        nsvfl  = 0
1849        ncsfl  = 0
1850        nsvfla = gasize
1851        msvf   = 1
1852        ALLOCATE( asvf1(nsvfla) )
1853        asvf => asvf1
1854        IF ( plant_canopy )  THEN
1855            ncsfla = gasize
1856            mcsf   = 1
1857            ALLOCATE( acsf1(ncsfla) )
1858            acsf => acsf1
1859        ENDIF
1860       
1861!--     initialize temporary terrain and plant canopy height arrays (global 2D array!)
1862        ALLOCATE( nzterr(0:(nx+1)*(ny+1)-1) )
1863#if defined( __parallel )
1864        ALLOCATE( nzterrl(nys:nyn,nxl:nxr) )
1865        nzterrl = MAXLOC(                                                      &
1866                          MERGE( 1, 0,                                         &
1867                                 BTEST( wall_flags_0(:,nys:nyn,nxl:nxr), 12 )  &
1868                               ), DIM = 1                                      &
1869                        ) - 1  ! = nzb_s_inner(nys:nyn,nxl:nxr)
1870        CALL MPI_AllGather( nzterrl, nnx*nny, MPI_INTEGER, &
1871                            nzterr, nnx*nny, MPI_INTEGER, comm2d, ierr )
1872        DEALLOCATE(nzterrl)
1873#else
1874        nzterr = RESHAPE( MAXLOC(                                              &
1875                          MERGE( 1, 0,                                         &
1876                                 BTEST( wall_flags_0(:,nys:nyn,nxl:nxr), 12 )  &
1877                               ), DIM = 1                                      &
1878                                ) - 1,                                         &
1879                          (/(nx+1)*(ny+1)/)                                    &
1880                        )
1881#endif
1882        IF ( plant_canopy )  THEN
1883            ALLOCATE( plantt(0:(nx+1)*(ny+1)-1) )
1884            maxboxesg = nx + ny + nzu + 1
1885!--         temporary arrays storing values for csf calculation during raytracing
1886            ALLOCATE( boxes(3, maxboxesg) )
1887            ALLOCATE( crlens(maxboxesg) )
1888
1889#if defined( __parallel )
1890            ALLOCATE( planthl(nys:nyn,nxl:nxr) )
1891            planthl = pch(nys:nyn,nxl:nxr)
1892       
1893            CALL MPI_AllGather( planthl, nnx*nny, MPI_INTEGER, &
1894                                plantt, nnx*nny, MPI_INTEGER, comm2d, ierr )
1895            DEALLOCATE( planthl )
1896           
1897!--         temporary arrays storing values for csf calculation during raytracing
1898            ALLOCATE( lad_ip(maxboxesg) )
1899            ALLOCATE( lad_disp(maxboxesg) )
1900
1901            IF ( usm_lad_rma )  THEN
1902                ALLOCATE( lad_s_ray(maxboxesg) )
1903               
1904                ! set conditions for RMA communication
1905                CALL MPI_Info_create(minfo, ierr)
1906                CALL MPI_Info_set(minfo, 'accumulate_ordering', '', ierr)
1907                CALL MPI_Info_set(minfo, 'accumulate_ops', 'same_op', ierr)
1908                CALL MPI_Info_set(minfo, 'same_size', 'true', ierr)
1909                CALL MPI_Info_set(minfo, 'same_disp_unit', 'true', ierr)
1910
1911!--             Allocate and initialize the MPI RMA window
1912!--             must be in accordance with allocation of lad_s in plant_canopy_model
1913!--             optimization of memory should be done
1914!--             Argument X of function c_sizeof(X) needs arbitrary REAL(wp) value, set to 1.0_wp for now
1915                size_lad_rma = c_sizeof(1.0_wp)*nnx*nny*nzu
1916                CALL MPI_Win_allocate(size_lad_rma, c_sizeof(1.0_wp), minfo, comm2d, &
1917                                        lad_s_rma_p, win_lad, ierr)
1918                CALL c_f_pointer(lad_s_rma_p, lad_s_rma, (/ nzu, nny, nnx /))
1919                usm_lad(nzub:, nys:, nxl:) => lad_s_rma(:,:,:)
1920            ELSE
1921                ALLOCATE(usm_lad(nzub:nzut, nys:nyn, nxl:nxr))
1922            ENDIF
1923#else
1924            plantt = RESHAPE( pct(nys:nyn,nxl:nxr), (/(nx+1)*(ny+1)/) )
1925            ALLOCATE(usm_lad(nzub:nzut, nys:nyn, nxl:nxr))
1926#endif
1927            usm_lad(:,:,:) = 0._wp
1928            DO i = nxl, nxr
1929                DO j = nys, nyn
1930                    k = get_topography_top_index( j, i, 's' )
1931
1932                    usm_lad(k:nzut, j, i) = lad_s(0:nzut-k, j, i)
1933                ENDDO
1934            ENDDO
1935
1936#if defined( __parallel )
1937            IF ( usm_lad_rma )  THEN
1938                CALL MPI_Info_free(minfo, ierr)
1939                CALL MPI_Win_lock_all(0, win_lad, ierr)
1940            ELSE
1941                ALLOCATE( usm_lad_g(0:(nx+1)*(ny+1)*nzu-1) )
1942                CALL MPI_AllGather( usm_lad, nnx*nny*nzu, MPI_REAL, &
1943                                    usm_lad_g, nnx*nny*nzu, MPI_REAL, comm2d, ierr )
1944            ENDIF
1945#endif
1946        ENDIF
1947
1948        IF ( mrt_factors )  THEN
1949            OPEN(153, file='MRT_TARGETS', access='SEQUENTIAL', &
1950                    action='READ', status='OLD', form='FORMATTED', err=524)
1951            OPEN(154, file='MRT_FACTORS'//myid_char, access='DIRECT', recl=(5*4+2*8), &
1952                    action='WRITE', status='REPLACE', form='UNFORMATTED', err=525)
1953            imrtf = 1
1954            DO
1955                READ(153, *, end=526, err=524) imrtt, i, j, k
1956                IF ( i < nxl  .OR.  i > nxr &
1957                     .OR.  j < nys  .OR.  j > nyn ) CYCLE
1958                ta = (/ REAL(k), REAL(j), REAL(i) /)
1959
1960                DO isurfs = 1, nsurf
1961                    IF ( .NOT.  usm_facing(i, j, k, -1, &
1962                        surf(ix, isurfs), surf(iy, isurfs), &
1963                        surf(iz, isurfs), surf(id, isurfs)) )  THEN
1964                        CYCLE
1965                    ENDIF
1966                     
1967                    sd = surf(id, isurfs)
1968                    sa = (/ REAL(surf(iz, isurfs), wp) - 0.5_wp * kdir(sd), &
1969                            REAL(surf(iy, isurfs), wp) - 0.5_wp * jdir(sd), &
1970                            REAL(surf(ix, isurfs), wp) - 0.5_wp * idir(sd) /)
1971
1972!--                 unit vector source -> target
1973                    uv = (/ (ta(1)-sa(1))*dz, (ta(2)-sa(2))*dy, (ta(3)-sa(3))*dx /)
1974                    sqdist = SUM(uv(:)**2)
1975                    uv = uv / SQRT(sqdist)
1976
1977!--                 irradiance factor - see svf. Here we consider that target face is always normal,
1978!--                 i.e. the second dot product equals 1
1979                    rirrf = dot_product((/ kdir(sd), jdir(sd), idir(sd) /), uv) &
1980                        / (pi * sqdist) * facearea(sd)
1981
1982!--                 raytrace while not creating any canopy sink factors
1983                    CALL usm_raytrace(sa, ta, isurfs, rirrf, 1._wp, .FALSE., &
1984                            visible, transparency, win_lad)
1985                    IF ( .NOT.  visible ) CYCLE
1986
1987                    !rsvf = rirrf * transparency
1988                    WRITE(154, rec=imrtf, err=525) INT(imrtt, kind=4), &
1989                        INT(surf(id, isurfs), kind=4), &
1990                        INT(surf(iz, isurfs), kind=4), &
1991                        INT(surf(iy, isurfs), kind=4), &
1992                        INT(surf(ix, isurfs), kind=4), &
1993                        REAL(rirrf, kind=8), REAL(transparency, kind=8)
1994                    imrtf = imrtf + 1
1995
1996                ENDDO !< isurfs
1997            ENDDO !< MRT_TARGETS record
1998
1999524         message_string = 'error reading file MRT_TARGETS'
2000            CALL message( 'usm_calc_svf', 'PA0524', 1, 2, 0, 6, 0 )
2001
2002525         message_string = 'error writing file MRT_FACTORS'//myid_char
2003            CALL message( 'usm_calc_svf', 'PA0525', 1, 2, 0, 6, 0 )
2004
2005526         CLOSE(153)
2006            CLOSE(154)
2007        ENDIF  !< mrt_factors
2008
2009       
2010        DO isurflt = 1, nsurfl
2011!--         determine face centers
2012            td = surfl(id, isurflt)
2013            IF ( td >= isky  .AND.  .NOT.  plant_canopy ) CYCLE
2014            ta = (/ REAL(surfl(iz, isurflt), wp) - 0.5_wp * kdir(td),  &
2015                      REAL(surfl(iy, isurflt), wp) - 0.5_wp * jdir(td),  &
2016                      REAL(surfl(ix, isurflt), wp) - 0.5_wp * idir(td)  /)
2017            DO isurfs = 1, nsurf
2018                IF ( .NOT.  usm_facing(surfl(ix, isurflt), surfl(iy, isurflt), &
2019                    surfl(iz, isurflt), surfl(id, isurflt), &
2020                    surf(ix, isurfs), surf(iy, isurfs), &
2021                    surf(iz, isurfs), surf(id, isurfs)) )  THEN
2022                    CYCLE
2023                ENDIF
2024                 
2025                sd = surf(id, isurfs)
2026                sa = (/ REAL(surf(iz, isurfs), wp) - 0.5_wp * kdir(sd),  &
2027                        REAL(surf(iy, isurfs), wp) - 0.5_wp * jdir(sd),  &
2028                        REAL(surf(ix, isurfs), wp) - 0.5_wp * idir(sd)  /)
2029
2030!--             unit vector source -> target
2031                uv = (/ (ta(1)-sa(1))*dz, (ta(2)-sa(2))*dy, (ta(3)-sa(3))*dx /)
2032                sqdist = SUM(uv(:)**2)
2033                uv = uv / SQRT(sqdist)
2034               
2035!--             irradiance factor (our unshaded shape view factor) = view factor per differential target area * source area
2036                rirrf = dot_product((/ kdir(sd), jdir(sd), idir(sd) /), uv) & ! cosine of source normal and direction
2037                    * dot_product((/ kdir(td), jdir(td), idir(td) /), -uv) &  ! cosine of target normal and reverse direction
2038                    / (pi * sqdist) & ! square of distance between centers
2039                    * facearea(sd)
2040
2041!--             raytrace + process plant canopy sinks within
2042                CALL usm_raytrace(sa, ta, isurfs, rirrf, facearea(td), .TRUE., &
2043                        visible, transparency, win_lad)
2044               
2045                IF ( .NOT.  visible ) CYCLE
2046                IF ( td >= isky ) CYCLE !< we calculated these only for raytracing
2047                                        !< to find plant canopy sinks, we don't need svf for them
2048                ! rsvf = rirrf * transparency
2049
2050!--             write to the svf array
2051                nsvfl = nsvfl + 1
2052!--             check dimmension of asvf array and enlarge it if needed
2053                IF ( nsvfla < nsvfl )  THEN
2054                    k = nsvfla * 2
2055                    IF ( msvf == 0 )  THEN
2056                        msvf = 1
2057                        ALLOCATE( asvf1(k) )
2058                        asvf => asvf1
2059                        asvf1(1:nsvfla) = asvf2
2060                        DEALLOCATE( asvf2 )
2061                    ELSE
2062                        msvf = 0
2063                        ALLOCATE( asvf2(k) )
2064                        asvf => asvf2
2065                        asvf2(1:nsvfla) = asvf1
2066                        DEALLOCATE( asvf1 )
2067                    ENDIF
2068                    nsvfla = k
2069                ENDIF
2070!--             write svf values into the array
2071                asvf(nsvfl)%isurflt = isurflt
2072                asvf(nsvfl)%isurfs = isurfs
2073                asvf(nsvfl)%rsvf = rirrf !we postopne multiplication by transparency
2074                asvf(nsvfl)%rtransp = transparency !a.k.a. Direct Irradiance Factor
2075            ENDDO
2076        ENDDO
2077
2078        CALL location_message( '    waiting for completion of SVF and CSF calculation in all processes', .TRUE. )
2079!--     deallocate temporary global arrays
2080        DEALLOCATE(nzterr)
2081       
2082        IF ( plant_canopy )  THEN
2083!--         finalize mpi_rma communication and deallocate temporary arrays
2084#if defined( __parallel )
2085            IF ( usm_lad_rma )  THEN
2086                CALL MPI_Win_flush_all(win_lad, ierr)
2087!--             unlock MPI window
2088                CALL MPI_Win_unlock_all(win_lad, ierr)
2089!--             free MPI window
2090                CALL MPI_Win_free(win_lad, ierr)
2091               
2092!--             deallocate temporary arrays storing values for csf calculation during raytracing
2093                DEALLOCATE( lad_s_ray )
2094!--             usm_lad is the pointer to lad_s_rma in case of usm_lad_rma
2095!--             and must not be deallocated here
2096            ELSE
2097                DEALLOCATE(usm_lad)
2098                DEALLOCATE(usm_lad_g)
2099            ENDIF
2100#else
2101            DEALLOCATE(usm_lad)
2102#endif
2103            DEALLOCATE( boxes )
2104            DEALLOCATE( crlens )
2105            DEALLOCATE( plantt )
2106        ENDIF
2107
2108        CALL location_message( '    calculation of the complete SVF array', .TRUE. )
2109
2110!--     sort svf ( a version of quicksort )
2111        CALL quicksort_svf(asvf,1,nsvfl)
2112
2113        ALLOCATE( svf(ndsvf,nsvfl) )
2114        ALLOCATE( svfsurf(idsvf,nsvfl) )
2115
2116        !< load svf from the structure array to plain arrays
2117        isurflt_prev = -1
2118        ksvf = 1
2119        svfsum = 0._wp
2120        DO isvf = 1, nsvfl
2121!--         normalize svf per target face
2122            IF ( asvf(ksvf)%isurflt /= isurflt_prev )  THEN
2123                IF ( isurflt_prev /= -1  .AND.  svfsum /= 0._wp )  THEN
2124!--                 TODO detect and log when normalization differs too much from 1
2125                    svf(1, isvf_surflt:isvf-1) = svf(1, isvf_surflt:isvf-1) / svfsum
2126                ENDIF
2127                isurflt_prev = asvf(ksvf)%isurflt
2128                isvf_surflt = isvf
2129                svfsum = asvf(ksvf)%rsvf !?? / asvf(ksvf)%rtransp
2130            ELSE
2131                svfsum = svfsum + asvf(ksvf)%rsvf !?? / asvf(ksvf)%rtransp
2132            ENDIF
2133
2134            svf(:, isvf) = (/ asvf(ksvf)%rsvf, asvf(ksvf)%rtransp /)
2135            svfsurf(:, isvf) = (/ asvf(ksvf)%isurflt, asvf(ksvf)%isurfs /)
2136
2137!--         next element
2138            ksvf = ksvf + 1
2139        ENDDO
2140
2141        IF ( isurflt_prev /= -1  .AND.  svfsum /= 0._wp )  THEN
2142!--         TODO detect and log when normalization differs too much from 1
2143            svf(1, isvf_surflt:nsvfl) = svf(1, isvf_surflt:nsvfl) / svfsum
2144        ENDIF
2145
2146!--     deallocate temporary asvf array
2147!--     DEALLOCATE(asvf) - ifort has a problem with deallocation of allocatable target
2148!--     via pointing pointer - we need to test original targets
2149        IF ( ALLOCATED(asvf1) )  THEN
2150            DEALLOCATE(asvf1)
2151        ENDIF
2152        IF ( ALLOCATED(asvf2) )  THEN
2153            DEALLOCATE(asvf2)
2154        ENDIF
2155
2156        npcsfl = 0
2157        IF ( plant_canopy )  THEN
2158
2159            CALL location_message( '    calculation of the complete CSF array', .TRUE. )
2160
2161!--         sort and merge csf for the last time, keeping the array size to minimum
2162            CALL usm_merge_and_grow_csf(-1)
2163           
2164!--         aggregate csb among processors
2165!--         allocate necessary arrays
2166            ALLOCATE( csflt(ndcsf,max(ncsfl,ndcsf)) )
2167            ALLOCATE( kcsflt(kdcsf,max(ncsfl,kdcsf)) )
2168            ALLOCATE( icsflt(0:numprocs-1) )
2169            ALLOCATE( dcsflt(0:numprocs-1) )
2170            ALLOCATE( ipcsflt(0:numprocs-1) )
2171            ALLOCATE( dpcsflt(0:numprocs-1) )
2172           
2173!--         fill out arrays of csf values and
2174!--         arrays of number of elements and displacements
2175!--         for particular precessors
2176            icsflt = 0
2177            dcsflt = 0
2178            ip = -1
2179            j = -1
2180            d = 0
2181            DO kcsf = 1, ncsfl
2182                j = j+1
2183                IF ( acsf(kcsf)%ip /= ip )  THEN
2184!--                 new block of the processor
2185!--                 number of elements of previous block
2186                    IF ( ip>=0) icsflt(ip) = j
2187                    d = d+j
2188!--                 blank blocks
2189                    DO jp = ip+1, acsf(kcsf)%ip-1
2190!--                     number of elements is zero, displacement is equal to previous
2191                        icsflt(jp) = 0
2192                        dcsflt(jp) = d
2193                    ENDDO
2194!--                 the actual block
2195                    ip = acsf(kcsf)%ip
2196                    dcsflt(ip) = d
2197                    j = 0
2198                ENDIF
2199!--             fill out real values of rsvf, rtransp
2200                csflt(1,kcsf) = acsf(kcsf)%rsvf
2201                csflt(2,kcsf) = acsf(kcsf)%rtransp
2202!--             fill out integer values of itz,ity,itx,isurfs
2203                kcsflt(1,kcsf) = acsf(kcsf)%itz
2204                kcsflt(2,kcsf) = acsf(kcsf)%ity
2205                kcsflt(3,kcsf) = acsf(kcsf)%itx
2206                kcsflt(4,kcsf) = acsf(kcsf)%isurfs
2207            ENDDO
2208!--         last blank blocks at the end of array
2209            j = j+1
2210            IF ( ip>=0 ) icsflt(ip) = j
2211            d = d+j
2212            DO jp = ip+1, numprocs-1
2213!--             number of elements is zero, displacement is equal to previous
2214                icsflt(jp) = 0
2215                dcsflt(jp) = d
2216            ENDDO
2217           
2218!--         deallocate temporary acsf array
2219!--         DEALLOCATE(acsf) - ifort has a problem with deallocation of allocatable target
2220!--         via pointing pointer - we need to test original targets
2221            IF ( ALLOCATED(acsf1) )  THEN
2222                DEALLOCATE(acsf1)
2223            ENDIF
2224            IF ( ALLOCATED(acsf2) )  THEN
2225                DEALLOCATE(acsf2)
2226            ENDIF
2227                   
2228#if defined( __parallel )
2229!--         scatter and gather the number of elements to and from all processor
2230!--         and calculate displacements
2231            CALL MPI_AlltoAll(icsflt,1,MPI_INTEGER,ipcsflt,1,MPI_INTEGER,comm2d, ierr)
2232           
2233            npcsfl = SUM(ipcsflt)
2234            d = 0
2235            DO i = 0, numprocs-1
2236                dpcsflt(i) = d
2237                d = d + ipcsflt(i)
2238            ENDDO
2239       
2240!--         exchange csf fields between processors
2241            ALLOCATE( pcsflt(ndcsf,max(npcsfl,ndcsf)) )
2242            ALLOCATE( kpcsflt(kdcsf,max(npcsfl,kdcsf)) )
2243            CALL MPI_AlltoAllv(csflt, ndcsf*icsflt, ndcsf*dcsflt, MPI_REAL, &
2244                pcsflt, ndcsf*ipcsflt, ndcsf*dpcsflt, MPI_REAL, comm2d, ierr)
2245            CALL MPI_AlltoAllv(kcsflt, kdcsf*icsflt, kdcsf*dcsflt, MPI_INTEGER, &
2246                kpcsflt, kdcsf*ipcsflt, kdcsf*dpcsflt, MPI_INTEGER, comm2d, ierr)
2247           
2248#else
2249            npcsfl = ncsfl
2250            ALLOCATE( pcsflt(ndcsf,max(npcsfl,ndcsf)) )
2251            ALLOCATE( kpcsflt(kdcsf,max(npcsfl,kdcsf)) )
2252            pcsflt = csflt
2253            kpcsflt = kcsflt
2254#endif
2255
2256!--         deallocate temporary arrays
2257            DEALLOCATE( csflt )
2258            DEALLOCATE( kcsflt )
2259            DEALLOCATE( icsflt )
2260            DEALLOCATE( dcsflt )
2261            DEALLOCATE( ipcsflt )
2262            DEALLOCATE( dpcsflt )
2263
2264!--         sort csf ( a version of quicksort )
2265            CALL quicksort_csf2(kpcsflt, pcsflt, 1, npcsfl)
2266
2267!--         aggregate canopy sink factor records with identical box & source
2268!--         againg across all values from all processors
2269            IF ( npcsfl > 0 )  THEN
2270                icsf = 1 !< reading index
2271                kcsf = 1 !< writing index
2272                DO while (icsf < npcsfl)
2273!--                 here kpcsf(kcsf) already has values from kpcsf(icsf)
2274                    IF ( kpcsflt(3,icsf) == kpcsflt(3,icsf+1)  .AND.  &
2275                         kpcsflt(2,icsf) == kpcsflt(2,icsf+1)  .AND.  &
2276                         kpcsflt(1,icsf) == kpcsflt(1,icsf+1)  .AND.  &
2277                         kpcsflt(4,icsf) == kpcsflt(4,icsf+1) )  THEN
2278!--                     We could simply take either first or second rtransp, both are valid. As a very simple heuristic about which ray
2279!--                     probably passes nearer the center of the target box, we choose DIF from the entry with greater CSF, since that
2280!--                     might mean that the traced beam passes longer through the canopy box.
2281                        IF ( pcsflt(1,kcsf) < pcsflt(1,icsf+1) )  THEN
2282                            pcsflt(2,kcsf) = pcsflt(2,icsf+1)
2283                        ENDIF
2284                        pcsflt(1,kcsf) = pcsflt(1,kcsf) + pcsflt(1,icsf+1)
2285
2286!--                     advance reading index, keep writing index
2287                        icsf = icsf + 1
2288                    ELSE
2289!--                     not identical, just advance and copy
2290                        icsf = icsf + 1
2291                        kcsf = kcsf + 1
2292                        kpcsflt(:,kcsf) = kpcsflt(:,icsf)
2293                        pcsflt(:,kcsf) = pcsflt(:,icsf)
2294                    ENDIF
2295                ENDDO
2296!--             last written item is now also the last item in valid part of array
2297                npcsfl = kcsf
2298            ENDIF
2299
2300            ncsfl = npcsfl
2301            IF ( ncsfl > 0 )  THEN
2302                ALLOCATE( csf(ndcsf,ncsfl) )
2303                ALLOCATE( csfsurf(idcsf,ncsfl) )
2304                DO icsf = 1, ncsfl
2305                    csf(:,icsf) = pcsflt(:,icsf)
2306                    csfsurf(1,icsf) =  gridpcbl(kpcsflt(1,icsf),kpcsflt(2,icsf),kpcsflt(3,icsf))
2307                    csfsurf(2,icsf) =  kpcsflt(4,icsf)
2308                ENDDO
2309            ENDIF
2310           
2311!--         deallocation of temporary arrays
2312            DEALLOCATE( pcsflt )
2313            DEALLOCATE( kpcsflt )
2314           
2315        ENDIF
2316       
2317        RETURN
2318       
2319301     WRITE( message_string, * )  &
2320            'I/O error when processing shape view factors / ',  &
2321            'plant canopy sink factors / direct irradiance factors.'
2322        CALL message( 'init_urban_surface', 'PA0502', 2, 2, 0, 6, 0 )
2323       
2324    END SUBROUTINE usm_calc_svf
2325
2326
2327!------------------------------------------------------------------------------!
2328!
2329! Description:
2330! ------------
2331!> Subroutine checks variables and assigns units.
2332!> It is caaled out from subroutine check_parameters.
2333!------------------------------------------------------------------------------!
2334    SUBROUTINE usm_check_data_output( variable, unit )
2335       
2336        IMPLICIT NONE
2337 
2338        CHARACTER (len=*),INTENT(IN)    ::  variable !:
2339        CHARACTER (len=*),INTENT(OUT)   ::  unit     !:
2340       
2341        CHARACTER (len=varnamelength)   :: var
2342
2343        var = TRIM(variable)
2344        IF ( var(1:12) == 'usm_rad_net_'  .OR.  var(1:13) == 'usm_rad_insw_'  .OR.        &
2345             var(1:13) == 'usm_rad_inlw_'  .OR.  var(1:16) == 'usm_rad_inswdir_'  .OR.    &
2346             var(1:16) == 'usm_rad_inswdif_'  .OR.  var(1:16) == 'usm_rad_inswref_'  .OR. &
2347             var(1:16) == 'usm_rad_inlwdif_'  .OR.  var(1:16) == 'usm_rad_inlwref_'  .OR. &
2348             var(1:14) == 'usm_rad_outsw_'  .OR.  var(1:14) == 'usm_rad_outlw_'  .OR.     &
2349             var(1:14) == 'usm_rad_ressw_'  .OR.  var(1:14) == 'usm_rad_reslw_'  .OR.     &
2350             var(1:11) == 'usm_rad_hf_'  .OR.                                             &
2351             var(1:9)  == 'usm_wshf_'  .OR.  var(1:9) == 'usm_wghf_' )  THEN
2352            unit = 'W/m2'
2353        ELSE IF ( var(1:10) == 'usm_t_surf'  .OR.  var(1:10) == 'usm_t_wall' )  THEN
2354            unit = 'K'
2355        ELSE IF ( var(1:9) == 'usm_surfz'  .OR.  var(1:7) == 'usm_svf'  .OR.              & 
2356                  var(1:7) == 'usm_dif'  .OR.  var(1:11) == 'usm_surfcat'  .OR.           &
2357                  var(1:11) == 'usm_surfalb'  .OR.  var(1:12) == 'usm_surfemis')  THEN
2358            unit = '1'
2359        ELSE
2360            unit = 'illegal'
2361        ENDIF
2362
2363    END SUBROUTINE usm_check_data_output
2364
2365
2366!------------------------------------------------------------------------------!
2367! Description:
2368! ------------
2369!> Check parameters routine for urban surface model
2370!------------------------------------------------------------------------------!
2371    SUBROUTINE usm_check_parameters
2372   
2373       USE control_parameters,                                                 &
2374           ONLY:  bc_pt_b, bc_q_b, constant_flux_layer, large_scale_forcing,   &
2375                  lsf_surf, topography
2376
2377!
2378!--    Dirichlet boundary conditions are required as the surface fluxes are
2379!--    calculated from the temperature/humidity gradients in the urban surface
2380!--    model
2381       IF ( bc_pt_b == 'neumann'   .OR.   bc_q_b == 'neumann' )  THEN
2382          message_string = 'urban surface model requires setting of '//        &
2383                           'bc_pt_b = "dirichlet" and '//                      &
2384                           'bc_q_b  = "dirichlet"'
2385          CALL message( 'check_parameters', 'PA0590', 1, 2, 0, 6, 0 )
2386       ENDIF
2387
2388       IF ( .NOT.  constant_flux_layer )  THEN
2389          message_string = 'urban surface model requires '//                   &
2390                           'constant_flux_layer = .T.'
2391          CALL message( 'check_parameters', 'PA0591', 1, 2, 0, 6, 0 )
2392       ENDIF
2393!       
2394!--    Surface forcing has to be disabled for LSF in case of enabled
2395!--    urban surface module
2396       IF ( large_scale_forcing )  THEN
2397          lsf_surf = .FALSE.
2398       ENDIF
2399!
2400!--    Topography
2401       IF ( topography == 'flat' )  THEN
2402          message_string = 'topography /= "flat" is required '//               &
2403                           'when using the urban surface model'
2404          CALL message( 'check_parameters', 'PA0592', 1, 2, 0, 6, 0 )
2405       ENDIF
2406
2407
2408    END SUBROUTINE usm_check_parameters
2409
2410
2411!------------------------------------------------------------------------------!
2412!
2413! Description:
2414! ------------
2415!> Output of the 3D-arrays in netCDF and/or AVS format
2416!> for variables of urban_surface model.
2417!> It resorts the urban surface module output quantities from surf style
2418!> indexing into temporary 3D array with indices (i,j,k).
2419!> It is called from subroutine data_output_3d.
2420!------------------------------------------------------------------------------!
2421    SUBROUTINE usm_data_output_3d( av, variable, found, local_pf, nzb_do, nzt_do )
2422       
2423        IMPLICIT NONE
2424
2425        INTEGER(iwp), INTENT(IN)       ::  av        !<
2426        CHARACTER (len=*), INTENT(IN)  ::  variable  !<
2427        INTEGER(iwp), INTENT(IN)       ::  nzb_do    !< lower limit of the data output (usually 0)
2428        INTEGER(iwp), INTENT(IN)       ::  nzt_do    !< vertical upper limit of the data output (usually nz_do3d)
2429        LOGICAL, INTENT(OUT)           ::  found     !<
2430        REAL(sp), DIMENSION(nxl:nxr,nys:nyn,nzb_do:nzt_do) ::  local_pf   !< sp - it has to correspond to module data_output_3d
2431        REAL(wp), DIMENSION(nzb:nzt+1,nys:nyn,nxl:nxr)     ::  temp_pf    !< temp array for urban surface output procedure
2432       
2433        CHARACTER (len=varnamelength)                          :: var, surfid
2434        INTEGER(iwp), PARAMETER                                :: nd = 5
2435        CHARACTER(len=6), DIMENSION(0:nd-1), PARAMETER         :: dirname = (/ '_roof ', '_south', '_north', '_west ', '_east ' /)
2436        INTEGER(iwp), DIMENSION(0:nd-1), PARAMETER             :: dirint = (/ iroof, isouth, inorth, iwest, ieast /)
2437        INTEGER(iwp), DIMENSION(0:nd-1)                        :: dirstart
2438        INTEGER(iwp), DIMENSION(0:nd-1)                        :: dirend
2439        INTEGER(iwp)                                           :: ids,isurf,isvf,isurfs,isurflt
2440        INTEGER(iwp)                                           :: is,js,ks,i,j,k,iwl,istat, l, m
2441        INTEGER(iwp)                                           ::  k_topo    !< topography top index
2442
2443        dirstart = (/ startland, startwall, startwall, startwall, startwall /)
2444        dirend = (/ endland, endwall, endwall, endwall, endwall /)
2445
2446        found = .TRUE.
2447        temp_pf = -1._wp
2448       
2449        ids = -1
2450        var = TRIM(variable)
2451        DO i = 0, nd-1
2452            k = len(TRIM(var))
2453            j = len(TRIM(dirname(i)))
2454            IF ( var(k-j+1:k) == dirname(i) )  THEN
2455                ids = i
2456                var = var(:k-j)
2457                EXIT
2458            ENDIF
2459        ENDDO
2460        IF ( ids == -1 )  THEN
2461            var = TRIM(variable)
2462        ENDIF
2463        IF ( var(1:11) == 'usm_t_wall_'  .AND.  len(TRIM(var)) >= 12 )  THEN
2464!--         wall layers
2465            READ(var(12:12), '(I1)', iostat=istat ) iwl
2466            IF ( istat == 0  .AND.  iwl >= nzb_wall  .AND.  iwl <= nzt_wall )  THEN
2467                var = var(1:10)
2468            ENDIF
2469        ENDIF
2470        IF ( (var(1:8) == 'usm_svf_'  .OR.  var(1:8) == 'usm_dif_')  .AND.  len(TRIM(var)) >= 13 )  THEN
2471!--         svf values to particular surface
2472            surfid = var(9:)
2473            i = index(surfid,'_')
2474            j = index(surfid(i+1:),'_')
2475            READ(surfid(1:i-1),*, iostat=istat ) is
2476            IF ( istat == 0 )  THEN
2477                READ(surfid(i+1:i+j-1),*, iostat=istat ) js
2478            ENDIF
2479            IF ( istat == 0 )  THEN
2480                READ(surfid(i+j+1:),*, iostat=istat ) ks
2481            ENDIF
2482            IF ( istat == 0 )  THEN
2483                var = var(1:7)
2484            ENDIF
2485        ENDIF
2486       
2487        SELECT CASE ( TRIM(var) )
2488
2489          CASE ( 'usm_surfz' )
2490!--           array of lw radiation falling to local surface after i-th reflection
2491              DO  m = 1, surf_usm_h%ns
2492                 i = surf_usm_h%i(m)
2493                 j = surf_usm_h%j(m)
2494                 k = surf_usm_h%k(m)
2495                 temp_pf(0,j,i) = MAX( temp_pf(0,j,i), REAL( k, kind=wp) )
2496              ENDDO
2497              DO  l = 0, 3
2498                 DO  m = 1, surf_usm_v(l)%ns
2499                    i = surf_usm_v(l)%i(m)
2500                    j = surf_usm_v(l)%j(m)
2501                    k = surf_usm_v(l)%k(m)
2502                    temp_pf(0,j,i) = MAX( temp_pf(0,j,i), REAL( k, kind=wp) + 1.0_wp )
2503                 ENDDO
2504              ENDDO
2505
2506          CASE ( 'usm_surfcat' )
2507!--           surface category
2508              DO  m = 1, surf_usm_h%ns
2509                 i = surf_usm_h%i(m)
2510                 j = surf_usm_h%j(m)
2511                 k = surf_usm_h%k(m)
2512                 temp_pf(k,j,i) = surf_usm_h%surface_types(m)
2513              ENDDO
2514              DO  l = 0, 3
2515                 DO  m = 1, surf_usm_v(l)%ns
2516                    i = surf_usm_v(l)%i(m)
2517                    j = surf_usm_v(l)%j(m)
2518                    k = surf_usm_v(l)%k(m)
2519                    temp_pf(k,j,i) = surf_usm_v(l)%surface_types(m)
2520                 ENDDO
2521              ENDDO
2522             
2523          CASE ( 'usm_surfalb' )
2524!--           surface albedo
2525              DO  m = 1, surf_usm_h%ns
2526                 i = surf_usm_h%i(m)
2527                 j = surf_usm_h%j(m)
2528                 k = surf_usm_h%k(m)
2529                 temp_pf(k,j,i) = surf_usm_h%albedo_surf(m)
2530              ENDDO
2531              DO  l = 0, 3
2532                 DO  m = 1, surf_usm_v(l)%ns
2533                    i = surf_usm_v(l)%i(m)
2534                    j = surf_usm_v(l)%j(m)
2535                    k = surf_usm_v(l)%k(m)
2536                    temp_pf(k,j,i) = surf_usm_v(l)%albedo_surf(m)
2537                 ENDDO
2538              ENDDO
2539             
2540          CASE ( 'usm_surfemis' )
2541!--           surface albedo
2542              DO  m = 1, surf_usm_h%ns
2543                 i = surf_usm_h%i(m)
2544                 j = surf_usm_h%j(m)
2545                 k = surf_usm_h%k(m)
2546                 temp_pf(k,j,i) = surf_usm_h%emiss_surf(m)
2547              ENDDO
2548              DO  l = 0, 3
2549                 DO  m = 1, surf_usm_v(l)%ns
2550                    i = surf_usm_v(l)%i(m)
2551                    j = surf_usm_v(l)%j(m)
2552                    k = surf_usm_v(l)%k(m)
2553                    temp_pf(k,j,i) = surf_usm_v(l)%emiss_surf(m)
2554                 ENDDO
2555              ENDDO
2556!
2557!-- Not adjusted so far             
2558          CASE ( 'usm_svf', 'usm_dif' )
2559!--           shape view factors or iradiance factors to selected surface
2560              IF ( TRIM(var)=='usm_svf' )  THEN
2561                  k = 1
2562              ELSE
2563                  k = 2
2564              ENDIF
2565              DO isvf = 1, nsvfl
2566                  isurflt = svfsurf(1, isvf)
2567                  isurfs = svfsurf(2, isvf)
2568                             
2569                  IF ( surf(ix,isurfs) == is  .AND.  surf(iy,isurfs) == js  .AND.       &
2570                       surf(iz,isurfs) == ks  .AND.  surf(id,isurfs) == ids )  THEN
2571  !--                 correct source surface
2572                      temp_pf(surfl(iz,isurflt),surfl(iy,isurflt),surfl(ix,isurflt)) = svf(k,isvf)
2573                  ENDIF
2574              ENDDO
2575
2576          CASE ( 'usm_rad_net' )
2577!--           array of complete radiation balance
2578              IF ( av == 0 )  THEN
2579                 DO  m = 1, surf_usm_h%ns
2580                    i = surf_usm_h%i(m)
2581                    j = surf_usm_h%j(m)
2582                    k = surf_usm_h%k(m)
2583                    temp_pf(k,j,i) = surf_usm_h%rad_net_l(m)
2584                 ENDDO
2585                 DO  l = 0, 3
2586                    DO  m = 1, surf_usm_v(l)%ns
2587                       i = surf_usm_v(l)%i(m)
2588                       j = surf_usm_v(l)%j(m)
2589                       k = surf_usm_v(l)%k(m)
2590                       temp_pf(k,j,i) = surf_usm_v(l)%rad_net_l(m)
2591                    ENDDO
2592                 ENDDO
2593              ELSE
2594                 DO  m = 1, surf_usm_h%ns
2595                    i = surf_usm_h%i(m)
2596                    j = surf_usm_h%j(m)
2597                    k = surf_usm_h%k(m)
2598                    temp_pf(k,j,i) = surf_usm_h%rad_net_av(m)
2599                 ENDDO
2600                 DO  l = 0, 3
2601                    DO  m = 1, surf_usm_v(l)%ns
2602                       i = surf_usm_v(l)%i(m)
2603                       j = surf_usm_v(l)%j(m)
2604                       k = surf_usm_v(l)%k(m)
2605                       temp_pf(k,j,i) = surf_usm_v(l)%rad_net_av(m)
2606                    ENDDO
2607                 ENDDO
2608              ENDIF
2609
2610          CASE ( 'usm_rad_insw' )
2611!--           array of sw radiation falling to surface after i-th reflection
2612              DO isurf = dirstart(ids), dirend(ids)
2613                 IF ( surfl(id,isurf) == ids )  THEN
2614                   IF ( av == 0 )  THEN
2615                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinsw(isurf)
2616                   ELSE
2617                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinsw_av(isurf)
2618                   ENDIF
2619                 ENDIF
2620              ENDDO
2621
2622          CASE ( 'usm_rad_inlw' )
2623!--           array of lw radiation falling to surface after i-th reflection
2624              DO isurf = dirstart(ids), dirend(ids)
2625                 IF ( surfl(id,isurf) == ids )  THEN
2626                   IF ( av == 0 )  THEN
2627                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlw(isurf)
2628                   ELSE
2629                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlw_av(isurf)
2630                   ENDIF
2631                 ENDIF
2632              ENDDO
2633
2634          CASE ( 'usm_rad_inswdir' )
2635!--           array of direct sw radiation falling to surface from sun
2636              DO isurf = dirstart(ids), dirend(ids)
2637                 IF ( surfl(id,isurf) == ids )  THEN
2638                   IF ( av == 0 )  THEN
2639                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdir(isurf)
2640                   ELSE
2641                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdir_av(isurf)
2642                   ENDIF
2643                 ENDIF
2644              ENDDO
2645
2646          CASE ( 'usm_rad_inswdif' )
2647!--           array of difusion sw radiation falling to surface from sky and borders of the domain
2648              DO isurf = dirstart(ids), dirend(ids)
2649                 IF ( surfl(id,isurf) == ids )  THEN
2650                   IF ( av == 0 )  THEN
2651                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdif(isurf)
2652                   ELSE
2653                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdif_av(isurf)
2654                   ENDIF
2655                 ENDIF
2656              ENDDO
2657
2658          CASE ( 'usm_rad_inswref' )
2659!--           array of sw radiation falling to surface from reflections
2660              DO isurf = dirstart(ids), dirend(ids)
2661                 IF ( surfl(id,isurf) == ids )  THEN
2662                   IF ( av == 0 )  THEN
2663                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = &
2664                       surfinsw(isurf) - surfinswdir(isurf) - surfinswdif(isurf)
2665                   ELSE
2666                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswref_av(isurf)
2667                   ENDIF
2668                 ENDIF
2669              ENDDO
2670
2671          CASE ( 'usm_rad_inlwref' )
2672!--           array of lw radiation falling to surface from reflections
2673              DO isurf = dirstart(ids), dirend(ids)
2674                 IF ( surfl(id,isurf) == ids )  THEN
2675                   IF ( av == 0 )  THEN
2676                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlw(isurf) - surfinlwdif(isurf)
2677                   ELSE
2678                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlwref_av(isurf)
2679                   ENDIF
2680                 ENDIF
2681              ENDDO
2682
2683          CASE ( 'usm_rad_outsw' )
2684!--           array of sw radiation emitted from surface after i-th reflection
2685              DO isurf = dirstart(ids), dirend(ids)
2686                 IF ( surfl(id,isurf) == ids )  THEN
2687                   IF ( av == 0 )  THEN
2688                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutsw(isurf)
2689                   ELSE
2690                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutsw_av(isurf)
2691                   ENDIF
2692                 ENDIF
2693              ENDDO
2694
2695          CASE ( 'usm_rad_outlw' )
2696!--           array of lw radiation emitted from surface after i-th reflection
2697              DO isurf = dirstart(ids), dirend(ids)
2698                 IF ( surfl(id,isurf) == ids )  THEN
2699                   IF ( av == 0 )  THEN
2700                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutlw(isurf)
2701                   ELSE
2702                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutlw_av(isurf)
2703                   ENDIF
2704                 ENDIF
2705              ENDDO
2706
2707          CASE ( 'usm_rad_ressw' )
2708!--           average of array of residua of sw radiation absorbed in surface after last reflection
2709              DO isurf = dirstart(ids), dirend(ids)
2710                 IF ( surfl(id,isurf) == ids )  THEN
2711                   IF ( av == 0 )  THEN
2712                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfins(isurf)
2713                   ELSE
2714                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfins_av(isurf)
2715                   ENDIF
2716                 ENDIF
2717              ENDDO
2718
2719          CASE ( 'usm_rad_reslw' )
2720!--           average of array of residua of lw radiation absorbed in surface after last reflection
2721              DO isurf = dirstart(ids), dirend(ids)
2722                 IF ( surfl(id,isurf) == ids )  THEN
2723                   IF ( av == 0 )  THEN
2724                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinl(isurf)
2725                   ELSE
2726                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinl_av(isurf)
2727                   ENDIF
2728                 ENDIF
2729              ENDDO
2730 
2731          CASE ( 'usm_rad_hf' )
2732!--           array of heat flux from radiation for surfaces after all reflections
2733              IF ( av == 0 )  THEN
2734                 DO  m = 1, surf_usm_h%ns
2735                    i = surf_usm_h%i(m)
2736                    j = surf_usm_h%j(m)
2737                    k = surf_usm_h%k(m)
2738                    temp_pf(k,j,i) = surf_usm_h%surfhf(m)
2739                 ENDDO
2740                 DO  l = 0, 3
2741                    DO  m = 1, surf_usm_v(l)%ns
2742                       i = surf_usm_v(l)%i(m)
2743                       j = surf_usm_v(l)%j(m)
2744                       k = surf_usm_v(l)%k(m)
2745                       temp_pf(k,j,i) = surf_usm_v(l)%surfhf(m)
2746                    ENDDO
2747                 ENDDO
2748              ELSE
2749                 DO  m = 1, surf_usm_h%ns
2750                    i = surf_usm_h%i(m)
2751                    j = surf_usm_h%j(m)
2752                    k = surf_usm_h%k(m)
2753                    temp_pf(k,j,i) = surf_usm_h%surfhf_av(m)
2754                 ENDDO
2755                 DO  l = 0, 3
2756                    DO  m = 1, surf_usm_v(l)%ns
2757                       i = surf_usm_v(l)%i(m)
2758                       j = surf_usm_v(l)%j(m)
2759                       k = surf_usm_v(l)%k(m)
2760                       temp_pf(k,j,i) = surf_usm_v(l)%surfhf_av(m)
2761                    ENDDO
2762                 ENDDO
2763              ENDIF
2764 
2765          CASE ( 'usm_wshf' )
2766!--           array of sensible heat flux from surfaces
2767              IF ( av == 0 )  THEN
2768                 DO  m = 1, surf_usm_h%ns
2769                    i = surf_usm_h%i(m)
2770                    j = surf_usm_h%j(m)
2771                    k = surf_usm_h%k(m)
2772                    temp_pf(k,j,i) = surf_usm_h%wshf_eb(m)
2773                 ENDDO
2774                 DO  l = 0, 3
2775                    DO  m = 1, surf_usm_v(l)%ns
2776                       i = surf_usm_v(l)%i(m)
2777                       j = surf_usm_v(l)%j(m)
2778                       k = surf_usm_v(l)%k(m)
2779                       temp_pf(k,j,i) = surf_usm_v(l)%wshf_eb(m)
2780                    ENDDO
2781                 ENDDO
2782              ELSE
2783                 DO  m = 1, surf_usm_h%ns
2784                    i = surf_usm_h%i(m)
2785                    j = surf_usm_h%j(m)
2786                    k = surf_usm_h%k(m)
2787                    temp_pf(k,j,i) = surf_usm_h%wshf_eb_av(m)
2788                 ENDDO
2789                 DO  l = 0, 3
2790                    DO  m = 1, surf_usm_v(l)%ns
2791                       i = surf_usm_v(l)%i(m)
2792                       j = surf_usm_v(l)%j(m)
2793                       k = surf_usm_v(l)%k(m)
2794                       temp_pf(k,j,i) = surf_usm_v(l)%wshf_eb_av(m)
2795                    ENDDO
2796                 ENDDO
2797              ENDIF
2798
2799
2800          CASE ( 'usm_wghf' )
2801!--           array of heat flux from ground (land, wall, roof)
2802              IF ( av == 0 )  THEN
2803                 DO  m = 1, surf_usm_h%ns
2804                    i = surf_usm_h%i(m)
2805                    j = surf_usm_h%j(m)
2806                    k = surf_usm_h%k(m)
2807                    temp_pf(k,j,i) = surf_usm_h%wghf_eb(m)
2808                 ENDDO
2809                 DO  l = 0, 3
2810                    DO  m = 1, surf_usm_v(l)%ns
2811                       i = surf_usm_v(l)%i(m)
2812                       j = surf_usm_v(l)%j(m)
2813                       k = surf_usm_v(l)%k(m)
2814                       temp_pf(k,j,i) = surf_usm_v(l)%wghf_eb(m)
2815                    ENDDO
2816                 ENDDO
2817              ELSE
2818                 DO  m = 1, surf_usm_h%ns
2819                    i = surf_usm_h%i(m)
2820                    j = surf_usm_h%j(m)
2821                    k = surf_usm_h%k(m)
2822                    temp_pf(k,j,i) = surf_usm_h%wghf_eb_av(m)
2823                 ENDDO
2824                 DO  l = 0, 3
2825                    DO  m = 1, surf_usm_v(l)%ns
2826                       i = surf_usm_v(l)%i(m)
2827                       j = surf_usm_v(l)%j(m)
2828                       k = surf_usm_v(l)%k(m)
2829                       temp_pf(k,j,i) = surf_usm_v(l)%wghf_eb_av(m)
2830                    ENDDO
2831                 ENDDO
2832              ENDIF
2833
2834          CASE ( 'usm_t_surf' )
2835!--           surface temperature for surfaces
2836              IF ( av == 0 )  THEN
2837                 DO  m = 1, surf_usm_h%ns
2838                    i = surf_usm_h%i(m)
2839                    j = surf_usm_h%j(m)
2840                    k = surf_usm_h%k(m)
2841                    temp_pf(k,j,i) = t_surf_h(m)
2842                 ENDDO
2843                 DO  l = 0, 3
2844                    DO  m = 1, surf_usm_v(l)%ns
2845                       i = surf_usm_v(l)%i(m)
2846                       j = surf_usm_v(l)%j(m)
2847                       k = surf_usm_v(l)%k(m)
2848                       temp_pf(k,j,i) = t_surf_v(l)%t(m)
2849                    ENDDO
2850                 ENDDO
2851              ELSE
2852                 DO  m = 1, surf_usm_h%ns
2853                    i = surf_usm_h%i(m)
2854                    j = surf_usm_h%j(m)
2855                    k = surf_usm_h%k(m)
2856                    temp_pf(k,j,i) = surf_usm_h%t_surf_av(m)
2857                 ENDDO
2858                 DO  l = 0, 3
2859                    DO  m = 1, surf_usm_v(l)%ns
2860                       i = surf_usm_v(l)%i(m)
2861                       j = surf_usm_v(l)%j(m)
2862                       k = surf_usm_v(l)%k(m)
2863                       temp_pf(k,j,i) = surf_usm_v(l)%t_surf_av(m)
2864                    ENDDO
2865                 ENDDO
2866              ENDIF
2867             
2868          CASE ( 'usm_t_wall' )
2869!--           wall temperature for  iwl layer of walls and land
2870              IF ( av == 0 )  THEN
2871                 DO  m = 1, surf_usm_h%ns
2872                    i = surf_usm_h%i(m)
2873                    j = surf_usm_h%j(m)
2874                    k = surf_usm_h%k(m)
2875                    temp_pf(k,j,i) = t_wall_h(iwl,m)
2876                 ENDDO
2877                 DO  l = 0, 3
2878                    DO  m = 1, surf_usm_v(l)%ns
2879                       i = surf_usm_v(l)%i(m)
2880                       j = surf_usm_v(l)%j(m)
2881                       k = surf_usm_v(l)%k(m)
2882                       temp_pf(k,j,i) = t_wall_v(l)%t(iwl,m)
2883                    ENDDO
2884                 ENDDO
2885              ELSE
2886                 DO  m = 1, surf_usm_h%ns
2887                    i = surf_usm_h%i(m)
2888                    j = surf_usm_h%j(m)
2889                    k = surf_usm_h%k(m)
2890                    temp_pf(k,j,i) = surf_usm_h%t_wall_av(iwl,m)
2891                 ENDDO
2892                 DO  l = 0, 3
2893                    DO  m = 1, surf_usm_v(l)%ns
2894                       i = surf_usm_v(l)%i(m)
2895                       j = surf_usm_v(l)%j(m)
2896                       k = surf_usm_v(l)%k(m)
2897                       temp_pf(k,j,i) = surf_usm_v(l)%t_wall_av(iwl,m)
2898                    ENDDO
2899                 ENDDO
2900              ENDIF
2901             
2902          CASE DEFAULT
2903              found = .FALSE.
2904             
2905        END SELECT
2906!
2907!--     Rearrange dimensions for NetCDF output
2908        DO  j = nys, nyn
2909            DO  i = nxl, nxr
2910                DO  k = nzb_do, nzt_do
2911                    local_pf(i,j,k) = temp_pf(k,j,i)
2912                ENDDO
2913            ENDDO
2914        ENDDO
2915       
2916    END SUBROUTINE usm_data_output_3d
2917   
2918
2919!------------------------------------------------------------------------------!
2920!
2921! Description:
2922! ------------
2923!> Soubroutine defines appropriate grid for netcdf variables.
2924!> It is called out from subroutine netcdf.
2925!------------------------------------------------------------------------------!
2926    SUBROUTINE usm_define_netcdf_grid( variable, found, grid_x, grid_y, grid_z )
2927   
2928        IMPLICIT NONE
2929
2930        CHARACTER (len=*), INTENT(IN)  ::  variable    !<
2931        LOGICAL, INTENT(OUT)           ::  found       !<
2932        CHARACTER (len=*), INTENT(OUT) ::  grid_x      !<
2933        CHARACTER (len=*), INTENT(OUT) ::  grid_y      !<
2934        CHARACTER (len=*), INTENT(OUT) ::  grid_z      !<
2935
2936        CHARACTER (len=varnamelength)  :: var
2937
2938        var = TRIM(variable)
2939        IF ( var(1:12) == 'usm_rad_net_'  .OR.  var(1:13) == 'usm_rad_insw_'  .OR.          &
2940             var(1:13) == 'usm_rad_inlw_'  .OR.  var(1:16) == 'usm_rad_inswdir_'  .OR.      &
2941             var(1:16) == 'usm_rad_inswdif_'  .OR.  var(1:16) == 'usm_rad_inswref_'  .OR.   &
2942             var(1:16) == 'usm_rad_inlwdif_'  .OR.  var(1:16) == 'usm_rad_inlwref_'  .OR.   &
2943             var(1:14) == 'usm_rad_outsw_'  .OR.  var(1:14) == 'usm_rad_outlw_'  .OR.       &
2944             var(1:14) == 'usm_rad_ressw_'  .OR.  var(1:14) == 'usm_rad_reslw_'  .OR.       &
2945             var(1:11) == 'usm_rad_hf_'  .OR.                                               &
2946             var(1:9) == 'usm_wshf_'  .OR.  var(1:9) == 'usm_wghf_'  .OR.                   &
2947             var(1:10) == 'usm_t_surf'  .OR.  var(1:10) == 'usm_t_wall'  .OR.               &
2948             var(1:9) == 'usm_surfz'  .OR.  var(1:7) == 'usm_svf'  .OR.                     & 
2949             var(1:7) == 'usm_dif'  .OR.  var(1:11) == 'usm_surfcat'  .OR.                  &
2950             var(1:11) == 'usm_surfalb'  .OR.  var(1:12) == 'usm_surfemis' )  THEN
2951
2952            found = .TRUE.
2953            grid_x = 'x'
2954            grid_y = 'y'
2955            grid_z = 'zu'
2956        ELSE
2957            found  = .FALSE.
2958            grid_x = 'none'
2959            grid_y = 'none'
2960            grid_z = 'none'
2961        ENDIF
2962
2963    END SUBROUTINE usm_define_netcdf_grid
2964   
2965   
2966!------------------------------------------------------------------------------!
2967!> Finds first model boundary crossed by a ray
2968!------------------------------------------------------------------------------!
2969    PURE SUBROUTINE usm_find_boundary_face(origin, uvect, bdycross)
2970   
2971       IMPLICIT NONE
2972       
2973       INTEGER(iwp) ::  d       !<
2974       INTEGER(iwp) ::  seldim  !< found fist crossing index
2975
2976       INTEGER(iwp), DIMENSION(3)              ::  bdyd      !< boundary direction       
2977       INTEGER(iwp), DIMENSION(4), INTENT(out) ::  bdycross  !< found boundary crossing (d, z, y, x)
2978       
2979       REAL(wp)                                ::  bdydim  !<
2980       REAL(wp)                                ::  dist    !<
2981       
2982       REAL(wp), DIMENSION(3)             ::  crossdist  !< crossing distance
2983       REAL(wp), DIMENSION(3), INTENT(in) ::  origin     !< ray origin
2984       REAL(wp), DIMENSION(3), INTENT(in) ::  uvect      !< ray unit vector
2985 
2986
2987       bdydim       = nzut + .5_wp  !< top boundary
2988       bdyd(1)      = isky
2989       crossdist(1) = ( bdydim - origin(1) ) / uvect(1)  !< subroutine called only when uvect(1)>0
2990
2991       IF ( uvect(2) == 0._wp )  THEN
2992          crossdist(2) = huge(1._wp)
2993       ELSE
2994          IF ( uvect(2) >= 0._wp )  THEN
2995             bdydim  = ny + .5_wp  !< north global boundary
2996             bdyd(2) = inorthb
2997          ELSE
2998             bdydim  = -.5_wp  !< south global boundary
2999             bdyd(2) = isouthb
3000          ENDIF
3001          crossdist(2) = ( bdydim - origin(2) ) / uvect(2)
3002       ENDIF
3003
3004       IF ( uvect(3) == 0._wp )  THEN
3005          crossdist(3) = huge(1._wp)
3006       ELSE
3007          IF ( uvect(3) >= 0._wp )  THEN
3008             bdydim  = nx + .5_wp  !< east global boundary
3009             bdyd(3) = ieastb
3010          ELSE
3011             bdydim  = -.5_wp  !< west global boundary
3012             bdyd(3) = iwestb
3013          ENDIF
3014          crossdist(3) = ( bdydim - origin(3) ) / uvect(3)
3015       ENDIF
3016
3017       seldim = minloc(crossdist, 1)
3018       dist   = crossdist(seldim)
3019       d      = bdyd(seldim)
3020
3021       bdycross(1)   = d
3022       bdycross(2:4) = NINT( origin(:) + uvect(:) * dist &
3023                                       + .5_wp * (/ kdir(d), jdir(d), idir(d) /) )
3024                       
3025    END SUBROUTINE
3026
3027
3028!------------------------------------------------------------------------------!
3029!> Determines whether two faces are oriented towards each other
3030!------------------------------------------------------------------------------!
3031    PURE LOGICAL FUNCTION usm_facing(x, y, z, d, x2, y2, z2, d2)
3032        IMPLICIT NONE
3033        INTEGER(iwp),   INTENT(in)  :: x, y, z, d, x2, y2, z2, d2
3034     
3035        usm_facing = .FALSE.
3036        IF ( d==iroof  .AND.  d2==iroof ) RETURN
3037        IF ( d==isky  .AND.  d2==isky ) RETURN
3038        IF ( (d==isouth  .OR.  d==inorthb)  .AND.  (d2==isouth.OR.d2==inorthb) ) RETURN
3039        IF ( (d==inorth  .OR.  d==isouthb)  .AND.  (d2==inorth.OR.d2==isouthb) ) RETURN
3040        IF ( (d==iwest  .OR.  d==ieastb)  .AND.  (d2==iwest.OR.d2==ieastb) ) RETURN
3041        IF ( (d==ieast  .OR.  d==iwestb)  .AND.  (d2==ieast.OR.d2==iwestb) ) RETURN
3042
3043        SELECT CASE (d)
3044            CASE (iroof)                   !< ground, roof
3045                IF ( z2 < z ) RETURN
3046            CASE (isky)                    !< sky
3047                IF ( z2 > z ) RETURN
3048            CASE (isouth, inorthb)         !< south facing
3049                IF ( y2 > y ) RETURN
3050            CASE (inorth, isouthb)         !< north facing
3051                IF ( y2 < y ) RETURN
3052            CASE (iwest, ieastb)           !< west facing
3053                IF ( x2 > x ) RETURN
3054            CASE (ieast, iwestb)           !< east facing
3055                IF ( x2 < x ) RETURN
3056        END SELECT
3057
3058        SELECT CASE (d2)
3059            CASE (iroof)                   !< ground, roof
3060                IF ( z < z2 ) RETURN
3061            CASE (isky)                    !< sky
3062                IF ( z > z2 ) RETURN
3063            CASE (isouth, inorthb)         !< south facing
3064                IF ( y > y2 ) RETURN
3065            CASE (inorth, isouthb)         !< north facing
3066                IF ( y < y2 ) RETURN
3067            CASE (iwest, ieastb)           !< west facing
3068                IF ( x > x2 ) RETURN
3069            CASE (ieast, iwestb)           !< east facing
3070                IF ( x < x2 ) RETURN
3071            CASE (-1)
3072                CONTINUE
3073        END SELECT
3074
3075        usm_facing = .TRUE.
3076       
3077    END FUNCTION usm_facing
3078   
3079
3080!------------------------------------------------------------------------------!
3081! Description:
3082! ------------
3083!> Initialization of the wall surface model
3084!------------------------------------------------------------------------------!
3085    SUBROUTINE usm_init_material_model
3086
3087        IMPLICIT NONE
3088
3089        INTEGER(iwp) ::  k, l, m            !< running indices
3090       
3091        CALL location_message( '    initialization of wall surface model', .TRUE. )
3092       
3093!--     Calculate wall grid spacings.
3094!--     Temperature is defined at the center of the wall layers,
3095!--     whereas gradients/fluxes are defined at the edges (_stag)
3096        DO k = nzb_wall, nzt_wall
3097           zwn(k) = zwn_default(k)
3098        ENDDO
3099!       
3100!--     apply for all particular surface grids. First for horizontal surfaces
3101        DO  m = 1, surf_usm_h%ns
3102           surf_usm_h%zw(:,m)             = zwn(:) *                           &
3103                                            surf_usm_h%thickness_wall(m)
3104           surf_usm_h%dz_wall(nzb_wall,m) = surf_usm_h%zw(nzb_wall,m)
3105           DO k = nzb_wall+1, nzt_wall
3106               surf_usm_h%dz_wall(k,m) = surf_usm_h%zw(k,m) -                  &
3107                                         surf_usm_h%zw(k-1,m)
3108           ENDDO
3109           
3110           surf_usm_h%dz_wall(nzt_wall+1,m) = surf_usm_h%dz_wall(nzt_wall,m)
3111
3112           DO k = nzb_wall, nzt_wall-1
3113               surf_usm_h%dz_wall_stag(k,m) = 0.5 * (                          &
3114                           surf_usm_h%dz_wall(k+1,m) + surf_usm_h%dz_wall(k,m) )
3115           ENDDO
3116           surf_usm_h%dz_wall_stag(nzt_wall,m) = surf_usm_h%dz_wall(nzt_wall,m)
3117        ENDDO
3118        surf_usm_h%ddz_wall      = 1.0_wp / surf_usm_h%dz_wall
3119        surf_usm_h%ddz_wall_stag = 1.0_wp / surf_usm_h%dz_wall_stag
3120!       
3121!--     For vertical surfaces
3122        DO  l = 0, 3
3123           DO  m = 1, surf_usm_v(l)%ns
3124              surf_usm_v(l)%zw(:,m)             = zwn(:) *                     &
3125                                                  surf_usm_v(l)%thickness_wall(m)
3126              surf_usm_v(l)%dz_wall(nzb_wall,m) = surf_usm_v(l)%zw(nzb_wall,m)
3127              DO k = nzb_wall+1, nzt_wall
3128                  surf_usm_v(l)%dz_wall(k,m) = surf_usm_v(l)%zw(k,m) -         &
3129                                               surf_usm_v(l)%zw(k-1,m)
3130              ENDDO
3131           
3132              surf_usm_v(l)%dz_wall(nzt_wall+1,m) =                            &
3133                                              surf_usm_v(l)%dz_wall(nzt_wall,m)
3134
3135              DO k = nzb_wall, nzt_wall-1
3136                  surf_usm_v(l)%dz_wall_stag(k,m) = 0.5 * (                    &
3137                                                surf_usm_v(l)%dz_wall(k+1,m) + &
3138                                                surf_usm_v(l)%dz_wall(k,m) )
3139              ENDDO
3140              surf_usm_v(l)%dz_wall_stag(nzt_wall,m) =                         &
3141                                              surf_usm_v(l)%dz_wall(nzt_wall,m)
3142           ENDDO
3143           surf_usm_v(l)%ddz_wall      = 1.0_wp / surf_usm_v(l)%dz_wall
3144           surf_usm_v(l)%ddz_wall_stag = 1.0_wp / surf_usm_v(l)%dz_wall_stag
3145        ENDDO     
3146
3147       
3148        CALL location_message( '    wall structures filed out', .TRUE. )
3149
3150        CALL location_message( '    initialization of wall surface model finished', .TRUE. )
3151
3152    END SUBROUTINE usm_init_material_model
3153
3154 
3155!------------------------------------------------------------------------------!
3156! Description:
3157! ------------
3158!> Initialization of the urban surface model
3159!------------------------------------------------------------------------------!
3160    SUBROUTINE usm_init_urban_surface
3161   
3162        IMPLICIT NONE
3163
3164        INTEGER(iwp) ::  i, j, k, l, m            !< running indices
3165        REAL(wp)     ::  c, d, tin, exn
3166
3167!
3168!-- NOPOINTER version not implemented yet
3169#if defined( __nopointer )
3170    message_string = 'The urban surface module only runs with POINTER version'
3171    CALL message( 'urban_surface_mod', 'PA0452', 1, 2, 0, 6, 0 )
3172#endif
3173
3174        CALL cpu_log( log_point_s(78), 'usm_init', 'start' )
3175!--     surface forcing have to be disabled for LSF
3176!--     in case of enabled urban surface module
3177        IF ( large_scale_forcing )  THEN
3178            lsf_surf = .FALSE.
3179        ENDIF
3180       
3181!--     init anthropogenic sources of heat
3182        CALL usm_allocate_urban_surface()
3183       
3184!--     read the surface_types array somewhere
3185        CALL usm_read_urban_surface_types()
3186       
3187!--     init material heat model
3188        CALL usm_init_material_model()
3189       
3190        IF ( usm_anthropogenic_heat )  THEN
3191!--         init anthropogenic sources of heat (from transportation for now)
3192            CALL usm_read_anthropogenic_heat()
3193        ENDIF
3194       
3195        IF ( read_svf_on_init )  THEN
3196!--         read svf, csf, svfsurf and csfsurf data from file
3197            CALL location_message( '    Start reading SVF from file', .TRUE. )
3198            CALL usm_read_svf_from_file()
3199            CALL location_message( '    Reading SVF from file has finished', .TRUE. )
3200        ELSE
3201!--         calculate SFV and CSF
3202            CALL location_message( '    Start calculation of SVF', .TRUE. )
3203            CALL cpu_log( log_point_s(79), 'usm_calc_svf', 'start' )
3204            CALL usm_calc_svf()
3205            CALL cpu_log( log_point_s(79), 'usm_calc_svf', 'stop' )
3206            CALL location_message( '    Calculation of SVF has finished', .TRUE. )
3207        ENDIF
3208
3209        IF ( write_svf_on_init )  THEN
3210!--         write svf, csf svfsurf and csfsurf data to file
3211            CALL location_message( '    Store SVF and CSF to file', .TRUE. )
3212            CALL usm_write_svf_to_file()
3213        ENDIF
3214       
3215        IF ( plant_canopy )  THEN
3216!--         gridpcbl was only necessary for initialization
3217            DEALLOCATE( gridpcbl )
3218            IF ( .NOT.  ALLOCATED(pc_heating_rate) )  THEN
3219!--             then pc_heating_rate is allocated in init_plant_canopy
3220!--             in case of cthf /= 0 => we need to allocate it for our use here
3221                ALLOCATE( pc_heating_rate(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
3222            ENDIF
3223        ENDIF
3224
3225!--     Intitialization of the surface and wall/ground/roof temperature
3226
3227!--     Initialization for restart runs
3228        IF ( TRIM( initializing_actions ) /= 'read_restart_data'  .AND.        &
3229             TRIM( initializing_actions ) /= 'cyclic_fill' )  THEN
3230       
3231!--         Calculate initial surface temperature from pt of adjacent gridbox
3232            exn = ( surface_pressure / 1000.0_wp )**0.286_wp
3233
3234!
3235!--         At horizontal surfaces. Please note, t_surf_h is defined on a
3236!--         different data type, but with the same dimension.
3237#if ! defined( __nopointer )
3238            DO  m = 1, surf_usm_h%ns
3239               i = surf_usm_h%i(m)           
3240               j = surf_usm_h%j(m)
3241               k = surf_usm_h%k(m)
3242
3243               t_surf_h(m) = pt(k,j,i) * exn
3244            ENDDO
3245!
3246!--         At vertical surfaces.
3247            DO  l = 0, 3
3248               DO  m = 1, surf_usm_v(l)%ns
3249                  i = surf_usm_v(l)%i(m)           
3250                  j = surf_usm_v(l)%j(m)
3251                  k = surf_usm_v(l)%k(m)
3252
3253                  t_surf_v(l)%t(m) = pt(k,j,i) * exn
3254               ENDDO
3255            ENDDO
3256#endif
3257     
3258!--         initial values for t_wall
3259!--         outer value is set to surface temperature
3260!--         inner value is set to wall_inner_temperature
3261!--         and profile is logaritmic (linear in nz).
3262!--         Horizontal surfaces
3263            DO  m = 1, surf_usm_h%ns
3264!
3265!--            Roof
3266               IF ( surf_usm_h%isroof_surf(m) )  THEN
3267                   tin = roof_inner_temperature
3268!
3269!--            Normal land surface
3270               ELSE
3271                   tin = soil_inner_temperature
3272               ENDIF
3273
3274               DO k = nzb_wall, nzt_wall+1
3275                   c = REAL( k - nzb_wall, wp ) /                              &
3276                       REAL( nzt_wall + 1 - nzb_wall , wp )
3277
3278                   t_wall_h(k,m) = ( 1.0_wp - c ) * t_surf_h(m) + c * tin
3279               ENDDO
3280            ENDDO
3281!
3282!--         Vertical surfaces
3283            DO  l = 0, 3
3284               DO  m = 1, surf_usm_v(l)%ns
3285!
3286!--               Inner wall
3287                  tin = wall_inner_temperature
3288
3289                  DO k = nzb_wall, nzt_wall+1
3290                     c = REAL( k - nzb_wall, wp ) /                            &
3291                         REAL( nzt_wall + 1 - nzb_wall , wp )
3292
3293                     t_wall_v(l)%t(k,m) = ( 1.0_wp - c ) * t_surf_v(l)%t(m) +  &
3294                                          c * tin
3295                  ENDDO
3296               ENDDO
3297            ENDDO
3298
3299        ENDIF
3300       
3301!--   
3302!--     Possibly DO user-defined actions (e.g. define heterogeneous wall surface)
3303        CALL user_init_urban_surface
3304
3305!--     initialize prognostic values for the first timestep
3306        t_surf_h_p = t_surf_h
3307        t_surf_v_p = t_surf_v
3308
3309        t_wall_h_p = t_wall_h
3310        t_wall_v_p = t_wall_v
3311       
3312!--     Adjust radiative fluxes for urban surface at model start
3313        CALL usm_radiation
3314       
3315        CALL cpu_log( log_point_s(78), 'usm_init', 'stop' )
3316
3317       
3318    END SUBROUTINE usm_init_urban_surface
3319
3320
3321!------------------------------------------------------------------------------!
3322! Description:
3323! ------------
3324!
3325!> Wall model as part of the urban surface model. The model predicts wall
3326!> temperature.
3327!------------------------------------------------------------------------------!
3328    SUBROUTINE usm_material_heat_model
3329
3330
3331        IMPLICIT NONE
3332
3333        INTEGER(iwp) ::  i,j,k,l,kw, m                      !< running indices
3334
3335        REAL(wp), DIMENSION(nzb_wall:nzt_wall) :: wtend  !< tendency
3336
3337!
3338!--     For horizontal surfaces                                   
3339        DO  m = 1, surf_usm_h%ns
3340!
3341!--        Obtain indices
3342           i = surf_usm_h%i(m)           
3343           j = surf_usm_h%j(m)
3344           k = surf_usm_h%k(m)
3345!
3346!--        prognostic equation for ground/roof temperature t_wall_h
3347           wtend(:) = 0.0_wp
3348           wtend(nzb_wall) = (1.0_wp / surf_usm_h%rho_c_wall(nzb_wall,m)) *    &
3349                                      ( surf_usm_h%lambda_h(nzb_wall,m) *      &
3350                                        ( t_wall_h(nzb_wall+1,m)               &
3351                                        - t_wall_h(nzb_wall,m) ) *             &
3352                                        surf_usm_h%ddz_wall(nzb_wall+1,m)      &
3353                                      + surf_usm_h%wghf_eb(m) ) *              &
3354                                        surf_usm_h%ddz_wall_stag(nzb_wall,m)
3355           
3356           DO  kw = nzb_wall+1, nzt_wall
3357               wtend(kw) = (1.0_wp / surf_usm_h%rho_c_wall(kw,m))              &
3358                              * (   surf_usm_h%lambda_h(kw,m)                  &
3359                                 * ( t_wall_h(kw+1,m) - t_wall_h(kw,m) )       &
3360                                 * surf_usm_h%ddz_wall(kw+1,m)                 &
3361                              - surf_usm_h%lambda_h(kw-1,m)                    &
3362                                 * ( t_wall_h(kw,m) - t_wall_h(kw-1,m) )       &
3363                                 * surf_usm_h%ddz_wall(kw,m)                   &
3364                              ) * surf_usm_h%ddz_wall_stag(kw,m)
3365            ENDDO
3366
3367           t_wall_h_p(nzb_wall:nzt_wall,m) = t_wall_h(nzb_wall:nzt_wall,m)     &
3368                                 + dt_3d * ( tsc(2)                            &
3369                                 * wtend(nzb_wall:nzt_wall) + tsc(3)           &
3370                                 * surf_usm_h%tt_wall_m(nzb_wall:nzt_wall,m) )   
3371           
3372!
3373!--        calculate t_wall tendencies for the next Runge-Kutta step
3374           IF ( timestep_scheme(1:5) == 'runge' )  THEN
3375               IF ( intermediate_timestep_count == 1 )  THEN
3376                  DO  kw = nzb_wall, nzt_wall
3377                     surf_usm_h%tt_wall_m(kw,m) = wtend(kw)
3378                  ENDDO
3379               ELSEIF ( intermediate_timestep_count <                          &
3380                        intermediate_timestep_count_max )  THEN
3381                   DO  kw = nzb_wall, nzt_wall
3382                      surf_usm_h%tt_wall_m(kw,m) = -9.5625_wp * wtend(kw) +    &
3383                                         5.3125_wp * surf_usm_h%tt_wall_m(kw,m)
3384                   ENDDO
3385               ENDIF
3386           ENDIF
3387        ENDDO
3388!
3389!--     For vertical surfaces     
3390        DO  l = 0, 3                             
3391           DO  m = 1, surf_usm_v(l)%ns
3392!
3393!--           Obtain indices
3394              i = surf_usm_v(l)%i(m)           
3395              j = surf_usm_v(l)%j(m)
3396              k = surf_usm_v(l)%k(m)
3397!
3398!--           prognostic equation for wall temperature t_wall_v
3399              wtend(:) = 0.0_wp
3400              wtend(nzb_wall) = (1.0_wp / surf_usm_v(l)%rho_c_wall(nzb_wall,m)) * &
3401                                      ( surf_usm_v(l)%lambda_h(nzb_wall,m) *   &
3402                                        ( t_wall_v(l)%t(nzb_wall+1,m)          &
3403                                        - t_wall_v(l)%t(nzb_wall,m) ) *        &
3404                                        surf_usm_v(l)%ddz_wall(nzb_wall+1,m)   &
3405                                      + surf_usm_v(l)%wghf_eb(m) ) *           &
3406                                        surf_usm_v(l)%ddz_wall_stag(nzb_wall,m)
3407           
3408              DO  kw = nzb_wall+1, nzt_wall
3409                  wtend(kw) = (1.0_wp / surf_usm_v(l)%rho_c_wall(kw,m))        &
3410                           * (   surf_usm_v(l)%lambda_h(kw,m)                  &
3411                              * ( t_wall_v(l)%t(kw+1,m) - t_wall_v(l)%t(kw,m) )&
3412                              * surf_usm_v(l)%ddz_wall(kw+1,m)                 &
3413                           - surf_usm_v(l)%lambda_h(kw-1,m)                    &
3414                              * ( t_wall_v(l)%t(kw,m) - t_wall_v(l)%t(kw-1,m) )&
3415                              * surf_usm_v(l)%ddz_wall(kw,m)                   &
3416                              ) * surf_usm_v(l)%ddz_wall_stag(kw,m)
3417               ENDDO
3418
3419              t_wall_v_p(l)%t(nzb_wall:nzt_wall,m) =                           &
3420                                   t_wall_v(l)%t(nzb_wall:nzt_wall,m)          &
3421                                 + dt_3d * ( tsc(2)                            &
3422                                 * wtend(nzb_wall:nzt_wall) + tsc(3)           &
3423                                 * surf_usm_v(l)%tt_wall_m(nzb_wall:nzt_wall,m) )   
3424           
3425!
3426!--           calculate t_wall tendencies for the next Runge-Kutta step
3427              IF ( timestep_scheme(1:5) == 'runge' )  THEN
3428                  IF ( intermediate_timestep_count == 1 )  THEN
3429                     DO  kw = nzb_wall, nzt_wall
3430                        surf_usm_v(l)%tt_wall_m(kw,m) = wtend(kw)
3431                     ENDDO
3432                  ELSEIF ( intermediate_timestep_count <                       &
3433                           intermediate_timestep_count_max )  THEN
3434                      DO  kw = nzb_wall, nzt_wall
3435                         surf_usm_v(l)%tt_wall_m(kw,m) =                       &
3436                                     - 9.5625_wp * wtend(kw) +                 &
3437                                       5.3125_wp * surf_usm_v(l)%tt_wall_m(kw,m)
3438                      ENDDO
3439                  ENDIF
3440              ENDIF
3441           ENDDO
3442        ENDDO
3443
3444    END SUBROUTINE usm_material_heat_model
3445
3446
3447!------------------------------------------------------------------------------!
3448! Description:
3449! ------------
3450!> Parin for &usm_par for urban surface model
3451!------------------------------------------------------------------------------!
3452    SUBROUTINE usm_parin
3453
3454       IMPLICIT NONE
3455
3456       CHARACTER (LEN=80) ::  line  !< string containing current line of file PARIN
3457
3458       NAMELIST /urban_surface_par/                                            &
3459                           land_category,                                      &
3460                           mrt_factors,                                        &
3461                           nrefsteps,                                          &
3462                           pedestrant_category,                                &
3463                           ra_horiz_coef,                                      &
3464                           read_svf_on_init,                                   &
3465                           roof_category,                                      &
3466                           split_diffusion_radiation,                          &
3467                           urban_surface,                                      &
3468                           usm_anthropogenic_heat,                             &
3469                           usm_energy_balance_land,                            &
3470                           usm_energy_balance_wall,                            &
3471                           usm_material_model,                                 &
3472                           usm_lad_rma,                                        &
3473                           wall_category,                                      &
3474                           write_svf_on_init
3475
3476       line = ' '
3477
3478!
3479!--    Try to find urban surface model package
3480       REWIND ( 11 )
3481       line = ' '
3482       DO   WHILE ( INDEX( line, '&urban_surface_par' ) == 0 )
3483          READ ( 11, '(A)', END=10 )  line
3484       ENDDO
3485       BACKSPACE ( 11 )
3486
3487!
3488!--    Read user-defined namelist
3489       READ ( 11, urban_surface_par )
3490!
3491!--    Set flag that indicates that the land surface model is switched on
3492       urban_surface = .TRUE.
3493
3494!
3495!--    Activate spinup
3496       IF ( spinup_time > 0.0_wp )  THEN
3497          coupling_start_time = spinup_time
3498          end_time = end_time + spinup_time
3499          IF ( spinup_pt_mean == 9999999.9_wp )  THEN
3500             spinup_pt_mean = pt_surface
3501          ENDIF
3502          spinup = .TRUE.
3503       ENDIF
3504
3505 10    CONTINUE
3506
3507    END SUBROUTINE usm_parin
3508
3509
3510!------------------------------------------------------------------------------!
3511! Description:
3512! ------------
3513!> This subroutine calculates interaction of the solar radiation
3514!> with urban surface and updates surface, roofs and walls heatfluxes.
3515!> It also updates rad_sw_out and rad_lw_out.
3516!------------------------------------------------------------------------------!
3517    SUBROUTINE usm_radiation
3518   
3519        IMPLICIT NONE
3520       
3521        INTEGER(iwp)               :: i, j, k, kk, is, js, d, ku, refstep, m, mm, l, ll
3522        INTEGER(iwp)               :: nzubl, nzutl, isurf, isurfsrc, isurf1, isvf, icsf, ipcgb
3523        INTEGER(iwp), DIMENSION(4) :: bdycross
3524        REAL(wp), DIMENSION(3,3)   :: mrot            !< grid rotation matrix (xyz)
3525        REAL(wp), DIMENSION(3,0:9) :: vnorm           !< face direction normal vectors (xyz)
3526        REAL(wp), DIMENSION(3)     :: sunorig         !< grid rotated solar direction unit vector (xyz)
3527        REAL(wp), DIMENSION(3)     :: sunorig_grid    !< grid squashed solar direction unit vector (zyx)
3528        REAL(wp), DIMENSION(0:9)   :: costheta        !< direct irradiance factor of solar angle
3529        REAL(wp), DIMENSION(nzub:nzut) :: pchf_prep   !< precalculated factor for canopy temp tendency
3530        REAL(wp), PARAMETER        :: alpha = 0._wp   !< grid rotation (TODO: add to namelist or remove)
3531        REAL(wp)                   :: rx, ry, rz
3532        REAL(wp)                   :: pc_box_area, pc_abs_frac, pc_abs_eff
3533        INTEGER(iwp)               :: pc_box_dimshift !< transform for best accuracy
3534        INTEGER(iwp), DIMENSION(0:3) :: reorder = (/ 1, 0, 3, 2 /)
3535       
3536#if ! defined( __nopointer )
3537        IF ( plant_canopy )  THEN
3538            pchf_prep(:) = r_d * (hyp(nzub:nzut) / 100000.0_wp)**0.286_wp &
3539                        / (cp * hyp(nzub:nzut) * dx*dy*dz) !< equals to 1 / (rho * c_p * Vbox * T)
3540        ENDIF
3541#endif
3542        sun_direction = .TRUE.
3543        CALL calc_zenith  !< required also for diffusion radiation
3544
3545!--     prepare rotated normal vectors and irradiance factor
3546        vnorm(1,:) = idir(:)
3547        vnorm(2,:) = jdir(:)
3548        vnorm(3,:) = kdir(:)
3549        mrot(1, :) = (/ cos(alpha), -sin(alpha), 0._wp /)
3550        mrot(2, :) = (/ sin(alpha),  cos(alpha), 0._wp /)
3551        mrot(3, :) = (/ 0._wp,       0._wp,      1._wp /)
3552        sunorig = (/ sun_dir_lon, sun_dir_lat, zenith(0) /)
3553        sunorig = matmul(mrot, sunorig)
3554        DO d = 0, 9
3555            costheta(d) = dot_product(sunorig, vnorm(:,d))
3556        ENDDO
3557       
3558        IF ( zenith(0) > 0 )  THEN
3559!--         now we will "squash" the sunorig vector by grid box size in
3560!--         each dimension, so that this new direction vector will allow us
3561!--         to traverse the ray path within grid coordinates directly
3562            sunorig_grid = (/ sunorig(3)/dz, sunorig(2)/dy, sunorig(1)/dx /)
3563!--         sunorig_grid = sunorig_grid / norm2(sunorig_grid)
3564            sunorig_grid = sunorig_grid / SQRT(SUM(sunorig_grid**2))
3565
3566            IF ( plant_canopy )  THEN
3567!--            precompute effective box depth with prototype Leaf Area Density
3568               pc_box_dimshift = maxloc(sunorig, 1) - 1
3569               CALL usm_box_absorb(cshift((/dx,dy,dz/), pc_box_dimshift),      &
3570                                   60, prototype_lad,                          &
3571                                   cshift(sunorig, pc_box_dimshift),           &
3572                                   pc_box_area, pc_abs_frac)
3573               pc_box_area = pc_box_area * sunorig(pc_box_dimshift+1) / sunorig(3)
3574               pc_abs_eff = log(1._wp - pc_abs_frac) / prototype_lad
3575            ENDIF
3576        ENDIF
3577       
3578!--     split diffusion and direct part of the solar downward radiation
3579!--     comming from radiation model and store it in 2D arrays
3580!--     rad_sw_in_diff, rad_sw_in_dir and rad_lw_in_diff
3581        IF ( split_diffusion_radiation )  THEN
3582            CALL usm_calc_diffusion_radiation
3583        ELSE
3584            rad_sw_in_diff = 0.0_wp
3585            rad_sw_in_dir(:,:)  = rad_sw_in(0,:,:)
3586            rad_lw_in_diff(:,:) = rad_lw_in(0,:,:)
3587        ENDIF
3588
3589!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3590!--     First pass: direct + diffuse irradiance
3591!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3592        surfinswdir   = 0._wp !nsurfl
3593        surfinswdif   = 0._wp !nsurfl
3594        surfinlwdif   = 0._wp !nsurfl
3595        surfins       = 0._wp !nsurfl
3596        surfinl       = 0._wp !nsurfl
3597        surfoutsl(:)  = 0.0_wp !start-end
3598        surfoutll(:)  = 0.0_wp !start-end
3599       
3600!--     Set up thermal radiation from surfaces
3601!--     emiss_surf is defined only for surfaces for which energy balance is calculated
3602!--     Workaround: reorder surface data type back on 1D array including all surfaces,
3603!--     which implies to reorder horizontal and vertical surfaces
3604!
3605!--     Horizontal walls
3606        mm = 1
3607        DO  i = nxl, nxr
3608           DO  j = nys, nyn
3609
3610              DO  m = surf_usm_h%start_index(j,i), surf_usm_h%end_index(j,i)
3611                 surfoutll(mm) = surf_usm_h%emiss_surf(m) * sigma_sb   &
3612                                     * t_surf_h(m)**4
3613                 albedo_surf(mm) = surf_usm_h%albedo_surf(m)
3614                 emiss_surf(mm)  = surf_usm_h%emiss_surf(m)
3615                 mm = mm + 1
3616              ENDDO
3617           ENDDO
3618        ENDDO
3619!
3620!--     Vertical walls
3621        DO  i = nxl, nxr
3622           DO  j = nys, nyn
3623              DO  ll = 0, 3
3624                 l = reorder(ll)
3625                 DO  m = surf_usm_v(l)%start_index(j,i), surf_usm_v(l)%end_index(j,i)
3626                    surfoutll(mm) = surf_usm_v(l)%emiss_surf(m) * sigma_sb   &
3627                                     * t_surf_v(l)%t(m)**4
3628                    albedo_surf(mm) = surf_usm_v(l)%albedo_surf(m)
3629                    emiss_surf(mm) = surf_usm_v(l)%emiss_surf(m)
3630                    mm = mm + 1
3631                 ENDDO
3632              ENDDO
3633           ENDDO
3634        ENDDO
3635       
3636#if defined( __parallel )
3637!--     might be optimized and gather only values relevant for current processor
3638       
3639        CALL MPI_AllGatherv(surfoutll, nenergy, MPI_REAL, &
3640                            surfoutl, nsurfs, surfstart, MPI_REAL, comm2d, ierr) !nsurf global
3641#else
3642        surfoutl(:) = surfoutll(:) !nsurf global
3643#endif
3644       
3645        isurf1 = -1   !< previous processed surface
3646        DO isvf = 1, nsvfl
3647            isurf = svfsurf(1, isvf)
3648            k = surfl(iz, isurf)
3649            j = surfl(iy, isurf)
3650            i = surfl(ix, isurf)
3651            isurfsrc = svfsurf(2, isvf)
3652            IF ( zenith(0) > 0  .AND.  isurf /= isurf1 )  THEN
3653!--             locate the virtual surface where the direct solar ray crosses domain boundary
3654!--             (once per target surface)
3655                d = surfl(id, isurf)
3656                rz = REAL(k, wp) - 0.5_wp * kdir(d)
3657                ry = REAL(j, wp) - 0.5_wp * jdir(d)
3658                rx = REAL(i, wp) - 0.5_wp * idir(d)
3659               
3660                CALL usm_find_boundary_face( (/ rz, ry, rx /), sunorig_grid, bdycross)
3661               
3662                isurf1 = isurf
3663            ENDIF
3664
3665            IF ( surf(id, isurfsrc) >= isky )  THEN
3666!--             diffuse rad from boundary surfaces. Since it is a simply
3667!--             calculated value, it is not assigned to surfref(s/l),
3668!--             instead it is used directly here
3669!--             we consider the radiation from the radiation model falling on surface
3670!--             as the radiation falling on the top of urban layer into the place of the source surface
3671!--             we consider it as a very reasonable simplification which allow as avoid
3672!--             necessity of other global range arrays and some all to all mpi communication
3673                surfinswdif(isurf) = surfinswdif(isurf) + rad_sw_in_diff(j,i) * svf(1,isvf) * svf(2,isvf)
3674                                                                !< canopy shading is applied only to shortwave
3675                surfinlwdif(isurf) = surfinlwdif(isurf) + rad_lw_in_diff(j,i) * svf(1,isvf)
3676            ELSE
3677!--             for surface-to-surface factors we calculate thermal radiation in 1st pass
3678                surfinl(isurf) = surfinl(isurf) + svf(1,isvf) * surfoutl(isurfsrc)
3679            ENDIF
3680
3681            IF ( zenith(0) > 0  .AND.  all( surf(1:4,isurfsrc) == bdycross ) )  THEN
3682!--             found svf between model boundary and the face => face isn't shaded
3683                surfinswdir(isurf) = rad_sw_in_dir(j,i) &
3684                    * costheta(surfl(id, isurf)) * svf(2,isvf) / zenith(0)
3685
3686            ENDIF
3687        ENDDO
3688
3689        IF ( plant_canopy )  THEN
3690       
3691            pcbinsw(:) = 0._wp
3692            pcbinlw(:) = 0._wp  !< will stay always 0 since we don't absorb lw anymore
3693            !
3694!--         pcsf first pass
3695            isurf1 = -1  !< previous processed pcgb
3696            DO icsf = 1, ncsfl
3697                ipcgb = csfsurf(1, icsf)
3698                i = pcbl(ix,ipcgb)
3699                j = pcbl(iy,ipcgb)
3700                k = pcbl(iz,ipcgb)
3701                isurfsrc = csfsurf(2, icsf)
3702
3703                IF ( zenith(0) > 0  .AND.  ipcgb /= isurf1 )  THEN
3704!--                 locate the virtual surface where the direct solar ray crosses domain boundary
3705!--                 (once per target PC gridbox)
3706                    rz = REAL(k, wp)
3707                    ry = REAL(j, wp)
3708                    rx = REAL(i, wp)
3709                    CALL usm_find_boundary_face( (/ rz, ry, rx /), &
3710                        sunorig_grid, bdycross)
3711
3712                    isurf1 = ipcgb
3713                ENDIF
3714
3715                IF ( surf(id, isurfsrc) >= isky )  THEN
3716!--                 Diffuse rad from boundary surfaces. See comments for svf above.
3717                    pcbinsw(ipcgb) = pcbinsw(ipcgb) + csf(1,icsf) * csf(2,icsf) * rad_sw_in_diff(j,i)
3718!--                 canopy shading is applied only to shortwave, therefore no absorbtion for lw
3719!--                 pcbinlw(ipcgb) = pcbinlw(ipcgb) + svf(1,isvf) * rad_lw_in_diff(j,i)
3720                !ELSE
3721!--                 Thermal radiation in 1st pass
3722!--                 pcbinlw(ipcgb) = pcbinlw(ipcgb) + svf(1,isvf) * surfoutl(isurfsrc)
3723                ENDIF
3724
3725                IF ( zenith(0) > 0  .AND.  all( surf(1:4,isurfsrc) == bdycross ) )  THEN
3726!--                 found svf between model boundary and the pcgb => pcgb isn't shaded
3727                    pc_abs_frac = 1._wp - exp(pc_abs_eff * lad_s(k,j,i))
3728                    pcbinsw(ipcgb) = pcbinsw(ipcgb) &
3729                        + rad_sw_in_dir(j, i) * pc_box_area * csf(2,icsf) * pc_abs_frac
3730                ENDIF
3731            ENDDO
3732        ENDIF
3733
3734        surfins(startenergy:endenergy) = surfinswdir(startenergy:endenergy) + surfinswdif(startenergy:endenergy)
3735        surfinl(startenergy:endenergy) = surfinl(startenergy:endenergy) + surfinlwdif(startenergy:endenergy)
3736        surfinsw(:) = surfins(:)
3737        surfinlw(:) = surfinl(:)
3738        surfoutsw(:) = 0.0_wp
3739        surfoutlw(:) = surfoutll(:)
3740!         surfhf(startenergy:endenergy) = surfinsw(startenergy:endenergy) + surfinlw(startenergy:endenergy) &
3741!                                       - surfoutsw(startenergy:endenergy) - surfoutlw(startenergy:endenergy)
3742       
3743!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3744!--     Next passes - reflections
3745!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3746        DO refstep = 1, nrefsteps
3747       
3748            surfoutsl(startenergy:endenergy) = albedo_surf(startenergy:endenergy) * surfins(startenergy:endenergy)
3749!--         for non-transparent surfaces, longwave albedo is 1 - emissivity
3750            surfoutll(startenergy:endenergy) = (1._wp - emiss_surf(startenergy:endenergy)) * surfinl(startenergy:endenergy)
3751
3752#if defined( __parallel )
3753            CALL MPI_AllGatherv(surfoutsl, nsurfl, MPI_REAL, &
3754                surfouts, nsurfs, surfstart, MPI_REAL, comm2d, ierr)
3755            CALL MPI_AllGatherv(surfoutll, nsurfl, MPI_REAL, &
3756                surfoutl, nsurfs, surfstart, MPI_REAL, comm2d, ierr)
3757#else
3758            surfouts(:) = surfoutsl(:)
3759            surfoutl(:) = surfoutll(:)
3760#endif
3761
3762!--         reset for next pass input
3763            surfins(:) = 0._wp
3764            surfinl(:) = 0._wp
3765           
3766!--         reflected radiation
3767            DO isvf = 1, nsvfl
3768                isurf = svfsurf(1, isvf)
3769                isurfsrc = svfsurf(2, isvf)
3770
3771!--             TODO: to remove if, use start+end for isvf
3772                IF ( surf(id, isurfsrc) < isky )  THEN
3773                    surfins(isurf) = surfins(isurf) + svf(1,isvf) * svf(2,isvf) * surfouts(isurfsrc)
3774                    surfinl(isurf) = surfinl(isurf) + svf(1,isvf) * surfoutl(isurfsrc)
3775                ENDIF
3776            ENDDO
3777
3778!--         radiation absorbed by plant canopy
3779            DO icsf = 1, ncsfl
3780                ipcgb = csfsurf(1, icsf)
3781                isurfsrc = csfsurf(2, icsf)
3782
3783                IF ( surf(id, isurfsrc) < isky )  THEN
3784                    pcbinsw(ipcgb) = pcbinsw(ipcgb) + csf(1,icsf) * csf(2,icsf) * surfouts(isurfsrc)
3785!--                 pcbinlw(ipcgb) = pcbinlw(ipcgb) + csf(1,icsf) * surfoutl(isurfsrc)
3786                ENDIF
3787            ENDDO
3788           
3789            surfinsw(:) = surfinsw(:)  + surfins(:)
3790            surfinlw(:) = surfinlw(:)  + surfinl(:)
3791            surfoutsw(startenergy:endenergy) = surfoutsw(startenergy:endenergy) + surfoutsl(startenergy:endenergy)
3792            surfoutlw(startenergy:endenergy) = surfoutlw(startenergy:endenergy) + surfoutll(startenergy:endenergy)
3793!             surfhf(startenergy:endenergy) = surfinsw(startenergy:endenergy) + surfinlw(startenergy:endenergy) &
3794!                                           - surfoutsw(startenergy:endenergy) - surfoutlw(startenergy:endenergy)
3795       
3796        ENDDO
3797
3798!--     push heat flux absorbed by plant canopy to respective 3D arrays
3799#if ! defined( __nopointer )
3800        IF ( plant_canopy )  THEN
3801            pc_heating_rate(:,:,:) = 0._wp
3802            DO ipcgb = 1, npcbl
3803                j = pcbl(iy, ipcgb)
3804                i = pcbl(ix, ipcgb)
3805                k = pcbl(iz, ipcgb)
3806!
3807!--             Following expression equals former kk = k - nzb_s_inner(j,i)
3808                kk = k - ( get_topography_top_index( j, i, 's' ) )  !- lad arrays are defined flat
3809                pc_heating_rate(kk, j, i) = (pcbinsw(ipcgb) + pcbinlw(ipcgb)) &
3810                    * pchf_prep(k) * pt(k, j, i) !-- = dT/dt
3811            ENDDO
3812        ENDIF
3813#endif
3814!
3815!--     Transfer radiation arrays required for energy balance to the respective data types
3816        DO  i = startenergy, endenergy
3817           m  = surfl(5,i)         
3818!
3819!--        upward-facing
3820           IF ( surfl(1,i) == 0 )  THEN
3821              surf_usm_h%rad_in_sw(m)  = surfinsw(i) 
3822              surf_usm_h%rad_out_sw(m) = surfoutsw(i) 
3823              surf_usm_h%rad_in_lw(m)  = surfinlw(i)
3824              surf_usm_h%rad_out_lw(m) = surfoutlw(i)
3825!
3826!--        southward-facding
3827           ELSEIF ( surfl(1,i) == 1 )  THEN
3828              surf_usm_v(1)%rad_in_sw(m)  = surfinsw(i) 
3829              surf_usm_v(1)%rad_out_sw(m) = surfoutsw(i) 
3830              surf_usm_v(1)%rad_in_lw(m)  = surfinlw(i)
3831              surf_usm_v(1)%rad_out_lw(m) = surfoutlw(i)
3832!
3833!--        northward-facding
3834           ELSEIF ( surfl(1,i) == 2 )  THEN
3835              surf_usm_v(0)%rad_in_sw(m)  = surfinsw(i) 
3836              surf_usm_v(0)%rad_out_sw(m) = surfoutsw(i) 
3837              surf_usm_v(0)%rad_in_lw(m)  = surfinlw(i)
3838              surf_usm_v(0)%rad_out_lw(m) = surfoutlw(i)
3839!
3840!--        westward-facding
3841           ELSEIF ( surfl(1,i) == 3 )  THEN
3842              surf_usm_v(3)%rad_in_sw(m)  = surfinsw(i) 
3843              surf_usm_v(3)%rad_out_sw(m) = surfoutsw(i) 
3844              surf_usm_v(3)%rad_in_lw(m)  = surfinlw(i)
3845              surf_usm_v(3)%rad_out_lw(m) = surfoutlw(i)
3846!
3847!--        eastward-facing
3848           ELSEIF ( surfl(1,i) == 4 )  THEN
3849              surf_usm_v(2)%rad_in_sw(m)  = surfinsw(i) 
3850              surf_usm_v(2)%rad_out_sw(m) = surfoutsw(i) 
3851              surf_usm_v(2)%rad_in_lw(m)  = surfinlw(i)
3852              surf_usm_v(2)%rad_out_lw(m) = surfoutlw(i)
3853           ENDIF
3854
3855        ENDDO
3856
3857
3858        DO  m = 1, surf_usm_h%ns
3859           surf_usm_h%surfhf(m) = surf_usm_h%rad_in_sw(m)  +                   &
3860                                  surf_usm_h%rad_in_lw(m)  -                   &
3861                                  surf_usm_h%rad_out_sw(m) -                   &
3862                                  surf_usm_h%rad_out_lw(m)
3863        ENDDO
3864
3865        DO  l = 0, 3
3866           DO  m = 1, surf_usm_v(l)%ns
3867              surf_usm_v(l)%surfhf(m) = surf_usm_v(l)%rad_in_sw(m)  +          &
3868                                        surf_usm_v(l)%rad_in_lw(m)  -          &
3869                                        surf_usm_v(l)%rad_out_sw(m) -          &
3870                                        surf_usm_v(l)%rad_out_lw(m)
3871           ENDDO
3872        ENDDO
3873
3874!--     return surface radiation to horizontal surfaces
3875!--     to rad_sw_in, rad_lw_in and rad_net for outputs
3876        !!!!!!!!!!
3877!--     we need the original radiation on urban top layer
3878!--     for calculation of MRT so we can't do adjustment here for now
3879        !!!!!!!!!!
3880        !!!DO isurf = 1, nsurfl
3881        !!!    i = surfl(ix,isurf)
3882        !!!    j = surfl(iy,isurf)
3883        !!!    k = surfl(iz,isurf)
3884        !!!    d = surfl(id,isurf)
3885        !!!    IF ( d==iroof )  THEN
3886        !!!        rad_sw_in(:,j,i) = surfinsw(isurf)
3887        !!!        rad_lw_in(:,j,i) = surfinlw(isurf)
3888        !!!        rad_net(j,i) = rad_sw_in(k,j,i) - rad_sw_out(k,j,i) + rad_lw_in(k,j,i) - rad_lw_out(k,j,i)
3889        !!!    ENDIF
3890        !!!ENDDO
3891
3892    END SUBROUTINE usm_radiation
3893
3894   
3895!------------------------------------------------------------------------------!
3896! Description:
3897! ------------
3898!> Raytracing for detecting obstacles and calculating compound canopy sink
3899!> factors. (A simple obstacle detection would only need to process faces in
3900!> 3 dimensions without any ordering.)
3901!> Assumtions:
3902!> -----------
3903!> 1. The ray always originates from a face midpoint (only one coordinate equals
3904!>    *.5, i.e. wall) and doesn't travel parallel to the surface (that would mean
3905!>    shape factor=0). Therefore, the ray may never travel exactly along a face
3906!>    or an edge.
3907!> 2. From grid bottom to urban surface top the grid has to be *equidistant*
3908!>    within each of the dimensions, including vertical (but the resolution
3909!>    doesn't need to be the same in all three dimensions).
3910!------------------------------------------------------------------------------!
3911    SUBROUTINE usm_raytrace(src, targ, isrc, rirrf, atarg, create_csf, visible, transparency, win_lad)
3912        IMPLICIT NONE
3913
3914        REAL(wp), DIMENSION(3), INTENT(in)     :: src, targ    !< real coordinates z,y,x
3915        INTEGER(iwp), INTENT(in)               :: isrc         !< index of source face for csf
3916        REAL(wp), INTENT(in)                   :: rirrf        !< irradiance factor for csf
3917        REAL(wp), INTENT(in)                   :: atarg        !< target surface area for csf
3918        LOGICAL, INTENT(in)                    :: create_csf   !< whether to generate new CSFs during raytracing
3919        LOGICAL, INTENT(out)                   :: visible
3920        REAL(wp), INTENT(out)                  :: transparency !< along whole path
3921        INTEGER(iwp), INTENT(in)               :: win_lad
3922        INTEGER(iwp)                           :: i, j, k, d
3923        INTEGER(iwp)                           :: seldim       !< dimension to be incremented
3924        INTEGER(iwp)                           :: ncsb         !< no of written plant canopy sinkboxes
3925        INTEGER(iwp)                           :: maxboxes     !< max no of gridboxes visited
3926        REAL(wp)                               :: distance     !< euclidean along path
3927        REAL(wp)                               :: crlen        !< length of gridbox crossing
3928        REAL(wp)                               :: lastdist     !< beginning of current crossing
3929        REAL(wp)                               :: nextdist     !< end of current crossing
3930        REAL(wp)                               :: realdist     !< distance in meters per unit distance
3931        REAL(wp)                               :: crmid        !< midpoint of crossing