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

Last change on this file since 2267 was 2258, checked in by suehring, 8 years ago

Bugfix, add pre-preprocessor directives to enable non-parrallel mode

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