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

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

changes related to steering and formating of urban surface model

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