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

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

changes related to urban surface model and output of ssws

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