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

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

last commit documented

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