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

Last change on this file since 2038 was 2032, checked in by knoop, 7 years ago

last commit documented

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