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

Last change on this file since 2209 was 2209, checked in by kanani, 7 years ago

small bugfix, formatting and new PCM output

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