source: palm/trunk/SOURCE/lagrangian_particle_model_mod.f90 @ 4329

Last change on this file since 4329 was 4329, checked in by motisi, 5 years ago

Renamed wall_flags_0 to wall_flags_static_0

  • Property svn:keywords set to Id
File size: 353.9 KB
Line 
1!> @file lagrangian_particle_model_mod.f90
2!------------------------------------------------------------------------------!
3! This file is part of the PALM model system.
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 1997-2019 Leibniz Universitaet Hannover
18!------------------------------------------------------------------------------!
19!
20! Current revisions:
21! ------------------
22!
23!
24! Former revisions:
25! -----------------
26! $Id: lagrangian_particle_model_mod.f90 4329 2019-12-10 15:46:36Z motisi $
27! Renamed wall_flags_0 to wall_flags_static_0
28!
29! 4282 2019-10-29 16:18:46Z schwenkel
30! Bugfix of particle timeseries in case of more than one particle group
31!
32! 4277 2019-10-28 16:53:23Z schwenkel
33! Bugfix: Added first_call_lpm in use statement
34!
35! 4276 2019-10-28 16:03:29Z schwenkel
36! Modularize lpm: Move conditions in time intergration to module
37!
38! 4275 2019-10-28 15:34:55Z schwenkel
39! Change call of simple predictor corrector method, i.e. two divergence free
40! velocitiy fields are now used.
41!
42! 4232 2019-09-20 09:34:22Z knoop
43! Removed INCLUDE "mpif.h", as it is not needed because of USE pegrid
44!
45! 4195 2019-08-28 13:44:27Z schwenkel
46! Bugfix for simple_corrector interpolation method in case of ocean runs and
47! output particle advection interpolation method into header
48!
49! 4182 2019-08-22 15:20:23Z scharf
50! Corrected "Former revisions" section
51!
52! 4168 2019-08-16 13:50:17Z suehring
53! Replace function get_topography_top_index by topo_top_ind
54!
55! 4145 2019-08-06 09:55:22Z schwenkel
56! Some reformatting
57!
58! 4144 2019-08-06 09:11:47Z raasch
59! relational operators .EQ., .NE., etc. replaced by ==, /=, etc.
60!
61! 4143 2019-08-05 15:14:53Z schwenkel
62! Rename variable and change select case to if statement
63!
64! 4122 2019-07-26 13:11:56Z schwenkel
65! Implement reset method as bottom boundary condition
66!
67! 4121 2019-07-26 10:01:22Z schwenkel
68! Implementation of an simple method for interpolating the velocities to
69! particle position
70!
71! 4114 2019-07-23 14:09:27Z schwenkel
72! Bugfix: Added working precision for if statement
73!
74! 4054 2019-06-27 07:42:18Z raasch
75! bugfix for calculating the minimum particle time step
76!
77! 4044 2019-06-19 12:28:27Z schwenkel
78! Bugfix in case of grid strecting: corrected calculation of k-Index
79!
80! 4043 2019-06-18 16:59:00Z schwenkel
81! Remove min_nr_particle, Add lpm_droplet_interactions_ptq into module
82!
83! 4028 2019-06-13 12:21:37Z schwenkel
84! Further modularization of particle code components
85!
86! 4020 2019-06-06 14:57:48Z schwenkel
87! Removing submodules
88!
89! 4018 2019-06-06 13:41:50Z eckhard
90! Bugfix for former revision
91!
92! 4017 2019-06-06 12:16:46Z schwenkel
93! Modularization of all lagrangian particle model code components
94!
95! 3655 2019-01-07 16:51:22Z knoop
96! bugfix to guarantee correct particle releases in case that the release
97! interval is smaller than the model timestep
98!
99! Revision 1.1  1999/11/25 16:16:06  raasch
100! Initial revision
101!
102!
103! Description:
104! ------------
105!> The embedded LPM allows for studying transport and dispersion processes within
106!> turbulent flows. This model including passive particles that do not show any
107!> feedback on the turbulent flow. Further also particles with inertia and
108!> cloud droplets ca be simulated explicitly.
109!>
110!> @todo test lcm
111!>       implement simple interpolation method for subgrid scale velocites
112!> @note <Enter notes on the module>
113!> @bug  <Enter bug on the module>
114!------------------------------------------------------------------------------!
115 MODULE lagrangian_particle_model_mod
116
117    USE, INTRINSIC ::  ISO_C_BINDING
118
119    USE arrays_3d,                                                             &
120        ONLY:  de_dx, de_dy, de_dz, dzw, zu, zw,  ql_c, ql_v, ql_vp, hyp,      &
121               pt, q, exner, ql, diss, e, u, v, w, km, ql_1, ql_2, pt_p, q_p,  &
122               d_exner
123 
124    USE averaging,                                                             &
125        ONLY:  ql_c_av, pr_av, pc_av, ql_vp_av, ql_v_av
126
127    USE basic_constants_and_equations_mod,                                     &
128        ONLY: molecular_weight_of_solute, molecular_weight_of_water, magnus,   &
129              pi, rd_d_rv, rho_l, r_v, rho_s, vanthoff, l_v, kappa, g, lv_d_cp
130
131    USE control_parameters,                                                    &
132        ONLY:  bc_dirichlet_l, bc_dirichlet_n, bc_dirichlet_r, bc_dirichlet_s, &
133               cloud_droplets, constant_flux_layer, current_timestep_number,   &
134               dt_3d, dt_3d_reached, first_call_lpm, humidity,                 &
135               dt_3d_reached_l, dt_dopts, dz, initializing_actions,            &
136               intermediate_timestep_count, intermediate_timestep_count_max,   &
137               message_string, molecular_viscosity, ocean_mode,                &
138               particle_maximum_age, iran,                                     & 
139               simulated_time, topography, dopts_time_count,                   &
140               time_since_reference_point, rho_surface, u_gtrans, v_gtrans,    &
141               dz_stretch_level, dz_stretch_level_start
142
143    USE cpulog,                                                                &
144        ONLY:  cpu_log, log_point, log_point_s
145
146    USE indices,                                                               &
147        ONLY:  nx, nxl, nxlg, nxrg, nxr, ny, nyn, nys, nyng, nysg, nz, nzb,    &
148               nzb_max, nzt,nbgp, ngp_2dh_outer,                               &
149               topo_top_ind,                                                   &
150               wall_flags_static_0
151
152    USE kinds
153
154    USE pegrid
155
156    USE particle_attributes
157
158    USE pmc_particle_interface,                                                &
159        ONLY: pmcp_c_get_particle_from_parent, pmcp_p_fill_particle_win,       &
160              pmcp_c_send_particle_to_parent, pmcp_p_empty_particle_win,       &
161              pmcp_p_delete_particles_in_fine_grid_area, pmcp_g_init,          &
162              pmcp_g_print_number_of_particles
163
164    USE pmc_interface,                                                         &
165        ONLY: nested_run
166
167    USE grid_variables,                                                        &
168        ONLY:  ddx, dx, ddy, dy
169
170    USE netcdf_interface,                                                      &
171        ONLY:  netcdf_data_format, netcdf_deflate, dopts_num, id_set_pts,      &
172               id_var_dopts, id_var_time_pts, nc_stat,                         &
173               netcdf_handle_error
174
175    USE random_function_mod,                                                   &
176        ONLY:  random_function
177
178    USE statistics,                                                            &
179        ONLY:  hom
180
181    USE surface_mod,                                                           &
182        ONLY:  bc_h,                                                           &
183               surf_def_h,                                                     &
184               surf_lsm_h,                                                     &
185               surf_usm_h
186
187#if defined( __parallel )  &&  !defined( __mpifh )
188    USE MPI
189#endif
190
191#if defined( __netcdf )
192    USE NETCDF
193#endif
194
195    IMPLICIT NONE
196
197    CHARACTER(LEN=15) ::  aero_species = 'nacl'                   !< aerosol species
198    CHARACTER(LEN=15) ::  aero_type    = 'maritime'               !< aerosol type
199    CHARACTER(LEN=15) ::  bc_par_lr    = 'cyclic'                 !< left/right boundary condition
200    CHARACTER(LEN=15) ::  bc_par_ns    = 'cyclic'                 !< north/south boundary condition
201    CHARACTER(LEN=15) ::  bc_par_b     = 'reflect'                !< bottom boundary condition
202    CHARACTER(LEN=15) ::  bc_par_t     = 'absorb'                 !< top boundary condition
203    CHARACTER(LEN=15) ::  collision_kernel   = 'none'             !< collision kernel
204
205    CHARACTER(LEN=5)  ::  splitting_function = 'gamma'            !< function for calculation critical weighting factor
206    CHARACTER(LEN=5)  ::  splitting_mode     = 'const'            !< splitting mode
207
208    CHARACTER(LEN=25) ::  particle_advection_interpolation = 'trilinear' !< interpolation method for calculatin the particle
209
210    INTEGER(iwp) ::  deleted_particles = 0                        !< number of deleted particles per time step   
211    INTEGER(iwp) ::  i_splitting_mode                             !< dummy for splitting mode
212    INTEGER(iwp) ::  iran_part = -1234567                         !< number for random generator   
213    INTEGER(iwp) ::  max_number_particles_per_gridbox = 100       !< namelist parameter (see documentation)
214    INTEGER(iwp) ::  isf                                          !< dummy for splitting function
215    INTEGER(iwp) ::  number_particles_per_gridbox = -1            !< namelist parameter (see documentation)
216    INTEGER(iwp) ::  number_of_sublayers = 20                     !< number of sublayers for particle velocities betwenn surface and first grid level
217    INTEGER(iwp) ::  offset_ocean_nzt = 0                         !< in case of oceans runs, the vertical index calculations need an offset
218    INTEGER(iwp) ::  offset_ocean_nzt_m1 = 0                      !< in case of oceans runs, the vertical index calculations need an offset
219    INTEGER(iwp) ::  particles_per_point = 1                      !< namelist parameter (see documentation)
220    INTEGER(iwp) ::  radius_classes = 20                          !< namelist parameter (see documentation)
221    INTEGER(iwp) ::  splitting_factor = 2                         !< namelist parameter (see documentation)
222    INTEGER(iwp) ::  splitting_factor_max = 5                     !< namelist parameter (see documentation)
223    INTEGER(iwp) ::  step_dealloc = 100                           !< namelist parameter (see documentation)
224    INTEGER(iwp) ::  total_number_of_particles                    !< total number of particles in the whole model domain
225    INTEGER(iwp) ::  trlp_count_sum                               !< parameter for particle exchange of PEs
226    INTEGER(iwp) ::  trlp_count_recv_sum                          !< parameter for particle exchange of PEs
227    INTEGER(iwp) ::  trrp_count_sum                               !< parameter for particle exchange of PEs
228    INTEGER(iwp) ::  trrp_count_recv_sum                          !< parameter for particle exchange of PEs
229    INTEGER(iwp) ::  trsp_count_sum                               !< parameter for particle exchange of PEs
230    INTEGER(iwp) ::  trsp_count_recv_sum                          !< parameter for particle exchange of PEs
231    INTEGER(iwp) ::  trnp_count_sum                               !< parameter for particle exchange of PEs
232    INTEGER(iwp) ::  trnp_count_recv_sum                          !< parameter for particle exchange of PEs
233
234    LOGICAL ::  lagrangian_particle_model = .FALSE.       !< namelist parameter (see documentation)
235    LOGICAL ::  curvature_solution_effects = .FALSE.      !< namelist parameter (see documentation)
236    LOGICAL ::  deallocate_memory = .TRUE.                !< namelist parameter (see documentation)
237    LOGICAL ::  hall_kernel = .FALSE.                     !< flag for collision kernel
238    LOGICAL ::  merging = .FALSE.                         !< namelist parameter (see documentation)
239    LOGICAL ::  random_start_position = .FALSE.           !< namelist parameter (see documentation)
240    LOGICAL ::  read_particles_from_restartfile = .TRUE.  !< namelist parameter (see documentation)
241    LOGICAL ::  seed_follows_topography = .FALSE.         !< namelist parameter (see documentation)
242    LOGICAL ::  splitting = .FALSE.                       !< namelist parameter (see documentation)
243    LOGICAL ::  use_kernel_tables = .FALSE.               !< parameter, which turns on the use of precalculated collision kernels
244    LOGICAL ::  write_particle_statistics = .FALSE.       !< namelist parameter (see documentation)
245    LOGICAL ::  interpolation_simple_predictor = .FALSE.  !< flag for simple particle advection interpolation with predictor step
246    LOGICAL ::  interpolation_simple_corrector = .FALSE.  !< flag for simple particle advection interpolation with corrector step
247    LOGICAL ::  interpolation_trilinear = .FALSE.         !< flag for trilinear particle advection interpolation
248
249    LOGICAL, DIMENSION(max_number_of_particle_groups) ::   vertical_particle_advection = .TRUE. !< Switch for vertical particle transport
250
251    REAL(wp) ::  aero_weight = 1.0_wp                      !< namelist parameter (see documentation)
252    REAL(wp) ::  dt_min_part = 0.0002_wp                   !< minimum particle time step when SGS velocities are used (s)
253    REAL(wp) ::  dt_prel = 9999999.9_wp                    !< namelist parameter (see documentation)
254    REAL(wp) ::  dt_write_particle_data = 9999999.9_wp     !< namelist parameter (see documentation)
255    REAL(wp) ::  end_time_prel = 9999999.9_wp              !< namelist parameter (see documentation)
256    REAL(wp) ::  initial_weighting_factor = 1.0_wp         !< namelist parameter (see documentation)
257    REAL(wp) ::  last_particle_release_time = 0.0_wp       !< last time of particle release
258    REAL(wp) ::  log_sigma(3) = 1.0_wp                     !< namelist parameter (see documentation)
259    REAL(wp) ::  na(3) = 0.0_wp                            !< namelist parameter (see documentation)
260    REAL(wp) ::  number_concentration = -1.0_wp            !< namelist parameter (see documentation)
261    REAL(wp) ::  radius_merge = 1.0E-7_wp                  !< namelist parameter (see documentation)
262    REAL(wp) ::  radius_split = 40.0E-6_wp                 !< namelist parameter (see documentation)
263    REAL(wp) ::  rm(3) = 1.0E-6_wp                         !< namelist parameter (see documentation)
264    REAL(wp) ::  sgs_wf_part                               !< parameter for sgs
265    REAL(wp) ::  time_write_particle_data = 0.0_wp         !< write particle data at current time on file
266    REAL(wp) ::  weight_factor_merge = -1.0_wp             !< namelist parameter (see documentation)
267    REAL(wp) ::  weight_factor_split = -1.0_wp             !< namelist parameter (see documentation)
268    REAL(wp) ::  z0_av_global                              !< horizontal mean value of z0
269
270    REAL(wp) ::  rclass_lbound !<
271    REAL(wp) ::  rclass_ubound !<
272
273    REAL(wp), PARAMETER ::  c_0 = 3.0_wp         !< parameter for lagrangian timescale
274
275    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  density_ratio = 9999999.9_wp  !< namelist parameter (see documentation)
276    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  pdx = 9999999.9_wp            !< namelist parameter (see documentation)
277    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  pdy = 9999999.9_wp            !< namelist parameter (see documentation)
278    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  pdz = 9999999.9_wp            !< namelist parameter (see documentation)
279    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  psb = 9999999.9_wp            !< namelist parameter (see documentation)
280    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  psl = 9999999.9_wp            !< namelist parameter (see documentation)
281    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  psn = 9999999.9_wp            !< namelist parameter (see documentation)
282    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  psr = 9999999.9_wp            !< namelist parameter (see documentation)
283    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  pss = 9999999.9_wp            !< namelist parameter (see documentation)
284    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  pst = 9999999.9_wp            !< namelist parameter (see documentation).
285    REAL(wp), DIMENSION(max_number_of_particle_groups) ::  radius = 9999999.9_wp         !< namelist parameter (see documentation)
286
287    REAL(wp), DIMENSION(:), ALLOCATABLE     ::  log_z_z0   !< Precalculate LOG(z/z0) 
288
289    INTEGER(iwp), PARAMETER ::  NR_2_direction_move = 10000 !<
290    INTEGER(iwp)            ::  nr_move_north               !<
291    INTEGER(iwp)            ::  nr_move_south               !<
292
293    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  move_also_north
294    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  move_also_south
295
296    REAL(wp) ::  epsilon_collision !<
297    REAL(wp) ::  urms              !<
298
299    REAL(wp), DIMENSION(:),   ALLOCATABLE ::  epsclass  !< dissipation rate class
300    REAL(wp), DIMENSION(:),   ALLOCATABLE ::  radclass  !< radius class
301    REAL(wp), DIMENSION(:),   ALLOCATABLE ::  winf      !<
302
303    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::  ec        !<
304    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::  ecf       !<
305    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::  gck       !<
306    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::  hkernel   !<
307    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::  hwratio   !<
308
309    REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::  ckernel !<
310    REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::  u_t   !< u value of old timelevel t
311    REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::  v_t   !< v value of old timelevel t
312    REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::  w_t   !< w value of old timelevel t
313
314
315    INTEGER(iwp), PARAMETER         ::  PHASE_INIT    = 1  !<
316    INTEGER(iwp), PARAMETER, PUBLIC ::  PHASE_RELEASE = 2  !<
317
318    SAVE
319
320    PRIVATE
321
322    PUBLIC lpm_parin,     &
323           lpm_header,    &
324           lpm_init_arrays,&
325           lpm_init,      &
326           lpm_actions,   &
327           lpm_data_output_ptseries, &
328           lpm_interaction_droplets_ptq, &
329           lpm_rrd_local_particles, &
330           lpm_wrd_local, &
331           lpm_rrd_global, &
332           lpm_wrd_global, &
333           lpm_rrd_local, &
334           lpm_check_parameters
335
336    PUBLIC lagrangian_particle_model
337
338    INTERFACE lpm_check_parameters
339       MODULE PROCEDURE lpm_check_parameters
340    END INTERFACE lpm_check_parameters
341
342    INTERFACE lpm_parin
343       MODULE PROCEDURE lpm_parin
344    END INTERFACE lpm_parin
345
346    INTERFACE lpm_header
347       MODULE PROCEDURE lpm_header
348    END INTERFACE lpm_header
349
350    INTERFACE lpm_init_arrays
351       MODULE PROCEDURE lpm_init_arrays
352    END INTERFACE lpm_init_arrays
353 
354    INTERFACE lpm_init
355       MODULE PROCEDURE lpm_init
356    END INTERFACE lpm_init
357
358    INTERFACE lpm_actions
359       MODULE PROCEDURE lpm_actions
360    END INTERFACE lpm_actions
361
362    INTERFACE lpm_data_output_ptseries
363       MODULE PROCEDURE lpm_data_output_ptseries
364    END INTERFACE
365
366    INTERFACE lpm_rrd_local_particles
367       MODULE PROCEDURE lpm_rrd_local_particles
368    END INTERFACE lpm_rrd_local_particles
369
370    INTERFACE lpm_rrd_global
371       MODULE PROCEDURE lpm_rrd_global
372    END INTERFACE lpm_rrd_global
373
374    INTERFACE lpm_rrd_local
375       MODULE PROCEDURE lpm_rrd_local
376    END INTERFACE lpm_rrd_local
377
378    INTERFACE lpm_wrd_local
379       MODULE PROCEDURE lpm_wrd_local
380    END INTERFACE lpm_wrd_local
381
382    INTERFACE lpm_wrd_global
383       MODULE PROCEDURE lpm_wrd_global
384    END INTERFACE lpm_wrd_global
385
386    INTERFACE lpm_advec
387       MODULE PROCEDURE lpm_advec
388    END INTERFACE lpm_advec
389
390    INTERFACE lpm_calc_liquid_water_content
391       MODULE PROCEDURE lpm_calc_liquid_water_content
392    END INTERFACE
393
394    INTERFACE lpm_interaction_droplets_ptq
395       MODULE PROCEDURE lpm_interaction_droplets_ptq
396       MODULE PROCEDURE lpm_interaction_droplets_ptq_ij
397    END INTERFACE lpm_interaction_droplets_ptq
398
399    INTERFACE lpm_boundary_conds
400       MODULE PROCEDURE lpm_boundary_conds
401    END INTERFACE lpm_boundary_conds
402
403    INTERFACE lpm_droplet_condensation
404       MODULE PROCEDURE lpm_droplet_condensation
405    END INTERFACE
406
407    INTERFACE lpm_droplet_collision
408       MODULE PROCEDURE lpm_droplet_collision
409    END INTERFACE lpm_droplet_collision
410
411    INTERFACE lpm_init_kernels
412       MODULE PROCEDURE lpm_init_kernels
413    END INTERFACE lpm_init_kernels
414
415    INTERFACE lpm_splitting
416       MODULE PROCEDURE lpm_splitting
417    END INTERFACE lpm_splitting
418
419    INTERFACE lpm_merging
420       MODULE PROCEDURE lpm_merging
421    END INTERFACE lpm_merging
422
423    INTERFACE lpm_exchange_horiz
424       MODULE PROCEDURE lpm_exchange_horiz
425    END INTERFACE lpm_exchange_horiz
426
427    INTERFACE lpm_move_particle
428       MODULE PROCEDURE lpm_move_particle
429    END INTERFACE lpm_move_particle
430
431    INTERFACE realloc_particles_array
432       MODULE PROCEDURE realloc_particles_array
433    END INTERFACE realloc_particles_array
434
435    INTERFACE dealloc_particles_array
436       MODULE PROCEDURE dealloc_particles_array
437    END INTERFACE dealloc_particles_array
438
439    INTERFACE lpm_sort_and_delete
440       MODULE PROCEDURE lpm_sort_and_delete
441    END INTERFACE lpm_sort_and_delete
442
443    INTERFACE lpm_sort_timeloop_done
444       MODULE PROCEDURE lpm_sort_timeloop_done
445    END INTERFACE lpm_sort_timeloop_done
446
447    INTERFACE lpm_pack
448       MODULE PROCEDURE lpm_pack
449    END INTERFACE lpm_pack
450
451 CONTAINS
452 
453
454!------------------------------------------------------------------------------!
455! Description:
456! ------------
457!> Parin for &particle_parameters for the Lagrangian particle model
458!------------------------------------------------------------------------------!
459 SUBROUTINE lpm_parin
460 
461    CHARACTER (LEN=80) ::  line  !<
462
463    NAMELIST /particles_par/ &
464       aero_species, &
465       aero_type, &
466       aero_weight, &
467       alloc_factor, &
468       bc_par_b, &
469       bc_par_lr, &
470       bc_par_ns, &
471       bc_par_t, &
472       collision_kernel, &
473       curvature_solution_effects, &
474       deallocate_memory, &
475       density_ratio, &
476       dissipation_classes, &
477       dt_dopts, &
478       dt_min_part, &
479       dt_prel, &
480       dt_write_particle_data, &
481       end_time_prel, &
482       initial_weighting_factor, &
483       log_sigma, &
484       max_number_particles_per_gridbox, &
485       merging, &
486       na, &
487       number_concentration, &
488       number_of_particle_groups, &
489       number_particles_per_gridbox, &
490       particles_per_point, &
491       particle_advection_start, &
492       particle_advection_interpolation, &
493       particle_maximum_age, &
494       pdx, &
495       pdy, &
496       pdz, &
497       psb, &
498       psl, &
499       psn, &
500       psr, &
501       pss, &
502       pst, &
503       radius, &
504       radius_classes, &
505       radius_merge, &
506       radius_split, &
507       random_start_position, &
508       read_particles_from_restartfile, &
509       rm, &
510       seed_follows_topography, &
511       splitting, &
512       splitting_factor, &
513       splitting_factor_max, &
514       splitting_function, &
515       splitting_mode, &
516       step_dealloc, &
517       use_sgs_for_particles, &
518       vertical_particle_advection, &
519       weight_factor_merge, &
520       weight_factor_split, &
521       write_particle_statistics
522
523       NAMELIST /particle_parameters/ &
524       aero_species, &
525       aero_type, &
526       aero_weight, &
527       alloc_factor, &
528       bc_par_b, &
529       bc_par_lr, &
530       bc_par_ns, &
531       bc_par_t, &
532       collision_kernel, &
533       curvature_solution_effects, &
534       deallocate_memory, &
535       density_ratio, &
536       dissipation_classes, &
537       dt_dopts, &
538       dt_min_part, &
539       dt_prel, &
540       dt_write_particle_data, &
541       end_time_prel, &
542       initial_weighting_factor, &
543       log_sigma, &
544       max_number_particles_per_gridbox, &
545       merging, &
546       na, &
547       number_concentration, &
548       number_of_particle_groups, &
549       number_particles_per_gridbox, &
550       particles_per_point, &
551       particle_advection_start, &
552       particle_advection_interpolation, &
553       particle_maximum_age, &
554       pdx, &
555       pdy, &
556       pdz, &
557       psb, &
558       psl, &
559       psn, &
560       psr, &
561       pss, &
562       pst, &
563       radius, &
564       radius_classes, &
565       radius_merge, &
566       radius_split, &
567       random_start_position, &
568       read_particles_from_restartfile, &
569       rm, &
570       seed_follows_topography, &
571       splitting, &
572       splitting_factor, &
573       splitting_factor_max, &
574       splitting_function, &
575       splitting_mode, &
576       step_dealloc, &
577       use_sgs_for_particles, &
578       vertical_particle_advection, &
579       weight_factor_merge, &
580       weight_factor_split, &
581       write_particle_statistics
582
583!
584!-- Position the namelist-file at the beginning (it was already opened in
585!-- parin), search for the namelist-group of the package and position the
586!-- file at this line. Do the same for each optionally used package.
587    line = ' '
588   
589!
590!-- Try to find particles package
591    REWIND ( 11 )
592    line = ' '
593    DO   WHILE ( INDEX( line, '&particle_parameters' ) == 0 )
594       READ ( 11, '(A)', END=12 )  line
595    ENDDO
596    BACKSPACE ( 11 )
597!
598!-- Read user-defined namelist
599    READ ( 11, particle_parameters, ERR = 10 )
600!
601!-- Set flag that indicates that particles are switched on
602    particle_advection = .TRUE.
603   
604    GOTO 14
605
60610  BACKSPACE( 11 )
607    READ( 11 , '(A)') line
608    CALL parin_fail_message( 'particle_parameters', line )
609!
610!-- Try to find particles package (old namelist)
61112  REWIND ( 11 )
612    line = ' '
613    DO WHILE ( INDEX( line, '&particles_par' ) == 0 )
614       READ ( 11, '(A)', END=14 )  line
615    ENDDO
616    BACKSPACE ( 11 )
617!
618!-- Read user-defined namelist
619    READ ( 11, particles_par, ERR = 13, END = 14 )
620
621    message_string = 'namelist particles_par is deprecated and will be ' //    &
622                     'removed in near future. Please use namelist ' //         &
623                     'particle_parameters instead'
624    CALL message( 'package_parin', 'PA0487', 0, 1, 0, 6, 0 )
625
626!
627!-- Set flag that indicates that particles are switched on
628    particle_advection = .TRUE.
629
630    GOTO 14
631
63213    BACKSPACE( 11 )
633       READ( 11 , '(A)') line
634       CALL parin_fail_message( 'particles_par', line )
635
63614 CONTINUE
637
638 END SUBROUTINE lpm_parin
639 
640!------------------------------------------------------------------------------!
641! Description:
642! ------------
643!> Writes used particle attributes in header file.
644!------------------------------------------------------------------------------!
645 SUBROUTINE lpm_header ( io )
646
647    CHARACTER (LEN=40) ::  output_format       !< netcdf format
648
649    INTEGER(iwp) ::  i               !<
650    INTEGER(iwp), INTENT(IN) ::  io  !< Unit of the output file
651
652
653     IF ( humidity  .AND.  cloud_droplets )  THEN
654       WRITE ( io, 433 )
655       IF ( curvature_solution_effects )  WRITE ( io, 434 )
656       IF ( collision_kernel /= 'none' )  THEN
657          WRITE ( io, 435 )  TRIM( collision_kernel )
658          IF ( collision_kernel(6:9) == 'fast' )  THEN
659             WRITE ( io, 436 )  radius_classes, dissipation_classes
660          ENDIF
661       ELSE
662          WRITE ( io, 437 )
663       ENDIF
664    ENDIF
665 
666    IF ( particle_advection )  THEN
667!
668!--    Particle attributes
669       WRITE ( io, 480 )  particle_advection_start, TRIM(particle_advection_interpolation), &
670                          dt_prel, bc_par_lr, &
671                          bc_par_ns, bc_par_b, bc_par_t, particle_maximum_age, &
672                          end_time_prel
673       IF ( use_sgs_for_particles )  WRITE ( io, 488 )  dt_min_part
674       IF ( random_start_position )  WRITE ( io, 481 )
675       IF ( seed_follows_topography )  WRITE ( io, 496 )
676       IF ( particles_per_point > 1 )  WRITE ( io, 489 )  particles_per_point
677       WRITE ( io, 495 )  total_number_of_particles
678       IF ( dt_write_particle_data /= 9999999.9_wp )  THEN
679          WRITE ( io, 485 )  dt_write_particle_data
680          IF ( netcdf_data_format > 1 )  THEN
681             output_format = 'netcdf (64 bit offset) and binary'
682          ELSE
683             output_format = 'netcdf and binary'
684          ENDIF
685          IF ( netcdf_deflate == 0 )  THEN
686             WRITE ( io, 344 )  output_format
687          ELSE
688             WRITE ( io, 354 )  TRIM( output_format ), netcdf_deflate
689          ENDIF
690       ENDIF
691       IF ( dt_dopts /= 9999999.9_wp )  WRITE ( io, 494 )  dt_dopts
692       IF ( write_particle_statistics )  WRITE ( io, 486 )
693
694       WRITE ( io, 487 )  number_of_particle_groups
695
696       DO  i = 1, number_of_particle_groups
697          IF ( i == 1  .AND.  density_ratio(i) == 9999999.9_wp )  THEN
698             WRITE ( io, 490 )  i, 0.0_wp
699             WRITE ( io, 492 )
700          ELSE
701             WRITE ( io, 490 )  i, radius(i)
702             IF ( density_ratio(i) /= 0.0_wp )  THEN
703                WRITE ( io, 491 )  density_ratio(i)
704             ELSE
705                WRITE ( io, 492 )
706             ENDIF
707          ENDIF
708          WRITE ( io, 493 )  psl(i), psr(i), pss(i), psn(i), psb(i), pst(i), &
709                             pdx(i), pdy(i), pdz(i)
710          IF ( .NOT. vertical_particle_advection(i) )  WRITE ( io, 482 )
711       ENDDO
712
713    ENDIF
714   
715344 FORMAT ('       Output format: ',A/)
716354 FORMAT ('       Output format: ',A, '   compressed with level: ',I1/)
717
718433 FORMAT ('    Cloud droplets treated explicitly using the Lagrangian part', &
719                 'icle model')
720434 FORMAT ('    Curvature and solution effecs are considered for growth of', &
721                 ' droplets < 1.0E-6 m')
722435 FORMAT ('    Droplet collision is handled by ',A,'-kernel')
723436 FORMAT ('       Fast kernel with fixed radius- and dissipation classes ', &
724                    'are used'/ &
725            '          number of radius classes:       ',I3,'    interval ', &
726                       '[1.0E-6,2.0E-4] m'/ &
727            '          number of dissipation classes:   ',I2,'    interval ', &
728                       '[0,1000] cm**2/s**3')
729437 FORMAT ('    Droplet collision is switched off')
730
731480 FORMAT ('    Particles:'/ &
732            '    ---------'// &
733            '       Particle advection is active (switched on at t = ', F7.1, &
734                    ' s)'/ &
735            '       Interpolation of particle velocities is done by using ', A, &
736                    ' method'/ &
737            '       Start of new particle generations every  ',F6.1,' s'/ &
738            '       Boundary conditions: left/right: ', A, ' north/south: ', A/&
739            '                            bottom:     ', A, ' top:         ', A/&
740            '       Maximum particle age:                 ',F9.1,' s'/ &
741            '       Advection stopped at t = ',F9.1,' s'/)
742481 FORMAT ('       Particles have random start positions'/)
743482 FORMAT ('          Particles are advected only horizontally'/)
744485 FORMAT ('       Particle data are written on file every ', F9.1, ' s')
745486 FORMAT ('       Particle statistics are written on file'/)
746487 FORMAT ('       Number of particle groups: ',I2/)
747488 FORMAT ('       SGS velocity components are used for particle advection'/ &
748            '          minimum timestep for advection:', F8.5/)
749489 FORMAT ('       Number of particles simultaneously released at each ', &
750                    'point: ', I5/)
751490 FORMAT ('       Particle group ',I2,':'/ &
752            '          Particle radius: ',E10.3, 'm')
753491 FORMAT ('          Particle inertia is activated'/ &
754            '             density_ratio (rho_fluid/rho_particle) =',F6.3/)
755492 FORMAT ('          Particles are advected only passively (no inertia)'/)
756493 FORMAT ('          Boundaries of particle source: x:',F8.1,' - ',F8.1,' m'/&
757            '                                         y:',F8.1,' - ',F8.1,' m'/&
758            '                                         z:',F8.1,' - ',F8.1,' m'/&
759            '          Particle distances:  dx = ',F8.1,' m  dy = ',F8.1, &
760                       ' m  dz = ',F8.1,' m'/)
761494 FORMAT ('       Output of particle time series in NetCDF format every ', &
762                    F8.2,' s'/)
763495 FORMAT ('       Number of particles in total domain: ',I10/)
764496 FORMAT ('       Initial vertical particle positions are interpreted ', &
765                    'as relative to the given topography')
766   
767 END SUBROUTINE lpm_header
768 
769!------------------------------------------------------------------------------!
770! Description:
771! ------------
772!> Writes used particle attributes in header file.
773!------------------------------------------------------------------------------! 
774 SUBROUTINE lpm_check_parameters
775 
776!
777!-- Collision kernels:
778    SELECT CASE ( TRIM( collision_kernel ) )
779
780       CASE ( 'hall', 'hall_fast' )
781          hall_kernel = .TRUE.
782
783       CASE ( 'wang', 'wang_fast' )
784          wang_kernel = .TRUE.
785
786       CASE ( 'none' )
787
788
789       CASE DEFAULT
790          message_string = 'unknown collision kernel: collision_kernel = "' // &
791                           TRIM( collision_kernel ) // '"'
792          CALL message( 'lpm_check_parameters', 'PA0350', 1, 2, 0, 6, 0 )
793
794    END SELECT
795    IF ( collision_kernel(6:9) == 'fast' )  use_kernel_tables = .TRUE.
796
797!
798!-- Subgrid scale velocites with the simple interpolation method for resolved
799!-- velocites is not implemented for passive particles. However, for cloud
800!-- it can be combined as the sgs-velocites for active particles are
801!-- calculated differently, i.e. no subboxes are needed.
802    IF ( .NOT. TRIM( particle_advection_interpolation ) == 'trilinear'  .AND.  &
803       use_sgs_for_particles  .AND.  .NOT. cloud_droplets )  THEN
804          message_string = 'subrgrid scale velocities in combination with ' // &
805                           'simple interpolation method is not '            // &
806                           'implemented'
807          CALL message( 'lpm_check_parameters', 'PA0659', 1, 2, 0, 6, 0 )
808    ENDIF
809
810    IF ( nested_run  .AND.  cloud_droplets )  THEN
811       message_string = 'nested runs in combination with cloud droplets ' // &
812                        'is not implemented'
813          CALL message( 'lpm_check_parameters', 'PA0687', 1, 2, 0, 6, 0 )
814    ENDIF
815
816
817 END SUBROUTINE lpm_check_parameters
818 
819!------------------------------------------------------------------------------!
820! Description:
821! ------------
822!> Initialize arrays for lpm
823!------------------------------------------------------------------------------!   
824 SUBROUTINE lpm_init_arrays
825 
826    IF ( cloud_droplets )  THEN
827!
828!--    Liquid water content, change in liquid water content
829       ALLOCATE ( ql_1(nzb:nzt+1,nysg:nyng,nxlg:nxrg),                      &
830                  ql_2(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
831!
832!--    Real volume of particles (with weighting), volume of particles
833       ALLOCATE ( ql_v(nzb:nzt+1,nysg:nyng,nxlg:nxrg),                      &
834                     ql_vp(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
835    ENDIF
836
837
838    ALLOCATE( u_t(nzb:nzt+1,nysg:nyng,nxlg:nxrg),                             &
839              v_t(nzb:nzt+1,nysg:nyng,nxlg:nxrg),                             &
840              w_t(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
841!
842!-- Initialize values with current time step
843    u_t = u
844    v_t = v
845    w_t = w
846!
847!--    Initial assignment of the pointers
848    IF ( cloud_droplets )  THEN
849       ql   => ql_1
850       ql_c => ql_2
851    ENDIF
852
853 END SUBROUTINE lpm_init_arrays
854 
855!------------------------------------------------------------------------------!
856! Description:
857! ------------
858!> Initialize Lagrangian particle model
859!------------------------------------------------------------------------------!
860 SUBROUTINE lpm_init
861
862    INTEGER(iwp) ::  i                           !<
863    INTEGER(iwp) ::  j                           !<
864    INTEGER(iwp) ::  k                           !<
865
866    REAL(wp) ::  div                             !<
867    REAL(wp) ::  height_int                      !<
868    REAL(wp) ::  height_p                        !<
869    REAL(wp) ::  z_p                             !<
870    REAL(wp) ::  z0_av_local                     !<
871
872!
873!-- In case of oceans runs, the vertical index calculations need an offset,
874!-- because otherwise the k indices will become negative
875    IF ( ocean_mode )  THEN
876       offset_ocean_nzt    = nzt
877       offset_ocean_nzt_m1 = nzt - 1
878    ENDIF
879
880!
881!-- Define block offsets for dividing a gridcell in 8 sub cells
882!-- See documentation for List of subgrid boxes
883!-- See pack_and_sort in lpm_pack_arrays.f90 for assignment of the subgrid boxes
884    block_offset(0) = block_offset_def ( 0, 0, 0)
885    block_offset(1) = block_offset_def ( 0, 0,-1)
886    block_offset(2) = block_offset_def ( 0,-1, 0)
887    block_offset(3) = block_offset_def ( 0,-1,-1)
888    block_offset(4) = block_offset_def (-1, 0, 0)
889    block_offset(5) = block_offset_def (-1, 0,-1)
890    block_offset(6) = block_offset_def (-1,-1, 0)
891    block_offset(7) = block_offset_def (-1,-1,-1)
892!
893!-- Check the number of particle groups.
894    IF ( number_of_particle_groups > max_number_of_particle_groups )  THEN
895       WRITE( message_string, * ) 'max_number_of_particle_groups =',           &
896                                  max_number_of_particle_groups ,              &
897                                  '&number_of_particle_groups reset to ',      &
898                                  max_number_of_particle_groups
899       CALL message( 'lpm_init', 'PA0213', 0, 1, 0, 6, 0 )
900       number_of_particle_groups = max_number_of_particle_groups
901    ENDIF
902!
903!-- Check if downward-facing walls exist. This case, reflection boundary
904!-- conditions (as well as subgrid-scale velocities) may do not work
905!-- propably (not realized so far).
906    IF ( surf_def_h(1)%ns >= 1 )  THEN
907       WRITE( message_string, * ) 'Overhanging topography do not work '//      &
908                                  'with particles'
909       CALL message( 'lpm_init', 'PA0212', 0, 1, 0, 6, 0 )
910
911    ENDIF
912
913!
914!-- Set default start positions, if necessary
915    IF ( psl(1) == 9999999.9_wp )  psl(1) = 0.0_wp
916    IF ( psr(1) == 9999999.9_wp )  psr(1) = ( nx +1 ) * dx
917    IF ( pss(1) == 9999999.9_wp )  pss(1) = 0.0_wp
918    IF ( psn(1) == 9999999.9_wp )  psn(1) = ( ny +1 ) * dy
919    IF ( psb(1) == 9999999.9_wp )  psb(1) = zu(nz/2)
920    IF ( pst(1) == 9999999.9_wp )  pst(1) = psb(1)
921
922    IF ( pdx(1) == 9999999.9_wp  .OR.  pdx(1) == 0.0_wp )  pdx(1) = dx
923    IF ( pdy(1) == 9999999.9_wp  .OR.  pdy(1) == 0.0_wp )  pdy(1) = dy
924    IF ( pdz(1) == 9999999.9_wp  .OR.  pdz(1) == 0.0_wp )  pdz(1) = zu(2) - zu(1)
925
926!
927!-- If number_particles_per_gridbox is set, the parametres pdx, pdy and pdz are
928!-- calculated diagnostically. Therfore an isotropic distribution is prescribed.
929    IF ( number_particles_per_gridbox /= -1 .AND.   &
930         number_particles_per_gridbox >= 1 )    THEN
931       pdx(1) = (( dx * dy * ( zu(2) - zu(1) ) ) /  &
932             REAL(number_particles_per_gridbox))**0.3333333_wp
933!
934!--    Ensure a smooth value (two significant digits) of distance between
935!--    particles (pdx, pdy, pdz).
936       div = 1000.0_wp
937       DO  WHILE ( pdx(1) < div )
938          div = div / 10.0_wp
939       ENDDO
940       pdx(1) = NINT( pdx(1) * 100.0_wp / div ) * div / 100.0_wp
941       pdy(1) = pdx(1)
942       pdz(1) = pdx(1)
943
944    ENDIF
945
946    DO  j = 2, number_of_particle_groups
947       IF ( psl(j) == 9999999.9_wp )  psl(j) = psl(j-1)
948       IF ( psr(j) == 9999999.9_wp )  psr(j) = psr(j-1)
949       IF ( pss(j) == 9999999.9_wp )  pss(j) = pss(j-1)
950       IF ( psn(j) == 9999999.9_wp )  psn(j) = psn(j-1)
951       IF ( psb(j) == 9999999.9_wp )  psb(j) = psb(j-1)
952       IF ( pst(j) == 9999999.9_wp )  pst(j) = pst(j-1)
953       IF ( pdx(j) == 9999999.9_wp  .OR.  pdx(j) == 0.0_wp )  pdx(j) = pdx(j-1)
954       IF ( pdy(j) == 9999999.9_wp  .OR.  pdy(j) == 0.0_wp )  pdy(j) = pdy(j-1)
955       IF ( pdz(j) == 9999999.9_wp  .OR.  pdz(j) == 0.0_wp )  pdz(j) = pdz(j-1)
956    ENDDO
957
958!
959!-- Allocate arrays required for calculating particle SGS velocities.
960!-- Initialize prefactor required for stoachastic Weil equation.
961    IF ( use_sgs_for_particles  .AND.  .NOT. cloud_droplets )  THEN
962       ALLOCATE( de_dx(nzb:nzt+1,nysg:nyng,nxlg:nxrg), &
963                 de_dy(nzb:nzt+1,nysg:nyng,nxlg:nxrg), &
964                 de_dz(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
965
966       de_dx = 0.0_wp
967       de_dy = 0.0_wp
968       de_dz = 0.0_wp
969
970       sgs_wf_part = 1.0_wp / 3.0_wp
971    ENDIF
972
973!
974!-- Allocate array required for logarithmic vertical interpolation of
975!-- horizontal particle velocities between the surface and the first vertical
976!-- grid level. In order to avoid repeated CPU cost-intensive CALLS of
977!-- intrinsic FORTRAN procedure LOG(z/z0), LOG(z/z0) is precalculated for
978!-- several heights. Splitting into 20 sublayers turned out to be sufficient.
979!-- To obtain exact height levels of particles, linear interpolation is applied
980!-- (see lpm_advec.f90).
981    IF ( constant_flux_layer )  THEN
982
983       ALLOCATE ( log_z_z0(0:number_of_sublayers) )
984       z_p = zu(nzb+1) - zw(nzb)
985
986!
987!--    Calculate horizontal mean value of z0 used for logartihmic
988!--    interpolation. Note: this is not exact for heterogeneous z0.
989!--    However, sensitivity studies showed that the effect is
990!--    negligible.
991       z0_av_local  = SUM( surf_def_h(0)%z0 ) + SUM( surf_lsm_h%z0 ) +         &
992                      SUM( surf_usm_h%z0 )
993       z0_av_global = 0.0_wp
994
995#if defined( __parallel )
996       CALL MPI_ALLREDUCE(z0_av_local, z0_av_global, 1, MPI_REAL, MPI_SUM, &
997                          comm2d, ierr )
998#else
999       z0_av_global = z0_av_local
1000#endif
1001
1002       z0_av_global = z0_av_global  / ( ( ny + 1 ) * ( nx + 1 ) )
1003!
1004!--    Horizontal wind speed is zero below and at z0
1005       log_z_z0(0) = 0.0_wp
1006!
1007!--    Calculate vertical depth of the sublayers
1008       height_int  = ( z_p - z0_av_global ) / REAL( number_of_sublayers, KIND=wp )
1009!
1010!--    Precalculate LOG(z/z0)
1011       height_p    = z0_av_global
1012       DO  k = 1, number_of_sublayers
1013
1014          height_p    = height_p + height_int
1015          log_z_z0(k) = LOG( height_p / z0_av_global )
1016
1017       ENDDO
1018
1019    ENDIF
1020
1021!
1022!-- Check which particle interpolation method should be used
1023    IF ( TRIM( particle_advection_interpolation )  ==  'trilinear' )  THEN
1024       interpolation_simple_corrector = .FALSE.
1025       interpolation_simple_predictor = .FALSE.
1026       interpolation_trilinear        = .TRUE.
1027    ELSEIF ( TRIM( particle_advection_interpolation )  ==  'simple_corrector' )  THEN
1028       interpolation_simple_corrector = .TRUE.
1029       interpolation_simple_predictor = .FALSE.
1030       interpolation_trilinear        = .FALSE.
1031    ELSEIF ( TRIM( particle_advection_interpolation )  ==  'simple_predictor' )  THEN
1032       interpolation_simple_corrector = .FALSE.
1033       interpolation_simple_predictor = .TRUE.
1034       interpolation_trilinear        = .FALSE.
1035    ENDIF
1036
1037!
1038!-- Check boundary condition and set internal variables
1039    SELECT CASE ( bc_par_b )
1040
1041       CASE ( 'absorb' )
1042          ibc_par_b = 1
1043
1044       CASE ( 'reflect' )
1045          ibc_par_b = 2
1046
1047       CASE ( 'reset' )
1048          ibc_par_b = 3
1049
1050       CASE DEFAULT
1051          WRITE( message_string, * )  'unknown boundary condition ',           &
1052                                       'bc_par_b = "', TRIM( bc_par_b ), '"'
1053          CALL message( 'lpm_init', 'PA0217', 1, 2, 0, 6, 0 )
1054
1055    END SELECT
1056    SELECT CASE ( bc_par_t )
1057
1058       CASE ( 'absorb' )
1059          ibc_par_t = 1
1060
1061       CASE ( 'reflect' )
1062          ibc_par_t = 2
1063
1064       CASE ( 'nested' )
1065          ibc_par_t = 3
1066
1067       CASE DEFAULT
1068          WRITE( message_string, * ) 'unknown boundary condition ',            &
1069                                     'bc_par_t = "', TRIM( bc_par_t ), '"'
1070          CALL message( 'lpm_init', 'PA0218', 1, 2, 0, 6, 0 )
1071
1072    END SELECT
1073    SELECT CASE ( bc_par_lr )
1074
1075       CASE ( 'cyclic' )
1076          ibc_par_lr = 0
1077
1078       CASE ( 'absorb' )
1079          ibc_par_lr = 1
1080
1081       CASE ( 'reflect' )
1082          ibc_par_lr = 2
1083
1084       CASE ( 'nested' )
1085          ibc_par_lr = 3
1086
1087       CASE DEFAULT
1088          WRITE( message_string, * ) 'unknown boundary condition ',   &
1089                                     'bc_par_lr = "', TRIM( bc_par_lr ), '"'
1090          CALL message( 'lpm_init', 'PA0219', 1, 2, 0, 6, 0 )
1091
1092    END SELECT
1093    SELECT CASE ( bc_par_ns )
1094
1095       CASE ( 'cyclic' )
1096          ibc_par_ns = 0
1097
1098       CASE ( 'absorb' )
1099          ibc_par_ns = 1
1100
1101       CASE ( 'reflect' )
1102          ibc_par_ns = 2
1103
1104       CASE ( 'nested' )
1105          ibc_par_ns = 3
1106
1107       CASE DEFAULT
1108          WRITE( message_string, * ) 'unknown boundary condition ',   &
1109                                     'bc_par_ns = "', TRIM( bc_par_ns ), '"'
1110          CALL message( 'lpm_init', 'PA0220', 1, 2, 0, 6, 0 )
1111
1112    END SELECT
1113    SELECT CASE ( splitting_mode )
1114
1115       CASE ( 'const' )
1116          i_splitting_mode = 1
1117
1118       CASE ( 'cl_av' )
1119          i_splitting_mode = 2
1120
1121       CASE ( 'gb_av' )
1122          i_splitting_mode = 3
1123
1124       CASE DEFAULT
1125          WRITE( message_string, * )  'unknown splitting_mode = "',            &
1126                                      TRIM( splitting_mode ), '"'
1127          CALL message( 'lpm_init', 'PA0146', 1, 2, 0, 6, 0 )
1128
1129    END SELECT
1130    SELECT CASE ( splitting_function )
1131
1132       CASE ( 'gamma' )
1133          isf = 1
1134
1135       CASE ( 'log' )
1136          isf = 2
1137
1138       CASE ( 'exp' )
1139          isf = 3
1140
1141       CASE DEFAULT
1142          WRITE( message_string, * )  'unknown splitting function = "',        &
1143                                       TRIM( splitting_function ), '"'
1144          CALL message( 'lpm_init', 'PA0147', 1, 2, 0, 6, 0 )
1145
1146    END SELECT
1147!
1148!-- Initialize collision kernels
1149    IF ( collision_kernel /= 'none' )  CALL lpm_init_kernels
1150!
1151!-- For the first model run of a possible job chain initialize the
1152!-- particles, otherwise read the particle data from restart file.
1153    IF ( TRIM( initializing_actions ) == 'read_restart_data'  &
1154         .AND.  read_particles_from_restartfile )  THEN
1155       CALL lpm_rrd_local_particles
1156    ELSE
1157!
1158!--    Allocate particle arrays and set attributes of the initial set of
1159!--    particles, which can be also periodically released at later times.
1160       ALLOCATE( prt_count(nzb:nzt+1,nysg:nyng,nxlg:nxrg), &
1161                 grid_particles(nzb+1:nzt,nys:nyn,nxl:nxr) )
1162
1163       number_of_particles = 0
1164       prt_count           = 0
1165!
1166!--    initialize counter for particle IDs
1167       grid_particles%id_counter = 1
1168!
1169!--    Initialize all particles with dummy values (otherwise errors may
1170!--    occur within restart runs). The reason for this is still not clear
1171!--    and may be presumably caused by errors in the respective user-interface.
1172       zero_particle = particle_type( 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,  &
1173                                      0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,  &
1174                                      0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,  &
1175                                      0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,  &
1176                                      0, 0, 0_idp, .FALSE., -1 )
1177
1178       particle_groups = particle_groups_type( 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp )
1179!
1180!--    Set values for the density ratio and radius for all particle
1181!--    groups, if necessary
1182       IF ( density_ratio(1) == 9999999.9_wp )  density_ratio(1) = 0.0_wp
1183       IF ( radius(1)        == 9999999.9_wp )  radius(1) = 0.0_wp
1184       DO  i = 2, number_of_particle_groups
1185          IF ( density_ratio(i) == 9999999.9_wp )  THEN
1186             density_ratio(i) = density_ratio(i-1)
1187          ENDIF
1188          IF ( radius(i) == 9999999.9_wp )  radius(i) = radius(i-1)
1189       ENDDO
1190
1191       DO  i = 1, number_of_particle_groups
1192          IF ( density_ratio(i) /= 0.0_wp  .AND.  radius(i) == 0 )  THEN
1193             WRITE( message_string, * ) 'particle group #', i, ' has a',       &
1194                                        'density ratio /= 0 but radius = 0'
1195             CALL message( 'lpm_init', 'PA0215', 1, 2, 0, 6, 0 )
1196          ENDIF
1197          particle_groups(i)%density_ratio = density_ratio(i)
1198          particle_groups(i)%radius        = radius(i)
1199       ENDDO
1200!
1201!--    Set a seed value for the random number generator to be exclusively
1202!--    used for the particle code. The generated random numbers should be
1203!--    different on the different PEs.
1204       iran_part = iran_part + myid
1205!
1206!--    Create the particle set, and set the initial particles
1207       CALL lpm_create_particle( phase_init )
1208       last_particle_release_time = particle_advection_start
1209!
1210!--    User modification of initial particles
1211       CALL user_lpm_init
1212!
1213!--    Open file for statistical informations about particle conditions
1214       IF ( write_particle_statistics )  THEN
1215          CALL check_open( 80 )
1216          WRITE ( 80, 8000 )  current_timestep_number, simulated_time,         &
1217                              number_of_particles
1218          CALL close_file( 80 )
1219       ENDIF
1220
1221    ENDIF
1222
1223    IF ( nested_run )  CALL pmcp_g_init
1224!
1225!-- To avoid programm abort, assign particles array to the local version of
1226!-- first grid cell
1227    number_of_particles = prt_count(nzb+1,nys,nxl)
1228    particles => grid_particles(nzb+1,nys,nxl)%particles(1:number_of_particles)
1229!
1230!-- Formats
12318000 FORMAT (I6,1X,F7.2,4X,I10,71X,I10)
1232
1233 END SUBROUTINE lpm_init
1234 
1235!------------------------------------------------------------------------------!
1236! Description:
1237! ------------
1238!> Create Lagrangian particles
1239!------------------------------------------------------------------------------! 
1240 SUBROUTINE lpm_create_particle (phase)
1241
1242    INTEGER(iwp)               ::  alloc_size  !< relative increase of allocated memory for particles
1243    INTEGER(iwp)               ::  i           !< loop variable ( particle groups )
1244    INTEGER(iwp)               ::  ip          !< index variable along x
1245    INTEGER(iwp)               ::  j           !< loop variable ( particles per point )
1246    INTEGER(iwp)               ::  jp          !< index variable along y
1247    INTEGER(iwp)               ::  k           !< index variable along z
1248    INTEGER(iwp)               ::  k_surf      !< index of surface grid point
1249    INTEGER(iwp)               ::  kp          !< index variable along z
1250    INTEGER(iwp)               ::  loop_stride !< loop variable for initialization
1251    INTEGER(iwp)               ::  n           !< loop variable ( number of particles )
1252    INTEGER(iwp)               ::  new_size    !< new size of allocated memory for particles
1253
1254    INTEGER(iwp), INTENT(IN)   ::  phase       !< mode of inititialization
1255
1256    INTEGER(iwp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg) ::  local_count !< start address of new particle
1257    INTEGER(iwp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg) ::  local_start !< start address of new particle
1258
1259    LOGICAL                    ::  first_stride !< flag for initialization
1260
1261    REAL(wp)                   ::  pos_x      !< increment for particle position in x
1262    REAL(wp)                   ::  pos_y      !< increment for particle position in y
1263    REAL(wp)                   ::  pos_z      !< increment for particle position in z
1264    REAL(wp)                   ::  rand_contr !< dummy argument for random position
1265
1266    TYPE(particle_type),TARGET ::  tmp_particle !< temporary particle used for initialization
1267
1268
1269!
1270!-- Calculate particle positions and store particle attributes, if
1271!-- particle is situated on this PE
1272    DO  loop_stride = 1, 2
1273       first_stride = (loop_stride == 1)
1274       IF ( first_stride )   THEN
1275          local_count = 0           ! count number of particles
1276       ELSE
1277          local_count = prt_count   ! Start address of new particles
1278       ENDIF
1279
1280!
1281!--    Calculate initial_weighting_factor diagnostically
1282       IF ( number_concentration /= -1.0_wp  .AND.  number_concentration > 0.0_wp )  THEN
1283          initial_weighting_factor =  number_concentration  *                           &
1284                                      pdx(1) * pdy(1) * pdz(1)
1285       END IF
1286
1287       n = 0
1288       DO  i = 1, number_of_particle_groups
1289          pos_z = psb(i)
1290          DO WHILE ( pos_z <= pst(i) )
1291             IF ( pos_z >= zw(0) .AND.  pos_z < zw(nzt) )  THEN
1292                pos_y = pss(i)
1293                DO WHILE ( pos_y <= psn(i) )
1294                   IF ( pos_y >= nys * dy  .AND.                  &
1295                        pos_y <  ( nyn + 1 ) * dy  )  THEN
1296                      pos_x = psl(i)
1297               xloop: DO WHILE ( pos_x <= psr(i) )
1298                         IF ( pos_x >= nxl * dx  .AND.            &
1299                              pos_x <  ( nxr + 1) * dx )  THEN
1300                            DO  j = 1, particles_per_point
1301                               n = n + 1
1302                               tmp_particle%x             = pos_x
1303                               tmp_particle%y             = pos_y
1304                               tmp_particle%z             = pos_z
1305                               tmp_particle%age           = 0.0_wp
1306                               tmp_particle%age_m         = 0.0_wp
1307                               tmp_particle%dt_sum        = 0.0_wp
1308                               tmp_particle%e_m           = 0.0_wp
1309                               tmp_particle%rvar1         = 0.0_wp
1310                               tmp_particle%rvar2         = 0.0_wp
1311                               tmp_particle%rvar3         = 0.0_wp
1312                               tmp_particle%speed_x       = 0.0_wp
1313                               tmp_particle%speed_y       = 0.0_wp
1314                               tmp_particle%speed_z       = 0.0_wp
1315                               tmp_particle%origin_x      = pos_x
1316                               tmp_particle%origin_y      = pos_y
1317                               tmp_particle%origin_z      = pos_z
1318                               IF ( curvature_solution_effects )  THEN
1319                                  tmp_particle%aux1      = 0.0_wp    ! dry aerosol radius
1320                                  tmp_particle%aux2      = dt_3d     ! last Rosenbrock timestep
1321                               ELSE
1322                                  tmp_particle%aux1      = 0.0_wp    ! free to use
1323                                  tmp_particle%aux2      = 0.0_wp    ! free to use
1324                               ENDIF
1325                               tmp_particle%radius        = particle_groups(i)%radius
1326                               tmp_particle%weight_factor = initial_weighting_factor
1327                               tmp_particle%class         = 1
1328                               tmp_particle%group         = i
1329                               tmp_particle%id            = 0_idp
1330                               tmp_particle%particle_mask = .TRUE.
1331                               tmp_particle%block_nr      = -1
1332!
1333!--                            Determine the grid indices of the particle position
1334                               ip = INT( tmp_particle%x * ddx )
1335                               jp = INT( tmp_particle%y * ddy )
1336!
1337!--                            In case of stretching the actual k index is found iteratively
1338                               IF ( dz_stretch_level /= -9999999.9_wp  .OR.           &
1339                                    dz_stretch_level_start(1) /= -9999999.9_wp )  THEN
1340                                  kp = MINLOC( ABS( tmp_particle%z - zu ), DIM = 1 ) - 1
1341                               ELSE
1342                                  kp = INT( tmp_particle%z / dz(1) + 1 + offset_ocean_nzt )
1343                               ENDIF
1344!
1345!--                            Determine surface level. Therefore, check for
1346!--                            upward-facing wall on w-grid.
1347                               k_surf = topo_top_ind(jp,ip,3)
1348                               IF ( seed_follows_topography )  THEN
1349!
1350!--                               Particle height is given relative to topography
1351                                  kp = kp + k_surf
1352                                  tmp_particle%z = tmp_particle%z + zw(k_surf)
1353!--                               Skip particle release if particle position is
1354!--                               above model top, or within topography in case
1355!--                               of overhanging structures.
1356                                  IF ( kp > nzt  .OR.                          &
1357                                 .NOT. BTEST( wall_flags_static_0(kp,jp,ip), 0 ) )  THEN
1358                                     pos_x = pos_x + pdx(i)
1359                                     CYCLE xloop
1360                                  ENDIF
1361!
1362!--                            Skip particle release if particle position is
1363!--                            below surface, or within topography in case
1364!--                            of overhanging structures.
1365                               ELSEIF ( .NOT. seed_follows_topography .AND.    &
1366                                         tmp_particle%z <= zw(k_surf)  .OR.    &
1367                                        .NOT. BTEST( wall_flags_static_0(kp,jp,ip), 0 ) )&
1368                               THEN
1369                                  pos_x = pos_x + pdx(i)
1370                                  CYCLE xloop
1371                               ENDIF
1372
1373                               local_count(kp,jp,ip) = local_count(kp,jp,ip) + 1
1374
1375                               IF ( .NOT. first_stride )  THEN
1376                                  IF ( ip < nxl  .OR.  jp < nys  .OR.  kp < nzb+1 )  THEN
1377                                     write(6,*) 'xl ',ip,jp,kp,nxl,nys,nzb+1
1378                                  ENDIF
1379                                  IF ( ip > nxr  .OR.  jp > nyn  .OR.  kp > nzt )  THEN
1380                                     write(6,*) 'xu ',ip,jp,kp,nxr,nyn,nzt
1381                                  ENDIF
1382                                  grid_particles(kp,jp,ip)%particles(local_count(kp,jp,ip)) = tmp_particle
1383                               ENDIF
1384                            ENDDO
1385                         ENDIF
1386                         pos_x = pos_x + pdx(i)
1387                      ENDDO xloop
1388                   ENDIF
1389                   pos_y = pos_y + pdy(i)
1390                ENDDO
1391             ENDIF
1392
1393             pos_z = pos_z + pdz(i)
1394          ENDDO
1395       ENDDO
1396
1397       IF ( first_stride )  THEN
1398          DO  ip = nxl, nxr
1399             DO  jp = nys, nyn
1400                DO  kp = nzb+1, nzt
1401                   IF ( phase == PHASE_INIT )  THEN
1402                      IF ( local_count(kp,jp,ip) > 0 )  THEN
1403                         alloc_size = MAX( INT( local_count(kp,jp,ip) *        &
1404                            ( 1.0_wp + alloc_factor / 100.0_wp ) ),            &
1405                            1 )
1406                      ELSE
1407                         alloc_size = 1
1408                      ENDIF
1409                      ALLOCATE(grid_particles(kp,jp,ip)%particles(1:alloc_size))
1410                      DO  n = 1, alloc_size
1411                         grid_particles(kp,jp,ip)%particles(n) = zero_particle
1412                      ENDDO
1413                   ELSEIF ( phase == PHASE_RELEASE )  THEN
1414                      IF ( local_count(kp,jp,ip) > 0 )  THEN
1415                         new_size   = local_count(kp,jp,ip) + prt_count(kp,jp,ip)
1416                         alloc_size = MAX( INT( new_size * ( 1.0_wp +          &
1417                            alloc_factor / 100.0_wp ) ), 1 )
1418                         IF( alloc_size > SIZE( grid_particles(kp,jp,ip)%particles) )  THEN
1419                            CALL realloc_particles_array( ip, jp, kp, alloc_size )
1420                         ENDIF
1421                      ENDIF
1422                   ENDIF
1423                ENDDO
1424             ENDDO
1425          ENDDO
1426       ENDIF
1427
1428    ENDDO
1429
1430    local_start = prt_count+1
1431    prt_count   = local_count
1432!
1433!-- Calculate particle IDs
1434    DO  ip = nxl, nxr
1435       DO  jp = nys, nyn
1436          DO  kp = nzb+1, nzt
1437             number_of_particles = prt_count(kp,jp,ip)
1438             IF ( number_of_particles <= 0 )  CYCLE
1439             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
1440
1441             DO  n = local_start(kp,jp,ip), number_of_particles  !only new particles
1442
1443                particles(n)%id = 10000_idp**3 * grid_particles(kp,jp,ip)%id_counter + &
1444                                  10000_idp**2 * kp + 10000_idp * jp + ip
1445!
1446!--             Count the number of particles that have been released before
1447                grid_particles(kp,jp,ip)%id_counter =                          &
1448                                         grid_particles(kp,jp,ip)%id_counter + 1
1449
1450             ENDDO
1451
1452          ENDDO
1453       ENDDO
1454    ENDDO
1455!
1456!-- Initialize aerosol background spectrum
1457    IF ( curvature_solution_effects )  THEN
1458       CALL lpm_init_aerosols( local_start )
1459    ENDIF
1460!
1461!-- Add random fluctuation to particle positions.
1462    IF ( random_start_position )  THEN
1463       DO  ip = nxl, nxr
1464          DO  jp = nys, nyn
1465             DO  kp = nzb+1, nzt
1466                number_of_particles = prt_count(kp,jp,ip)
1467                IF ( number_of_particles <= 0 )  CYCLE
1468                particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
1469!
1470!--             Move only new particles. Moreover, limit random fluctuation
1471!--             in order to prevent that particles move more than one grid box,
1472!--             which would lead to problems concerning particle exchange
1473!--             between processors in case pdx/pdy are larger than dx/dy,
1474!--             respectively.
1475                DO  n = local_start(kp,jp,ip), number_of_particles
1476                   IF ( psl(particles(n)%group) /= psr(particles(n)%group) )  THEN
1477                      rand_contr = ( random_function( iran_part ) - 0.5_wp ) * &
1478                                     pdx(particles(n)%group)
1479                      particles(n)%x = particles(n)%x +                        &
1480                              MERGE( rand_contr, SIGN( dx, rand_contr ),       &
1481                                     ABS( rand_contr ) < dx                    &
1482                                   )
1483                   ENDIF
1484                   IF ( pss(particles(n)%group) /= psn(particles(n)%group) )  THEN
1485                      rand_contr = ( random_function( iran_part ) - 0.5_wp ) * &
1486                                     pdy(particles(n)%group)
1487                      particles(n)%y = particles(n)%y +                        &
1488                              MERGE( rand_contr, SIGN( dy, rand_contr ),       &
1489                                     ABS( rand_contr ) < dy                    &
1490                                   )
1491                   ENDIF
1492                   IF ( psb(particles(n)%group) /= pst(particles(n)%group) )  THEN
1493                      rand_contr = ( random_function( iran_part ) - 0.5_wp ) * &
1494                                     pdz(particles(n)%group)
1495                      particles(n)%z = particles(n)%z +                        &
1496                              MERGE( rand_contr, SIGN( dzw(kp), rand_contr ),  &
1497                                     ABS( rand_contr ) < dzw(kp)               &
1498                                   )
1499                   ENDIF
1500                ENDDO
1501!
1502!--             Identify particles located outside the model domain and reflect
1503!--             or absorb them if necessary.
1504                CALL lpm_boundary_conds( 'bottom/top', i, j, k )
1505!
1506!--             Furthermore, remove particles located in topography. Note, as
1507!--             the particle speed is still zero at this point, wall
1508!--             reflection boundary conditions will not work in this case.
1509                particles =>                                                   &
1510                       grid_particles(kp,jp,ip)%particles(1:number_of_particles)
1511                DO  n = local_start(kp,jp,ip), number_of_particles
1512                   i = particles(n)%x * ddx
1513                   j = particles(n)%y * ddy
1514                   k = particles(n)%z / dz(1) + 1 + offset_ocean_nzt
1515                   DO WHILE( zw(k) < particles(n)%z )
1516                      k = k + 1
1517                   ENDDO
1518                   DO WHILE( zw(k-1) > particles(n)%z )
1519                      k = k - 1
1520                   ENDDO
1521!
1522!--                Check if particle is within topography
1523                   IF ( .NOT. BTEST( wall_flags_static_0(k,j,i), 0 ) )  THEN
1524                      particles(n)%particle_mask = .FALSE.
1525                      deleted_particles = deleted_particles + 1
1526                   ENDIF
1527
1528                ENDDO
1529             ENDDO
1530          ENDDO
1531       ENDDO
1532!
1533!--    Exchange particles between grid cells and processors
1534       CALL lpm_move_particle
1535       CALL lpm_exchange_horiz
1536
1537    ENDIF
1538!
1539!-- In case of random_start_position, delete particles identified by
1540!-- lpm_exchange_horiz and lpm_boundary_conds. Then sort particles into blocks,
1541!-- which is needed for a fast interpolation of the LES fields on the particle
1542!-- position.
1543    CALL lpm_sort_and_delete
1544!
1545!-- Determine the current number of particles
1546    DO  ip = nxl, nxr
1547       DO  jp = nys, nyn
1548          DO  kp = nzb+1, nzt
1549             number_of_particles         = number_of_particles                 &
1550                                           + prt_count(kp,jp,ip)
1551          ENDDO
1552       ENDDO
1553    ENDDO
1554!
1555!-- Calculate the number of particles of the total domain
1556#if defined( __parallel )
1557    IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1558    CALL MPI_ALLREDUCE( number_of_particles, total_number_of_particles, 1, &
1559    MPI_INTEGER, MPI_SUM, comm2d, ierr )
1560#else
1561    total_number_of_particles = number_of_particles
1562#endif
1563
1564    RETURN
1565
1566 END SUBROUTINE lpm_create_particle
1567 
1568 
1569!------------------------------------------------------------------------------!
1570! Description:
1571! ------------
1572!> This routine initialize the particles as aerosols with physio-chemical
1573!> properties.
1574!------------------------------------------------------------------------------!   
1575 SUBROUTINE lpm_init_aerosols(local_start)
1576
1577    REAL(wp) ::  afactor            !< curvature effects
1578    REAL(wp) ::  bfactor            !< solute effects
1579    REAL(wp) ::  dlogr              !< logarithmic width of radius bin
1580    REAL(wp) ::  e_a                !< vapor pressure
1581    REAL(wp) ::  e_s                !< saturation vapor pressure
1582    REAL(wp) ::  rmin = 0.005e-6_wp !< minimum aerosol radius
1583    REAL(wp) ::  rmax = 10.0e-6_wp  !< maximum aerosol radius
1584    REAL(wp) ::  r_mid              !< mean radius of bin
1585    REAL(wp) ::  r_l                !< left radius of bin
1586    REAL(wp) ::  r_r                !< right radius of bin
1587    REAL(wp) ::  sigma              !< surface tension
1588    REAL(wp) ::  t_int              !< temperature
1589
1590    INTEGER(iwp), DIMENSION(nzb:nzt+1,nysg:nyng,nxlg:nxrg), INTENT(IN) ::  local_start !<
1591
1592    INTEGER(iwp) ::  n              !<
1593    INTEGER(iwp) ::  ip             !<
1594    INTEGER(iwp) ::  jp             !<
1595    INTEGER(iwp) ::  kp             !<
1596
1597!
1598!-- Set constants for different aerosol species
1599    IF ( TRIM( aero_species ) == 'nacl' )  THEN
1600       molecular_weight_of_solute = 0.05844_wp 
1601       rho_s                      = 2165.0_wp
1602       vanthoff                   = 2.0_wp
1603    ELSEIF ( TRIM( aero_species ) == 'c3h4o4' )  THEN
1604       molecular_weight_of_solute = 0.10406_wp 
1605       rho_s                      = 1600.0_wp
1606       vanthoff                   = 1.37_wp
1607    ELSEIF ( TRIM( aero_species ) == 'nh4o3' )  THEN
1608       molecular_weight_of_solute = 0.08004_wp 
1609       rho_s                      = 1720.0_wp
1610       vanthoff                   = 2.31_wp
1611    ELSE
1612       WRITE( message_string, * ) 'unknown aerosol species ',   &
1613                                'aero_species = "', TRIM( aero_species ), '"'
1614       CALL message( 'lpm_init', 'PA0470', 1, 2, 0, 6, 0 )
1615    ENDIF
1616!
1617!-- The following typical aerosol spectra are taken from Jaenicke (1993):
1618!-- Tropospheric aerosols. Published in Aerosol-Cloud-Climate Interactions.
1619    IF ( TRIM( aero_type ) == 'polar' )  THEN
1620       na        = (/ 2.17e1, 1.86e-1, 3.04e-4 /) * 1.0E6_wp
1621       rm        = (/ 0.0689, 0.375, 4.29 /) * 1.0E-6_wp
1622       log_sigma = (/ 0.245, 0.300, 0.291 /)
1623    ELSEIF ( TRIM( aero_type ) == 'background' )  THEN
1624       na        = (/ 1.29e2, 5.97e1, 6.35e1 /) * 1.0E6_wp
1625       rm        = (/ 0.0036, 0.127, 0.259 /) * 1.0E-6_wp
1626       log_sigma = (/ 0.645, 0.253, 0.425 /)
1627    ELSEIF ( TRIM( aero_type ) == 'maritime' )  THEN
1628       na        = (/ 1.33e2, 6.66e1, 3.06e0 /) * 1.0E6_wp
1629       rm        = (/ 0.0039, 0.133, 0.29 /) * 1.0E-6_wp
1630       log_sigma = (/ 0.657, 0.210, 0.396 /)
1631    ELSEIF ( TRIM( aero_type ) == 'continental' )  THEN
1632       na        = (/ 3.20e3, 2.90e3, 3.00e-1 /) * 1.0E6_wp
1633       rm        = (/ 0.01, 0.058, 0.9 /) * 1.0E-6_wp
1634       log_sigma = (/ 0.161, 0.217, 0.380 /)
1635    ELSEIF ( TRIM( aero_type ) == 'desert' )  THEN
1636       na        = (/ 7.26e2, 1.14e3, 1.78e-1 /) * 1.0E6_wp
1637       rm        = (/ 0.001, 0.0188, 10.8 /) * 1.0E-6_wp
1638       log_sigma = (/ 0.247, 0.770, 0.438 /)
1639    ELSEIF ( TRIM( aero_type ) == 'rural' )  THEN
1640       na        = (/ 6.65e3, 1.47e2, 1.99e3 /) * 1.0E6_wp
1641       rm        = (/ 0.00739, 0.0269, 0.0419 /) * 1.0E-6_wp
1642       log_sigma = (/ 0.225, 0.557, 0.266 /)
1643    ELSEIF ( TRIM( aero_type ) == 'urban' )  THEN
1644       na        = (/ 9.93e4, 1.11e3, 3.64e4 /) * 1.0E6_wp
1645       rm        = (/ 0.00651, 0.00714, 0.0248 /) * 1.0E-6_wp
1646       log_sigma = (/ 0.245, 0.666, 0.337 /)
1647    ELSEIF ( TRIM( aero_type ) == 'user' )  THEN
1648       CONTINUE
1649    ELSE
1650       WRITE( message_string, * ) 'unknown aerosol type ',   &
1651                                'aero_type = "', TRIM( aero_type ), '"'
1652       CALL message( 'lpm_init', 'PA0459', 1, 2, 0, 6, 0 )
1653    ENDIF
1654
1655    DO  ip = nxl, nxr
1656       DO  jp = nys, nyn
1657          DO  kp = nzb+1, nzt
1658
1659             number_of_particles = prt_count(kp,jp,ip)
1660             IF ( number_of_particles <= 0 )  CYCLE
1661             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
1662
1663             dlogr   = ( LOG10(rmax) - LOG10(rmin) ) / ( number_of_particles - local_start(kp,jp,ip) + 1 )
1664!
1665!--          Initialize the aerosols with a predefined spectral distribution
1666!--          of the dry radius (logarithmically increasing bins) and a varying
1667!--          weighting factor
1668             DO  n = local_start(kp,jp,ip), number_of_particles  !only new particles
1669
1670                r_l   = 10.0**( LOG10( rmin ) + (n-1) * dlogr )
1671                r_r   = 10.0**( LOG10( rmin ) + n * dlogr )
1672                r_mid = SQRT( r_l * r_r )
1673
1674                particles(n)%aux1          = r_mid
1675                particles(n)%weight_factor =                                           &
1676                   ( na(1) / ( SQRT( 2.0_wp * pi ) * log_sigma(1) ) *                     &
1677                     EXP( - LOG10( r_mid / rm(1) )**2 / ( 2.0_wp * log_sigma(1)**2 ) ) +  &
1678                     na(2) / ( SQRT( 2.0_wp * pi ) * log_sigma(2) ) *                     &
1679                     EXP( - LOG10( r_mid / rm(2) )**2 / ( 2.0_wp * log_sigma(2)**2 ) ) +  &
1680                     na(3) / ( SQRT( 2.0_wp * pi ) * log_sigma(3) ) *                     &
1681                     EXP( - LOG10( r_mid / rm(3) )**2 / ( 2.0_wp * log_sigma(3)**2 ) )    &
1682                   ) * ( LOG10(r_r) - LOG10(r_l) ) * ( dx * dy * dzw(kp) )
1683
1684!
1685!--             Multiply weight_factor with the namelist parameter aero_weight
1686!--             to increase or decrease the number of simulated aerosols
1687                particles(n)%weight_factor = particles(n)%weight_factor * aero_weight
1688
1689                IF ( particles(n)%weight_factor - FLOOR(particles(n)%weight_factor,KIND=wp) &
1690                     > random_function( iran_part ) )  THEN
1691                   particles(n)%weight_factor = FLOOR(particles(n)%weight_factor,KIND=wp) + 1.0_wp
1692                ELSE
1693                   particles(n)%weight_factor = FLOOR(particles(n)%weight_factor,KIND=wp)
1694                ENDIF
1695!
1696!--             Unnecessary particles will be deleted
1697                IF ( particles(n)%weight_factor <= 0.0_wp )  particles(n)%particle_mask = .FALSE.
1698
1699             ENDDO
1700!
1701!--          Set particle radius to equilibrium radius based on the environmental
1702!--          supersaturation (Khvorostyanov and Curry, 2007, JGR). This avoids
1703!--          the sometimes lengthy growth toward their equilibrium radius within
1704!--          the simulation.
1705             t_int  = pt(kp,jp,ip) * exner(kp)
1706
1707             e_s = magnus( t_int )
1708             e_a = q(kp,jp,ip) * hyp(kp) / ( q(kp,jp,ip) + rd_d_rv )
1709
1710             sigma   = 0.0761_wp - 0.000155_wp * ( t_int - 273.15_wp )
1711             afactor = 2.0_wp * sigma / ( rho_l * r_v * t_int )
1712
1713             bfactor = vanthoff * molecular_weight_of_water *    &
1714                       rho_s / ( molecular_weight_of_solute * rho_l )
1715!
1716!--          The formula is only valid for subsaturated environments. For
1717!--          supersaturations higher than -5 %, the supersaturation is set to -5%.
1718             IF ( e_a / e_s >= 0.95_wp )  e_a = 0.95_wp * e_s
1719
1720             DO  n = local_start(kp,jp,ip), number_of_particles  !only new particles
1721!
1722!--             For details on this equation, see Eq. (14) of Khvorostyanov and
1723!--             Curry (2007, JGR)
1724                particles(n)%radius = bfactor**0.3333333_wp *                  &
1725                   particles(n)%aux1 / ( 1.0_wp - e_a / e_s )**0.3333333_wp / &
1726                   ( 1.0_wp + ( afactor / ( 3.0_wp * bfactor**0.3333333_wp *   &
1727                     particles(n)%aux1 ) ) /                                  &
1728                     ( 1.0_wp - e_a / e_s )**0.6666666_wp                      &
1729                   )
1730
1731             ENDDO
1732
1733          ENDDO
1734       ENDDO
1735    ENDDO
1736
1737 END SUBROUTINE lpm_init_aerosols
1738
1739
1740!------------------------------------------------------------------------------!
1741! Description:
1742! ------------
1743!> Calculates quantities required for considering the SGS velocity fluctuations
1744!> in the particle transport by a stochastic approach. The respective
1745!> quantities are: SGS-TKE gradients and horizontally averaged profiles of the
1746!> SGS TKE and the resolved-scale velocity variances.
1747!------------------------------------------------------------------------------!
1748 SUBROUTINE lpm_init_sgs_tke
1749
1750    USE statistics,                                                            &
1751        ONLY:  flow_statistics_called, hom, sums, sums_l
1752
1753    INTEGER(iwp) ::  i      !< index variable along x
1754    INTEGER(iwp) ::  j      !< index variable along y
1755    INTEGER(iwp) ::  k      !< index variable along z
1756    INTEGER(iwp) ::  m      !< running index for the surface elements
1757
1758    REAL(wp) ::  flag1      !< flag to mask topography
1759
1760!
1761!-- TKE gradient along x and y
1762    DO  i = nxl, nxr
1763       DO  j = nys, nyn
1764          DO  k = nzb, nzt+1
1765
1766             IF ( .NOT. BTEST( wall_flags_static_0(k,j,i-1), 0 )  .AND.               &
1767                        BTEST( wall_flags_static_0(k,j,i), 0   )  .AND.               &
1768                        BTEST( wall_flags_static_0(k,j,i+1), 0 ) )                    &
1769             THEN
1770                de_dx(k,j,i) = 2.0_wp * sgs_wf_part *                          &
1771                               ( e(k,j,i+1) - e(k,j,i) ) * ddx
1772             ELSEIF ( BTEST( wall_flags_static_0(k,j,i-1), 0 )  .AND.                 &
1773                      BTEST( wall_flags_static_0(k,j,i), 0   )  .AND.                 &
1774                .NOT. BTEST( wall_flags_static_0(k,j,i+1), 0 ) )                      &
1775             THEN
1776                de_dx(k,j,i) = 2.0_wp * sgs_wf_part *                          &
1777                               ( e(k,j,i) - e(k,j,i-1) ) * ddx
1778             ELSEIF ( .NOT. BTEST( wall_flags_static_0(k,j,i), 22   )  .AND.          &
1779                      .NOT. BTEST( wall_flags_static_0(k,j,i+1), 22 ) )               &   
1780             THEN
1781                de_dx(k,j,i) = 0.0_wp
1782             ELSEIF ( .NOT. BTEST( wall_flags_static_0(k,j,i-1), 22 )  .AND.          &
1783                      .NOT. BTEST( wall_flags_static_0(k,j,i), 22   ) )               &
1784             THEN
1785                de_dx(k,j,i) = 0.0_wp
1786             ELSE
1787                de_dx(k,j,i) = sgs_wf_part * ( e(k,j,i+1) - e(k,j,i-1) ) * ddx
1788             ENDIF
1789
1790             IF ( .NOT. BTEST( wall_flags_static_0(k,j-1,i), 0 )  .AND.               &
1791                        BTEST( wall_flags_static_0(k,j,i), 0   )  .AND.               &
1792                        BTEST( wall_flags_static_0(k,j+1,i), 0 ) )                    &
1793             THEN
1794                de_dy(k,j,i) = 2.0_wp * sgs_wf_part *                          &
1795                               ( e(k,j+1,i) - e(k,j,i) ) * ddy
1796             ELSEIF ( BTEST( wall_flags_static_0(k,j-1,i), 0 )  .AND.                 &
1797                      BTEST( wall_flags_static_0(k,j,i), 0   )  .AND.                 &
1798                .NOT. BTEST( wall_flags_static_0(k,j+1,i), 0 ) )                      &
1799             THEN
1800                de_dy(k,j,i) = 2.0_wp * sgs_wf_part *                          &
1801                               ( e(k,j,i) - e(k,j-1,i) ) * ddy
1802             ELSEIF ( .NOT. BTEST( wall_flags_static_0(k,j,i), 22   )  .AND.          &
1803                      .NOT. BTEST( wall_flags_static_0(k,j+1,i), 22 ) )               &   
1804             THEN
1805                de_dy(k,j,i) = 0.0_wp
1806             ELSEIF ( .NOT. BTEST( wall_flags_static_0(k,j-1,i), 22 )  .AND.          &
1807                      .NOT. BTEST( wall_flags_static_0(k,j,i), 22   ) )               &
1808             THEN
1809                de_dy(k,j,i) = 0.0_wp
1810             ELSE
1811                de_dy(k,j,i) = sgs_wf_part * ( e(k,j+1,i) - e(k,j-1,i) ) * ddy
1812             ENDIF
1813
1814          ENDDO
1815       ENDDO
1816    ENDDO
1817
1818!
1819!-- TKE gradient along z at topograhy and  including bottom and top boundary conditions
1820    DO  i = nxl, nxr
1821       DO  j = nys, nyn
1822          DO  k = nzb+1, nzt-1
1823!
1824!--          Flag to mask topography
1825             flag1 = MERGE( 1.0_wp, 0.0_wp, BTEST( wall_flags_static_0(k,j,i), 0  ) )
1826
1827             de_dz(k,j,i) = 2.0_wp * sgs_wf_part *                             &
1828                           ( e(k+1,j,i) - e(k-1,j,i) ) / ( zu(k+1) - zu(k-1) ) &
1829                                                 * flag1 
1830          ENDDO
1831!
1832!--       upward-facing surfaces
1833          DO  m = bc_h(0)%start_index(j,i), bc_h(0)%end_index(j,i)
1834             k            = bc_h(0)%k(m)
1835             de_dz(k,j,i) = 2.0_wp * sgs_wf_part *                             &
1836                           ( e(k+1,j,i) - e(k,j,i)   ) / ( zu(k+1) - zu(k) )
1837          ENDDO
1838!
1839!--       downward-facing surfaces
1840          DO  m = bc_h(1)%start_index(j,i), bc_h(1)%end_index(j,i)
1841             k            = bc_h(1)%k(m)
1842             de_dz(k,j,i) = 2.0_wp * sgs_wf_part *                             &
1843                           ( e(k,j,i) - e(k-1,j,i)   ) / ( zu(k) - zu(k-1) )
1844          ENDDO
1845
1846          de_dz(nzb,j,i)   = 0.0_wp
1847          de_dz(nzt,j,i)   = 0.0_wp
1848          de_dz(nzt+1,j,i) = 0.0_wp
1849       ENDDO
1850    ENDDO
1851!
1852!-- Ghost point exchange
1853    CALL exchange_horiz( de_dx, nbgp )
1854    CALL exchange_horiz( de_dy, nbgp )
1855    CALL exchange_horiz( de_dz, nbgp )
1856    CALL exchange_horiz( diss, nbgp  )
1857!
1858!-- Set boundary conditions at non-periodic boundaries. Note, at non-period
1859!-- boundaries zero-gradient boundary conditions are set for the subgrid TKE.
1860!-- Thus, TKE gradients normal to the respective lateral boundaries are zero,
1861!-- while tangetial TKE gradients then must be the same as within the prognostic
1862!-- domain. 
1863    IF ( bc_dirichlet_l )  THEN
1864       de_dx(:,:,-1) = 0.0_wp
1865       de_dy(:,:,-1) = de_dy(:,:,0) 
1866       de_dz(:,:,-1) = de_dz(:,:,0)
1867    ENDIF
1868    IF ( bc_dirichlet_r )  THEN
1869       de_dx(:,:,nxr+1) = 0.0_wp
1870       de_dy(:,:,nxr+1) = de_dy(:,:,nxr) 
1871       de_dz(:,:,nxr+1) = de_dz(:,:,nxr)
1872    ENDIF
1873    IF ( bc_dirichlet_n )  THEN
1874       de_dx(:,nyn+1,:) = de_dx(:,nyn,:)
1875       de_dy(:,nyn+1,:) = 0.0_wp 
1876       de_dz(:,nyn+1,:) = de_dz(:,nyn,:)
1877    ENDIF
1878    IF ( bc_dirichlet_s )  THEN
1879       de_dx(:,nys-1,:) = de_dx(:,nys,:)
1880       de_dy(:,nys-1,:) = 0.0_wp 
1881       de_dz(:,nys-1,:) = de_dz(:,nys,:)
1882    ENDIF 
1883!
1884!-- Calculate the horizontally averaged profiles of SGS TKE and resolved
1885!-- velocity variances (they may have been already calculated in routine
1886!-- flow_statistics).
1887    IF ( .NOT. flow_statistics_called )  THEN
1888
1889!
1890!--    First calculate horizontally averaged profiles of the horizontal
1891!--    velocities.
1892       sums_l(:,1,0) = 0.0_wp
1893       sums_l(:,2,0) = 0.0_wp
1894
1895       DO  i = nxl, nxr
1896          DO  j =  nys, nyn
1897             DO  k = nzb, nzt+1
1898!
1899!--             Flag indicating vicinity of wall
1900                flag1 = MERGE( 1.0_wp, 0.0_wp, BTEST( wall_flags_static_0(k,j,i), 24 ) )
1901
1902                sums_l(k,1,0)  = sums_l(k,1,0)  + u(k,j,i) * flag1
1903                sums_l(k,2,0)  = sums_l(k,2,0)  + v(k,j,i) * flag1
1904             ENDDO
1905          ENDDO
1906       ENDDO
1907
1908#if defined( __parallel )
1909!
1910!--    Compute total sum from local sums
1911       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1912       CALL MPI_ALLREDUCE( sums_l(nzb,1,0), sums(nzb,1), nzt+2-nzb, &
1913                           MPI_REAL, MPI_SUM, comm2d, ierr )
1914       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1915       CALL MPI_ALLREDUCE( sums_l(nzb,2,0), sums(nzb,2), nzt+2-nzb, &
1916                              MPI_REAL, MPI_SUM, comm2d, ierr )
1917#else
1918       sums(:,1) = sums_l(:,1,0)
1919       sums(:,2) = sums_l(:,2,0)
1920#endif
1921
1922!
1923!--    Final values are obtained by division by the total number of grid
1924!--    points used for the summation.
1925       hom(:,1,1,0) = sums(:,1) / ngp_2dh_outer(:,0)   ! u
1926       hom(:,1,2,0) = sums(:,2) / ngp_2dh_outer(:,0)   ! v
1927
1928!
1929!--    Now calculate the profiles of SGS TKE and the resolved-scale
1930!--    velocity variances
1931       sums_l(:,8,0)  = 0.0_wp
1932       sums_l(:,30,0) = 0.0_wp
1933       sums_l(:,31,0) = 0.0_wp
1934       sums_l(:,32,0) = 0.0_wp
1935       DO  i = nxl, nxr
1936          DO  j = nys, nyn
1937             DO  k = nzb, nzt+1
1938!
1939!--             Flag indicating vicinity of wall
1940                flag1 = MERGE( 1.0_wp, 0.0_wp, BTEST( wall_flags_static_0(k,j,i), 24 ) )
1941
1942                sums_l(k,8,0)  = sums_l(k,8,0)  + e(k,j,i)                       * flag1
1943                sums_l(k,30,0) = sums_l(k,30,0) + ( u(k,j,i) - hom(k,1,1,0) )**2 * flag1
1944                sums_l(k,31,0) = sums_l(k,31,0) + ( v(k,j,i) - hom(k,1,2,0) )**2 * flag1
1945                sums_l(k,32,0) = sums_l(k,32,0) + w(k,j,i)**2                    * flag1
1946             ENDDO
1947          ENDDO
1948       ENDDO
1949
1950#if defined( __parallel )
1951!
1952!--    Compute total sum from local sums
1953       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1954       CALL MPI_ALLREDUCE( sums_l(nzb,8,0), sums(nzb,8), nzt+2-nzb, &
1955                           MPI_REAL, MPI_SUM, comm2d, ierr )
1956       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1957       CALL MPI_ALLREDUCE( sums_l(nzb,30,0), sums(nzb,30), nzt+2-nzb, &
1958                           MPI_REAL, MPI_SUM, comm2d, ierr )
1959       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1960       CALL MPI_ALLREDUCE( sums_l(nzb,31,0), sums(nzb,31), nzt+2-nzb, &
1961                           MPI_REAL, MPI_SUM, comm2d, ierr )
1962       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1963       CALL MPI_ALLREDUCE( sums_l(nzb,32,0), sums(nzb,32), nzt+2-nzb, &
1964                           MPI_REAL, MPI_SUM, comm2d, ierr )
1965
1966#else
1967       sums(:,8)  = sums_l(:,8,0)
1968       sums(:,30) = sums_l(:,30,0)
1969       sums(:,31) = sums_l(:,31,0)
1970       sums(:,32) = sums_l(:,32,0)
1971#endif
1972
1973!
1974!--    Final values are obtained by division by the total number of grid
1975!--    points used for the summation.
1976       hom(:,1,8,0)  = sums(:,8)  / ngp_2dh_outer(:,0)   ! e
1977       hom(:,1,30,0) = sums(:,30) / ngp_2dh_outer(:,0)   ! u*2
1978       hom(:,1,31,0) = sums(:,31) / ngp_2dh_outer(:,0)   ! v*2
1979       hom(:,1,32,0) = sums(:,32) / ngp_2dh_outer(:,0)   ! w*2
1980
1981    ENDIF
1982
1983 END SUBROUTINE lpm_init_sgs_tke
1984 
1985 
1986!------------------------------------------------------------------------------!
1987! Description:
1988! ------------
1989!> Sobroutine control lpm actions, i.e. all actions during one time step.
1990!------------------------------------------------------------------------------! 
1991 SUBROUTINE lpm_actions( location )
1992
1993    CHARACTER (LEN=*), INTENT(IN) ::  location !< call location string
1994
1995    INTEGER(iwp)       ::  i                  !<
1996    INTEGER(iwp)       ::  ie                 !<
1997    INTEGER(iwp)       ::  is                 !<
1998    INTEGER(iwp)       ::  j                  !<
1999    INTEGER(iwp)       ::  je                 !<
2000    INTEGER(iwp)       ::  js                 !<
2001    INTEGER(iwp), SAVE ::  lpm_count = 0      !<
2002    INTEGER(iwp)       ::  k                  !<
2003    INTEGER(iwp)       ::  ke                 !<
2004    INTEGER(iwp)       ::  ks                 !<
2005    INTEGER(iwp)       ::  m                  !<
2006    INTEGER(iwp), SAVE ::  steps = 0          !<
2007
2008    LOGICAL            ::  first_loop_stride  !<
2009
2010
2011    SELECT CASE ( location )
2012
2013       CASE ( 'after_pressure_solver' )
2014!
2015!--       The particle model is executed if particle advection start is reached and only at the end
2016!--       of the intermediate time step loop.
2017          IF ( time_since_reference_point >= particle_advection_start   &
2018               .AND.  intermediate_timestep_count == intermediate_timestep_count_max )             &
2019          THEN
2020             CALL cpu_log( log_point(25), 'lpm', 'start' )
2021!
2022!--          Write particle data at current time on file.
2023!--          This has to be done here, before particles are further processed,
2024!--          because they may be deleted within this timestep (in case that
2025!--          dt_write_particle_data = dt_prel = particle_maximum_age).
2026             time_write_particle_data = time_write_particle_data + dt_3d
2027             IF ( time_write_particle_data >= dt_write_particle_data )  THEN
2028
2029                CALL lpm_data_output_particles
2030!
2031!--          The MOD function allows for changes in the output interval with restart
2032!--          runs.
2033                time_write_particle_data = MOD( time_write_particle_data, &
2034                                           MAX( dt_write_particle_data, dt_3d ) )
2035             ENDIF
2036
2037!
2038!--          Initialize arrays for marking those particles to be deleted after the
2039!--          (sub-) timestep
2040             deleted_particles = 0
2041
2042!
2043!--          Initialize variables used for accumulating the number of particles
2044!--          xchanged between the subdomains during all sub-timesteps (if sgs
2045!--          velocities are included). These data are output further below on the
2046!--          particle statistics file.
2047             trlp_count_sum      = 0
2048             trlp_count_recv_sum = 0
2049             trrp_count_sum      = 0
2050             trrp_count_recv_sum = 0
2051             trsp_count_sum      = 0
2052             trsp_count_recv_sum = 0
2053             trnp_count_sum      = 0
2054             trnp_count_recv_sum = 0
2055!
2056!--          Calculate exponential term used in case of particle inertia for each
2057!--          of the particle groups
2058             DO  m = 1, number_of_particle_groups
2059                IF ( particle_groups(m)%density_ratio /= 0.0_wp )  THEN
2060                   particle_groups(m)%exp_arg  =                                        &
2061                             4.5_wp * particle_groups(m)%density_ratio *                &
2062                             molecular_viscosity / ( particle_groups(m)%radius )**2
2063
2064                   particle_groups(m)%exp_term = EXP( -particle_groups(m)%exp_arg *     &
2065                             dt_3d )
2066                ENDIF
2067             ENDDO
2068!
2069!--          If necessary, release new set of particles
2070             IF ( ( simulated_time - last_particle_release_time ) >= dt_prel  .AND.     &
2071                    end_time_prel > simulated_time )  THEN
2072                DO WHILE ( ( simulated_time - last_particle_release_time ) >= dt_prel )
2073                   CALL lpm_create_particle( PHASE_RELEASE )
2074                   last_particle_release_time = last_particle_release_time + dt_prel
2075                ENDDO
2076             ENDIF
2077!
2078!--          Reset summation arrays
2079             IF ( cloud_droplets )  THEN
2080                ql_c  = 0.0_wp
2081                ql_v  = 0.0_wp
2082                ql_vp = 0.0_wp
2083             ENDIF
2084
2085             first_loop_stride = .TRUE.
2086             grid_particles(:,:,:)%time_loop_done = .TRUE.
2087!
2088!--          Timestep loop for particle advection.
2089!--          This loop has to be repeated until the advection time of every particle
2090!--          (within the total domain!) has reached the LES timestep (dt_3d).
2091!--          In case of including the SGS velocities, the particle timestep may be
2092!--          smaller than the LES timestep (because of the Lagrangian timescale
2093!--          restriction) and particles may require to undergo several particle
2094!--          timesteps, before the LES timestep is reached. Because the number of these
2095!--          particle timesteps to be carried out is unknown at first, these steps are
2096!--          carried out in the following infinite loop with exit condition.
2097             DO
2098                CALL cpu_log( log_point_s(44), 'lpm_advec', 'start' )
2099                CALL cpu_log( log_point_s(44), 'lpm_advec', 'pause' )
2100
2101!
2102!--             If particle advection includes SGS velocity components, calculate the
2103!--             required SGS quantities (i.e. gradients of the TKE, as well as
2104!--             horizontally averaged profiles of the SGS TKE and the resolved-scale
2105!--             velocity variances)
2106                IF ( use_sgs_for_particles  .AND.  .NOT. cloud_droplets )  THEN
2107                   CALL lpm_init_sgs_tke
2108                ENDIF
2109!
2110!--             In case SGS-particle speed is considered, particles may carry out
2111!--             several particle timesteps. In order to prevent unnecessary
2112!--             treatment of particles that already reached the final time level,
2113!--             particles are sorted into contiguous blocks of finished and
2114!--             not-finished particles, in addition to their already sorting
2115!--             according to their sub-boxes.
2116                IF ( .NOT. first_loop_stride  .AND.  use_sgs_for_particles )            &
2117                   CALL lpm_sort_timeloop_done
2118                DO  i = nxl, nxr
2119                   DO  j = nys, nyn
2120                      DO  k = nzb+1, nzt
2121
2122                         number_of_particles = prt_count(k,j,i)
2123!
2124!--                      If grid cell gets empty, flag must be true
2125                         IF ( number_of_particles <= 0 )  THEN
2126                            grid_particles(k,j,i)%time_loop_done = .TRUE.
2127                            CYCLE
2128                         ENDIF
2129
2130                         IF ( .NOT. first_loop_stride  .AND.  &
2131                              grid_particles(k,j,i)%time_loop_done )  CYCLE
2132
2133                         particles => grid_particles(k,j,i)%particles(1:number_of_particles)
2134
2135                         particles(1:number_of_particles)%particle_mask = .TRUE.
2136!
2137!--                      Initialize the variable storing the total time that a particle
2138!--                      has advanced within the timestep procedure
2139                         IF ( first_loop_stride )  THEN
2140                            particles(1:number_of_particles)%dt_sum = 0.0_wp
2141                         ENDIF
2142!
2143!--                      Particle (droplet) growth by condensation/evaporation and
2144!--                      collision
2145                         IF ( cloud_droplets  .AND.  first_loop_stride)  THEN
2146!
2147!--                         Droplet growth by condensation / evaporation
2148                            CALL lpm_droplet_condensation(i,j,k)
2149!
2150!--                         Particle growth by collision
2151                            IF ( collision_kernel /= 'none' )  THEN
2152                               CALL lpm_droplet_collision(i,j,k)
2153                            ENDIF
2154
2155                         ENDIF
2156!
2157!--                      Initialize the switch used for the loop exit condition checked
2158!--                      at the end of this loop. If at least one particle has failed to
2159!--                      reach the LES timestep, this switch will be set false in
2160!--                      lpm_advec.
2161                         dt_3d_reached_l = .TRUE.
2162
2163!
2164!--                      Particle advection
2165                         CALL lpm_advec( i, j, k )
2166!
2167!--                      Particle reflection from walls. Only applied if the particles
2168!--                      are in the vertical range of the topography. (Here, some
2169!--                      optimization is still possible.)
2170                         IF ( topography /= 'flat'  .AND.  k < nzb_max + 2 )  THEN
2171                            CALL  lpm_boundary_conds( 'walls', i, j, k )
2172                         ENDIF
2173!
2174!--                      User-defined actions after the calculation of the new particle
2175!--                      position
2176                         CALL user_lpm_advec( i, j, k )
2177!
2178!--                      Apply boundary conditions to those particles that have crossed
2179!--                      the top or bottom boundary and delete those particles, which are
2180!--                      older than allowed
2181                         CALL lpm_boundary_conds( 'bottom/top', i, j, k )
2182!
2183!---                     If not all particles of the actual grid cell have reached the
2184!--                      LES timestep, this cell has to do another loop iteration. Due to
2185!--                      the fact that particles can move into neighboring grid cells,
2186!--                      these neighbor cells also have to perform another loop iteration.
2187!--                      Please note, this realization does not work properly if
2188!--                      particles move into another subdomain.
2189                         IF ( .NOT. dt_3d_reached_l )  THEN
2190                            ks = MAX(nzb+1,k-1)
2191                            ke = MIN(nzt,k+1)
2192                            js = MAX(nys,j-1)
2193                            je = MIN(nyn,j+1)
2194                            is = MAX(nxl,i-1)
2195                            ie = MIN(nxr,i+1)
2196                            grid_particles(ks:ke,js:je,is:ie)%time_loop_done = .FALSE.
2197                         ELSE
2198                            grid_particles(k,j,i)%time_loop_done = .TRUE.
2199                         ENDIF
2200
2201                      ENDDO
2202                   ENDDO
2203                ENDDO
2204                steps = steps + 1
2205                dt_3d_reached_l = ALL(grid_particles(:,:,:)%time_loop_done)
2206!
2207!--             Find out, if all particles on every PE have completed the LES timestep
2208!--             and set the switch corespondingly
2209#if defined( __parallel )
2210                IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
2211                CALL MPI_ALLREDUCE( dt_3d_reached_l, dt_3d_reached, 1, MPI_LOGICAL, &
2212                                    MPI_LAND, comm2d, ierr )
2213#else
2214                dt_3d_reached = dt_3d_reached_l
2215#endif
2216                CALL cpu_log( log_point_s(44), 'lpm_advec', 'stop' )
2217
2218!
2219!--             Apply splitting and merging algorithm
2220                IF ( cloud_droplets )  THEN
2221                   IF ( splitting )  THEN
2222                      CALL lpm_splitting
2223                   ENDIF
2224                   IF ( merging )  THEN
2225                      CALL lpm_merging
2226                   ENDIF
2227                ENDIF
2228!
2229!--             Move Particles local to PE to a different grid cell
2230                CALL lpm_move_particle
2231!
2232!--             Horizontal boundary conditions including exchange between subdmains
2233                CALL lpm_exchange_horiz
2234
2235!
2236!--             IF .FALSE., lpm_sort_and_delete is done inside pcmp
2237                IF ( .NOT. dt_3d_reached  .OR.  .NOT. nested_run )   THEN
2238!
2239!--                Pack particles (eliminate those marked for deletion),
2240!--                determine new number of particles
2241                   CALL lpm_sort_and_delete
2242
2243!--                Initialize variables for the next (sub-) timestep, i.e., for marking
2244!--                those particles to be deleted after the timestep
2245                   deleted_particles = 0
2246                ENDIF
2247
2248                IF ( dt_3d_reached )  EXIT
2249
2250                first_loop_stride = .FALSE.
2251             ENDDO   ! timestep loop
2252!
2253!--          in case of nested runs do the transfer of particles after every full model time step
2254             IF ( nested_run )   THEN
2255                CALL particles_from_parent_to_child
2256                CALL particles_from_child_to_parent
2257                CALL pmcp_p_delete_particles_in_fine_grid_area
2258
2259                CALL lpm_sort_and_delete
2260
2261                deleted_particles = 0
2262             ENDIF
2263
2264!
2265!--          Calculate the new liquid water content for each grid box
2266             IF ( cloud_droplets )  CALL lpm_calc_liquid_water_content
2267
2268!
2269!--          At the end all arrays are exchanged
2270             IF ( cloud_droplets )  THEN
2271                CALL exchange_horiz( ql, nbgp )
2272                CALL exchange_horiz( ql_c, nbgp )
2273                CALL exchange_horiz( ql_v, nbgp )
2274                CALL exchange_horiz( ql_vp, nbgp )
2275             ENDIF
2276
2277!
2278!--          Deallocate unused memory
2279             IF ( deallocate_memory  .AND.  lpm_count == step_dealloc )  THEN
2280                CALL dealloc_particles_array
2281                lpm_count = 0
2282             ELSEIF ( deallocate_memory )  THEN
2283                lpm_count = lpm_count + 1
2284             ENDIF
2285
2286!
2287!--          Write particle statistics (in particular the number of particles
2288!--          exchanged between the subdomains) on file
2289             IF ( write_particle_statistics )  CALL lpm_write_exchange_statistics
2290!
2291!--          Execute Interactions of condnesation and evaporation to humidity and
2292!--          temperature field
2293             IF ( cloud_droplets )  THEN
2294                CALL lpm_interaction_droplets_ptq
2295                CALL exchange_horiz( pt, nbgp )
2296                CALL exchange_horiz( q, nbgp )
2297             ENDIF
2298
2299             CALL cpu_log( log_point(25), 'lpm', 'stop' )
2300
2301! !
2302! !--       Output of particle time series
2303!           IF ( particle_advection )  THEN
2304!              IF ( time_dopts >= dt_dopts  .OR.                                                        &
2305!                   ( time_since_reference_point >= particle_advection_start  .AND.                     &
2306!                    first_call_lpm ) )  THEN
2307!                 CALL lpm_data_output_ptseries
2308!                 time_dopts = MOD( time_dopts, MAX( dt_dopts, dt_3d ) )
2309!              ENDIF
2310!           ENDIF
2311
2312!
2313!--           Set this switch to .false. @todo: maybe find better solution.
2314              first_call_lpm = .FALSE.
2315           ENDIF! ENDIF statement of lpm_actions('after_pressure_solver')
2316
2317       CASE ( 'after_integration' )
2318!
2319!--       Call at the end of timestep routine to save particle velocities fields
2320!--       for the next timestep
2321          CALL lpm_swap_timelevel_for_particle_advection
2322
2323       CASE DEFAULT
2324          CONTINUE
2325
2326    END SELECT
2327
2328 END SUBROUTINE lpm_actions
2329 
2330 
2331!------------------------------------------------------------------------------!
2332! Description:
2333! ------------
2334!
2335!------------------------------------------------------------------------------!
2336 SUBROUTINE particles_from_parent_to_child
2337    IMPLICIT NONE
2338
2339    CALL pmcp_c_get_particle_from_parent                         ! Child actions
2340    CALL pmcp_p_fill_particle_win                                ! Parent actions
2341
2342    RETURN
2343 END SUBROUTINE particles_from_parent_to_child
2344
2345 
2346!------------------------------------------------------------------------------!
2347! Description:
2348! ------------
2349!
2350!------------------------------------------------------------------------------!
2351 SUBROUTINE particles_from_child_to_parent
2352    IMPLICIT NONE
2353
2354    CALL pmcp_c_send_particle_to_parent                         ! Child actions
2355    CALL pmcp_p_empty_particle_win                              ! Parent actions
2356
2357    RETURN
2358 END SUBROUTINE particles_from_child_to_parent
2359 
2360!------------------------------------------------------------------------------!
2361! Description:
2362! ------------
2363!> This routine write exchange statistics of the lpm in a ascii file.
2364!------------------------------------------------------------------------------!
2365 SUBROUTINE lpm_write_exchange_statistics
2366
2367    INTEGER(iwp) ::  ip         !<
2368    INTEGER(iwp) ::  jp         !<
2369    INTEGER(iwp) ::  kp         !<
2370    INTEGER(iwp) ::  tot_number_of_particles !<
2371
2372!
2373!-- Determine the current number of particles
2374    number_of_particles         = 0
2375    DO  ip = nxl, nxr
2376       DO  jp = nys, nyn
2377          DO  kp = nzb+1, nzt
2378             number_of_particles = number_of_particles                         &
2379                                     + prt_count(kp,jp,ip)
2380          ENDDO
2381       ENDDO
2382    ENDDO
2383
2384    CALL check_open( 80 )
2385#if defined( __parallel )
2386    WRITE ( 80, 8000 )  current_timestep_number+1, simulated_time+dt_3d, &
2387                        number_of_particles, pleft, trlp_count_sum,      &
2388                        trlp_count_recv_sum, pright, trrp_count_sum,     &
2389                        trrp_count_recv_sum, psouth, trsp_count_sum,     &
2390                        trsp_count_recv_sum, pnorth, trnp_count_sum,     &
2391                        trnp_count_recv_sum
2392#else
2393    WRITE ( 80, 8000 )  current_timestep_number+1, simulated_time+dt_3d, &
2394                        number_of_particles
2395#endif
2396    CALL close_file( 80 )
2397
2398    IF ( number_of_particles > 0 )  THEN
2399        WRITE(9,*) 'number_of_particles ', number_of_particles,                &
2400                    current_timestep_number + 1, simulated_time + dt_3d
2401    ENDIF
2402
2403#if defined( __parallel )
2404    CALL MPI_ALLREDUCE( number_of_particles, tot_number_of_particles, 1,       &
2405                        MPI_INTEGER, MPI_SUM, comm2d, ierr )
2406#else
2407    tot_number_of_particles = number_of_particles
2408#endif
2409
2410    IF ( nested_run )  THEN
2411       CALL pmcp_g_print_number_of_particles( simulated_time+dt_3d,            &
2412                                              tot_number_of_particles)
2413    ENDIF
2414
2415!
2416!-- Formats
24178000 FORMAT (I6,1X,F7.2,4X,I10,5X,4(I3,1X,I4,'/',I4,2X),6X,I10)
2418
2419
2420 END SUBROUTINE lpm_write_exchange_statistics
2421 
2422
2423!------------------------------------------------------------------------------!
2424! Description:
2425! ------------
2426!> Write particle data in FORTRAN binary and/or netCDF format
2427!------------------------------------------------------------------------------!
2428 SUBROUTINE lpm_data_output_particles
2429 
2430    INTEGER(iwp) ::  ip !<
2431    INTEGER(iwp) ::  jp !<
2432    INTEGER(iwp) ::  kp !<
2433
2434    CALL cpu_log( log_point_s(40), 'lpm_data_output', 'start' )
2435
2436!
2437!-- Attention: change version number for unit 85 (in routine check_open)
2438!--            whenever the output format for this unit is changed!
2439    CALL check_open( 85 )
2440
2441    WRITE ( 85 )  simulated_time
2442    WRITE ( 85 )  prt_count
2443
2444    DO  ip = nxl, nxr
2445       DO  jp = nys, nyn
2446          DO  kp = nzb+1, nzt
2447             number_of_particles = prt_count(kp,jp,ip)
2448             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
2449             IF ( number_of_particles <= 0 )  CYCLE
2450             WRITE ( 85 )  particles
2451          ENDDO
2452       ENDDO
2453    ENDDO
2454
2455    CALL close_file( 85 )
2456
2457
2458#if defined( __netcdf )
2459! !
2460! !-- Output in netCDF format
2461!     CALL check_open( 108 )
2462!
2463! !
2464! !-- Update the NetCDF time axis
2465!     prt_time_count = prt_time_count + 1
2466!
2467!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_time_prt, &
2468!                             (/ simulated_time /),        &
2469!                             start = (/ prt_time_count /), count = (/ 1 /) )
2470!     CALL netcdf_handle_error( 'lpm_data_output_particles', 1 )
2471!
2472! !
2473! !-- Output the real number of particles used
2474!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_rnop_prt, &
2475!                             (/ number_of_particles /),   &
2476!                             start = (/ prt_time_count /), count = (/ 1 /) )
2477!     CALL netcdf_handle_error( 'lpm_data_output_particles', 2 )
2478!
2479! !
2480! !-- Output all particle attributes
2481!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(1), particles%age,      &
2482!                             start = (/ 1, prt_time_count /),               &
2483!                             count = (/ maximum_number_of_particles /) )
2484!     CALL netcdf_handle_error( 'lpm_data_output_particles', 3 )
2485!
2486!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(2), particles%user,     &
2487!                             start = (/ 1, prt_time_count /),               &
2488!                             count = (/ maximum_number_of_particles /) )
2489!     CALL netcdf_handle_error( 'lpm_data_output_particles', 4 )
2490!
2491!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(3), particles%origin_x, &
2492!                             start = (/ 1, prt_time_count /),               &
2493!                             count = (/ maximum_number_of_particles /) )
2494!     CALL netcdf_handle_error( 'lpm_data_output_particles', 5 )
2495!
2496!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(4), particles%origin_y, &
2497!                             start = (/ 1, prt_time_count /),               &
2498!                             count = (/ maximum_number_of_particles /) )
2499!     CALL netcdf_handle_error( 'lpm_data_output_particles', 6 )
2500!
2501!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(5), particles%origin_z, &
2502!                             start = (/ 1, prt_time_count /),               &
2503!                             count = (/ maximum_number_of_particles /) )
2504!     CALL netcdf_handle_error( 'lpm_data_output_particles', 7 )
2505!
2506!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(6), particles%radius,   &
2507!                             start = (/ 1, prt_time_count /),               &
2508!                             count = (/ maximum_number_of_particles /) )
2509!     CALL netcdf_handle_error( 'lpm_data_output_particles', 8 )
2510!
2511!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(7), particles%speed_x,  &
2512!                             start = (/ 1, prt_time_count /),               &
2513!                             count = (/ maximum_number_of_particles /) )
2514!     CALL netcdf_handle_error( 'lpm_data_output_particles', 9 )
2515!
2516!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(8), particles%speed_y,  &
2517!                             start = (/ 1, prt_time_count /),               &
2518!                             count = (/ maximum_number_of_particles /) )
2519!     CALL netcdf_handle_error( 'lpm_data_output_particles', 10 )
2520!
2521!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(9), particles%speed_z,  &
2522!                             start = (/ 1, prt_time_count /),               &
2523!                             count = (/ maximum_number_of_particles /) )
2524!     CALL netcdf_handle_error( 'lpm_data_output_particles', 11 )
2525!
2526!     nc_stat = NF90_PUT_VAR( id_set_prt,id_var_prt(10),                     &
2527!                             particles%weight_factor,                       &
2528!                             start = (/ 1, prt_time_count /),               &
2529!                             count = (/ maximum_number_of_particles /) )
2530!     CALL netcdf_handle_error( 'lpm_data_output_particles', 12 )
2531!
2532!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(11), particles%x,       &
2533!                             start = (/ 1, prt_time_count /),               &
2534!                             count = (/ maximum_number_of_particles /) )
2535!     CALL netcdf_handle_error( 'lpm_data_output_particles', 13 )
2536!
2537!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(12), particles%y,       &
2538!                             start = (/ 1, prt_time_count /),               &
2539!                             count = (/ maximum_number_of_particles /) )
2540!     CALL netcdf_handle_error( 'lpm_data_output_particles', 14 )
2541!
2542!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(13), particles%z,       &
2543!                             start = (/ 1, prt_time_count /),               &
2544!                             count = (/ maximum_number_of_particles /) )
2545!     CALL netcdf_handle_error( 'lpm_data_output_particles', 15 )
2546!
2547!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(14), particles%class,   &
2548!                             start = (/ 1, prt_time_count /),               &
2549!                             count = (/ maximum_number_of_particles /) )
2550!     CALL netcdf_handle_error( 'lpm_data_output_particles', 16 )
2551!
2552!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(15), particles%group,   &
2553!                             start = (/ 1, prt_time_count /),               &
2554!                             count = (/ maximum_number_of_particles /) )
2555!     CALL netcdf_handle_error( 'lpm_data_output_particles', 17 )
2556!
2557!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(16),                    &
2558!                             particles%id2,                                 &
2559!                             start = (/ 1, prt_time_count /),               &
2560!                             count = (/ maximum_number_of_particles /) )
2561!     CALL netcdf_handle_error( 'lpm_data_output_particles', 18 )
2562!
2563!     nc_stat = NF90_PUT_VAR( id_set_prt, id_var_prt(17), particles%id1,     &
2564!                             start = (/ 1, prt_time_count /),               &
2565!                             count = (/ maximum_number_of_particles /) )
2566!     CALL netcdf_handle_error( 'lpm_data_output_particles', 19 )
2567!
2568#endif
2569
2570    CALL cpu_log( log_point_s(40), 'lpm_data_output', 'stop' )
2571
2572 END SUBROUTINE lpm_data_output_particles
2573 
2574!------------------------------------------------------------------------------!
2575! Description:
2576! ------------
2577!> This routine calculates and provide particle timeseries output.
2578!------------------------------------------------------------------------------!
2579 SUBROUTINE lpm_data_output_ptseries
2580 
2581    INTEGER(iwp) ::  i    !<
2582    INTEGER(iwp) ::  inum !<
2583    INTEGER(iwp) ::  j    !<
2584    INTEGER(iwp) ::  jg   !<
2585    INTEGER(iwp) ::  k    !<
2586    INTEGER(iwp) ::  n    !<
2587
2588    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::  pts_value   !<
2589    REAL(wp), DIMENSION(:,:), ALLOCATABLE ::  pts_value_l !<
2590
2591
2592    CALL cpu_log( log_point(36), 'data_output_ptseries', 'start' )
2593
2594    IF ( myid == 0 )  THEN
2595!
2596!--    Open file for time series output in NetCDF format
2597       dopts_time_count = dopts_time_count + 1
2598       CALL check_open( 109 )
2599#if defined( __netcdf )
2600!
2601!--    Update the particle time series time axis
2602       nc_stat = NF90_PUT_VAR( id_set_pts, id_var_time_pts,      &
2603                               (/ time_since_reference_point /), &
2604                               start = (/ dopts_time_count /), count = (/ 1 /) )
2605       CALL netcdf_handle_error( 'data_output_ptseries', 391 )
2606#endif
2607
2608    ENDIF
2609
2610    ALLOCATE( pts_value(0:number_of_particle_groups,dopts_num), &
2611              pts_value_l(0:number_of_particle_groups,dopts_num) )
2612
2613    pts_value_l = 0.0_wp
2614    pts_value_l(:,16) = 9999999.9_wp    ! for calculation of minimum radius
2615
2616!
2617!-- Calculate or collect the particle time series quantities for all particles
2618!-- and seperately for each particle group (if there is more than one group)
2619    DO  i = nxl, nxr
2620       DO  j = nys, nyn
2621          DO  k = nzb, nzt
2622             number_of_particles = prt_count(k,j,i)
2623             IF (number_of_particles <= 0)  CYCLE
2624             particles => grid_particles(k,j,i)%particles(1:number_of_particles)
2625             DO  n = 1, number_of_particles
2626
2627                IF ( particles(n)%particle_mask )  THEN  ! Restrict analysis to active particles
2628
2629                   pts_value_l(0,1)  = pts_value_l(0,1) + 1.0_wp  ! total # of particles
2630                   pts_value_l(0,2)  = pts_value_l(0,2) +                      &
2631                          ( particles(n)%x - particles(n)%origin_x )  ! mean x
2632                   pts_value_l(0,3)  = pts_value_l(0,3) +                      &
2633                          ( particles(n)%y - particles(n)%origin_y )  ! mean y
2634                   pts_value_l(0,4)  = pts_value_l(0,4) +                      &
2635                          ( particles(n)%z - particles(n)%origin_z )  ! mean z
2636                   pts_value_l(0,5)  = pts_value_l(0,5) + particles(n)%z        ! mean z (absolute)
2637                   pts_value_l(0,6)  = pts_value_l(0,6) + particles(n)%speed_x  ! mean u
2638                   pts_value_l(0,7)  = pts_value_l(0,7) + particles(n)%speed_y  ! mean v
2639                   pts_value_l(0,8)  = pts_value_l(0,8) + particles(n)%speed_z  ! mean w
2640                   pts_value_l(0,9)  = pts_value_l(0,9)  + particles(n)%rvar1 ! mean sgsu
2641                   pts_value_l(0,10) = pts_value_l(0,10) + particles(n)%rvar2 ! mean sgsv
2642                   pts_value_l(0,11) = pts_value_l(0,11) + particles(n)%rvar3 ! mean sgsw
2643                   IF ( particles(n)%speed_z > 0.0_wp )  THEN
2644                      pts_value_l(0,12) = pts_value_l(0,12) + 1.0_wp  ! # of upward moving prts
2645                      pts_value_l(0,13) = pts_value_l(0,13) +                  &
2646                                              particles(n)%speed_z ! mean w upw.
2647                   ELSE
2648                      pts_value_l(0,14) = pts_value_l(0,14) +                  &
2649                                              particles(n)%speed_z ! mean w down
2650                   ENDIF
2651                   pts_value_l(0,15) = pts_value_l(0,15) + particles(n)%radius ! mean rad
2652                   pts_value_l(0,16) = MIN( pts_value_l(0,16), particles(n)%radius ) ! minrad
2653                   pts_value_l(0,17) = MAX( pts_value_l(0,17), particles(n)%radius ) ! maxrad
2654                   pts_value_l(0,18) = pts_value_l(0,18) + 1.0_wp
2655                   pts_value_l(0,19) = pts_value_l(0,18) + 1.0_wp
2656!
2657!--                Repeat the same for the respective particle group
2658                   IF ( number_of_particle_groups > 1 )  THEN
2659                      jg = particles(n)%group
2660
2661                      pts_value_l(jg,1)  = pts_value_l(jg,1) + 1.0_wp
2662                      pts_value_l(jg,2)  = pts_value_l(jg,2) +                   &
2663                           ( particles(n)%x - particles(n)%origin_x )
2664                      pts_value_l(jg,3)  = pts_value_l(jg,3) +                   &
2665                           ( particles(n)%y - particles(n)%origin_y )
2666                      pts_value_l(jg,4)  = pts_value_l(jg,4) +                   &
2667                           ( particles(n)%z - particles(n)%origin_z )
2668                      pts_value_l(jg,5)  = pts_value_l(jg,5) + particles(n)%z
2669                      pts_value_l(jg,6)  = pts_value_l(jg,6) + particles(n)%speed_x
2670                      pts_value_l(jg,7)  = pts_value_l(jg,7) + particles(n)%speed_y
2671                      pts_value_l(jg,8)  = pts_value_l(jg,8) + particles(n)%speed_z
2672                      pts_value_l(jg,9)  = pts_value_l(jg,9)  + particles(n)%rvar1
2673                      pts_value_l(jg,10) = pts_value_l(jg,10) + particles(n)%rvar2
2674                      pts_value_l(jg,11) = pts_value_l(jg,11) + particles(n)%rvar3
2675                      IF ( particles(n)%speed_z > 0.0_wp )  THEN
2676                         pts_value_l(jg,12) = pts_value_l(jg,12) + 1.0_wp
2677                         pts_value_l(jg,13) = pts_value_l(jg,13) + particles(n)%speed_z
2678                      ELSE
2679                         pts_value_l(jg,14) = pts_value_l(jg,14) + particles(n)%speed_z
2680                      ENDIF
2681                      pts_value_l(jg,15) = pts_value_l(jg,15) + particles(n)%radius
2682                      pts_value_l(jg,16) = MIN( pts_value_l(jg,16), particles(n)%radius )
2683                      pts_value_l(jg,17) = MAX( pts_value_l(jg,17), particles(n)%radius )
2684                      pts_value_l(jg,18) = pts_value_l(jg,18) + 1.0_wp
2685                      pts_value_l(jg,19) = pts_value_l(jg,19) + 1.0_wp
2686                   ENDIF
2687
2688                ENDIF
2689
2690             ENDDO
2691
2692          ENDDO
2693       ENDDO
2694    ENDDO
2695
2696
2697#if defined( __parallel )
2698!
2699!-- Sum values of the subdomains
2700    inum = number_of_particle_groups + 1
2701
2702    IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
2703    CALL MPI_ALLREDUCE( pts_value_l(0,1), pts_value(0,1), 15*inum, MPI_REAL, &
2704                        MPI_SUM, comm2d, ierr )
2705    IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
2706    CALL MPI_ALLREDUCE( pts_value_l(0,16), pts_value(0,16), inum, MPI_REAL, &
2707                        MPI_MIN, comm2d, ierr )
2708    IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
2709    CALL MPI_ALLREDUCE( pts_value_l(0,17), pts_value(0,17), inum, MPI_REAL, &
2710                        MPI_MAX, comm2d, ierr )
2711    IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
2712    CALL MPI_ALLREDUCE( pts_value_l(0,18), pts_value(0,18), inum, MPI_REAL, &
2713                        MPI_MAX, comm2d, ierr )
2714    IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
2715    CALL MPI_ALLREDUCE( pts_value_l(0,19), pts_value(0,19), inum, MPI_REAL, &
2716                        MPI_MIN, comm2d, ierr )
2717#else
2718    pts_value(:,1:19) = pts_value_l(:,1:19)
2719#endif
2720
2721!
2722!-- Normalize the above calculated quantities (except min/max values) with the
2723!-- total number of particles
2724    IF ( number_of_particle_groups > 1 )  THEN
2725       inum = number_of_particle_groups
2726    ELSE
2727       inum = 0
2728    ENDIF
2729
2730    DO  j = 0, inum
2731
2732       IF ( pts_value(j,1) > 0.0_wp )  THEN
2733
2734          pts_value(j,2:15) = pts_value(j,2:15) / pts_value(j,1)
2735          IF ( pts_value(j,12) > 0.0_wp  .AND.  pts_value(j,12) < 1.0_wp )  THEN
2736             pts_value(j,13) = pts_value(j,13) / pts_value(j,12)
2737             pts_value(j,14) = pts_value(j,14) / ( 1.0_wp - pts_value(j,12) )
2738          ELSEIF ( pts_value(j,12) == 0.0_wp )  THEN
2739             pts_value(j,13) = -1.0_wp
2740          ELSE
2741             pts_value(j,14) = -1.0_wp
2742          ENDIF
2743
2744       ENDIF
2745
2746    ENDDO
2747
2748!
2749!-- Calculate higher order moments of particle time series quantities,
2750!-- seperately for each particle group (if there is more than one group)
2751    DO  i = nxl, nxr
2752       DO  j = nys, nyn
2753          DO  k = nzb, nzt
2754             number_of_particles = prt_count(k,j,i)
2755             IF (number_of_particles <= 0)  CYCLE
2756             particles => grid_particles(k,j,i)%particles(1:number_of_particles)
2757             DO  n = 1, number_of_particles
2758
2759                pts_value_l(0,20) = pts_value_l(0,20) + ( particles(n)%x - &
2760                                    particles(n)%origin_x - pts_value(0,2) )**2 ! x*2
2761                pts_value_l(0,21) = pts_value_l(0,21) + ( particles(n)%y - &
2762                                    particles(n)%origin_y - pts_value(0,3) )**2 ! y*2
2763                pts_value_l(0,22) = pts_value_l(0,22) + ( particles(n)%z - &
2764                                    particles(n)%origin_z - pts_value(0,4) )**2 ! z*2
2765                pts_value_l(0,23) = pts_value_l(0,23) + ( particles(n)%speed_x - &
2766                                                         pts_value(0,6) )**2   ! u*2
2767                pts_value_l(0,24) = pts_value_l(0,24) + ( particles(n)%speed_y - &
2768                                                          pts_value(0,7) )**2   ! v*2
2769                pts_value_l(0,25) = pts_value_l(0,25) + ( particles(n)%speed_z - &
2770                                                          pts_value(0,8) )**2   ! w*2
2771                pts_value_l(0,26) = pts_value_l(0,26) + ( particles(n)%rvar1 - &
2772                                                          pts_value(0,9) )**2   ! u"2
2773                pts_value_l(0,27) = pts_value_l(0,27) + ( particles(n)%rvar2 - &
2774                                                          pts_value(0,10) )**2  ! v"2
2775                pts_value_l(0,28) = pts_value_l(0,28) + ( particles(n)%rvar3 - &
2776                                                          pts_value(0,11) )**2  ! w"2
2777!
2778!--             Repeat the same for the respective particle group
2779                IF ( number_of_particle_groups > 1 )  THEN
2780                   jg = particles(n)%group
2781
2782                   pts_value_l(jg,20) = pts_value_l(jg,20) + ( particles(n)%x - &
2783                                       particles(n)%origin_x - pts_value(jg,2) )**2
2784                   pts_value_l(jg,21) = pts_value_l(jg,21) + ( particles(n)%y - &
2785                                       particles(n)%origin_y - pts_value(jg,3) )**2
2786                   pts_value_l(jg,22) = pts_value_l(jg,22) + ( particles(n)%z - &
2787                                       particles(n)%origin_z - pts_value(jg,4) )**2
2788                   pts_value_l(jg,23) = pts_value_l(jg,23) + ( particles(n)%speed_x - &
2789                                                             pts_value(jg,6) )**2
2790                   pts_value_l(jg,24) = pts_value_l(jg,24) + ( particles(n)%speed_y - &
2791                                                             pts_value(jg,7) )**2
2792                   pts_value_l(jg,25) = pts_value_l(jg,25) + ( particles(n)%speed_z - &
2793                                                             pts_value(jg,8) )**2
2794                   pts_value_l(jg,26) = pts_value_l(jg,26) + ( particles(n)%rvar1 - &
2795                                                             pts_value(jg,9) )**2
2796                   pts_value_l(jg,27) = pts_value_l(jg,27) + ( particles(n)%rvar2 - &
2797                                                             pts_value(jg,10) )**2
2798                   pts_value_l(jg,28) = pts_value_l(jg,28) + ( particles(n)%rvar3 - &
2799                                                             pts_value(jg,11) )**2
2800                ENDIF
2801
2802             ENDDO
2803          ENDDO
2804       ENDDO
2805    ENDDO
2806
2807    pts_value_l(0,29) = ( number_of_particles - pts_value(0,1) / numprocs )**2
2808                                                 ! variance of particle numbers
2809    IF ( number_of_particle_groups > 1 )  THEN
2810       DO  j = 1, number_of_particle_groups
2811          pts_value_l(j,29) = ( pts_value_l(j,1) - &
2812                                pts_value(j,1) / numprocs )**2
2813       ENDDO
2814    ENDIF
2815
2816#if defined( __parallel )
2817!
2818!-- Sum values of the subdomains
2819    inum = number_of_particle_groups + 1
2820
2821    IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
2822    CALL MPI_ALLREDUCE( pts_value_l(0,20), pts_value(0,20), inum*10, MPI_REAL, &
2823                        MPI_SUM, comm2d, ierr )
2824#else
2825    pts_value(:,20:29) = pts_value_l(:,20:29)
2826#endif
2827
2828!
2829!-- Normalize the above calculated quantities with the total number of
2830!-- particles
2831    IF ( number_of_particle_groups > 1 )  THEN
2832       inum = number_of_particle_groups
2833    ELSE
2834       inum = 0
2835    ENDIF
2836
2837    DO  j = 0, inum
2838
2839       IF ( pts_value(j,1) > 0.0_wp )  THEN
2840          pts_value(j,20:28) = pts_value(j,20:28) / pts_value(j,1)
2841       ENDIF
2842       pts_value(j,29) = pts_value(j,29) / numprocs
2843
2844    ENDDO
2845
2846#if defined( __netcdf )
2847!
2848!-- Output particle time series quantities in NetCDF format
2849    IF ( myid == 0 )  THEN
2850       DO  j = 0, inum
2851          DO  i = 1, dopts_num
2852             nc_stat = NF90_PUT_VAR( id_set_pts, id_var_dopts(i,j),  &
2853                                     (/ pts_value(j,i) /),           &
2854                                     start = (/ dopts_time_count /), &
2855                                     count = (/ 1 /) )
2856             CALL netcdf_handle_error( 'data_output_ptseries', 392 )
2857          ENDDO
2858       ENDDO
2859    ENDIF
2860#endif
2861
2862    DEALLOCATE( pts_value, pts_value_l )
2863
2864    CALL cpu_log( log_point(36), 'data_output_ptseries', 'stop' )
2865
2866END SUBROUTINE lpm_data_output_ptseries
2867
2868 
2869!------------------------------------------------------------------------------!
2870! Description:
2871! ------------
2872!> This routine reads the respective restart data for the lpm.
2873!------------------------------------------------------------------------------!
2874 SUBROUTINE lpm_rrd_local_particles
2875
2876    CHARACTER (LEN=10) ::  particle_binary_version    !<
2877    CHARACTER (LEN=10) ::  version_on_file            !<
2878
2879    INTEGER(iwp) ::  alloc_size !<
2880    INTEGER(iwp) ::  ip         !<
2881    INTEGER(iwp) ::  jp         !<
2882    INTEGER(iwp) ::  kp         !<
2883
2884    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  tmp_particles !<
2885
2886!
2887!-- Read particle data from previous model run.
2888!-- First open the input unit.
2889    IF ( myid_char == '' )  THEN
2890       OPEN ( 90, FILE='PARTICLE_RESTART_DATA_IN'//myid_char,                  &
2891                  FORM='UNFORMATTED' )
2892    ELSE
2893       OPEN ( 90, FILE='PARTICLE_RESTART_DATA_IN/'//myid_char,                 &
2894                  FORM='UNFORMATTED' )
2895    ENDIF
2896
2897!
2898!-- First compare the version numbers
2899    READ ( 90 )  version_on_file
2900    particle_binary_version = '4.0'
2901    IF ( TRIM( version_on_file ) /= TRIM( particle_binary_version ) )  THEN
2902       message_string = 'version mismatch concerning data from prior ' //      &
2903                        'run &version on file = "' //                          &
2904                                      TRIM( version_on_file ) //               &
2905                        '&version in program = "' //                           &
2906                                      TRIM( particle_binary_version ) // '"'
2907       CALL message( 'lpm_read_restart_file', 'PA0214', 1, 2, 0, 6, 0 )
2908    ENDIF
2909
2910!
2911!-- If less particles are stored on the restart file than prescribed by
2912!-- 1, the remainder is initialized by zero_particle to avoid
2913!-- errors.
2914    zero_particle = particle_type( 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,     &
2915                                   0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,     &
2916                                   0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,     &
2917                                   0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp,     &
2918                                   0, 0, 0_idp, .FALSE., -1 )
2919!
2920!-- Read some particle parameters and the size of the particle arrays,
2921!-- allocate them and read their contents.
2922    READ ( 90 )  bc_par_b, bc_par_lr, bc_par_ns, bc_par_t,                     &
2923                 last_particle_release_time, number_of_particle_groups,        &
2924                 particle_groups, time_write_particle_data
2925
2926    ALLOCATE( prt_count(nzb:nzt+1,nysg:nyng,nxlg:nxrg),                        &
2927              grid_particles(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
2928
2929    READ ( 90 )  prt_count
2930
2931    DO  ip = nxl, nxr
2932       DO  jp = nys, nyn
2933          DO  kp = nzb+1, nzt
2934
2935             number_of_particles = prt_count(kp,jp,ip)
2936             IF ( number_of_particles > 0 )  THEN
2937                alloc_size = MAX( INT( number_of_particles *                   &
2938                             ( 1.0_wp + alloc_factor / 100.0_wp ) ),           &
2939                             1 )
2940             ELSE
2941                alloc_size = 1
2942             ENDIF
2943
2944             ALLOCATE( grid_particles(kp,jp,ip)%particles(1:alloc_size) )
2945
2946             IF ( number_of_particles > 0 )  THEN
2947                ALLOCATE( tmp_particles(1:number_of_particles) )
2948                READ ( 90 )  tmp_particles
2949                grid_particles(kp,jp,ip)%particles(1:number_of_particles) = tmp_particles
2950                DEALLOCATE( tmp_particles )
2951                IF ( number_of_particles < alloc_size )  THEN
2952                   grid_particles(kp,jp,ip)%particles(number_of_particles+1:alloc_size) &
2953                      = zero_particle
2954                ENDIF
2955             ELSE
2956                grid_particles(kp,jp,ip)%particles(1:alloc_size) = zero_particle
2957             ENDIF
2958
2959          ENDDO
2960       ENDDO
2961    ENDDO
2962
2963    CLOSE ( 90 )
2964!
2965!-- Must be called to sort particles into blocks, which is needed for a fast
2966!-- interpolation of the LES fields on the particle position.
2967    CALL lpm_sort_and_delete
2968
2969
2970 END SUBROUTINE lpm_rrd_local_particles
2971 
2972 
2973 SUBROUTINE lpm_rrd_local( k, nxlf, nxlc, nxl_on_file, nxrf, nxrc,          &
2974                              nxr_on_file, nynf, nync, nyn_on_file, nysf,  &
2975                              nysc, nys_on_file, tmp_3d, found )
2976
2977
2978   USE control_parameters,                                                 &
2979       ONLY: length, restart_string
2980
2981    INTEGER(iwp) ::  k               !<
2982    INTEGER(iwp) ::  nxlc            !<
2983    INTEGER(iwp) ::  nxlf            !<
2984    INTEGER(iwp) ::  nxl_on_file     !<
2985    INTEGER(iwp) ::  nxrc            !<
2986    INTEGER(iwp) ::  nxrf            !<
2987    INTEGER(iwp) ::  nxr_on_file     !<
2988    INTEGER(iwp) ::  nync            !<
2989    INTEGER(iwp) ::  nynf            !<
2990    INTEGER(iwp) ::  nyn_on_file     !<
2991    INTEGER(iwp) ::  nysc            !<
2992    INTEGER(iwp) ::  nysf            !<
2993    INTEGER(iwp) ::  nys_on_file     !<
2994
2995    LOGICAL, INTENT(OUT)  ::  found
2996
2997    REAL(wp), DIMENSION(nzb:nzt+1,nys_on_file-nbgp:nyn_on_file+nbgp,nxl_on_file-nbgp:nxr_on_file+nbgp) ::  tmp_3d   !<
2998
2999
3000    found = .TRUE.
3001
3002    SELECT CASE ( restart_string(1:length) )
3003
3004       CASE ( 'iran' ) ! matching random numbers is still unresolved issue
3005          IF ( k == 1 )  READ ( 13 )  iran, iran_part
3006
3007        CASE ( 'pc_av' )
3008           IF ( .NOT. ALLOCATED( pc_av ) )  THEN
3009              ALLOCATE( pc_av(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
3010           ENDIF
3011           IF ( k == 1 )  READ ( 13 )  tmp_3d
3012           pc_av(:,nysc-nbgp:nync+nbgp,nxlc-nbgp:nxrc+nbgp) =          &
3013              tmp_3d(:,nysf-nbgp:nynf+nbgp,nxlf-nbgp:nxrf+nbgp)
3014
3015        CASE ( 'pr_av' )
3016           IF ( .NOT. ALLOCATED( pr_av ) )  THEN
3017              ALLOCATE( pr_av(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
3018           ENDIF
3019           IF ( k == 1 )  READ ( 13 )  tmp_3d
3020           pr_av(:,nysc-nbgp:nync+nbgp,nxlc-nbgp:nxrc+nbgp) =          &
3021              tmp_3d(:,nysf-nbgp:nynf+nbgp,nxlf-nbgp:nxrf+nbgp)
3022 
3023         CASE ( 'ql_c_av' )
3024            IF ( .NOT. ALLOCATED( ql_c_av ) )  THEN
3025               ALLOCATE( ql_c_av(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
3026            ENDIF
3027            IF ( k == 1 )  READ ( 13 )  tmp_3d
3028            ql_c_av(:,nysc-nbgp:nync+nbgp,nxlc-nbgp:nxrc+nbgp) =        &
3029               tmp_3d(:,nysf-nbgp:nynf+nbgp,nxlf-nbgp:nxrf+nbgp)
3030
3031         CASE ( 'ql_v_av' )
3032            IF ( .NOT. ALLOCATED( ql_v_av ) )  THEN
3033               ALLOCATE( ql_v_av(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
3034            ENDIF
3035            IF ( k == 1 )  READ ( 13 )  tmp_3d
3036            ql_v_av(:,nysc-nbgp:nync+nbgp,nxlc-nbgp:nxrc+nbgp) =        &
3037               tmp_3d(:,nysf-nbgp:nynf+nbgp,nxlf-nbgp:nxrf+nbgp)
3038
3039         CASE ( 'ql_vp_av' )
3040            IF ( .NOT. ALLOCATED( ql_vp_av ) )  THEN
3041               ALLOCATE( ql_vp_av(nzb:nzt+1,nysg:nyng,nxlg:nxrg) )
3042            ENDIF
3043            IF ( k == 1 )  READ ( 13 )  tmp_3d
3044            ql_vp_av(:,nysc-nbgp:nync+nbgp,nxlc-nbgp:nxrc+nbgp) =       &
3045               tmp_3d(:,nysf-nbgp:nynf+nbgp,nxlf-nbgp:nxrf+nbgp)
3046
3047          CASE DEFAULT
3048
3049             found = .FALSE.
3050
3051       END SELECT
3052
3053
3054 END SUBROUTINE lpm_rrd_local
3055 
3056!------------------------------------------------------------------------------!
3057! Description:
3058! ------------
3059!> This routine writes the respective restart data for the lpm.
3060!------------------------------------------------------------------------------!
3061 SUBROUTINE lpm_wrd_local
3062 
3063    CHARACTER (LEN=10) ::  particle_binary_version   !<
3064
3065    INTEGER(iwp) ::  ip                              !<
3066    INTEGER(iwp) ::  jp                              !<
3067    INTEGER(iwp) ::  kp                              !<
3068!
3069!-- First open the output unit.
3070    IF ( myid_char == '' )  THEN
3071       OPEN ( 90, FILE='PARTICLE_RESTART_DATA_OUT'//myid_char, &
3072                  FORM='UNFORMATTED')
3073    ELSE
3074       IF ( myid == 0 )  CALL local_system( 'mkdir PARTICLE_RESTART_DATA_OUT' )
3075#if defined( __parallel )
3076!
3077!--    Set a barrier in order to allow that thereafter all other processors
3078!--    in the directory created by PE0 can open their file
3079       CALL MPI_BARRIER( comm2d, ierr )
3080#endif
3081       OPEN ( 90, FILE='PARTICLE_RESTART_DATA_OUT/'//myid_char, &
3082                  FORM='UNFORMATTED' )
3083    ENDIF
3084
3085!
3086!-- Write the version number of the binary format.
3087!-- Attention: After changes to the following output commands the version
3088!-- ---------  number of the variable particle_binary_version must be
3089!--            changed! Also, the version number and the list of arrays
3090!--            to be read in lpm_read_restart_file must be adjusted
3091!--            accordingly.
3092    particle_binary_version = '4.0'
3093    WRITE ( 90 )  particle_binary_version
3094
3095!
3096!-- Write some particle parameters, the size of the particle arrays
3097    WRITE ( 90 )  bc_par_b, bc_par_lr, bc_par_ns, bc_par_t,                    &
3098                  last_particle_release_time, number_of_particle_groups,       &
3099                  particle_groups, time_write_particle_data
3100
3101    WRITE ( 90 )  prt_count
3102         
3103    DO  ip = nxl, nxr
3104       DO  jp = nys, nyn
3105          DO  kp = nzb+1, nzt
3106             number_of_particles = prt_count(kp,jp,ip)
3107             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
3108             IF ( number_of_particles <= 0 )  CYCLE
3109             WRITE ( 90 )  particles
3110          ENDDO
3111       ENDDO
3112    ENDDO
3113
3114    CLOSE ( 90 )
3115
3116#if defined( __parallel )
3117       CALL MPI_BARRIER( comm2d, ierr )
3118#endif
3119
3120    CALL wrd_write_string( 'iran' ) 
3121    WRITE ( 14 )  iran, iran_part 
3122
3123
3124 END SUBROUTINE lpm_wrd_local
3125
3126
3127!------------------------------------------------------------------------------!
3128! Description:
3129! ------------
3130!> This routine writes the respective restart data for the lpm.
3131!------------------------------------------------------------------------------!
3132 SUBROUTINE lpm_wrd_global
3133 
3134    CALL wrd_write_string( 'curvature_solution_effects' ) 
3135    WRITE ( 14 )  curvature_solution_effects
3136
3137    CALL wrd_write_string( 'interpolation_simple_corrector' )
3138    WRITE ( 14 )  interpolation_simple_corrector
3139
3140    CALL wrd_write_string( 'interpolation_simple_predictor' )
3141    WRITE ( 14 )  interpolation_simple_predictor
3142
3143    CALL wrd_write_string( 'interpolation_trilinear' )
3144    WRITE ( 14 )  interpolation_trilinear
3145
3146 END SUBROUTINE lpm_wrd_global
3147 
3148
3149!------------------------------------------------------------------------------!
3150! Description:
3151! ------------
3152!> This routine writes the respective restart data for the lpm.
3153!------------------------------------------------------------------------------!
3154 SUBROUTINE lpm_rrd_global( found )
3155 
3156    USE control_parameters,                            &
3157        ONLY: length, restart_string
3158
3159    LOGICAL, INTENT(OUT)  ::  found
3160
3161    found = .TRUE.
3162
3163    SELECT CASE ( restart_string(1:length) )
3164
3165       CASE ( 'curvature_solution_effects' )
3166          READ ( 13 )  curvature_solution_effects
3167
3168       CASE ( 'interpolation_simple_corrector' )
3169          READ ( 13 )  interpolation_simple_corrector
3170
3171       CASE ( 'interpolation_simple_predictor' )
3172          READ ( 13 )  interpolation_simple_predictor
3173
3174       CASE ( 'interpolation_trilinear' )
3175          READ ( 13 )  interpolation_trilinear
3176
3177!          CASE ( 'global_paramter' )
3178!             READ ( 13 )  global_parameter
3179!          CASE ( 'global_array' )
3180!             IF ( .NOT. ALLOCATED( global_array ) )  ALLOCATE( global_array(1:10) )
3181!             READ ( 13 )  global_array
3182
3183       CASE DEFAULT
3184
3185          found = .FALSE.
3186
3187    END SELECT
3188   
3189 END SUBROUTINE lpm_rrd_global
3190
3191
3192!------------------------------------------------------------------------------!
3193! Description:
3194! ------------
3195!> This is a submodule of the lagrangian particle model. It contains all
3196!> dynamic processes of the lpm. This includes the advection (resolved and sub-
3197!> grid scale) as well as the boundary conditions of particles. As a next step
3198!> this submodule should be excluded as an own file.
3199!------------------------------------------------------------------------------!
3200 SUBROUTINE lpm_advec (ip,jp,kp)
3201
3202    LOGICAL ::  subbox_at_wall !< flag to see if the current subgridbox is adjacent to a wall
3203
3204    INTEGER(iwp) ::  i                           !< index variable along x
3205    INTEGER(iwp) ::  i_next                      !< index variable along x
3206    INTEGER(iwp) ::  ip                          !< index variable along x
3207    INTEGER(iwp) ::  iteration_steps = 1         !< amount of iterations steps for corrector step
3208    INTEGER(iwp) ::  j                           !< index variable along y
3209    INTEGER(iwp) ::  j_next                      !< index variable along y
3210    INTEGER(iwp) ::  jp                          !< index variable along y
3211    INTEGER(iwp) ::  k                           !< index variable along z
3212    INTEGER(iwp) ::  k_wall                      !< vertical index of topography top
3213    INTEGER(iwp) ::  kp                          !< index variable along z
3214    INTEGER(iwp) ::  k_next                      !< index variable along z
3215    INTEGER(iwp) ::  kw                          !< index variable along z
3216    INTEGER(iwp) ::  kkw                         !< index variable along z
3217    INTEGER(iwp) ::  n                           !< loop variable over all particles in a grid box
3218    INTEGER(iwp) ::  nb                          !< block number particles are sorted in
3219    INTEGER(iwp) ::  particle_end                !< end index for partilce loop
3220    INTEGER(iwp) ::  particle_start              !< start index for particle loop
3221    INTEGER(iwp) ::  surf_start                  !< Index on surface data-type for current grid box
3222    INTEGER(iwp) ::  subbox_end                  !< end index for loop over subboxes in particle advection
3223    INTEGER(iwp) ::  subbox_start                !< start index for loop over subboxes in particle advection
3224    INTEGER(iwp) ::  nn                          !< loop variable over iterations steps
3225
3226    INTEGER(iwp), DIMENSION(0:7) ::  start_index !< start particle index for current block
3227    INTEGER(iwp), DIMENSION(0:7) ::  end_index   !< start particle index for current block
3228
3229    REAL(wp) ::  aa                 !< dummy argument for horizontal particle interpolation
3230    REAL(wp) ::  alpha              !< interpolation facor for x-direction
3231
3232    REAL(wp) ::  bb                 !< dummy argument for horizontal particle interpolation
3233    REAL(wp) ::  beta               !< interpolation facor for y-direction
3234    REAL(wp) ::  cc                 !< dummy argument for horizontal particle interpolation
3235    REAL(wp) ::  d_z_p_z0           !< inverse of interpolation length for logarithmic interpolation
3236    REAL(wp) ::  dd                 !< dummy argument for horizontal particle interpolation
3237    REAL(wp) ::  de_dx_int_l        !< x/y-interpolated TKE gradient (x) at particle position at lower vertical level
3238    REAL(wp) ::  de_dx_int_u        !< x/y-interpolated TKE gradient (x) at particle position at upper vertical level
3239    REAL(wp) ::  de_dy_int_l        !< x/y-interpolated TKE gradient (y) at particle position at lower vertical level
3240    REAL(wp) ::  de_dy_int_u        !< x/y-interpolated TKE gradient (y) at particle position at upper vertical level
3241    REAL(wp) ::  de_dt              !< temporal derivative of TKE experienced by the particle
3242    REAL(wp) ::  de_dt_min          !< lower level for temporal TKE derivative
3243    REAL(wp) ::  de_dz_int_l        !< x/y-interpolated TKE gradient (z) at particle position at lower vertical level
3244    REAL(wp) ::  de_dz_int_u        !< x/y-interpolated TKE gradient (z) at particle position at upper vertical level
3245    REAL(wp) ::  diameter           !< diamter of droplet
3246    REAL(wp) ::  diss_int_l         !< x/y-interpolated dissipation at particle position at lower vertical level
3247    REAL(wp) ::  diss_int_u         !< x/y-interpolated dissipation at particle position at upper vertical level
3248    REAL(wp) ::  dt_particle_m      !< previous particle time step
3249    REAL(wp) ::  dz_temp            !< dummy for the vertical grid spacing
3250    REAL(wp) ::  e_int_l            !< x/y-interpolated TKE at particle position at lower vertical level
3251    REAL(wp) ::  e_int_u            !< x/y-interpolated TKE at particle position at upper vertical level
3252    REAL(wp) ::  e_mean_int         !< horizontal mean TKE at particle height
3253    REAL(wp) ::  exp_arg            !< argument in the exponent - particle radius
3254    REAL(wp) ::  exp_term           !< exponent term
3255    REAL(wp) ::  gamma              !< interpolation facor for z-direction
3256    REAL(wp) ::  gg                 !< dummy argument for horizontal particle interpolation
3257    REAL(wp) ::  height_p           !< dummy argument for logarithmic interpolation
3258    REAL(wp) ::  log_z_z0_int       !< logarithmus used for surface_layer interpolation
3259    REAL(wp) ::  random_gauss       !< Gaussian-distributed random number used for SGS particle advection
3260    REAL(wp) ::  RL                 !< Lagrangian autocorrelation coefficient
3261    REAL(wp) ::  rg1                !< Gaussian distributed random number
3262    REAL(wp) ::  rg2                !< Gaussian distributed random number
3263    REAL(wp) ::  rg3                !< Gaussian distributed random number
3264    REAL(wp) ::  sigma              !< velocity standard deviation
3265    REAL(wp) ::  u_int_l            !< x/y-interpolated u-component at particle position at lower vertical level
3266    REAL(wp) ::  u_int_u            !< x/y-interpolated u-component at particle position at upper vertical level
3267    REAL(wp) ::  unext              !< calculated particle u-velocity of corrector step
3268    REAL(wp) ::  us_int             !< friction velocity at particle grid box
3269    REAL(wp) ::  usws_int           !< surface momentum flux (u component) at particle grid box
3270    REAL(wp) ::  v_int_l            !< x/y-interpolated v-component at particle position at lower vertical level
3271    REAL(wp) ::  v_int_u            !< x/y-interpolated v-component at particle position at upper vertical level
3272    REAL(wp) ::  vsws_int           !< surface momentum flux (u component) at particle grid box
3273    REAL(wp) ::  vnext              !< calculated particle v-velocity of corrector step
3274    REAL(wp) ::  vv_int             !< dummy to compute interpolated mean SGS TKE, used to scale SGS advection
3275    REAL(wp) ::  w_int_l            !< x/y-interpolated w-component at particle position at lower vertical level
3276    REAL(wp) ::  w_int_u            !< x/y-interpolated w-component at particle position at upper vertical level
3277    REAL(wp) ::  wnext              !< calculated particle w-velocity of corrector step
3278    REAL(wp) ::  w_s                !< terminal velocity of droplets
3279    REAL(wp) ::  x                  !< dummy argument for horizontal particle interpolation
3280    REAL(wp) ::  xp                 !< calculated particle position in x of predictor step
3281    REAL(wp) ::  y                  !< dummy argument for horizontal particle interpolation
3282    REAL(wp) ::  yp                 !< calculated particle position in y of predictor step
3283    REAL(wp) ::  z_p                !< surface layer height (0.5 dz)
3284    REAL(wp) ::  zp                 !< calculated particle position in z of predictor step
3285
3286    REAL(wp), PARAMETER ::  a_rog = 9.65_wp      !< parameter for fall velocity
3287    REAL(wp), PARAMETER ::  b_rog = 10.43_wp     !< parameter for fall velocity
3288    REAL(wp), PARAMETER ::  c_rog = 0.6_wp       !< parameter for fall velocity
3289    REAL(wp), PARAMETER ::  k_cap_rog = 4.0_wp   !< parameter for fall velocity
3290    REAL(wp), PARAMETER ::  k_low_rog = 12.0_wp  !< parameter for fall velocity
3291    REAL(wp), PARAMETER ::  d0_rog = 0.745_wp    !< separation diameter
3292
3293    REAL(wp), DIMENSION(number_of_particles) ::  term_1_2       !< flag to communicate whether a particle is near topography or not
3294    REAL(wp), DIMENSION(number_of_particles) ::  dens_ratio     !< ratio between the density of the fluid and the density of the particles
3295    REAL(wp), DIMENSION(number_of_particles) ::  de_dx_int      !< horizontal TKE gradient along x at particle position
3296    REAL(wp), DIMENSION(number_of_particles) ::  de_dy_int      !< horizontal TKE gradient along y at particle position
3297    REAL(wp), DIMENSION(number_of_particles) ::  de_dz_int      !< horizontal TKE gradient along z at particle position
3298    REAL(wp), DIMENSION(number_of_particles) ::  diss_int       !< dissipation at particle position
3299    REAL(wp), DIMENSION(number_of_particles) ::  dt_gap         !< remaining time until particle time integration reaches LES time
3300    REAL(wp), DIMENSION(number_of_particles) ::  dt_particle    !< particle time step
3301    REAL(wp), DIMENSION(number_of_particles) ::  e_int          !< TKE at particle position
3302    REAL(wp), DIMENSION(number_of_particles) ::  fs_int         !< weighting factor for subgrid-scale particle speed
3303    REAL(wp), DIMENSION(number_of_particles) ::  lagr_timescale !< Lagrangian timescale
3304    REAL(wp), DIMENSION(number_of_particles) ::  rvar1_temp     !< SGS particle velocity - u-component
3305    REAL(wp), DIMENSION(number_of_particles) ::  rvar2_temp     !< SGS particle velocity - v-component
3306    REAL(wp), DIMENSION(number_of_particles) ::  rvar3_temp     !< SGS particle velocity - w-component
3307    REAL(wp), DIMENSION(number_of_particles) ::  u_int          !< u-component of particle speed
3308    REAL(wp), DIMENSION(number_of_particles) ::  v_int          !< v-component of particle speed
3309    REAL(wp), DIMENSION(number_of_particles) ::  w_int          !< w-component of particle speed
3310    REAL(wp), DIMENSION(number_of_particles) ::  xv             !< x-position
3311    REAL(wp), DIMENSION(number_of_particles) ::  yv             !< y-position
3312    REAL(wp), DIMENSION(number_of_particles) ::  zv             !< z-position
3313
3314    REAL(wp), DIMENSION(number_of_particles, 3) ::  rg !< vector of Gaussian distributed random numbers
3315
3316    CALL cpu_log( log_point_s(44), 'lpm_advec', 'continue' )
3317!
3318!-- Determine height of Prandtl layer and distance between Prandtl-layer
3319!-- height and horizontal mean roughness height, which are required for
3320!-- vertical logarithmic interpolation of horizontal particle speeds
3321!-- (for particles below first vertical grid level).
3322    z_p      = zu(nzb+1) - zw(nzb)
3323    d_z_p_z0 = 1.0_wp / ( z_p - z0_av_global )
3324
3325    xv = particles(1:number_of_particles)%x
3326    yv = particles(1:number_of_particles)%y
3327    zv = particles(1:number_of_particles)%z
3328    dt_particle = dt_3d
3329
3330!
3331!-- This case uses a simple interpolation method for the particle velocites,
3332!-- and applying a predictor-corrector method. @note the current time divergence
3333!-- free time step is denoted with u_t etc.; the velocities of the time level of
3334!-- t+1 wit u,v, and w, as the model is called after swap timelevel
3335!-- @attention: for the corrector step the velocities of t(n+1) are required.
3336!-- Therefore the particle code is executed at the end of the time intermediate
3337!-- timestep routine. This interpolation method is described in more detail
3338!-- in Grabowski et al., 2018 (GMD).
3339    IF ( interpolation_simple_corrector )  THEN
3340!
3341!--    Predictor step
3342       kkw = kp - 1
3343       DO  n = 1, number_of_particles
3344
3345          alpha = MAX( MIN( ( particles(n)%x - ip * dx ) * ddx, 1.0_wp ), 0.0_wp )
3346          u_int(n) = u_t(kp,jp,ip) * ( 1.0_wp - alpha ) + u_t(kp,jp,ip+1) * alpha
3347
3348          beta  = MAX( MIN( ( particles(n)%y - jp * dy ) * ddy, 1.0_wp ), 0.0_wp )
3349          v_int(n) = v_t(kp,jp,ip) * ( 1.0_wp - beta ) + v_t(kp,jp+1,ip) * beta
3350
3351          gamma = MAX( MIN( ( particles(n)%z - zw(kkw) ) /                   &
3352                            ( zw(kkw+1) - zw(kkw) ), 1.0_wp ), 0.0_wp )
3353          w_int(n) = w_t(kkw,jp,ip) * ( 1.0_wp - gamma ) + w_t(kkw+1,jp,ip) * gamma
3354
3355       ENDDO
3356!
3357!--    Corrector step
3358       DO  n = 1, number_of_particles
3359
3360          IF ( .NOT. particles(n)%particle_mask )  CYCLE
3361
3362          DO  nn = 1, iteration_steps
3363
3364!
3365!--          Guess new position
3366             xp = particles(n)%x + u_int(n) * dt_particle(n)
3367             yp = particles(n)%y + v_int(n) * dt_particle(n)
3368             zp = particles(n)%z + w_int(n) * dt_particle(n)
3369!
3370!--          x direction
3371             i_next = FLOOR( xp * ddx , KIND=iwp)
3372             alpha  = MAX( MIN( ( xp - i_next * dx ) * ddx, 1.0_wp ), 0.0_wp )
3373!
3374!--          y direction
3375             j_next = FLOOR( yp * ddy )
3376             beta   = MAX( MIN( ( yp - j_next * dy ) * ddy, 1.0_wp ), 0.0_wp )
3377!
3378!--          z_direction
3379             k_next = MAX( MIN( FLOOR( zp / (zw(kkw+1)-zw(kkw)) + offset_ocean_nzt ), nzt ), 0)
3380             gamma = MAX( MIN( ( zp - zw(k_next) ) /                      &
3381                               ( zw(k_next+1) - zw(k_next) ), 1.0_wp ), 0.0_wp )
3382!
3383!--          Calculate part of the corrector step
3384             unext = u(k_next+1, j_next, i_next) * ( 1.0_wp - alpha ) +    &
3385                     u(k_next+1, j_next,   i_next+1) * alpha
3386
3387             vnext = v(k_next+1, j_next, i_next) * ( 1.0_wp - beta  ) +    &
3388                     v(k_next+1, j_next+1, i_next  ) * beta
3389
3390             wnext = w(k_next,   j_next, i_next) * ( 1.0_wp - gamma ) +    &
3391                     w(k_next+1, j_next, i_next  ) * gamma
3392
3393!
3394!--          Calculate interpolated particle velocity with predictor
3395!--          corrector step. u_int, v_int and w_int describes the part of
3396!--          the predictor step. unext, vnext and wnext is the part of the
3397!--          corrector step. The resulting new position is set below. The
3398!--          implementation is based on Grabowski et al., 2018 (GMD).
3399             u_int(n) = 0.5_wp * ( u_int(n) + unext )
3400             v_int(n) = 0.5_wp * ( v_int(n) + vnext )
3401             w_int(n) = 0.5_wp * ( w_int(n) + wnext )
3402
3403          ENDDO
3404       ENDDO
3405!
3406!-- This case uses a simple interpolation method for the particle velocites,
3407!-- and applying a predictor.
3408    ELSEIF ( interpolation_simple_predictor )  THEN
3409!
3410!--    The particle position for the w velociy is based on the value of kp and kp-1
3411       kkw = kp - 1
3412       DO  n = 1, number_of_particles
3413          IF ( .NOT. particles(n)%particle_mask )  CYCLE
3414
3415          alpha    = MAX( MIN( ( particles(n)%x - ip * dx ) * ddx, 1.0_wp ), 0.0_wp )
3416          u_int(n) = u(kp,jp,ip) * ( 1.0_wp - alpha ) + u(kp,jp,ip+1) * alpha
3417
3418          beta     = MAX( MIN( ( particles(n)%y - jp * dy ) * ddy, 1.0_wp ), 0.0_wp )
3419          v_int(n) = v(kp,jp,ip) * ( 1.0_wp - beta ) + v(kp,jp+1,ip) * beta
3420
3421          gamma    = MAX( MIN( ( particles(n)%z - zw(kkw) ) /                   &
3422                               ( zw(kkw+1) - zw(kkw) ), 1.0_wp ), 0.0_wp )
3423          w_int(n) = w(kkw,jp,ip) * ( 1.0_wp - gamma ) + w(kkw+1,jp,ip) * gamma
3424       ENDDO
3425!
3426!-- The trilinear interpolation.
3427    ELSEIF ( interpolation_trilinear )  THEN
3428
3429       start_index = grid_particles(kp,jp,ip)%start_index
3430       end_index   = grid_particles(kp,jp,ip)%end_index
3431
3432       DO  nb = 0, 7
3433!
3434!--       Interpolate u velocity-component
3435          i = ip
3436          j = jp + block_offset(nb)%j_off
3437          k = kp + block_offset(nb)%k_off
3438
3439          DO  n = start_index(nb), end_index(nb)
3440!
3441!--          Interpolation of the u velocity component onto particle position.
3442!--          Particles are interpolation bi-linearly in the horizontal and a
3443!--          linearly in the vertical. An exception is made for particles below
3444!--          the first vertical grid level in case of a prandtl layer. In this
3445!--          case the horizontal particle velocity components are determined using
3446!--          Monin-Obukhov relations (if branch).
3447!--          First, check if particle is located below first vertical grid level
3448!--          above topography (Prandtl-layer height)
3449!--          Determine vertical index of topography top
3450             k_wall = topo_top_ind(jp,ip,0)
3451
3452             IF ( constant_flux_layer  .AND.  zv(n) - zw(k_wall) < z_p )  THEN
3453!
3454!--             Resolved-scale horizontal particle velocity is zero below z0.
3455                IF ( zv(n) - zw(k_wall) < z0_av_global )  THEN
3456                   u_int(n) = 0.0_wp
3457                ELSE
3458!
3459!--                Determine the sublayer. Further used as index.
3460                   height_p = ( zv(n) - zw(k_wall) - z0_av_global ) &
3461                                        * REAL( number_of_sublayers, KIND=wp )    &
3462                                        * d_z_p_z0
3463!
3464!--                Calculate LOG(z/z0) for exact particle height. Therefore,
3465!--                interpolate linearly between precalculated logarithm.
3466                   log_z_z0_int = log_z_z0(INT(height_p))                         &
3467                                    + ( height_p - INT(height_p) )                &
3468                                    * ( log_z_z0(INT(height_p)+1)                 &
3469                                         - log_z_z0(INT(height_p))                &
3470                                      )
3471!
3472!--                Get friction velocity and momentum flux from new surface data
3473!--                types.
3474                   IF ( surf_def_h(0)%start_index(jp,ip) <=                   &
3475                        surf_def_h(0)%end_index(jp,ip) )  THEN
3476                      surf_start = surf_def_h(0)%start_index(jp,ip)
3477!--                   Limit friction velocity. In narrow canyons or holes the
3478!--                   friction velocity can become very small, resulting in a too
3479!--                   large particle speed.
3480                      us_int    = MAX( surf_def_h(0)%us(surf_start), 0.01_wp )
3481                      usws_int  = surf_def_h(0)%usws(surf_start)
3482                   ELSEIF ( surf_lsm_h%start_index(jp,ip) <=                  &
3483                            surf_lsm_h%end_index(jp,ip) )  THEN
3484                      surf_start = surf_lsm_h%start_index(jp,ip)
3485                      us_int    = MAX( surf_lsm_h%us(surf_start), 0.01_wp )
3486                      usws_int  = surf_lsm_h%usws(surf_start)
3487                   ELSEIF ( surf_usm_h%start_index(jp,ip) <=                  &
3488                            surf_usm_h%end_index(jp,ip) )  THEN
3489                      surf_start = surf_usm_h%start_index(jp,ip)
3490                      us_int    = MAX( surf_usm_h%us(surf_start), 0.01_wp )
3491                      usws_int  = surf_usm_h%usws(surf_start)
3492                   ENDIF
3493!
3494!--                Neutral solution is applied for all situations, e.g. also for
3495!--                unstable and stable situations. Even though this is not exact
3496!--                this saves a lot of CPU time since several calls of intrinsic
3497!--                FORTRAN procedures (LOG, ATAN) are avoided, This is justified
3498!--                as sensitivity studies revealed no significant effect of
3499!--                using the neutral solution also for un/stable situations.
3500                   u_int(n) = -usws_int / ( us_int * kappa + 1E-10_wp )           &
3501                               * log_z_z0_int - u_gtrans
3502                ENDIF
3503!
3504!--          Particle above the first grid level. Bi-linear interpolation in the
3505!--          horizontal and linear interpolation in the vertical direction.
3506             ELSE
3507                x  = xv(n) - i * dx
3508                y  = yv(n) + ( 0.5_wp - j ) * dy
3509                aa = x**2          + y**2
3510                bb = ( dx - x )**2 + y**2
3511                cc = x**2          + ( dy - y )**2
3512                dd = ( dx - x )**2 + ( dy - y )**2
3513                gg = aa + bb + cc + dd
3514
3515                u_int_l = ( ( gg - aa ) * u(k,j,i)   + ( gg - bb ) * u(k,j,i+1)   &
3516                            + ( gg - cc ) * u(k,j+1,i) + ( gg - dd ) *            &
3517                            u(k,j+1,i+1) ) / ( 3.0_wp * gg ) - u_gtrans
3518
3519                IF ( k == nzt )  THEN
3520                   u_int(n) = u_int_l
3521                ELSE
3522                   u_int_u = ( ( gg-aa ) * u(k+1,j,i) + ( gg-bb ) * u(k+1,j,i+1)  &
3523                               + ( gg-cc ) * u(k+1,j+1,i) + ( gg-dd ) *           &
3524                               u(k+1,j+1,i+1) ) / ( 3.0_wp * gg ) - u_gtrans
3525                   u_int(n) = u_int_l + ( zv(n) - zu(k) ) / dzw(k+1) *            &
3526                              ( u_int_u - u_int_l )
3527                ENDIF
3528             ENDIF
3529          ENDDO
3530!
3531!--       Same procedure for interpolation of the v velocity-component
3532          i = ip + block_offset(nb)%i_off
3533          j = jp
3534          k = kp + block_offset(nb)%k_off
3535
3536          DO  n = start_index(nb), end_index(nb)
3537!
3538!--          Determine vertical index of topography top
3539             k_wall = topo_top_ind(jp,ip,0)
3540
3541             IF ( constant_flux_layer  .AND.  zv(n) - zw(k_wall) < z_p )  THEN
3542                IF ( zv(n) - zw(k_wall) < z0_av_global )  THEN
3543!
3544!--                Resolved-scale horizontal particle velocity is zero below z0.
3545                   v_int(n) = 0.0_wp
3546                ELSE
3547!
3548!--                Determine the sublayer. Further used as index. Please note,
3549!--                logarithmus can not be reused from above, as in in case of
3550!--                topography particle on u-grid can be above surface-layer height,
3551!--                whereas it can be below on v-grid.
3552                   height_p = ( zv(n) - zw(k_wall) - z0_av_global ) &
3553                                     * REAL( number_of_sublayers, KIND=wp )       &
3554                                     * d_z_p_z0
3555!
3556!--                Calculate LOG(z/z0) for exact particle height. Therefore,
3557!--                interpolate linearly between precalculated logarithm.
3558                   log_z_z0_int = log_z_z0(INT(height_p))                         &
3559                                    + ( height_p - INT(height_p) )                &
3560                                    * ( log_z_z0(INT(height_p)+1)                 &
3561                                         - log_z_z0(INT(height_p))                &
3562                                      )
3563!
3564!--                Get friction velocity and momentum flux from new surface data
3565!--                types.
3566                   IF ( surf_def_h(0)%start_index(jp,ip) <=                   &
3567                        surf_def_h(0)%end_index(jp,ip) )  THEN
3568                      surf_start = surf_def_h(0)%start_index(jp,ip)
3569!--                   Limit friction velocity. In narrow canyons or holes the
3570!--                   friction velocity can become very small, resulting in a too
3571!--                   large particle speed.
3572                      us_int    = MAX( surf_def_h(0)%us(surf_start), 0.01_wp )
3573                      vsws_int  = surf_def_h(0)%vsws(surf_start)
3574                   ELSEIF ( surf_lsm_h%start_index(jp,ip) <=                  &
3575                            surf_lsm_h%end_index(jp,ip) )  THEN
3576                      surf_start = surf_lsm_h%start_index(jp,ip)
3577                      us_int    = MAX( surf_lsm_h%us(surf_start), 0.01_wp )
3578                      vsws_int  = surf_lsm_h%vsws(surf_start)
3579                   ELSEIF ( surf_usm_h%start_index(jp,ip) <=                  &
3580                            surf_usm_h%end_index(jp,ip) )  THEN
3581                      surf_start = surf_usm_h%start_index(jp,ip)
3582                      us_int    = MAX( surf_usm_h%us(surf_start), 0.01_wp )
3583                      vsws_int  = surf_usm_h%vsws(surf_start)
3584                   ENDIF
3585!
3586!--                Neutral solution is applied for all situations, e.g. also for
3587!--                unstable and stable situations. Even though this is not exact
3588!--                this saves a lot of CPU time since several calls of intrinsic
3589!--                FORTRAN procedures (LOG, ATAN) are avoided, This is justified
3590!--                as sensitivity studies revealed no significant effect of
3591!--                using the neutral solution also for un/stable situations.
3592                   v_int(n) = -vsws_int / ( us_int * kappa + 1E-10_wp )           &
3593                            * log_z_z0_int - v_gtrans
3594
3595                ENDIF
3596             ELSE
3597                x  = xv(n) + ( 0.5_wp - i ) * dx
3598                y  = yv(n) - j * dy
3599                aa = x**2          + y**2
3600                bb = ( dx - x )**2 + y**2
3601                cc = x**2          + ( dy - y )**2
3602                dd = ( dx - x )**2 + ( dy - y )**2
3603                gg = aa + bb + cc + dd
3604
3605                v_int_l = ( ( gg - aa ) * v(k,j,i)   + ( gg - bb ) * v(k,j,i+1)   &
3606                          + ( gg - cc ) * v(k,j+1,i) + ( gg - dd ) * v(k,j+1,i+1) &
3607                          ) / ( 3.0_wp * gg ) - v_gtrans
3608
3609                IF ( k == nzt )  THEN
3610                   v_int(n) = v_int_l
3611                ELSE
3612                   v_int_u = ( ( gg-aa ) * v(k+1,j,i)   + ( gg-bb ) * v(k+1,j,i+1)   &
3613                             + ( gg-cc ) * v(k+1,j+1,i) + ( gg-dd ) * v(k+1,j+1,i+1) &
3614                             ) / ( 3.0_wp * gg ) - v_gtrans
3615                   v_int(n) = v_int_l + ( zv(n) - zu(k) ) / dzw(k+1) *               &
3616                                     ( v_int_u - v_int_l )
3617                ENDIF
3618             ENDIF
3619          ENDDO
3620!
3621!--       Same procedure for interpolation of the w velocity-component
3622          i = ip + block_offset(nb)%i_off
3623          j = jp + block_offset(nb)%j_off
3624          k = kp - 1
3625
3626          DO  n = start_index(nb), end_index(nb)
3627             IF ( vertical_particle_advection(particles(n)%group) )  THEN
3628                x  = xv(n) + ( 0.5_wp - i ) * dx
3629                y  = yv(n) + ( 0.5_wp - j ) * dy
3630                aa = x**2          + y**2
3631                bb = ( dx - x )**2 + y**2
3632                cc = x**2          + ( dy - y )**2
3633                dd = ( dx - x )**2 + ( dy - y )**2
3634                gg = aa + bb + cc + dd
3635
3636                w_int_l = ( ( gg - aa ) * w(k,j,i)   + ( gg - bb ) * w(k,j,i+1)   &
3637                          + ( gg - cc ) * w(k,j+1,i) + ( gg - dd ) * w(k,j+1,i+1) &
3638                          ) / ( 3.0_wp * gg )
3639
3640                IF ( k == nzt )  THEN
3641                   w_int(n) = w_int_l
3642                ELSE
3643                   w_int_u = ( ( gg-aa ) * w(k+1,j,i)   + &
3644                               ( gg-bb ) * w(k+1,j,i+1) + &
3645                               ( gg-cc ) * w(k+1,j+1,i) + &
3646                               ( gg-dd ) * w(k+1,j+1,i+1) &
3647                             ) / ( 3.0_wp * gg )
3648                   w_int(n) = w_int_l + ( zv(n) - zw(k) ) / dzw(k+1) *               &
3649                              ( w_int_u - w_int_l )
3650                ENDIF
3651             ELSE
3652                w_int(n) = 0.0_wp
3653             ENDIF
3654          ENDDO
3655       ENDDO
3656    ENDIF
3657
3658!-- Interpolate and calculate quantities needed for calculating the SGS
3659!-- velocities
3660    IF ( use_sgs_for_particles  .AND.  .NOT. cloud_droplets )  THEN
3661
3662       DO  nb = 0,7
3663
3664          subbox_at_wall = .FALSE.
3665!
3666!--       In case of topography check if subbox is adjacent to a wall
3667          IF ( .NOT. topography == 'flat' )  THEN
3668             i = ip + MERGE( -1_iwp , 1_iwp, BTEST( nb, 2 ) )
3669             j = jp + MERGE( -1_iwp , 1_iwp, BTEST( nb, 1 ) )
3670             k = kp + MERGE( -1_iwp , 1_iwp, BTEST( nb, 0 ) )
3671             IF ( .NOT. BTEST(wall_flags_static_0(k,  jp, ip), 0) .OR.                &
3672                  .NOT. BTEST(wall_flags_static_0(kp, j,  ip), 0) .OR.                &
3673                  .NOT. BTEST(wall_flags_static_0(kp, jp, i ), 0) )                   &
3674             THEN
3675                subbox_at_wall = .TRUE.
3676             ENDIF
3677          ENDIF
3678          IF ( subbox_at_wall )  THEN
3679             e_int(start_index(nb):end_index(nb))     = e(kp,jp,ip) 
3680             diss_int(start_index(nb):end_index(nb))  = diss(kp,jp,ip)
3681             de_dx_int(start_index(nb):end_index(nb)) = de_dx(kp,jp,ip)
3682             de_dy_int(start_index(nb):end_index(nb)) = de_dy(kp,jp,ip)
3683             de_dz_int(start_index(nb):end_index(nb)) = de_dz(kp,jp,ip)
3684!
3685!--          Set flag for stochastic equation.
3686             term_1_2(start_index(nb):end_index(nb)) = 0.0_wp
3687          ELSE
3688             i = ip + block_offset(nb)%i_off
3689             j = jp + block_offset(nb)%j_off
3690             k = kp + block_offset(nb)%k_off
3691
3692             DO  n = start_index(nb), end_index(nb)
3693!
3694!--             Interpolate TKE
3695                x  = xv(n) + ( 0.5_wp - i ) * dx
3696                y  = yv(n) + ( 0.5_wp - j ) * dy
3697                aa = x**2          + y**2
3698                bb = ( dx - x )**2 + y**2
3699                cc = x**2          + ( dy - y )**2
3700                dd = ( dx - x )**2 + ( dy - y )**2
3701                gg = aa + bb + cc + dd
3702
3703                e_int_l = ( ( gg-aa ) * e(k,j,i)   + ( gg-bb ) * e(k,j,i+1)   &
3704                          + ( gg-cc ) * e(k,j+1,i) + ( gg-dd ) * e(k,j+1,i+1) &
3705                          ) / ( 3.0_wp * gg )
3706
3707                IF ( k+1 == nzt+1 )  THEN
3708                   e_int(n) = e_int_l
3709                ELSE
3710                   e_int_u = ( ( gg - aa ) * e(k+1,j,i)   + &
3711                               ( gg - bb ) * e(k+1,j,i+1) + &
3712                               ( gg - cc ) * e(k+1,j+1,i) + &
3713                               ( gg - dd ) * e(k+1,j+1,i+1) &
3714                            ) / ( 3.0_wp * gg )
3715                   e_int(n) = e_int_l + ( zv(n) - zu(k) ) / dzw(k+1) *            &
3716                                     ( e_int_u - e_int_l )
3717                ENDIF
3718!
3719!--             Needed to avoid NaN particle velocities (this might not be
3720!--             required any more)
3721                IF ( e_int(n) <= 0.0_wp )  THEN
3722                   e_int(n) = 1.0E-20_wp
3723                ENDIF
3724!
3725!--             Interpolate the TKE gradient along x (adopt incides i,j,k and
3726!--             all position variables from above (TKE))
3727                de_dx_int_l = ( ( gg - aa ) * de_dx(k,j,i)   + &
3728                                ( gg - bb ) * de_dx(k,j,i+1) + &
3729                                ( gg - cc ) * de_dx(k,j+1,i) + &
3730                                ( gg - dd ) * de_dx(k,j+1,i+1) &
3731                               ) / ( 3.0_wp * gg )
3732
3733                IF ( ( k+1 == nzt+1 )  .OR.  ( k == nzb ) )  THEN
3734                   de_dx_int(n) = de_dx_int_l
3735                ELSE
3736                   de_dx_int_u = ( ( gg - aa ) * de_dx(k+1,j,i)   + &
3737                                   ( gg - bb ) * de_dx(k+1,j,i+1) + &
3738                                   ( gg - cc ) * de_dx(k+1,j+1,i) + &
3739                                   ( gg - dd ) * de_dx(k+1,j+1,i+1) &
3740                                  ) / ( 3.0_wp * gg )
3741                   de_dx_int(n) = de_dx_int_l + ( zv(n) - zu(k) ) / dzw(k+1) *    &
3742                                              ( de_dx_int_u - de_dx_int_l )
3743                ENDIF
3744!
3745!--             Interpolate the TKE gradient along y
3746                de_dy_int_l = ( ( gg - aa ) * de_dy(k,j,i)   + &
3747                                ( gg - bb ) * de_dy(k,j,i+1) + &
3748                                ( gg - cc ) * de_dy(k,j+1,i) + &
3749                                ( gg - dd ) * de_dy(k,j+1,i+1) &
3750                               ) / ( 3.0_wp * gg )
3751                IF ( ( k+1 == nzt+1 )  .OR.  ( k == nzb ) )  THEN
3752                   de_dy_int(n) = de_dy_int_l
3753                ELSE
3754                   de_dy_int_u = ( ( gg - aa ) * de_dy(k+1,j,i)   + &
3755                                   ( gg - bb ) * de_dy(k+1,j,i+1) + &
3756                                   ( gg - cc ) * de_dy(k+1,j+1,i) + &
3757                                   ( gg - dd ) * de_dy(k+1,j+1,i+1) &
3758                                  ) / ( 3.0_wp * gg )
3759                      de_dy_int(n) = de_dy_int_l + ( zv(n) - zu(k) ) / dzw(k+1) * &
3760                                                 ( de_dy_int_u - de_dy_int_l )
3761                ENDIF
3762
3763!
3764!--             Interpolate the TKE gradient along z
3765                IF ( zv(n) < 0.5_wp * dz(1) )  THEN
3766                   de_dz_int(n) = 0.0_wp
3767                ELSE
3768                   de_dz_int_l = ( ( gg - aa ) * de_dz(k,j,i)   + &
3769                                   ( gg - bb ) * de_dz(k,j,i+1) + &
3770                                   ( gg - cc ) * de_dz(k,j+1,i) + &
3771                                   ( gg - dd ) * de_dz(k,j+1,i+1) &
3772                                  ) / ( 3.0_wp * gg )
3773
3774                   IF ( ( k+1 == nzt+1 )  .OR.  ( k == nzb ) )  THEN
3775                      de_dz_int(n) = de_dz_int_l
3776                   ELSE
3777                      de_dz_int_u = ( ( gg - aa ) * de_dz(k+1,j,i)   + &
3778                                      ( gg - bb ) * de_dz(k+1,j,i+1) + &
3779                                      ( gg - cc ) * de_dz(k+1,j+1,i) + &
3780                                      ( gg - dd ) * de_dz(k+1,j+1,i+1) &
3781                                     ) / ( 3.0_wp * gg )
3782                      de_dz_int(n) = de_dz_int_l + ( zv(n) - zu(k) ) / dzw(k+1) * &
3783                                                 ( de_dz_int_u - de_dz_int_l )
3784                   ENDIF
3785                ENDIF
3786
3787!
3788!--             Interpolate the dissipation of TKE
3789                diss_int_l = ( ( gg - aa ) * diss(k,j,i)   + &
3790                               ( gg - bb ) * diss(k,j,i+1) + &
3791                               ( gg - cc ) * diss(k,j+1,i) + &
3792                               ( gg - dd ) * diss(k,j+1,i+1) &
3793                               ) / ( 3.0_wp * gg )
3794
3795                IF ( k == nzt )  THEN
3796                   diss_int(n) = diss_int_l
3797                ELSE
3798                   diss_int_u = ( ( gg - aa ) * diss(k+1,j,i)   + &
3799                                  ( gg - bb ) * diss(k+1,j,i+1) + &
3800                                  ( gg - cc ) * diss(k+1,j+1,i) + &
3801                                  ( gg - dd ) * diss(k+1,j+1,i+1) &
3802                                 ) / ( 3.0_wp * gg )
3803                   diss_int(n) = diss_int_l + ( zv(n) - zu(k) ) / dzw(k+1) *      &
3804                                            ( diss_int_u - diss_int_l )
3805                ENDIF
3806
3807!
3808!--             Set flag for stochastic equation.
3809                term_1_2(n) = 1.0_wp
3810             ENDDO
3811          ENDIF
3812       ENDDO
3813
3814       DO  nb = 0,7
3815          i = ip + block_offset(nb)%i_off
3816          j = jp + block_offset(nb)%j_off
3817          k = kp + block_offset(nb)%k_off
3818
3819          DO  n = start_index(nb), end_index(nb)
3820!
3821!--          Vertical interpolation of the horizontally averaged SGS TKE and
3822!--          resolved-scale velocity variances and use the interpolated values
3823!--          to calculate the coefficient fs, which is a measure of the ratio
3824!--          of the subgrid-scale turbulent kinetic energy to the total amount
3825!--          of turbulent kinetic energy.
3826             IF ( k == 0 )  THEN
3827                e_mean_int = hom(0,1,8,0)
3828             ELSE
3829                e_mean_int = hom(k,1,8,0) +                                    &
3830                                           ( hom(k+1,1,8,0) - hom(k,1,8,0) ) / &
3831                                           ( zu(k+1) - zu(k) ) *               &
3832                                           ( zv(n) - zu(k) )
3833             ENDIF
3834
3835             kw = kp - 1
3836
3837             IF ( k == 0 )  THEN
3838                aa  = hom(k+1,1,30,0)  * ( zv(n) / &
3839                                         ( 0.5_wp * ( zu(k+1) - zu(k) ) ) )
3840                bb  = hom(k+1,1,31,0)  * ( zv(n) / &
3841                                         ( 0.5_wp * ( zu(k+1) - zu(k) ) ) )
3842                cc  = hom(kw+1,1,32,0) * ( zv(n) / &
3843                                         ( 1.0_wp * ( zw(kw+1) - zw(kw) ) ) )
3844             ELSE
3845                aa  = hom(k,1,30,0) + ( hom(k+1,1,30,0) - hom(k,1,30,0) ) *    &
3846                           ( ( zv(n) - zu(k) ) / ( zu(k+1) - zu(k) ) )
3847                bb  = hom(k,1,31,0) + ( hom(k+1,1,31,0) - hom(k,1,31,0) ) *    &
3848                           ( ( zv(n) - zu(k) ) / ( zu(k+1) - zu(k) ) )
3849                cc  = hom(kw,1,32,0) + ( hom(kw+1,1,32,0)-hom(kw,1,32,0) ) *   &
3850                           ( ( zv(n) - zw(kw) ) / ( zw(kw+1)-zw(kw) ) )
3851             ENDIF
3852
3853             vv_int = ( 1.0_wp / 3.0_wp ) * ( aa + bb + cc )
3854!
3855!--          Needed to avoid NaN particle velocities. The value of 1.0 is just
3856!--          an educated guess for the given case.
3857             IF ( vv_int + ( 2.0_wp / 3.0_wp ) * e_mean_int == 0.0_wp )  THEN
3858                fs_int(n) = 1.0_wp
3859             ELSE
3860                fs_int(n) = ( 2.0_wp / 3.0_wp ) * e_mean_int /                 &
3861                            ( vv_int + ( 2.0_wp / 3.0_wp ) * e_mean_int )
3862             ENDIF
3863
3864          ENDDO
3865       ENDDO
3866
3867       DO  nb = 0, 7
3868          DO  n = start_index(nb), end_index(nb)
3869             rg(n,1) = random_gauss( iran_part, 5.0_wp )
3870             rg(n,2) = random_gauss( iran_part, 5.0_wp )
3871             rg(n,3) = random_gauss( iran_part, 5.0_wp )
3872          ENDDO
3873       ENDDO
3874
3875       DO  nb = 0, 7
3876          DO  n = start_index(nb), end_index(nb)
3877
3878!
3879!--          Calculate the Lagrangian timescale according to Weil et al. (2004).
3880             lagr_timescale(n) = ( 4.0_wp * e_int(n) + 1E-20_wp ) / &
3881                              ( 3.0_wp * fs_int(n) * c_0 * diss_int(n) + 1E-20_wp )
3882
3883!
3884!--          Calculate the next particle timestep. dt_gap is the time needed to
3885!--          complete the current LES timestep.
3886             dt_gap(n) = dt_3d - particles(n)%dt_sum
3887             dt_particle(n) = MIN( dt_3d, 0.025_wp * lagr_timescale(n), dt_gap(n) )
3888             particles(n)%aux1 = lagr_timescale(n)
3889             particles(n)%aux2 = dt_gap(n)
3890!
3891!--          The particle timestep should not be too small in order to prevent
3892!--          the number of particle timesteps of getting too large
3893             IF ( dt_particle(n) < dt_min_part )  THEN
3894                IF ( dt_min_part < dt_gap(n) )  THEN
3895                   dt_particle(n) = dt_min_part
3896                ELSE
3897                   dt_particle(n) = dt_gap(n)
3898                ENDIF
3899             ENDIF
3900             rvar1_temp(n) = particles(n)%rvar1
3901             rvar2_temp(n) = particles(n)%rvar2
3902             rvar3_temp(n) = particles(n)%rvar3
3903!
3904!--          Calculate the SGS velocity components
3905             IF ( particles(n)%age == 0.0_wp )  THEN
3906!
3907!--             For new particles the SGS components are derived from the SGS
3908!--             TKE. Limit the Gaussian random number to the interval
3909!--             [-5.0*sigma, 5.0*sigma] in order to prevent the SGS velocities
3910!--             from becoming unrealistically large.
3911                rvar1_temp(n) = SQRT( 2.0_wp * sgs_wf_part * e_int(n)          &
3912                                          + 1E-20_wp ) * ( rg(n,1) - 1.0_wp )
3913                rvar2_temp(n) = SQRT( 2.0_wp * sgs_wf_part * e_int(n)          &
3914                                          + 1E-20_wp ) * ( rg(n,2) - 1.0_wp )
3915                rvar3_temp(n) = SQRT( 2.0_wp * sgs_wf_part * e_int(n)          &
3916                                          + 1E-20_wp ) * ( rg(n,3) - 1.0_wp )
3917
3918             ELSE
3919!
3920!--             Restriction of the size of the new timestep: compared to the
3921!--             previous timestep the increase must not exceed 200%. First,
3922!--             check if age > age_m, in order to prevent that particles get zero
3923!--             timestep.
3924                dt_particle_m = MERGE( dt_particle(n),                         &
3925                                       particles(n)%age - particles(n)%age_m,  &
3926                                       particles(n)%age - particles(n)%age_m < &
3927                                       1E-8_wp )
3928                IF ( dt_particle(n) > 2.0_wp * dt_particle_m )  THEN
3929                   dt_particle(n) = 2.0_wp * dt_particle_m
3930                ENDIF
3931
3932!--             For old particles the SGS components are correlated with the
3933!--             values from the previous timestep. Random numbers have also to
3934!--             be limited (see above).
3935!--             As negative values for the subgrid TKE are not allowed, the
3936!--             change of the subgrid TKE with time cannot be smaller than
3937!--             -e_int(n)/dt_particle. This value is used as a lower boundary
3938!--             value for the change of TKE
3939                de_dt_min = - e_int(n) / dt_particle(n)
3940
3941                de_dt = ( e_int(n) - particles(n)%e_m ) / dt_particle_m
3942
3943                IF ( de_dt < de_dt_min )  THEN
3944                   de_dt = de_dt_min
3945                ENDIF
3946
3947                CALL weil_stochastic_eq( rvar1_temp(n), fs_int(n), e_int(n),    &
3948                                        de_dx_int(n), de_dt, diss_int(n),       &
3949                                        dt_particle(n), rg(n,1), term_1_2(n) )
3950
3951                CALL weil_stochastic_eq( rvar2_temp(n), fs_int(n), e_int(n),    &
3952                                        de_dy_int(n), de_dt, diss_int(n),       &
3953                                        dt_particle(n), rg(n,2), term_1_2(n) )
3954
3955                CALL weil_stochastic_eq( rvar3_temp(n), fs_int(n), e_int(n),    &
3956                                        de_dz_int(n), de_dt, diss_int(n),       &
3957                                        dt_particle(n), rg(n,3), term_1_2(n) )
3958
3959             ENDIF
3960
3961          ENDDO
3962       ENDDO
3963!
3964!--    Check if the added SGS velocities result in a violation of the CFL-
3965!--    criterion. If yes choose a smaller timestep based on the new velocities
3966!--    and calculate SGS velocities again
3967       dz_temp = zw(kp)-zw(kp-1)
3968
3969       DO  nb = 0, 7
3970          DO  n = start_index(nb), end_index(nb)
3971             IF ( .NOT. particles(n)%age == 0.0_wp .AND.                       &
3972                (ABS( u_int(n) + rvar1_temp(n) ) > (dx/dt_particle(n))  .OR.   &
3973                 ABS( v_int(n) + rvar2_temp(n) ) > (dy/dt_particle(n))  .OR.   &
3974                 ABS( w_int(n) + rvar3_temp(n) ) > (dz_temp/dt_particle(n))))  THEN
3975
3976                dt_particle(n) = 0.9_wp * MIN(                                 &
3977                                 ( dx / ABS( u_int(n) + rvar1_temp(n) ) ),     &
3978                                 ( dy / ABS( v_int(n) + rvar2_temp(n) ) ),     &
3979                                 ( dz_temp / ABS( w_int(n) + rvar3_temp(n) ) ) )
3980
3981!
3982!--             Reset temporary SGS velocites to "current" ones
3983                rvar1_temp(n) = particles(n)%rvar1
3984                rvar2_temp(n) = particles(n)%rvar2
3985                rvar3_temp(n) = particles(n)%rvar3
3986
3987                de_dt_min = - e_int(n) / dt_particle(n)
3988
3989                de_dt = ( e_int(n) - particles(n)%e_m ) / dt_particle_m
3990
3991                IF ( de_dt < de_dt_min )  THEN
3992                   de_dt = de_dt_min
3993                ENDIF
3994
3995                CALL weil_stochastic_eq( rvar1_temp(n), fs_int(n), e_int(n),    &
3996                                        de_dx_int(n), de_dt, diss_int(n),       &
3997                                        dt_particle(n), rg(n,1), term_1_2(n) )
3998
3999                CALL weil_stochastic_eq( rvar2_temp(n), fs_int(n), e_int(n),    &
4000                                        de_dy_int(n), de_dt, diss_int(n),       &
4001                                        dt_particle(n), rg(n,2), term_1_2(n) )
4002
4003                CALL weil_stochastic_eq( rvar3_temp(n), fs_int(n), e_int(n),    &
4004                                        de_dz_int(n), de_dt, diss_int(n),       &
4005                                        dt_particle(n), rg(n,3), term_1_2(n) )
4006             ENDIF
4007
4008!
4009!--          Update particle velocites
4010             particles(n)%rvar1 = rvar1_temp(n)
4011             particles(n)%rvar2 = rvar2_temp(n)
4012             particles(n)%rvar3 = rvar3_temp(n)
4013             u_int(n) = u_int(n) + particles(n)%rvar1
4014             v_int(n) = v_int(n) + particles(n)%rvar2
4015             w_int(n) = w_int(n) + particles(n)%rvar3
4016!
4017!--          Store the SGS TKE of the current timelevel which is needed for
4018!--          for calculating the SGS particle velocities at the next timestep
4019             particles(n)%e_m = e_int(n)
4020          ENDDO
4021       ENDDO
4022
4023    ELSE
4024!
4025!--    If no SGS velocities are used, only the particle timestep has to
4026!--    be set
4027       dt_particle = dt_3d
4028
4029    ENDIF
4030
4031    dens_ratio = particle_groups(particles(1:number_of_particles)%group)%density_ratio
4032    IF ( ANY( dens_ratio == 0.0_wp ) )  THEN
4033!
4034!--    Decide whether the particle loop runs over the subboxes or only over 1,
4035!--    number_of_particles. This depends on the selected interpolation method.
4036!--    If particle interpolation method is not trilinear, then the sorting within
4037!--    subboxes is not required. However, therefore the index start_index(nb) and
4038!--    end_index(nb) are not defined and the loops are still over
4039!--    number_of_particles. @todo find a more generic way to write this loop or
4040!--    delete trilinear interpolation
4041       IF ( interpolation_trilinear )  THEN
4042          subbox_start = 0
4043          subbox_end   = 7
4044       ELSE
4045          subbox_start = 1
4046          subbox_end   = 1
4047       ENDIF
4048!
4049!--    loop over subboxes. In case of simple interpolation scheme no subboxes
4050!--    are introduced, as they are not required. Accordingly, this loops goes
4051!--    from 1 to 1.
4052       DO  nb = subbox_start, subbox_end
4053          IF ( interpolation_trilinear )  THEN
4054             particle_start = start_index(nb)
4055             particle_end   = end_index(nb)
4056          ELSE
4057             particle_start = 1
4058             particle_end   = number_of_particles
4059          ENDIF
4060!
4061!--         Loop from particle start to particle end
4062            DO  n = particle_start, particle_end
4063
4064!
4065!--          Particle advection
4066             IF ( dens_ratio(n) == 0.0_wp )  THEN
4067!
4068!--             Pure passive transport (without particle inertia)
4069                particles(n)%x = xv(n) + u_int(n) * dt_particle(n)
4070                particles(n)%y = yv(n) + v_int(n) * dt_particle(n)
4071                particles(n)%z = zv(n) + w_int(n) * dt_particle(n)
4072
4073                particles(n)%speed_x = u_int(n)
4074                particles(n)%speed_y = v_int(n)
4075                particles(n)%speed_z = w_int(n)
4076
4077             ELSE
4078!
4079!--             Transport of particles with inertia
4080                particles(n)%x = particles(n)%x + particles(n)%speed_x * &
4081                                                  dt_particle(n)
4082                particles(n)%y = particles(n)%y + particles(n)%speed_y * &
4083                                                  dt_particle(n)
4084                particles(n)%z = particles(n)%z + particles(n)%speed_z * &
4085                                                  dt_particle(n)
4086
4087!
4088!--             Update of the particle velocity
4089                IF ( cloud_droplets )  THEN
4090!
4091!--                Terminal velocity is computed for vertical direction (Rogers et
4092!--                al., 1993, J. Appl. Meteorol.)
4093                   diameter = particles(n)%radius * 2000.0_wp !diameter in mm
4094                   IF ( diameter <= d0_rog )  THEN
4095                      w_s = k_cap_rog * diameter * ( 1.0_wp - EXP( -k_low_rog * diameter ) )
4096                   ELSE
4097                      w_s = a_rog - b_rog * EXP( -c_rog * diameter )
4098                   ENDIF
4099
4100!
4101!--                If selected, add random velocities following Soelch and Kaercher
4102!--                (2010, Q. J. R. Meteorol. Soc.)
4103                   IF ( use_sgs_for_particles )  THEN
4104                      lagr_timescale(n) = km(kp,jp,ip) / MAX( e(kp,jp,ip), 1.0E-20_wp )
4105                      RL             = EXP( -1.0_wp * dt_3d / MAX( lagr_timescale(n), &
4106                                             1.0E-20_wp ) )
4107                      sigma          = SQRT( e(kp,jp,ip) )
4108
4109                      rg1 = random_gauss( iran_part, 5.0_wp ) - 1.0_wp
4110                      rg2 = random_gauss( iran_part, 5.0_wp ) - 1.0_wp
4111                      rg3 = random_gauss( iran_part, 5.0_wp ) - 1.0_wp
4112
4113                      particles(n)%rvar1 = RL * particles(n)%rvar1 +              &
4114                                           SQRT( 1.0_wp - RL**2 ) * sigma * rg1
4115                      particles(n)%rvar2 = RL * particles(n)%rvar2 +              &
4116                                           SQRT( 1.0_wp - RL**2 ) * sigma * rg2
4117                      particles(n)%rvar3 = RL * particles(n)%rvar3 +              &
4118                                           SQRT( 1.0_wp - RL**2 ) * sigma * rg3
4119
4120                      particles(n)%speed_x = u_int(n) + particles(n)%rvar1
4121                      particles(n)%speed_y = v_int(n) + particles(n)%rvar2
4122                      particles(n)%speed_z = w_int(n) + particles(n)%rvar3 - w_s
4123                   ELSE
4124                      particles(n)%speed_x = u_int(n)
4125                      particles(n)%speed_y = v_int(n)
4126                      particles(n)%speed_z = w_int(n) - w_s
4127                   ENDIF
4128
4129                ELSE
4130
4131                   IF ( use_sgs_for_particles )  THEN
4132                      exp_arg  = particle_groups(particles(n)%group)%exp_arg
4133                      exp_term = EXP( -exp_arg * dt_particle(n) )
4134                   ELSE
4135                      exp_arg  = particle_groups(particles(n)%group)%exp_arg
4136                      exp_term = particle_groups(particles(n)%group)%exp_term
4137                   ENDIF
4138                   particles(n)%speed_x = particles(n)%speed_x * exp_term +         &
4139                                          u_int(n) * ( 1.0_wp - exp_term )
4140                   particles(n)%speed_y = particles(n)%speed_y * exp_term +         &
4141                                          v_int(n) * ( 1.0_wp - exp_term )
4142                   particles(n)%speed_z = particles(n)%speed_z * exp_term +         &
4143                                          ( w_int(n) - ( 1.0_wp - dens_ratio(n) ) * &
4144                                          g / exp_arg ) * ( 1.0_wp - exp_term )
4145                ENDIF
4146
4147             ENDIF
4148          ENDDO
4149       ENDDO
4150
4151    ELSE
4152!
4153!--    Decide whether the particle loop runs over the subboxes or only over 1,
4154!--    number_of_particles. This depends on the selected interpolation method.
4155       IF ( interpolation_trilinear )  THEN
4156          subbox_start = 0
4157          subbox_end   = 7
4158       ELSE
4159          subbox_start = 1
4160          subbox_end   = 1
4161       ENDIF
4162!--    loop over subboxes. In case of simple interpolation scheme no subboxes
4163!--    are introduced, as they are not required. Accordingly, this loops goes
4164!--    from 1 to 1.
4165       DO  nb = subbox_start, subbox_end
4166          IF ( interpolation_trilinear )  THEN
4167             particle_start = start_index(nb)
4168             particle_end   = end_index(nb)
4169          ELSE
4170             particle_start = 1
4171             particle_end   = number_of_particles
4172          ENDIF
4173!
4174!--         Loop from particle start to particle end
4175            DO  n = particle_start, particle_end
4176
4177!
4178!--          Transport of particles with inertia
4179             particles(n)%x = xv(n) + particles(n)%speed_x * dt_particle(n)
4180             particles(n)%y = yv(n) + particles(n)%speed_y * dt_particle(n)
4181             particles(n)%z = zv(n) + particles(n)%speed_z * dt_particle(n)
4182!
4183!--          Update of the particle velocity
4184             IF ( cloud_droplets )  THEN
4185!
4186!--             Terminal velocity is computed for vertical direction (Rogers et al.,
4187!--             1993, J. Appl. Meteorol.)
4188                diameter = particles(n)%radius * 2000.0_wp !diameter in mm
4189                IF ( diameter <= d0_rog )  THEN
4190                   w_s = k_cap_rog * diameter * ( 1.0_wp - EXP( -k_low_rog * diameter ) )
4191                ELSE
4192                   w_s = a_rog - b_rog * EXP( -c_rog * diameter )
4193                ENDIF
4194
4195!
4196!--             If selected, add random velocities following Soelch and Kaercher
4197!--             (2010, Q. J. R. Meteorol. Soc.)
4198                IF ( use_sgs_for_particles )  THEN
4199                    lagr_timescale(n) = km(kp,jp,ip) / MAX( e(kp,jp,ip), 1.0E-20_wp )
4200                     RL             = EXP( -1.0_wp * dt_3d / MAX( lagr_timescale(n), &
4201                                             1.0E-20_wp ) )
4202                    sigma          = SQRT( e(kp,jp,ip) )
4203
4204                    rg1 = random_gauss( iran_part, 5.0_wp ) - 1.0_wp
4205                    rg2 = random_gauss( iran_part, 5.0_wp ) - 1.0_wp
4206                    rg3 = random_gauss( iran_part, 5.0_wp ) - 1.0_wp
4207
4208                    particles(n)%rvar1 = RL * particles(n)%rvar1 +                &
4209                                         SQRT( 1.0_wp - RL**2 ) * sigma * rg1
4210                    particles(n)%rvar2 = RL * particles(n)%rvar2 +                &
4211                                         SQRT( 1.0_wp - RL**2 ) * sigma * rg2
4212                    particles(n)%rvar3 = RL * particles(n)%rvar3 +                &
4213                                         SQRT( 1.0_wp - RL**2 ) * sigma * rg3
4214
4215                    particles(n)%speed_x = u_int(n) + particles(n)%rvar1
4216                    particles(n)%speed_y = v_int(n) + particles(n)%rvar2
4217                    particles(n)%speed_z = w_int(n) + particles(n)%rvar3 - w_s
4218                ELSE
4219                    particles(n)%speed_x = u_int(n)
4220                    particles(n)%speed_y = v_int(n)
4221                    particles(n)%speed_z = w_int(n) - w_s
4222                ENDIF
4223
4224             ELSE
4225
4226                IF ( use_sgs_for_particles )  THEN
4227                   exp_arg  = particle_groups(particles(n)%group)%exp_arg
4228                   exp_term = EXP( -exp_arg * dt_particle(n) )
4229                ELSE
4230                   exp_arg  = particle_groups(particles(n)%group)%exp_arg
4231                   exp_term = particle_groups(particles(n)%group)%exp_term
4232                ENDIF
4233                particles(n)%speed_x = particles(n)%speed_x * exp_term +             &
4234                                       u_int(n) * ( 1.0_wp - exp_term )
4235                particles(n)%speed_y = particles(n)%speed_y * exp_term +             &
4236                                       v_int(n) * ( 1.0_wp - exp_term )
4237                particles(n)%speed_z = particles(n)%speed_z * exp_term +             &
4238                                       ( w_int(n) - ( 1.0_wp - dens_ratio(n) ) * g / &
4239                                       exp_arg ) * ( 1.0_wp - exp_term )
4240             ENDIF
4241          ENDDO
4242       ENDDO
4243
4244    ENDIF
4245
4246!
4247!-- Store the old age of the particle ( needed to prevent that a
4248!-- particle crosses several PEs during one timestep, and for the
4249!-- evaluation of the subgrid particle velocity fluctuations )
4250    particles(1:number_of_particles)%age_m = particles(1:number_of_particles)%age
4251
4252!
4253!--    loop over subboxes. In case of simple interpolation scheme no subboxes
4254!--    are introduced, as they are not required. Accordingly, this loops goes
4255!--    from 1 to 1.
4256!
4257!-- Decide whether the particle loop runs over the subboxes or only over 1,
4258!-- number_of_particles. This depends on the selected interpolation method.
4259    IF ( interpolation_trilinear )  THEN
4260       subbox_start = 0
4261       subbox_end   = 7
4262    ELSE
4263       subbox_start = 1
4264       subbox_end   = 1
4265    ENDIF
4266    DO  nb = subbox_start, subbox_end
4267       IF ( interpolation_trilinear )  THEN
4268          particle_start = start_index(nb)
4269          particle_end   = end_index(nb)
4270       ELSE
4271          particle_start = 1
4272          particle_end   = number_of_particles
4273       ENDIF
4274!
4275!--    Loop from particle start to particle end
4276       DO  n = particle_start, particle_end
4277!
4278!--       Increment the particle age and the total time that the particle
4279!--       has advanced within the particle timestep procedure
4280          particles(n)%age    = particles(n)%age    + dt_particle(n)
4281          particles(n)%dt_sum = particles(n)%dt_sum + dt_particle(n)
4282
4283!
4284!--       Check whether there is still a particle that has not yet completed
4285!--       the total LES timestep
4286          IF ( ( dt_3d - particles(n)%dt_sum ) > 1E-8_wp )  THEN
4287             dt_3d_reached_l = .FALSE.
4288          ENDIF
4289
4290       ENDDO
4291    ENDDO
4292
4293    CALL cpu_log( log_point_s(44), 'lpm_advec', 'pause' )
4294
4295
4296 END SUBROUTINE lpm_advec
4297
4298 
4299!------------------------------------------------------------------------------! 
4300! Description:
4301! ------------
4302!> Calculation of subgrid-scale particle speed using the stochastic model
4303!> of Weil et al. (2004, JAS, 61, 2877-2887).
4304!------------------------------------------------------------------------------!
4305 SUBROUTINE weil_stochastic_eq( v_sgs, fs_n, e_n, dedxi_n, dedt_n, diss_n,     &
4306                                dt_n, rg_n, fac )
4307
4308    REAL(wp) ::  a1      !< dummy argument
4309    REAL(wp) ::  dedt_n  !< time derivative of TKE at particle position
4310    REAL(wp) ::  dedxi_n !< horizontal derivative of TKE at particle position
4311    REAL(wp) ::  diss_n  !< dissipation at particle position
4312    REAL(wp) ::  dt_n    !< particle timestep
4313    REAL(wp) ::  e_n     !< TKE at particle position
4314    REAL(wp) ::  fac     !< flag to identify adjacent topography
4315    REAL(wp) ::  fs_n    !< weighting factor to prevent that subgrid-scale particle speed becomes too large
4316    REAL(wp) ::  rg_n    !< random number
4317    REAL(wp) ::  term1   !< memory term
4318    REAL(wp) ::  term2   !< drift correction term
4319    REAL(wp) ::  term3   !< random term
4320    REAL(wp) ::  v_sgs   !< subgrid-scale velocity component
4321
4322!-- At first, limit TKE to a small non-zero number, in order to prevent
4323!-- the occurrence of extremely large SGS-velocities in case TKE is zero,
4324!-- (could occur at the simulation begin).
4325    e_n = MAX( e_n, 1E-20_wp )
4326!
4327!-- Please note, terms 1 and 2 (drift and memory term, respectively) are
4328!-- multiplied by a flag to switch of both terms near topography.
4329!-- This is necessary, as both terms may cause a subgrid-scale velocity build up
4330!-- if particles are trapped in regions with very small TKE, e.g. in narrow street
4331!-- canyons resolved by only a few grid points. Hence, term 1 and term 2 are
4332!-- disabled if one of the adjacent grid points belongs to topography.
4333!-- Moreover, in this case, the  previous subgrid-scale component is also set
4334!-- to zero.
4335
4336    a1 = fs_n * c_0 * diss_n
4337!
4338!-- Memory term
4339    term1 = - a1 * v_sgs * dt_n / ( 4.0_wp * sgs_wf_part * e_n + 1E-20_wp )    &
4340                 * fac
4341!
4342!-- Drift correction term
4343    term2 = ( ( dedt_n * v_sgs / e_n ) + dedxi_n ) * 0.5_wp * dt_n              &
4344                 * fac
4345!
4346!-- Random term
4347    term3 = SQRT( MAX( a1, 1E-20_wp ) ) * ( rg_n - 1.0_wp ) * SQRT( dt_n )
4348!
4349!-- In cese one of the adjacent grid-boxes belongs to topograhy, the previous
4350!-- subgrid-scale velocity component is set to zero, in order to prevent a
4351!-- velocity build-up.
4352!-- This case, set also previous subgrid-scale component to zero.
4353    v_sgs = v_sgs * fac + term1 + term2 + term3
4354
4355 END SUBROUTINE weil_stochastic_eq
4356
4357
4358!------------------------------------------------------------------------------!
4359! Description:
4360! ------------
4361!> swap timelevel in case of particle advection interpolation 'simple-corrector'
4362!> This routine is called at the end of one timestep, the velocities are then
4363!> used for the next timestep
4364!------------------------------------------------------------------------------!
4365 SUBROUTINE lpm_swap_timelevel_for_particle_advection
4366
4367!
4368!-- save the divergence free velocites of t+1 to use them at the end of the
4369!-- next time step
4370    u_t = u
4371    v_t = v
4372    w_t = w
4373
4374 END SUBROUTINE lpm_swap_timelevel_for_particle_advection
4375
4376
4377!------------------------------------------------------------------------------! 
4378! Description:
4379! ------------
4380!> Boundary conditions for the Lagrangian particles.
4381!> The routine consists of two different parts. One handles the bottom (flat)
4382!> and top boundary. In this part, also particles which exceeded their lifetime
4383!> are deleted.
4384!> The other part handles the reflection of particles from vertical walls.
4385!> This part was developed by Jin Zhang during 2006-2007.
4386!>
4387!> To do: Code structure for finding the t_index values and for checking the
4388!> -----  reflection conditions is basically the same for all four cases, so it
4389!>        should be possible to further simplify/shorten it.
4390!>
4391!> THE WALLS PART OF THIS ROUTINE HAS NOT BEEN TESTED FOR OCEAN RUNS SO FAR!!!!
4392!> (see offset_ocean_*)
4393!------------------------------------------------------------------------------!
4394 SUBROUTINE lpm_boundary_conds( location_bc , i, j, k )
4395
4396    CHARACTER (LEN=*), INTENT(IN) ::  location_bc !< general mode: boundary conditions at bottom/top of the model domain
4397                                   !< or at vertical surfaces (buildings, terrain steps)   
4398    INTEGER(iwp), INTENT(IN) ::  i !< grid index of particle box along x
4399    INTEGER(iwp), INTENT(IN) ::  j !< grid index of particle box along y
4400    INTEGER(iwp), INTENT(IN) ::  k !< grid index of particle box along z
4401
4402    INTEGER(iwp) ::  inc            !< dummy for sorting algorithmus
4403    INTEGER(iwp) ::  ir             !< dummy for sorting algorithmus
4404    INTEGER(iwp) ::  i1             !< grid index (x) of old particle position
4405    INTEGER(iwp) ::  i2             !< grid index (x) of current particle position
4406    INTEGER(iwp) ::  i3             !< grid index (x) of intermediate particle position
4407    INTEGER(iwp) ::  index_reset    !< index reset height
4408    INTEGER(iwp) ::  jr             !< dummy for sorting algorithmus
4409    INTEGER(iwp) ::  j1             !< grid index (y) of old particle position
4410    INTEGER(iwp) ::  j2             !< grid index (y) of current particle position
4411    INTEGER(iwp) ::  j3             !< grid index (y) of intermediate particle position
4412    INTEGER(iwp) ::  k1             !< grid index (z) of old particle position
4413    INTEGER(iwp) ::  k2             !< grid index (z) of current particle position
4414    INTEGER(iwp) ::  k3             !< grid index (z) of intermediate particle position
4415    INTEGER(iwp) ::  n              !< particle number
4416    INTEGER(iwp) ::  particles_top  !< maximum reset height
4417    INTEGER(iwp) ::  t_index        !< running index for intermediate particle timesteps in reflection algorithmus
4418    INTEGER(iwp) ::  t_index_number !< number of intermediate particle timesteps in reflection algorithmus
4419    INTEGER(iwp) ::  tmp_x          !< dummy for sorting algorithm
4420    INTEGER(iwp) ::  tmp_y          !< dummy for sorting algorithm
4421    INTEGER(iwp) ::  tmp_z          !< dummy for sorting algorithm
4422
4423    INTEGER(iwp), DIMENSION(0:10) ::  x_ind(0:10) = 0 !< index array (x) of intermediate particle positions
4424    INTEGER(iwp), DIMENSION(0:10) ::  y_ind(0:10) = 0 !< index array (y) of intermediate particle positions
4425    INTEGER(iwp), DIMENSION(0:10) ::  z_ind(0:10) = 0 !< index array (z) of intermediate particle positions
4426
4427    LOGICAL  ::  cross_wall_x    !< flag to check if particle reflection along x is necessary
4428    LOGICAL  ::  cross_wall_y    !< flag to check if particle reflection along y is necessary
4429    LOGICAL  ::  cross_wall_z    !< flag to check if particle reflection along z is necessary
4430    LOGICAL  ::  reflect_x       !< flag to check if particle is already reflected along x
4431    LOGICAL  ::  reflect_y       !< flag to check if particle is already reflected along y
4432    LOGICAL  ::  reflect_z       !< flag to check if particle is already reflected along z
4433    LOGICAL  ::  tmp_reach_x     !< dummy for sorting algorithmus
4434    LOGICAL  ::  tmp_reach_y     !< dummy for sorting algorithmus
4435    LOGICAL  ::  tmp_reach_z     !< dummy for sorting algorithmus
4436    LOGICAL  ::  x_wall_reached  !< flag to check if particle has already reached wall
4437    LOGICAL  ::  y_wall_reached  !< flag to check if particle has already reached wall
4438    LOGICAL  ::  z_wall_reached  !< flag to check if particle has already reached wall
4439
4440    LOGICAL, DIMENSION(0:10) ::  reach_x  !< flag to check if particle is at a yz-wall
4441    LOGICAL, DIMENSION(0:10) ::  reach_y  !< flag to check if particle is at a xz-wall
4442    LOGICAL, DIMENSION(0:10) ::  reach_z  !< flag to check if particle is at a xy-wall
4443
4444    REAL(wp) ::  dt_particle    !< particle timestep
4445    REAL(wp) ::  eps = 1E-10_wp !< security number to check if particle has reached a wall
4446    REAL(wp) ::  pos_x          !< intermediate particle position (x)
4447    REAL(wp) ::  pos_x_old      !< particle position (x) at previous particle timestep
4448    REAL(wp) ::  pos_y          !< intermediate particle position (y)
4449    REAL(wp) ::  pos_y_old      !< particle position (y) at previous particle timestep
4450    REAL(wp) ::  pos_z          !< intermediate particle position (z)
4451    REAL(wp) ::  pos_z_old      !< particle position (z) at previous particle timestep
4452    REAL(wp) ::  prt_x          !< current particle position (x)
4453    REAL(wp) ::  prt_y          !< current particle position (y)
4454    REAL(wp) ::  prt_z          !< current particle position (z)
4455    REAL(wp) ::  ran_val        !< location of wall in z
4456    REAL(wp) ::  reset_top      !< location of wall in z
4457    REAL(wp) ::  t_old          !< previous reflection time
4458    REAL(wp) ::  tmp_t          !< dummy for sorting algorithmus
4459    REAL(wp) ::  xwall          !< location of wall in x
4460    REAL(wp) ::  ywall          !< location of wall in y
4461    REAL(wp) ::  zwall          !< location of wall in z
4462
4463    REAL(wp), DIMENSION(0:10) ::  t  !< reflection time
4464
4465    SELECT CASE ( location_bc )
4466
4467       CASE ( 'bottom/top' )
4468
4469!
4470!--    Apply boundary conditions to those particles that have crossed the top or
4471!--    bottom boundary and delete those particles, which are older than allowed
4472       DO  n = 1, number_of_particles
4473
4474!
4475!--       Stop if particles have moved further than the length of one
4476!--       PE subdomain (newly released particles have age = age_m!)
4477          IF ( particles(n)%age /= particles(n)%age_m )  THEN
4478             IF ( ABS(particles(n)%speed_x) >                                  &
4479                  ((nxr-nxl+2)*dx)/(particles(n)%age-particles(n)%age_m)  .OR. &
4480                  ABS(particles(n)%speed_y) >                                  &
4481                  ((nyn-nys+2)*dy)/(particles(n)%age-particles(n)%age_m) )  THEN
4482
4483                  WRITE( message_string, * )  'particle too fast.  n = ',  n 
4484                  CALL message( 'lpm_boundary_conds', 'PA0148', 2, 2, -1, 6, 1 )
4485             ENDIF
4486          ENDIF
4487
4488          IF ( particles(n)%age > particle_maximum_age  .AND.  &
4489               particles(n)%particle_mask )                              &
4490          THEN
4491             particles(n)%particle_mask  = .FALSE.
4492             deleted_particles = deleted_particles + 1
4493          ENDIF
4494
4495          IF ( particles(n)%z >= zw(nz)  .AND.  particles(n)%particle_mask )  THEN
4496             IF ( ibc_par_t == 1 )  THEN
4497!
4498!--             Particle absorption
4499                particles(n)%particle_mask  = .FALSE.
4500                deleted_particles = deleted_particles + 1
4501             ELSEIF ( ibc_par_t == 2 )  THEN
4502!
4503!--             Particle reflection
4504                particles(n)%z       = 2.0_wp * zw(nz) - particles(n)%z
4505                particles(n)%speed_z = -particles(n)%speed_z
4506                IF ( use_sgs_for_particles  .AND. &
4507                     particles(n)%rvar3 > 0.0_wp )  THEN
4508                   particles(n)%rvar3 = -particles(n)%rvar3
4509                ENDIF
4510             ENDIF
4511          ENDIF
4512
4513          IF ( particles(n)%z < zw(0)  .AND.  particles(n)%particle_mask )  THEN
4514             IF ( ibc_par_b == 1 )  THEN
4515!
4516!--             Particle absorption
4517                particles(n)%particle_mask  = .FALSE.
4518                deleted_particles = deleted_particles + 1
4519             ELSEIF ( ibc_par_b == 2 )  THEN
4520!
4521!--             Particle reflection
4522                particles(n)%z       = 2.0_wp * zw(0) - particles(n)%z
4523                particles(n)%speed_z = -particles(n)%speed_z
4524                IF ( use_sgs_for_particles  .AND. &
4525                     particles(n)%rvar3 < 0.0_wp )  THEN
4526                   particles(n)%rvar3 = -particles(n)%rvar3
4527                ENDIF
4528             ELSEIF ( ibc_par_b == 3 )  THEN
4529!
4530!--             Find reset height. @note this works only in non-strechted cases
4531                particles_top = INT( pst(1) / dz(1) )
4532                index_reset = MINLOC( prt_count(nzb+1:particles_top,j,i), DIM = 1 )
4533                reset_top = zu(index_reset)
4534                iran_part = iran_part + myid
4535                ran_val = random_function( iran_part )
4536                particles(n)%z       = reset_top *  ( 1.0  + ( ran_val / 10.0_wp) )
4537                particles(n)%speed_z = 0.0_wp
4538                IF ( curvature_solution_effects )  THEN
4539                   particles(n)%radius = particles(n)%aux1
4540                ELSE
4541                   particles(n)%radius = 1.0E-8
4542                ENDIF
4543             ENDIF
4544          ENDIF
4545       ENDDO
4546
4547      CASE ( 'walls' )
4548
4549       CALL cpu_log( log_point_s(48), 'lpm_wall_reflect', 'start' )
4550
4551       DO  n = 1, number_of_particles
4552!
4553!--       Recalculate particle timestep
4554          dt_particle = particles(n)%age - particles(n)%age_m
4555!
4556!--       Obtain x/y indices for current particle position
4557          i2 = particles(n)%x * ddx
4558          j2 = particles(n)%y * ddy
4559          IF ( zw(k)   < particles(n)%z ) k2 = k + 1
4560          IF ( zw(k)   > particles(n)%z  .AND.  zw(k-1) < particles(n)%z ) k2 = k
4561          IF ( zw(k-1) > particles(n)%z ) k2 = k - 1
4562!
4563!--       Save current particle positions
4564          prt_x = particles(n)%x
4565          prt_y = particles(n)%y
4566          prt_z = particles(n)%z
4567!
4568!--       Recalculate old particle positions
4569          pos_x_old = particles(n)%x - particles(n)%speed_x * dt_particle
4570          pos_y_old = particles(n)%y - particles(n)%speed_y * dt_particle
4571          pos_z_old = particles(n)%z - particles(n)%speed_z * dt_particle
4572!
4573!--       Obtain x/y indices for old particle positions
4574          i1 = i
4575          j1 = j
4576          k1 = k
4577!
4578!--       Determine horizontal as well as vertical walls at which particle can
4579!--       be potentially reflected.
4580!--       Start with walls aligned in yz layer.
4581!--       Wall to the right
4582          IF ( prt_x > pos_x_old )  THEN
4583             xwall = ( i1 + 1 ) * dx
4584!
4585!--       Wall to the left
4586          ELSE
4587             xwall = i1 * dx
4588          ENDIF
4589!
4590!--       Walls aligned in xz layer
4591!--       Wall to the north
4592          IF ( prt_y > pos_y_old )  THEN
4593             ywall = ( j1 + 1 ) * dy
4594!--       Wall to the south
4595          ELSE
4596             ywall = j1 * dy
4597          ENDIF
4598
4599          IF ( prt_z > pos_z_old )  THEN
4600             zwall = zw(k)
4601          ELSE
4602             zwall = zw(k-1)
4603          ENDIF
4604!
4605!--       Initialize flags to check if particle reflection is necessary
4606          cross_wall_x = .FALSE.
4607          cross_wall_y = .FALSE.
4608          cross_wall_z = .FALSE.
4609!
4610!--       Initialize flags to check if a wall is reached
4611          reach_x      = .FALSE.
4612          reach_y      = .FALSE.
4613          reach_z      = .FALSE.
4614!
4615!--       Initialize flags to check if a particle was already reflected
4616          reflect_x    = .FALSE.
4617          reflect_y    = .FALSE.
4618          reflect_z    = .FALSE.
4619!
4620!--       Initialize flags to check if a wall is already crossed.
4621!--       ( Required to obtain correct indices. )
4622          x_wall_reached = .FALSE.
4623          y_wall_reached = .FALSE.
4624          z_wall_reached = .FALSE.
4625!
4626!--       Initialize time array
4627          t     = 0.0_wp
4628!
4629!--       Check if particle can reach any wall. This case, calculate the
4630!--       fractional time needed to reach this wall. Store this fractional
4631!--       timestep in array t. Moreover, store indices for these grid
4632!--       boxes where the respective wall belongs to. 
4633!--       Start with x-direction.
4634          t_index    = 1
4635          t(t_index) = ( xwall - pos_x_old )                                   &
4636                     / MERGE( MAX( prt_x - pos_x_old,  1E-30_wp ),             &
4637                              MIN( prt_x - pos_x_old, -1E-30_wp ),             &
4638                              prt_x > pos_x_old )
4639          x_ind(t_index)   = i2
4640          y_ind(t_index)   = j1
4641          z_ind(t_index)   = k1
4642          reach_x(t_index) = .TRUE.
4643          reach_y(t_index) = .FALSE.
4644          reach_z(t_index) = .FALSE.
4645!
4646!--       Store these values only if particle really reaches any wall. t must
4647!--       be in a interval between [0:1].
4648          IF ( t(t_index) <= 1.0_wp  .AND.  t(t_index) >= 0.0_wp )  THEN
4649             t_index      = t_index + 1
4650             cross_wall_x = .TRUE.
4651          ENDIF
4652!
4653!--       y-direction
4654          t(t_index) = ( ywall - pos_y_old )                                   &
4655                     / MERGE( MAX( prt_y - pos_y_old,  1E-30_wp ),             &
4656                              MIN( prt_y - pos_y_old, -1E-30_wp ),             &
4657                              prt_y > pos_y_old )
4658          x_ind(t_index)   = i1
4659          y_ind(t_index)   = j2
4660          z_ind(t_index)   = k1
4661          reach_x(t_index) = .FALSE.
4662          reach_y(t_index) = .TRUE.
4663          reach_z(t_index) = .FALSE.
4664          IF ( t(t_index) <= 1.0_wp  .AND.  t(t_index) >= 0.0_wp )  THEN
4665             t_index      = t_index + 1
4666             cross_wall_y = .TRUE.
4667          ENDIF
4668!
4669!--       z-direction
4670          t(t_index) = (zwall - pos_z_old )                                    &
4671                     / MERGE( MAX( prt_z - pos_z_old,  1E-30_wp ),             &
4672                              MIN( prt_z - pos_z_old, -1E-30_wp ),             &
4673                              prt_z > pos_z_old )
4674
4675          x_ind(t_index)   = i1
4676          y_ind(t_index)   = j1
4677          z_ind(t_index)   = k2
4678          reach_x(t_index) = .FALSE.
4679          reach_y(t_index) = .FALSE.
4680          reach_z(t_index) = .TRUE.
4681          IF( t(t_index) <= 1.0_wp  .AND.  t(t_index) >= 0.0_wp)  THEN
4682             t_index      = t_index + 1
4683             cross_wall_z = .TRUE.
4684          ENDIF
4685
4686          t_index_number = t_index - 1
4687!
4688!--       Carry out reflection only if particle reaches any wall
4689          IF ( cross_wall_x  .OR.  cross_wall_y  .OR.  cross_wall_z )  THEN
4690!
4691!--          Sort fractional timesteps in ascending order. Also sort the
4692!--          corresponding indices and flag according to the time interval a 
4693!--          particle reaches the respective wall.
4694             inc = 1
4695             jr  = 1
4696             DO WHILE ( inc <= t_index_number )
4697                inc = 3 * inc + 1
4698             ENDDO
4699
4700             DO WHILE ( inc > 1 )
4701                inc = inc / 3
4702                DO  ir = inc+1, t_index_number
4703                   tmp_t       = t(ir)
4704                   tmp_x       = x_ind(ir)
4705                   tmp_y       = y_ind(ir)
4706                   tmp_z       = z_ind(ir)
4707                   tmp_reach_x = reach_x(ir)
4708                   tmp_reach_y = reach_y(ir)
4709                   tmp_reach_z = reach_z(ir)
4710                   jr    = ir
4711                   DO WHILE ( t(jr-inc) > tmp_t )
4712                      t(jr)       = t(jr-inc)
4713                      x_ind(jr)   = x_ind(jr-inc)
4714                      y_ind(jr)   = y_ind(jr-inc)
4715                      z_ind(jr)   = z_ind(jr-inc)
4716                      reach_x(jr) = reach_x(jr-inc)
4717                      reach_y(jr) = reach_y(jr-inc)
4718                      reach_z(jr) = reach_z(jr-inc)
4719                      jr    = jr - inc
4720                      IF ( jr <= inc )  EXIT
4721                   ENDDO
4722                   t(jr)       = tmp_t
4723                   x_ind(jr)   = tmp_x
4724                   y_ind(jr)   = tmp_y
4725                   z_ind(jr)   = tmp_z
4726                   reach_x(jr) = tmp_reach_x
4727                   reach_y(jr) = tmp_reach_y
4728                   reach_z(jr) = tmp_reach_z
4729                ENDDO
4730             ENDDO
4731!
4732!--          Initialize temporary particle positions
4733             pos_x = pos_x_old
4734             pos_y = pos_y_old
4735             pos_z = pos_z_old
4736!
4737!--          Loop over all times a particle possibly moves into a new grid box
4738             t_old = 0.0_wp
4739             DO t_index = 1, t_index_number 
4740!
4741!--             Calculate intermediate particle position according to the
4742!--             timesteps a particle reaches any wall.
4743                pos_x = pos_x + ( t(t_index) - t_old ) * dt_particle           &
4744                                                       * particles(n)%speed_x
4745                pos_y = pos_y + ( t(t_index) - t_old ) * dt_particle           &
4746                                                       * particles(n)%speed_y
4747                pos_z = pos_z + ( t(t_index) - t_old ) * dt_particle           &
4748                                                       * particles(n)%speed_z
4749!
4750!--             Obtain x/y grid indices for intermediate particle position from
4751!--             sorted index array
4752                i3 = x_ind(t_index)
4753                j3 = y_ind(t_index)
4754                k3 = z_ind(t_index)
4755!
4756!--             Check which wall is already reached
4757                IF ( .NOT. x_wall_reached )  x_wall_reached = reach_x(t_index) 
4758                IF ( .NOT. y_wall_reached )  y_wall_reached = reach_y(t_index)
4759                IF ( .NOT. z_wall_reached )  z_wall_reached = reach_z(t_index)
4760!
4761!--             Check if a particle needs to be reflected at any yz-wall. If
4762!--             necessary, carry out reflection. Please note, a security
4763!--             constant is required, as the particle position does not
4764!--             necessarily exactly match the wall location due to rounding
4765!--             errors.
4766                IF ( reach_x(t_index)                      .AND.               & 
4767                     ABS( pos_x - xwall ) < eps            .AND.               &
4768                     .NOT. BTEST(wall_flags_static_0(k3,j3,i3),0) .AND.               &
4769                     .NOT. reflect_x )  THEN
4770!
4771!
4772!--                Reflection in x-direction.
4773!--                Ensure correct reflection by MIN/MAX functions, depending on
4774!--                direction of particle transport.
4775!--                Due to rounding errors pos_x does not exactly match the wall
4776!--                location, leading to erroneous reflection.             
4777                   pos_x = MERGE( MIN( 2.0_wp * xwall - pos_x, xwall ),        &
4778                                  MAX( 2.0_wp * xwall - pos_x, xwall ),        &
4779                                  particles(n)%x > xwall )
4780!
4781!--                Change sign of particle speed                     
4782                   particles(n)%speed_x = - particles(n)%speed_x
4783!
4784!--                Also change sign of subgrid-scale particle speed
4785                   particles(n)%rvar1 = - particles(n)%rvar1
4786!
4787!--                Set flag that reflection along x is already done
4788                   reflect_x          = .TRUE.
4789!
4790!--                As the particle does not cross any further yz-wall during
4791!--                this timestep, set further x-indices to the current one.
4792                   x_ind(t_index:t_index_number) = i1
4793!
4794!--             If particle already reached the wall but was not reflected,
4795!--             set further x-indices to the new one.
4796                ELSEIF ( x_wall_reached .AND. .NOT. reflect_x )  THEN
4797                    x_ind(t_index:t_index_number) = i2
4798                ENDIF !particle reflection in x direction done
4799
4800!
4801!--             Check if a particle needs to be reflected at any xz-wall. If
4802!--             necessary, carry out reflection. Please note, a security
4803!--             constant is required, as the particle position does not
4804!--             necessarily exactly match the wall location due to rounding
4805!--             errors.
4806                IF ( reach_y(t_index)                      .AND.               & 
4807                     ABS( pos_y - ywall ) < eps            .AND.               &
4808                     .NOT. BTEST(wall_flags_static_0(k3,j3,i3),0) .AND.               &
4809                     .NOT. reflect_y )  THEN
4810!
4811!
4812!--                Reflection in y-direction.
4813!--                Ensure correct reflection by MIN/MAX functions, depending on
4814!--                direction of particle transport.
4815!--                Due to rounding errors pos_y does not exactly match the wall
4816!--                location, leading to erroneous reflection.             
4817                   pos_y = MERGE( MIN( 2.0_wp * ywall - pos_y, ywall ),        &
4818                                  MAX( 2.0_wp * ywall - pos_y, ywall ),        &
4819                                  particles(n)%y > ywall )
4820!
4821!--                Change sign of particle speed                     
4822                   particles(n)%speed_y = - particles(n)%speed_y
4823!
4824!--                Also change sign of subgrid-scale particle speed
4825                   particles(n)%rvar2 = - particles(n)%rvar2
4826!
4827!--                Set flag that reflection along y is already done
4828                   reflect_y          = .TRUE.
4829!
4830!--                As the particle does not cross any further xz-wall during
4831!--                this timestep, set further y-indices to the current one.
4832                   y_ind(t_index:t_index_number) = j1
4833!
4834!--             If particle already reached the wall but was not reflected,
4835!--             set further y-indices to the new one.
4836                ELSEIF ( y_wall_reached .AND. .NOT. reflect_y )  THEN
4837                    y_ind(t_index:t_index_number) = j2
4838                ENDIF !particle reflection in y direction done
4839
4840!
4841!--             Check if a particle needs to be reflected at any xy-wall. If
4842!--             necessary, carry out reflection. Please note, a security
4843!--             constant is required, as the particle position does not
4844!--             necessarily exactly match the wall location due to rounding
4845!--             errors.
4846                IF ( reach_z(t_index)                      .AND.               & 
4847                     ABS( pos_z - zwall ) < eps            .AND.               &
4848                     .NOT. BTEST(wall_flags_static_0(k3,j3,i3),0) .AND.               &
4849                     .NOT. reflect_z )  THEN
4850!
4851!
4852!--                Reflection in z-direction.
4853!--                Ensure correct reflection by MIN/MAX functions, depending on
4854!--                direction of particle transport.
4855!--                Due to rounding errors pos_z does not exactly match the wall
4856!--                location, leading to erroneous reflection.             
4857                   pos_z = MERGE( MIN( 2.0_wp * zwall - pos_z, zwall ),        &
4858                                  MAX( 2.0_wp * zwall - pos_z, zwall ),        &
4859                                  particles(n)%z > zwall )
4860!
4861!--                Change sign of particle speed                     
4862                   particles(n)%speed_z = - particles(n)%speed_z
4863!
4864!--                Also change sign of subgrid-scale particle speed
4865                   particles(n)%rvar3 = - particles(n)%rvar3
4866!
4867!--                Set flag that reflection along z is already done
4868                   reflect_z          = .TRUE.
4869!
4870!--                As the particle does not cross any further xy-wall during
4871!--                this timestep, set further z-indices to the current one.
4872                   z_ind(t_index:t_index_number) = k1
4873!
4874!--             If particle already reached the wall but was not reflected,
4875!--             set further z-indices to the new one.
4876                ELSEIF ( z_wall_reached .AND. .NOT. reflect_z )  THEN
4877                    z_ind(t_index:t_index_number) = k2
4878                ENDIF !particle reflection in z direction done               
4879
4880!
4881!--             Swap time
4882                t_old = t(t_index)
4883
4884             ENDDO
4885!
4886!--          If a particle was reflected, calculate final position from last
4887!--          intermediate position.
4888             IF ( reflect_x  .OR.  reflect_y  .OR.  reflect_z )  THEN
4889
4890                particles(n)%x = pos_x + ( 1.0_wp - t_old ) * dt_particle      &
4891                                                         * particles(n)%speed_x
4892                particles(n)%y = pos_y + ( 1.0_wp - t_old ) * dt_particle      &
4893                                                         * particles(n)%speed_y
4894                particles(n)%z = pos_z + ( 1.0_wp - t_old ) * dt_particle      &
4895                                                         * particles(n)%speed_z
4896
4897             ENDIF
4898
4899          ENDIF
4900
4901       ENDDO
4902
4903       CALL cpu_log( log_point_s(48), 'lpm_wall_reflect', 'stop' )
4904
4905       CASE DEFAULT
4906          CONTINUE
4907
4908    END SELECT
4909
4910 END SUBROUTINE lpm_boundary_conds 
4911
4912
4913!------------------------------------------------------------------------------!
4914! Description:
4915! ------------
4916!> Calculates change in droplet radius by condensation/evaporation, using
4917!> either an analytic formula or by numerically integrating the radius growth
4918!> equation including curvature and solution effects using Rosenbrocks method
4919!> (see Numerical recipes in FORTRAN, 2nd edition, p. 731).
4920!> The analytical formula and growth equation follow those given in
4921!> Rogers and Yau (A short course in cloud physics, 3rd edition, p. 102/103).
4922!------------------------------------------------------------------------------!
4923 SUBROUTINE lpm_droplet_condensation (i,j,k)
4924
4925    INTEGER(iwp), INTENT(IN) ::  i              !<
4926    INTEGER(iwp), INTENT(IN) ::  j              !<
4927    INTEGER(iwp), INTENT(IN) ::  k              !<
4928    INTEGER(iwp) ::  n                          !<
4929
4930    REAL(wp) ::  afactor                       !< curvature effects
4931    REAL(wp) ::  arg                           !<
4932    REAL(wp) ::  bfactor                       !< solute effects
4933    REAL(wp) ::  ddenom                        !<
4934    REAL(wp) ::  delta_r                       !<
4935    REAL(wp) ::  diameter                      !< diameter of cloud droplets
4936    REAL(wp) ::  diff_coeff                    !< diffusivity for water vapor
4937    REAL(wp) ::  drdt                          !<
4938    REAL(wp) ::  dt_ros                        !<
4939    REAL(wp) ::  dt_ros_sum                    !<
4940    REAL(wp) ::  d2rdtdr                       !<
4941    REAL(wp) ::  e_a                           !< current vapor pressure
4942    REAL(wp) ::  e_s                           !< current saturation vapor pressure
4943    REAL(wp) ::  error                         !< local truncation error in Rosenbrock
4944    REAL(wp) ::  k1                            !<
4945    REAL(wp) ::  k2                            !<
4946    REAL(wp) ::  r_err                         !< First order estimate of Rosenbrock radius
4947    REAL(wp) ::  r_ros                         !< Rosenbrock radius
4948    REAL(wp) ::  r_ros_ini                     !< initial Rosenbrock radius
4949    REAL(wp) ::  r0                            !< gas-kinetic lengthscale
4950    REAL(wp) ::  sigma                         !< surface tension of water
4951    REAL(wp) ::  thermal_conductivity          !< thermal conductivity for water
4952    REAL(wp) ::  t_int                         !< temperature
4953    REAL(wp) ::  w_s                           !< terminal velocity of droplets
4954    REAL(wp) ::  re_p                          !< particle Reynolds number
4955!
4956!-- Parameters for Rosenbrock method (see Verwer et al., 1999)
4957    REAL(wp), PARAMETER ::  prec = 1.0E-3_wp     !< precision of Rosenbrock solution
4958    REAL(wp), PARAMETER ::  q_increase = 1.5_wp  !< increase factor in timestep
4959    REAL(wp), PARAMETER ::  q_decrease = 0.9_wp  !< decrease factor in timestep
4960    REAL(wp), PARAMETER ::  gamma = 0.292893218814_wp !< = 1.0 - 1.0 / SQRT(2.0)
4961!
4962!-- Parameters for terminal velocity
4963    REAL(wp), PARAMETER ::  a_rog = 9.65_wp      !< parameter for fall velocity
4964    REAL(wp), PARAMETER ::  b_rog = 10.43_wp     !< parameter for fall velocity
4965    REAL(wp), PARAMETER ::  c_rog = 0.6_wp       !< parameter for fall velocity
4966    REAL(wp), PARAMETER ::  k_cap_rog = 4.0_wp   !< parameter for fall velocity
4967    REAL(wp), PARAMETER ::  k_low_rog = 12.0_wp  !< parameter for fall velocity
4968    REAL(wp), PARAMETER ::  d0_rog = 0.745_wp    !< separation diameter
4969
4970    REAL(wp), DIMENSION(number_of_particles) ::  ventilation_effect     !<
4971    REAL(wp), DIMENSION(number_of_particles) ::  new_r                  !<
4972
4973    CALL cpu_log( log_point_s(42), 'lpm_droplet_condens', 'start' )
4974
4975!
4976!-- Absolute temperature
4977    t_int = pt(k,j,i) * exner(k)
4978!
4979!-- Saturation vapor pressure (Eq. 10 in Bolton, 1980)
4980    e_s = magnus( t_int )
4981!
4982!-- Current vapor pressure
4983    e_a = q(k,j,i) * hyp(k) / ( q(k,j,i) + rd_d_rv )
4984!
4985!-- Thermal conductivity for water (from Rogers and Yau, Table 7.1)
4986    thermal_conductivity = 7.94048E-05_wp * t_int + 0.00227011_wp
4987!
4988!-- Moldecular diffusivity of water vapor in air (Hall und Pruppacher, 1976)
4989    diff_coeff           = 0.211E-4_wp * ( t_int / 273.15_wp )**1.94_wp * &
4990                           ( 101325.0_wp / hyp(k) )
4991!
4992!-- Lengthscale for gas-kinetic effects (from Mordy, 1959, p. 23):
4993    r0 = diff_coeff / 0.036_wp * SQRT( 2.0_wp * pi / ( r_v * t_int ) )
4994!
4995!-- Calculate effects of heat conductivity and diffusion of water vapor on the
4996!-- diffusional growth process (usually known as 1.0 / (F_k + F_d) )
4997    ddenom  = 1.0_wp / ( rho_l * r_v * t_int / ( e_s * diff_coeff ) +          &
4998                         ( l_v / ( r_v * t_int ) - 1.0_wp ) * rho_l *          &
4999                         l_v / ( thermal_conductivity * t_int )                &
5000                       )
5001    new_r = 0.0_wp
5002!
5003!-- Determine ventilation effect on evaporation of large drops
5004    DO  n = 1, number_of_particles
5005
5006       IF ( particles(n)%radius >= 4.0E-5_wp  .AND.  e_a / e_s < 1.0_wp )  THEN
5007!
5008!--       Terminal velocity is computed for vertical direction (Rogers et al.,
5009!--       1993, J. Appl. Meteorol.)
5010          diameter = particles(n)%radius * 2000.0_wp !diameter in mm
5011          IF ( diameter <= d0_rog )  THEN
5012             w_s = k_cap_rog * diameter * ( 1.0_wp - EXP( -k_low_rog * diameter ) )
5013          ELSE
5014             w_s = a_rog - b_rog * EXP( -c_rog * diameter )
5015          ENDIF
5016!
5017!--       Calculate droplet's Reynolds number
5018          re_p = 2.0_wp * particles(n)%radius * w_s / molecular_viscosity
5019!
5020!--       Ventilation coefficient (Rogers and Yau, 1989):
5021          IF ( re_p > 2.5_wp )  THEN
5022             ventilation_effect(n) = 0.78_wp + 0.28_wp * SQRT( re_p )
5023          ELSE
5024             ventilation_effect(n) = 1.0_wp + 0.09_wp * re_p
5025          ENDIF
5026       ELSE
5027!
5028!--       For small droplets or in supersaturated environments, the ventilation
5029!--       effect does not play a role
5030          ventilation_effect(n) = 1.0_wp
5031       ENDIF
5032    ENDDO
5033
5034    IF( .NOT. curvature_solution_effects )  THEN
5035!
5036!--    Use analytic model for diffusional growth including gas-kinetic
5037!--    effects (Mordy, 1959) but without the impact of aerosols.
5038       DO  n = 1, number_of_particles
5039          arg      = ( particles(n)%radius + r0 )**2 + 2.0_wp * dt_3d * ddenom * &
5040                                                       ventilation_effect(n) *   &
5041                                                       ( e_a / e_s - 1.0_wp )
5042          arg      = MAX( arg, ( 0.01E-6 + r0 )**2 )
5043          new_r(n) = SQRT( arg ) - r0
5044       ENDDO
5045
5046    ELSE
5047!
5048!--    Integrate the diffusional growth including gas-kinetic (Mordy, 1959),
5049!--    as well as curvature and solute effects (e.g., Köhler, 1936).
5050!
5051!--    Curvature effect (afactor) with surface tension (sigma) by Straka (2009)
5052       sigma = 0.0761_wp - 0.000155_wp * ( t_int - 273.15_wp )
5053!
5054!--    Solute effect (afactor)
5055       afactor = 2.0_wp * sigma / ( rho_l * r_v * t_int )
5056
5057       DO  n = 1, number_of_particles
5058!
5059!--       Solute effect (bfactor)
5060          bfactor = vanthoff * rho_s * particles(n)%aux1**3 *                    &
5061                    molecular_weight_of_water / ( rho_l * molecular_weight_of_solute )
5062
5063          dt_ros     = particles(n)%aux2  ! use previously stored Rosenbrock timestep
5064          dt_ros_sum = 0.0_wp
5065
5066          r_ros     = particles(n)%radius  ! initialize Rosenbrock particle radius
5067          r_ros_ini = r_ros
5068!
5069!--       Integrate growth equation using a 2nd-order Rosenbrock method
5070!--       (see Verwer et al., 1999, Eq. (3.2)). The Rosenbrock method adjusts
5071!--       its with internal timestep to minimize the local truncation error.
5072          DO WHILE ( dt_ros_sum < dt_3d )
5073
5074             dt_ros = MIN( dt_ros, dt_3d - dt_ros_sum )
5075
5076             DO
5077
5078                drdt = ddenom * ventilation_effect(n) * ( e_a / e_s - 1.0_wp - &
5079                                                          afactor / r_ros +    &
5080                                                          bfactor / r_ros**3   &
5081                                                        ) / ( r_ros + r0 )
5082
5083                d2rdtdr = -ddenom * ventilation_effect(n) * (                  &
5084                                            (e_a / e_s - 1.0_wp ) * r_ros**4 - &
5085                                            afactor * r0 * r_ros**2 -          &
5086                                            2.0_wp * afactor * r_ros**3 +      &
5087                                            3.0_wp * bfactor * r0 +            &
5088                                            4.0_wp * bfactor * r_ros           &
5089                                                            )                  &
5090                          / ( r_ros**4 * ( r_ros + r0 )**2 )
5091
5092                k1    = drdt / ( 1.0_wp - gamma * dt_ros * d2rdtdr )
5093
5094                r_ros = MAX(r_ros_ini + k1 * dt_ros, particles(n)%aux1)
5095                r_err = r_ros
5096
5097                drdt  = ddenom * ventilation_effect(n) * ( e_a / e_s - 1.0_wp - &
5098                                                           afactor / r_ros +    &
5099                                                           bfactor / r_ros**3   &
5100                                                         ) / ( r_ros + r0 )
5101
5102                k2 = ( drdt - dt_ros * 2.0 * gamma * d2rdtdr * k1 ) / &
5103                     ( 1.0_wp - dt_ros * gamma * d2rdtdr )
5104
5105                r_ros = MAX(r_ros_ini + dt_ros * ( 1.5_wp * k1 + 0.5_wp * k2), particles(n)%aux1)
5106   !
5107   !--          Check error of the solution, and reduce dt_ros if necessary.
5108                error = ABS(r_err - r_ros) / r_ros
5109                IF ( error > prec )  THEN
5110                   dt_ros = SQRT( q_decrease * prec / error ) * dt_ros
5111                   r_ros  = r_ros_ini
5112                ELSE
5113                   dt_ros_sum = dt_ros_sum + dt_ros
5114                   dt_ros     = q_increase * dt_ros
5115                   r_ros_ini  = r_ros
5116                   EXIT
5117                ENDIF
5118
5119             END DO
5120
5121          END DO !Rosenbrock loop
5122!
5123!--       Store new particle radius
5124          new_r(n) = r_ros
5125!
5126!--       Store internal time step value for next PALM step
5127          particles(n)%aux2 = dt_ros
5128
5129       ENDDO !Particle loop
5130
5131    ENDIF
5132
5133    DO  n = 1, number_of_particles
5134!
5135!--    Sum up the change in liquid water for the respective grid
5136!--    box for the computation of the release/depletion of water vapor
5137!--    and heat.
5138       ql_c(k,j,i) = ql_c(k,j,i) + particles(n)%weight_factor *          &
5139                                   rho_l * 1.33333333_wp * pi *                &
5140                                   ( new_r(n)**3 - particles(n)%radius**3 ) /  &
5141                                   ( rho_surface * dx * dy * dzw(k) )
5142!
5143!--    Check if the increase in liqid water is not too big. If this is the case,
5144!--    the model timestep might be too long.
5145       IF ( ql_c(k,j,i) > 100.0_wp )  THEN
5146          WRITE( message_string, * ) 'k=',k,' j=',j,' i=',i,                &
5147                       ' ql_c=',ql_c(k,j,i), '&part(',n,')%wf=',            &
5148                       particles(n)%weight_factor,' delta_r=',delta_r
5149          CALL message( 'lpm_droplet_condensation', 'PA0143', 2, 2, -1, 6, 1 )
5150       ENDIF
5151!
5152!--    Check if the change in the droplet radius is not too big. If this is the
5153!--    case, the model timestep might be too long.
5154       delta_r = new_r(n) - particles(n)%radius
5155       IF ( delta_r < 0.0_wp  .AND.  new_r(n) < 0.0_wp )  THEN
5156          WRITE( message_string, * ) '#1 k=',k,' j=',j,' i=',i,                &
5157                       ' e_s=',e_s, ' e_a=',e_a,' t_int=',t_int,               &
5158                       '&delta_r=',delta_r,                                    &
5159                       ' particle_radius=',particles(n)%radius
5160          CALL message( 'lpm_droplet_condensation', 'PA0144', 2, 2, -1, 6, 1 )
5161       ENDIF
5162!
5163!--    Sum up the total volume of liquid water (needed below for
5164!--    re-calculating the weighting factors)
5165       ql_v(k,j,i) = ql_v(k,j,i) + particles(n)%weight_factor * new_r(n)**3
5166!
5167!--    Determine radius class of the particle needed for collision
5168       IF ( use_kernel_tables )  THEN
5169          particles(n)%class = ( LOG( new_r(n) ) - rclass_lbound ) /           &
5170                               ( rclass_ubound - rclass_lbound ) *             &
5171                               radius_classes
5172          particles(n)%class = MIN( particles(n)%class, radius_classes )
5173          particles(n)%class = MAX( particles(n)%class, 1 )
5174       ENDIF
5175!
5176!--    Store new radius to particle features
5177       particles(n)%radius = new_r(n)
5178
5179    ENDDO
5180
5181    CALL cpu_log( log_point_s(42), 'lpm_droplet_condens', 'stop' )
5182
5183
5184 END SUBROUTINE lpm_droplet_condensation
5185
5186
5187!------------------------------------------------------------------------------!
5188! Description:
5189! ------------
5190!> Release of latent heat and change of mixing ratio due to condensation /
5191!> evaporation of droplets.
5192!------------------------------------------------------------------------------!
5193 SUBROUTINE lpm_interaction_droplets_ptq
5194
5195    INTEGER(iwp) ::  i    !< running index x direction
5196    INTEGER(iwp) ::  j    !< running index y direction
5197    INTEGER(iwp) ::  k    !< running index z direction
5198
5199    REAL(wp) ::  flag     !< flag to mask topography grid points
5200
5201    DO  i = nxl, nxr
5202       DO  j = nys, nyn
5203          DO  k = nzb+1, nzt
5204!
5205!--          Predetermine flag to mask topography
5206             flag = MERGE( 1.0_wp, 0.0_wp, BTEST( wall_flags_static_0(k,j,i), 0 ) )
5207
5208             q(k,j,i)  = q_p(k,j,i)  - ql_c(k,j,i) * flag
5209             pt(k,j,i) = pt(k,j,i) + lv_d_cp * ql_c(k,j,i) * d_exner(k) &
5210                                                           * flag
5211          ENDDO
5212       ENDDO
5213    ENDDO
5214
5215 END SUBROUTINE lpm_interaction_droplets_ptq
5216
5217
5218!------------------------------------------------------------------------------!
5219! Description:
5220! ------------
5221!> Release of latent heat and change of mixing ratio due to condensation /
5222!> evaporation of droplets. Call for grid point i,j
5223!------------------------------------------------------------------------------!
5224 SUBROUTINE lpm_interaction_droplets_ptq_ij( i, j )
5225
5226    INTEGER(iwp) ::  i    !< running index x direction
5227    INTEGER(iwp) ::  j    !< running index y direction
5228    INTEGER(iwp) ::  k    !< running index z direction
5229
5230    REAL(wp) ::  flag     !< flag to mask topography grid points
5231
5232
5233    DO  k = nzb+1, nzt
5234!
5235!--    Predetermine flag to mask topography
5236       flag = MERGE( 1.0_wp, 0.0_wp, BTEST( wall_flags_static_0(k,j,i), 0 ) )
5237
5238       q(k,j,i)  = q(k,j,i)  - ql_c(k,j,i) * flag
5239       pt(k,j,i) = pt(k,j,i) + lv_d_cp * ql_c(k,j,i) * d_exner(k) * flag
5240    ENDDO
5241
5242 END SUBROUTINE lpm_interaction_droplets_ptq_ij
5243
5244
5245!------------------------------------------------------------------------------!
5246! Description:
5247! ------------
5248!> Calculate the liquid water content for each grid box.
5249!------------------------------------------------------------------------------!
5250 SUBROUTINE lpm_calc_liquid_water_content
5251
5252
5253    INTEGER(iwp) ::  i   !<
5254    INTEGER(iwp) ::  j   !<
5255    INTEGER(iwp) ::  k   !<
5256    INTEGER(iwp) ::  n   !<
5257
5258    CALL cpu_log( log_point_s(45), 'lpm_calc_ql', 'start' )
5259
5260!
5261!-- Set water content initially to zero
5262    ql = 0.0_wp;  ql_v = 0.0_wp;  ql_vp = 0.0_wp
5263
5264!
5265!-- Calculate for each grid box
5266    DO  i = nxl, nxr
5267       DO  j = nys, nyn
5268          DO  k = nzb+1, nzt
5269             number_of_particles = prt_count(k,j,i)
5270             IF ( number_of_particles <= 0 )  CYCLE
5271             particles => grid_particles(k,j,i)%particles(1:number_of_particles)
5272!
5273!--          Calculate the total volume in the boxes (ql_v, weighting factor
5274!--          has to beincluded)
5275             DO  n = 1, prt_count(k,j,i)
5276                ql_v(k,j,i)  = ql_v(k,j,i)  + particles(n)%weight_factor *     &
5277                                              particles(n)%radius**3
5278             ENDDO
5279!
5280!--          Calculate the liquid water content
5281             IF ( ql_v(k,j,i) /= 0.0_wp )  THEN
5282                ql(k,j,i) = ql(k,j,i) + rho_l * 1.33333333_wp * pi *           &
5283                                        ql_v(k,j,i) /                          &
5284                                        ( rho_surface * dx * dy * dzw(k) )
5285                IF ( ql(k,j,i) < 0.0_wp )  THEN
5286                   WRITE( message_string, * )  'LWC out of range: ' , &
5287                                               ql(k,j,i),i,j,k
5288                   CALL message( 'lpm_calc_liquid_water_content', '', 2, 2,    &
5289                                 -1, 6, 1 )
5290                ENDIF
5291             ELSE
5292                ql(k,j,i) = 0.0_wp
5293             ENDIF
5294          ENDDO
5295       ENDDO
5296    ENDDO
5297
5298    CALL cpu_log( log_point_s(45), 'lpm_calc_ql', 'stop' )
5299
5300 END SUBROUTINE lpm_calc_liquid_water_content
5301
5302
5303!------------------------------------------------------------------------------!
5304! Description:
5305! ------------
5306!> Calculates change in droplet radius by collision. Droplet collision is
5307!> calculated for each grid box seperately. Collision is parameterized by
5308!> using collision kernels. Two different kernels are available:
5309!> Hall kernel: Kernel from Hall (1980, J. Atmos. Sci., 2486-2507), which
5310!>              considers collision due to pure gravitational effects.
5311!> Wang kernel: Beside gravitational effects (treated with the Hall-kernel) also
5312!>              the effects of turbulence on the collision are considered using
5313!>              parameterizations of Ayala et al. (2008, New J. Phys., 10,
5314!>              075015) and Wang and Grabowski (2009, Atmos. Sci. Lett., 10,
5315!>              1-8). This kernel includes three possible effects of turbulence:
5316!>              the modification of the relative velocity between the droplets,
5317!>              the effect of preferential concentration, and the enhancement of
5318!>              collision efficiencies.
5319!------------------------------------------------------------------------------!
5320 SUBROUTINE lpm_droplet_collision (i,j,k)
5321
5322    INTEGER(iwp), INTENT(IN) ::  i        !<
5323    INTEGER(iwp), INTENT(IN) ::  j        !<
5324    INTEGER(iwp), INTENT(IN) ::  k        !<
5325
5326    INTEGER(iwp) ::  eclass   !<
5327    INTEGER(iwp) ::  n        !<
5328    INTEGER(iwp) ::  m        !<
5329    INTEGER(iwp) ::  rclass_l !<
5330    INTEGER(iwp) ::  rclass_s !<
5331
5332    REAL(wp) ::  collection_probability  !< probability for collection
5333    REAL(wp) ::  ddV                     !< inverse grid box volume
5334    REAL(wp) ::  epsilon_collision       !< dissipation rate
5335    REAL(wp) ::  factor_volume_to_mass   !< 4.0 / 3.0 * pi * rho_l
5336    REAL(wp) ::  xm                      !< droplet mass of super-droplet m
5337    REAL(wp) ::  xn                      !< droplet mass of super-droplet n
5338    REAL(wp) ::  xsm                     !< aerosol mass of super-droplet m
5339    REAL(wp) ::  xsn                     !< aerosol mass of super-droplet n
5340
5341    REAL(wp), DIMENSION(:), ALLOCATABLE ::  weight    !< weighting factor
5342    REAL(wp), DIMENSION(:), ALLOCATABLE ::  mass      !< total mass of super droplet
5343    REAL(wp), DIMENSION(:), ALLOCATABLE ::  aero_mass !< total aerosol mass of super droplet
5344
5345    CALL cpu_log( log_point_s(43), 'lpm_droplet_coll', 'start' )
5346
5347    number_of_particles   = prt_count(k,j,i)
5348    factor_volume_to_mass = 4.0_wp / 3.0_wp * pi * rho_l
5349    ddV                   = 1.0_wp / ( dx * dy * dzw(k) )
5350!
5351!-- Collision requires at least one super droplet inside the box
5352    IF ( number_of_particles > 0 )  THEN
5353
5354       IF ( use_kernel_tables )  THEN
5355!
5356!--       Fast method with pre-calculated collection kernels for
5357!--       discrete radius- and dissipation-classes.
5358          IF ( wang_kernel )  THEN
5359             eclass = INT( diss(k,j,i) * 1.0E4_wp / 600.0_wp * &
5360                           dissipation_classes ) + 1
5361             epsilon_collision = diss(k,j,i)
5362          ELSE
5363             epsilon_collision = 0.0_wp
5364          ENDIF
5365
5366          IF ( hall_kernel  .OR.  epsilon_collision * 1.0E4_wp < 0.001_wp )  THEN
5367             eclass = 0   ! Hall kernel is used
5368          ELSE
5369             eclass = MIN( dissipation_classes, eclass )
5370          ENDIF
5371
5372       ELSE
5373!
5374!--       Collection kernels are re-calculated for every new
5375!--       grid box. First, allocate memory for kernel table.
5376!--       Third dimension is 1, because table is re-calculated for
5377!--       every new dissipation value.
5378          ALLOCATE( ckernel(1:number_of_particles,1:number_of_particles,1:1) )
5379!
5380!--       Now calculate collection kernel for this box. Note that
5381!--       the kernel is based on the previous time step
5382          CALL recalculate_kernel( i, j, k )
5383
5384       ENDIF
5385!
5386!--    Temporary fields for total mass of super-droplet, aerosol mass, and
5387!--    weighting factor are allocated.
5388       ALLOCATE(mass(1:number_of_particles), weight(1:number_of_particles))
5389       IF ( curvature_solution_effects )  ALLOCATE(aero_mass(1:number_of_particles))
5390
5391       mass(1:number_of_particles)   = particles(1:number_of_particles)%weight_factor * &
5392                                       particles(1:number_of_particles)%radius**3     * &
5393                                       factor_volume_to_mass
5394
5395       weight(1:number_of_particles) = particles(1:number_of_particles)%weight_factor
5396
5397       IF ( curvature_solution_effects )  THEN
5398          aero_mass(1:number_of_particles) = particles(1:number_of_particles)%weight_factor * &
5399                                             particles(1:number_of_particles)%aux1**3       * &
5400                                             4.0_wp / 3.0_wp * pi * rho_s
5401       ENDIF
5402!
5403!--    Calculate collision/coalescence
5404       DO  n = 1, number_of_particles
5405
5406          DO  m = n, number_of_particles
5407!
5408!--          For collisions, the weighting factor of at least one super-droplet
5409!--          needs to be larger or equal to one.
5410             IF ( MIN( weight(n), weight(m) ) < 1.0_wp )  CYCLE
5411!
5412!--          Get mass of individual droplets (aerosols)
5413             xn = mass(n) / weight(n)
5414             xm = mass(m) / weight(m)
5415             IF ( curvature_solution_effects )  THEN
5416                xsn = aero_mass(n) / weight(n)
5417                xsm = aero_mass(m) / weight(m)
5418             ENDIF
5419!
5420!--          Probability that the necessary collisions take place
5421             IF ( use_kernel_tables )  THEN
5422                rclass_l = particles(n)%class
5423                rclass_s = particles(m)%class
5424
5425                collection_probability  = MAX( weight(n), weight(m) ) *     &
5426                                          ckernel(rclass_l,rclass_s,eclass) * ddV * dt_3d
5427             ELSE
5428                collection_probability  = MAX( weight(n), weight(m) ) *     &
5429                                          ckernel(n,m,1) * ddV * dt_3d
5430             ENDIF
5431!
5432!--          Calculate the number of collections and consider multiple collections.
5433!--          (Accordingly, p_crit will be 0.0, 1.0, 2.0, ...)
5434             IF ( collection_probability - FLOOR(collection_probability)    &
5435                  > random_function( iran_part ) )  THEN
5436                collection_probability = FLOOR(collection_probability) + 1.0_wp
5437             ELSE
5438                collection_probability = FLOOR(collection_probability)
5439             ENDIF
5440
5441             IF ( collection_probability > 0.0_wp )  THEN
5442!
5443!--             Super-droplet n collects droplets of super-droplet m
5444                IF ( weight(n) < weight(m) )  THEN
5445
5446                   mass(n)   = mass(n)   + weight(n) * xm * collection_probability
5447                   weight(m) = weight(m) - weight(n)      * collection_probability
5448                   mass(m)   = mass(m)   - weight(n) * xm * collection_probability
5449                   IF ( curvature_solution_effects )  THEN
5450                      aero_mass(n) = aero_mass(n) + weight(n) * xsm * collection_probability
5451                      aero_mass(m) = aero_mass(m) - weight(n) * xsm * collection_probability
5452                   ENDIF
5453
5454                ELSEIF ( weight(m) < weight(n) )  THEN
5455
5456                   mass(m)   = mass(m)   + weight(m) * xn * collection_probability
5457                   weight(n) = weight(n) - weight(m)      * collection_probability
5458                   mass(n)   = mass(n)   - weight(m) * xn * collection_probability
5459                   IF ( curvature_solution_effects )  THEN
5460                      aero_mass(m) = aero_mass(m) + weight(m) * xsn * collection_probability
5461                      aero_mass(n) = aero_mass(n) - weight(m) * xsn * collection_probability
5462                   ENDIF
5463
5464                ELSE
5465!
5466!--                Collisions of particles of the same weighting factor.
5467!--                Particle n collects 1/2 weight(n) droplets of particle m,
5468!--                particle m collects 1/2 weight(m) droplets of particle n.
5469!--                The total mass mass changes accordingly.
5470!--                If n = m, the first half of the droplets coalesces with the
5471!--                second half of the droplets; mass is unchanged because
5472!--                xm = xn for n = m.
5473!--
5474!--                Note: For m = n this equation is an approximation only
5475!--                valid for weight >> 1 (which is usually the case). The
5476!--                approximation is weight(n)-1 = weight(n).
5477                   mass(n)   = mass(n)   + 0.5_wp * weight(n) * ( xm - xn )
5478                   mass(m)   = mass(m)   + 0.5_wp * weight(m) * ( xn - xm )
5479                   IF ( curvature_solution_effects )  THEN
5480                      aero_mass(n) = aero_mass(n) + 0.5_wp * weight(n) * ( xsm - xsn )
5481                      aero_mass(m) = aero_mass(m) + 0.5_wp * weight(m) * ( xsn - xsm )
5482                   ENDIF
5483                   weight(n) = weight(n) - 0.5_wp * weight(m)
5484                   weight(m) = weight(n)
5485
5486                ENDIF
5487
5488             ENDIF
5489
5490          ENDDO
5491
5492          ql_vp(k,j,i) = ql_vp(k,j,i) + mass(n) / factor_volume_to_mass
5493
5494       ENDDO
5495
5496       IF ( ANY(weight < 0.0_wp) )  THEN
5497             WRITE( message_string, * ) 'negative weighting factor'
5498             CALL message( 'lpm_droplet_collision', 'PA0028',      &
5499                            2, 2, -1, 6, 1 )
5500       ENDIF
5501
5502       particles(1:number_of_particles)%radius = ( mass(1:number_of_particles) /   &
5503                                                   ( weight(1:number_of_particles) &
5504                                                     * factor_volume_to_mass       &
5505                                                   )                               &
5506                                                 )**0.33333333333333_wp
5507
5508       IF ( curvature_solution_effects )  THEN
5509          particles(1:number_of_particles)%aux1 = ( aero_mass(1:number_of_particles) / &
5510                                                    ( weight(1:number_of_particles)    &
5511                                                      * 4.0_wp / 3.0_wp * pi * rho_s   &
5512                                                    )                                  &
5513                                                  )**0.33333333333333_wp
5514       ENDIF
5515
5516       particles(1:number_of_particles)%weight_factor = weight(1:number_of_particles)
5517
5518       DEALLOCATE( weight, mass )
5519       IF ( curvature_solution_effects )  DEALLOCATE( aero_mass )
5520       IF ( .NOT. use_kernel_tables )  DEALLOCATE( ckernel )
5521
5522!
5523!--    Check if LWC is conserved during collision process
5524       IF ( ql_v(k,j,i) /= 0.0_wp )  THEN
5525          IF ( ql_vp(k,j,i) / ql_v(k,j,i) >= 1.0001_wp  .OR.                      &
5526               ql_vp(k,j,i) / ql_v(k,j,i) <= 0.9999_wp )  THEN
5527             WRITE( message_string, * ) ' LWC is not conserved during',           &
5528                                        ' collision! ',                           &
5529                                        ' LWC after condensation: ', ql_v(k,j,i), &
5530                                        ' LWC after collision: ', ql_vp(k,j,i)
5531             CALL message( 'lpm_droplet_collision', 'PA0040', 2, 2, -1, 6, 1 )
5532          ENDIF
5533       ENDIF
5534
5535    ENDIF
5536
5537    CALL cpu_log( log_point_s(43), 'lpm_droplet_coll', 'stop' )
5538
5539 END SUBROUTINE lpm_droplet_collision
5540 
5541!------------------------------------------------------------------------------!
5542! Description:
5543! ------------
5544!> Initialization of the collision efficiency matrix with fixed radius and
5545!> dissipation classes, calculated at simulation start only.
5546!------------------------------------------------------------------------------!
5547 SUBROUTINE lpm_init_kernels
5548
5549    INTEGER(iwp) ::  i !<
5550    INTEGER(iwp) ::  j !<
5551    INTEGER(iwp) ::  k !<
5552   
5553!
5554!-- Calculate collision efficiencies for fixed radius- and dissipation
5555!-- classes
5556    IF ( collision_kernel(6:9) == 'fast' )  THEN
5557
5558       ALLOCATE( ckernel(1:radius_classes,1:radius_classes,                 &
5559                 0:dissipation_classes), epsclass(1:dissipation_classes),   &
5560                 radclass(1:radius_classes) )
5561
5562!
5563!--    Calculate the radius class bounds with logarithmic distances
5564!--    in the interval [1.0E-6, 1000.0E-6] m
5565       rclass_lbound = LOG( 1.0E-6_wp )
5566       rclass_ubound = LOG( 1000.0E-6_wp )
5567       radclass(1)   = EXP( rclass_lbound )
5568       DO  i = 2, radius_classes
5569          radclass(i) = EXP( rclass_lbound +                                &
5570                             ( rclass_ubound - rclass_lbound ) *            &
5571                             ( i - 1.0_wp ) / ( radius_classes - 1.0_wp ) )
5572       ENDDO
5573
5574!
5575!--    Set the class bounds for dissipation in interval [0.0, 600.0] cm**2/s**3
5576       DO  i = 1, dissipation_classes
5577          epsclass(i) = 0.06_wp * REAL( i, KIND=wp ) / dissipation_classes
5578       ENDDO
5579!
5580!--    Calculate collision efficiencies of the Wang/ayala kernel
5581       ALLOCATE( ec(1:radius_classes,1:radius_classes),  &
5582                 ecf(1:radius_classes,1:radius_classes), &
5583                 gck(1:radius_classes,1:radius_classes), &
5584                 winf(1:radius_classes) )
5585
5586       DO  k = 1, dissipation_classes
5587
5588          epsilon_collision = epsclass(k)
5589          urms    = 2.02_wp * ( epsilon_collision / 0.04_wp )**( 1.0_wp / 3.0_wp )
5590
5591          CALL turbsd
5592          CALL turb_enhance_eff
5593          CALL effic
5594
5595          DO  j = 1, radius_classes
5596             DO  i = 1, radius_classes
5597                ckernel(i,j,k) = ec(i,j) * gck(i,j) * ecf(i,j)
5598             ENDDO
5599          ENDDO
5600
5601       ENDDO
5602
5603!
5604!--    Calculate collision efficiencies of the Hall kernel
5605       ALLOCATE( hkernel(1:radius_classes,1:radius_classes), &
5606                 hwratio(1:radius_classes,1:radius_classes) )
5607
5608       CALL fallg
5609       CALL effic
5610
5611       DO  j = 1, radius_classes
5612          DO  i =  1, radius_classes
5613             hkernel(i,j) = pi * ( radclass(j) + radclass(i) )**2 &
5614                               * ec(i,j) * ABS( winf(j) - winf(i) )
5615             ckernel(i,j,0) = hkernel(i,j)  ! hall kernel stored on index 0
5616           ENDDO
5617       ENDDO
5618
5619!
5620!--    Test output of efficiencies
5621       IF ( j == -1 )  THEN
5622          PRINT*, '*** Hall kernel'
5623          WRITE ( *,'(5X,20(F4.0,1X))' ) ( radclass(i)*1.0E6_wp, &
5624                                           i = 1,radius_classes )
5625          DO  j = 1, radius_classes
5626             WRITE ( *,'(F4.0,1X,20(F8.4,1X))' ) radclass(j),  &
5627                                       ( hkernel(i,j), i = 1,radius_classes )
5628          ENDDO
5629
5630          DO  k = 1, dissipation_classes
5631             DO  i = 1, radius_classes
5632                DO  j = 1, radius_classes
5633                   IF ( hkernel(i,j) == 0.0_wp )  THEN
5634                      hwratio(i,j) = 9999999.9_wp
5635                   ELSE
5636                      hwratio(i,j) = ckernel(i,j,k) / hkernel(i,j)
5637                   ENDIF
5638                ENDDO
5639             ENDDO
5640
5641             PRINT*, '*** epsilon = ', epsclass(k)
5642             WRITE ( *,'(5X,20(F4.0,1X))' ) ( radclass(i) * 1.0E6_wp, &
5643                                              i = 1,radius_classes )
5644             DO  j = 1, radius_classes
5645                WRITE ( *,'(F4.0,1X,20(F8.4,1X))' ) radclass(j) * 1.0E6_wp, &
5646                                       ( hwratio(i,j), i = 1,radius_classes )
5647             ENDDO
5648          ENDDO
5649       ENDIF
5650
5651       DEALLOCATE( ec, ecf, epsclass, gck, hkernel, winf )
5652
5653    ENDIF
5654
5655 END SUBROUTINE lpm_init_kernels
5656 
5657!------------------------------------------------------------------------------!
5658! Description:
5659! ------------
5660!> Calculation of collision kernels during each timestep and for each grid box
5661!------------------------------------------------------------------------------!
5662 SUBROUTINE recalculate_kernel( i1, j1, k1 )
5663
5664
5665    INTEGER(iwp) ::  i      !<
5666    INTEGER(iwp) ::  i1     !<
5667    INTEGER(iwp) ::  j      !<
5668    INTEGER(iwp) ::  j1     !<
5669    INTEGER(iwp) ::  k1     !<
5670
5671
5672    number_of_particles = prt_count(k1,j1,i1)
5673    radius_classes      = number_of_particles   ! necessary to use the same
5674                                                ! subroutines as for
5675                                                ! precalculated kernels
5676
5677    ALLOCATE( ec(1:number_of_particles,1:number_of_particles), &
5678              radclass(1:number_of_particles), winf(1:number_of_particles) )
5679
5680!
5681!-- Store particle radii on the radclass array
5682    radclass(1:number_of_particles) = particles(1:number_of_particles)%radius
5683
5684    IF ( wang_kernel )  THEN
5685       epsilon_collision = diss(k1,j1,i1)   ! dissipation rate in m**2/s**3
5686    ELSE
5687       epsilon_collision = 0.0_wp
5688    ENDIF
5689    urms    = 2.02_wp * ( epsilon_collision / 0.04_wp )**( 0.33333333333_wp )
5690
5691    IF ( wang_kernel  .AND.  epsilon_collision > 1.0E-7_wp )  THEN
5692!
5693!--    Call routines to calculate efficiencies for the Wang kernel
5694       ALLOCATE( gck(1:number_of_particles,1:number_of_particles), &
5695                 ecf(1:number_of_particles,1:number_of_particles) )
5696
5697       CALL turbsd
5698       CALL turb_enhance_eff
5699       CALL effic
5700
5701       DO  j = 1, number_of_particles
5702          DO  i =  1, number_of_particles
5703             ckernel(1+i-1,1+j-1,1) = ec(i,j) * gck(i,j) * ecf(i,j)
5704          ENDDO
5705       ENDDO
5706
5707       DEALLOCATE( gck, ecf )
5708    ELSE
5709!
5710!--    Call routines to calculate efficiencies for the Hall kernel
5711       CALL fallg
5712       CALL effic
5713
5714       DO  j = 1, number_of_particles
5715          DO  i =  1, number_of_particles
5716             ckernel(i,j,1) = pi * ( radclass(j) + radclass(i) )**2         &
5717                                 * ec(i,j) * ABS( winf(j) - winf(i) )
5718          ENDDO
5719       ENDDO
5720    ENDIF
5721
5722    DEALLOCATE( ec, radclass, winf )
5723
5724 END SUBROUTINE recalculate_kernel
5725
5726!------------------------------------------------------------------------------!
5727! Description:
5728! ------------
5729!> Calculation of effects of turbulence on the geometric collision kernel
5730!> (by including the droplets' average radial relative velocities and their
5731!> radial distribution function) following the analytic model by Aayala et al.
5732!> (2008, New J. Phys.). For details check the second part 2 of the publication,
5733!> page 37ff.
5734!>
5735!> Input parameters, which need to be replaced by PALM parameters:
5736!>    water density, air density
5737!------------------------------------------------------------------------------!
5738 SUBROUTINE turbsd
5739
5740    INTEGER(iwp) ::  i     !<
5741    INTEGER(iwp) ::  j     !<
5742
5743    REAL(wp) ::  ao        !<
5744    REAL(wp) ::  ao_gr     !<
5745    REAL(wp) ::  bbb       !<
5746    REAL(wp) ::  be        !<
5747    REAL(wp) ::  b1        !<
5748    REAL(wp) ::  b2        !<
5749    REAL(wp) ::  ccc       !<
5750    REAL(wp) ::  c1        !<
5751    REAL(wp) ::  c1_gr     !<
5752    REAL(wp) ::  c2        !<
5753    REAL(wp) ::  d1        !<
5754    REAL(wp) ::  d2        !<
5755    REAL(wp) ::  eta       !<
5756    REAL(wp) ::  e1        !<
5757    REAL(wp) ::  e2        !<
5758    REAL(wp) ::  fao_gr    !<
5759    REAL(wp) ::  fr        !<
5760    REAL(wp) ::  grfin     !<
5761    REAL(wp) ::  lambda    !<
5762    REAL(wp) ::  lambda_re !<
5763    REAL(wp) ::  lf        !<
5764    REAL(wp) ::  rc        !<
5765    REAL(wp) ::  rrp       !<
5766    REAL(wp) ::  sst       !<
5767    REAL(wp) ::  tauk      !<
5768    REAL(wp) ::  tl        !<
5769    REAL(wp) ::  t2        !<
5770    REAL(wp) ::  tt        !<
5771    REAL(wp) ::  t1        !<
5772    REAL(wp) ::  vk        !<
5773    REAL(wp) ::  vrms1xy   !<
5774    REAL(wp) ::  vrms2xy   !<
5775    REAL(wp) ::  v1        !<
5776    REAL(wp) ::  v1v2xy    !<
5777    REAL(wp) ::  v1xysq    !<
5778    REAL(wp) ::  v2        !<
5779    REAL(wp) ::  v2xysq    !<
5780    REAL(wp) ::  wrfin     !<
5781    REAL(wp) ::  wrgrav2   !<
5782    REAL(wp) ::  wrtur2xy  !<
5783    REAL(wp) ::  xx        !<
5784    REAL(wp) ::  yy        !<
5785    REAL(wp) ::  z         !<
5786
5787    REAL(wp), DIMENSION(1:radius_classes) ::  st  !< Stokes number
5788    REAL(wp), DIMENSION(1:radius_classes) ::  tau !< inertial time scale
5789
5790    lambda    = urms * SQRT( 15.0_wp * molecular_viscosity / epsilon_collision )
5791    lambda_re = urms**2 * SQRT( 15.0_wp / epsilon_collision / molecular_viscosity )
5792    tl        = urms**2 / epsilon_collision
5793    lf        = 0.5_wp * urms**3 / epsilon_collision
5794    tauk      = SQRT( molecular_viscosity / epsilon_collision )
5795    eta       = ( molecular_viscosity**3 / epsilon_collision )**0.25_wp
5796    vk        = eta / tauk
5797
5798    ao = ( 11.0_wp + 7.0_wp * lambda_re ) / ( 205.0_wp + lambda_re )
5799    tt = SQRT( 2.0_wp * lambda_re / ( SQRT( 15.0_wp ) * ao ) ) * tauk
5800
5801!
5802!-- Get terminal velocity of droplets
5803    CALL fallg
5804
5805    DO  i = 1, radius_classes
5806       tau(i) = winf(i) / g    ! inertial time scale
5807       st(i)  = tau(i) / tauk  ! Stokes number
5808    ENDDO
5809
5810!
5811!-- Calculate average radial relative velocity at contact (wrfin)
5812    z   = tt / tl
5813    be  = SQRT( 2.0_wp ) * lambda / lf
5814    bbb = SQRT( 1.0_wp - 2.0_wp * be**2 )
5815    d1  = ( 1.0_wp + bbb ) / ( 2.0_wp * bbb )
5816    e1  = lf * ( 1.0_wp + bbb ) * 0.5_wp
5817    d2  = ( 1.0_wp - bbb ) * 0.5_wp / bbb
5818    e2  = lf * ( 1.0_wp - bbb ) * 0.5_wp
5819    ccc = SQRT( 1.0_wp - 2.0_wp * z**2 )
5820    b1  = ( 1.0_wp + ccc ) * 0.5_wp / ccc
5821    c1  = tl * ( 1.0_wp + ccc ) * 0.5_wp
5822    b2  = ( 1.0_wp - ccc ) * 0.5_wp / ccc
5823    c2  = tl * ( 1.0_wp - ccc ) * 0.5_wp
5824
5825    DO  i = 1, radius_classes
5826
5827       v1 = winf(i)
5828       t1 = tau(i)
5829
5830       DO  j = 1, i
5831          rrp = radclass(i) + radclass(j)
5832          v2  = winf(j)
5833          t2  = tau(j)
5834
5835          v1xysq  = b1 * d1 * phi_w(c1,e1,v1,t1) - b1 * d2 * phi_w(c1,e2,v1,t1) &
5836                  - b2 * d1 * phi_w(c2,e1,v1,t1) + b2 * d2 * phi_w(c2,e2,v1,t1)
5837          v1xysq  = v1xysq * urms**2 / t1
5838          vrms1xy = SQRT( v1xysq )
5839
5840          v2xysq  = b1 * d1 * phi_w(c1,e1,v2,t2) - b1 * d2 * phi_w(c1,e2,v2,t2) &
5841                  - b2 * d1 * phi_w(c2,e1,v2,t2) + b2 * d2 * phi_w(c2,e2,v2,t2)
5842          v2xysq  = v2xysq * urms**2 / t2
5843          vrms2xy = SQRT( v2xysq )
5844
5845          IF ( winf(i) >= winf(j) )  THEN
5846             v1 = winf(i)
5847             t1 = tau(i)
5848             v2 = winf(j)
5849             t2 = tau(j)
5850          ELSE
5851             v1 = winf(j)
5852             t1 = tau(j)
5853             v2 = winf(i)
5854             t2 = tau(i)
5855          ENDIF
5856
5857          v1v2xy   =  b1 * d1 * zhi(c1,e1,v1,t1,v2,t2) - &
5858                      b1 * d2 * zhi(c1,e2,v1,t1,v2,t2) - &
5859                      b2 * d1 * zhi(c2,e1,v1,t1,v2,t2) + &
5860                      b2 * d2* zhi(c2,e2,v1,t1,v2,t2)
5861          fr       = d1 * EXP( -rrp / e1 ) - d2 * EXP( -rrp / e2 )
5862          v1v2xy   = v1v2xy * fr * urms**2 / tau(i) / tau(j)
5863          wrtur2xy = vrms1xy**2 + vrms2xy**2 - 2.0_wp * v1v2xy
5864          IF ( wrtur2xy < 0.0_wp )  wrtur2xy = 0.0_wp
5865          wrgrav2  = pi / 8.0_wp * ( winf(j) - winf(i) )**2
5866          wrfin    = SQRT( ( 2.0_wp / pi ) * ( wrtur2xy + wrgrav2) )
5867
5868!
5869!--       Calculate radial distribution function (grfin)
5870          IF ( st(j) > st(i) )  THEN
5871             sst = st(j)
5872          ELSE
5873             sst = st(i)
5874          ENDIF
5875
5876          xx = -0.1988_wp * sst**4 + 1.5275_wp * sst**3 - 4.2942_wp *       &
5877                sst**2 + 5.3406_wp * sst
5878          IF ( xx < 0.0_wp )  xx = 0.0_wp
5879          yy = 0.1886_wp * EXP( 20.306_wp / lambda_re )
5880
5881          c1_gr  =  xx / ( g / vk * tauk )**yy
5882
5883          ao_gr  = ao + ( pi / 8.0_wp) * ( g / vk * tauk )**2
5884          fao_gr = 20.115_wp * SQRT( ao_gr / lambda_re )
5885          rc     = SQRT( fao_gr * ABS( st(j) - st(i) ) ) * eta
5886
5887          grfin  = ( ( eta**2 + rc**2 ) / ( rrp**2 + rc**2) )**( c1_gr*0.5_wp )
5888          IF ( grfin < 1.0_wp )  grfin = 1.0_wp
5889
5890!
5891!--       Calculate general collection kernel (without the consideration of
5892!--       collection efficiencies)
5893          gck(i,j) = 2.0_wp * pi * rrp**2 * wrfin * grfin
5894          gck(j,i) = gck(i,j)
5895
5896       ENDDO
5897    ENDDO
5898
5899 END SUBROUTINE turbsd
5900
5901 REAL(wp) FUNCTION phi_w( a, b, vsett, tau0 )
5902!
5903!-- Function used in the Ayala et al. (2008) analytical model for turbulent
5904!-- effects on the collision kernel
5905   
5906
5907    REAL(wp) ::  a     !<
5908    REAL(wp) ::  aa1   !<
5909    REAL(wp) ::  b     !<
5910    REAL(wp) ::  tau0  !<
5911    REAL(wp) ::  vsett !<
5912
5913    aa1 = 1.0_wp / tau0 + 1.0_wp / a + vsett / b
5914    phi_w = 1.0_wp / aa1  - 0.5_wp * vsett / b / aa1**2
5915
5916 END FUNCTION phi_w
5917
5918 REAL(wp) FUNCTION zhi( a, b, vsett1, tau1, vsett2, tau2 )
5919!
5920!-- Function used in the Ayala et al. (2008) analytical model for turbulent
5921!-- effects on the collision kernel
5922
5923    REAL(wp) ::  a      !<
5924    REAL(wp) ::  aa1    !<
5925    REAL(wp) ::  aa2    !<
5926    REAL(wp) ::  aa3    !<
5927    REAL(wp) ::  aa4    !<
5928    REAL(wp) ::  aa5    !<
5929    REAL(wp) ::  aa6    !<
5930    REAL(wp) ::  b      !<
5931    REAL(wp) ::  tau1   !<
5932    REAL(wp) ::  tau2   !<
5933    REAL(wp) ::  vsett1 !<
5934    REAL(wp) ::  vsett2 !<
5935
5936    aa1 = vsett2 / b - 1.0_wp / tau2 - 1.0_wp / a
5937    aa2 = vsett1 / b + 1.0_wp / tau1 + 1.0_wp / a
5938    aa3 = ( vsett1 - vsett2 ) / b + 1.0_wp / tau1 + 1.0_wp / tau2
5939    aa4 = ( vsett2 / b )**2 - ( 1.0_wp / tau2 + 1.0_wp / a )**2
5940    aa5 = vsett2 / b + 1.0_wp / tau2 + 1.0_wp / a
5941    aa6 = 1.0_wp / tau1 - 1.0_wp / a + ( 1.0_wp / tau2 + 1.0_wp / a) *      &
5942          vsett1 / vsett2
5943    zhi = (1.0_wp / aa1 - 1.0_wp / aa2 ) * ( vsett1 - vsett2 ) * 0.5_wp /   &
5944          b / aa3**2 + ( 4.0_wp / aa4 - 1.0_wp / aa5**2 - 1.0_wp / aa1**2 ) &
5945          * vsett2 * 0.5_wp / b /aa6 + ( 2.0_wp * ( b / aa2 - b / aa1 ) -   &
5946          vsett1 / aa2**2 + vsett2 / aa1**2 ) * 0.5_wp / b / aa3
5947
5948 END FUNCTION zhi
5949
5950
5951!------------------------------------------------------------------------------!
5952! Description:
5953! ------------
5954!> Parameterization of terminal velocity following Rogers et al. (1993, J. Appl.
5955!> Meteorol.)
5956!------------------------------------------------------------------------------!
5957 SUBROUTINE fallg
5958
5959    INTEGER(iwp) ::  j                            !<
5960
5961    REAL(wp), PARAMETER ::  k_cap_rog = 4.0_wp    !< parameter
5962    REAL(wp), PARAMETER ::  k_low_rog = 12.0_wp   !< parameter
5963    REAL(wp), PARAMETER ::  a_rog     = 9.65_wp   !< parameter
5964    REAL(wp), PARAMETER ::  b_rog     = 10.43_wp  !< parameter
5965    REAL(wp), PARAMETER ::  c_rog     = 0.6_wp    !< parameter
5966    REAL(wp), PARAMETER ::  d0_rog    = 0.745_wp  !< seperation diameter
5967
5968    REAL(wp)            ::  diameter              !< droplet diameter in mm
5969
5970
5971    DO  j = 1, radius_classes
5972
5973       diameter = radclass(j) * 2000.0_wp
5974
5975       IF ( diameter <= d0_rog )  THEN
5976          winf(j) = k_cap_rog * diameter * ( 1.0_wp -                       &
5977                                             EXP( -k_low_rog * diameter ) )
5978       ELSE
5979          winf(j) = a_rog - b_rog * EXP( -c_rog * diameter )
5980       ENDIF
5981
5982    ENDDO
5983
5984 END SUBROUTINE fallg
5985
5986
5987!------------------------------------------------------------------------------!
5988! Description:
5989! ------------
5990!> Interpolation of collision efficiencies (Hall, 1980, J. Atmos. Sci.)
5991!------------------------------------------------------------------------------!
5992 SUBROUTINE effic
5993 
5994    INTEGER(iwp) ::  i  !<
5995    INTEGER(iwp) ::  iq !<
5996    INTEGER(iwp) ::  ir !<
5997    INTEGER(iwp) ::  j  !<
5998    INTEGER(iwp) ::  k  !<
5999
6000    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  ira !<
6001
6002    LOGICAL, SAVE ::  first = .TRUE. !<
6003
6004    REAL(wp) ::  ek              !<
6005    REAL(wp) ::  particle_radius !<
6006    REAL(wp) ::  pp              !<
6007    REAL(wp) ::  qq              !<
6008    REAL(wp) ::  rq              !<
6009
6010    REAL(wp), DIMENSION(1:21), SAVE ::  rat        !<
6011   
6012    REAL(wp), DIMENSION(1:15), SAVE ::  r0         !<
6013   
6014    REAL(wp), DIMENSION(1:15,1:21), SAVE ::  ecoll !<
6015
6016!
6017!-- Initial assignment of constants
6018    IF ( first )  THEN
6019
6020      first = .FALSE.
6021      r0  = (/   6.0_wp,   8.0_wp,  10.0_wp, 15.0_wp,  20.0_wp,  25.0_wp,   &
6022                30.0_wp,  40.0_wp,  50.0_wp, 60.0_wp,  70.0_wp, 100.0_wp,   &
6023               150.0_wp, 200.0_wp, 300.0_wp /)
6024
6025      rat = (/ 0.00_wp, 0.05_wp, 0.10_wp, 0.15_wp, 0.20_wp, 0.25_wp,        &
6026               0.30_wp, 0.35_wp, 0.40_wp, 0.45_wp, 0.50_wp, 0.55_wp,        &
6027               0.60_wp, 0.65_wp, 0.70_wp, 0.75_wp, 0.80_wp, 0.85_wp,        &
6028               0.90_wp, 0.95_wp, 1.00_wp /)
6029
6030      ecoll(:,1)  = (/ 0.001_wp, 0.001_wp, 0.001_wp, 0.001_wp, 0.001_wp,    &
6031                       0.001_wp, 0.001_wp, 0.001_wp, 0.001_wp, 0.001_wp,    &
6032                       0.001_wp, 0.001_wp, 0.001_wp, 0.001_wp, 0.001_wp /)
6033      ecoll(:,2)  = (/ 0.003_wp, 0.003_wp, 0.003_wp, 0.004_wp, 0.005_wp,    &
6034                       0.005_wp, 0.005_wp, 0.010_wp, 0.100_wp, 0.050_wp,    &
6035                       0.200_wp, 0.500_wp, 0.770_wp, 0.870_wp, 0.970_wp /)
6036      ecoll(:,3)  = (/ 0.007_wp, 0.007_wp, 0.007_wp, 0.008_wp, 0.009_wp,    &
6037                       0.010_wp, 0.010_wp, 0.070_wp, 0.400_wp, 0.430_wp,    &
6038                       0.580_wp, 0.790_wp, 0.930_wp, 0.960_wp, 1.000_wp /)
6039      ecoll(:,4)  = (/ 0.009_wp, 0.009_wp, 0.009_wp, 0.012_wp, 0.015_wp,    &
6040                       0.010_wp, 0.020_wp, 0.280_wp, 0.600_wp, 0.640_wp,    &
6041                       0.750_wp, 0.910_wp, 0.970_wp, 0.980_wp, 1.000_wp /)
6042      ecoll(:,5)  = (/ 0.014_wp, 0.014_wp, 0.014_wp, 0.015_wp, 0.016_wp,    &
6043                       0.030_wp, 0.060_wp, 0.500_wp, 0.700_wp, 0.770_wp,    &
6044                       0.840_wp, 0.950_wp, 0.970_wp, 1.000_wp, 1.000_wp /)
6045      ecoll(:,6)  = (/ 0.017_wp, 0.017_wp, 0.017_wp, 0.020_wp, 0.022_wp,    &
6046                       0.060_wp, 0.100_wp, 0.620_wp, 0.780_wp, 0.840_wp,    &
6047                       0.880_wp, 0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6048      ecoll(:,7)  = (/ 0.030_wp, 0.030_wp, 0.024_wp, 0.022_wp, 0.032_wp,    &
6049                       0.062_wp, 0.200_wp, 0.680_wp, 0.830_wp, 0.870_wp,    &
6050                       0.900_wp, 0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6051      ecoll(:,8)  = (/ 0.025_wp, 0.025_wp, 0.025_wp, 0.036_wp, 0.043_wp,    &
6052                       0.130_wp, 0.270_wp, 0.740_wp, 0.860_wp, 0.890_wp,    &
6053                       0.920_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6054      ecoll(:,9)  = (/ 0.027_wp, 0.027_wp, 0.027_wp, 0.040_wp, 0.052_wp,    &
6055                       0.200_wp, 0.400_wp, 0.780_wp, 0.880_wp, 0.900_wp,    &
6056                       0.940_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6057      ecoll(:,10) = (/ 0.030_wp, 0.030_wp, 0.030_wp, 0.047_wp, 0.064_wp,    &
6058                       0.250_wp, 0.500_wp, 0.800_wp, 0.900_wp, 0.910_wp,    &
6059                       0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6060      ecoll(:,11) = (/ 0.040_wp, 0.040_wp, 0.033_wp, 0.037_wp, 0.068_wp,    &
6061                       0.240_wp, 0.550_wp, 0.800_wp, 0.900_wp, 0.910_wp,    &
6062                       0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6063      ecoll(:,12) = (/ 0.035_wp, 0.035_wp, 0.035_wp, 0.055_wp, 0.079_wp,    &
6064                       0.290_wp, 0.580_wp, 0.800_wp, 0.900_wp, 0.910_wp,    &
6065                       0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6066      ecoll(:,13) = (/ 0.037_wp, 0.037_wp, 0.037_wp, 0.062_wp, 0.082_wp,    &
6067                       0.290_wp, 0.590_wp, 0.780_wp, 0.900_wp, 0.910_wp,    &
6068                       0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6069      ecoll(:,14) = (/ 0.037_wp, 0.037_wp, 0.037_wp, 0.060_wp, 0.080_wp,    &
6070                       0.290_wp, 0.580_wp, 0.770_wp, 0.890_wp, 0.910_wp,    &
6071                       0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6072      ecoll(:,15) = (/ 0.037_wp, 0.037_wp, 0.037_wp, 0.041_wp, 0.075_wp,    &
6073                       0.250_wp, 0.540_wp, 0.760_wp, 0.880_wp, 0.920_wp,    &
6074                       0.950_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6075      ecoll(:,16) = (/ 0.037_wp, 0.037_wp, 0.037_wp, 0.052_wp, 0.067_wp,    &
6076                       0.250_wp, 0.510_wp, 0.770_wp, 0.880_wp, 0.930_wp,    &
6077                       0.970_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6078      ecoll(:,17) = (/ 0.037_wp, 0.037_wp, 0.037_wp, 0.047_wp, 0.057_wp,    &
6079                       0.250_wp, 0.490_wp, 0.770_wp, 0.890_wp, 0.950_wp,    &
6080                       1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp, 1.000_wp /)
6081      ecoll(:,18) = (/ 0.036_wp, 0.036_wp, 0.036_wp, 0.042_wp, 0.048_wp,    &
6082                       0.230_wp, 0.470_wp, 0.780_wp, 0.920_wp, 1.000_wp,    &
6083                       1.020_wp, 1.020_wp, 1.020_wp, 1.020_wp, 1.020_wp /)
6084      ecoll(:,19) = (/ 0.040_wp, 0.040_wp, 0.035_wp, 0.033_wp, 0.040_wp,    &
6085                       0.112_wp, 0.450_wp, 0.790_wp, 1.010_wp, 1.030_wp,    &
6086                       1.040_wp, 1.040_wp, 1.040_wp, 1.040_wp, 1.040_wp /)
6087      ecoll(:,20) = (/ 0.033_wp, 0.033_wp, 0.033_wp, 0.033_wp, 0.033_wp,    &
6088                       0.119_wp, 0.470_wp, 0.950_wp, 1.300_wp, 1.700_wp,    &
6089                       2.300_wp, 2.300_wp, 2.300_wp, 2.300_wp, 2.300_wp /)
6090      ecoll(:,21) = (/ 0.027_wp, 0.027_wp, 0.027_wp, 0.027_wp, 0.027_wp,    &
6091                       0.125_wp, 0.520_wp, 1.400_wp, 2.300_wp, 3.000_wp,    &
6092                       4.000_wp, 4.000_wp, 4.000_wp, 4.000_wp, 4.000_wp /)
6093    ENDIF
6094
6095!
6096!-- Calculate the radius class index of particles with respect to array r
6097!-- Radius has to be in microns
6098    ALLOCATE( ira(1:radius_classes) )
6099    DO  j = 1, radius_classes
6100       particle_radius = radclass(j) * 1.0E6_wp
6101       DO  k = 1, 15
6102          IF ( particle_radius < r0(k) )  THEN
6103             ira(j) = k
6104             EXIT
6105          ENDIF
6106       ENDDO
6107       IF ( particle_radius >= r0(15) )  ira(j) = 16
6108    ENDDO
6109
6110!
6111!-- Two-dimensional linear interpolation of the collision efficiency.
6112!-- Radius has to be in microns
6113    DO  j = 1, radius_classes
6114       DO  i = 1, j
6115
6116          ir = MAX( ira(i), ira(j) )
6117          rq = MIN( radclass(i) / radclass(j), radclass(j) / radclass(i) )
6118          iq = INT( rq * 20 ) + 1
6119          iq = MAX( iq , 2)
6120
6121          IF ( ir < 16 )  THEN
6122             IF ( ir >= 2 )  THEN
6123                pp = ( ( MAX( radclass(j), radclass(i) ) * 1.0E6_wp ) -     &
6124                       r0(ir-1) ) / ( r0(ir) - r0(ir-1) )
6125                qq = ( rq - rat(iq-1) ) / ( rat(iq) - rat(iq-1) )
6126                ec(j,i) = ( 1.0_wp - pp ) * ( 1.0_wp - qq )                 &
6127                          * ecoll(ir-1,iq-1)                                &
6128                          + pp * ( 1.0_wp - qq ) * ecoll(ir,iq-1)           &
6129                          + qq * ( 1.0_wp - pp ) * ecoll(ir-1,iq)           &
6130                          + pp * qq * ecoll(ir,iq)
6131             ELSE
6132                qq = ( rq - rat(iq-1) ) / ( rat(iq) - rat(iq-1) )
6133                ec(j,i) = ( 1.0_wp - qq ) * ecoll(1,iq-1) + qq * ecoll(1,iq)
6134             ENDIF
6135          ELSE
6136             qq = ( rq - rat(iq-1) ) / ( rat(iq) - rat(iq-1) )
6137             ek = ( 1.0_wp - qq ) * ecoll(15,iq-1) + qq * ecoll(15,iq)
6138             ec(j,i) = MIN( ek, 1.0_wp )
6139          ENDIF
6140
6141          IF ( ec(j,i) < 1.0E-20_wp )  ec(j,i) = 0.0_wp
6142
6143          ec(i,j) = ec(j,i)
6144
6145       ENDDO
6146    ENDDO
6147
6148    DEALLOCATE( ira )
6149
6150 END SUBROUTINE effic
6151
6152
6153!------------------------------------------------------------------------------!
6154! Description:
6155! ------------
6156!> Interpolation of turbulent enhancement factor for collision efficencies
6157!> following Wang and Grabowski (2009, Atmos. Sci. Let.)
6158!------------------------------------------------------------------------------!
6159 SUBROUTINE turb_enhance_eff
6160
6161    INTEGER(iwp) ::  i  !<
6162    INTEGER(iwp) ::  iq !<
6163    INTEGER(iwp) ::  ir !<
6164    INTEGER(iwp) ::  j  !<
6165    INTEGER(iwp) ::  k  !<
6166    INTEGER(iwp) ::  kk !<
6167
6168    INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  ira !<
6169
6170    LOGICAL, SAVE ::  first = .TRUE. !<
6171
6172    REAL(wp) ::  particle_radius !<
6173    REAL(wp) ::  pp              !<
6174    REAL(wp) ::  qq              !<
6175    REAL(wp) ::  rq              !<
6176    REAL(wp) ::  y1              !<
6177    REAL(wp) ::  y2              !<
6178    REAL(wp) ::  y3              !<
6179
6180    REAL(wp), DIMENSION(1:11), SAVE ::  rat           !<
6181    REAL(wp), DIMENSION(1:7), SAVE  ::  r0            !<
6182
6183    REAL(wp), DIMENSION(1:7,1:11), SAVE ::  ecoll_100 !<
6184    REAL(wp), DIMENSION(1:7,1:11), SAVE ::  ecoll_400 !<
6185
6186!
6187!-- Initial assignment of constants
6188    IF ( first )  THEN
6189
6190       first = .FALSE.
6191
6192       r0  = (/  10.0_wp, 20.0_wp, 30.0_wp, 40.0_wp, 50.0_wp, 60.0_wp,  &
6193                100.0_wp /)
6194
6195       rat = (/ 0.0_wp, 0.1_wp, 0.2_wp, 0.3_wp, 0.4_wp, 0.5_wp, 0.6_wp, &
6196                0.7_wp, 0.8_wp, 0.9_wp, 1.0_wp /)
6197!
6198!--    Tabulated turbulent enhancement factor at 100 cm**2/s**3
6199       ecoll_100(:,1)  = (/  1.74_wp,   1.74_wp,   1.773_wp, 1.49_wp,  &
6200                             1.207_wp,  1.207_wp,  1.0_wp /)
6201       ecoll_100(:,2)  = (/  1.46_wp,   1.46_wp,   1.421_wp, 1.245_wp, &
6202                             1.069_wp,  1.069_wp,  1.0_wp /)
6203       ecoll_100(:,3)  = (/  1.32_wp,   1.32_wp,   1.245_wp, 1.123_wp, &
6204                             1.000_wp,  1.000_wp,  1.0_wp /)
6205       ecoll_100(:,4)  = (/  1.250_wp,  1.250_wp,  1.148_wp, 1.087_wp, &
6206                             1.025_wp,  1.025_wp,  1.0_wp /)
6207       ecoll_100(:,5)  = (/  1.186_wp,  1.186_wp,  1.066_wp, 1.060_wp, &
6208                             1.056_wp,  1.056_wp,  1.0_wp /)
6209       ecoll_100(:,6)  = (/  1.045_wp,  1.045_wp,  1.000_wp, 1.014_wp, &
6210                             1.028_wp,  1.028_wp,  1.0_wp /)
6211       ecoll_100(:,7)  = (/  1.070_wp,  1.070_wp,  1.030_wp, 1.038_wp, &
6212                             1.046_wp,  1.046_wp,  1.0_wp /)
6213       ecoll_100(:,8)  = (/  1.000_wp,  1.000_wp,  1.054_wp, 1.042_wp, &
6214                             1.029_wp,  1.029_wp,  1.0_wp /)
6215       ecoll_100(:,9)  = (/  1.223_wp,  1.223_wp,  1.117_wp, 1.069_wp, &
6216                             1.021_wp,  1.021_wp,  1.0_wp /)
6217       ecoll_100(:,10) = (/  1.570_wp,  1.570_wp,  1.244_wp, 1.166_wp, &
6218                             1.088_wp,  1.088_wp,  1.0_wp /)
6219       ecoll_100(:,11) = (/ 20.3_wp,   20.3_wp,   14.6_wp,   8.61_wp,  &
6220                             2.60_wp,   2.60_wp,   1.0_wp /)
6221!
6222!--    Tabulated turbulent enhancement factor at 400 cm**2/s**3
6223       ecoll_400(:,1)  = (/  4.976_wp,  4.976_wp,  3.593_wp,  2.519_wp, &
6224                             1.445_wp,  1.445_wp,  1.0_wp /)
6225       ecoll_400(:,2)  = (/  2.984_wp,  2.984_wp,  2.181_wp,  1.691_wp, &
6226                             1.201_wp,  1.201_wp,  1.0_wp /)
6227       ecoll_400(:,3)  = (/  1.988_wp,  1.988_wp,  1.475_wp,  1.313_wp, &
6228                             1.150_wp,  1.150_wp,  1.0_wp /)
6229       ecoll_400(:,4)  = (/  1.490_wp,  1.490_wp,  1.187_wp,  1.156_wp, &
6230                             1.126_wp,  1.126_wp,  1.0_wp /)
6231       ecoll_400(:,5)  = (/  1.249_wp,  1.249_wp,  1.088_wp,  1.090_wp, &
6232                             1.092_wp,  1.092_wp,  1.0_wp /)
6233       ecoll_400(:,6)  = (/  1.139_wp,  1.139_wp,  1.130_wp,  1.091_wp, &
6234                             1.051_wp,  1.051_wp,  1.0_wp /)
6235       ecoll_400(:,7)  = (/  1.220_wp,  1.220_wp,  1.190_wp,  1.138_wp, &
6236                             1.086_wp,  1.086_wp,  1.0_wp /)
6237       ecoll_400(:,8)  = (/  1.325_wp,  1.325_wp,  1.267_wp,  1.165_wp, &
6238                             1.063_wp,  1.063_wp,  1.0_wp /)
6239       ecoll_400(:,9)  = (/  1.716_wp,  1.716_wp,  1.345_wp,  1.223_wp, &
6240                             1.100_wp,  1.100_wp,  1.0_wp /)
6241       ecoll_400(:,10) = (/  3.788_wp,  3.788_wp,  1.501_wp,  1.311_wp, &
6242                             1.120_wp,  1.120_wp,  1.0_wp /)
6243       ecoll_400(:,11) = (/ 36.52_wp,  36.52_wp,  19.16_wp,  22.80_wp,  &
6244                            26.0_wp,   26.0_wp,    1.0_wp /)
6245
6246    ENDIF
6247
6248!
6249!-- Calculate the radius class index of particles with respect to array r0
6250!-- The droplet radius has to be given in microns.
6251    ALLOCATE( ira(1:radius_classes) )
6252
6253    DO  j = 1, radius_classes
6254       particle_radius = radclass(j) * 1.0E6_wp
6255       DO  k = 1, 7
6256          IF ( particle_radius < r0(k) )  THEN
6257             ira(j) = k
6258             EXIT
6259          ENDIF
6260       ENDDO
6261       IF ( particle_radius >= r0(7) )  ira(j) = 8
6262    ENDDO
6263
6264!
6265!-- Two-dimensional linear interpolation of the turbulent enhancement factor.
6266!-- The droplet radius has to be given in microns.
6267    DO  j =  1, radius_classes
6268       DO  i = 1, j
6269
6270          ir = MAX( ira(i), ira(j) )
6271          rq = MIN( radclass(i) / radclass(j), radclass(j) / radclass(i) )
6272
6273          DO  kk = 2, 11
6274             IF ( rq <= rat(kk) )  THEN
6275                iq = kk
6276                EXIT
6277             ENDIF
6278          ENDDO
6279
6280          y1 = 1.0_wp  ! turbulent enhancement factor at 0 m**2/s**3
6281
6282          IF ( ir < 8 )  THEN
6283             IF ( ir >= 2 )  THEN
6284                pp = ( MAX( radclass(j), radclass(i) ) * 1.0E6_wp -  &
6285                       r0(ir-1) ) / ( r0(ir) - r0(ir-1) )
6286                qq = ( rq - rat(iq-1) ) / ( rat(iq) - rat(iq-1) )
6287                y2 = ( 1.0_wp - pp ) * ( 1.0_wp - qq ) * ecoll_100(ir-1,iq-1) + &
6288                             pp * ( 1.0_wp - qq ) * ecoll_100(ir,iq-1)        + &
6289                             qq * ( 1.0_wp - pp ) * ecoll_100(ir-1,iq)        + &
6290                             pp * qq              * ecoll_100(ir,iq)
6291                y3 = ( 1.0-pp ) * ( 1.0_wp - qq ) * ecoll_400(ir-1,iq-1)      + &
6292                             pp * ( 1.0_wp - qq ) * ecoll_400(ir,iq-1)        + &
6293                             qq * ( 1.0_wp - pp ) * ecoll_400(ir-1,iq)        + &
6294                             pp * qq              * ecoll_400(ir,iq)
6295             ELSE
6296                qq = ( rq - rat(iq-1) ) / ( rat(iq) - rat(iq-1) )
6297                y2 = ( 1.0_wp - qq ) * ecoll_100(1,iq-1) + qq * ecoll_100(1,iq)
6298                y3 = ( 1.0_wp - qq ) * ecoll_400(1,iq-1) + qq * ecoll_400(1,iq)
6299             ENDIF
6300          ELSE
6301             qq = ( rq - rat(iq-1) ) / ( rat(iq) - rat(iq-1) )
6302             y2 = ( 1.0_wp - qq ) * ecoll_100(7,iq-1) + qq * ecoll_100(7,iq)
6303             y3 = ( 1.0_wp - qq ) * ecoll_400(7,iq-1) + qq * ecoll_400(7,iq)
6304          ENDIF
6305!
6306!--       Linear interpolation of turbulent enhancement factor
6307          IF ( epsilon_collision <= 0.01_wp )  THEN
6308             ecf(j,i) = ( epsilon_collision - 0.01_wp ) / ( 0.0_wp  - 0.01_wp ) * y1 &
6309                      + ( epsilon_collision - 0.0_wp  ) / ( 0.01_wp - 0.0_wp  ) * y2
6310          ELSEIF ( epsilon_collision <= 0.06_wp )  THEN
6311             ecf(j,i) = ( epsilon_collision - 0.04_wp ) / ( 0.01_wp - 0.04_wp ) * y2 &
6312                      + ( epsilon_collision - 0.01_wp ) / ( 0.04_wp - 0.01_wp ) * y3
6313          ELSE
6314             ecf(j,i) = ( 0.06_wp - 0.04_wp ) / ( 0.01_wp - 0.04_wp ) * y2 &
6315                      + ( 0.06_wp - 0.01_wp ) / ( 0.04_wp - 0.01_wp ) * y3
6316          ENDIF
6317
6318          IF ( ecf(j,i) < 1.0_wp )  ecf(j,i) = 1.0_wp
6319
6320          ecf(i,j) = ecf(j,i)
6321
6322       ENDDO
6323    ENDDO
6324
6325 END SUBROUTINE turb_enhance_eff
6326 
6327 
6328 !------------------------------------------------------------------------------!
6329! Description:
6330! ------------
6331! This routine is a part of the Lagrangian particle model. Super droplets which
6332! fulfill certain criterion's (e.g. a big weighting factor and a large radius)
6333! can be split into several super droplets with a reduced number of
6334! represented particles of every super droplet. This mechanism ensures an
6335! improved representation of the right tail of the drop size distribution with
6336! a feasible amount of computational costs. The limits of particle creation
6337! should be chosen carefully! The idea of this algorithm is based on
6338! Unterstrasser and Soelch, 2014.
6339!------------------------------------------------------------------------------!
6340 SUBROUTINE lpm_splitting
6341
6342    INTEGER(iwp) ::  i                !<
6343    INTEGER(iwp) ::  j                !<
6344    INTEGER(iwp) ::  jpp              !<
6345    INTEGER(iwp) ::  k                !<
6346    INTEGER(iwp) ::  n                !<
6347    INTEGER(iwp) ::  new_particles_gb !< counter of created particles within one grid box
6348    INTEGER(iwp) ::  new_size         !< new particle array size
6349    INTEGER(iwp) ::  np               !<
6350    INTEGER(iwp) ::  old_size         !< old particle array size
6351
6352    INTEGER(iwp), PARAMETER ::  n_max = 100 !< number of radii bin for splitting functions   
6353
6354    LOGICAL ::  first_loop_stride_sp = .TRUE. !< flag to calculate constants only once
6355
6356    REAL(wp) ::  diameter                 !< diameter of droplet
6357    REAL(wp) ::  dlog                     !< factor for DSD calculation
6358    REAL(wp) ::  factor_volume_to_mass    !< pre calculate factor volume to mass
6359    REAL(wp) ::  lambda                   !< slope parameter of gamma-distribution
6360    REAL(wp) ::  lwc                      !< liquid water content of grid box
6361    REAL(wp) ::  lwc_total                !< average liquid water content of cloud
6362    REAL(wp) ::  m1                       !< first moment of DSD
6363    REAL(wp) ::  m1_total                 !< average over all PEs of first moment of DSD
6364    REAL(wp) ::  m2                       !< second moment of DSD
6365    REAL(wp) ::  m2_total                 !< average average over all PEs second moment of DSD
6366    REAL(wp) ::  m3                       !< third moment of DSD
6367    REAL(wp) ::  m3_total                 !< average average over all PEs third moment of DSD
6368    REAL(wp) ::  mu                       !< spectral shape parameter of gamma distribution
6369    REAL(wp) ::  nrclgb                   !< number of cloudy grid boxes (ql >= 1.0E-5 kg/kg)
6370    REAL(wp) ::  nrclgb_total             !< average over all PEs of number of cloudy grid boxes
6371    REAL(wp) ::  nr                       !< number concentration of cloud droplets
6372    REAL(wp) ::  nr_total                 !< average over all PEs of number of cloudy grid boxes
6373    REAL(wp) ::  nr0                      !< intercept parameter of gamma distribution
6374    REAL(wp) ::  pirho_l                  !< pi * rho_l / 6.0
6375    REAL(wp) ::  ql_crit = 1.0E-5_wp      !< threshold lwc for cloudy grid cells
6376                                          !< (Siebesma et al 2003, JAS, 60)
6377    REAL(wp) ::  rm                       !< volume averaged mean radius
6378    REAL(wp) ::  rm_total                 !< average over all PEs of volume averaged mean radius
6379    REAL(wp) ::  r_min = 1.0E-6_wp        !< minimum radius of approximated spectra
6380    REAL(wp) ::  r_max = 1.0E-3_wp        !< maximum radius of approximated spectra
6381    REAL(wp) ::  sigma_log = 1.5_wp       !< standard deviation of the LOG-distribution
6382    REAL(wp) ::  zeta                     !< Parameter for DSD calculation of Seifert
6383
6384    REAL(wp), DIMENSION(0:n_max-1) ::  an_spl     !< size dependent critical weight factor
6385    REAL(wp), DIMENSION(0:n_max-1) ::  r_bin_mid  !< mass weighted mean radius of a bin
6386    REAL(wp), DIMENSION(0:n_max)   ::  r_bin      !< boundaries of a radius bin
6387
6388    TYPE(particle_type) ::  tmp_particle   !< temporary particle TYPE
6389
6390    CALL cpu_log( log_point_s(80), 'lpm_splitting', 'start' )
6391
6392    IF ( first_loop_stride_sp )  THEN
6393       IF ( i_splitting_mode == 2  .OR.  i_splitting_mode == 3 )  THEN
6394          dlog   = ( LOG10(r_max) - LOG10(r_min) ) / ( n_max - 1 )
6395          DO  i = 0, n_max-1
6396             r_bin(i) = 10.0_wp**( LOG10(r_min) + i * dlog - 0.5_wp * dlog )
6397             r_bin_mid(i) = 10.0_wp**( LOG10(r_min) + i * dlog )
6398          ENDDO
6399          r_bin(n_max) = 10.0_wp**( LOG10(r_min) + n_max * dlog - 0.5_wp * dlog )
6400       ENDIF   
6401       factor_volume_to_mass =  4.0_wp / 3.0_wp * pi * rho_l
6402       pirho_l  = pi * rho_l / 6.0_wp
6403       IF ( weight_factor_split == -1.0_wp )  THEN
6404          weight_factor_split = 0.1_wp * initial_weighting_factor 
6405       ENDIF
6406    ENDIF
6407
6408
6409    IF ( i_splitting_mode == 1 )  THEN
6410
6411       DO  i = nxl, nxr
6412          DO  j = nys, nyn
6413             DO  k = nzb+1, nzt
6414
6415                new_particles_gb = 0
6416                number_of_particles = prt_count(k,j,i)
6417                IF ( number_of_particles <= 0  .OR.                            & 
6418                     ql(k,j,i) < ql_crit )  CYCLE
6419                particles => grid_particles(k,j,i)%particles(1:number_of_particles)
6420!
6421!--             Start splitting operations. Each particle is checked if it
6422!--             fulfilled the splitting criterion's. In splitting mode 'const'   
6423!--             a critical radius  (radius_split) a critical weighting factor
6424!--             (weight_factor_split) and a splitting factor (splitting_factor)
6425!--             must  be prescribed (see particle_parameters). Super droplets
6426!--             which have a larger radius and larger weighting factor are split
6427!--             into 'splitting_factor' super droplets. Therefore, the weighting
6428!--             factor of  the super droplet and all created clones is reduced
6429!--             by the factor of 'splitting_factor'.
6430                DO  n = 1, number_of_particles
6431                   IF ( particles(n)%particle_mask  .AND.                      &
6432                        particles(n)%radius >= radius_split  .AND.             & 
6433                        particles(n)%weight_factor >= weight_factor_split )    &
6434                   THEN
6435!
6436!--                   Calculate the new number of particles.
6437                      new_size = prt_count(k,j,i) + splitting_factor - 1
6438!
6439!--                   Cycle if maximum number of particles per grid box
6440!--                   is greater than the allowed maximum number.
6441                      IF ( new_size >= max_number_particles_per_gridbox )  CYCLE
6442!
6443!--                   Reallocate particle array if necessary.
6444                      IF ( new_size > SIZE(particles) )  THEN
6445                         CALL realloc_particles_array( i, j, k, new_size )
6446                      ENDIF
6447                      old_size = prt_count(k,j,i)
6448!
6449!--                   Calculate new weighting factor.
6450                      particles(n)%weight_factor =  & 
6451                         particles(n)%weight_factor / splitting_factor
6452                      tmp_particle = particles(n)
6453!
6454!--                   Create splitting_factor-1 new particles.
6455                      DO  jpp = 1, splitting_factor-1
6456                         grid_particles(k,j,i)%particles(jpp+old_size) =       & 
6457                            tmp_particle
6458                      ENDDO 
6459                      new_particles_gb = new_particles_gb + splitting_factor - 1
6460!   
6461!--                   Save the new number of super droplets for every grid box.
6462                      prt_count(k,j,i) = prt_count(k,j,i) +                    &
6463                                         splitting_factor - 1
6464                   ENDIF
6465                ENDDO
6466
6467             ENDDO
6468          ENDDO
6469       ENDDO
6470
6471    ELSEIF ( i_splitting_mode == 2 )  THEN 
6472!
6473!--    Initialize summing variables.
6474       lwc          = 0.0_wp
6475       lwc_total    = 0.0_wp 
6476       m1           = 0.0_wp
6477       m1_total     = 0.0_wp
6478       m2           = 0.0_wp
6479       m2_total     = 0.0_wp
6480       m3           = 0.0_wp
6481       m3_total     = 0.0_wp
6482       nr           = 0.0_wp
6483       nrclgb       = 0.0_wp
6484       nrclgb_total = 0.0_wp
6485       nr_total     = 0.0_wp
6486       rm           = 0.0_wp
6487       rm_total     = 0.0_wp
6488
6489       DO  i = nxl, nxr
6490          DO  j = nys, nyn
6491             DO  k = nzb+1, nzt
6492                number_of_particles = prt_count(k,j,i)
6493                IF ( number_of_particles <= 0  .OR.                            & 
6494                     ql(k,j,i) < ql_crit )  CYCLE
6495                particles => grid_particles(k,j,i)%particles(1:number_of_particles)
6496                nrclgb = nrclgb + 1.0_wp
6497!
6498!--             Calculate moments of DSD.
6499                DO  n = 1, number_of_particles
6500                   IF ( particles(n)%particle_mask  .AND.                      &
6501                        particles(n)%radius >= r_min )                         &
6502                   THEN
6503                      nr  = nr  + particles(n)%weight_factor
6504                      rm  = rm  + factor_volume_to_mass  *                     &
6505                                 particles(n)%radius**3  *                     &
6506                                 particles(n)%weight_factor
6507                      IF ( isf == 1 )  THEN           
6508                         diameter   = particles(n)%radius * 2.0_wp
6509                         lwc = lwc + factor_volume_to_mass *                   &
6510                                     particles(n)%radius**3 *                  & 
6511                                     particles(n)%weight_factor 
6512                         m1  = m1  + particles(n)%weight_factor * diameter
6513                         m2  = m2  + particles(n)%weight_factor * diameter**2
6514                         m3  = m3  + particles(n)%weight_factor * diameter**3
6515                      ENDIF
6516                   ENDIF
6517                ENDDO 
6518             ENDDO
6519          ENDDO
6520       ENDDO
6521
6522#if defined( __parallel )
6523       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
6524       CALL MPI_ALLREDUCE( nr, nr_total, 1 , &
6525       MPI_REAL, MPI_SUM, comm2d, ierr )
6526       CALL MPI_ALLREDUCE( rm, rm_total, 1 , &
6527       MPI_REAL, MPI_SUM, comm2d, ierr )
6528       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
6529       CALL MPI_ALLREDUCE( nrclgb, nrclgb_total, 1 , &
6530       MPI_REAL, MPI_SUM, comm2d, ierr )
6531       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
6532       CALL MPI_ALLREDUCE( lwc, lwc_total, 1 , &
6533       MPI_REAL, MPI_SUM, comm2d, ierr )
6534       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
6535       CALL MPI_ALLREDUCE( m1, m1_total, 1 , &
6536       MPI_REAL, MPI_SUM, comm2d, ierr )
6537       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
6538       CALL MPI_ALLREDUCE( m2, m2_total, 1 , &
6539       MPI_REAL, MPI_SUM, comm2d, ierr )
6540       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
6541       CALL MPI_ALLREDUCE( m3, m3_total, 1 , &
6542       MPI_REAL, MPI_SUM, comm2d, ierr )
6543#endif 
6544
6545!
6546!--    Calculate number concentration and mean volume averaged radius.
6547       nr_total = MERGE( nr_total / nrclgb_total,                              &
6548                         0.0_wp, nrclgb_total > 0.0_wp                         &
6549                       )
6550       rm_total = MERGE( ( rm_total /                                          &
6551                            ( nr_total * factor_volume_to_mass )               &
6552                          )**0.3333333_wp, 0.0_wp, nrclgb_total > 0.0_wp       &
6553                       )
6554!
6555!--    Check which function should be used to approximate the DSD.
6556       IF ( isf == 1 )  THEN
6557          lwc_total = MERGE( lwc_total / nrclgb_total,                         &
6558                             0.0_wp, nrclgb_total > 0.0_wp                     &
6559                           )
6560          m1_total  = MERGE( m1_total / nrclgb_total,                          &
6561                             0.0_wp, nrclgb_total > 0.0_wp                     &
6562                           )
6563          m2_total  = MERGE( m2_total / nrclgb_total,                          &
6564                             0.0_wp, nrclgb_total > 0.0_wp                     &
6565                           )
6566          m3_total  = MERGE( m3_total / nrclgb_total,                          &
6567                             0.0_wp, nrclgb_total > 0.0_wp                     &
6568                           )
6569          zeta = m1_total * m3_total / m2_total**2
6570          mu   = MAX( ( ( 1.0_wp - zeta ) * 2.0_wp + 1.0_wp ) /                &
6571                        ( zeta - 1.0_wp ), 0.0_wp                              &
6572                    )
6573
6574          lambda = ( pirho_l * nr_total / lwc_total *                          &
6575                     ( mu + 3.0_wp ) * ( mu + 2.0_wp ) * ( mu + 1.0_wp )       &
6576                   )**0.3333333_wp
6577          nr0 = nr_total / gamma( mu + 1.0_wp ) * lambda**( mu + 1.0_wp ) 
6578
6579          DO  n = 0, n_max-1
6580             diameter  = r_bin_mid(n) * 2.0_wp
6581             an_spl(n) = nr0 * diameter**mu * EXP( -lambda * diameter ) *      & 
6582                         ( r_bin(n+1) - r_bin(n) ) * 2.0_wp 
6583          ENDDO
6584       ELSEIF ( isf == 2 )  THEN
6585          DO  n = 0, n_max-1
6586             an_spl(n) = nr_total / ( SQRT( 2.0_wp * pi ) *                    &
6587                                     LOG(sigma_log) * r_bin_mid(n)             &
6588                                     ) *                                       &
6589                         EXP( -( LOG( r_bin_mid(n) / rm_total )**2 ) /         &
6590                               ( 2.0_wp * LOG(sigma_log)**2 )                  & 
6591                             ) *                                               & 
6592                         ( r_bin(n+1) - r_bin(n) )
6593          ENDDO
6594       ELSEIF( isf == 3 )  THEN
6595          DO  n = 0, n_max-1 
6596             an_spl(n) = 3.0_wp * nr_total * r_bin_mid(n)**2 / rm_total**3  *  &
6597                         EXP( - ( r_bin_mid(n)**3 / rm_total**3 ) )         *  &
6598                         ( r_bin(n+1) - r_bin(n) )
6599          ENDDO
6600       ENDIF
6601!
6602!--    Criterion to avoid super droplets with a weighting factor < 1.0.
6603       an_spl = MAX(an_spl, 1.0_wp)
6604
6605       DO  i = nxl, nxr
6606          DO  j = nys, nyn
6607             DO  k = nzb+1, nzt
6608                number_of_particles = prt_count(k,j,i)
6609                IF ( number_of_particles <= 0  .OR.                            &
6610                     ql(k,j,i) < ql_crit )  CYCLE
6611                particles => grid_particles(k,j,i)%particles(1:number_of_particles)
6612                new_particles_gb = 0
6613!
6614!--             Start splitting operations. Each particle is checked if it
6615!--             fulfilled the splitting criterion's. In splitting mode 'cl_av'
6616!--             a critical radius (radius_split) and a splitting function must
6617!--             be prescribed (see particles_par). The critical weighting factor
6618!--             is calculated while approximating a 'gamma', 'log' or 'exp'-
6619!--             drop size distribution. In this mode the DSD is calculated as
6620!--             an average over all cloudy grid boxes. Super droplets which
6621!--             have a larger radius and larger weighting factor are split into
6622!--             'splitting_factor' super droplets. In this case the splitting
6623!--             factor is calculated of weighting factor of the super droplet
6624!--             and the approximated number concentration for droplet of such
6625!--             a size. Due to the splitting, the weighting factor of the
6626!--             super droplet and all created clones is reduced by the factor
6627!--             of 'splitting_facor'.
6628                DO  n = 1, number_of_particles
6629                   DO  np = 0, n_max-1
6630                      IF ( r_bin(np) >= radius_split  .AND.                    &
6631                           particles(n)%particle_mask  .AND.                   &
6632                           particles(n)%radius >= r_bin(np)  .AND.             &
6633                           particles(n)%radius < r_bin(np+1)  .AND.            &
6634                           particles(n)%weight_factor >= an_spl(np)  )         &
6635                      THEN
6636!
6637!--                      Calculate splitting factor
6638                         splitting_factor =                                    & 
6639                             MIN( INT( particles(n)%weight_factor /            &
6640                                        an_spl(np)                             &
6641                                     ), splitting_factor_max                   &
6642                                )
6643                         IF ( splitting_factor < 2 )  CYCLE
6644!
6645!--                      Calculate the new number of particles.
6646                         new_size = prt_count(k,j,i) + splitting_factor - 1
6647!
6648!--                      Cycle if maximum number of particles per grid box
6649!--                      is greater than the allowed maximum number.
6650                         IF ( new_size >= max_number_particles_per_gridbox )   & 
6651                         CYCLE
6652!
6653!--                      Reallocate particle array if necessary.
6654                         IF ( new_size > SIZE(particles) )  THEN
6655                            CALL realloc_particles_array( i, j, k, new_size )
6656                         ENDIF
6657                         old_size  = prt_count(k,j,i)
6658                         new_particles_gb = new_particles_gb +                 &
6659                                            splitting_factor - 1
6660!
6661!--                      Calculate new weighting factor.
6662                         particles(n)%weight_factor =                          & 
6663                            particles(n)%weight_factor / splitting_factor
6664                         tmp_particle = particles(n)
6665!
6666!--                      Create splitting_factor-1 new particles.
6667                         DO  jpp = 1, splitting_factor-1
6668                            grid_particles(k,j,i)%particles(jpp+old_size) =    &
6669                                                                    tmp_particle
6670                         ENDDO
6671!
6672!--                      Save the new number of super droplets.
6673                         prt_count(k,j,i) = prt_count(k,j,i) +                 &
6674                                            splitting_factor - 1
6675                      ENDIF
6676                   ENDDO
6677                ENDDO 
6678
6679             ENDDO
6680          ENDDO
6681       ENDDO
6682
6683    ELSEIF ( i_splitting_mode == 3 )  THEN
6684
6685       DO  i = nxl, nxr
6686          DO  j = nys, nyn
6687             DO  k = nzb+1, nzt
6688
6689!
6690!--             Initialize summing variables.
6691                lwc = 0.0_wp
6692                m1  = 0.0_wp
6693                m2  = 0.0_wp
6694                m3  = 0.0_wp
6695                nr  = 0.0_wp
6696                rm  = 0.0_wp 
6697
6698                new_particles_gb = 0
6699                number_of_particles = prt_count(k,j,i)
6700                IF ( number_of_particles <= 0  .OR.                            & 
6701                     ql(k,j,i) < ql_crit )  CYCLE
6702                particles => grid_particles(k,j,i)%particles
6703!
6704!--             Calculate moments of DSD.
6705                DO  n = 1, number_of_particles
6706                   IF ( particles(n)%particle_mask  .AND.                      &
6707                        particles(n)%radius >= r_min )                         &
6708                   THEN
6709                      nr  = nr + particles(n)%weight_factor
6710                      rm  = rm + factor_volume_to_mass  *                      &
6711                                 particles(n)%radius**3  *                     &
6712                                 particles(n)%weight_factor
6713                      IF ( isf == 1 )  THEN
6714                         diameter   = particles(n)%radius * 2.0_wp
6715                         lwc = lwc + factor_volume_to_mass *                   &
6716                                     particles(n)%radius**3 *                  &
6717                                     particles(n)%weight_factor 
6718                         m1  = m1 + particles(n)%weight_factor * diameter
6719                         m2  = m2 + particles(n)%weight_factor * diameter**2
6720                         m3  = m3 + particles(n)%weight_factor * diameter**3
6721                      ENDIF
6722                   ENDIF
6723                ENDDO
6724
6725                IF ( nr <= 0.0_wp  .OR.  rm <= 0.0_wp )  CYCLE
6726!
6727!--             Calculate mean volume averaged radius.
6728                rm = ( rm / ( nr * factor_volume_to_mass ) )**0.3333333_wp
6729!
6730!--             Check which function should be used to approximate the DSD.
6731                IF ( isf == 1 )  THEN
6732!
6733!--                Gamma size distribution to calculate 
6734!--                critical weight_factor (e.g. Marshall + Palmer, 1948).
6735                   zeta = m1 * m3 / m2**2
6736                   mu   = MAX( ( ( 1.0_wp - zeta ) * 2.0_wp + 1.0_wp ) /       &
6737                                ( zeta - 1.0_wp ), 0.0_wp                      &
6738                             )   
6739                   lambda = ( pirho_l * nr / lwc *                             &
6740                              ( mu + 3.0_wp ) * ( mu + 2.0_wp ) *              &
6741                              ( mu + 1.0_wp )                                  &
6742                            )**0.3333333_wp
6743                   nr0 =  ( nr / (gamma( mu + 1.0_wp ) ) ) *                   &
6744                          lambda**( mu + 1.0_wp ) 
6745
6746                   DO  n = 0, n_max-1
6747                      diameter         = r_bin_mid(n) * 2.0_wp
6748                      an_spl(n) = nr0 * diameter**mu *                         &
6749                                  EXP( -lambda * diameter ) *                  & 
6750                                  ( r_bin(n+1) - r_bin(n) ) * 2.0_wp 
6751                   ENDDO
6752                ELSEIF ( isf == 2 )  THEN
6753!
6754!--                Lognormal size distribution to calculate critical
6755!--                weight_factor (e.g. Levin, 1971, Bradley + Stow, 1974).
6756                   DO  n = 0, n_max-1
6757                      an_spl(n) = nr / ( SQRT( 2.0_wp * pi ) *                 &
6758                                              LOG(sigma_log) * r_bin_mid(n)    &
6759                                        ) *                                    &
6760                                  EXP( -( LOG( r_bin_mid(n) / rm )**2 ) /      &
6761                                        ( 2.0_wp * LOG(sigma_log)**2 )         &
6762                                      ) *                                      &
6763                                  ( r_bin(n+1) - r_bin(n) )
6764                   ENDDO
6765                ELSEIF ( isf == 3 )  THEN
6766!
6767!--                Exponential size distribution to calculate critical
6768!--                weight_factor (e.g. Berry + Reinhardt, 1974). 
6769                   DO  n = 0, n_max-1
6770                      an_spl(n) = 3.0_wp * nr * r_bin_mid(n)**2 / rm**3 *     &
6771                                  EXP( - ( r_bin_mid(n)**3 / rm**3 ) ) *      &
6772                                  ( r_bin(n+1) - r_bin(n) )
6773                   ENDDO
6774                ENDIF
6775
6776!
6777!--             Criterion to avoid super droplets with a weighting factor < 1.0.
6778                an_spl = MAX(an_spl, 1.0_wp)
6779!
6780!--             Start splitting operations. Each particle is checked if it
6781!--             fulfilled the splitting criterion's. In splitting mode 'gb_av'
6782!--             a critical radius (radius_split) and a splitting function must
6783!--             be prescribed (see particles_par). The critical weighting factor
6784!--             is calculated while appoximating a 'gamma', 'log' or 'exp'-
6785!--             drop size distribution. In this mode a DSD is calculated for
6786!--             every cloudy grid box. Super droplets which have a larger
6787!--             radius and larger weighting factor are split into
6788!--             'splitting_factor' super droplets. In this case the splitting 
6789!--             factor is calculated of weighting factor of the super droplet 
6790!--             and theapproximated number concentration for droplet of such
6791!--             a size. Due to the splitting, the weighting factor of the 
6792!--             super droplet and all created clones is reduced by the factor 
6793!--             of 'splitting_facor'.
6794                DO  n = 1, number_of_particles
6795                   DO  np = 0, n_max-1
6796                      IF ( r_bin(np) >= radius_split  .AND.                    &
6797                           particles(n)%particle_mask  .AND.                   &
6798                           particles(n)%radius >= r_bin(np)    .AND.           &
6799                           particles(n)%radius < r_bin(np+1)   .AND.           &
6800                           particles(n)%weight_factor >= an_spl(np) )          &
6801                      THEN
6802!
6803!--                      Calculate splitting factor.
6804                         splitting_factor =                                    & 
6805                             MIN( INT( particles(n)%weight_factor /            &
6806                                        an_spl(np)                             &
6807                                     ), splitting_factor_max                   &
6808                                )
6809                         IF ( splitting_factor < 2 )  CYCLE
6810
6811!
6812!--                      Calculate the new number of particles.
6813                         new_size = prt_count(k,j,i) + splitting_factor - 1
6814!
6815!--                      Cycle if maximum number of particles per grid box
6816!--                      is greater than the allowed maximum number.
6817                         IF ( new_size >= max_number_particles_per_gridbox )   &
6818                         CYCLE
6819!
6820!--                      Reallocate particle array if necessary.
6821                         IF ( new_size > SIZE(particles) )  THEN
6822                            CALL realloc_particles_array( i, j, k, new_size )
6823                         ENDIF
6824!
6825!--                      Calculate new weighting factor.
6826                         particles(n)%weight_factor = & 
6827                            particles(n)%weight_factor / splitting_factor
6828                         tmp_particle               = particles(n)
6829                         old_size                   = prt_count(k,j,i)
6830!
6831!--                      Create splitting_factor-1 new particles.
6832                         DO  jpp = 1, splitting_factor-1
6833                            grid_particles(k,j,i)%particles( jpp + old_size ) = &
6834                               tmp_particle
6835                         ENDDO
6836!
6837!--                      Save the new number of droplets for every grid box.
6838                         prt_count(k,j,i)    = prt_count(k,j,i) +              &
6839                                               splitting_factor - 1
6840                         new_particles_gb    = new_particles_gb +              &
6841                                               splitting_factor - 1
6842                      ENDIF
6843                   ENDDO
6844                ENDDO
6845             ENDDO
6846          ENDDO
6847       ENDDO
6848    ENDIF
6849
6850    CALL cpu_log( log_point_s(80), 'lpm_splitting', 'stop' )
6851
6852 END SUBROUTINE lpm_splitting
6853 
6854
6855!------------------------------------------------------------------------------!
6856! Description:
6857! ------------
6858! This routine is a part of the Lagrangian particle model. Two Super droplets
6859! which fulfill certain criterion's (e.g. a big weighting factor and a small
6860! radius) can be merged into one super droplet with a increased number of
6861! represented particles of the super droplet. This mechanism ensures an
6862! improved a feasible amount of computational costs. The limits of particle
6863! creation should be chosen carefully! The idea of this algorithm is based on
6864! Unterstrasser and Soelch, 2014.
6865!------------------------------------------------------------------------------!
6866 SUBROUTINE lpm_merging
6867
6868    INTEGER(iwp) ::  i         !<
6869    INTEGER(iwp) ::  j         !<
6870    INTEGER(iwp) ::  k         !<
6871    INTEGER(iwp) ::  n         !<
6872    INTEGER(iwp) ::  merge_drp = 0     !< number of merged droplets
6873
6874
6875    REAL(wp) ::  ql_crit = 1.0E-5_wp  !< threshold lwc for cloudy grid cells
6876                                      !< (e.g. Siebesma et al 2003, JAS, 60)
6877
6878    CALL cpu_log( log_point_s(81), 'lpm_merging', 'start' )
6879
6880    merge_drp  = 0
6881
6882    IF ( weight_factor_merge == -1.0_wp )  THEN
6883       weight_factor_merge = 0.5_wp * initial_weighting_factor 
6884    ENDIF
6885
6886    DO  i = nxl, nxr
6887       DO  j = nys, nyn
6888          DO  k = nzb+1, nzt
6889
6890             number_of_particles = prt_count(k,j,i)
6891             IF ( number_of_particles <= 0  .OR.                               &
6892                   ql(k,j,i) >= ql_crit )  CYCLE
6893             particles => grid_particles(k,j,i)%particles(1:number_of_particles)
6894!
6895!--          Start merging operations: This routine delete super droplets with
6896!--          a small radius (radius <= radius_merge) and a low weighting
6897!--          factor (weight_factor  <= weight_factor_merge). The number of
6898!--          represented particles will be added to the next particle of the
6899!--          particle array. Tests showed that this simplified method can be
6900!--          used because it will only take place outside of cloudy grid
6901!--          boxes where ql <= 1.0E-5 kg/kg. Therefore, especially former cloned
6902!--          and subsequent evaporated super droplets will be merged.
6903             DO  n = 1, number_of_particles-1
6904                IF ( particles(n)%particle_mask                    .AND.       &
6905                     particles(n+1)%particle_mask                  .AND.       &
6906                     particles(n)%radius        <= radius_merge    .AND.       &
6907                     particles(n)%weight_factor <= weight_factor_merge )       &
6908                THEN
6909                   particles(n+1)%weight_factor  =                             &
6910                                       particles(n+1)%weight_factor +          &
6911                                       ( particles(n)%radius**3     /          &
6912                                         particles(n+1)%radius**3   *          &
6913                                         particles(n)%weight_factor            &
6914                                       )
6915                   particles(n)%particle_mask = .FALSE.
6916                   deleted_particles          = deleted_particles + 1 
6917                   merge_drp                  = merge_drp + 1
6918
6919                ENDIF
6920             ENDDO
6921          ENDDO
6922       ENDDO
6923    ENDDO
6924
6925
6926    CALL cpu_log( log_point_s(81), 'lpm_merging', 'stop' )
6927
6928 END SUBROUTINE lpm_merging
6929
6930 
6931
6932 
6933!------------------------------------------------------------------------------!
6934! Description:
6935! ------------
6936!> Exchange between subdomains.
6937!> As soon as one particle has moved beyond the boundary of the domain, it
6938!> is included in the relevant transfer arrays and marked for subsequent
6939!> deletion on this PE.
6940!> First sweep for crossings in x direction. Find out first the number of
6941!> particles to be transferred and allocate temporary arrays needed to store
6942!> them.
6943!> For a one-dimensional decomposition along y, no transfer is necessary,
6944!> because the particle remains on the PE, but the particle coordinate has to
6945!> be adjusted.
6946!------------------------------------------------------------------------------!
6947 SUBROUTINE lpm_exchange_horiz
6948
6949    INTEGER(iwp) ::  i                 !< grid index (x) of particle positition
6950    INTEGER(iwp) ::  ip                !< index variable along x
6951    INTEGER(iwp) ::  j                 !< grid index (y) of particle positition
6952    INTEGER(iwp) ::  jp                !< index variable along y
6953    INTEGER(iwp) ::  kp                !< index variable along z
6954    INTEGER(iwp) ::  n                 !< particle index variable
6955    INTEGER(iwp) ::  par_size          !< Particle size in bytes
6956    INTEGER(iwp) ::  trlp_count        !< number of particles send to left PE
6957    INTEGER(iwp) ::  trlp_count_recv   !< number of particles receive from right PE
6958    INTEGER(iwp) ::  trnp_count        !< number of particles send to north PE
6959    INTEGER(iwp) ::  trnp_count_recv   !< number of particles receive from south PE
6960    INTEGER(iwp) ::  trrp_count        !< number of particles send to right PE
6961    INTEGER(iwp) ::  trrp_count_recv   !< number of particles receive from left PE
6962    INTEGER(iwp) ::  trsp_count        !< number of particles send to south PE
6963    INTEGER(iwp) ::  trsp_count_recv   !< number of particles receive from north PE
6964
6965    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  rvlp  !< particles received from right PE
6966    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  rvnp  !< particles received from south PE
6967    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  rvrp  !< particles received from left PE
6968    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  rvsp  !< particles received from north PE
6969    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  trlp  !< particles send to left PE
6970    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  trnp  !< particles send to north PE
6971    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  trrp  !< particles send to right PE
6972    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  trsp  !< particles send to south PE
6973
6974    CALL cpu_log( log_point_s(23), 'lpm_exchange_horiz', 'start' )
6975
6976#if defined( __parallel )
6977
6978!
6979!-- Exchange between subdomains.
6980!-- As soon as one particle has moved beyond the boundary of the domain, it
6981!-- is included in the relevant transfer arrays and marked for subsequent
6982!-- deletion on this PE.
6983!-- First sweep for crossings in x direction. Find out first the number of
6984!-- particles to be transferred and allocate temporary arrays needed to store
6985!-- them.
6986!-- For a one-dimensional decomposition along y, no transfer is necessary,
6987!-- because the particle remains on the PE, but the particle coordinate has to
6988!-- be adjusted.
6989    trlp_count  = 0
6990    trrp_count  = 0
6991
6992    trlp_count_recv   = 0
6993    trrp_count_recv   = 0
6994
6995    IF ( pdims(1) /= 1 )  THEN
6996!
6997!--    First calculate the storage necessary for sending and receiving the data.
6998!--    Compute only first (nxl) and last (nxr) loop iterration.
6999       DO  ip = nxl, nxr, nxr - nxl
7000          DO  jp = nys, nyn
7001             DO  kp = nzb+1, nzt
7002
7003                number_of_particles = prt_count(kp,jp,ip)
7004                IF ( number_of_particles <= 0 )  CYCLE
7005                particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
7006                DO  n = 1, number_of_particles
7007                   IF ( particles(n)%particle_mask )  THEN
7008                      i = particles(n)%x * ddx
7009!
7010!--                   Above calculation does not work for indices less than zero
7011                      IF ( particles(n)%x < 0.0_wp)  i = -1
7012
7013                      IF ( i < nxl )  THEN
7014                         trlp_count = trlp_count + 1
7015                      ELSEIF ( i > nxr )  THEN
7016                         trrp_count = trrp_count + 1
7017                      ENDIF
7018                   ENDIF
7019                ENDDO
7020
7021             ENDDO
7022          ENDDO
7023       ENDDO
7024
7025       IF ( trlp_count  == 0 )  trlp_count  = 1
7026       IF ( trrp_count  == 0 )  trrp_count  = 1
7027
7028       ALLOCATE( trlp(trlp_count), trrp(trrp_count) )
7029
7030       trlp = zero_particle
7031       trrp = zero_particle
7032
7033       trlp_count  = 0
7034       trrp_count  = 0
7035
7036    ENDIF
7037!
7038!-- Compute only first (nxl) and last (nxr) loop iterration
7039    DO  ip = nxl, nxr, nxr-nxl
7040       DO  jp = nys, nyn
7041          DO  kp = nzb+1, nzt
7042             number_of_particles = prt_count(kp,jp,ip)
7043             IF ( number_of_particles <= 0 )  CYCLE
7044             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
7045             DO  n = 1, number_of_particles
7046!
7047!--             Only those particles that have not been marked as 'deleted' may
7048!--             be moved.
7049                IF ( particles(n)%particle_mask )  THEN
7050
7051                   i = particles(n)%x * ddx
7052!
7053!--                Above calculation does not work for indices less than zero
7054                   IF ( particles(n)%x < 0.0_wp )  i = -1
7055
7056                   IF ( i <  nxl )  THEN
7057                      IF ( i < 0 )  THEN
7058!
7059!--                   Apply boundary condition along x
7060                         IF ( ibc_par_lr == 0 )  THEN
7061!
7062!--                         Cyclic condition
7063                            IF ( pdims(1) == 1 )  THEN
7064                               particles(n)%x        = ( nx + 1 ) * dx + particles(n)%x
7065                               particles(n)%origin_x = ( nx + 1 ) * dx + &
7066                               particles(n)%origin_x
7067                            ELSE
7068                               trlp_count = trlp_count + 1
7069                               trlp(trlp_count)   = particles(n)
7070                               trlp(trlp_count)%x = ( nx + 1 ) * dx + trlp(trlp_count)%x
7071                               trlp(trlp_count)%origin_x = trlp(trlp_count)%origin_x + &
7072                               ( nx + 1 ) * dx
7073                               particles(n)%particle_mask  = .FALSE.
7074                               deleted_particles = deleted_particles + 1
7075
7076                               IF ( trlp(trlp_count)%x >= (nx + 1)* dx - 1.0E-12_wp )  THEN
7077                                  trlp(trlp_count)%x = trlp(trlp_count)%x - 1.0E-10_wp
7078                                  !++ why is 1 subtracted in next statement???
7079                                  trlp(trlp_count)%origin_x = trlp(trlp_count)%origin_x - 1
7080                               ENDIF
7081
7082                            ENDIF
7083
7084                         ELSEIF ( ibc_par_lr == 1 )  THEN
7085!
7086!--                         Particle absorption
7087                            particles(n)%particle_mask = .FALSE.
7088                            deleted_particles = deleted_particles + 1
7089
7090                         ELSEIF ( ibc_par_lr == 2 )  THEN
7091!
7092!--                         Particle reflection
7093                            particles(n)%x       = -particles(n)%x
7094                            particles(n)%speed_x = -particles(n)%speed_x
7095
7096                         ENDIF
7097                      ELSE
7098!
7099!--                      Store particle data in the transfer array, which will be
7100!--                      send to the neighbouring PE
7101                         trlp_count = trlp_count + 1
7102                         trlp(trlp_count) = particles(n)
7103                         particles(n)%particle_mask = .FALSE.
7104                         deleted_particles = deleted_particles + 1
7105
7106                      ENDIF
7107
7108                   ELSEIF ( i > nxr )  THEN
7109                      IF ( i > nx )  THEN
7110!
7111!--                      Apply boundary condition along x
7112                         IF ( ibc_par_lr == 0 )  THEN
7113!
7114!--                         Cyclic condition
7115                            IF ( pdims(1) == 1 )  THEN
7116                               particles(n)%x = particles(n)%x - ( nx + 1 ) * dx
7117                               particles(n)%origin_x = particles(n)%origin_x - &
7118                               ( nx + 1 ) * dx
7119                            ELSE
7120                               trrp_count = trrp_count + 1
7121                               trrp(trrp_count) = particles(n)
7122                               trrp(trrp_count)%x = trrp(trrp_count)%x - ( nx + 1 ) * dx
7123                               trrp(trrp_count)%origin_x = trrp(trrp_count)%origin_x - &
7124                               ( nx + 1 ) * dx
7125                               particles(n)%particle_mask = .FALSE.
7126                               deleted_particles = deleted_particles + 1
7127
7128                            ENDIF
7129
7130                         ELSEIF ( ibc_par_lr == 1 )  THEN
7131!
7132!--                         Particle absorption
7133                            particles(n)%particle_mask = .FALSE.
7134                            deleted_particles = deleted_particles + 1
7135
7136                         ELSEIF ( ibc_par_lr == 2 )  THEN
7137!
7138!--                         Particle reflection
7139                            particles(n)%x       = 2 * ( nx * dx ) - particles(n)%x
7140                            particles(n)%speed_x = -particles(n)%speed_x
7141
7142                         ENDIF
7143                      ELSE
7144!
7145!--                      Store particle data in the transfer array, which will be send
7146!--                      to the neighbouring PE
7147                         trrp_count = trrp_count + 1
7148                         trrp(trrp_count) = particles(n)
7149                         particles(n)%particle_mask = .FALSE.
7150                         deleted_particles = deleted_particles + 1
7151
7152                      ENDIF
7153
7154                   ENDIF
7155                ENDIF
7156
7157             ENDDO
7158          ENDDO
7159       ENDDO
7160    ENDDO
7161
7162!
7163!-- STORAGE_SIZE returns the storage size of argument A in bits. However , it
7164!-- is needed in bytes. The function C_SIZEOF which produces this value directly
7165!-- causes problems with gfortran. For this reason the use of C_SIZEOF is avoided
7166    par_size = STORAGE_SIZE(trlp(1))/8
7167
7168
7169!
7170!-- Allocate arrays required for north-south exchange, as these
7171!-- are used directly after particles are exchange along x-direction.
7172    ALLOCATE( move_also_north(1:NR_2_direction_move) )
7173    ALLOCATE( move_also_south(1:NR_2_direction_move) )
7174
7175    nr_move_north = 0
7176    nr_move_south = 0
7177!
7178!-- Send left boundary, receive right boundary (but first exchange how many
7179!-- and check, if particle storage must be extended)
7180    IF ( pdims(1) /= 1 )  THEN
7181
7182       CALL MPI_SENDRECV( trlp_count,      1, MPI_INTEGER, pleft,  0, &
7183                          trrp_count_recv, 1, MPI_INTEGER, pright, 0, &
7184                          comm2d, status, ierr )
7185
7186       ALLOCATE(rvrp(MAX(1,trrp_count_recv)))
7187
7188       CALL MPI_SENDRECV( trlp, max(1,trlp_count)*par_size, MPI_BYTE,&
7189                          pleft, 1, rvrp,                            &
7190                          max(1,trrp_count_recv)*par_size, MPI_BYTE, pright, 1,&
7191                          comm2d, status, ierr )
7192
7193       IF ( trrp_count_recv > 0 )  CALL lpm_add_particles_to_gridcell(rvrp(1:trrp_count_recv))
7194
7195       DEALLOCATE(rvrp)
7196
7197!
7198!--    Send right boundary, receive left boundary
7199       CALL MPI_SENDRECV( trrp_count,      1, MPI_INTEGER, pright, 0, &
7200                          trlp_count_recv, 1, MPI_INTEGER, pleft,  0, &
7201                          comm2d, status, ierr )
7202
7203       ALLOCATE(rvlp(MAX(1,trlp_count_recv)))
7204!
7205!--    This MPI_SENDRECV should work even with odd mixture on 32 and 64 Bit
7206!--    variables in structure particle_type (due to the calculation of par_size)
7207       CALL MPI_SENDRECV( trrp, max(1,trrp_count)*par_size, MPI_BYTE,&
7208                          pright, 1, rvlp,                           &
7209                          max(1,trlp_count_recv)*par_size, MPI_BYTE, pleft, 1, &
7210                          comm2d, status, ierr )
7211
7212       IF ( trlp_count_recv > 0 )  CALL lpm_add_particles_to_gridcell(rvlp(1:trlp_count_recv))
7213
7214       DEALLOCATE( rvlp )
7215       DEALLOCATE( trlp, trrp )
7216
7217    ENDIF
7218
7219!
7220!-- Check whether particles have crossed the boundaries in y direction. Note
7221!-- that this case can also apply to particles that have just been received
7222!-- from the adjacent right or left PE.
7223!-- Find out first the number of particles to be transferred and allocate
7224!-- temporary arrays needed to store them.
7225!-- For a one-dimensional decomposition along y, no transfer is necessary,
7226!-- because the particle remains on the PE.
7227    trsp_count  = nr_move_south
7228    trnp_count  = nr_move_north
7229
7230    trsp_count_recv   = 0
7231    trnp_count_recv   = 0
7232
7233    IF ( pdims(2) /= 1 )  THEN
7234!
7235!--    First calculate the storage necessary for sending and receiving the
7236!--    data
7237       DO  ip = nxl, nxr
7238          DO  jp = nys, nyn, nyn-nys    !compute only first (nys) and last (nyn) loop iterration
7239             DO  kp = nzb+1, nzt
7240                number_of_particles = prt_count(kp,jp,ip)
7241                IF ( number_of_particles <= 0 )  CYCLE
7242                particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
7243                DO  n = 1, number_of_particles
7244                   IF ( particles(n)%particle_mask )  THEN
7245                      j = particles(n)%y * ddy
7246!
7247!--                   Above calculation does not work for indices less than zero
7248                      IF ( particles(n)%y < 0.0_wp)  j = -1
7249
7250                      IF ( j < nys )  THEN
7251                         trsp_count = trsp_count + 1
7252                      ELSEIF ( j > nyn )  THEN
7253                         trnp_count = trnp_count + 1
7254                      ENDIF
7255                   ENDIF
7256                ENDDO
7257             ENDDO
7258          ENDDO
7259       ENDDO
7260
7261       IF ( trsp_count  == 0 )  trsp_count  = 1
7262       IF ( trnp_count  == 0 )  trnp_count  = 1
7263
7264       ALLOCATE( trsp(trsp_count), trnp(trnp_count) )
7265
7266       trsp = zero_particle
7267       trnp = zero_particle
7268
7269       trsp_count  = nr_move_south
7270       trnp_count  = nr_move_north
7271
7272       trsp(1:nr_move_south) = move_also_south(1:nr_move_south)
7273       trnp(1:nr_move_north) = move_also_north(1:nr_move_north)
7274
7275    ENDIF
7276
7277    DO  ip = nxl, nxr
7278       DO  jp = nys, nyn, nyn-nys ! compute only first (nys) and last (nyn) loop iterration
7279          DO  kp = nzb+1, nzt
7280             number_of_particles = prt_count(kp,jp,ip)
7281             IF ( number_of_particles <= 0 )  CYCLE
7282             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
7283             DO  n = 1, number_of_particles
7284!
7285!--             Only those particles that have not been marked as 'deleted' may
7286!--             be moved.
7287                IF ( particles(n)%particle_mask )  THEN
7288
7289                   j = particles(n)%y * ddy
7290!
7291!--                Above calculation does not work for indices less than zero
7292                   IF ( particles(n)%y < 0.0_wp )  j = -1
7293
7294                   IF ( j < nys )  THEN
7295                      IF ( j < 0 )  THEN
7296!
7297!--                      Apply boundary condition along y
7298                         IF ( ibc_par_ns == 0 )  THEN
7299!
7300!--                         Cyclic condition
7301                            IF ( pdims(2) == 1 )  THEN
7302                               particles(n)%y = ( ny + 1 ) * dy + particles(n)%y
7303                               particles(n)%origin_y = ( ny + 1 ) * dy + &
7304                                                     particles(n)%origin_y
7305                            ELSE
7306                               trsp_count         = trsp_count + 1
7307                               trsp(trsp_count)   = particles(n)
7308                               trsp(trsp_count)%y = ( ny + 1 ) * dy + &
7309                                                 trsp(trsp_count)%y
7310                               trsp(trsp_count)%origin_y = trsp(trsp_count)%origin_y &
7311                                                + ( ny + 1 ) * dy
7312                               particles(n)%particle_mask = .FALSE.
7313                               deleted_particles = deleted_particles + 1
7314
7315                               IF ( trsp(trsp_count)%y >= (ny+1)* dy - 1.0E-12_wp )  THEN
7316                                  trsp(trsp_count)%y = trsp(trsp_count)%y - 1.0E-10_wp
7317                                  !++ why is 1 subtracted in next statement???
7318                                  trsp(trsp_count)%origin_y =                        &
7319                                                  trsp(trsp_count)%origin_y - 1
7320                               ENDIF
7321
7322                            ENDIF
7323
7324                         ELSEIF ( ibc_par_ns == 1 )  THEN
7325!
7326!--                         Particle absorption
7327                            particles(n)%particle_mask = .FALSE.
7328                            deleted_particles          = deleted_particles + 1
7329
7330                         ELSEIF ( ibc_par_ns == 2 )  THEN
7331!
7332!--                         Particle reflection
7333                            particles(n)%y       = -particles(n)%y
7334                            particles(n)%speed_y = -particles(n)%speed_y
7335
7336                         ENDIF
7337                      ELSE
7338!
7339!--                      Store particle data in the transfer array, which will
7340!--                      be send to the neighbouring PE
7341                         trsp_count = trsp_count + 1
7342                         trsp(trsp_count) = particles(n)
7343                         particles(n)%particle_mask = .FALSE.
7344                         deleted_particles = deleted_particles + 1
7345
7346                      ENDIF
7347
7348                   ELSEIF ( j > nyn )  THEN
7349                      IF ( j > ny )  THEN
7350!
7351!--                       Apply boundary condition along y
7352                         IF ( ibc_par_ns == 0 )  THEN
7353!
7354!--                         Cyclic condition
7355                            IF ( pdims(2) == 1 )  THEN
7356                               particles(n)%y        = particles(n)%y - ( ny + 1 ) * dy
7357                               particles(n)%origin_y =                         &
7358                                          particles(n)%origin_y - ( ny + 1 ) * dy
7359                            ELSE
7360                               trnp_count         = trnp_count + 1
7361                               trnp(trnp_count)   = particles(n)
7362                               trnp(trnp_count)%y =                            &
7363                                          trnp(trnp_count)%y - ( ny + 1 ) * dy
7364                               trnp(trnp_count)%origin_y =                     &
7365                                         trnp(trnp_count)%origin_y - ( ny + 1 ) * dy
7366                               particles(n)%particle_mask = .FALSE.
7367                               deleted_particles          = deleted_particles + 1
7368                            ENDIF
7369
7370                         ELSEIF ( ibc_par_ns == 1 )  THEN
7371!
7372!--                         Particle absorption
7373                            particles(n)%particle_mask = .FALSE.
7374                            deleted_particles = deleted_particles + 1
7375
7376                         ELSEIF ( ibc_par_ns == 2 )  THEN
7377!
7378!--                         Particle reflection
7379                            particles(n)%y       = 2 * ( ny * dy ) - particles(n)%y
7380                            particles(n)%speed_y = -particles(n)%speed_y
7381
7382                         ENDIF
7383                      ELSE
7384!
7385!--                      Store particle data in the transfer array, which will
7386!--                      be send to the neighbouring PE
7387                         trnp_count = trnp_count + 1
7388                         trnp(trnp_count) = particles(n)
7389                         particles(n)%particle_mask = .FALSE.
7390                         deleted_particles = deleted_particles + 1
7391
7392                      ENDIF
7393
7394                   ENDIF
7395                ENDIF
7396             ENDDO
7397          ENDDO
7398       ENDDO
7399    ENDDO
7400
7401!
7402!-- Send front boundary, receive back boundary (but first exchange how many
7403!-- and check, if particle storage must be extended)
7404    IF ( pdims(2) /= 1 )  THEN
7405
7406       CALL MPI_SENDRECV( trsp_count,      1, MPI_INTEGER, psouth, 0, &
7407                          trnp_count_recv, 1, MPI_INTEGER, pnorth, 0, &
7408                          comm2d, status, ierr )
7409
7410       ALLOCATE(rvnp(MAX(1,trnp_count_recv)))
7411!
7412!--    This MPI_SENDRECV should work even with odd mixture on 32 and 64 Bit
7413!--    variables in structure particle_type (due to the calculation of par_size)
7414       CALL MPI_SENDRECV( trsp, trsp_count*par_size, MPI_BYTE,      &
7415                          psouth, 1, rvnp,                             &
7416                          trnp_count_recv*par_size, MPI_BYTE, pnorth, 1,   &
7417                          comm2d, status, ierr )
7418
7419       IF ( trnp_count_recv  > 0 )  CALL lpm_add_particles_to_gridcell(rvnp(1:trnp_count_recv))
7420
7421       DEALLOCATE(rvnp)
7422
7423!
7424!--    Send back boundary, receive front boundary
7425       CALL MPI_SENDRECV( trnp_count,      1, MPI_INTEGER, pnorth, 0, &
7426                          trsp_count_recv, 1, MPI_INTEGER, psouth, 0, &
7427                          comm2d, status, ierr )
7428
7429       ALLOCATE(rvsp(MAX(1,trsp_count_recv)))
7430!
7431!--    This MPI_SENDRECV should work even with odd mixture on 32 and 64 Bit
7432!--    variables in structure particle_type (due to the calculation of par_size)
7433       CALL MPI_SENDRECV( trnp, trnp_count*par_size, MPI_BYTE,      &
7434                          pnorth, 1, rvsp,                          &
7435                          trsp_count_recv*par_size, MPI_BYTE, psouth, 1,   &
7436                          comm2d, status, ierr )
7437
7438       IF ( trsp_count_recv > 0 )  CALL lpm_add_particles_to_gridcell(rvsp(1:trsp_count_recv))
7439
7440       DEALLOCATE(rvsp)
7441
7442       number_of_particles = number_of_particles + trsp_count_recv
7443
7444       DEALLOCATE( trsp, trnp )
7445
7446    ENDIF
7447
7448    DEALLOCATE( move_also_north )
7449    DEALLOCATE( move_also_south )
7450
7451#else
7452
7453    DO  ip = nxl, nxr, nxr-nxl
7454       DO  jp = nys, nyn
7455          DO  kp = nzb+1, nzt
7456             number_of_particles = prt_count(kp,jp,ip)
7457             IF ( number_of_particles <= 0 )  CYCLE
7458             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
7459             DO  n = 1, number_of_particles
7460!
7461!--             Apply boundary conditions
7462
7463                IF ( particles(n)%x < 0.0_wp )  THEN
7464
7465                   IF ( ibc_par_lr == 0 )  THEN
7466!
7467!--                   Cyclic boundary. Relevant coordinate has to be changed.
7468                      particles(n)%x = ( nx + 1 ) * dx + particles(n)%x
7469                      particles(n)%origin_x = ( nx + 1 ) * dx + &
7470                               particles(n)%origin_x
7471                   ELSEIF ( ibc_par_lr == 1 )  THEN
7472!
7473!--                   Particle absorption
7474                      particles(n)%particle_mask = .FALSE.
7475                      deleted_particles = deleted_particles + 1
7476
7477                   ELSEIF ( ibc_par_lr == 2 )  THEN
7478!
7479!--                   Particle reflection
7480                      particles(n)%x       = -dx - particles(n)%x
7481                      particles(n)%speed_x = -particles(n)%speed_x
7482                   ENDIF
7483
7484                ELSEIF ( particles(n)%x >= ( nx + 1) * dx )  THEN
7485
7486                   IF ( ibc_par_lr == 0 )  THEN
7487!
7488!--                   Cyclic boundary. Relevant coordinate has to be changed.
7489                      particles(n)%x = particles(n)%x - ( nx + 1 ) * dx
7490                      particles(n)%origin_x = particles(n)%origin_x - &
7491                               ( nx + 1 ) * dx
7492
7493                   ELSEIF ( ibc_par_lr == 1 )  THEN
7494!
7495!--                   Particle absorption
7496                      particles(n)%particle_mask = .FALSE.
7497                      deleted_particles = deleted_particles + 1
7498
7499                   ELSEIF ( ibc_par_lr == 2 )  THEN
7500!
7501!--                   Particle reflection
7502                      particles(n)%x       = ( nx + 1 ) * dx - particles(n)%x
7503                      particles(n)%speed_x = -particles(n)%speed_x
7504                   ENDIF
7505
7506                ENDIF
7507             ENDDO
7508          ENDDO
7509       ENDDO
7510    ENDDO
7511
7512    DO  ip = nxl, nxr
7513       DO  jp = nys, nyn, nyn-nys
7514          DO  kp = nzb+1, nzt
7515             number_of_particles = prt_count(kp,jp,ip)
7516             IF ( number_of_particles <= 0 )  CYCLE
7517             particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
7518             DO  n = 1, number_of_particles
7519
7520                IF ( particles(n)%y < 0.0_wp)  THEN
7521
7522                   IF ( ibc_par_ns == 0 )  THEN
7523!
7524!--                   Cyclic boundary. Relevant coordinate has to be changed.
7525                      particles(n)%y = ( ny + 1 ) * dy + particles(n)%y
7526                      particles(n)%origin_y = ( ny + 1 ) * dy + &
7527                           particles(n)%origin_y
7528
7529                   ELSEIF ( ibc_par_ns == 1 )  THEN
7530!
7531!--                   Particle absorption
7532                      particles(n)%particle_mask = .FALSE.
7533                      deleted_particles = deleted_particles + 1
7534
7535                   ELSEIF ( ibc_par_ns == 2 )  THEN
7536!
7537!--                   Particle reflection
7538                      particles(n)%y       = -dy - particles(n)%y
7539                      particles(n)%speed_y = -particles(n)%speed_y
7540                   ENDIF
7541
7542                ELSEIF ( particles(n)%y >= ( ny + 1) * dy )  THEN
7543
7544                   IF ( ibc_par_ns == 0 )  THEN
7545!
7546!--                   Cyclic boundary. Relevant coordinate has to be changed.
7547                      particles(n)%y = particles(n)%y - ( ny + 1 ) * dy
7548                      particles(n)%origin_y = particles(n)%origin_y - &
7549                                ( ny + 1 ) * dy
7550
7551                   ELSEIF ( ibc_par_ns == 1 )  THEN
7552!
7553!--                   Particle absorption
7554                      particles(n)%particle_mask = .FALSE.
7555                      deleted_particles = deleted_particles + 1
7556
7557                   ELSEIF ( ibc_par_ns == 2 )  THEN
7558!
7559!--                   Particle reflection
7560                      particles(n)%y       = ( ny + 1 ) * dy - particles(n)%y
7561                      particles(n)%speed_y = -particles(n)%speed_y
7562                   ENDIF
7563
7564                ENDIF
7565
7566             ENDDO
7567          ENDDO
7568       ENDDO
7569    ENDDO
7570#endif
7571
7572!
7573!-- Accumulate the number of particles transferred between the subdomains
7574#if defined( __parallel )
7575    trlp_count_sum      = trlp_count_sum      + trlp_count
7576    trlp_count_recv_sum = trlp_count_recv_sum + trlp_count_recv
7577    trrp_count_sum      = trrp_count_sum      + trrp_count
7578    trrp_count_recv_sum = trrp_count_recv_sum + trrp_count_recv
7579    trsp_count_sum      = trsp_count_sum      + trsp_count
7580    trsp_count_recv_sum = trsp_count_recv_sum + trsp_count_recv
7581    trnp_count_sum      = trnp_count_sum      + trnp_count
7582    trnp_count_recv_sum = trnp_count_recv_sum + trnp_count_recv
7583#endif
7584
7585    CALL cpu_log( log_point_s(23), 'lpm_exchange_horiz', 'stop' )
7586
7587 END SUBROUTINE lpm_exchange_horiz
7588
7589!------------------------------------------------------------------------------!
7590! Description:
7591! ------------
7592!> If a particle moves from one processor to another, this subroutine moves
7593!> the corresponding elements from the particle arrays of the old grid cells
7594!> to the particle arrays of the new grid cells.
7595!------------------------------------------------------------------------------!
7596 SUBROUTINE lpm_add_particles_to_gridcell (particle_array)
7597
7598    IMPLICIT NONE
7599
7600    INTEGER(iwp)        ::  ip        !< grid index (x) of particle
7601    INTEGER(iwp)        ::  jp        !< grid index (x) of particle
7602    INTEGER(iwp)        ::  kp        !< grid index (x) of particle
7603    INTEGER(iwp)        ::  n         !< index variable of particle
7604    INTEGER(iwp)        ::  pindex    !< dummy argument for new number of particles per grid box
7605
7606    LOGICAL             ::  pack_done !<
7607
7608    TYPE(particle_type), DIMENSION(:), INTENT(IN)  ::  particle_array !< new particles in a grid box
7609    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  temp_ns        !< temporary particle array for reallocation
7610
7611    pack_done     = .FALSE.
7612
7613    DO  n = 1, SIZE(particle_array)
7614
7615       IF ( .NOT. particle_array(n)%particle_mask )  CYCLE
7616
7617       ip = particle_array(n)%x * ddx
7618       jp = particle_array(n)%y * ddy
7619!
7620!--    In case of stretching the actual k index must be found
7621       IF ( dz_stretch_level /= -9999999.9_wp  .OR.         &
7622            dz_stretch_level_start(1) /= -9999999.9_wp )  THEN
7623          kp = MINLOC( ABS( particle_array(n)%z - zu ), DIM = 1 ) - 1
7624       ELSE
7625          kp = INT( particle_array(n)%z / dz(1) + 1 + offset_ocean_nzt )
7626       ENDIF
7627
7628       IF ( ip >= nxl  .AND.  ip <= nxr  .AND.  jp >= nys  .AND.  jp <= nyn    &
7629            .AND.  kp >= nzb+1  .AND.  kp <= nzt)  THEN ! particle stays on processor
7630          number_of_particles = prt_count(kp,jp,ip)
7631          particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
7632
7633          pindex = prt_count(kp,jp,ip)+1
7634          IF( pindex > SIZE(grid_particles(kp,jp,ip)%particles) )  THEN
7635             IF ( pack_done )  THEN
7636                CALL realloc_particles_array ( ip, jp, kp )
7637             ELSE
7638                CALL lpm_pack
7639                prt_count(kp,jp,ip) = number_of_particles
7640                pindex = prt_count(kp,jp,ip)+1
7641                IF ( pindex > SIZE(grid_particles(kp,jp,ip)%particles) )  THEN
7642                   CALL realloc_particles_array ( ip, jp, kp )
7643                ENDIF
7644                pack_done = .TRUE.
7645             ENDIF
7646          ENDIF
7647          grid_particles(kp,jp,ip)%particles(pindex) = particle_array(n)
7648          prt_count(kp,jp,ip) = pindex
7649       ELSE
7650          IF ( jp <= nys - 1 )  THEN
7651             nr_move_south = nr_move_south+1
7652!
7653!--          Before particle information is swapped to exchange-array, check
7654!--          if enough memory is allocated. If required, reallocate exchange
7655!--          array.
7656             IF ( nr_move_south > SIZE(move_also_south) )  THEN
7657!
7658!--             At first, allocate further temporary array to swap particle
7659!--             information.
7660                ALLOCATE( temp_ns(SIZE(move_also_south)+NR_2_direction_move) )
7661                temp_ns(1:nr_move_south-1) = move_also_south(1:nr_move_south-1)
7662                DEALLOCATE( move_also_south )
7663                ALLOCATE( move_also_south(SIZE(temp_ns)) )
7664                move_also_south(1:nr_move_south-1) = temp_ns(1:nr_move_south-1)
7665                DEALLOCATE( temp_ns )
7666
7667             ENDIF
7668
7669             move_also_south(nr_move_south) = particle_array(n)
7670
7671             IF ( jp == -1 )  THEN
7672!
7673!--             Apply boundary condition along y
7674                IF ( ibc_par_ns == 0 )  THEN
7675                   move_also_south(nr_move_south)%y =                          &
7676                      move_also_south(nr_move_south)%y + ( ny + 1 ) * dy
7677                   move_also_south(nr_move_south)%origin_y =                   &
7678                      move_also_south(nr_move_south)%origin_y + ( ny + 1 ) * dy
7679                ELSEIF ( ibc_par_ns == 1 )  THEN
7680!
7681!--                Particle absorption
7682                   move_also_south(nr_move_south)%particle_mask = .FALSE.
7683                   deleted_particles = deleted_particles + 1
7684
7685                ELSEIF ( ibc_par_ns == 2 )  THEN
7686!
7687!--                Particle reflection
7688                   move_also_south(nr_move_south)%y       =                    &
7689                      -move_also_south(nr_move_south)%y
7690                   move_also_south(nr_move_south)%speed_y =                    &
7691                      -move_also_south(nr_move_south)%speed_y
7692
7693                ENDIF
7694             ENDIF
7695          ELSEIF ( jp >= nyn+1 )  THEN
7696             nr_move_north = nr_move_north+1
7697!
7698!--          Before particle information is swapped to exchange-array, check
7699!--          if enough memory is allocated. If required, reallocate exchange
7700!--          array.
7701             IF ( nr_move_north > SIZE(move_also_north) )  THEN
7702!
7703!--             At first, allocate further temporary array to swap particle
7704!--             information.
7705                ALLOCATE( temp_ns(SIZE(move_also_north)+NR_2_direction_move) )
7706                temp_ns(1:nr_move_north-1) = move_also_south(1:nr_move_north-1)
7707                DEALLOCATE( move_also_north )
7708                ALLOCATE( move_also_north(SIZE(temp_ns)) )
7709                move_also_north(1:nr_move_north-1) = temp_ns(1:nr_move_north-1)
7710                DEALLOCATE( temp_ns )
7711
7712             ENDIF
7713
7714             move_also_north(nr_move_north) = particle_array(n)
7715             IF ( jp == ny+1 )  THEN
7716!
7717!--             Apply boundary condition along y
7718                IF ( ibc_par_ns == 0 )  THEN
7719
7720                   move_also_north(nr_move_north)%y =                          &
7721                      move_also_north(nr_move_north)%y - ( ny + 1 ) * dy
7722                   move_also_north(nr_move_north)%origin_y =                   &
7723                      move_also_north(nr_move_north)%origin_y - ( ny + 1 ) * dy
7724                ELSEIF ( ibc_par_ns == 1 )  THEN
7725!
7726!--                Particle absorption
7727                   move_also_north(nr_move_north)%particle_mask = .FALSE.
7728                   deleted_particles = deleted_particles + 1
7729
7730                ELSEIF ( ibc_par_ns == 2 )  THEN
7731!
7732!--                Particle reflection
7733                   move_also_north(nr_move_north)%y       =                    &
7734                      -move_also_north(nr_move_north)%y
7735                   move_also_north(nr_move_north)%speed_y =                    &
7736                      -move_also_north(nr_move_north)%speed_y
7737
7738                ENDIF
7739             ENDIF
7740          ELSE
7741             WRITE(0,'(a,8i7)') 'particle out of range ',myid,ip,jp,kp,nxl,nxr,nys,nyn
7742          ENDIF
7743       ENDIF
7744    ENDDO
7745
7746    RETURN
7747
7748 END SUBROUTINE lpm_add_particles_to_gridcell
7749 
7750 
7751!------------------------------------------------------------------------------!
7752! Description:
7753! ------------
7754!> If a particle moves from one grid cell to another (on the current
7755!> processor!), this subroutine moves the corresponding element from the
7756!> particle array of the old grid cell to the particle array of the new grid
7757!> cell.
7758!------------------------------------------------------------------------------!
7759 SUBROUTINE lpm_move_particle
7760 
7761    INTEGER(iwp)        ::  i           !< grid index (x) of particle position
7762    INTEGER(iwp)        ::  ip          !< index variable along x
7763    INTEGER(iwp)        ::  j           !< grid index (y) of particle position
7764    INTEGER(iwp)        ::  jp          !< index variable along y
7765    INTEGER(iwp)        ::  k           !< grid index (z) of particle position
7766    INTEGER(iwp)        ::  kp          !< index variable along z
7767    INTEGER(iwp)        ::  n           !< index variable for particle array
7768    INTEGER(iwp)        ::  np_before_move !< number of particles per grid box before moving
7769    INTEGER(iwp)        ::  pindex      !< dummy argument for number of new particle per grid box
7770
7771    TYPE(particle_type), DIMENSION(:), POINTER  ::  particles_before_move !< particles before moving
7772
7773    CALL cpu_log( log_point_s(41), 'lpm_move_particle', 'start' )
7774    CALL lpm_check_cfl
7775    DO  ip = nxl, nxr
7776       DO  jp = nys, nyn
7777          DO  kp = nzb+1, nzt
7778
7779             np_before_move = prt_count(kp,jp,ip)
7780             IF ( np_before_move <= 0 )  CYCLE
7781             particles_before_move => grid_particles(kp,jp,ip)%particles(1:np_before_move)
7782
7783             DO  n = 1, np_before_move
7784                i = particles_before_move(n)%x * ddx
7785                j = particles_before_move(n)%y * ddy
7786                k = kp
7787!
7788!--             Find correct vertical particle grid box (necessary in case of grid stretching)
7789!--             Due to the CFL limitations only the neighbouring grid boxes are considered.
7790                IF( zw(k)   < particles_before_move(n)%z ) k = k + 1
7791                IF( zw(k-1) > particles_before_move(n)%z ) k = k - 1 
7792
7793!--             For lpm_exchange_horiz to work properly particles need to be moved to the outermost gridboxes
7794!--             of the respective processor. If the particle index is inside the processor the following lines
7795!--             will not change the index
7796                i = MIN ( i , nxr )
7797                i = MAX ( i , nxl )
7798                j = MIN ( j , nyn )
7799                j = MAX ( j , nys )
7800
7801                k = MIN ( k , nzt )
7802                k = MAX ( k , nzb+1 )
7803
7804!
7805!--             Check, if particle has moved to another grid cell.
7806                IF ( i /= ip  .OR.  j /= jp  .OR.  k /= kp )  THEN
7807!!
7808!--                If the particle stays on the same processor, the particle
7809!--                will be added to the particle array of the new processor.
7810                   number_of_particles = prt_count(k,j,i)
7811                   particles => grid_particles(k,j,i)%particles(1:number_of_particles)
7812
7813                   pindex = prt_count(k,j,i)+1
7814                   IF (  pindex > SIZE(grid_particles(k,j,i)%particles)  )     &
7815                   THEN
7816                      CALL realloc_particles_array( i, j, k )
7817                   ENDIF
7818
7819                   grid_particles(k,j,i)%particles(pindex) = particles_before_move(n)
7820                   prt_count(k,j,i) = pindex
7821
7822                   particles_before_move(n)%particle_mask = .FALSE.
7823                ENDIF
7824             ENDDO
7825
7826          ENDDO
7827       ENDDO
7828    ENDDO
7829
7830    CALL cpu_log( log_point_s(41), 'lpm_move_particle', 'stop' )
7831
7832    RETURN
7833
7834 END SUBROUTINE lpm_move_particle
7835 
7836
7837!------------------------------------------------------------------------------!
7838! Description:
7839! ------------
7840!> Check CFL-criterion for each particle. If one particle violated the
7841!> criterion the particle will be deleted and a warning message is given.
7842!------------------------------------------------------------------------------!
7843 SUBROUTINE lpm_check_cfl 
7844
7845    IMPLICIT NONE
7846
7847    INTEGER(iwp)  ::  i !< running index, x-direction
7848    INTEGER(iwp)  ::  j !< running index, y-direction
7849    INTEGER(iwp)  ::  k !< running index, z-direction
7850    INTEGER(iwp)  ::  n !< running index, number of particles
7851
7852    DO  i = nxl, nxr
7853       DO  j = nys, nyn
7854          DO  k = nzb+1, nzt
7855             number_of_particles = prt_count(k,j,i)
7856             IF ( number_of_particles <= 0 )  CYCLE
7857             particles => grid_particles(k,j,i)%particles(1:number_of_particles)         
7858             DO  n = 1, number_of_particles
7859!
7860!--             Note, check for CFL does not work at first particle timestep
7861!--             when both, age and age_m are zero.
7862                IF ( particles(n)%age - particles(n)%age_m > 0.0_wp )  THEN 
7863                   IF(ABS(particles(n)%speed_x) >                              &
7864                      (dx/(particles(n)%age-particles(n)%age_m))  .OR.         &
7865                      ABS(particles(n)%speed_y) >                              & 
7866                      (dy/(particles(n)%age-particles(n)%age_m))  .OR.         &
7867                      ABS(particles(n)%speed_z) >                              &
7868                      ((zw(k)-zw(k-1))/(particles(n)%age-particles(n)%age_m))) &
7869                   THEN
7870                      WRITE( message_string, * )                               &
7871                      'Particle violated CFL-criterion: &particle with id ',   &
7872                      particles(n)%id, ' will be deleted!'   
7873                      CALL message( 'lpm_check_cfl', 'PA0475', 0, 1, -1, 6, 0 )
7874                      particles(n)%particle_mask= .FALSE.
7875                   ENDIF
7876                ENDIF
7877             ENDDO
7878          ENDDO
7879       ENDDO
7880    ENDDO   
7881
7882 END SUBROUTINE lpm_check_cfl
7883 
7884 
7885!------------------------------------------------------------------------------!
7886! Description:
7887! ------------
7888!> If the allocated memory for the particle array do not suffice to add arriving
7889!> particles from neighbour grid cells, this subrouting reallocates the
7890!> particle array to assure enough memory is available.
7891!------------------------------------------------------------------------------!
7892 SUBROUTINE realloc_particles_array ( i, j, k, size_in )
7893
7894    INTEGER(iwp), INTENT(IN)                       ::  i              !<
7895    INTEGER(iwp), INTENT(IN)                       ::  j              !<
7896    INTEGER(iwp), INTENT(IN)                       ::  k              !<
7897    INTEGER(iwp), INTENT(IN), OPTIONAL             ::  size_in        !<
7898
7899    INTEGER(iwp)                                   ::  old_size        !<
7900    INTEGER(iwp)                                   ::  new_size        !<
7901    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  tmp_particles_d !<
7902    TYPE(particle_type), DIMENSION(500)            ::  tmp_particles_s !<
7903
7904    old_size = SIZE(grid_particles(k,j,i)%particles)
7905
7906    IF ( PRESENT(size_in) )   THEN
7907       new_size = size_in
7908    ELSE
7909       new_size = old_size * ( 1.0_wp + alloc_factor / 100.0_wp )
7910    ENDIF
7911
7912    new_size = MAX( new_size, 1, old_size + 1 )
7913
7914    IF ( old_size <= 500 )  THEN
7915
7916       tmp_particles_s(1:old_size) = grid_particles(k,j,i)%particles(1:old_size)
7917
7918       DEALLOCATE(grid_particles(k,j,i)%particles)
7919       ALLOCATE(grid_particles(k,j,i)%particles(new_size))
7920
7921       grid_particles(k,j,i)%particles(1:old_size)          = tmp_particles_s(1:old_size)
7922       grid_particles(k,j,i)%particles(old_size+1:new_size) = zero_particle
7923
7924    ELSE
7925
7926       ALLOCATE(tmp_particles_d(new_size))
7927       tmp_particles_d(1:old_size) = grid_particles(k,j,i)%particles
7928
7929       DEALLOCATE(grid_particles(k,j,i)%particles)
7930       ALLOCATE(grid_particles(k,j,i)%particles(new_size))
7931
7932       grid_particles(k,j,i)%particles(1:old_size)          = tmp_particles_d(1:old_size)
7933       grid_particles(k,j,i)%particles(old_size+1:new_size) = zero_particle
7934
7935       DEALLOCATE(tmp_particles_d)
7936
7937    ENDIF
7938    particles => grid_particles(k,j,i)%particles(1:new_size)
7939
7940    RETURN
7941   
7942 END SUBROUTINE realloc_particles_array
7943 
7944 
7945!------------------------------------------------------------------------------!
7946! Description:
7947! ------------
7948!> Not needed but allocated space for particles is dealloced.
7949!------------------------------------------------------------------------------!
7950 SUBROUTINE dealloc_particles_array
7951
7952 
7953    INTEGER(iwp) ::  i               !<
7954    INTEGER(iwp) ::  j               !<
7955    INTEGER(iwp) ::  k               !<
7956    INTEGER(iwp) ::  old_size        !<
7957    INTEGER(iwp) ::  new_size        !<
7958
7959    LOGICAL ::  dealloc
7960
7961    TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  tmp_particles_d !<
7962    TYPE(particle_type), DIMENSION(500)            ::  tmp_particles_s !<
7963
7964    DO  i = nxl, nxr
7965       DO  j = nys, nyn
7966          DO  k = nzb+1, nzt
7967!
7968!--          Determine number of active particles
7969             number_of_particles = prt_count(k,j,i)
7970!
7971!--          Determine allocated memory size
7972             old_size = SIZE( grid_particles(k,j,i)%particles )
7973!
7974!--          Check for large unused memory
7975             dealloc = ( ( number_of_particles < 1 .AND.         &
7976                           old_size            > 1 )  .OR.       &
7977                         ( number_of_particles > 1 .AND.         &
7978                           old_size - number_of_particles *                    &
7979                              ( 1.0_wp + 0.01_wp * alloc_factor ) > 0.0_wp ) )
7980
7981             IF ( dealloc )  THEN
7982                IF ( number_of_particles < 1 )  THEN
7983                   new_size = 1
7984                ELSE
7985                   new_size = INT( number_of_particles * ( 1.0_wp + 0.01_wp * alloc_factor ) )
7986                ENDIF
7987
7988                IF ( number_of_particles <= 500 )  THEN
7989
7990                   tmp_particles_s(1:number_of_particles) = grid_particles(k,j,i)%particles(1:number_of_particles)
7991
7992                   DEALLOCATE(grid_particles(k,j,i)%particles)
7993                   ALLOCATE(grid_particles(k,j,i)%particles(new_size))
7994
7995                   grid_particles(k,j,i)%particles(1:number_of_particles)          = tmp_particles_s(1:number_of_particles)
7996                   grid_particles(k,j,i)%particles(number_of_particles+1:new_size) = zero_particle
7997
7998                ELSE
7999
8000                   ALLOCATE(tmp_particles_d(number_of_particles))
8001                   tmp_particles_d(1:number_of_particles) = grid_particles(k,j,i)%particles(1:number_of_particles)
8002
8003                   DEALLOCATE(grid_particles(k,j,i)%particles)
8004                   ALLOCATE(grid_particles(k,j,i)%particles(new_size))
8005
8006                   grid_particles(k,j,i)%particles(1:number_of_particles)          = tmp_particles_d(1:number_of_particles)
8007                   grid_particles(k,j,i)%particles(number_of_particles+1:new_size) = zero_particle
8008
8009                   DEALLOCATE(tmp_particles_d)
8010
8011                ENDIF
8012
8013             ENDIF
8014          ENDDO
8015       ENDDO
8016    ENDDO
8017
8018 END SUBROUTINE dealloc_particles_array 
8019 
8020 
8021!------------------------------------------------------------------------------!
8022! Description:
8023! -----------
8024!> Routine for the whole processor
8025!> Sort all particles into the 8 respective subgrid boxes (in case of trilinear
8026!> interpolation method) and free space of particles which has been marked for
8027!> deletion.
8028!------------------------------------------------------------------------------!
8029   SUBROUTINE lpm_sort_and_delete
8030
8031       INTEGER(iwp) ::  i  !<
8032       INTEGER(iwp) ::  ip !<
8033       INTEGER(iwp) ::  is !<
8034       INTEGER(iwp) ::  j  !<
8035       INTEGER(iwp) ::  jp !<
8036       INTEGER(iwp) ::  kp !<
8037       INTEGER(iwp) ::  m  !<
8038       INTEGER(iwp) ::  n  !<
8039       INTEGER(iwp) ::  nn !<
8040       INTEGER(iwp) ::  sort_index  !<
8041
8042       INTEGER(iwp), DIMENSION(0:7) ::  sort_count  !<
8043
8044       TYPE(particle_type), DIMENSION(:,:), ALLOCATABLE ::  sort_particles    !<
8045
8046       CALL cpu_log( log_point_s(51), 'lpm_sort_and_delete', 'start' )
8047       IF ( interpolation_trilinear )  THEN
8048          DO  ip = nxl, nxr
8049             DO  jp = nys, nyn
8050                DO  kp = nzb+1, nzt
8051                   number_of_particles = prt_count(kp,jp,ip)
8052                   IF ( number_of_particles <= 0 )  CYCLE
8053                   particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
8054                   nn = 0
8055                   sort_count = 0
8056                   ALLOCATE( sort_particles(number_of_particles, 0:7) )
8057
8058                   DO  n = 1, number_of_particles
8059                      sort_index = 0
8060
8061                      IF ( particles(n)%particle_mask )  THEN
8062                         nn = nn + 1
8063!
8064!--                      Sorting particles with a binary scheme
8065!--                      sort_index=111_2=7_10 -> particle at the left,south,bottom subgridbox
8066!--                      sort_index=000_2=0_10 -> particle at the right,north,top subgridbox
8067!--                      For this the center of the gridbox is calculated
8068                         i = (particles(n)%x + 0.5_wp * dx) * ddx
8069                         j = (particles(n)%y + 0.5_wp * dy) * ddy
8070
8071                         IF ( i == ip )  sort_index = sort_index + 4
8072                         IF ( j == jp )  sort_index = sort_index + 2
8073                         IF ( zu(kp) > particles(n)%z ) sort_index = sort_index + 1
8074
8075                         sort_count(sort_index) = sort_count(sort_index) + 1
8076                         m = sort_count(sort_index)
8077                         sort_particles(m,sort_index) = particles(n)
8078                         sort_particles(m,sort_index)%block_nr = sort_index
8079                      ENDIF
8080                   ENDDO
8081!
8082!--                Delete and resort particles by overwritting and set
8083!--                the number_of_particles to the actual value.
8084                   nn = 0
8085                   DO  is = 0,7
8086                      grid_particles(kp,jp,ip)%start_index(is) = nn + 1
8087                      DO  n = 1,sort_count(is)
8088                         nn = nn + 1
8089                         particles(nn) = sort_particles(n,is)
8090                      ENDDO
8091                      grid_particles(kp,jp,ip)%end_index(is) = nn
8092                   ENDDO
8093
8094                   number_of_particles = nn
8095                   prt_count(kp,jp,ip) = number_of_particles
8096                   DEALLOCATE(sort_particles)
8097                ENDDO
8098             ENDDO
8099          ENDDO
8100
8101!--    In case of the simple interpolation method the particles must not
8102!--    be sorted in subboxes. Particles marked for deletion however, must be
8103!--    deleted and number of particles must be recalculated as it is also
8104!--    done for the trilinear particle advection interpolation method.
8105       ELSE
8106
8107          DO  ip = nxl, nxr
8108             DO  jp = nys, nyn
8109                DO  kp = nzb+1, nzt
8110
8111                   number_of_particles = prt_count(kp,jp,ip)
8112                   IF ( number_of_particles <= 0 )  CYCLE
8113                   particles => grid_particles(kp,jp,ip)%particles(1:number_of_particles)
8114!
8115!--                Repack particles array, i.e. delete particles and recalculate
8116!--                number of particles
8117                   CALL lpm_pack
8118                   prt_count(kp,jp,ip) = number_of_particles
8119                ENDDO
8120             ENDDO
8121          ENDDO
8122       ENDIF
8123       CALL cpu_log( log_point_s(51), 'lpm_sort_and_delete', 'stop' )
8124
8125    END SUBROUTINE lpm_sort_and_delete
8126
8127 
8128!------------------------------------------------------------------------------!
8129! Description:
8130! ------------
8131!> Move all particles not marked for deletion to lowest indices (packing)
8132!------------------------------------------------------------------------------!
8133    SUBROUTINE lpm_pack
8134
8135       INTEGER(iwp) ::  n       !<
8136       INTEGER(iwp) ::  nn      !<
8137!
8138!--    Find out elements marked for deletion and move data from highest index
8139!--    values to these free indices
8140       nn = number_of_particles
8141
8142       DO WHILE ( .NOT. particles(nn)%particle_mask )
8143          nn = nn-1
8144          IF ( nn == 0 )  EXIT
8145       ENDDO
8146
8147       IF ( nn > 0 )  THEN
8148          DO  n = 1, number_of_particles
8149             IF ( .NOT. particles(n)%particle_mask )  THEN
8150                particles(n) = particles(nn)
8151                nn = nn - 1
8152                DO WHILE ( .NOT. particles(nn)%particle_mask )
8153                   nn = nn-1
8154                   IF ( n == nn )  EXIT
8155                ENDDO
8156             ENDIF
8157             IF ( n == nn )  EXIT
8158          ENDDO
8159       ENDIF
8160
8161!
8162!--    The number of deleted particles has been determined in routines
8163!--    lpm_boundary_conds, lpm_droplet_collision, and lpm_exchange_horiz
8164       number_of_particles = nn
8165
8166    END SUBROUTINE lpm_pack 
8167
8168
8169!------------------------------------------------------------------------------!
8170! Description:
8171! ------------
8172!> Sort particles in each sub-grid box into two groups: particles that already
8173!> completed the LES timestep, and particles that need further timestepping to
8174!> complete the LES timestep.
8175!------------------------------------------------------------------------------!
8176    SUBROUTINE lpm_sort_timeloop_done
8177
8178       INTEGER(iwp) ::  end_index     !< particle end index for each sub-box
8179       INTEGER(iwp) ::  i             !< index of particle grid box in x-direction
8180       INTEGER(iwp) ::  j             !< index of particle grid box in y-direction
8181       INTEGER(iwp) ::  k             !< index of particle grid box in z-direction
8182       INTEGER(iwp) ::  n             !< running index for number of particles
8183       INTEGER(iwp) ::  nb            !< index of subgrid boux
8184       INTEGER(iwp) ::  nf            !< indices for particles in each sub-box that already finalized their substeps
8185       INTEGER(iwp) ::  nnf           !< indices for particles in each sub-box that need further treatment
8186       INTEGER(iwp) ::  num_finalized !< number of particles in each sub-box that already finalized their substeps
8187       INTEGER(iwp) ::  start_index   !< particle start index for each sub-box
8188
8189       TYPE(particle_type), DIMENSION(:), ALLOCATABLE ::  sort_particles  !< temporary particle array
8190
8191       DO  i = nxl, nxr
8192          DO  j = nys, nyn
8193             DO  k = nzb+1, nzt
8194
8195                number_of_particles = prt_count(k,j,i)
8196                IF ( number_of_particles <= 0 )  CYCLE
8197                particles => grid_particles(k,j,i)%particles(1:number_of_particles)
8198
8199                DO  nb = 0, 7
8200!
8201!--                Obtain start and end index for each subgrid box
8202                   start_index = grid_particles(k,j,i)%start_index(nb)
8203                   end_index   = grid_particles(k,j,i)%end_index(nb)
8204!
8205!--                Allocate temporary array used for sorting.
8206                   ALLOCATE( sort_particles(start_index:end_index) )
8207!
8208!--                Determine number of particles already completed the LES
8209!--                timestep, and write them into a temporary array.
8210                   nf = start_index
8211                   num_finalized = 0
8212                   DO  n = start_index, end_index
8213                      IF ( dt_3d - particles(n)%dt_sum < 1E-8_wp )  THEN
8214                         sort_particles(nf) = particles(n)
8215                         nf                 = nf + 1
8216                         num_finalized      = num_finalized + 1
8217                      ENDIF
8218                   ENDDO
8219!
8220!--                Determine number of particles that not completed the LES
8221!--                timestep, and write them into a temporary array.
8222                   nnf = nf
8223                   DO  n = start_index, end_index
8224                      IF ( dt_3d - particles(n)%dt_sum > 1E-8_wp )  THEN
8225                         sort_particles(nnf) = particles(n)
8226                         nnf                 = nnf + 1
8227                      ENDIF
8228                   ENDDO
8229!
8230!--                Write back sorted particles
8231                   particles(start_index:end_index) =                          &
8232                                           sort_particles(start_index:end_index)
8233!
8234!--                Determine updated start_index, used to masked already
8235!--                completed particles.
8236                   grid_particles(k,j,i)%start_index(nb) =                     &
8237                                      grid_particles(k,j,i)%start_index(nb)    &
8238                                    + num_finalized
8239!
8240!--                Deallocate dummy array
8241                   DEALLOCATE ( sort_particles )
8242!
8243!--                Finally, if number of non-completed particles is non zero
8244!--                in any of the sub-boxes, set control flag appropriately.
8245                   IF ( nnf > nf )                                             &
8246                      grid_particles(k,j,i)%time_loop_done = .FALSE.
8247
8248                ENDDO
8249             ENDDO
8250          ENDDO
8251       ENDDO
8252
8253    END SUBROUTINE lpm_sort_timeloop_done 
8254
8255END MODULE lagrangian_particle_model_mod
Note: See TracBrowser for help on using the repository browser.