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

Last change on this file since 2213 was 2213, checked in by kanani, 8 years ago

bugfix in PCM output, minor formatting and clean-up

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