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

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

last commit documented

  • Property svn:keywords set to Id
File size: 207.5 KB
Line 
1!> @file urban_surface_mod.f90
2!--------------------------------------------------------------------------------!
3! This file is part of PALM.
4!
5! PALM is free software: you can redistribute it and/or modify it under the
6! terms of the GNU General Public License as published by the Free Software
7! Foundation, either version 3 of the License, or (at your option) any later
8! version.
9!
10! PALM is distributed in the hope that it will be useful, but WITHOUT ANY
11! WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12! A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13!
14! You should have received a copy of the GNU General Public License along with
15! PALM. If not, see <http://www.gnu.org/licenses/>.
16!
17! Copyright 2015-2017 Czech Technical University in Prague
18! Copyright 1997-2017 Leibniz Universitaet Hannover
19!--------------------------------------------------------------------------------!
20!
21! Current revisions:
22! ------------------
23!
24!
25! Former revisions:
26! -----------------
27! $Id: urban_surface_mod.f90 2210 2017-04-19 09:35:50Z 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 IF ( plant_canopy  .AND.  var(1:7) == 'usm_lad' )  THEN
2008            unit = 'm2/m3'
2009        ELSE IF ( plant_canopy  .AND.  var(1:13) == 'usm_canopy_hr' )  THEN
2010            unit = 'K/s'
2011        ELSE
2012            unit = 'illegal'
2013        ENDIF
2014
2015    END SUBROUTINE usm_check_data_output
2016
2017
2018!------------------------------------------------------------------------------!
2019! Description:
2020! ------------
2021!> Check parameters routine for urban surface model
2022!------------------------------------------------------------------------------!
2023    SUBROUTINE usm_check_parameters
2024   
2025       USE control_parameters,                                                 &
2026           ONLY:  bc_pt_b, bc_q_b, constant_flux_layer, large_scale_forcing,   &
2027                  lsf_surf, topography
2028
2029!
2030!--    Dirichlet boundary conditions are required as the surface fluxes are
2031!--    calculated from the temperature/humidity gradients in the urban surface
2032!--    model
2033       IF ( bc_pt_b == 'neumann'   .OR.   bc_q_b == 'neumann' )  THEN
2034          message_string = 'urban surface model requires setting of '//        &
2035                           'bc_pt_b = "dirichlet" and '//                      &
2036                           'bc_q_b  = "dirichlet"'
2037          CALL message( 'check_parameters', 'PA0590', 1, 2, 0, 6, 0 )
2038       ENDIF
2039
2040       IF ( .NOT.  constant_flux_layer )  THEN
2041          message_string = 'urban surface model requires '//                   &
2042                           'constant_flux_layer = .T.'
2043          CALL message( 'check_parameters', 'PA0591', 1, 2, 0, 6, 0 )
2044       ENDIF
2045!       
2046!--    Surface forcing has to be disabled for LSF in case of enabled
2047!--    urban surface module
2048       IF ( large_scale_forcing )  THEN
2049          lsf_surf = .FALSE.
2050       ENDIF
2051!
2052!--    Topography
2053       IF ( topography == 'flat' )  THEN
2054          message_string = 'topography /= "flat" is required '//               &
2055                           'when using the urban surface model'
2056          CALL message( 'check_parameters', 'PA0592', 1, 2, 0, 6, 0 )
2057       ENDIF
2058
2059
2060    END SUBROUTINE usm_check_parameters
2061
2062
2063!------------------------------------------------------------------------------!
2064!
2065! Description:
2066! ------------
2067!> Output of the 3D-arrays in netCDF and/or AVS format
2068!> for variables of urban_surface model.
2069!> It resorts the urban surface module output quantities from surf style
2070!> indexing into temporary 3D array with indices (i,j,k).
2071!> It is called from subroutine data_output_3d.
2072!------------------------------------------------------------------------------!
2073    SUBROUTINE usm_data_output_3d( av, variable, found, local_pf, nzb_do, nzt_do )
2074       
2075        IMPLICIT NONE
2076
2077        INTEGER(iwp), INTENT(IN)       ::  av        !<
2078        CHARACTER (len=*), INTENT(IN)  ::  variable  !<
2079        INTEGER(iwp), INTENT(IN)       ::  nzb_do    !< lower limit of the data output (usually 0)
2080        INTEGER(iwp), INTENT(IN)       ::  nzt_do    !< vertical upper limit of the data output (usually nz_do3d)
2081        LOGICAL, INTENT(OUT)           ::  found     !<
2082        REAL(sp), DIMENSION(nxlg:nxrg,nysg:nyng,nzb_do:nzt_do) ::  local_pf   !< sp - it has to correspond to module data_output_3d
2083        REAL(wp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg)     ::  temp_pf    !< temp array for urban surface output procedure
2084       
2085        CHARACTER (len=varnamelength)                          :: var, surfid
2086        INTEGER(iwp), PARAMETER                                :: nd = 5
2087        CHARACTER(len=6), DIMENSION(0:nd-1), PARAMETER         :: dirname = (/ '_roof ', '_south', '_north', '_west ', '_east ' /)
2088        INTEGER(iwp), DIMENSION(0:nd-1), PARAMETER             :: dirint = (/ iroof, isouth, inorth, iwest, ieast /)
2089        INTEGER(iwp), DIMENSION(0:nd-1)                        :: dirstart
2090        INTEGER(iwp), DIMENSION(0:nd-1)                        :: dirend
2091        INTEGER(iwp)                                           :: ids,isurf,isvf,isurfs,isurflt
2092        INTEGER(iwp)                                           :: is,js,ks,i,j,k,iwl,istat
2093
2094        dirstart = (/ startland, startwall, startwall, startwall, startwall /)
2095        dirend = (/ endland, endwall, endwall, endwall, endwall /)
2096
2097        found = .TRUE.
2098        temp_pf = -1._wp
2099       
2100        ids = -1
2101        var = TRIM(variable)
2102        DO i = 0, nd-1
2103            k = len(TRIM(var))
2104            j = len(TRIM(dirname(i)))
2105            IF ( var(k-j+1:k) == dirname(i) )  THEN
2106                ids = i
2107                var = var(:k-j)
2108                EXIT
2109            ENDIF
2110        ENDDO
2111        IF ( ids == -1 )  THEN
2112            var = TRIM(variable)
2113        ENDIF
2114        IF ( var(1:11) == 'usm_t_wall_'  .AND.  len(TRIM(var)) >= 12 )  THEN
2115!--         wall layers
2116            READ(var(12:12), '(I1)', iostat=istat ) iwl
2117            IF ( istat == 0  .AND.  iwl >= nzb_wall  .AND.  iwl <= nzt_wall )  THEN
2118                var = var(1:10)
2119            ENDIF
2120        ENDIF
2121        IF ( (var(1:8) == 'usm_svf_'  .OR.  var(1:8) == 'usm_dif_')  .AND.  len(TRIM(var)) >= 13 )  THEN
2122!--         svf values to particular surface
2123            surfid = var(9:)
2124            i = index(surfid,'_')
2125            j = index(surfid(i+1:),'_')
2126            READ(surfid(1:i-1),*, iostat=istat ) is
2127            IF ( istat == 0 )  THEN
2128                READ(surfid(i+1:i+j-1),*, iostat=istat ) js
2129            ENDIF
2130            IF ( istat == 0 )  THEN
2131                READ(surfid(i+j+1:),*, iostat=istat ) ks
2132            ENDIF
2133            IF ( istat == 0 )  THEN
2134                var = var(1:7)
2135            ENDIF
2136        ENDIF
2137       
2138        SELECT CASE ( TRIM(var) )
2139
2140          CASE ( 'usm_surfz' )
2141!--           array of lw radiation falling to local surface after i-th reflection
2142              DO isurf = dirstart(ids), dirend(ids)
2143                  IF ( surfl(id,isurf) == ids )  THEN
2144                      IF ( surfl(id,isurf) == iroof )  THEN
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))
2148                      ELSE
2149                          temp_pf(0,surfl(iy,isurf),surfl(ix,isurf)) =             &
2150                                  max(temp_pf(0,surfl(iy,isurf),surfl(ix,isurf)),  &
2151                                      REAL(surfl(iz,isurf),wp)+1.0_wp)
2152                      ENDIF
2153                  ENDIF
2154              ENDDO
2155
2156          CASE ( 'usm_surfcat' )
2157!--           surface category
2158              DO isurf = dirstart(ids), dirend(ids)
2159                 IF ( surfl(id,isurf) == ids )  THEN
2160                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surface_types(isurf)
2161                 ENDIF
2162              ENDDO
2163             
2164          CASE ( 'usm_surfalb' )
2165!--           surface albedo
2166              DO isurf = dirstart(ids), dirend(ids)
2167                 IF ( surfl(id,isurf) == ids )  THEN
2168                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = albedo_surf(isurf)
2169                 ENDIF
2170              ENDDO
2171             
2172          CASE ( 'usm_surfemis' )
2173!--           surface albedo
2174              DO isurf = dirstart(ids), dirend(ids)
2175                 IF ( surfl(id,isurf) == ids )  THEN
2176                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = emiss_surf(isurf)
2177                 ENDIF
2178              ENDDO
2179             
2180          CASE ( 'usm_svf', 'usm_dif' )
2181!--           shape view factors or iradiance factors to selected surface
2182              IF ( TRIM(var)=='usm_svf' )  THEN
2183                  k = 1
2184              ELSE
2185                  k = 2
2186              ENDIF
2187              DO isvf = 1, nsvfl
2188                  isurflt = svfsurf(1, isvf)
2189                  isurfs = svfsurf(2, isvf)
2190                             
2191                  IF ( surf(ix,isurfs) == is  .AND.  surf(iy,isurfs) == js  .AND.       &
2192                       surf(iz,isurfs) == ks  .AND.  surf(id,isurfs) == ids )  THEN
2193  !--                 correct source surface
2194                      temp_pf(surfl(iz,isurflt),surfl(iy,isurflt),surfl(ix,isurflt)) = svf(k,isvf)
2195                  ENDIF
2196              ENDDO
2197
2198          CASE ( 'usm_rad_net' )
2199!--           array of complete radiation balance
2200              DO isurf = dirstart(ids), dirend(ids)
2201                 IF ( surfl(id,isurf) == ids )  THEN
2202                   IF ( av == 0 )  THEN
2203                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = rad_net_l(isurf)
2204                   ELSE
2205                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = rad_net_av(isurf)
2206                   ENDIF
2207                 ENDIF
2208              ENDDO
2209
2210          CASE ( 'usm_rad_insw' )
2211!--           array of sw radiation falling to surface after i-th reflection
2212              DO isurf = dirstart(ids), dirend(ids)
2213                 IF ( surfl(id,isurf) == ids )  THEN
2214                   IF ( av == 0 )  THEN
2215                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinsw(isurf)
2216                   ELSE
2217                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinsw_av(isurf)
2218                   ENDIF
2219                 ENDIF
2220              ENDDO
2221
2222          CASE ( 'usm_rad_inlw' )
2223!--           array of lw radiation falling to surface after i-th reflection
2224              DO isurf = dirstart(ids), dirend(ids)
2225                 IF ( surfl(id,isurf) == ids )  THEN
2226                   IF ( av == 0 )  THEN
2227                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlw(isurf)
2228                   ELSE
2229                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlw_av(isurf)
2230                   ENDIF
2231                 ENDIF
2232              ENDDO
2233
2234          CASE ( 'usm_rad_inswdir' )
2235!--           array of direct sw radiation falling to surface from sun
2236              DO isurf = dirstart(ids), dirend(ids)
2237                 IF ( surfl(id,isurf) == ids )  THEN
2238                   IF ( av == 0 )  THEN
2239                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdir(isurf)
2240                   ELSE
2241                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdir_av(isurf)
2242                   ENDIF
2243                 ENDIF
2244              ENDDO
2245
2246          CASE ( 'usm_rad_inswdif' )
2247!--           array of difusion sw radiation falling to surface from sky and borders of the domain
2248              DO isurf = dirstart(ids), dirend(ids)
2249                 IF ( surfl(id,isurf) == ids )  THEN
2250                   IF ( av == 0 )  THEN
2251                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdif(isurf)
2252                   ELSE
2253                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswdif_av(isurf)
2254                   ENDIF
2255                 ENDIF
2256              ENDDO
2257
2258          CASE ( 'usm_rad_inswref' )
2259!--           array of sw radiation falling to surface from reflections
2260              DO isurf = dirstart(ids), dirend(ids)
2261                 IF ( surfl(id,isurf) == ids )  THEN
2262                   IF ( av == 0 )  THEN
2263                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = &
2264                       surfinsw(isurf) - surfinswdir(isurf) - surfinswdif(isurf)
2265                   ELSE
2266                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinswref_av(isurf)
2267                   ENDIF
2268                 ENDIF
2269              ENDDO
2270
2271          CASE ( 'usm_rad_inlwdif' )
2272!--           array of sw radiation falling to surface after i-th reflection
2273              DO isurf = dirstart(ids), dirend(ids)
2274                 IF ( surfl(id,isurf) == ids )  THEN
2275                   IF ( av == 0 )  THEN
2276                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlwdif(isurf)
2277                   ELSE
2278                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlwdif_av(isurf)
2279                   ENDIF
2280                 ENDIF
2281              ENDDO
2282
2283          CASE ( 'usm_rad_inlwref' )
2284!--           array of lw radiation falling to surface from reflections
2285              DO isurf = dirstart(ids), dirend(ids)
2286                 IF ( surfl(id,isurf) == ids )  THEN
2287                   IF ( av == 0 )  THEN
2288                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlw(isurf) - surfinlwdif(isurf)
2289                   ELSE
2290                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinlwref_av(isurf)
2291                   ENDIF
2292                 ENDIF
2293              ENDDO
2294
2295          CASE ( 'usm_rad_outsw' )
2296!--           array of sw radiation emitted from surface after i-th reflection
2297              DO isurf = dirstart(ids), dirend(ids)
2298                 IF ( surfl(id,isurf) == ids )  THEN
2299                   IF ( av == 0 )  THEN
2300                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutsw(isurf)
2301                   ELSE
2302                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutsw_av(isurf)
2303                   ENDIF
2304                 ENDIF
2305              ENDDO
2306
2307          CASE ( 'usm_rad_outlw' )
2308!--           array of lw radiation emitted from surface after i-th reflection
2309              DO isurf = dirstart(ids), dirend(ids)
2310                 IF ( surfl(id,isurf) == ids )  THEN
2311                   IF ( av == 0 )  THEN
2312                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutlw(isurf)
2313                   ELSE
2314                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfoutlw_av(isurf)
2315                   ENDIF
2316                 ENDIF
2317              ENDDO
2318
2319          CASE ( 'usm_rad_ressw' )
2320!--           average of array of residua of sw radiation absorbed in surface after last reflection
2321              DO isurf = dirstart(ids), dirend(ids)
2322                 IF ( surfl(id,isurf) == ids )  THEN
2323                   IF ( av == 0 )  THEN
2324                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfins(isurf)
2325                   ELSE
2326                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfins_av(isurf)
2327                   ENDIF
2328                 ENDIF
2329              ENDDO
2330
2331          CASE ( 'usm_rad_reslw' )
2332!--           average of array of residua of lw radiation absorbed in surface after last reflection
2333              DO isurf = dirstart(ids), dirend(ids)
2334                 IF ( surfl(id,isurf) == ids )  THEN
2335                   IF ( av == 0 )  THEN
2336                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinl(isurf)
2337                   ELSE
2338                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfinl_av(isurf)
2339                   ENDIF
2340                 ENDIF
2341              ENDDO
2342
2343          CASE ( 'usm_rad_hf' )
2344!--           array of heat flux from radiation for surfaces after all reflections
2345              DO isurf = dirstart(ids), dirend(ids)
2346                 IF ( surfl(id,isurf) == ids )  THEN
2347                   IF ( av == 0 )  THEN
2348                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfhf(isurf)
2349                   ELSE
2350                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = surfhf_av(isurf)
2351                   ENDIF
2352                 ENDIF
2353              ENDDO
2354
2355          CASE ( 'usm_wshf' )
2356!--           array of sensible heat flux from surfaces
2357!--           horizontal surfaces
2358              DO isurf = dirstart(ids), dirend(ids)
2359                 IF ( surfl(id,isurf) == ids )  THEN
2360                   IF ( av == 0 )  THEN
2361                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = wshf_eb(isurf)
2362                   ELSE
2363                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = wshf_eb_av(isurf)
2364                   ENDIF
2365                 ENDIF
2366              ENDDO
2367
2368          CASE ( 'usm_wghf' )
2369!--           array of heat flux from ground (land, wall, roof)
2370              DO isurf = dirstart(ids), dirend(ids)
2371                 IF ( surfl(id,isurf) == ids )  THEN
2372                   IF ( av == 0 )  THEN
2373                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = wghf_eb(isurf)
2374                   ELSE
2375                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = wghf_eb_av(isurf)
2376                   ENDIF
2377                 ENDIF
2378              ENDDO
2379
2380          CASE ( 'usm_t_surf' )
2381!--           surface temperature for surfaces
2382              DO isurf = max(startenergy,dirstart(ids)), min(endenergy,dirend(ids))
2383                 IF ( surfl(id,isurf) == ids )  THEN
2384                   IF ( av == 0 )  THEN
2385                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = t_surf(isurf)
2386                   ELSE
2387                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = t_surf_av(isurf)
2388                   ENDIF
2389                 ENDIF
2390              ENDDO
2391             
2392          CASE ( 'usm_t_wall' )
2393!--           wall temperature for  iwl layer of walls and land
2394              DO isurf = dirstart(ids), dirend(ids)
2395                 IF ( surfl(id,isurf) == ids )  THEN
2396                   IF ( av == 0 )  THEN
2397                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = t_wall(iwl,isurf)
2398                   ELSE
2399                     temp_pf(surfl(iz,isurf),surfl(iy,isurf),surfl(ix,isurf)) = t_wall_av(iwl,isurf)
2400                   ENDIF
2401                 ENDIF
2402              ENDDO
2403
2404          CASE ( 'usm_lad' )
2405!--           leaf area density
2406              DO i = nxl, nxr
2407                 DO j = nys, nyn
2408                     DO k = nzb_s_inner(j,i), nzut
2409                         temp_pf(k,j,i) = lad_s(k-nzb_s_inner(j,i),j,i)
2410                     ENDDO
2411                 ENDDO
2412              ENDDO
2413             
2414          CASE ( 'usm_canopy_hr' )
2415!--           canopy heating rate
2416              DO i = nxl, nxr
2417                 DO j = nys, nyn
2418                     DO k = nzb_s_inner(j,i), nzut
2419                         temp_pf(k,j,i) = pc_heating_rate(k-nzb_s_inner(j,i),j,i)
2420                     ENDDO
2421                 ENDDO
2422              ENDDO
2423             
2424          CASE DEFAULT
2425              found = .FALSE.
2426             
2427        END SELECT
2428       
2429!--     fill out array local_pf which is subsequently treated by data_output_3d
2430        CALL exchange_horiz( temp_pf, nbgp )
2431        DO j = nysg,nyng
2432            DO i = nxlg,nxrg
2433                DO k = nzb_do, nzt_do
2434                    local_pf(i,j,k) = temp_pf(k,j,i)
2435                ENDDO
2436            ENDDO
2437        ENDDO
2438       
2439    END SUBROUTINE usm_data_output_3d
2440   
2441
2442!------------------------------------------------------------------------------!
2443!
2444! Description:
2445! ------------
2446!> Soubroutine defines appropriate grid for netcdf variables.
2447!> It is called out from subroutine netcdf.
2448!------------------------------------------------------------------------------!
2449    SUBROUTINE usm_define_netcdf_grid( variable, found, grid_x, grid_y, grid_z )
2450   
2451        IMPLICIT NONE
2452
2453        CHARACTER (len=*), INTENT(IN)  ::  variable    !<
2454        LOGICAL, INTENT(OUT)           ::  found       !<
2455        CHARACTER (len=*), INTENT(OUT) ::  grid_x      !<
2456        CHARACTER (len=*), INTENT(OUT) ::  grid_y      !<
2457        CHARACTER (len=*), INTENT(OUT) ::  grid_z      !<
2458
2459        CHARACTER (len=varnamelength)  :: var
2460
2461        var = TRIM(variable)
2462        IF ( var(1:12) == 'usm_rad_net_'  .OR.  var(1:13) == 'usm_rad_insw_'  .OR.          &
2463             var(1:13) == 'usm_rad_inlw_'  .OR.  var(1:16) == 'usm_rad_inswdir_'  .OR.      &
2464             var(1:16) == 'usm_rad_inswdif_'  .OR.  var(1:16) == 'usm_rad_inswref_'  .OR.   &
2465             var(1:16) == 'usm_rad_inlwdif_'  .OR.  var(1:16) == 'usm_rad_inlwref_'  .OR.   &
2466             var(1:14) == 'usm_rad_outsw_'  .OR.  var(1:14) == 'usm_rad_outlw_'  .OR.       &
2467             var(1:14) == 'usm_rad_ressw_'  .OR.  var(1:14) == 'usm_rad_reslw_'  .OR.       &
2468             var(1:11) == 'usm_rad_hf_'  .OR.                                               &
2469             var(1:9) == 'usm_wshf_'  .OR.  var(1:9) == 'usm_wghf_'  .OR.                   &
2470             var(1:10) == 'usm_t_surf'  .OR.  var(1:10) == 'usm_t_wall'  .OR.               &
2471             var(1:9) == 'usm_surfz'  .OR.  var(1:7) == 'usm_svf'  .OR.                     & 
2472             var(1:7) == 'usm_dif'  .OR.  var(1:11) == 'usm_surfcat'  .OR.                  &
2473             var(1:11) == 'usm_surfalb'  .OR.  var(1:12) == 'usm_surfemis'  .OR.            &
2474             var(1:7) == 'usm_lad'  .OR.  var(1:13) == 'usm_canopy_hr' )  THEN
2475
2476            found = .TRUE.
2477            grid_x = 'x'
2478            grid_y = 'y'
2479            grid_z = 'zu'
2480        ELSE
2481            found  = .FALSE.
2482            grid_x = 'none'
2483            grid_y = 'none'
2484            grid_z = 'none'
2485        ENDIF
2486
2487    END SUBROUTINE usm_define_netcdf_grid
2488   
2489   
2490!------------------------------------------------------------------------------!
2491!> Finds first model boundary crossed by a ray
2492!------------------------------------------------------------------------------!
2493    PURE SUBROUTINE usm_find_boundary_face(origin, uvect, bdycross)
2494   
2495       IMPLICIT NONE
2496       
2497       INTEGER(iwp) ::  d       !<
2498       INTEGER(iwp) ::  seldim  !< found fist crossing index
2499
2500       INTEGER(iwp), DIMENSION(3)              ::  bdyd      !< boundary direction       
2501       INTEGER(iwp), DIMENSION(4), INTENT(out) ::  bdycross  !< found boundary crossing (d, z, y, x)
2502       
2503       REAL(wp)                                ::  bdydim  !<
2504       REAL(wp)                                ::  dist    !<
2505       
2506       REAL(wp), DIMENSION(3)             ::  crossdist  !< crossing distance
2507       REAL(wp), DIMENSION(3), INTENT(in) ::  origin     !< ray origin
2508       REAL(wp), DIMENSION(3), INTENT(in) ::  uvect      !< ray unit vector
2509 
2510
2511       bdydim       = nzut + .5_wp  !< top boundary
2512       bdyd(1)      = isky
2513       crossdist(1) = ( bdydim - origin(1) ) / uvect(1)  !< subroutine called only when uvect(1)>0
2514
2515       IF ( uvect(2) == 0._wp )  THEN
2516          crossdist(2) = huge(1._wp)
2517       ELSE
2518          IF ( uvect(2) >= 0._wp )  THEN
2519             bdydim  = ny + .5_wp  !< north global boundary
2520             bdyd(2) = inorthb
2521          ELSE
2522             bdydim  = -.5_wp  !< south global boundary
2523             bdyd(2) = isouthb
2524          ENDIF
2525          crossdist(2) = ( bdydim - origin(2) ) / uvect(2)
2526       ENDIF
2527
2528       IF ( uvect(3) == 0._wp )  THEN
2529          crossdist(3) = huge(1._wp)
2530       ELSE
2531          IF ( uvect(3) >= 0._wp )  THEN
2532             bdydim  = nx + .5_wp  !< east global boundary
2533             bdyd(3) = ieastb
2534          ELSE
2535             bdydim  = -.5_wp  !< west global boundary
2536             bdyd(3) = iwestb
2537          ENDIF
2538          crossdist(3) = ( bdydim - origin(3) ) / uvect(3)
2539       ENDIF
2540
2541       seldim = minloc(crossdist, 1)
2542       dist   = crossdist(seldim)
2543       d      = bdyd(seldim)
2544
2545       bdycross(1)   = d
2546       bdycross(2:4) = NINT( origin(:) + uvect(:) * dist &
2547                                       + .5_wp * (/ kdir(d), jdir(d), idir(d) /) )
2548                       
2549    END SUBROUTINE
2550
2551
2552!------------------------------------------------------------------------------!
2553!> Determines whether two faces are oriented towards each other
2554!------------------------------------------------------------------------------!
2555    PURE LOGICAL FUNCTION usm_facing(x, y, z, d, x2, y2, z2, d2)
2556        IMPLICIT NONE
2557        INTEGER(iwp),   INTENT(in)  :: x, y, z, d, x2, y2, z2, d2
2558     
2559        usm_facing = .FALSE.
2560        IF ( d==iroof  .AND.  d2==iroof ) RETURN
2561        IF ( d==isky  .AND.  d2==isky ) RETURN
2562        IF ( (d==isouth  .OR.  d==inorthb)  .AND.  (d2==isouth.OR.d2==inorthb) ) RETURN
2563        IF ( (d==inorth  .OR.  d==isouthb)  .AND.  (d2==inorth.OR.d2==isouthb) ) RETURN
2564        IF ( (d==iwest  .OR.  d==ieastb)  .AND.  (d2==iwest.OR.d2==ieastb) ) RETURN
2565        IF ( (d==ieast  .OR.  d==iwestb)  .AND.  (d2==ieast.OR.d2==iwestb) ) RETURN
2566
2567        SELECT CASE (d)
2568            CASE (iroof)                   !< ground, roof
2569                IF ( z2 < z ) RETURN
2570            CASE (isky)                    !< sky
2571                IF ( z2 > z ) RETURN
2572            CASE (isouth, inorthb)         !< south facing
2573                IF ( y2 > y ) RETURN
2574            CASE (inorth, isouthb)         !< north facing
2575                IF ( y2 < y ) RETURN
2576            CASE (iwest, ieastb)           !< west facing
2577                IF ( x2 > x ) RETURN
2578            CASE (ieast, iwestb)           !< east facing
2579                IF ( x2 < x ) RETURN
2580        END SELECT
2581
2582        SELECT CASE (d2)
2583            CASE (iroof)                   !< ground, roof
2584                IF ( z < z2 ) RETURN
2585            CASE (isky)                    !< sky
2586                IF ( z > z2 ) RETURN
2587            CASE (isouth, inorthb)         !< south facing
2588                IF ( y > y2 ) RETURN
2589            CASE (inorth, isouthb)         !< north facing
2590                IF ( y < y2 ) RETURN
2591            CASE (iwest, ieastb)           !< west facing
2592                IF ( x > x2 ) RETURN
2593            CASE (ieast, iwestb)           !< east facing
2594                IF ( x < x2 ) RETURN
2595            CASE (-1)
2596                CONTINUE
2597        END SELECT
2598
2599        usm_facing = .TRUE.
2600       
2601    END FUNCTION usm_facing
2602   
2603
2604!------------------------------------------------------------------------------!
2605! Description:
2606! ------------
2607!> Initialization of the wall surface model
2608!------------------------------------------------------------------------------!
2609    SUBROUTINE usm_init_material_model
2610
2611        IMPLICIT NONE
2612
2613        INTEGER(iwp) ::  k, l            !< running indices
2614       
2615        CALL location_message( '    initialization of wall surface model', .TRUE. )
2616       
2617!--     Calculate wall grid spacings.
2618!--     Temperature is defined at the center of the wall layers,
2619!--     whereas gradients/fluxes are defined at the edges (_stag)
2620        DO l = nzb_wall, nzt_wall
2621           zwn(l) = zwn_default(l)
2622        ENDDO
2623       
2624!--     apply for all particular wall grids
2625        DO l = startenergy, endenergy
2626           zw(:,l) = zwn(:) * thickness_wall(l)
2627           dz_wall(nzb_wall,l) = zw(nzb_wall,l)
2628           DO k = nzb_wall+1, nzt_wall
2629               dz_wall(k,l) = zw(k,l) - zw(k-1,l)
2630           ENDDO
2631           
2632           dz_wall(nzt_wall+1,l) = dz_wall(nzt_wall,l)
2633
2634           DO k = nzb_wall, nzt_wall-1
2635               dz_wall_stag(k,l) = 0.5 * (dz_wall(k+1,l) + dz_wall(k,l))
2636           ENDDO
2637           dz_wall_stag(nzt_wall,l) = dz_wall(nzt_wall,l)
2638        ENDDO
2639       
2640        ddz_wall      = 1.0_wp / dz_wall
2641        ddz_wall_stag = 1.0_wp / dz_wall_stag
2642       
2643        CALL location_message( '    wall structures filed out', .TRUE. )
2644
2645        CALL location_message( '    initialization of wall surface model finished', .TRUE. )
2646
2647    END SUBROUTINE usm_init_material_model
2648
2649 
2650!------------------------------------------------------------------------------!
2651! Description:
2652! ------------
2653!> Initialization of the urban surface model
2654!------------------------------------------------------------------------------!
2655    SUBROUTINE usm_init_urban_surface
2656   
2657        IMPLICIT NONE
2658
2659        INTEGER(iwp) ::  i, j, k, l            !< running indices
2660        REAL(wp)     ::  c, d, tin, exn
2661       
2662
2663        CALL cpu_log( log_point_s(78), 'usm_init', 'start' )
2664!--     surface forcing have to be disabled for LSF
2665!--     in case of enabled urban surface module
2666        IF ( large_scale_forcing )  THEN
2667            lsf_surf = .FALSE.
2668        ENDIF
2669       
2670!--     init anthropogenic sources of heat
2671        CALL usm_allocate_urban_surface()
2672       
2673!--     read the surface_types array somewhere
2674        CALL usm_read_urban_surface_types()
2675       
2676!--     init material heat model
2677        CALL usm_init_material_model()
2678       
2679        IF ( usm_anthropogenic_heat )  THEN
2680!--         init anthropogenic sources of heat (from transportation for now)
2681            CALL usm_read_anthropogenic_heat()
2682        ENDIF
2683       
2684        IF ( read_svf_on_init )  THEN
2685!--         read svf, csf, svfsurf and csfsurf data from file
2686            CALL location_message( '    Start reading SVF from file', .TRUE. )
2687            CALL usm_read_svf_from_file()
2688            CALL location_message( '    Reading SVF from file has finished', .TRUE. )
2689        ELSE
2690!--         calculate SFV and CSF
2691            CALL location_message( '    Start calculation of SVF', .TRUE. )
2692            CALL cpu_log( log_point_s(79), 'usm_calc_svf', 'start' )
2693            CALL usm_calc_svf()
2694            CALL cpu_log( log_point_s(79), 'usm_calc_svf', 'stop' )
2695            CALL location_message( '    Calculation of SVF has finished', .TRUE. )
2696        ENDIF
2697
2698        IF ( write_svf_on_init )  THEN
2699!--         write svf, csf svfsurf and csfsurf data to file
2700            CALL location_message( '    Store SVF and CSF to file', .TRUE. )
2701            CALL usm_write_svf_to_file()
2702        ENDIF
2703       
2704        IF ( plant_canopy )  THEN
2705!--         gridpcbl was only necessary for initialization
2706            DEALLOCATE( gridpcbl )
2707            IF ( .NOT.  ALLOCATED(pc_heating_rate) )  THEN
2708!--             then pc_heating_rate is allocated in init_plant_canopy
2709!--             in case of cthf /= 0 => we need to allocate it for our use here
2710                ALLOCATE( pc_heating_rate(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
2711            ENDIF
2712        ENDIF
2713
2714!--     Intitialization of the surface and wall/ground/roof temperature
2715
2716!--     Initialization for restart runs
2717        IF ( TRIM( initializing_actions ) == 'read_restart_data' )  THEN
2718
2719!--         restore data from restart file
2720            CALL usm_read_restart_data()
2721        ELSE
2722       
2723!--         Calculate initial surface temperature
2724            exn = ( surface_pressure / 1000.0_wp )**0.286_wp
2725
2726            DO l = startenergy, endenergy
2727                k = surfl(iz,l)
2728                j = surfl(iy,l)
2729                i = surfl(ix,l)
2730
2731!--              Initial surface temperature set from pt of adjacent gridbox
2732                t_surf(l) = pt(k,j,i) * exn
2733            ENDDO
2734     
2735!--         initial values for t_wall
2736!--         outer value is set to surface temperature
2737!--         inner value is set to wall_inner_temperature
2738!--         and profile is logaritmic (linear in nz)
2739            DO l = startenergy, endenergy
2740                IF ( isroof_surf(l) )  THEN
2741                    tin = roof_inner_temperature
2742                ELSE IF ( surf(id,l)==iroof )  THEN
2743                    tin = soil_inner_temperature
2744                ELSE
2745                    tin = wall_inner_temperature
2746                ENDIF
2747                DO k = nzb_wall, nzt_wall+1
2748                    c = REAL(k-nzb_wall,wp)/REAL(nzt_wall+1-nzb_wall,wp)
2749                    t_wall(k,:) = (1.0_wp-c)*t_surf(:) + c*tin
2750                ENDDO
2751            ENDDO
2752        ENDIF
2753       
2754!--   
2755!--        Possibly DO user-defined actions (e.g. define heterogeneous wall surface)
2756        CALL user_init_urban_surface
2757
2758!--     initialize prognostic values for the first timestep
2759        t_surf_p = t_surf
2760        t_wall_p = t_wall
2761       
2762!--     Adjust radiative fluxes for urban surface at model start
2763        CALL usm_radiation
2764       
2765        CALL cpu_log( log_point_s(78), 'usm_init', 'stop' )
2766
2767       
2768    END SUBROUTINE usm_init_urban_surface
2769
2770
2771!------------------------------------------------------------------------------!
2772! Description:
2773! ------------
2774!
2775!> Wall model as part of the urban surface model. The model predicts wall
2776!> temperature.
2777!------------------------------------------------------------------------------!
2778    SUBROUTINE usm_material_heat_model
2779
2780
2781        IMPLICIT NONE
2782
2783        INTEGER(iwp) ::  i,j,k,l,kw                      !< running indices
2784
2785        REAL(wp), DIMENSION(nzb_wall:nzt_wall) :: wtend  !< tendency
2786
2787                                               
2788        DO l = startenergy, endenergy
2789!--         calculate frequently used parameters
2790            k = surfl(iz,l)
2791            j = surfl(iy,l)
2792            i = surfl(ix,l)
2793
2794            !
2795!--         prognostic equation for ground/wall/roof temperature t_wall
2796            wtend(:) = 0.0_wp
2797            wtend(nzb_wall) = (1.0_wp/rho_c_wall(nzb_wall,l)) *                     &
2798                       ( lambda_h(nzb_wall,l) * ( t_wall(nzb_wall+1,l)              &
2799                         - t_wall(nzb_wall,l) ) * ddz_wall(nzb_wall+1,l)            &
2800                         + wghf_eb(l) ) * ddz_wall_stag(nzb_wall,l)
2801           
2802            DO  kw = nzb_wall+1, nzt_wall
2803                wtend(kw) = (1.0_wp/rho_c_wall(kw,l))                               &
2804                              * (   lambda_h(kw,l)                                  &
2805                                 * ( t_wall(kw+1,l) - t_wall(kw,l) )                &
2806                                 * ddz_wall(kw+1,l)                                 &
2807                              - lambda_h(kw-1,l)                                    &
2808                                 * ( t_wall(kw,l) - t_wall(kw-1,l) )                &
2809                                 * ddz_wall(kw,l)                                   &
2810                              ) * ddz_wall_stag(kw,l)
2811            ENDDO
2812
2813            t_wall_p(nzb_wall:nzt_wall,l) = t_wall(nzb_wall:nzt_wall,l)             &
2814                                             + dt_3d * ( tsc(2)                     &
2815                                             * wtend(nzb_wall:nzt_wall) + tsc(3)    &
2816                                             * tt_wall_m(nzb_wall:nzt_wall,l) )   
2817           
2818            !
2819!--         calculate t_wall tendencies for the next Runge-Kutta step
2820            IF ( timestep_scheme(1:5) == 'runge' )  THEN
2821                IF ( intermediate_timestep_count == 1 )  THEN
2822                   DO  kw = nzb_wall, nzt_wall
2823                      tt_wall_m(kw,l) = wtend(kw)
2824                   ENDDO
2825                ELSEIF ( intermediate_timestep_count <                              &
2826                         intermediate_timestep_count_max )  THEN
2827                    DO  kw = nzb_wall, nzt_wall
2828                        tt_wall_m(kw,l) = -9.5625_wp * wtend(kw) + 5.3125_wp        &
2829                                         * tt_wall_m(kw,l)
2830                    ENDDO
2831                ENDIF
2832            ENDIF
2833        ENDDO
2834
2835    END SUBROUTINE usm_material_heat_model
2836
2837
2838!------------------------------------------------------------------------------!
2839! Description:
2840! ------------
2841!> Parin for &usm_par for urban surface model
2842!------------------------------------------------------------------------------!
2843    SUBROUTINE usm_parin
2844
2845       IMPLICIT NONE
2846
2847       CHARACTER (LEN=80) ::  line  !< string containing current line of file PARIN
2848
2849       NAMELIST /urban_surface_par/                                            &
2850                           land_category,                                      &
2851                           mrt_factors,                                        &
2852                           nrefsteps,                                          &
2853                           pedestrant_category,                                &
2854                           ra_horiz_coef,                                      &
2855                           read_svf_on_init,                                   &
2856                           roof_category,                                      &
2857                           split_diffusion_radiation,                          &
2858                           urban_surface,                                      &
2859                           usm_anthropogenic_heat,                             &
2860                           usm_energy_balance_land,                            &
2861                           usm_energy_balance_wall,                            &
2862                           usm_material_model,                                 &
2863                           usm_lad_rma,                                        &
2864                           wall_category,                                      &
2865                           write_svf_on_init
2866
2867       line = ' '
2868
2869!
2870!--    Try to find urban surface model package
2871       REWIND ( 11 )
2872       line = ' '
2873       DO   WHILE ( INDEX( line, '&urban_surface_par' ) == 0 )
2874          READ ( 11, '(A)', END=10 )  line
2875       ENDDO
2876       BACKSPACE ( 11 )
2877
2878!
2879!--    Read user-defined namelist
2880       READ ( 11, urban_surface_par )
2881
2882!
2883!--    Set flag that indicates that the land surface model is switched on
2884       urban_surface = .TRUE.
2885       
2886
2887 10    CONTINUE
2888
2889    END SUBROUTINE usm_parin
2890
2891
2892!------------------------------------------------------------------------------!
2893! Description:
2894! ------------
2895!> This subroutine calculates interaction of the solar radiation
2896!> with urban surface and updates surface, roofs and walls heatfluxes.
2897!> It also updates rad_sw_out and rad_lw_out.
2898!------------------------------------------------------------------------------!
2899    SUBROUTINE usm_radiation
2900   
2901        IMPLICIT NONE
2902       
2903        INTEGER(iwp)               :: i, j, k, kk, is, js, d, ku, refstep
2904        INTEGER(iwp)               :: nzubl, nzutl, isurf, isurfsrc, isurf1, isvf, icsf, ipcgb
2905        INTEGER(iwp), DIMENSION(4) :: bdycross
2906        REAL(wp), DIMENSION(3,3)   :: mrot            !< grid rotation matrix (xyz)
2907        REAL(wp), DIMENSION(3,0:9) :: vnorm           !< face direction normal vectors (xyz)
2908        REAL(wp), DIMENSION(3)     :: sunorig         !< grid rotated solar direction unit vector (xyz)
2909        REAL(wp), DIMENSION(3)     :: sunorig_grid    !< grid squashed solar direction unit vector (zyx)
2910        REAL(wp), DIMENSION(0:9)   :: costheta        !< direct irradiance factor of solar angle
2911        REAL(wp), DIMENSION(nzub:nzut) :: pchf_prep   !< precalculated factor for canopy temp tendency
2912        REAL(wp), PARAMETER        :: alpha = 0._wp   !< grid rotation (TODO: add to namelist or remove)
2913        REAL(wp)                   :: rx, ry, rz
2914        REAL(wp)                   :: pc_box_area, pc_abs_frac, pc_abs_eff
2915        INTEGER(iwp)               :: pc_box_dimshift !< transform for best accuracy
2916       
2917       
2918        IF ( plant_canopy )  THEN
2919            pchf_prep(:) = r_d * (hyp(nzub:nzut) / 100000.0_wp)**0.286_wp &
2920                        / (cp * hyp(nzub:nzut) * dx*dy*dz) !< equals to 1 / (rho * c_p * Vbox * T)
2921        ENDIF
2922
2923        sun_direction = .TRUE.
2924        CALL calc_zenith  !< required also for diffusion radiation
2925
2926!--     prepare rotated normal vectors and irradiance factor
2927        vnorm(1,:) = idir(:)
2928        vnorm(2,:) = jdir(:)
2929        vnorm(3,:) = kdir(:)
2930        mrot(1, :) = (/ cos(alpha), -sin(alpha), 0._wp /)
2931        mrot(2, :) = (/ sin(alpha),  cos(alpha), 0._wp /)
2932        mrot(3, :) = (/ 0._wp,       0._wp,      1._wp /)
2933        sunorig = (/ sun_dir_lon, sun_dir_lat, zenith(0) /)
2934        sunorig = matmul(mrot, sunorig)
2935        DO d = 0, 9
2936            costheta(d) = dot_product(sunorig, vnorm(:,d))
2937        ENDDO
2938       
2939        IF ( zenith(0) > 0 )  THEN
2940!--         now we will "squash" the sunorig vector by grid box size in
2941!--         each dimension, so that this new direction vector will allow us
2942!--         to traverse the ray path within grid coordinates directly
2943            sunorig_grid = (/ sunorig(3)/dz, sunorig(2)/dy, sunorig(1)/dx /)
2944!--         sunorig_grid = sunorig_grid / norm2(sunorig_grid)
2945            sunorig_grid = sunorig_grid / SQRT(SUM(sunorig_grid**2))
2946
2947            IF ( plant_canopy )  THEN
2948!--            precompute effective box depth with prototype Leaf Area Density
2949               pc_box_dimshift = maxloc(sunorig, 1) - 1
2950               CALL usm_box_absorb(cshift((/dx,dy,dz/), pc_box_dimshift),      &
2951                                   60, prototype_lad,                          &
2952                                   cshift(sunorig, pc_box_dimshift),           &
2953                                   pc_box_area, pc_abs_frac)
2954               pc_box_area = pc_box_area * sunorig(pc_box_dimshift+1) / sunorig(3)
2955               pc_abs_eff = log(1._wp - pc_abs_frac) / prototype_lad
2956            ENDIF
2957        ENDIF
2958       
2959!--     split diffusion and direct part of the solar downward radiation
2960!--     comming from radiation model and store it in 2D arrays
2961!--     rad_sw_in_diff, rad_sw_in_dir and rad_lw_in_diff
2962        IF ( split_diffusion_radiation )  THEN
2963            CALL usm_calc_diffusion_radiation
2964        ELSE
2965            rad_sw_in_diff = 0.0_wp
2966            rad_sw_in_dir(:,:)  = rad_sw_in(0,:,:)
2967            rad_lw_in_diff(:,:) = rad_lw_in(0,:,:)
2968        ENDIF
2969
2970!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2971!--     First pass: direct + diffuse irradiance
2972!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2973        surfinswdir   = 0._wp
2974        surfinswdif   = 0._wp
2975        surfinlwdif   = 0._wp
2976        surfins   = 0._wp
2977        surfinl   = 0._wp
2978        surfoutsl    = 0._wp
2979        surfoutll    = 0._wp
2980       
2981!--     Set up thermal radiation from surfaces
2982!--     emiss_surf is defined only for surfaces for which energy balance is calculated
2983        surfoutll(startenergy:endenergy) = emiss_surf(startenergy:endenergy) * sigma_sb   &
2984                                           * t_surf(startenergy:endenergy)**4
2985       
2986#if defined( __parallel )
2987!--     might be optimized and gather only values relevant for current processor
2988        CALL MPI_AllGatherv(surfoutll, nenergy, MPI_REAL, &
2989                            surfoutl, nsurfs, surfstart, MPI_REAL, comm2d, ierr)
2990#else
2991        surfoutl(:) = surfoutll(:)
2992#endif
2993       
2994        isurf1 = -1   !< previous processed surface
2995        DO isvf = 1, nsvfl
2996            isurf = svfsurf(1, isvf)
2997            k = surfl(iz, isurf)
2998            j = surfl(iy, isurf)
2999            i = surfl(ix, isurf)
3000            isurfsrc = svfsurf(2, isvf)
3001            IF ( zenith(0) > 0  .AND.  isurf /= isurf1 )  THEN
3002!--             locate the virtual surface where the direct solar ray crosses domain boundary
3003!--             (once per target surface)
3004                d = surfl(id, isurf)
3005                rz = REAL(k, wp) - 0.5_wp * kdir(d)
3006                ry = REAL(j, wp) - 0.5_wp * jdir(d)
3007                rx = REAL(i, wp) - 0.5_wp * idir(d)
3008               
3009                CALL usm_find_boundary_face( (/ rz, ry, rx /), sunorig_grid, bdycross)
3010               
3011                isurf1 = isurf
3012            ENDIF
3013
3014            IF ( surf(id, isurfsrc) >= isky )  THEN
3015!--             diffuse rad from boundary surfaces. Since it is a simply
3016!--             calculated value, it is not assigned to surfref(s/l),
3017!--             instead it is used directly here
3018!--             we consider the radiation from the radiation model falling on surface
3019!--             as the radiation falling on the top of urban layer into the place of the source surface
3020!--             we consider it as a very reasonable simplification which allow as avoid
3021!--             necessity of other global range arrays and some all to all mpi communication
3022                surfinswdif(isurf) = surfinswdif(isurf) + rad_sw_in_diff(j,i) * svf(1,isvf) * svf(2,isvf)
3023                                                                !< canopy shading is applied only to shortwave
3024                surfinlwdif(isurf) = surfinlwdif(isurf) + rad_lw_in_diff(j,i) * svf(1,isvf)
3025            ELSE
3026!--             for surface-to-surface factors we calculate thermal radiation in 1st pass
3027                surfinl(isurf) = surfinl(isurf) + svf(1,isvf) * surfoutl(isurfsrc)
3028            ENDIF
3029           
3030            IF ( zenith(0) > 0  .AND.  all( surf(:, isurfsrc) == bdycross ) )  THEN
3031!--             found svf between model boundary and the face => face isn't shaded
3032                surfinswdir(isurf) = rad_sw_in_dir(j, i) &
3033                    * costheta(surfl(id, isurf)) * svf(2,isvf) / zenith(0)
3034
3035            ENDIF
3036        ENDDO
3037
3038        IF ( plant_canopy )  THEN
3039       
3040            pcbinsw(:) = 0._wp
3041            pcbinlw(:) = 0._wp  !< will stay always 0 since we don't absorb lw anymore
3042            !
3043!--         pcsf first pass
3044            isurf1 = -1  !< previous processed pcgb
3045            DO icsf = 1, ncsfl
3046                ipcgb = csfsurf(1, icsf)
3047                i = pcbl(ix,ipcgb)
3048                j = pcbl(iy,ipcgb)
3049                k = pcbl(iz,ipcgb)
3050                isurfsrc = csfsurf(2, icsf)
3051
3052                IF ( zenith(0) > 0  .AND.  ipcgb /= isurf1 )  THEN
3053!--                 locate the virtual surface where the direct solar ray crosses domain boundary
3054!--                 (once per target PC gridbox)
3055                    rz = REAL(k, wp)
3056                    ry = REAL(j, wp)
3057                    rx = REAL(i, wp)
3058                    CALL usm_find_boundary_face( (/ rz, ry, rx /), &
3059                        sunorig_grid, bdycross)
3060
3061                    isurf1 = ipcgb
3062                ENDIF
3063
3064                IF ( surf(id, isurfsrc) >= isky )  THEN
3065!--                 Diffuse rad from boundary surfaces. See comments for svf above.
3066                    pcbinsw(ipcgb) = pcbinsw(ipcgb) + csf(1,icsf) * csf(2,icsf) * rad_sw_in_diff(j,i)
3067!--                 canopy shading is applied only to shortwave, therefore no absorbtion for lw
3068!--                 pcbinlw(ipcgb) = pcbinlw(ipcgb) + svf(1,isvf) * rad_lw_in_diff(j,i)
3069                !ELSE
3070!--                 Thermal radiation in 1st pass
3071!--                 pcbinlw(ipcgb) = pcbinlw(ipcgb) + svf(1,isvf) * surfoutl(isurfsrc)
3072                ENDIF
3073
3074                IF ( zenith(0) > 0  .AND.  all( surf(:, isurfsrc) == bdycross ) )  THEN
3075!--                 found svf between model boundary and the pcgb => pcgb isn't shaded
3076                    pc_abs_frac = 1._wp - exp(pc_abs_eff * lad_s(k,j,i))
3077                    pcbinsw(ipcgb) = pcbinsw(ipcgb) &
3078                        + rad_sw_in_dir(j, i) * pc_box_area * csf(2,icsf) * pc_abs_frac
3079                ENDIF
3080            ENDDO
3081        ENDIF
3082        surfins(startenergy:endenergy) = surfinswdir(startenergy:endenergy) + surfinswdif(startenergy:endenergy)
3083        surfinl(startenergy:endenergy) = surfinl(startenergy:endenergy) + surfinlwdif(startenergy:endenergy)
3084        surfinsw(:) = surfins(:)
3085        surfinlw(:) = surfinl(:)
3086        surfoutsw(:) = 0.0_wp
3087        surfoutlw(:) = surfoutll(:)
3088        surfhf(startenergy:endenergy) = surfinsw(startenergy:endenergy) + surfinlw(startenergy:endenergy) &
3089                                      - surfoutsw(startenergy:endenergy) - surfoutlw(startenergy:endenergy)
3090       
3091!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3092!--     Next passes - reflections
3093!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3094        DO refstep = 1, nrefsteps
3095       
3096            surfoutsl(startenergy:endenergy) = albedo_surf(startenergy:endenergy) * surfins(startenergy:endenergy)
3097!--         for non-transparent surfaces, longwave albedo is 1 - emissivity
3098            surfoutll(startenergy:endenergy) = (1._wp - emiss_surf(startenergy:endenergy)) * surfinl(startenergy:endenergy)
3099
3100#if defined( __parallel )
3101            CALL MPI_AllGatherv(surfoutsl, nsurfl, MPI_REAL, &
3102                surfouts, nsurfs, surfstart, MPI_REAL, comm2d, ierr)
3103            CALL MPI_AllGatherv(surfoutll, nsurfl, MPI_REAL, &
3104                surfoutl, nsurfs, surfstart, MPI_REAL, comm2d, ierr)
3105#else
3106            surfouts(:) = surfoutsl(:)
3107            surfoutl(:) = surfoutll(:)
3108#endif
3109
3110!--         reset for next pass input
3111            surfins(:) = 0._wp
3112            surfinl(:) = 0._wp
3113           
3114!--         reflected radiation
3115            DO isvf = 1, nsvfl
3116                isurf = svfsurf(1, isvf)
3117                isurfsrc = svfsurf(2, isvf)
3118
3119!--             TODO: to remove if, use start+end for isvf
3120                IF ( surf(id, isurfsrc) < isky )  THEN
3121                    surfins(isurf) = surfins(isurf) + svf(1,isvf) * svf(2,isvf) * surfouts(isurfsrc)
3122                    surfinl(isurf) = surfinl(isurf) + svf(1,isvf) * surfoutl(isurfsrc)
3123                ENDIF
3124            ENDDO
3125
3126!--         radiation absorbed by plant canopy
3127            DO icsf = 1, ncsfl
3128                ipcgb = csfsurf(1, icsf)
3129                isurfsrc = csfsurf(2, icsf)
3130
3131                IF ( surf(id, isurfsrc) < isky )  THEN
3132                    pcbinsw(ipcgb) = pcbinsw(ipcgb) + csf(1,icsf) * csf(2,icsf) * surfouts(isurfsrc)
3133!--                 pcbinlw(ipcgb) = pcbinlw(ipcgb) + csf(1,icsf) * surfoutl(isurfsrc)
3134                ENDIF
3135            ENDDO
3136           
3137            surfinsw(:) = surfinsw(:)  + surfins(:)
3138            surfinlw(:) = surfinlw(:)  + surfinl(:)
3139            surfoutsw(startenergy:endenergy) = surfoutsw(startenergy:endenergy) + surfoutsl(startenergy:endenergy)
3140            surfoutlw(startenergy:endenergy) = surfoutlw(startenergy:endenergy) + surfoutll(startenergy:endenergy)
3141            surfhf(startenergy:endenergy) = surfinsw(startenergy:endenergy) + surfinlw(startenergy:endenergy) &
3142                                          - surfoutsw(startenergy:endenergy) - surfoutlw(startenergy:endenergy)
3143       
3144        ENDDO
3145
3146!--     push heat flux absorbed by plant canopy to respective 3D arrays
3147        IF ( plant_canopy )  THEN
3148            pc_heating_rate(:,:,:) = 0._wp
3149            DO ipcgb = 1, npcbl
3150                j = pcbl(iy, ipcgb)
3151                i = pcbl(ix, ipcgb)
3152                k = pcbl(iz, ipcgb)
3153                kk = k - nzb_s_inner(j,i)  !- lad arrays are defined flat
3154                pc_heating_rate(kk, j, i) = (pcbinsw(ipcgb) + pcbinlw(ipcgb)) &
3155                    * pchf_prep(k) * pt(k, j, i) !-- = dT/dt
3156            ENDDO
3157        ENDIF
3158
3159!--     return surface radiation to horizontal surfaces
3160!--     to rad_sw_in, rad_lw_in and rad_net for outputs
3161        !!!!!!!!!!
3162!--     we need the original radiation on urban top layer
3163!--     for calculation of MRT so we can't do adjustment here for now
3164        !!!!!!!!!!
3165        !!!DO isurf = 1, nsurfl
3166        !!!    i = surfl(ix,isurf)
3167        !!!    j = surfl(iy,isurf)
3168        !!!    k = surfl(iz,isurf)
3169        !!!    d = surfl(id,isurf)
3170        !!!    IF ( d==iroof )  THEN
3171        !!!        rad_sw_in(:,j,i) = surfinsw(isurf)
3172        !!!        rad_lw_in(:,j,i) = surfinlw(isurf)
3173        !!!        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)
3174        !!!    ENDIF
3175        !!!ENDDO
3176
3177    END SUBROUTINE usm_radiation
3178
3179   
3180!------------------------------------------------------------------------------!
3181! Description:
3182! ------------
3183!> Raytracing for detecting obstacles and calculating compound canopy sink
3184!> factors. (A simple obstacle detection would only need to process faces in
3185!> 3 dimensions without any ordering.)
3186!> Assumtions:
3187!> -----------
3188!> 1. The ray always originates from a face midpoint (only one coordinate equals
3189!>    *.5, i.e. wall) and doesn't travel parallel to the surface (that would mean
3190!>    shape factor=0). Therefore, the ray may never travel exactly along a face
3191!>    or an edge.
3192!> 2. From grid bottom to urban surface top the grid has to be *equidistant*
3193!>    within each of the dimensions, including vertical (but the resolution
3194!>    doesn't need to be the same in all three dimensions).
3195!------------------------------------------------------------------------------!
3196    SUBROUTINE usm_raytrace(src, targ, isrc, rirrf, atarg, create_csf, visible, transparency, win_lad)
3197        IMPLICIT NONE
3198
3199        REAL(wp), DIMENSION(3), INTENT(in)     :: src, targ    !< real coordinates z,y,x
3200        INTEGER(iwp), INTENT(in)               :: isrc         !< index of source face for csf
3201        REAL(wp), INTENT(in)                   :: rirrf        !< irradiance factor for csf
3202        REAL(wp), INTENT(in)                   :: atarg        !< target surface area for csf
3203        LOGICAL, INTENT(in)                    :: create_csf   !< whether to generate new CSFs during raytracing
3204        LOGICAL, INTENT(out)                   :: visible
3205        REAL(wp), INTENT(out)                  :: transparency !< along whole path
3206        INTEGER(iwp), INTENT(in)               :: win_lad
3207        INTEGER(iwp)                           :: i, j, k, d
3208        INTEGER(iwp)                           :: seldim       !< dimension to be incremented
3209        INTEGER(iwp)                           :: ncsb         !< no of written plant canopy sinkboxes
3210        INTEGER(iwp)                           :: maxboxes     !< max no of gridboxes visited
3211        REAL(wp)                               :: distance     !< euclidean along path
3212        REAL(wp)                               :: crlen        !< length of gridbox crossing
3213        REAL(wp)                               :: lastdist     !< beginning of current crossing
3214        REAL(wp)                               :: nextdist     !< end of current crossing
3215        REAL(wp)                               :: realdist     !< distance in meters per unit distance
3216        REAL(wp)                               :: crmid        !< midpoint of crossing
3217        REAL(wp)                               :: cursink      !< sink factor for current canopy box
3218        REAL(wp), DIMENSION(3)                 :: delta        !< path vector
3219        REAL(wp), DIMENSION(3)                 :: uvect        !< unit vector
3220        REAL(wp), DIMENSION(3)                 :: dimnextdist  !< distance for each dimension increments
3221        INTEGER(iwp), DIMENSION(3)             :: box          !< gridbox being crossed
3222        INTEGER(iwp), DIMENSION(3)             :: dimnext      !< next dimension increments along path
3223        INTEGER(iwp), DIMENSION(3)             :: dimdelta     !< dimension direction = +- 1
3224        INTEGER(iwp)                           :: px, py       !< number of processors in x and y dir before
3225                                                               !< the processor in the question
3226        INTEGER(iwp)                           :: ip           !< number of processor where gridbox reside
3227        INTEGER(iwp)                           :: ig           !< 1D index of gridbox in global 2D array
3228        REAL(wp)                               :: lad_s_target !< recieved lad_s of particular grid box
3229        REAL(wp), PARAMETER                    :: grow_factor = 1.5_wp !< factor of expansion of grow arrays
3230
3231
3232!--     Maximum number of gridboxes visited equals to maximum number of boundaries crossed in each dimension plus one. That's also
3233!--     the maximum number of plant canopy boxes written. We grow the acsf array accordingly using exponential factor.
3234        maxboxes = SUM(ABS(NINT(targ) - NINT(src))) + 1
3235        IF ( plant_canopy  .AND.  ncsfl + maxboxes > ncsfla )  THEN
3236!--         use this code for growing by fixed exponential increments (equivalent to case where ncsfl always increases by 1)
3237!--         k = CEILING(grow_factor ** real(CEILING(log(real(ncsfl + maxboxes, kind=wp)) &
3238!--                                                / log(grow_factor)), kind=wp))
3239!--         or use this code to simply always keep some extra space after growing
3240            k = CEILING(REAL(ncsfl + maxboxes, kind=wp) * grow_factor)
3241
3242            CALL usm_merge_and_grow_csf(k)
3243        ENDIF
3244       
3245        transparency = 1._wp
3246        ncsb = 0
3247
3248        delta(:) = targ(:) - src(:)
3249        distance = SQRT(SUM(delta(:)**2))
3250        IF ( distance == 0._wp )  THEN
3251            visible = .TRUE.
3252            RETURN
3253        ENDIF
3254        uvect(:) = delta(:) / distance
3255        realdist = SQRT(SUM( (uvect(:)*(/dz,dy,dx/))**2 ))
3256
3257        lastdist = 0._wp
3258
3259!--     Since all face coordinates have values *.5 and we'd like to use
3260!--     integers, all these have .5 added
3261        DO d = 1, 3
3262            IF ( uvect(d) == 0._wp )  THEN
3263                dimnext(d) = 999999999
3264                dimdelta(d) = 999999999
3265                dimnextdist(d) = 1.0E20_wp
3266            ELSE IF ( uvect(d) > 0._wp )  THEN
3267                dimnext(d) = CEILING(src(d) + .5_wp)
3268                dimdelta(d) = 1
3269                dimnextdist(d) = (dimnext(d) - .5_wp - src(d)) / uvect(d)
3270            ELSE
3271                dimnext(d) = FLOOR(src(d) + .5_wp)
3272                dimdelta(d) = -1
3273                dimnextdist(d) = (dimnext(d) - .5_wp - src(d)) / uvect(d)
3274            ENDIF
3275        ENDDO
3276
3277        DO
3278!--         along what dimension will the next wall crossing be?
3279            seldim = minloc(dimnextdist, 1)
3280            nextdist = dimnextdist(seldim)
3281            IF ( nextdist > distance ) nextdist = distance
3282
3283            crlen = nextdist - lastdist
3284            IF ( crlen > .001_wp )  THEN
3285                crmid = (lastdist + nextdist) * .5_wp
3286                box = NINT(src(:) + uvect(:) * crmid)
3287
3288!--             calculate index of the grid with global indices (box(2),box(3))
3289!--             in the array nzterr and plantt and id of the coresponding processor
3290                px = box(3)/nnx
3291                py = box(2)/nny
3292                ip = px*pdims(2)+py
3293                ig = ip*nnx*nny + (box(3)-px*nnx)*nny + box(2)-py*nny
3294                IF ( box(1) <= nzterr(ig) )  THEN
3295                    visible = .FALSE.
3296                    RETURN
3297                ENDIF
3298
3299                IF ( plant_canopy )  THEN
3300                    IF ( box(1) <= plantt(ig) )  THEN
3301                        ncsb = ncsb + 1
3302                        boxes(:,ncsb) = box
3303                        crlens(ncsb) = crlen
3304#if defined( __parallel )
3305                        lad_ip(ncsb) = ip
3306                        lad_disp(ncsb) = (box(3)-px*nnx)*(nny*nzu) + (box(2)-py*nny)*nzu + box(1)-nzub
3307#endif
3308                    ENDIF
3309                ENDIF
3310            ENDIF
3311
3312            IF ( nextdist >= distance ) EXIT
3313            lastdist = nextdist
3314            dimnext(seldim) = dimnext(seldim) + dimdelta(seldim)
3315            dimnextdist(seldim) = (dimnext(seldim) - .5_wp - src(seldim)) / uvect(seldim)
3316        ENDDO
3317       
3318        IF ( plant_canopy )  THEN
3319#if defined( __parallel )
3320            IF ( usm_lad_rma )  THEN
3321!--             send requests for lad_s to appropriate processor
3322                CALL cpu_log( log_point_s(77), 'usm_init_rma', 'start' )
3323                DO i = 1, ncsb
3324                    CALL MPI_Get(lad_s_ray(i), 1, MPI_REAL, lad_ip(i), lad_disp(i), &
3325                                 1, MPI_REAL, win_lad, ierr)
3326                    IF ( ierr /= 0 )  THEN
3327                        WRITE(message_string, *) 'MPI error ', ierr, ' at MPI_Get'
3328                        CALL message( 'usm_raytrace', 'PA0519', 1, 2, 0, 6, 0 )
3329                    ENDIF
3330                ENDDO
3331               
3332!--             wait for all pending local requests complete
3333                CALL MPI_Win_flush_local_all(win_lad, ierr)
3334                IF ( ierr /= 0 )  THEN
3335                    WRITE(message_string, *) 'MPI error ', ierr, ' at MPI_Win_flush_local_all'
3336                    CALL message( 'usm_raytrace', 'PA0519', 1, 2, 0, 6, 0 )
3337                ENDIF
3338                CALL cpu_log( log_point_s(77), 'usm_init_rma', 'stop' )
3339               
3340            ENDIF
3341#endif
3342
3343!--         calculate csf and transparency
3344            DO i = 1, ncsb
3345#if defined( __parallel )
3346                IF ( usm_lad_rma )  THEN
3347                    lad_s_target = lad_s_ray(i)
3348                ELSE
3349                    lad_s_target = usm_lad_g(lad_ip(i)*nnx*nny*nzu + lad_disp(i))
3350                ENDIF
3351#else
3352                lad_s_target = usm_lad(boxes(1,i),boxes(2,i),boxes(3,i))
3353#endif
3354                cursink = 1._wp - exp(-ext_coef * lad_s_target * crlens(i)*realdist)
3355
3356                IF ( create_csf )  THEN
3357!--                 write svf values into the array
3358                    ncsfl = ncsfl + 1
3359                    acsf(ncsfl)%ip = lad_ip(i)
3360                    acsf(ncsfl)%itx = boxes(3,i)
3361                    acsf(ncsfl)%ity = boxes(2,i)
3362                    acsf(ncsfl)%itz = boxes(1,i)
3363                    acsf(ncsfl)%isurfs = isrc
3364                    acsf(ncsfl)%rsvf = REAL(cursink*rirrf*atarg, wp) !-- we postpone multiplication by transparency
3365                    acsf(ncsfl)%rtransp = REAL(transparency, wp)
3366                ENDIF  !< create_csf
3367
3368                transparency = transparency * (1._wp - cursink)
3369               
3370            ENDDO
3371        ENDIF
3372       
3373        visible = .TRUE.
3374
3375       
3376    END SUBROUTINE usm_raytrace
3377   
3378 
3379!------------------------------------------------------------------------------!
3380! Description:
3381! ------------
3382!
3383!> This subroutine is part of the urban surface model.
3384!> It reads daily heat produced by anthropogenic sources
3385!> and the diurnal cycle of the heat.
3386!------------------------------------------------------------------------------!
3387    SUBROUTINE usm_read_anthropogenic_heat
3388   
3389        INTEGER(iwp)                  :: i,j,ii
3390        REAL(wp)                      :: heat
3391       
3392!--     allocation of array of sources of anthropogenic heat and their diural profile
3393        ALLOCATE( aheat(nys:nyn,nxl:nxr) )
3394        ALLOCATE( aheatprof(0:24) )
3395
3396!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3397!--     read daily amount of heat and its daily cycle
3398!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3399        aheat = 0.0_wp
3400        DO  ii = 0, io_blocks-1
3401            IF ( ii == io_group )  THEN
3402
3403!--             open anthropogenic heat file
3404                OPEN( 151, file='ANTHROPOGENIC_HEAT'//TRIM(coupling_char), action='read', &
3405                           status='old', form='formatted', err=11 )
3406                i = 0
3407                j = 0
3408                DO
3409                    READ( 151, *, err=12, end=13 )  i, j, heat
3410                    IF ( i >= nxl  .AND.  i <= nxr  .AND.  j >= nys  .AND.  j <= nyn )  THEN
3411!--                     write heat into the array
3412                        aheat(j,i) = heat
3413                    ENDIF
3414                    CYCLE
3415 12                 WRITE(message_string,'(a,2i4)') 'error in file ANTHROPOGENIC_HEAT'//TRIM(coupling_char)//' after line ',i,j
3416                    CALL message( 'usm_read_anthropogenic_heat', 'PA0515', 0, 1, 0, 6, 0 )
3417                ENDDO
3418 13             CLOSE(151)
3419                CYCLE
3420 11             message_string = 'file ANTHROPOGENIC_HEAT'//TRIM(coupling_char)//' does not exist'
3421                CALL message( 'usm_read_anthropogenic_heat', 'PA0516', 1, 2, 0, 6, 0 )
3422            ENDIF
3423           
3424#if defined( __parallel ) && ! defined ( __check )
3425            CALL MPI_BARRIER( comm2d, ierr )
3426#endif
3427        ENDDO
3428       
3429!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3430!--     read diurnal profiles of heat sources
3431!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3432        aheatprof = 0.0_wp
3433        DO  ii = 0, io_blocks-1
3434            IF ( ii == io_group )  THEN
3435
3436!--             open anthropogenic heat profile file
3437                OPEN( 151, file='ANTHROPOGENIC_HEAT_PROFILE'//TRIM(coupling_char), action='read', &
3438                           status='old', form='formatted', err=21 )
3439                i = 0
3440                DO
3441                    READ( 151, *, err=22, end=23 )  i, heat
3442                    IF ( i >= 0  .AND.  i <= 24 )  THEN
3443!--                     write heat into the array
3444                        aheatprof(i) = heat
3445                    ENDIF
3446                    CYCLE
3447 22                 WRITE(message_string,'(a,i4)') 'error in file ANTHROPOGENIC_HEAT_PROFILE'// &
3448                                                     TRIM(coupling_char)//' after line ',i
3449                    CALL message( 'usm_read_anthropogenic_heat', 'PA0517', 0, 1, 0, 6, 0 )
3450                ENDDO
3451                aheatprof(24) = aheatprof(0)
3452 23             CLOSE(151)
3453                CYCLE
3454 21             message_string = 'file ANTHROPOGENIC_HEAT_PROFILE'//TRIM(coupling_char)//' does not exist'
3455                CALL message( 'usm_read_anthropogenic_heat', 'PA0518', 1, 2, 0, 6, 0 )
3456            ENDIF
3457           
3458#if defined( __parallel ) && ! defined ( __check )
3459            CALL MPI_BARRIER( comm2d, ierr )
3460#endif
3461        ENDDO
3462       
3463    END SUBROUTINE usm_read_anthropogenic_heat
3464   
3465
3466!------------------------------------------------------------------------------!
3467!
3468! Description:
3469! ------------
3470!> Soubroutine reads t_surf and t_wall data from restart files
3471!kanani: Renamed this routine according to corresponging routines in PALM
3472!kanani: Modified the routine to match read_var_list, from where usm_read_restart_data
3473!        shall be called in the future. This part has not been tested yet. (see virtual_flight_mod)
3474!        Also, I had some trouble with the allocation of t_surf, since this is a pointer.
3475!        So, I added some directives here.
3476!------------------------------------------------------------------------------!
3477    SUBROUTINE usm_read_restart_data
3478
3479
3480       IMPLICIT NONE
3481       
3482       CHARACTER (LEN=30) ::  variable_chr  !< dummy variable to read string
3483       
3484       INTEGER(iwp)       ::  i             !< running index
3485
3486
3487       DO  i = 0, io_blocks-1
3488          IF ( i == io_group )  THEN
3489             READ ( 13 )  variable_chr
3490             DO   WHILE ( TRIM( variable_chr ) /= '*** end usm ***' )
3491
3492                SELECT CASE ( TRIM( variable_chr ) )
3493               
3494                   CASE ( 't_surf' )
3495#if defined( __nopointer )                   
3496                      IF ( .NOT.  ALLOCATED( t_surf ) )                         &
3497                         ALLOCATE( t_surf(startenergy:endenergy) )
3498                      READ ( 13 )  t_surf
3499#else                     
3500                      IF ( .NOT.  ALLOCATED( t_surf_1 ) )                         &
3501                         ALLOCATE( t_surf_1(startenergy:endenergy) )
3502                      READ ( 13 )  t_surf_1
3503#endif
3504
3505                   CASE ( 't_wall' )
3506#if defined( __nopointer )
3507                      IF ( .NOT.  ALLOCATED( t_wall ) )                         &
3508                         ALLOCATE( t_wall(nzb_wall:nzt_wall+1,startenergy:endenergy) )
3509                      READ ( 13 )  t_wall
3510#else
3511                      IF ( .NOT.  ALLOCATED( t_wall_1 ) )                         &
3512                         ALLOCATE( t_wall_1(nzb_wall:nzt_wall+1,startenergy:endenergy) )
3513                      READ ( 13 )  t_wall_1
3514#endif
3515
3516                   CASE DEFAULT
3517                      WRITE ( message_string, * )  'unknown variable named "', &
3518                                        TRIM( variable_chr ), '" found in',    &
3519                                        '&data from prior run on PE ', myid
3520                      CALL message( 'user_read_restart_data', 'UI0012', 1, 2, 0, 6, 0 )
3521
3522                END SELECT
3523
3524                READ ( 13 )  variable_chr
3525
3526             ENDDO
3527          ENDIF
3528#if defined( __parallel )
3529          CALL MPI_BARRIER( comm2d, ierr )
3530#endif
3531       ENDDO
3532
3533    END SUBROUTINE usm_read_restart_data
3534
3535
3536!------------------------------------------------------------------------------!
3537!
3538! Description:
3539! ------------
3540!> Soubroutine reads svf and svfsurf data from saved file
3541!------------------------------------------------------------------------------!
3542    SUBROUTINE usm_read_svf_from_file
3543
3544        IMPLICIT NONE
3545        INTEGER(iwp)                 :: fsvf = 89
3546        INTEGER(iwp)                 :: i
3547        CHARACTER(usm_version_len)   :: usm_version_field
3548        CHARACTER(svf_code_len)      :: svf_code_field
3549
3550        DO  i = 0, io_blocks-1
3551            IF ( i == io_group )  THEN
3552                OPEN ( fsvf, file=TRIM(svf_file_name)//TRIM(coupling_char)//myid_char,               &
3553                    form='unformatted', status='old' )
3554
3555!--             read and check version
3556                READ ( fsvf ) usm_version_field
3557                IF ( TRIM(usm_version_field) /= TRIM(usm_version) )  THEN
3558                    WRITE( message_string, * ) 'Version of binary SVF file "',           &
3559                                            TRIM(usm_version_field), '" does not match ',            &
3560                                            'the version of model "', TRIM(usm_version), '"'
3561                    CALL message( 'usm_read_svf_from_file', 'UI0012', 1, 2, 0, 6, 0 )
3562                ENDIF
3563               
3564!--             read nsvfl, ncsfl
3565                READ ( fsvf ) nsvfl, ncsfl
3566                IF ( nsvfl <= 0  .OR.  ncsfl < 0 )  THEN
3567                    WRITE( message_string, * ) 'Wrong number of SVF or CSF'
3568                    CALL message( 'usm_read_svf_from_file', 'UI0012', 1, 2, 0, 6, 0 )
3569                ELSE
3570                    WRITE(message_string,*) '    Number of SVF and CSF to read', nsvfl, ncsfl
3571                    CALL location_message( message_string, .TRUE. )
3572                ENDIF
3573               
3574                ALLOCATE(svf(ndsvf,nsvfl))
3575                ALLOCATE(svfsurf(idsvf,nsvfl))
3576                READ(fsvf) svf
3577                READ(fsvf) svfsurf
3578                IF ( plant_canopy )  THEN
3579                    ALLOCATE(csf(ndcsf,ncsfl))
3580                    ALLOCATE(csfsurf(idcsf,ncsfl))
3581                    READ(fsvf) csf
3582                    READ(fsvf) csfsurf
3583                ENDIF
3584                READ ( fsvf ) svf_code_field
3585               
3586                IF ( TRIM(svf_code_field) /= TRIM(svf_code) )  THEN
3587                    WRITE( message_string, * ) 'Wrong structure of binary svf file'
3588                    CALL message( 'usm_read_svf_from_file', 'UI0012', 1, 2, 0, 6, 0 )
3589                ENDIF
3590               
3591                CLOSE (fsvf)
3592               
3593            ENDIF
3594#if defined( __parallel )
3595            CALL MPI_BARRIER( comm2d, ierr )
3596#endif
3597        ENDDO
3598
3599    END SUBROUTINE usm_read_svf_from_file
3600
3601   
3602!------------------------------------------------------------------------------!
3603! Description:
3604! ------------
3605!
3606!> This subroutine reads walls, roofs and land categories and it parameters
3607!> from input files.
3608!------------------------------------------------------------------------------!
3609    SUBROUTINE usm_read_urban_surface_types
3610   
3611        CHARACTER(12)                                         :: wtn
3612        INTEGER(iwp)                                          :: wtc
3613        REAL(wp), DIMENSION(n_surface_params)                 :: wtp
3614   
3615        INTEGER(iwp), DIMENSION(0:17, nysg:nyng, nxlg:nxrg)   :: usm_par
3616        REAL(wp), DIMENSION(1:14, nysg:nyng, nxlg:nxrg)       :: usm_val
3617        INTEGER(iwp)                                          :: k, l, d, iw, jw, kw, it, ip, ii, ij
3618        INTEGER(iwp)                                          :: i, j
3619        INTEGER(iwp)                                          :: nz, roof, dirwe, dirsn
3620        INTEGER(iwp)                                          :: category
3621        INTEGER(iwp)                                          :: weheight1, wecat1, snheight1, sncat1
3622        INTEGER(iwp)                                          :: weheight2, wecat2, snheight2, sncat2
3623        INTEGER(iwp)                                          :: weheight3, wecat3, snheight3, sncat3
3624        REAL(wp)                                              :: height, albedo, thick
3625        REAL(wp)                                              :: wealbedo1, wethick1, snalbedo1, snthick1
3626        REAL(wp)                                              :: wealbedo2, wethick2, snalbedo2, snthick2
3627        REAL(wp)                                              :: wealbedo3, wethick3, snalbedo3, snthick3
3628       
3629!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3630!--     read categories of walls and their parameters
3631!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3632        DO  ii = 0, io_blocks-1
3633            IF ( ii == io_group )  THEN
3634
3635!--             open urban surface file
3636                OPEN( 151, file='SURFACE_PARAMETERS'//coupling_char, action='read', &
3637                           status='old', form='formatted', err=15 ) 
3638!--             first test and get n_surface_types
3639                k = 0
3640                l = 0
3641                DO
3642                    l = l+1
3643                    READ( 151, *, err=11, end=12 )  wtc, wtp, wtn
3644                    k = k+1
3645                    CYCLE
3646 11                 CONTINUE
3647                ENDDO
3648 12             n_surface_types = k
3649                ALLOCATE( surface_type_names(n_surface_types) )
3650                ALLOCATE( surface_type_codes(n_surface_types) )
3651                ALLOCATE( surface_params(n_surface_params, n_surface_types) )
3652!--             real reading
3653                rewind( 151 )
3654                k = 0
3655                DO
3656                    READ( 151, *, err=13, end=14 )  wtc, wtp, wtn
3657                    k = k+1
3658                    surface_type_codes(k) = wtc
3659                    surface_params(:,k) = wtp
3660                    surface_type_names(k) = wtn
3661                    CYCLE
366213                  WRITE(6,'(i3,a,2i5)') myid, 'readparams2 error k=', k
3663                    FLUSH(6)
3664                    CONTINUE
3665                ENDDO
3666 14             CLOSE(151)
3667                CYCLE
3668 15             message_string = 'file SURFACE_PARAMETERS'//TRIM(coupling_char)//' does not exist'
3669                CALL message( 'usm_read_urban_surface_types', 'PA0513', 1, 2, 0, 6, 0 )
3670            ENDIF
3671        ENDDO
3672   
3673!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3674!--     read types of surfaces
3675!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3676        usm_par = 0
3677        DO  ii = 0, io_blocks-1
3678            IF ( ii == io_group )  THEN
3679
3680                !
3681!--             open csv urban surface file
3682                OPEN( 151, file='URBAN_SURFACE'//TRIM(coupling_char), action='read', &
3683                      status='old', form='formatted', err=23 )
3684               
3685                l = 0
3686                DO
3687                    l = l+1
3688!--                 i, j, height, nz, roof, dirwe, dirsn, category, soilcat,
3689!--                 weheight1, wecat1, snheight1, sncat1, weheight2, wecat2, snheight2, sncat2,
3690!--                 weheight3, wecat3, snheight3, sncat3
3691                    READ( 151, *, err=21, end=25 )  i, j, height, nz, roof, dirwe, dirsn,            &
3692                                            category, albedo, thick,                                 &
3693                                            weheight1, wecat1, wealbedo1, wethick1,                  &
3694                                            weheight2, wecat2, wealbedo2, wethick2,                  &
3695                                            weheight3, wecat3, wealbedo3, wethick3,                  &
3696                                            snheight1, sncat1, snalbedo1, snthick1,                  &
3697                                            snheight2, sncat2, snalbedo2, snthick2,                  &
3698                                            snheight3, sncat3, snalbedo3, snthick3
3699
3700                    IF ( i >= nxlg  .AND.  i <= nxrg  .AND.  j >= nysg  .AND.  j <= nyng )  THEN
3701!--                     write integer variables into array
3702                        usm_par(:,j,i) = (/1, nz, roof, dirwe, dirsn, category,                      &
3703                                          weheight1, wecat1, weheight2, wecat2, weheight3, wecat3,   &
3704                                          snheight1, sncat1, snheight2, sncat2, snheight3, sncat3 /)
3705!--                     write real values into array
3706                        usm_val(:,j,i) = (/ albedo, thick,                                           &
3707                                           wealbedo1, wethick1, wealbedo2, wethick2,                 &
3708                                           wealbedo3, wethick3, snalbedo1, snthick1,                 &
3709                                           snalbedo2, snthick2, snalbedo3, snthick3 /)
3710                    ENDIF
3711                    CYCLE
3712 21                 WRITE (message_string, "(A,I5)") 'errors in file URBAN_SURFACE'//TRIM(coupling_char)//' on line ', l
3713                    CALL message( 'usm_read_urban_surface_types', 'PA0512', 0, 1, 0, 6, 0 )
3714                ENDDO
3715         
3716 23             message_string = 'file URBAN_SURFACE'//TRIM(coupling_char)//' does not exist'
3717                CALL message( 'usm_read_urban_surface_types', 'PA0514', 1, 2, 0, 6, 0 )
3718
3719 25             CLOSE( 90 )
3720
3721            ENDIF
3722#if defined( __parallel ) && ! defined ( __check )
3723            CALL MPI_BARRIER( comm2d, ierr )
3724#endif
3725        ENDDO
3726       
3727        !
3728!--     check completeness and formal correctness of the data
3729        DO i = nxlg, nxrg
3730            DO j = nysg, nyng
3731                IF ( usm_par(0,j,i) /= 0  .AND.  (        &  !< incomplete data,supply default values later
3732                     usm_par(1,j,i) < nzb  .OR.           &
3733                     usm_par(1,j,i) > nzt  .OR.           &  !< incorrect height (nz < nzb  .OR.  nz > nzt)
3734                     usm_par(2,j,i) < 0  .OR.             &
3735                     usm_par(2,j,i) > 1  .OR.             &  !< incorrect roof sign
3736                     usm_par(3,j,i) < nzb-nzt  .OR.       & 
3737                     usm_par(3,j,i) > nzt-nzb  .OR.       &  !< incorrect west-east wall direction sign
3738                     usm_par(4,j,i) < nzb-nzt  .OR.       &
3739                     usm_par(4,j,i) > nzt-nzb  .OR.       &  !< incorrect south-north wall direction sign
3740                     usm_par(6,j,i) < nzb  .OR.           & 
3741                     usm_par(6,j,i) > nzt  .OR.           &  !< incorrect pedestrian level height for west-east wall
3742                     usm_par(8,j,i) > nzt  .OR.           &
3743                     usm_par(10,j,i) > nzt  .OR.          &  !< incorrect wall or roof level height for west-east wall
3744                     usm_par(12,j,i) < nzb  .OR.          & 
3745                     usm_par(12,j,i) > nzt  .OR.          &  !< incorrect pedestrian level height for south-north wall
3746                     usm_par(14,j,i) > nzt  .OR.          &
3747                     usm_par(16,j,i) > nzt                &  !< incorrect wall or roof level height for south-north wall
3748                    ) )  THEN
3749!--                 incorrect input data
3750                    WRITE (message_string, "(A,2I5)") 'missing or incorrect data in file URBAN_SURFACE'// &
3751                                                       TRIM(coupling_char)//' for i,j=', i,j
3752                    CALL message( 'usm_read_urban_surface', 'PA0504', 1, 2, 0, 6, 0 )
3753                ENDIF
3754               
3755            ENDDO
3756        ENDDO
3757       
3758!--     assign the surface types to local surface array
3759        DO  l = startenergy, endenergy
3760           
3761            d = surfl(id,l)
3762            kw = surfl(iz,l)
3763            j = surfl(iy,l)
3764            i = surfl(ix,l)
3765            IF ( d == iroof )  THEN
3766!--             horizontal surface - land or roof
3767                iw = i
3768                jw = j
3769                IF ( usm_par(5,jw,iw) == 0 )  THEN
3770                    IF ( zu(kw) >= roof_height_limit )  THEN
3771                        isroof_surf(l) = .TRUE.
3772                        surface_types(l) = roof_category         !< default category for root surface
3773                    ELSE
3774                        isroof_surf(l) = .FALSE.
3775                        surface_types(l) = land_category         !< default category for land surface
3776                    ENDIF
3777                    albedo_surf(l) = -1.0_wp
3778                    thickness_wall(l) = -1.0_wp
3779                ELSE
3780                    IF ( usm_par(2,jw,iw)==0 )  THEN
3781                        isroof_surf(l) = .FALSE.
3782                        thickness_wall(l) = -1.0_wp
3783                    ELSE
3784                        isroof_surf(l) = .TRUE.
3785                        thickness_wall(l) = usm_val(2,jw,iw)
3786                    ENDIF
3787                    surface_types(l) = usm_par(5,jw,iw)
3788                    albedo_surf(l) = usm_val(1,jw,iw)
3789                ENDIF
3790            ELSE
3791                SELECT CASE (d)
3792                    CASE (iwest)
3793                        iw = i
3794                        jw = j
3795                        ii = 6
3796                        ij = 3
3797                    CASE (ieast)
3798                        iw = i-1
3799                        jw = j
3800                        ii = 6
3801                        ij = 3
3802                    CASE (isouth)
3803                        iw = i
3804                        jw = j
3805                        ii = 12
3806                        ij = 9
3807                    CASE (inorth)
3808                        iw = i
3809                        jw = j-1
3810                        ii = 12
3811                        ij = 9
3812                END SELECT
3813               
3814                IF ( kw <= usm_par(ii,jw,iw) )  THEN
3815!--                 pedestrant zone
3816                    isroof_surf(l) = .FALSE.
3817                    IF ( usm_par(ii+1,jw,iw) == 0 )  THEN
3818                        surface_types(l) = pedestrant_category   !< default category for wall surface in pedestrant zone
3819                        albedo_surf(l) = -1.0_wp
3820                        thickness_wall(l) = -1.0_wp
3821                    ELSE
3822                        surface_types(l) = usm_par(ii+1,jw,iw)
3823                        albedo_surf(l) = usm_val(ij,jw,iw)
3824                        thickness_wall(l) = usm_val(ij+1,jw,iw)
3825                    ENDIF
3826                ELSE IF ( kw <= usm_par(ii+2,jw,iw) )  THEN
3827!--                 wall zone
3828                    isroof_surf(l) = .FALSE.
3829                    IF ( usm_par(ii+3,jw,iw) == 0 )  THEN
3830                        surface_types(l) = wall_category         !< default category for wall surface
3831                        albedo_surf(l) = -1.0_wp
3832                        thickness_wall(l) = -1.0_wp
3833                    ELSE
3834                        surface_types(l) = usm_par(ii+3,jw,iw)
3835                        albedo_surf(l) = usm_val(ij+2,jw,iw)
3836                        thickness_wall(l) = usm_val(ij+3,jw,iw)
3837                    ENDIF
3838                ELSE IF ( kw <= usm_par(ii+4,jw,iw) )  THEN
3839!--                 roof zone
3840                    isroof_surf(l) = .TRUE.
3841                    IF ( usm_par(ii+5,jw,iw) == 0 )  THEN
3842                        surface_types(l) = roof_category         !< default category for roof surface
3843                        albedo_surf(l) = -1.0_wp
3844                        thickness_wall(l) = -1.0_wp
3845                    ELSE
3846                        surface_types(l) = usm_par(ii+5,jw,iw)
3847                        albedo_surf(l) = usm_val(ij+4,jw,iw)
3848                        thickness_wall(l) = usm_val(ij+5,jw,iw)
3849                    ENDIF
3850                ELSE
3851!--                 something wrong
3852                    CALL message( 'usm_read_urban_surface', 'PA0505', 1, 2, 0, 6, 0 )
3853                ENDIF
3854            ENDIF
3855           
3856!--         find the type position
3857            it = surface_types(l)
3858            ip = -99999
3859            DO k = 1, n_surface_types
3860                IF ( surface_type_codes(k) == it )  THEN
3861                    ip = k
3862                    EXIT
3863                ENDIF
3864            ENDDO
3865            IF ( ip == -99999 )  THEN
3866!--             wall category not found
3867                WRITE (message_string, "(A,I5,A,3I5)") 'wall category ', it, ' not found  for i,j,k=', iw,jw,kw
3868                CALL message( 'usm_read_urban_surface', 'PA0506', 1, 2, 0, 6, 0 )
3869            ENDIF
3870           
3871!--         Fill out the parameters of the wall
3872!--         wall surface:
3873           
3874!--         albedo
3875            IF ( albedo_surf(l) < 0.0_wp )  THEN
3876                albedo_surf(l) = surface_params(ialbedo, ip)
3877            ENDIF
3878           
3879!--         emissivity of the wall
3880            emiss_surf(l) = surface_params(iemiss, ip)
3881           
3882!--         heat conductivity λS between air and wall ( W m−2 K−1 )
3883            lambda_surf(l) = surface_params(ilambdas, ip)
3884           
3885!--         roughness relative to concrete
3886            roughness_wall(l) = surface_params(irough, ip)
3887           
3888!--         Surface skin layer heat capacity (J m−2 K−1 )
3889            c_surface(l) = surface_params(icsurf, ip)
3890           
3891!--         wall material parameters:
3892           
3893!--         thickness of the wall (m)
3894!--         missing values are replaced by default value for category
3895            IF ( thickness_wall(l) <= 0.001_wp )  THEN
3896                thickness_wall(l) = surface_params(ithick, ip)
3897            ENDIF
3898           
3899!--         volumetric heat capacity rho*C of the wall ( J m−3 K−1 )
3900            rho_c_wall(:,l) = surface_params(irhoC, ip)
3901           
3902!--         thermal conductivity λH of the wall (W m−1 K−1 )
3903            lambda_h(:,l) = surface_params(ilambdah, ip)
3904           
3905        ENDDO
3906
3907        CALL location_message( '    types and parameters of urban surfaces read', .TRUE. )
3908   
3909    END SUBROUTINE usm_read_urban_surface_types
3910
3911
3912!------------------------------------------------------------------------------!
3913! Description:
3914! ------------
3915!> Solver for the energy balance at the ground/roof/wall surface.
3916!> It follows basic ideas and structure of lsm_energy_balance
3917!> with many simplifications and adjustments.
3918!> TODO better description
3919!------------------------------------------------------------------------------!
3920    SUBROUTINE usm_surface_energy_balance
3921
3922        IMPLICIT NONE
3923
3924        INTEGER(iwp)                          :: i, j, k, l, d      !< running indices
3925       
3926        REAL(wp)                              :: pt1                !< temperature at first grid box adjacent to surface
3927        REAL(wp)                              :: u1,v1,w1           !< near wall u,v,w
3928        REAL(wp)                              :: stend              !< surface tendency
3929        REAL(wp)                              :: coef_1             !< first coeficient for prognostic equation
3930        REAL(wp)                              :: coef_2             !< second  coeficient for prognostic equation
3931        REAL(wp)                              :: rho_cp             !< rho_wall_surface * cp
3932        REAL(wp)                              :: r_a                !< aerodynamic resistance for horizontal and vertical surfaces
3933        REAL(wp)                              :: f_shf              !< factor for shf_eb
3934        REAL(wp)                              :: lambda_surface     !< current value of lambda_surface (heat conductivity between air and wall)
3935        REAL(wp)                              :: Ueff               !< effective wind speed for calculation of heat transfer coefficients
3936        REAL(wp)                              :: httc               !< heat transfer coefficient
3937        REAL(wp), DIMENSION(nzub:nzut)        :: exn                !< value of the Exner function in layers
3938       
3939        REAL(wp), DIMENSION(0:4)              :: dxdir              !< surface normal direction gridbox length
3940        REAL(wp)                              :: dtime              !< simulated time of day (in UTC)
3941        INTEGER(iwp)                          :: dhour              !< simulated hour of day (in UTC)
3942        REAL(wp)                              :: acoef              !< actual coefficient of diurnal profile of anthropogenic heat
3943
3944
3945        dxdir = (/dz,dy,dy,dx,dx/)
3946       
3947        exn(:) = (hyp(nzub:nzut) / 100000.0_wp )**0.286_wp          !< Exner function
3948           
3949!--   
3950        DO l = startenergy, endenergy
3951!--         Calculate frequently used parameters
3952            d = surfl(id,l)
3953            k = surfl(iz,l)
3954            j = surfl(iy,l)
3955            i = surfl(ix,l)
3956
3957!--         TODO - how to calculate lambda_surface for horizontal surfaces
3958!--         (lambda_surface is set according to stratification in land surface model)
3959            IF ( ol(j,i) >= 0.0_wp )  THEN
3960                lambda_surface = lambda_surf(l)
3961            ELSE
3962                lambda_surface = lambda_surf(l)
3963            ENDIF
3964           
3965            pt1  = pt(k,j,i)
3966
3967!--         calculate rho * cp coefficient at surface layer
3968            rho_cp  = cp * hyp(k) / ( r_d * pt1 * exn(k) )
3969
3970!--         calculate aerodyamic resistance.
3971            IF ( d == iroof )  THEN
3972!--             calculation for horizontal surfaces follows LSM formulation
3973!--             pt, us, ts are not available for the prognostic time step,
3974!--             data from the last time step is used here.
3975               
3976                r_a = (pt1 - t_surf(l)/exn(k)) / (ts(j,i) * us(j,i) + 1.0E-10_wp)
3977               
3978!--             make sure that the resistance does not drop to zero
3979                IF ( ABS(r_a) < 1.0E-10_wp )  r_a = 1.0E-10_wp
3980               
3981!--             the parameterization is developed originally for larger scales
3982!--             (compare with remark in TUF-3D)
3983!--             our first experiences show that the parameterization underestimates
3984!--             r_a in meter resolution.
3985!--             temporary solution - multiplication by magic constant :-(.
3986                r_a = r_a * ra_horiz_coef
3987               
3988!--             factor for shf_eb
3989                f_shf  = rho_cp / r_a
3990            ELSE
3991!--             calculation of r_a for vertical surfaces
3992!--
3993!--             heat transfer coefficient for forced convection along vertical walls
3994!--             follows formulation in TUF3d model (Krayenhoff & Voogt, 2006)
3995!--           
3996!--             H = httc (Tsfc - Tair)
3997!--             httc = rw * (11.8 + 4.2 * Ueff) - 4.0
3998!--           
3999!--                   rw: wall patch roughness relative to 1.0 for concrete
4000!--                   Ueff: effective wind speed
4001!--                   - 4.0 is a reduction of Rowley et al (1930) formulation based on
4002!--                   Cole and Sturrock (1977)
4003!--           
4004!--                   Ucan: Canyon wind speed
4005!--                   wstar: convective velocity
4006!--                   Qs: surface heat flux
4007!--                   zH: height of the convective layer
4008!--                   wstar = (g/Tcan*Qs*zH)**(1./3.)
4009               
4010!--             staggered grid needs to be taken into consideration
4011                IF ( d == inorth )  THEN
4012                    u1 = (u(k,j,i)+u(k,j,i+1))*0.5_wp
4013                    v1 = v(k,j+1,i)
4014                ELSE IF ( d == isouth )  THEN
4015                    u1 = (u(k,j,i)+u(k,j,i+1))*0.5_wp
4016                    v1 = v(k,j,i)
4017                ELSE IF ( d == ieast )  THEN
4018                    u1 = u(k,j,i+1)
4019                    v1 = (v(k,j,i)+v(k,j+1,i))*0.5_wp
4020                ELSE IF ( d == iwest )  THEN
4021                    u1 = u(k,j,i)
4022                    v1 = (v(k,j,i)+v(k,j+1,i))*0.5_wp
4023                ELSE
4024                    STOP
4025                ENDIF
4026                w1 = (w(k,j,i)+w(k-1,j,i))*0.5_wp
4027               
4028                Ueff = SQRT(u1**2 + v1**2 + w1**2)
4029                httc = roughness_wall(l) * (11.8 + 4.2 * Ueff) - 4.0
4030                f_shf  = httc
4031            ENDIF
4032       
4033!--         add LW up so that it can be removed in prognostic equation
4034            rad_net_l(l) = surfinsw(l) - surfoutsw(l) + surfinlw(l) - surfoutlw(l)
4035
4036!--         numerator of the prognostic equation
4037            coef_1 = rad_net_l(l) +    &    ! coef +1 corresponds to -lwout included in calculation of radnet_l
4038                     (3.0_wp+1.0_wp) * emiss_surf(l) * sigma_sb * t_surf(l) ** 4 +      & 
4039                     f_shf  * pt1 +                                                     &
4040                     lambda_surface * t_wall(nzb_wall,l)
4041
4042!--         denominator of the prognostic equation
4043            coef_2 = 4.0_wp * emiss_surf(l) * sigma_sb * t_surf(l) ** 3                 &
4044                         + lambda_surface + f_shf / exn(k)
4045
4046!--         implicit solution when the surface layer has no heat capacity,
4047!--         otherwise use RK3 scheme.
4048            t_surf_p(l) = ( coef_1 * dt_3d * tsc(2) + c_surface(l) * t_surf(l) ) /      & 
4049                              ( c_surface(l) + coef_2 * dt_3d * tsc(2) ) 
4050
4051!--         add RK3 term
4052            t_surf_p(l) = t_surf_p(l) + dt_3d * tsc(3) * tt_surface_m(l)
4053           
4054!--         calculate true tendency
4055            stend = (t_surf_p(l) - t_surf(l) - dt_3d * tsc(3) * tt_surface_m(l)) / (dt_3d  * tsc(2))
4056
4057!--         calculate t_surf tendencies for the next Runge-Kutta step
4058            IF ( timestep_scheme(1:5) == 'runge' )  THEN
4059                IF ( intermediate_timestep_count == 1 )  THEN
4060                    tt_surface_m(l) = stend
4061                ELSEIF ( intermediate_timestep_count <                                  &
4062                         intermediate_timestep_count_max )  THEN
4063                    tt_surface_m(l) = -9.5625_wp * stend + 5.3125_wp                    &
4064                                       * tt_surface_m(l)
4065                ENDIF
4066            ENDIF
4067
4068!--         in case of fast changes in the skin temperature, it is required to
4069!--         update the radiative fluxes in order to keep the solution stable
4070            IF ( ABS( t_surf_p(l) - t_surf(l) ) > 1.0_wp )  THEN
4071               force_radiation_call_l = .TRUE.
4072            ENDIF
4073           
4074!--         for horizontal surfaces is pt(nzb_s_inner(j,i),j,i) = pt_surf.
4075!--         there is no equivalent surface gridpoint for vertical surfaces.
4076!--         pt(k,j,i) is calculated for all directions in diffusion_s
4077!--         using surface and wall heat fluxes
4078            IF ( d == iroof )  THEN
4079               pt(nzb_s_inner(j,i),j,i) = t_surf_p(l) / exn(k)
4080            ENDIF
4081
4082!--         calculate fluxes
4083!--         rad_net_l is never used!           
4084            rad_net_l(l)     = rad_net_l(l) + 3.0_wp * sigma_sb                         &
4085                                * t_surf(l)**4 - 4.0_wp * sigma_sb                      &
4086                                * t_surf(l)**3 * t_surf_p(l)
4087            wghf_eb(l)       = lambda_surface * (t_surf_p(l) - t_wall(nzb_wall,l))
4088
4089!--         ground/wall/roof surface heat flux
4090            wshf_eb(l)  = - f_shf  * ( pt1 - t_surf_p(l) )
4091           
4092!--         store kinematic surface heat fluxes for utilization in other processes
4093!--         diffusion_s, surface_layer_fluxes,...
4094            IF ( d == iroof )  THEN
4095!--             shf is used in diffusion_s and also
4096!--             for calculation of surface layer fluxes
4097!--             update for horizontal surfaces
4098                shf(j,i) = wshf_eb(l) / rho_cp
4099            ELSE
4100!--             surface heat flux for vertical surfaces
4101!--             used in diffusion_s
4102                wshf(l) = wshf_eb(l) / rho_cp
4103            ENDIF
4104
4105        ENDDO
4106       
4107       
4108        IF ( usm_anthropogenic_heat  .AND.  &
4109             intermediate_timestep_count == intermediate_timestep_count_max )  THEN
4110!--         application of the additional anthropogenic heat sources
4111!--         we considere the traffic for now so all heat is absorbed
4112!--         to the first layer, generalization would be worth
4113           
4114!--         calculation of actual profile coefficient
4115!--         ??? check time_since_reference_point ???
4116            dtime = mod(simulated_time + time_utc_init, 24.0_wp*3600.0_wp)
4117            dhour = INT(dtime/3600.0_wp)
4118!--         linear interpolation of coeficient
4119            acoef = (REAL(dhour+1,wp)-dtime/3600.0_wp)*aheatprof(dhour) + (dtime/3600.0_wp-REAL(dhour,wp))*aheatprof(dhour+1)
4120            DO i = nxl, nxr
4121                DO j = nys, nyn
4122                    IF ( aheat(j,i) > 0.0_wp )  THEN
4123!--                     TODO the increase of pt in box i,j,nzb_s_inner(j,i)+1 in time dt_3d
4124!--                     given to anthropogenic heat aheat*acoef (W*m-2)
4125!--                     k = nzb_s_inner(j,i)+1
4126!--                     pt(k,j,i) = pt(k,j,i) + aheat(j,i)*acoef*dt_3d/(exn(k)*rho_cp*dz)
4127!--                     Instead of this, we can adjust shf in case AH only at surface
4128                        shf(j,i) = shf(j,i) + aheat(j,i)*acoef * ddx * ddy / rho_cp
4129                    ENDIF
4130                ENDDO
4131            ENDDO
4132        ENDIF
4133       
4134!--     pt and shf are defined on nxlg:nxrg,nysg:nyng
4135!--     get the borders from neighbours
4136        CALL exchange_horiz( pt, nbgp )
4137        CALL exchange_horiz_2d( shf )
4138
4139
4140!--    calculation of force_radiation_call:
4141!--    Make logical OR for all processes.
4142!--    Force radiation call if at least one processor forces it.
4143       IF ( intermediate_timestep_count == intermediate_timestep_count_max-1 )          &
4144       THEN
4145#if defined( __parallel )
4146          IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
4147              CALL mpi_allreduce( force_radiation_call_l, force_radiation_call,         &
4148                                  1, MPI_LOGICAL, MPI_LOR, comm2d, ierr )
4149#else
4150          force_radiation_call = force_radiation_call_l
4151#endif
4152          force_radiation_call_l = .FALSE.
4153       ENDIF
4154
4155
4156    END SUBROUTINE usm_surface_energy_balance
4157
4158
4159!------------------------------------------------------------------------------!
4160! Description:
4161! ------------
4162!> Swapping of timelevels for t_surf and t_wall
4163!> called out from subroutine swap_timelevel
4164!------------------------------------------------------------------------------!
4165    SUBROUTINE usm_swap_timelevel ( mod_count )
4166
4167       IMPLICIT NONE
4168
4169       INTEGER(iwp), INTENT(IN) :: mod_count
4170       INTEGER(iwp)             :: i
4171     
4172#if defined( __nopointer )
4173       t_surf    = t_surf_p
4174       t_wall    = t_wall_p
4175#else
4176       SELECT CASE ( mod_count )
4177          CASE ( 0 )
4178             t_surf  => t_surf_1; t_surf_p  => t_surf_2
4179             t_wall     => t_wall_1;    t_wall_p     => t_wall_2
4180          CASE ( 1 )
4181             t_surf  => t_surf_2; t_surf_p  => t_surf_1
4182             t_wall     => t_wall_2;    t_wall_p     => t_wall_1
4183       END SELECT
4184#endif
4185       
4186    END SUBROUTINE usm_swap_timelevel
4187
4188
4189!------------------------------------------------------------------------------!
4190! Description:
4191! ------------
4192!
4193!> This function applies the kinematic wall heat fluxes
4194!> for walls in four directions for all gridboxes in urban layer.
4195!> It is called out from subroutine prognostic_equations.
4196!> TODO Compare performance with cycle runnig l=startwall,endwall...
4197!------------------------------------------------------------------------------!
4198    SUBROUTINE usm_wall_heat_flux
4199   
4200        IMPLICIT NONE
4201
4202        INTEGER(iwp)              ::  i,j,k,d,l             !< running indices
4203       
4204        DO l = startenergy, endenergy
4205            j = surfl(iy,l)
4206            i = surfl(ix,l)
4207            k = surfl(iz,l)
4208            d = surfl(id,l)
4209            tend(k,j,i) = tend(k,j,i) + wshf(l) * ddxy2(d)
4210        ENDDO
4211
4212    END SUBROUTINE usm_wall_heat_flux
4213 
4214 
4215!------------------------------------------------------------------------------!
4216! Description:
4217! ------------
4218!
4219!> This function applies the kinematic wall heat fluxes
4220!> for walls in four directions around the gridbox i,j.
4221!> It is called out from subroutine prognostic_equations.
4222!------------------------------------------------------------------------------!
4223    SUBROUTINE usm_wall_heat_flux_ij(i,j) 
4224   
4225        IMPLICIT NONE
4226
4227        INTEGER(iwp), INTENT(in)  ::  i,j                   !< indices of grid box
4228        INTEGER(iwp)              ::  ii,jj,k,d,l
4229       
4230        DO l = startenergy, endenergy
4231            jj = surfl(iy,l)
4232            ii = surfl(ix,l)
4233            IF ( ii == i  .AND.  jj == j ) THEN
4234               k = surfl(iz,l)
4235               IF ( k >=  nzb_s_inner(j,i)+1  .AND.  k <=  nzb_s_outer(j,i) ) THEN
4236                  d = surfl(id,l)
4237                  IF ( d >= 1 .and. d <= 4 )   THEN
4238                     tend(k,j,i) = tend(k,j,i) + wshf(l) * ddxy2(d)
4239                  ENDIF
4240               ENDIF
4241            ENDIF
4242        ENDDO
4243
4244    END SUBROUTINE usm_wall_heat_flux_ij
4245 
4246
4247!------------------------------------------------------------------------------!
4248!
4249! Description:
4250! ------------
4251!> Subroutine writes t_surf and t_wall data into restart files
4252!kanani: Renamed this routine according to corresponging routines in PALM
4253!kanani: Modified the routine to match write_var_list, from where usm_write_restart_data
4254!        shall be called in the future. This part has not been tested yet. (see virtual_flight_mod)
4255!        Also, I had some trouble with the allocation of t_surf, since this is a pointer.
4256!        So, I added some directives here.
4257!------------------------------------------------------------------------------!
4258    SUBROUTINE usm_write_restart_data
4259   
4260       IMPLICIT NONE
4261       
4262       INTEGER(iwp)  ::  i
4263
4264       DO  i = 0, io_blocks-1
4265          IF ( i == io_group )  THEN
4266             WRITE ( 14 )  't_surf                        '
4267#if defined( __nopointer )             
4268             WRITE ( 14 )  t_surf
4269#else
4270             WRITE ( 14 )  t_surf_1
4271#endif
4272             WRITE ( 14 )  't_wall                        '
4273#if defined( __nopointer )             
4274             WRITE ( 14 )  t_wall
4275#else
4276             WRITE ( 14 )  t_wall_1
4277#endif
4278             WRITE ( 14 )  '*** end usm ***               '
4279          ENDIF
4280#if defined( __parallel )
4281          CALL MPI_BARRIER( comm2d, ierr )
4282#endif
4283       ENDDO
4284
4285       
4286    END SUBROUTINE usm_write_restart_data
4287
4288
4289!------------------------------------------------------------------------------!
4290!
4291! Description:
4292! ------------
4293!> Subroutine stores svf, svfsurf, csf and csfsurf data to a file.
4294!------------------------------------------------------------------------------!
4295    SUBROUTINE usm_write_svf_to_file
4296
4297        IMPLICIT NONE
4298        INTEGER(iwp)        :: fsvf = 89
4299        INTEGER(iwp)        :: i
4300
4301        DO  i = 0, io_blocks-1
4302            IF ( i == io_group )  THEN
4303                OPEN ( fsvf, file=TRIM(svf_file_name)//TRIM(coupling_char)//myid_char,               &
4304                    form='unformatted', status='new' )
4305
4306                WRITE ( fsvf )  usm_version
4307                WRITE ( fsvf )  nsvfl, ncsfl
4308                WRITE ( fsvf )  svf
4309                WRITE ( fsvf )  svfsurf
4310                IF ( plant_canopy )  THEN
4311                    WRITE ( fsvf )  csf
4312                    WRITE ( fsvf )  csfsurf
4313                ENDIF
4314                WRITE ( fsvf )  TRIM(svf_code)
4315
4316                CLOSE (fsvf)
4317#if defined( __parallel )
4318                CALL MPI_BARRIER( comm2d, ierr )
4319#endif
4320            ENDIF
4321        ENDDO
4322    END SUBROUTINE usm_write_svf_to_file
4323
4324
4325!------------------------------------------------------------------------------!
4326!
4327! Description:
4328! ------------
4329!> Block of auxiliary subroutines:
4330!> 1. quicksort and corresponding comparison
4331!> 2. usm_merge_and_grow_csf for implementation of "dynamical growing"
4332!>    array for csf
4333!------------------------------------------------------------------------------!   
4334    PURE FUNCTION svf_lt(svf1,svf2) result (res)
4335      TYPE (t_svf), INTENT(in) :: svf1,svf2
4336      LOGICAL                  :: res
4337      IF ( svf1%isurflt < svf2%isurflt  .OR.    &
4338          (svf1%isurflt == svf2%isurflt  .AND.  svf1%isurfs < svf2%isurfs) )  THEN
4339          res = .TRUE.
4340      ELSE
4341          res = .FALSE.
4342      ENDIF
4343    END FUNCTION svf_lt
4344   
4345 
4346!-- quicksort.f -*-f90-*-
4347!-- Author: t-nissie, adaptation J.Resler
4348!-- License: GPLv3
4349!-- Gist: https://gist.github.com/t-nissie/479f0f16966925fa29ea
4350    RECURSIVE SUBROUTINE quicksort_svf(svfl, first, last)
4351        IMPLICIT NONE
4352        TYPE(t_svf), DIMENSION(:), INTENT(INOUT)  :: svfl
4353        INTEGER(iwp), INTENT(IN)                  :: first, last
4354        TYPE(t_svf)                               :: x, t
4355        INTEGER(iwp)                              :: i, j
4356
4357        IF ( first>=last ) RETURN
4358        x = svfl( (first+last) / 2 )
4359        i = first
4360        j = last
4361        DO
4362            DO while ( svf_lt(svfl(i),x) )
4363                i=i+1
4364            ENDDO
4365            DO while ( svf_lt(x,svfl(j)) )
4366                j=j-1
4367            ENDDO
4368            IF ( i >= j ) EXIT
4369            t = svfl(i);  svfl(i) = svfl(j);  svfl(j) = t
4370            i=i+1
4371            j=j-1
4372        ENDDO
4373        IF ( first < i-1 ) CALL quicksort_svf(svfl, first, i-1)
4374        IF ( j+1 < last )  CALL quicksort_svf(svfl, j+1, last)
4375    END SUBROUTINE quicksort_svf
4376
4377   
4378    PURE FUNCTION csf_lt(csf1,csf2) result (res)
4379      TYPE (t_csf), INTENT(in) :: csf1,csf2
4380      LOGICAL                  :: res
4381      IF ( csf1%ip < csf2%ip  .OR.    &
4382           (csf1%ip == csf2%ip  .AND.  csf1%itx < csf2%itx)  .OR.  &
4383           (csf1%ip == csf2%ip  .AND.  csf1%itx == csf2%itx  .AND.  csf1%ity < csf2%ity)  .OR.  &
4384           (csf1%ip == csf2%ip  .AND.  csf1%itx == csf2%itx  .AND.  csf1%ity == csf2%ity  .AND.   &
4385            csf1%itz < csf2%itz)  .OR.  &
4386           (csf1%ip == csf2%ip  .AND.  csf1%itx == csf2%itx  .AND.  csf1%ity == csf2%ity  .AND.   &
4387            csf1%itz == csf2%itz  .AND.  csf1%isurfs < csf2%isurfs) )  THEN
4388          res = .TRUE.
4389      ELSE
4390          res = .FALSE.
4391      ENDIF
4392    END FUNCTION csf_lt
4393
4394
4395!-- quicksort.f -*-f90-*-
4396!-- Author: t-nissie, adaptation J.Resler
4397!-- License: GPLv3
4398!-- Gist: https://gist.github.com/t-nissie/479f0f16966925fa29ea
4399    RECURSIVE SUBROUTINE quicksort_csf(csfl, first, last)
4400        IMPLICIT NONE
4401        TYPE(t_csf), DIMENSION(:), INTENT(INOUT)  :: csfl
4402        INTEGER(iwp), INTENT(IN)                  :: first, last
4403        TYPE(t_csf)                               :: x, t
4404        INTEGER(iwp)                              :: i, j
4405
4406        IF ( first>=last ) RETURN
4407        x = csfl( (first+last)/2 )
4408        i = first
4409        j = last
4410        DO
4411            DO while ( csf_lt(csfl(i),x) )
4412                i=i+1
4413            ENDDO
4414            DO while ( csf_lt(x,csfl(j)) )
4415                j=j-1
4416            ENDDO
4417            IF ( i >= j ) EXIT
4418            t = csfl(i);  csfl(i) = csfl(j);  csfl(j) = t
4419            i=i+1
4420            j=j-1
4421        ENDDO
4422        IF ( first < i-1 ) CALL quicksort_csf(csfl, first, i-1)
4423        IF ( j+1 < last )  CALL quicksort_csf(csfl, j+1, last)
4424    END SUBROUTINE quicksort_csf
4425
4426   
4427    SUBROUTINE usm_merge_and_grow_csf(newsize)
4428        INTEGER(iwp), INTENT(in)                :: newsize  !< new array size after grow, must be >= ncsfl
4429                                                            !< or -1 to shrink to minimum
4430        INTEGER(iwp)                            :: iread, iwrite
4431        TYPE(t_csf), DIMENSION(:), POINTER      :: acsfnew
4432
4433        IF ( newsize == -1 )  THEN
4434!--         merge in-place
4435            acsfnew => acsf
4436        ELSE
4437!--         allocate new array
4438            IF ( mcsf == 0 )  THEN
4439                ALLOCATE( acsf1(newsize) )
4440                acsfnew => acsf1
4441            ELSE
4442                ALLOCATE( acsf2(newsize) )
4443                acsfnew => acsf2
4444            ENDIF
4445        ENDIF
4446
4447        IF ( ncsfl >= 1 )  THEN
4448!--         sort csf in place (quicksort)
4449            CALL quicksort_csf(acsf,1,ncsfl)
4450
4451!--         while moving to a new array, aggregate canopy sink factor records with identical box & source
4452            acsfnew(1) = acsf(1)
4453            iwrite = 1
4454            DO iread = 2, ncsfl
4455!--             here acsf(kcsf) already has values from acsf(icsf)
4456                IF ( acsfnew(iwrite)%itx == acsf(iread)%itx &
4457                         .AND.  acsfnew(iwrite)%ity == acsf(iread)%ity &
4458                         .AND.  acsfnew(iwrite)%itz == acsf(iread)%itz &
4459                         .AND.  acsfnew(iwrite)%isurfs == acsf(iread)%isurfs )  THEN
4460!--                 We could simply take either first or second rtransp, both are valid. As a very simple heuristic about which ray
4461!--                 probably passes nearer the center of the target box, we choose DIF from the entry with greater CSF, since that
4462!--                 might mean that the traced beam passes longer through the canopy box.
4463                    IF ( acsfnew(iwrite)%rsvf < acsf(iread)%rsvf )  THEN
4464                        acsfnew(iwrite)%rtransp = acsf(iread)%rtransp
4465                    ENDIF
4466                    acsfnew(iwrite)%rsvf = acsfnew(iwrite)%rsvf + acsf(iread)%rsvf
4467!--                 advance reading index, keep writing index
4468                ELSE
4469!--                 not identical, just advance and copy
4470                    iwrite = iwrite + 1
4471                    acsfnew(iwrite) = acsf(iread)
4472                ENDIF
4473            ENDDO
4474            ncsfl = iwrite
4475        ENDIF
4476
4477        IF ( newsize == -1 )  THEN
4478!--         allocate new array and copy shrinked data
4479            IF ( mcsf == 0 )  THEN
4480                ALLOCATE( acsf1(ncsfl) )
4481                acsf1(1:ncsfl) = acsf2(1:ncsfl)
4482            ELSE
4483                ALLOCATE( acsf2(ncsfl) )
4484                acsf2(1:ncsfl) = acsf1(1:ncsfl)
4485            ENDIF
4486        ENDIF
4487
4488!--     deallocate old array
4489        IF ( mcsf == 0 )  THEN
4490            mcsf = 1
4491            acsf => acsf1
4492            DEALLOCATE( acsf2 )
4493        ELSE
4494            mcsf = 0
4495            acsf => acsf2
4496            DEALLOCATE( acsf1 )
4497        ENDIF
4498        ncsfla = newsize
4499    END SUBROUTINE usm_merge_and_grow_csf
4500
4501   
4502!-- quicksort.f -*-f90-*-
4503!-- Author: t-nissie, adaptation J.Resler
4504!-- License: GPLv3
4505!-- Gist: https://gist.github.com/t-nissie/479f0f16966925fa29ea
4506    RECURSIVE SUBROUTINE quicksort_csf2(kpcsflt, pcsflt, first, last)
4507        IMPLICIT NONE
4508        INTEGER(iwp), DIMENSION(:,:), INTENT(INOUT)  :: kpcsflt
4509        REAL(wp), DIMENSION(:,:), INTENT(INOUT)      :: pcsflt
4510        INTEGER(iwp), INTENT(IN)                     :: first, last
4511        REAL(wp), DIMENSION(ndcsf)                   :: t2
4512        INTEGER(iwp), DIMENSION(kdcsf)               :: x, t1
4513        INTEGER(iwp)                                 :: i, j
4514
4515        IF ( first>=last ) RETURN
4516        x = kpcsflt(:, (first+last)/2 )
4517        i = first
4518        j = last
4519        DO
4520            DO while ( csf_lt2(kpcsflt(:,i),x) )
4521                i=i+1
4522            ENDDO
4523            DO while ( csf_lt2(x,kpcsflt(:,j)) )
4524                j=j-1
4525            ENDDO
4526            IF ( i >= j ) EXIT
4527            t1 = kpcsflt(:,i);  kpcsflt(:,i) = kpcsflt(:,j);  kpcsflt(:,j) = t1
4528            t2 = pcsflt(:,i);  pcsflt(:,i) = pcsflt(:,j);  pcsflt(:,j) = t2
4529            i=i+1
4530            j=j-1
4531        ENDDO
4532        IF ( first < i-1 ) CALL quicksort_csf2(kpcsflt, pcsflt, first, i-1)
4533        IF ( j+1 < last )  CALL quicksort_csf2(kpcsflt, pcsflt, j+1, last)
4534    END SUBROUTINE quicksort_csf2
4535   
4536
4537    PURE FUNCTION csf_lt2(item1, item2) result(res)
4538        INTEGER(iwp), DIMENSION(kdcsf), INTENT(in)  :: item1, item2
4539        LOGICAL                                     :: res
4540        res = ( (item1(3) < item2(3))                                                        &
4541             .OR.  (item1(3) == item2(3)  .AND.  item1(2) < item2(2))                            &
4542             .OR.  (item1(3) == item2(3)  .AND.  item1(2) == item2(2)  .AND.  item1(1) < item2(1)) &
4543             .OR.  (item1(3) == item2(3)  .AND.  item1(2) == item2(2)  .AND.  item1(1) == item2(1) &
4544                 .AND.  item1(4) < item2(4)) )
4545    END FUNCTION csf_lt2
4546
4547   
4548 END MODULE urban_surface_mod
Note: See TracBrowser for help on using the repository browser.