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

Last change on this file since 2072 was 2072, checked in by maronga, 7 years ago

last commit documented

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