source: palm/trunk/SOURCE/multi_agent_system_mod.f90 @ 3797

Last change on this file since 3797 was 3766, checked in by raasch, 5 years ago

unused_variables removed, bugfix in im_define_netcdf_grid argument list, trim added to avoid truncation compiler warnings, save attribute added to local targets to avoid outlive pointer target warning, first argument removed from module_interface_rrd_*, file module_interface reformatted with respect to coding standards, bugfix in surface_data_output_rrd_local (variable k removed)

  • Property svn:keywords set to Id
File size: 198.2 KB
Line 
1!> @file multi_agent_system_mod.f90
2!--------------------------------------------------------------------------------!
3! This file is part of PALM-4U.
4!
5! PALM-4U 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-4U 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 2016 Leibniz Universitaet Hannover
18!------------------------------------------------------------------------------!
19!
20! Current revisions:
21! ------------------
22!
23!
24! Former revisions:
25! -----------------
26! $Id: multi_agent_system_mod.f90 3766 2019-02-26 16:23:41Z forkel $
27! save attribute added to local targets to avoid outlive pointer target warning
28!
29! 3665 2019-01-10 08:28:24Z raasch
30! unused variables removed
31!
32! 3602 2018-12-04 16:03:51Z sward
33! Added check for missing NAVIGATION_DATA input file
34!
35! 3601 2018-12-04 16:00:04Z sward
36! Replace degree symbol by degree_C/degrees
37!
38! 3587 2018-11-30 13:52:19Z sward
39! Added output of agent substep time
40!
41! 3525 2018-11-14 16:06:14Z kanani
42! Changes related to clean-up of biometeorology (dom_dwd_user)
43!
44! 3448 2018-10-29 18:14:31Z kanani
45! Adjustment of biometeorology calls,
46! implement some agent biometeorology
47!
48! 3274 2018-09-24 15:42:55Z knoop
49! Modularization of all bulk cloud physics code components
50!
51! 3268 2018-09-21 13:45:37Z sward
52! Cleaned up agent pointer assignment in output routine
53!
54! 3248 2018-09-14 09:42:06Z sward
55! Minor formating changes
56!
57! 3246 2018-09-13 15:14:50Z sward
58! Added error handling for input namelist via parin_fail_message
59!
60! 3241 2018-09-12 15:02:00Z raasch
61! unused variables removed
62!
63! 3235 2018-09-07 14:06:15Z sward
64! Bugfix in output, added agent-number dimension and related messages and
65! input parameters, updated cpu logging, added mas_last_actions
66!
67! 3201 2018-08-20 11:45:01Z sward
68! Bugfix, missing pre-processor directive. Set default
69! read_agents_from_restartfile = .FALSE. restarts not yet implemented.
70!
71! 3198 2018-08-15 09:23:10Z sward
72! Now using time_since_reference_point; moved multi_agent_system_start and
73! multi_agent_system_end to control_parameters; renamed NAMELIST agents_par to
74! agent_parameters
75!
76! 3187 2018-07-31 10:32:34Z sward
77! Reworked agent pathfinding to avoid collisions with walls
78!
79! 3165 2018-07-24 13:12:42Z sward
80! Added agent ID output
81!
82! 3160 2018-07-20 11:52:56Z sward
83! Changed C_SIZEOF to STORAGE_SIZE
84!
85! 3159 2018-07-20 11:20:01Z sward
86! Initial revision
87!
88!
89!
90! Authors:
91! --------
92! @author sward
93!
94!
95! Description:
96! ------------
97!> Multi Agent System for the simulation of pedestrian movement in urban
98!> environments
99!------------------------------------------------------------------------------!
100 MODULE multi_agent_system_mod
101
102    USE, INTRINSIC ::  ISO_C_BINDING
103
104    USE basic_constants_and_equations_mod,                                     &
105        ONLY:  pi
106
107    USE control_parameters,                                                    &
108        ONLY:  biometeorology, dt_3d, dt_write_agent_data, message_string,     &
109               time_since_reference_point
110
111    USE cpulog,                                                                &
112        ONLY:  cpu_log, log_point, log_point_s
113
114    USE grid_variables,                                                        &
115        ONLY:  ddx, ddy, dx, dy
116
117    USE indices,                                                               &
118        ONLY:  nx, nxl, nxlg, nxr, nxrg, ny, nyn, nyng, nys, nysg, nzb,        &
119               wall_flags_0
120
121    USE random_function_mod,                                                   &
122        ONLY:  random_function
123
124    USE kinds
125
126    USE pegrid
127
128    CHARACTER(LEN=15) ::  bc_mas_lr = 'absorb'  !< left/right boundary condition
129    CHARACTER(LEN=15) ::  bc_mas_ns = 'absorb'  !< north/south boundary condition
130
131    INTEGER(iwp) ::  deleted_agents = 0                !< number of deleted agents per time step
132    INTEGER(iwp) ::  dim_size_agtnum_manual = 9999999  !< namelist parameter (see documentation)
133    INTEGER(iwp) ::  heap_count                        !< number of items in binary heap (for pathfinding)
134    INTEGER(iwp) ::  ibc_mas_lr                        !< agent left/right boundary condition dummy
135    INTEGER(iwp) ::  ibc_mas_ns                        !< agent north/south boundary condition dummy
136!    INTEGER(iwp) ::  ind_pm10 = -9                     !< chemical species index of PM10
137!    INTEGER(iwp) ::  ind_pm25 = -9                     !< chemical species index of PM2.5
138    INTEGER(iwp) ::  iran_agent = -1234567             !< number for random generator
139    INTEGER(iwp) ::  min_nr_agent = 2                  !< namelist parameter (see documentation)
140    INTEGER(iwp) ::  ghla_count_recv                   !< number of agents in left ghost layer
141    INTEGER(iwp) ::  ghna_count_recv                   !< number of agents in north ghost layer
142    INTEGER(iwp) ::  ghra_count_recv                   !< number of agents in right ghost layer
143    INTEGER(iwp) ::  ghsa_count_recv                   !< number of agents in south ghost layer
144    INTEGER(iwp) ::  maximum_number_of_agents = 0      !< maximum number of agents during run
145    INTEGER(iwp) ::  nr_move_north                     !< number of agts to move north during exchange_horiz
146    INTEGER(iwp) ::  nr_move_south                     !< number of agts to move south during exchange_horiz
147    INTEGER(iwp) ::  number_of_agents = 0              !< number of agents for each grid box (3d array is saved on agt_count)
148    INTEGER(iwp) ::  number_of_agent_groups = 1        !< namelist parameter (see documentation)
149    INTEGER(iwp) ::  sort_count_mas = 0                !< counter for sorting agents
150    INTEGER(iwp) ::  agt_path_size = 15                !< size of agent path array
151    INTEGER(iwp) ::  step_dealloc_mas = 100            !< namelist parameter (see documentation)
152    INTEGER(iwp) ::  total_number_of_agents            !< total number of agents in the whole model domain
153
154    INTEGER(iwp), PARAMETER ::  NR_2_direction_move = 10000 !< parameter for agent exchange
155    INTEGER(iwp), PARAMETER ::  PHASE_INIT    = 1           !< phase parameter
156    INTEGER(iwp), PARAMETER ::  PHASE_RELEASE = 2           !< phase parameter
157
158    INTEGER(iwp), PARAMETER ::  max_number_of_agent_groups = 100 !< maximum allowed number of agent groups
159
160    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  agt_count         !< 3d array of number of agents of every grid box
161    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  s_measure_height  !< k-index(s-grid) for measurement
162    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  top_top_s         !< k-index of first s-gridpoint above topography
163    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  top_top_w         !< k-index of first v-gridpoint above topography
164    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  obstacle_flags    !< flags to identify corners and edges of topography that cannot be crossed by agents
165
166    LOGICAL ::  deallocate_memory_mas = .TRUE.          !< namelist parameter (see documentation)
167    LOGICAL ::  dt_3d_reached_mas                       !< flag: agent timestep has reached model timestep
168    LOGICAL ::  dt_3d_reached_l_mas                     !< flag: agent timestep has reached model timestep
169    LOGICAL ::  agents_active = .FALSE.                 !< flag for agent system
170    LOGICAL ::  random_start_position_agents = .TRUE.   !< namelist parameter (see documentation)
171    LOGICAL ::  read_agents_from_restartfile = .FALSE.  !< namelist parameter (see documentation)
172    LOGICAL ::  agent_own_timestep = .FALSE.            !< namelist parameter (see documentation)
173
174    LOGICAL, DIMENSION(max_number_of_agent_groups) ::  a_rand_target = .FALSE. !< namelist parameter (see documentation)
175
176    REAL(wp) ::  agent_maximum_age = 9999999.9_wp          !< namelist parameter (see documentation)
177    REAL(wp) ::  agent_substep_time = 0.0_wp               !< time measurement during one LES timestep
178    REAL(wp) ::  alloc_factor_mas = 20.0_wp                !< namelist parameter (see documentation)
179    REAL(wp) ::  coll_t_0 = 3.                             !< namelist parameter (see documentation)
180    REAL(wp) ::  corner_gate_start = 0.5_wp                !< namelist parameter (see documentation)
181    REAL(wp) ::  corner_gate_width = 1.0_wp                !< namelist parameter (see documentation)
182    REAL(wp) ::  dim_size_factor_agtnum = 1.0_wp           !< namelist parameter (see documentation)
183    REAL(wp) ::  d_sigma_rep_agent                         !< inverse of sigma_rep_agent
184    REAL(wp) ::  d_sigma_rep_wall                          !< inverse of sigma_rep_wall
185    REAL(wp) ::  d_tau_accel_agent                         !< inverse of tau_accel_agent
186    REAL(wp) ::  desired_speed = 1.2_wp                    !< namelist parameter (see documentation)
187    REAL(wp) ::  des_sp_sig = .2_wp                        !< namelist parameter (see documentation)
188    REAL(wp) ::  dist_target_reached = 2.0_wp              !< distance at which target counts as reached
189    REAL(wp) ::  dist_to_int_target = .25_wp               !< namelist parameter (see documentation)
190    REAL(wp) ::  dt_agent = 0.02_wp                        !< namelist parameter (see documentation)
191    REAL(wp) ::  dt_arel = 9999999.9_wp                    !< namelist parameter (see documentation)
192    REAL(wp) ::  end_time_arel = 9999999.9_wp              !< namelist parameter (see documentation)
193    REAL(wp) ::  force_x                                   !< dummy value for force on current agent in x-direction
194    REAL(wp) ::  force_y                                   !< dummy value for force on current agent in y-direction
195    REAL(wp) ::  max_dist_from_path = 0.25_wp              !< distance from current path at which a new path is calculated
196    REAL(wp) ::  radius_agent = .25_wp                     !< namelist parameter (see documentation)
197    REAL(wp) ::  repuls_agent = 1.5_wp                     !< namelist parameter (see documentation)
198    REAL(wp) ::  repuls_wall = 7.0_wp                      !< namelist parameter (see documentation)
199    REAL(wp) ::  scan_radius_agent = 3.0_wp                !< namelist parameter (see documentation)
200    REAL(wp) ::  scan_radius_wall = 2.0_wp                 !< namelist parameter (see documentation)
201    REAL(wp) ::  sigma_rep_agent = 0.3_wp                  !< namelist parameter (see documentation)
202    REAL(wp) ::  sigma_rep_wall = 0.1_wp                   !< namelist parameter (see documentation)
203    REAL(wp) ::  tau_accel_agent = 0.5_wp                  !< namelist parameter (see documentation)
204    REAL(wp) ::  time_arel = 0.0_wp                        !< time for agent release
205    REAL(wp) ::  time_write_agent_data = 0.0_wp            !< write agent data at current time on file
206    REAL(wp) ::  v_max_agent = 1.3_wp                      !< namelist parameter (see documentation)
207
208    REAL(wp), DIMENSION(:), ALLOCATABLE ::  dummy_path_x  !<  dummy path (x-coordinate)
209    REAL(wp), DIMENSION(:), ALLOCATABLE ::  dummy_path_y  !<  dummy path (y-coordinate)
210
211    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  adx = 9999999.9_wp  !< namelist parameter (see documentation)
212    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  ady = 9999999.9_wp  !< namelist parameter (see documentation)
213    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  asl = 9999999.9_wp  !< namelist parameter (see documentation)
214    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  asn = 9999999.9_wp  !< namelist parameter (see documentation)
215    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  asr = 9999999.9_wp  !< namelist parameter (see documentation)
216    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  ass = 9999999.9_wp  !< namelist parameter (see documentation)
217    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  at_x = 9999999.9_wp !< namelist parameter (see documentation)
218    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  at_y = 9999999.9_wp !< namelist parameter (see documentation)
219!
220!-- Type for the definition of an agent
221    TYPE agent_type
222        INTEGER(iwp) ::  block_nr             !< number for sorting
223        INTEGER(iwp) ::  group                !< number of agent group
224        INTEGER(idp) ::  id                   !< particle ID (64 bit integer)
225        INTEGER(iwp) ::  path_counter         !< current target along path (path_x/y)
226        LOGICAL      ::  agent_mask           !< if this parameter is set to false the agent will be deleted
227        REAL(wp)     ::  age                  !< age of agent
228        REAL(wp)     ::  age_m                !< age of agent
229        REAL(wp)     ::  dt_sum               !< sum of agents subtimesteps
230        REAL(wp)     ::  clo                  !< clothing index
231        REAL(wp)     ::  energy_storage       !< energy stored by agent
232        REAL(wp)     ::  clothing_temp        !< energy stored by agent
233        REAL(wp)     ::  actlev               !< metabolic + work energy of the person
234        REAL(wp)     ::  age_years            !< physical age of the person
235        REAL(wp)     ::  weight               !< total weight of the person (kg)
236        REAL(wp)     ::  height               !< height of the person (m)
237        REAL(wp)     ::  work                 !< workload of the agent (W)
238        INTEGER(iwp) ::  sex                  !< agents gender: 1 = male, 2 = female
239        REAL(wp)     ::  force_x              !< force term x-direction
240        REAL(wp)     ::  force_y              !< force term y-direction
241        REAL(wp)     ::  origin_x             !< origin x-position of agent
242        REAL(wp)     ::  origin_y             !< origin y-position of agent
243        REAL(wp)     ::  pm10                 !< PM10 concentration at agent position
244        REAL(wp)     ::  pm25                 !< PM25 concentration at agent position
245        REAL(wp)     ::  speed_abs            !< absolute value of agent speed
246        REAL(wp)     ::  speed_e_x            !< normalized speed of agent in x
247        REAL(wp)     ::  speed_e_y            !< normalized speed of agent in y
248        REAL(wp)     ::  speed_des            !< agent's desired speed
249        REAL(wp)     ::  speed_x              !< speed of agent in x
250        REAL(wp)     ::  speed_y              !< speed of agent in y
251        REAL(wp)     ::  ipt                  !< instationary thermal index iPT (degree_C)
252        REAL(wp)     ::  windspeed            !< absolute value of windspeed at agent position
253        REAL(wp)     ::  x                    !< x-position
254        REAL(wp)     ::  y                    !< y-position
255        REAL(wp)     ::  t                    !< temperature
256        REAL(wp)     ::  t_x                  !< x-position
257        REAL(wp)     ::  t_y                  !< y-position
258        REAL(wp), DIMENSION(0:15) ::  path_x  !< agent path to target (x)
259        REAL(wp), DIMENSION(0:15) ::  path_y  !< agent path to target (y)
260    END TYPE agent_type
261
262    TYPE(agent_type), DIMENSION(:), POINTER ::  agents               !< Agent array for this grid cell
263    TYPE(agent_type)                        ::  zero_agent           !< zero agent to avoid weird thing
264    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  move_also_north  !< for agent exchange between PEs
265    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  move_also_south  !< for agent exchange between PEs
266    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_l         !< ghost layer left of pe domain
267    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_n         !< ghost layer north of pe domain
268    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_r         !< ghost layer right of pe domain
269    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_s         !< ghost layer south of pe domain
270!
271!-- Type for 2D grid on which agents are stored
272    TYPE  grid_agent_def
273        INTEGER(iwp), DIMENSION(0:3)            ::  start_index        !< start agent index for current block
274        INTEGER(iwp), DIMENSION(0:3)            ::  end_index          !< end agent index for current block
275        INTEGER(iwp)                            ::  id_counter         !< agent id counter (removeable?)
276        LOGICAL                                 ::  time_loop_done     !< timestep loop for agent advection
277        TYPE(agent_type), POINTER, DIMENSION(:) ::  agents             !< Particle array for this grid cell
278    END TYPE grid_agent_def
279
280    TYPE(grid_agent_def), DIMENSION(:,:), ALLOCATABLE, TARGET ::  grid_agents !< 2D grid on which agents are stored
281!
282!-- Item in a priority queue (binary heap)
283    TYPE heap_item
284       INTEGER(iwp) ::  mesh_id       !< id of the submitted mesh point
285       REAL(wp)     ::  priority      !< priority of the mesh point (= distance so far + heuristic to goal)
286    END TYPE heap_item
287
288    TYPE(heap_item), DIMENSION(:), ALLOCATABLE ::  queue  !< priority queue realized as binary heap
289!
290!-- Type for mesh point in visibility graph
291    TYPE  mesh_point
292        INTEGER(iwp)                            ::  polygon_id          !< Polygon the point belongs to
293        INTEGER(iwp)                            ::  vertex_id           !< Vertex in the polygon
294        INTEGER(iwp)                            ::  noc                 !< number of connections
295        INTEGER(iwp)                            ::  origin_id           !< ID of previous mesh point on path (A*)
296        INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  connected_vertices  !< Index of connected vertices
297        REAL(wp)                                ::  cost_so_far         !< Cost to reach this mesh point (A*)
298        REAL(wp)                                ::  x                   !< x-coordinate
299        REAL(wp)                                ::  y                   !< y-coordinate
300        REAL(wp)                                ::  x_s                 !< corner shifted outward from building by 1m (x)
301        REAL(wp)                                ::  y_s                 !< corner shifted outward from building by 1m (y)
302        REAL(wp), DIMENSION(:), ALLOCATABLE     ::  distance_to_vertex  !< Distance to each vertex
303    END TYPE mesh_point
304
305    TYPE(mesh_point), DIMENSION(:), ALLOCATABLE ::  mesh     !< navigation mesh
306    TYPE(mesh_point), DIMENSION(:), ALLOCATABLE ::  tmp_mesh !< temporary navigation mesh
307!
308!-- Vertex of a polygon
309    TYPE  vertex_type
310        LOGICAL               ::  delete  !< Flag to mark vertex for deletion
311        REAL(wp)              ::  x       !< x-coordinate
312        REAL(wp)              ::  y       !< y-coordinate
313    END TYPE vertex_type
314!
315!-- Polygon containing a number of vertices
316    TYPE  polygon_type
317        INTEGER(iwp)                                 ::  nov       !< Number of vertices in this polygon
318        TYPE(vertex_type), DIMENSION(:), ALLOCATABLE ::  vertices  !< Array of vertices
319    END TYPE polygon_type
320
321    TYPE(polygon_type), DIMENSION(:), ALLOCATABLE ::  polygons  !< Building data in polygon form
322
323    SAVE
324
325    PRIVATE
326!
327!-- Public functions
328    PUBLIC mas_init, mas_last_actions, mas_parin, multi_agent_system
329
330!
331!-- Public parameters, constants and initial values
332    PUBLIC agents_active
333
334    INTERFACE mas_parin
335       MODULE PROCEDURE mas_parin
336    END INTERFACE mas_parin
337
338    INTERFACE mas_init
339       MODULE PROCEDURE mas_init
340    END INTERFACE mas_init
341
342    INTERFACE mas_last_actions
343       MODULE PROCEDURE mas_last_actions
344    END INTERFACE mas_last_actions
345
346    INTERFACE multi_agent_system
347       MODULE PROCEDURE multi_agent_system
348    END INTERFACE multi_agent_system
349
350    CONTAINS
351
352
353!------------------------------------------------------------------------------!
354! Description:
355! ------------
356!> Multi Agent System:
357!> executes a number of agents sub-timesteps until the model timestep is reached.
358!> The agent timestep is usually smaller than the model timestep
359!------------------------------------------------------------------------------!
360 SUBROUTINE multi_agent_system
361
362    USE biometeorology_mod,                                                   &
363        ONLY:  bio_calc_ipt, bio_calculate_mrt_grid, bio_get_thermal_index_input_ij
364
365
366    IMPLICIT NONE
367
368    INTEGER(iwp)       ::  i                  !< counter
369    INTEGER(iwp)       ::  ie                 !< counter
370    INTEGER(iwp)       ::  is                 !< counter
371    INTEGER(iwp)       ::  j                  !< counter
372    INTEGER(iwp)       ::  je                 !< counter
373    INTEGER(iwp)       ::  js                 !< counter
374    INTEGER(iwp), SAVE ::  mas_count = 0      !< counts the mas-calls
375    INTEGER(iwp)                :: a     !< agent iterator
376    !-- local meteorological conditions
377    REAL(wp)                    :: tmrt  !< mean radiant temperature        (degree_C)
378    REAL(wp)                    :: ta    !< air temperature                 (degree_C)
379    REAL(wp)                    :: vp    !< vapour pressure                 (hPa)
380    REAL(wp)                    :: v     !< wind speed    (local level)     (m/s)
381    REAL(wp)                    :: pair  !< air pressure                    (hPa)
382
383
384    LOGICAL       ::  first_loop_stride   !< flag for first loop stride of agent sub-timesteps
385    LOGICAL, SAVE ::  first_call = .TRUE. !< first call of mas flag for output
386
387    CALL cpu_log( log_point(9), 'mas', 'start' )
388!
389!-- Initialize variables for the next (sub-) timestep, i.e., for marking
390!-- those agents to be deleted after the timestep
391    deleted_agents = 0
392    agent_substep_time = 0.0_wp
393!
394!-- If necessary, release new set of agents
395    IF ( time_arel >= dt_arel  .AND.  end_time_arel > time_since_reference_point )  THEN
396
397       CALL mas_create_agent(PHASE_RELEASE)
398!
399!--    The MOD function allows for changes in the output interval with
400!--    restart runs.
401       time_arel = MOD( time_arel, MAX( dt_arel, dt_3d ) )
402
403    ENDIF
404
405    first_loop_stride = .TRUE.
406    grid_agents(:,:)%time_loop_done = .TRUE.
407!
408!-- Set timestep variable
409    IF ( .NOT. agent_own_timestep ) dt_agent = dt_3d
410!
411!-- Timestep loop for agent transport.
412!-- This loop has to be repeated until the transport time of every agent
413!-- (within the total domain!) has reached the LES timestep (dt_3d).
414!-- Timestep scheme is Euler-forward
415    DO
416!
417!--    Write agent data at current time on file.
418       time_write_agent_data = time_write_agent_data + dt_agent
419       agent_substep_time    = agent_substep_time    + dt_agent
420       IF ( time_write_agent_data >= dt_write_agent_data )  THEN
421#if defined( __netcdf )
422          IF ( first_loop_stride ) CALL mas_get_prognostic_quantities
423          CALL mas_data_output_agents ( first_call )
424#else
425          WRITE( message_string, * ) 'NetCDF is needed for agent output. ',    &
426                                     'Set __netcdf in compiler options'
427          CALL message( 'multi_agent_system', 'PA0071', 1, 2, 0, 6, 0 )
428#endif
429          IF(first_call) first_call = .FALSE.
430          time_write_agent_data = time_write_agent_data - dt_write_agent_data
431       ENDIF
432!
433!--    Flag is true by default, will be set to false if an agent has not yet
434!--    reached the model timestep
435       grid_agents(:,:)%time_loop_done = .TRUE.
436
437!
438!--    First part of agent transport:
439!--    Evaluate social forces for all agents at current positions
440       CALL cpu_log( log_point_s(9), 'mas_social_forces', 'start' )
441       DO  i = nxl, nxr
442          DO  j = nys, nyn
443
444             number_of_agents = agt_count(j,i)
445!
446!--          If grid cell is empty, cycle
447             IF ( number_of_agents <= 0 ) CYCLE
448
449             agents => grid_agents(j,i)%agents(1:number_of_agents)
450!
451!--          Evaluation of social forces
452             CALL mas_timestep_forces_call(i,j)
453
454          ENDDO
455       ENDDO
456       CALL cpu_log( log_point_s(9), 'mas_social_forces', 'stop' )
457!
458!--    Second part of agent transport:
459!--    timestep
460       CALL cpu_log( log_point_s(16), 'mas_timestep', 'start' )
461       DO  i = nxl, nxr
462          DO  j = nys, nyn
463
464             number_of_agents = agt_count(j,i)
465!
466!--          If grid cell is empty, flag must be true
467             IF ( number_of_agents <= 0 )  THEN
468                grid_agents(j,i)%time_loop_done = .TRUE.
469                CYCLE
470             ENDIF
471
472             agents => grid_agents(j,i)%agents(1:number_of_agents)
473
474             agents(1:number_of_agents)%agent_mask = .TRUE.
475!
476!--          Initialize the variable storing the total time that an agent
477!--          has advanced within the timestep procedure
478             IF ( first_loop_stride )  THEN
479                agents(1:number_of_agents)%dt_sum = 0.0_wp
480             ENDIF
481!
482!--          Initialize the switch used for the loop exit condition checked
483!--          at the end of this loop. If at least one agent has failed to
484!--          reach the LES timestep, this switch will be set false in
485!--          mas_transport.
486             dt_3d_reached_l_mas = .TRUE.
487!
488!--          Timestep
489             CALL mas_timestep
490!
491!--          Delete agents that have been simulated longer than allowed
492             CALL mas_boundary_conds( 'max_sim_time' )
493!
494!--          Delete agents that have reached target area
495             CALL mas_boundary_conds( 'target_area' )
496!
497!---         If not all agents of the actual grid cell have reached the
498!--          LES timestep, this cell has to to another loop iteration. Due to
499!--          the fact that agents can move into neighboring grid cell,
500!--          these neighbor cells also have to perform another loop iteration
501             IF ( .NOT. dt_3d_reached_l_mas )  THEN
502                js = MAX(nys,j-1)
503                je = MIN(nyn,j+1)
504                is = MAX(nxl,i-1)
505                ie = MIN(nxr,i+1)
506                grid_agents(js:je,is:ie)%time_loop_done = .FALSE.
507             ENDIF
508
509          ENDDO
510       ENDDO
511       CALL cpu_log( log_point_s(16), 'mas_timestep', 'stop' )
512
513!
514!--    Find out, if all agents on every PE have completed the LES timestep
515!--    and set the switch corespondingly
516       dt_3d_reached_l_mas = ALL(grid_agents(:,:)%time_loop_done)
517#if defined( __parallel )
518       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
519       CALL MPI_ALLREDUCE( dt_3d_reached_l_mas, dt_3d_reached_mas, 1, MPI_LOGICAL, &
520                           MPI_LAND, comm2d, ierr )
521#else
522       dt_3d_reached_mas = dt_3d_reached_l_mas
523#endif
524
525!
526!--    Increment time since last release
527       IF ( dt_3d_reached_mas )  time_arel = time_arel + dt_3d
528
529!
530!--    Move Agents local to PE to a different grid cell
531       CALL cpu_log( log_point_s(18), 'mas_move_exch_sort', 'start' )
532       CALL mas_eh_move_agent
533!
534!--    Horizontal boundary conditions including exchange between subdmains
535       CALL mas_eh_exchange_horiz
536!
537!--    Pack agents (eliminate those marked for deletion),
538!--    determine new number of agents
539       CALL mas_ps_sort_in_subboxes
540       CALL cpu_log( log_point_s(18), 'mas_move_exch_sort', 'stop' )
541!
542!--    Initialize variables for the next (sub-) timestep, i.e., for marking
543!--    those agents to be deleted after the timestep
544       deleted_agents = 0
545
546       IF ( biometeorology )  THEN
547!
548!--       Fill out the MRT 2D grid from appropriate source (RTM, RRTMG,...)
549          CALL bio_calculate_mrt_grid ( .FALSE. )
550!
551!--       Call of human thermal comfort mod (and UV exposure)
552          DO  i = nxl, nxr
553             DO  j = nys, nyn
554
555                number_of_agents = agt_count(j,i)
556!
557!--             If grid cell gets empty, cycle
558                IF ( number_of_agents <= 0 )  CYCLE
559
560                agents => grid_agents(j,i)%agents(1:number_of_agents)
561!
562!--             Evaluation of social forces
563!                CALL bio_dynamic( i, j )
564!
565!--             Determine local meteorological conditions
566                CALL bio_get_thermal_index_input_ij ( .FALSE., i, j, ta, vp,  &
567                                                      v, pair, tmrt )
568
569                DO  a = 1, number_of_agents
570!
571!--                Calculate instationary thermal indices based on local tmrt
572
573                   CALL bio_calc_ipt ( ta, vp, v, pair, tmrt,                 &
574                                       agents(a)%dt_sum,                      &
575                                       agents(a)%energy_storage,              &
576                                       agents(a)%clothing_temp,               &
577                                       agents(a)%clo,                         &
578                                       agents(a)%actlev,                      &
579                                       agents(a)%age_years,                   &
580                                       agents(a)%weight,                      &
581                                       agents(a)%height,                      &
582                                       agents(a)%work,                        &
583                                       agents(a)%sex,                         &
584                                       agents(a)%ipt )
585                END DO
586
587             ENDDO
588          ENDDO
589       ENDIF
590
591       IF ( dt_3d_reached_mas )  EXIT
592
593       first_loop_stride = .FALSE.
594    ENDDO   ! timestep loop
595
596!
597!-- Deallocate unused memory
598    IF ( deallocate_memory_mas  .AND.  mas_count == step_dealloc_mas )  THEN
599       CALL mas_eh_dealloc_agents_array
600       mas_count = 0
601    ELSEIF ( deallocate_memory_mas )  THEN
602       mas_count = mas_count + 1
603    ENDIF
604
605    CALL cpu_log( log_point(9), 'mas', 'stop' )
606
607 END SUBROUTINE multi_agent_system
608
609!------------------------------------------------------------------------------!
610! Description:
611! ------------
612!> Calculation of the direction vector from each agent to its current
613!> intermittent target
614!------------------------------------------------------------------------------!
615    SUBROUTINE mas_agent_direction
616
617       IMPLICIT NONE
618
619       LOGICAL ::  path_flag !< true if new path must be calculated
620
621       INTEGER(iwp) ::  n  !< loop variable over all agents in a grid box
622       INTEGER(iwp) ::  pc !< agent path counter
623
624       REAL(wp) ::  abs_dir         !< length of direction vector (for normalization)
625!       REAL(wp) ::  d_curr_target   !< rounding influence expressed as x speed component
626!       REAL(wp) ::  d_prev_target   !< rounding influence expressed as x speed component
627       REAL(wp) ::  dir_x           !< direction of agent (x)
628       REAL(wp) ::  dir_y           !< direction of agent (y)
629!       REAL(wp) ::  dist_round = 3. !< distance at which agents start rounding a corner
630       REAL(wp) ::  dtit            !< distance to intermittent target
631!       REAL(wp) ::  round_fac  = 0.2 !< factor for rounding influence
632!       REAL(wp) ::  speed_round_x   !< rounding influence expressed as x speed component
633!       REAL(wp) ::  speed_round_y   !< rounding influence expressed as x speed component
634
635!
636!--    loop over all agents in the current grid box
637       DO n = 1, number_of_agents
638          path_flag = .FALSE.
639          pc = agents(n)%path_counter
640!
641!--       If no path was calculated for agent yet, do it
642          IF ( pc >= 999 ) THEN
643             CALL mas_nav_find_path(n)
644             pc = agents(n)%path_counter
645!
646!--       Check if new path must be calculated and if so, do it
647          ELSE
648!
649!--          Case one: Agent has come close enough to intermittent target.
650!--                    -> chose new int target and calculate rest of path if no
651!--                       new intermittent targets are left
652             dtit = SQRT((agents(n)%x - agents(n)%path_x(pc))**2               &
653                       + (agents(n)%y - agents(n)%path_y(pc))**2)
654             IF ( dtit < dist_to_int_target ) THEN
655                agents(n)%path_counter = agents(n)%path_counter + 1
656                pc = agents(n)%path_counter
657!
658!--             Path counter out of scope (each agent can store a maximum of 15
659!--             intermittent targets on the way to her final target); new path
660!--             must be calculated
661                IF ( pc >= SIZE(agents(n)%path_x) ) THEN
662                   path_flag = .TRUE.
663                ENDIF
664!
665!--          Case two: Agent too far from path
666!--                    -> set flag for new path to be calculated
667             ELSEIF ( dist_point_to_edge(agents(n)%path_x(pc-1),               &
668                                         agents(n)%path_y(pc-1),               &
669                                         agents(n)%path_x(pc),                 &
670                                         agents(n)%path_y(pc),                 &
671                                         agents(n)%x, agents(n)%y)             &
672                      > max_dist_from_path )                                   &
673             THEN
674                path_flag = .TRUE.
675             ENDIF
676!
677!--          If either of the above two cases was true, calculate new path and
678!--          reset 0th path point. This point (the last target the agent had)
679!--          is needed for the agents rounding of corners and the calculation
680!--          of her deviation from her current path
681             IF ( path_flag ) THEN
682                CALL mas_nav_find_path(n)
683                pc = agents(n)%path_counter
684             ENDIF
685          ENDIF
686!
687!--       Normalize direction vector
688          abs_dir             = 1.0d-12
689          dir_x               = agents(n)%path_x(pc) - agents(n)%x
690          dir_y               = agents(n)%path_y(pc) - agents(n)%y
691          abs_dir             = SQRT(dir_x**2 + dir_y**2)+1.0d-12
692!--         needed later for corner rounding
693!           dir_x               = dir_x/abs_dir
694!           dir_y               = dir_y/abs_dir
695!           dir_x               = dir_x + speed_round_x
696!           dir_y               = dir_y + speed_round_y
697!           abs_dir             = SQRT(dir_x**2 + dir_y**2)+1.0d-12
698          agents(n)%speed_e_x = dir_x/abs_dir
699          agents(n)%speed_e_y = dir_y/abs_dir
700       ENDDO
701
702!
703!-- corner rounding; to be added
704!
705!--       Calculate direction change due to rounding of corners
706
707!           speed_round_x = 0.
708!           speed_round_y = 0.
709!           
710!           d_curr_target = SQRT( (agents(n)%path_x(pc) - agents(n)%x)**2 +      &
711!                                 (agents(n)%path_y(pc) - agents(n)%y)**2 )
712!           d_prev_target = SQRT( (agents(n)%path_x(pc-1) - agents(n)%x)**2 +    &
713!                                 (agents(n)%path_y(pc-1) - agents(n)%y)**2 )
714! !
715! !--       Agent is close to next target and that target is not the final one
716!           IF ( d_curr_target < dist_round .AND. dist_round <                   &
717!                           SQRT( (agents(n)%path_x(pc) - agents(n)%t_x)**2 +    &
718!                                 (agents(n)%path_y(pc) - agents(n)%t_y)**2 ) )  &
719!           THEN
720!              speed_round_x = (agents(n)%path_x(pc+1) - agents(n)%path_x(pc)) / &
721!                              ABS( agents(n)%path_x(pc)                         &
722!                                 - agents(n)%path_x(pc+1)) * round_fac *        &
723!                              SIN( pi/dist_round*d_curr_target )
724!              speed_round_y = (agents(n)%path_y(pc+1) - agents(n)%path_y(pc)) / &
725!                              ABS( agents(n)%path_y(pc)                         &
726!                                 - agents(n)%path_y(pc+1)) * round_fac *        &
727!                              SIN( pi/dist_round*d_curr_target )
728!           ENDIF
729!
730!           IF ( d_prev_target < dist_round ) THEN
731!              IF ( agents(n)%path_x(pc) /= agents(n)%path_x(pc+1) ) THEN
732!                 speed_round_x = speed_round_x +                                   &
733!                                 (agents(n)%path_x(pc) - agents(n)%path_x(pc+1)) / &
734!                                 ABS( agents(n)%path_x(pc)                         &
735!                                    - agents(n)%path_x(pc+1)) * round_fac *        &
736!                                 SIN( pi/dist_round*d_prev_target )
737!              ENDIF
738!             
739!              IF ( agents(n)%path_y(pc) /= agents(n)%path_y(pc+1) ) THEN
740!                 speed_round_y = speed_round_y +                                   &
741!                              (agents(n)%path_y(pc) - agents(n)%path_y(pc+1)) / &
742!                              ABS( agents(n)%path_y(pc)                         &
743!                                 - agents(n)%path_y(pc+1)) * round_fac *        &
744!                              SIN( pi/dist_round*d_prev_target )
745!              ENDIF
746             
747!           ENDIF
748
749
750    END SUBROUTINE mas_agent_direction
751
752!------------------------------------------------------------------------------!
753! Description:
754! ------------
755!> Boundary conditions for maximum time, target reached and out of domain
756!------------------------------------------------------------------------------!
757    SUBROUTINE mas_boundary_conds( location )
758
759       IMPLICIT NONE
760
761       CHARACTER (LEN=*) ::  location !< Identifier
762
763       INTEGER(iwp) ::  n   !< agent number
764       INTEGER(iwp) ::  grp !< agent group
765
766       REAL(wp) ::  dist_to_target !< distance to target
767
768       IF ( location == 'max_sim_time' )  THEN
769
770!
771!--       Delete agents that have been simulated longer than allowed
772          DO  n = 1, number_of_agents
773
774             IF ( agents(n)%age > agent_maximum_age  .AND.                     &
775                  agents(n)%agent_mask )                                       &
776             THEN
777                agents(n)%agent_mask  = .FALSE.
778                deleted_agents = deleted_agents + 1
779             ENDIF
780
781          ENDDO
782       ENDIF
783
784       IF ( location == 'target_area' )  THEN
785
786!
787!--       Delete agents that entered target region
788          DO  n = 1, number_of_agents
789             grp = agents(n)%group
790             dist_to_target = SQRT((agents(n)%x-at_x(grp))**2                  &
791                                 + (agents(n)%y-at_y(grp))**2)
792             IF ( dist_to_target < dist_target_reached ) THEN
793                agents(n)%agent_mask  = .FALSE.
794                deleted_agents = deleted_agents + 1
795             ENDIF
796
797          ENDDO
798       ENDIF
799
800    END SUBROUTINE mas_boundary_conds
801
802!------------------------------------------------------------------------------!
803! Description:
804! ------------
805!> Release new agents at their respective sources
806!------------------------------------------------------------------------------!
807    SUBROUTINE mas_create_agent (phase)
808
809       IMPLICIT  NONE
810
811       INTEGER(iwp) ::  alloc_size  !< relative increase of allocated memory for agents
812       INTEGER(iwp) ::  i           !< loop variable ( agent groups )
813       INTEGER(iwp) ::  ip          !< index variable along x
814       INTEGER(iwp) ::  jp          !< index variable along y
815       INTEGER(iwp) ::  loop_stride !< loop variable for initialization
816       INTEGER(iwp) ::  n           !< loop variable ( number of agents )
817       INTEGER(iwp) ::  new_size    !< new size of allocated memory for agents
818       INTEGER(iwp) ::  rn_side     !< index of agent path
819
820       INTEGER(iwp), INTENT(IN) ::  phase       !< mode of inititialization
821
822       INTEGER(iwp), DIMENSION(nysg:nyng,nxlg:nxrg) ::  local_count !< start address of new agent
823       INTEGER(iwp), DIMENSION(nysg:nyng,nxlg:nxrg) ::  local_start !< start address of new agent
824
825       LOGICAL ::  first_stride !< flag for initialization
826
827       REAL(wp) ::  pos_x       !< increment for agent position in x
828       REAL(wp) ::  pos_y       !< increment for agent position in y
829       REAL(wp) ::  rand_contr  !< dummy argument for random position
830       REAL(wp) ::  rn_side_dum !< index of agent path
831
832       TYPE(agent_type),TARGET ::  tmp_agent !< temporary agent used for initialization
833
834!
835!--    Calculate agent positions and store agent attributes, if
836!--    agent is situated on this PE
837       DO  loop_stride = 1, 2
838          first_stride = (loop_stride == 1)
839          IF ( first_stride )   THEN
840             local_count = 0           ! count number of agents
841          ELSE
842             local_count = agt_count   ! Start address of new agents
843          ENDIF
844
845          DO  i = 1, number_of_agent_groups
846
847             pos_y = ass(i)
848
849             DO WHILE ( pos_y <= asn(i) )
850
851                IF ( pos_y >= nys * dy  .AND.                                  &
852                           pos_y <  ( nyn + 1 ) * dy  )                        &
853                THEN
854
855                   pos_x = asl(i)
856
857            xloop: DO WHILE ( pos_x <= asr(i) )
858
859                      IF ( pos_x >= nxl * dx  .AND.                            &
860                                 pos_x <  ( nxr + 1) * dx )                    &
861                      THEN
862
863                         tmp_agent%agent_mask = .TRUE.
864                         tmp_agent%group         = i
865                         tmp_agent%id            = 0_idp
866                         tmp_agent%block_nr      = -1
867                         tmp_agent%path_counter  = 999 !SIZE(tmp_agent%path_x)
868                         tmp_agent%age           = 0.0_wp
869                         tmp_agent%age_m         = 0.0_wp
870                         tmp_agent%dt_sum        = 0.0_wp
871                         tmp_agent%clo           = -999.0_wp
872                         tmp_agent%energy_storage= 0.0_wp
873                         tmp_agent%ipt           = 99999.0_wp
874                         tmp_agent%clothing_temp = -999._wp      !< energy stored by agent (W)
875                         tmp_agent%actlev        = 134.6862_wp   !< metabolic + work energy of the person
876                         tmp_agent%age_years     = 35._wp        !< physical age of the person
877                         tmp_agent%weight        = 75._wp        !< total weight of the person (kg)
878                         tmp_agent%height        = 1.75_wp       !< height of the person (m)
879                         tmp_agent%work          = 134.6862_wp   !< workload of the agent (W)
880                         tmp_agent%sex           = 1             !< agents gender: 1 = male, 2 = female
881                         tmp_agent%force_x       = 0.0_wp
882                         tmp_agent%force_y       = 0.0_wp
883                         tmp_agent%origin_x      = pos_x
884                         tmp_agent%origin_y      = pos_y
885                         tmp_agent%speed_abs     = 0.0_wp
886                         tmp_agent%speed_e_x     = 0.0_wp
887                         tmp_agent%speed_e_y     = 0.0_wp
888                         tmp_agent%speed_des     = random_normal(desired_speed,&
889                                                                 des_sp_sig)
890                         tmp_agent%speed_x       = 0.0_wp
891                         tmp_agent%speed_y       = 0.0_wp
892                         tmp_agent%x             = pos_x
893                         tmp_agent%y             = pos_y
894                         tmp_agent%path_x        = -1.0_wp
895                         tmp_agent%path_y        = -1.0_wp
896                         tmp_agent%t_x           = - pi
897                         tmp_agent%t_y           = - pi
898!
899!--                      Determine the grid indices of the agent position
900                         ip = tmp_agent%x * ddx
901                         jp = tmp_agent%y * ddy
902!
903!--                      Give each agent its target
904                         IF ( a_rand_target(i) ) THEN
905!
906!--                         Agent shall receive random target just outside
907!--                         simulated area
908                            rn_side_dum = random_function(iran_agent)
909                            rn_side     = FLOOR(4.*rn_side_dum)
910                            IF ( rn_side < 2 ) THEN
911                               IF ( rn_side == 0 ) THEN
912                                  tmp_agent%t_y = -2*dy
913                               ELSE
914                                  tmp_agent%t_y = (ny+3)*dy
915                               ENDIF
916                               tmp_agent%t_x = random_function(iran_agent) *   &
917                                               (nx+1)*dx
918                            ELSE
919                               IF ( rn_side == 2 ) THEN
920                                  tmp_agent%t_x = -2*dx
921                               ELSE
922                                  tmp_agent%t_x = (nx+3)*dx
923                               ENDIF
924                               tmp_agent%t_y = random_function(iran_agent) *   &
925                                               (ny+1)*dy
926                            ENDIF
927!
928!--                      Agent gets target of her group
929                         ELSE
930                            tmp_agent%t_x = at_x(i)
931                            tmp_agent%t_y = at_y(i)
932                         ENDIF
933
934                         local_count(jp,ip) = local_count(jp,ip) + 1
935
936                         IF ( .NOT. first_stride )  THEN
937                            grid_agents(jp,ip)%agents(local_count(jp,ip))      &
938                                              = tmp_agent
939                         ENDIF
940
941                      ENDIF
942
943                      pos_x = pos_x + adx(i)
944
945                   ENDDO xloop
946
947                ENDIF
948
949                pos_y = pos_y + ady(i)
950
951             ENDDO
952
953          ENDDO
954
955!
956!--       Allocate or reallocate agents array to new size
957          IF ( first_stride )  THEN
958             DO  ip = nxlg, nxrg
959                DO  jp = nysg, nyng
960                   IF ( phase == PHASE_INIT )  THEN
961                      IF ( local_count(jp,ip) > 0 )  THEN
962                         alloc_size = MAX( INT( local_count(jp,ip) *           &
963                            ( 1.0_wp + alloc_factor_mas / 100.0_wp ) ),        &
964                            min_nr_agent )
965                      ELSE
966                         alloc_size = min_nr_agent
967                      ENDIF
968                      ALLOCATE(grid_agents(jp,ip)%agents(1:alloc_size))
969                      DO  n = 1, alloc_size
970                         grid_agents(jp,ip)%agents(n) = zero_agent
971                      ENDDO
972                   ELSEIF ( phase == PHASE_RELEASE )  THEN
973                      IF ( local_count(jp,ip) > 0 )  THEN
974                         new_size   = local_count(jp,ip) + agt_count(jp,ip)
975                         alloc_size = MAX( INT( new_size * ( 1.0_wp +          &
976                            alloc_factor_mas / 100.0_wp ) ), min_nr_agent )
977                         IF( alloc_size > SIZE( grid_agents(jp,ip)%agents) )   &
978                         THEN
979                            CALL mas_eh_realloc_agents_array(ip,jp,alloc_size)
980                         ENDIF
981                      ENDIF
982                   ENDIF
983                ENDDO
984             ENDDO
985          ENDIF
986
987       ENDDO
988
989       local_start = agt_count+1
990       agt_count   = local_count
991
992!
993!--    Calculate agent IDs
994       DO  ip = nxl, nxr
995          DO  jp = nys, nyn
996             number_of_agents = agt_count(jp,ip)
997             IF ( number_of_agents <= 0 )  CYCLE
998             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
999
1000             DO  n = local_start(jp,ip), number_of_agents  !only new agents
1001
1002                agents(n)%id = 10000_idp**2 * grid_agents(jp,ip)%id_counter +  &
1003                               10000_idp * jp + ip
1004!
1005!--             Count the number of agents that have been released before
1006                grid_agents(jp,ip)%id_counter = grid_agents(jp,ip)%id_counter  &
1007                                                + 1
1008
1009             ENDDO
1010
1011          ENDDO
1012       ENDDO
1013
1014!
1015!--    Add random fluctuation to agent positions.
1016       IF ( random_start_position_agents )  THEN
1017          DO  ip = nxl, nxr
1018             DO  jp = nys, nyn
1019                number_of_agents = agt_count(jp,ip)
1020                IF ( number_of_agents <= 0 )  CYCLE
1021                agents => grid_agents(jp,ip)%agents(1:number_of_agents)
1022!
1023!--             Move only new agents. Moreover, limit random fluctuation
1024!--             in order to prevent that agents move more than one grid box,
1025!--             which would lead to problems concerning agent exchange
1026!--             between processors in case adx/ady are larger than dx/dy,
1027!--             respectively. 
1028                DO  n = local_start(jp,ip), number_of_agents
1029                   IF ( asl(agents(n)%group) /= asr(agents(n)%group) )  THEN
1030                      rand_contr = ( random_function( iran_agent ) - 0.5_wp ) *&
1031                                     adx(agents(n)%group)
1032                      agents(n)%x = agents(n)%x +                        &
1033                              MERGE( rand_contr, SIGN( dx, rand_contr ),       &
1034                                     ABS( rand_contr ) < dx                    &
1035                                   ) 
1036                   ENDIF
1037                   IF ( ass(agents(n)%group) /= asn(agents(n)%group) )  THEN
1038                      rand_contr = ( random_function( iran_agent ) - 0.5_wp ) *&
1039                                     ady(agents(n)%group)
1040                      agents(n)%y = agents(n)%y +                        &
1041                              MERGE( rand_contr, SIGN( dy, rand_contr ),       &
1042                                     ABS( rand_contr ) < dy )
1043                   ENDIF
1044                ENDDO
1045!
1046!--             Delete agents that have been simulated longer than allowed
1047                CALL mas_boundary_conds( 'max_sim_time' )
1048!
1049!--             Delete agents that have reached target area
1050                CALL mas_boundary_conds( 'target_area' )
1051
1052             ENDDO
1053          ENDDO
1054!
1055!--       Exchange agents between grid cells and processors
1056          CALL mas_eh_move_agent
1057          CALL mas_eh_exchange_horiz
1058
1059       ENDIF
1060!
1061!--    In case of random_start_position_agents, delete agents identified by
1062!--    mas_eh_exchange_horiz and mas_boundary_conds. Then sort agents into
1063!--    blocks, which is needed for a fast interpolation of the LES fields
1064!--    on the agent position.
1065       CALL mas_ps_sort_in_subboxes
1066
1067!
1068!--    Determine the current number of agents
1069       number_of_agents = 0
1070       DO  ip = nxl, nxr
1071          DO  jp = nys, nyn
1072             number_of_agents = number_of_agents + agt_count(jp,ip)
1073          ENDDO
1074       ENDDO
1075!
1076!--    Calculate the number of agents of the total domain
1077#if defined( __parallel )
1078       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1079       CALL MPI_ALLREDUCE( number_of_agents, total_number_of_agents, 1, &
1080       MPI_INTEGER, MPI_SUM, comm2d, ierr )
1081#else
1082       total_number_of_agents = number_of_agents
1083#endif
1084
1085       RETURN
1086
1087    END SUBROUTINE mas_create_agent
1088
1089!------------------------------------------------------------------------------!
1090! Description:
1091! ------------
1092!> Creates flags that indicate if a gridbox contains edges or corners. These
1093!> flags are used for agents to check if obstacles are close to them.
1094!------------------------------------------------------------------------------!
1095    SUBROUTINE mas_create_obstacle_flags
1096
1097       USE arrays_3d,                                                          &
1098           ONLY:  zw
1099
1100       IMPLICIT NONE
1101
1102       INTEGER(iwp) ::  il
1103       INTEGER(iwp) ::  jl
1104
1105       ALLOCATE(obstacle_flags(nysg:nyng,nxlg:nxrg))
1106
1107       obstacle_flags = 0
1108
1109       DO il = nxlg, nxrg
1110          DO jl = nysg, nyng
1111!
1112!--          Exclude cyclic topography boundary
1113             IF ( il < 0 .OR. il > nx .OR. jl < 0 .OR. jl > ny ) CYCLE
1114!
1115!--          North edge
1116             IF ( jl < nyng ) THEN
1117                IF ( ( top_top_s(jl,il) - top_top_s(jl+1,il) ) > 1 .AND.       &
1118                     ( zw( top_top_w(jl,il) ) -                                &
1119                       zw( top_top_w(jl+1,il) ) ) > .51_wp )                   &
1120                THEN
1121                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 0 )
1122                ENDIF
1123             ENDIF
1124!
1125!--          North right corner
1126             IF ( jl < nyng .AND. il < nxrg ) THEN
1127                IF ( ( top_top_s(jl,il) - top_top_s(jl+1,il) )   > 1 .AND.     &
1128                     ( top_top_s(jl,il) - top_top_s(jl+1,il+1) ) > 1 .AND.     &
1129                     ( top_top_s(jl,il) - top_top_s(jl,il+1) )   > 1 .AND.     &
1130                     ( zw( top_top_w(jl,il) ) -                                &
1131                       zw( top_top_w(jl+1,il+1) ) ) > .51_wp )                 &
1132                THEN
1133                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 1 )
1134                ENDIF
1135             ENDIF
1136!
1137!--          Right edge
1138             IF ( il < nxrg ) THEN
1139                IF ( ( top_top_s(jl,il) - top_top_s(jl,il+1) ) > 1 .AND.       &
1140                     ( zw( top_top_w(jl,il) ) -                                &
1141                       zw( top_top_w(jl,il+1) ) ) > .51_wp )                   &
1142                THEN
1143                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 2 )
1144                ENDIF
1145             ENDIF
1146!
1147!--          South right corner
1148             IF ( jl > nysg .AND. il < nxrg ) THEN
1149                IF ( ( top_top_s(jl,il) - top_top_s(jl,il+1) )   > 1 .AND.     &
1150                     ( top_top_s(jl,il) - top_top_s(jl-1,il+1) ) > 1 .AND.     &
1151                     ( top_top_s(jl,il) - top_top_s(jl-1,il) )   > 1 .AND.     &
1152                     ( zw(top_top_w(jl,il)) -                                  &
1153                       zw( top_top_w(jl-1,il+1) ) ) > .51_wp )                 &
1154                THEN
1155                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 3 )
1156                ENDIF
1157             ENDIF
1158!
1159!--          South edge
1160             IF ( jl > nysg ) THEN
1161                IF ( ( top_top_s(jl,il) - top_top_s(jl-1,il) ) > 1 .AND.       &
1162                     ( zw( top_top_w(jl,il) ) -                                &
1163                       zw( top_top_w(jl-1,il) ) ) > .51_wp )                   &
1164                THEN
1165                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 4 )
1166                ENDIF
1167             ENDIF
1168!
1169!--          South left corner
1170             IF ( jl > nysg .AND. il > nxlg ) THEN
1171                IF ( ( top_top_s(jl,il) - top_top_s(jl-1,il) )   > 1 .AND.     &
1172                     ( top_top_s(jl,il) - top_top_s(jl-1,il-1) ) > 1 .AND.     &
1173                     ( top_top_s(jl,il) - top_top_s(jl,il-1) )   > 1 .AND.     &
1174                     ( zw( top_top_w(jl,il) ) -                                &
1175                       zw(top_top_w(jl-1,il-1) ) ) > .51_wp )                  &
1176                THEN
1177                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 5 )
1178                ENDIF
1179             ENDIF
1180!
1181!--          Left edge
1182             IF ( il > nxlg ) THEN
1183                IF ( ( top_top_s(jl,il) - top_top_s(jl,il-1) ) > 1 .AND.       &
1184                     ( zw(top_top_w(jl,il) ) -                                 &
1185                       zw(top_top_w(jl,il-1) ) ) > .51_wp )                 &
1186                THEN
1187                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 6 )
1188                ENDIF
1189             ENDIF
1190!
1191!--          North left corner
1192             IF ( jl < nyng .AND. il > nxlg ) THEN
1193                IF ( ( top_top_s(jl,il) - top_top_s(jl,il-1) )   > 1 .AND.     &
1194                     ( top_top_s(jl,il) - top_top_s(jl+1,il-1) ) > 1 .AND.     &
1195                     ( top_top_s(jl,il) - top_top_s(jl+1,il) )   > 1 .AND.     &
1196                     ( zw( top_top_w(jl,il) ) -                                &
1197                       zw( top_top_w(jl+1,il-1) ) ) > .51_wp )                 &
1198                THEN
1199                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 7 )
1200                ENDIF
1201             ENDIF
1202
1203          ENDDO
1204       ENDDO
1205
1206    END SUBROUTINE mas_create_obstacle_flags
1207
1208!------------------------------------------------------------------------------!
1209! Description:
1210! ------------
1211!> Write agent data in netCDF format
1212!------------------------------------------------------------------------------!
1213    SUBROUTINE mas_data_output_agents( ftest )
1214
1215       USE control_parameters,                                                 &
1216           ONLY:  agt_time_count, end_time, message_string,                    &
1217                  multi_agent_system_end, multi_agent_system_start
1218
1219       USE netcdf_interface,                                                   &
1220           ONLY:  nc_stat, id_set_agt, id_var_time_agt,        &
1221                  id_var_agt, netcdf_handle_error
1222
1223       USE pegrid
1224
1225#if defined( __netcdf )
1226       USE NETCDF
1227#endif
1228       USE mas_global_attributes,                                              &
1229           ONLY:  dim_size_agtnum
1230
1231       IMPLICIT NONE
1232
1233       INTEGER(iwp) ::  agt_size !< Agent size in bytes
1234       INTEGER(iwp) ::  dummy    !< dummy
1235       INTEGER(iwp) ::  ii       !< counter (x)
1236       INTEGER(iwp) ::  ip       !< counter (x)
1237       INTEGER(iwp) ::  jp       !< counter (y)
1238       INTEGER(iwp) ::  n        !< counter (number of PEs)
1239       INTEGER(iwp) ::  noa      !< number of agents
1240       INTEGER(iwp) ::  noa_rcv  !< received number of agents
1241       INTEGER(iwp) ::  out_noa  !< number of agents for output
1242
1243       INTEGER(iwp), DIMENSION(0:numprocs-1) ::  noa_arr !< number of agents on each PE
1244!
1245!--    SAVE attribute required to avoid compiler warning about pointer outlive the pointer target
1246       TYPE(agent_type), DIMENSION(:), ALLOCATABLE, TARGET, SAVE ::  trf_agents !< all agents on current PE
1247       TYPE(agent_type), DIMENSION(:), ALLOCATABLE, TARGET, SAVE ::  out_agents !< all agents in entire domain
1248
1249       LOGICAL, INTENT (INOUT) :: ftest
1250
1251       LOGICAL, SAVE :: agt_dimension_exceeded = .FALSE.
1252
1253       CALL cpu_log( log_point_s(17), 'mas_data_output', 'start' )
1254!
1255!--    Get total number of agents and put all agents on one PE in one array
1256       noa = 0
1257       DO  ip = nxl, nxr
1258          DO  jp = nys, nyn
1259             noa  = noa  + agt_count(jp,ip)
1260          ENDDO
1261       ENDDO
1262       IF(noa > 0) THEN
1263          ALLOCATE(trf_agents(1:noa))
1264          dummy = 1
1265          DO  ip = nxl, nxr
1266             DO  jp = nys, nyn
1267                IF ( agt_count(jp,ip) == 0 ) CYCLE
1268                agents => grid_agents(jp,ip)%agents(1:agt_count(jp,ip))
1269                trf_agents(dummy:(dummy-1+agt_count(jp,ip))) = agents
1270                dummy = dummy + agt_count(jp,ip)
1271             ENDDO
1272          ENDDO
1273       ENDIF
1274#if defined( __parallel )
1275!
1276!--    Gather all agents on PE0 for output
1277       IF ( myid == 0 )  THEN
1278          noa_arr(0) = noa
1279!
1280!--       Receive data from all other PEs.
1281          DO  n = 1, numprocs-1
1282              CALL MPI_RECV( noa_arr(n), 1, MPI_INTEGER,                       &
1283                              n, 0, comm2d, status, ierr )
1284          ENDDO
1285       ELSE
1286          CALL MPI_SEND( noa, 1, MPI_INTEGER, 0, 0, comm2d, ierr )
1287       ENDIF
1288       CALL MPI_BARRIER( comm2d, ierr )
1289       agt_size = STORAGE_SIZE(zero_agent)/8
1290       IF ( myid == 0 )  THEN
1291!
1292!--       Receive data from all other PEs.
1293          out_noa = SUM(noa_arr)
1294          IF ( out_noa > 0 ) THEN
1295             ALLOCATE( out_agents(1:out_noa) )
1296             IF ( noa > 0 ) THEN
1297                out_agents(1:noa) = trf_agents
1298             ENDIF
1299             noa_rcv = noa
1300             DO n = 1, numprocs-1
1301                IF ( noa_arr(n) > 0 ) THEN
1302                   CALL MPI_RECV( out_agents(noa_rcv+1), noa_arr(n)*agt_size,  &
1303                                  MPI_BYTE, n, 0, comm2d, status, ierr )
1304                   noa_rcv = noa_rcv + noa_arr(n)
1305                ENDIF
1306             ENDDO
1307          ELSE
1308             ALLOCATE( out_agents(1:2) )
1309             out_agents = zero_agent
1310             out_noa    = 2
1311          ENDIF
1312       ELSE
1313          IF ( noa > 0 ) THEN
1314             CALL MPI_SEND( trf_agents(1), noa*agt_size, MPI_BYTE, 0, 0,       &
1315                                        comm2d, ierr )
1316          ENDIF
1317       ENDIF
1318!
1319!--    A barrier has to be set, because otherwise some PEs may
1320!--    proceed too fast so that PE0 may receive wrong data on
1321!--    tag 0
1322       CALL MPI_BARRIER( comm2d, ierr )
1323#endif
1324       IF ( myid == 0 ) THEN
1325#if defined( __parallel )
1326          agents => out_agents
1327#else
1328          agents => trf_agents
1329#endif
1330
1331#if defined( __netcdf )
1332!
1333!--       Update maximum number of agents
1334          maximum_number_of_agents = MAX(maximum_number_of_agents, out_noa)
1335!
1336!--       Output in netCDF format
1337          IF ( ftest ) THEN
1338!
1339!--          First, define size of agent number dimension from amount of agents
1340!--          released, release interval, time of agent simulation and max
1341!--          age of agents
1342             dim_size_agtnum = MIN( MIN( multi_agent_system_end, end_time )    &
1343                                       - multi_agent_system_start,             &
1344                                    agent_maximum_age)
1345
1346             DO ii = 1, number_of_agent_groups
1347                dim_size_agtnum = dim_size_agtnum                              &
1348                                + (FLOOR( ( asr(ii)-asl(ii) ) / adx(ii) ) + 1) &
1349                                * (FLOOR( ( asn(ii)-ass(ii) ) / ady(ii) ) + 1) &
1350                                * (FLOOR( dim_size_agtnum / dt_arel )     + 1) &
1351                                * dim_size_factor_agtnum
1352                dim_size_agtnum = MIN( dim_size_agtnum, dim_size_agtnum_manual )
1353             ENDDO
1354             CALL check_open( 118 )
1355          ENDIF
1356
1357!
1358!--       Update the NetCDF time axis
1359          agt_time_count = agt_time_count + 1
1360
1361          IF ( .NOT. agt_dimension_exceeded ) THEN
1362!
1363!--          if number of agents to be output exceeds dimension, set flag and
1364!--          print warning
1365             IF ( out_noa > dim_size_agtnum ) THEN
1366
1367                agt_dimension_exceeded = .TRUE.
1368                WRITE(message_string,'(A,F11.1,2(A,I8))')                      &
1369                                'Number of agents exceeds agent dimension.' // &
1370                                '&Starting at time_since_reference_point = ',  &
1371                                time_since_reference_point,                    &
1372                                ' s, &data may be missing.'//                  &
1373                                '&Number of agents:     ', out_noa,            &
1374                                '&Agent dimension size: ', dim_size_agtnum
1375
1376                CALL message( 'mas_data_output_agents',                        &
1377                              'PA0420', 0, 1, 0, 6, 0 )
1378
1379             ENDIF
1380          ENDIF
1381
1382!
1383!--       reduce number of output agents to dimension size, if necessary
1384          IF ( agt_dimension_exceeded ) THEN
1385
1386             out_noa = MIN( out_noa, dim_size_agtnum )
1387
1388          ENDIF
1389
1390          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_time_agt,                 &
1391                                  (/ time_since_reference_point + agent_substep_time /),            &
1392                                  start = (/ agt_time_count /),                &
1393                                  count = (/ 1 /) )
1394          CALL netcdf_handle_error( 'mas_data_output_agents', 1 )
1395
1396!
1397!--       Output agent attributes
1398
1399          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(1), agents%id,        &
1400                                  start = (/ 1, agt_time_count /),             &
1401                                  count = (/ out_noa /) )
1402          CALL netcdf_handle_error( 'mas_data_output_agents', 2 )
1403 
1404          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(2), agents%x,         &
1405                                  start = (/ 1, agt_time_count /),             &
1406                                  count = (/ out_noa /) )
1407          CALL netcdf_handle_error( 'mas_data_output_agents', 3 )
1408
1409          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(3), agents%y,         &
1410                                  start = (/ 1, agt_time_count /),             &
1411                                  count = (/ out_noa /) )
1412          CALL netcdf_handle_error( 'mas_data_output_agents', 4 )
1413
1414          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(4), agents%windspeed, &
1415                                  start = (/ 1, agt_time_count /),             &
1416                                  count = (/ out_noa /) )
1417          CALL netcdf_handle_error( 'mas_data_output_agents', 5 )
1418
1419          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(5), agents%t,         &
1420                                  start = (/ 1, agt_time_count /),             &
1421                                  count = (/ out_noa /) )
1422          CALL netcdf_handle_error( 'mas_data_output_agents', 6 )
1423
1424          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(6), agents%group,     &
1425                                  start = (/ 1, agt_time_count /),             &
1426                                  count = (/ out_noa /) )
1427          CALL netcdf_handle_error( 'mas_data_output_agents', 7 )
1428          CALL cpu_log( log_point_s(17), 'mas_data_output', 'stop' )
1429
1430
1431!           nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(6), agents%pm10,      &
1432!                                   start = (/ 1, agt_time_count /),             &
1433!                                   count = (/ out_noa /) )
1434!           CALL netcdf_handle_error( 'mas_data_output_agents', 8 )
1435!
1436!           nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(7), agents%pm25,      &
1437!                                   start = (/ 1, agt_time_count /),             &
1438!                                   count = (/ out_noa /) )
1439!           CALL netcdf_handle_error( 'mas_data_output_agents', 9 )
1440!
1441!           nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(8), agents%therm_comf,&
1442!                                   start = (/ 1, agt_time_count /),             &
1443!                                   count = (/ out_noa /) )
1444!
1445!           nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(9), agents%uv,        &
1446!                                   start = (/ 1, agt_time_count /),             &
1447!                                   count = (/ out_noa /) )
1448!           CALL netcdf_handle_error( 'mas_data_output_agents', 10 )
1449
1450#endif
1451
1452#if defined( __parallel )
1453          IF ( ALLOCATED( out_agents ) ) DEALLOCATE( out_agents )
1454#endif
1455       ELSE
1456          CALL cpu_log( log_point_s(17), 'mas_data_output', 'stop' )
1457       ENDIF
1458
1459       IF ( ALLOCATED( trf_agents ) ) DEALLOCATE( trf_agents )
1460
1461    END SUBROUTINE mas_data_output_agents
1462
1463!------------------------------------------------------------------------------!
1464! Description:
1465! ------------
1466!> If an agent moves from one processor to another, this subroutine moves
1467!> the corresponding elements from the agent arrays of the old grid cells
1468!> to the agent arrays of the new grid cells.
1469!------------------------------------------------------------------------------!
1470    SUBROUTINE mas_eh_add_agents_to_gridcell (agent_array)
1471
1472       IMPLICIT NONE
1473
1474       INTEGER(iwp) ::  aindex !< dummy argument for new number of agents per grid box
1475       INTEGER(iwp) ::  ip     !< grid index (x) of agent
1476       INTEGER(iwp) ::  jp     !< grid index (x) of agent
1477       INTEGER(iwp) ::  n      !< index variable of agent
1478
1479       LOGICAL ::  pack_done !< flag to indicate that packing is done
1480
1481       TYPE(agent_type), DIMENSION(:), INTENT(IN)  ::  agent_array !< new agents in a grid box
1482       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  temp_ns     !< temporary agent array for reallocation
1483
1484       pack_done     = .FALSE.
1485
1486       DO n = 1, SIZE(agent_array)
1487
1488          IF ( .NOT. agent_array(n)%agent_mask )  CYCLE
1489
1490          ip = agent_array(n)%x * ddx
1491          jp = agent_array(n)%y * ddy
1492
1493          IF ( ip >= nxl  .AND.  ip <= nxr  .AND.                              &
1494               jp >= nys  .AND.  jp <= nyn )  &
1495          THEN ! agent stays on processor
1496             number_of_agents = agt_count(jp,ip)
1497             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
1498
1499             aindex = agt_count(jp,ip)+1
1500             IF( aindex > SIZE(grid_agents(jp,ip)%agents) )  THEN
1501                IF ( pack_done )  THEN
1502                   CALL mas_eh_realloc_agents_array (ip,jp)
1503                ELSE
1504                   CALL mas_ps_pack
1505                   agt_count(jp,ip) = number_of_agents
1506                   aindex = agt_count(jp,ip)+1
1507                   IF ( aindex > SIZE(grid_agents(jp,ip)%agents) )  THEN
1508                      CALL mas_eh_realloc_agents_array (ip,jp)
1509                   ENDIF
1510                   pack_done = .TRUE.
1511                ENDIF
1512             ENDIF
1513             grid_agents(jp,ip)%agents(aindex) = agent_array(n)
1514             agt_count(jp,ip) = aindex
1515          ELSE
1516             IF ( jp <= nys - 1 )  THEN
1517                nr_move_south = nr_move_south+1
1518!
1519!--             Before agent information is swapped to exchange-array, check
1520!--             if enough memory is allocated. If required, reallocate exchange
1521!--             array.
1522                IF ( nr_move_south > SIZE(move_also_south) )  THEN
1523!
1524!--                At first, allocate further temporary array to swap agent
1525!--                information.
1526                   ALLOCATE( temp_ns(SIZE(move_also_south)+NR_2_direction_move))
1527                   temp_ns(1:nr_move_south-1) = move_also_south                &
1528                                                (1:nr_move_south-1)
1529                   DEALLOCATE( move_also_south )
1530                   ALLOCATE( move_also_south(SIZE(temp_ns)) )
1531                   move_also_south(1:nr_move_south-1) = temp_ns                &
1532                                                        (1:nr_move_south-1)
1533                   DEALLOCATE( temp_ns )
1534
1535                ENDIF
1536
1537                move_also_south(nr_move_south) = agent_array(n)
1538
1539                IF ( jp == -1 )  THEN
1540!
1541!--                Apply boundary condition along y
1542                   IF ( ibc_mas_ns == 0 )  THEN
1543                      move_also_south(nr_move_south)%y =                       &
1544                                         move_also_south(nr_move_south)%y      &
1545                                       + ( ny + 1 ) * dy
1546                      move_also_south(nr_move_south)%origin_y =                &
1547                                       move_also_south(nr_move_south)%origin_y &
1548                                       + ( ny + 1 ) * dy
1549                   ELSEIF ( ibc_mas_ns == 1 )  THEN
1550!
1551!--                   Agent absorption
1552                      move_also_south(nr_move_south)%agent_mask = .FALSE.
1553                      deleted_agents = deleted_agents + 1
1554
1555                   ENDIF
1556                ENDIF
1557             ELSEIF ( jp >= nyn+1 )  THEN
1558                nr_move_north = nr_move_north+1
1559!
1560!--             Before agent information is swapped to exchange-array, check
1561!--             if enough memory is allocated. If required, reallocate exchange
1562!--             array.
1563                IF ( nr_move_north > SIZE(move_also_north) )  THEN
1564!
1565!--                At first, allocate further temporary array to swap agent
1566!--                information.
1567                   ALLOCATE( temp_ns(SIZE(move_also_north)+NR_2_direction_move))
1568                   temp_ns(1:nr_move_north-1) =                                &
1569                                move_also_south(1:nr_move_north-1)
1570                   DEALLOCATE( move_also_north )
1571                   ALLOCATE( move_also_north(SIZE(temp_ns)) )
1572                   move_also_north(1:nr_move_north-1) =                        &
1573                               temp_ns(1:nr_move_north-1)
1574                   DEALLOCATE( temp_ns )
1575
1576                ENDIF
1577
1578                move_also_north(nr_move_north) = agent_array(n)
1579                IF ( jp == ny+1 )  THEN
1580!
1581!--                Apply boundary condition along y
1582                   IF ( ibc_mas_ns == 0 )  THEN
1583
1584                      move_also_north(nr_move_north)%y =                       &
1585                         move_also_north(nr_move_north)%y                      &
1586                       - ( ny + 1 ) * dy
1587                      move_also_north(nr_move_north)%origin_y =                &
1588                         move_also_north(nr_move_north)%origin_y               &
1589                       - ( ny + 1 ) * dy
1590                   ELSEIF ( ibc_mas_ns == 1 )  THEN
1591!
1592!--                   Agent absorption
1593                      move_also_north(nr_move_north)%agent_mask = .FALSE.
1594                      deleted_agents = deleted_agents + 1
1595
1596                   ENDIF
1597                ENDIF
1598             ENDIF
1599          ENDIF
1600       ENDDO
1601
1602       RETURN
1603
1604    END SUBROUTINE mas_eh_add_agents_to_gridcell
1605
1606!------------------------------------------------------------------------------!
1607! Description:
1608! ------------
1609!> After ghost layer agents have been received from neighboring PEs, this
1610!> subroutine sorts them into the corresponding grid cells
1611!------------------------------------------------------------------------------!
1612    SUBROUTINE mas_eh_add_ghost_agents_to_gridcell (agent_array)
1613
1614       IMPLICIT NONE
1615
1616       INTEGER(iwp) ::  ip     !< grid index (x) of agent
1617       INTEGER(iwp) ::  jp     !< grid index (x) of agent
1618       INTEGER(iwp) ::  n      !< index variable of agent
1619       INTEGER(iwp) ::  aindex !< dummy argument for new number of agents per grid box
1620
1621       LOGICAL ::  pack_done !< flag to indicate that packing is done
1622
1623       TYPE(agent_type), DIMENSION(:), INTENT(IN)  ::  agent_array !< new agents in a grid box
1624
1625       pack_done     = .FALSE.
1626
1627       DO n = 1, SIZE(agent_array)
1628
1629          IF ( .NOT. agent_array(n)%agent_mask )  CYCLE
1630
1631          ip = agent_array(n)%x * ddx
1632          jp = agent_array(n)%y * ddy
1633
1634          IF ( ip < nxl  .OR.  ip > nxr  .OR.  jp < nys  .OR.  jp > nyn ) THEN
1635             number_of_agents = agt_count(jp,ip)
1636             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
1637
1638             aindex = agt_count(jp,ip)+1
1639             IF( aindex > SIZE(grid_agents(jp,ip)%agents) )  THEN
1640                IF ( pack_done )  THEN
1641                   CALL mas_eh_realloc_agents_array (ip,jp)
1642                ELSE
1643                   CALL mas_ps_pack
1644                   agt_count(jp,ip) = number_of_agents
1645                   aindex = agt_count(jp,ip)+1
1646                   IF ( aindex > SIZE(grid_agents(jp,ip)%agents) )  THEN
1647                      CALL mas_eh_realloc_agents_array (ip,jp)
1648                   ENDIF
1649                   pack_done = .TRUE.
1650                ENDIF
1651             ENDIF
1652             grid_agents(jp,ip)%agents(aindex) = agent_array(n)
1653             agt_count(jp,ip) = aindex
1654          ENDIF
1655       ENDDO
1656    END SUBROUTINE mas_eh_add_ghost_agents_to_gridcell
1657
1658!------------------------------------------------------------------------------!
1659! Description:
1660! ------------
1661!> Resizing of agent arrays
1662!------------------------------------------------------------------------------!
1663    SUBROUTINE mas_eh_dealloc_agents_array
1664
1665       IMPLICIT NONE
1666
1667       INTEGER(iwp) ::  i         !< grid index (x) of agent
1668       INTEGER(iwp) ::  j         !< grid index (y) of agent
1669       INTEGER(iwp) ::  old_size  !< old array size
1670       INTEGER(iwp) ::  new_size  !< new array size
1671       INTEGER(iwp) ::  noa       !< number of agents
1672
1673       LOGICAL ::  dealloc  !< flag that indicates if reallocation is necessary
1674
1675       TYPE(agent_type), DIMENSION(10) ::  tmp_agents_s !< temporary static agent array
1676
1677       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  tmp_agents_d !< temporary dynamic agent array
1678
1679       DO  i = nxlg, nxrg
1680          DO  j = nysg, nyng
1681!
1682!--          Determine number of active agents
1683             noa = agt_count(j,i)
1684!
1685!--          Determine allocated memory size
1686             old_size = SIZE( grid_agents(j,i)%agents )
1687!
1688!--          Check for large unused memory
1689             dealloc = ( ( noa < min_nr_agent .AND. old_size  > min_nr_agent ) &
1690                    .OR. ( noa > min_nr_agent .AND. old_size - noa *           &
1691                         ( 1.0_wp + 0.01_wp * alloc_factor_mas ) > 0.0_wp ) )
1692!
1693!--          If large unused memory was found, resize the corresponding array
1694             IF ( dealloc )  THEN
1695                IF ( noa < min_nr_agent )  THEN
1696                   new_size = min_nr_agent
1697                ELSE
1698                   new_size = INT( noa * ( 1.0_wp +                            &
1699                                            0.01_wp * alloc_factor_mas ) )
1700                ENDIF
1701
1702                IF ( noa <= 10 )  THEN
1703
1704                   tmp_agents_s(1:noa) = grid_agents(j,i)%agents(1:noa)
1705
1706                   DEALLOCATE(grid_agents(j,i)%agents)
1707                   ALLOCATE(grid_agents(j,i)%agents(1:new_size))
1708
1709                   grid_agents(j,i)%agents(1:noa)          = tmp_agents_s(1:noa)
1710                   grid_agents(j,i)%agents(noa+1:new_size) = zero_agent
1711
1712                ELSE
1713
1714                   ALLOCATE(tmp_agents_d(noa))
1715                   tmp_agents_d(1:noa) = grid_agents(j,i)%agents(1:noa)
1716
1717                   DEALLOCATE(grid_agents(j,i)%agents)
1718                   ALLOCATE(grid_agents(j,i)%agents(new_size))
1719
1720                   grid_agents(j,i)%agents(1:noa)          = tmp_agents_d(1:noa)
1721                   grid_agents(j,i)%agents(noa+1:new_size) = zero_agent
1722
1723                   DEALLOCATE(tmp_agents_d)
1724
1725                ENDIF
1726
1727             ENDIF
1728          ENDDO
1729       ENDDO
1730
1731    END SUBROUTINE mas_eh_dealloc_agents_array
1732
1733!------------------------------------------------------------------------------!
1734! Description:
1735! ------------
1736!> Exchange between subdomains.
1737!> As soon as one agent has moved beyond the boundary of the domain, it
1738!> is included in the relevant transfer arrays and marked for subsequent
1739!> deletion on this PE.
1740!> First sweep for crossings in x direction. Find out first the number of
1741!> agents to be transferred and allocate temporary arrays needed to store
1742!> them.
1743!> For a one-dimensional decomposition along y, no transfer is necessary,
1744!> because the agent remains on the PE, but the agent coordinate has to
1745!> be adjusted.
1746!------------------------------------------------------------------------------!
1747    SUBROUTINE mas_eh_exchange_horiz
1748
1749       IMPLICIT NONE
1750
1751       INTEGER(iwp) ::  i                !< grid index (x) of agent positition
1752       INTEGER(iwp) ::  ip               !< index variable along x
1753       INTEGER(iwp) ::  j                !< grid index (y) of agent positition
1754       INTEGER(iwp) ::  jp               !< index variable along y
1755       INTEGER(iwp) ::  n                !< agent index variable
1756       INTEGER(iwp) ::  par_size         !< Agent size in bytes
1757       INTEGER(iwp) ::  trla_count       !< number of agents send to left PE
1758       INTEGER(iwp) ::  trla_count_recv  !< number of agents receive from right PE
1759       INTEGER(iwp) ::  trna_count       !< number of agents send to north PE
1760       INTEGER(iwp) ::  trna_count_recv  !< number of agents receive from south PE
1761       INTEGER(iwp) ::  trra_count       !< number of agents send to right PE
1762       INTEGER(iwp) ::  trra_count_recv  !< number of agents receive from left PE
1763       INTEGER(iwp) ::  trsa_count       !< number of agents send to south PE
1764       INTEGER(iwp) ::  trsa_count_recv  !< number of agents receive from north PE
1765
1766       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  rvla  !< agents received from right PE
1767       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  rvna  !< agents received from south PE
1768       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  rvra  !< agents received from left PE
1769       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  rvsa  !< agents received from north PE
1770       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  trla  !< agents send to left PE
1771       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  trna  !< agents send to north PE
1772       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  trra  !< agents send to right PE
1773       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  trsa  !< agents send to south PE
1774
1775#if defined( __parallel )
1776
1777!
1778!--    Exchange between subdomains.
1779!--    As soon as one agent has moved beyond the boundary of the domain, it
1780!--    is included in the relevant transfer arrays and marked for subsequent
1781!--    deletion on this PE.
1782!--    First sweep for crossings in x direction. Find out first the number of
1783!--    agents to be transferred and allocate temporary arrays needed to store
1784!--    them.
1785!--    For a one-dimensional decomposition along y, no transfer is necessary,
1786!--    because the agent remains on the PE, but the agent coordinate has to
1787!--    be adjusted.
1788       trla_count  = 0
1789       trra_count  = 0
1790
1791       trla_count_recv   = 0
1792       trra_count_recv   = 0
1793
1794       IF ( pdims(1) /= 1 )  THEN
1795!
1796!--       First calculate the storage necessary for sending and receiving the data.
1797!--       Compute only first (nxl) and last (nxr) loop iterration.
1798          DO  ip = nxl, nxr, nxr - nxl
1799             DO  jp = nys, nyn
1800
1801                number_of_agents = agt_count(jp,ip)
1802                IF ( number_of_agents <= 0 )  CYCLE
1803                agents => grid_agents(jp,ip)%agents(1:number_of_agents)
1804                DO  n = 1, number_of_agents
1805                   IF ( agents(n)%agent_mask )  THEN
1806                      i = agents(n)%x * ddx
1807!
1808!--                   Above calculation does not work for indices less than zero
1809                      IF ( agents(n)%x < 0.0_wp )  i = -1
1810
1811                      IF ( i < nxl )  THEN
1812                         trla_count = trla_count + 1
1813                      ELSEIF ( i > nxr )  THEN
1814                         trra_count = trra_count + 1
1815                      ENDIF
1816                   ENDIF
1817                ENDDO
1818
1819             ENDDO
1820          ENDDO
1821
1822          IF ( trla_count  == 0 )  trla_count  = 1
1823          IF ( trra_count  == 0 )  trra_count  = 1
1824
1825          ALLOCATE( trla(trla_count), trra(trra_count) )
1826
1827          trla = zero_agent
1828          trra = zero_agent
1829
1830          trla_count  = 0
1831          trra_count  = 0
1832
1833       ENDIF
1834!
1835!--    Compute only first (nxl) and last (nxr) loop iterration
1836       DO  ip = nxl, nxr, nxr-nxl
1837          DO  jp = nys, nyn
1838             number_of_agents = agt_count(jp,ip)
1839             IF ( number_of_agents <= 0 ) CYCLE
1840             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
1841             DO  n = 1, number_of_agents
1842!
1843!--             Only those agents that have not been marked as 'deleted' may
1844!--             be moved.
1845                IF ( agents(n)%agent_mask )  THEN
1846
1847                   i = agents(n)%x * ddx
1848!
1849!--                Above calculation does not work for indices less than zero
1850                   IF ( agents(n)%x < 0.0_wp )  i = -1
1851
1852                   IF ( i <  nxl )  THEN
1853                      IF ( i < 0 )  THEN
1854!
1855!--                      Apply boundary condition along x
1856                         IF ( ibc_mas_lr == 0 )  THEN
1857!
1858!--                         Cyclic condition
1859                            IF ( pdims(1) == 1 )  THEN
1860                               agents(n)%x        = ( nx + 1 ) * dx +          &
1861                                                    agents(n)%x
1862                               agents(n)%origin_x = ( nx + 1 ) * dx +          &
1863                                                    agents(n)%origin_x
1864                            ELSE
1865                               trla_count         = trla_count + 1
1866                               trla(trla_count)   = agents(n)
1867                               trla(trla_count)%x = ( nx + 1 ) * dx +          &
1868                                                    trla(trla_count)%x
1869                               trla(trla_count)%origin_x =                     &
1870                                                trla(trla_count)%origin_x +    &
1871                                                ( nx + 1 ) * dx
1872                               agents(n)%agent_mask  = .FALSE.
1873                               deleted_agents = deleted_agents + 1
1874
1875                               IF ( trla(trla_count)%x >=                      &
1876                                        (nx + 1)* dx - 1.0E-12_wp )            &
1877                               THEN
1878                                  trla(trla_count)%x = trla(trla_count)%x -    &
1879                                                   1.0E-10_wp
1880                                  trla(trla_count)%origin_x =                  &
1881                                                   trla(trla_count)%origin_x - 1
1882                               ENDIF
1883
1884                            ENDIF
1885
1886                         ELSEIF ( ibc_mas_lr == 1 )  THEN
1887!
1888!--                         Agent absorption
1889                            agents(n)%agent_mask = .FALSE.
1890                            deleted_agents = deleted_agents + 1
1891
1892                         ENDIF
1893                      ELSE
1894!
1895!--                      Store agent data in the transfer array, which will be
1896!--                      send to the neighbouring PE
1897                         trla_count = trla_count + 1
1898                         trla(trla_count) = agents(n)
1899                         agents(n)%agent_mask = .FALSE.
1900                         deleted_agents = deleted_agents + 1
1901
1902                      ENDIF
1903
1904                   ELSEIF ( i > nxr )  THEN
1905                      IF ( i > nx )  THEN
1906!
1907!--                      Apply boundary condition along x
1908                         IF ( ibc_mas_lr == 0 )  THEN
1909!
1910!--                         Cyclic condition
1911                            IF ( pdims(1) == 1 )  THEN
1912                               agents(n)%x = agents(n)%x - ( nx + 1 ) * dx
1913                               agents(n)%origin_x = agents(n)%origin_x - &
1914                               ( nx + 1 ) * dx
1915                            ELSE
1916                               trra_count = trra_count + 1
1917                               trra(trra_count) = agents(n)
1918                               trra(trra_count)%x = trra(trra_count)%x -       &
1919                                                    ( nx + 1 ) * dx
1920                               trra(trra_count)%origin_x =                     &
1921                                                   trra(trra_count)%origin_x - &
1922                                                   ( nx + 1 ) * dx
1923                               agents(n)%agent_mask = .FALSE.
1924                               deleted_agents = deleted_agents + 1
1925
1926                            ENDIF
1927
1928                         ELSEIF ( ibc_mas_lr == 1 )  THEN
1929!
1930!--                         Agent absorption
1931                            agents(n)%agent_mask = .FALSE.
1932                            deleted_agents = deleted_agents + 1
1933
1934                         ENDIF
1935                      ELSE
1936!
1937!--                      Store agent data in the transfer array, which will be send
1938!--                      to the neighbouring PE
1939                         trra_count = trra_count + 1
1940                         trra(trra_count) = agents(n)
1941                         agents(n)%agent_mask = .FALSE.
1942                         deleted_agents = deleted_agents + 1
1943
1944                      ENDIF
1945
1946                   ENDIF
1947                ENDIF
1948
1949             ENDDO
1950          ENDDO
1951       ENDDO
1952
1953!
1954!--    Allocate arrays required for north-south exchange, as these
1955!--    are used directly after agents are exchange along x-direction.
1956       ALLOCATE( move_also_north(1:NR_2_direction_move) )
1957       ALLOCATE( move_also_south(1:NR_2_direction_move) )
1958
1959       nr_move_north = 0
1960       nr_move_south = 0
1961!
1962!--    Send left boundary, receive right boundary (but first exchange how many
1963!--    and chec if agent storage must be extended)
1964       IF ( pdims(1) /= 1 )  THEN
1965
1966          CALL MPI_SENDRECV( trla_count,      1, MPI_INTEGER, pleft,  0, &
1967                             trra_count_recv, 1, MPI_INTEGER, pright, 0, &
1968                             comm2d, status, ierr )
1969
1970          ALLOCATE(rvra(MAX(1,trra_count_recv)))
1971!
1972!--       This MPI_SENDRECV should work even with odd mixture on 32 and 64 Bit
1973!--       variables in structure agent_type (due to the calculation of par_size)
1974          par_size = STORAGE_SIZE(trla(1))/8
1975          CALL MPI_SENDRECV( trla, max(1,trla_count)*par_size, MPI_BYTE, pleft,&
1976                    1, rvra, max(1,trra_count_recv)*par_size, MPI_BYTE, pright,&
1977                             1, comm2d, status, ierr )
1978
1979          IF ( trra_count_recv > 0 ) THEN
1980             CALL mas_eh_add_agents_to_gridcell(rvra(1:trra_count_recv))
1981          ENDIF
1982
1983          DEALLOCATE(rvra)
1984
1985!
1986!--       Send right boundary, receive left boundary
1987          CALL MPI_SENDRECV( trra_count,      1, MPI_INTEGER, pright, 0,       &
1988                             trla_count_recv, 1, MPI_INTEGER, pleft,  0,       &
1989                             comm2d, status, ierr )
1990
1991          ALLOCATE(rvla(MAX(1,trla_count_recv)))
1992!
1993!--       This MPI_SENDRECV should work even with odd mixture on 32 and 64 Bit
1994!--       variables in structure agent_type (due to the calculation of par_size)
1995          par_size = STORAGE_SIZE(trra(1))/8
1996          CALL MPI_SENDRECV( trra, max(1,trra_count)*par_size, MPI_BYTE,       &
1997                             pright, 1, rvla,                                  &
1998                             max(1,trla_count_recv)*par_size, MPI_BYTE,        &
1999                             pleft, 1, comm2d, status, ierr )
2000
2001          IF ( trla_count_recv > 0 ) THEN
2002             CALL mas_eh_add_agents_to_gridcell(rvla(1:trla_count_recv))
2003          ENDIF
2004
2005          DEALLOCATE( rvla )
2006          DEALLOCATE( trla, trra )
2007
2008       ENDIF
2009
2010!
2011!--    Check whether agents have crossed the boundaries in y direction. Note
2012!--    that this case can also apply to agents that have just been received
2013!--    from the adjacent right or left PE.
2014!--    Find out first the number of agents to be transferred and allocate
2015!--    temporary arrays needed to store them.
2016!--    For a one-dimensional decomposition along y, no transfer is necessary,
2017!--    because the agent remains on the PE.
2018       trsa_count  = nr_move_south
2019       trna_count  = nr_move_north
2020
2021       trsa_count_recv   = 0
2022       trna_count_recv   = 0
2023
2024       IF ( pdims(2) /= 1 )  THEN
2025!
2026!--       First calculate the storage necessary for sending and receiving the
2027!--       data
2028          DO  ip = nxl, nxr
2029             DO  jp = nys, nyn, nyn-nys    !compute only first (nys) and last (nyn) loop iterration
2030                number_of_agents = agt_count(jp,ip)
2031                IF ( number_of_agents <= 0 )  CYCLE
2032                agents => grid_agents(jp,ip)%agents(1:number_of_agents)
2033                DO  n = 1, number_of_agents
2034                   IF ( agents(n)%agent_mask )  THEN
2035                      j = agents(n)%y * ddy
2036!
2037!--                   Above calculation does not work for indices less than zero
2038                      IF ( agents(n)%y < 0.0_wp )  j = -1
2039
2040                      IF ( j < nys )  THEN
2041                         trsa_count = trsa_count + 1
2042                      ELSEIF ( j > nyn )  THEN
2043                         trna_count = trna_count + 1
2044                      ENDIF
2045                   ENDIF
2046                ENDDO
2047             ENDDO
2048          ENDDO
2049
2050          IF ( trsa_count  == 0 )  trsa_count  = 1
2051          IF ( trna_count  == 0 )  trna_count  = 1
2052
2053          ALLOCATE( trsa(trsa_count), trna(trna_count) )
2054
2055          trsa = zero_agent
2056          trna = zero_agent
2057
2058          trsa_count  = nr_move_south
2059          trna_count  = nr_move_north
2060
2061          trsa(1:nr_move_south) = move_also_south(1:nr_move_south)
2062          trna(1:nr_move_north) = move_also_north(1:nr_move_north)
2063
2064       ENDIF
2065
2066       DO  ip = nxl, nxr
2067          DO  jp = nys, nyn, nyn-nys ! compute only first (nys) and last (nyn) loop iterration
2068             number_of_agents = agt_count(jp,ip)
2069             IF ( number_of_agents <= 0 )  CYCLE
2070             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
2071             DO  n = 1, number_of_agents
2072!
2073!--             Only those agents that have not been marked as 'deleted' may
2074!--             be moved.
2075                IF ( agents(n)%agent_mask )  THEN
2076
2077                   j = agents(n)%y * ddy
2078!
2079!--                Above calculation does not work for indices less than zero
2080                   IF ( agents(n)%y < 0.0_wp * dy )  j = -1
2081
2082                   IF ( j < nys )  THEN
2083                      IF ( j < 0 )  THEN
2084!
2085!--                      Apply boundary condition along y
2086                         IF ( ibc_mas_ns == 0 )  THEN
2087!
2088!--                         Cyclic condition
2089                            IF ( pdims(2) == 1 )  THEN
2090                               agents(n)%y = ( ny + 1 ) * dy + agents(n)%y
2091                               agents(n)%origin_y = ( ny + 1 ) * dy +          &
2092                                                     agents(n)%origin_y
2093                            ELSE
2094                               trsa_count         = trsa_count + 1
2095                               trsa(trsa_count)   = agents(n)
2096                               trsa(trsa_count)%y = ( ny + 1 ) * dy +          &
2097                                                 trsa(trsa_count)%y
2098                               trsa(trsa_count)%origin_y =                     &
2099                                                  trsa(trsa_count)%origin_y    &
2100                                                + ( ny + 1 ) * dy
2101                               agents(n)%agent_mask = .FALSE.
2102                               deleted_agents = deleted_agents + 1
2103
2104                               IF ( trsa(trsa_count)%y >=                      &
2105                                                    (ny+1)* dy - 1.0E-12_wp )  &
2106                               THEN
2107                                  trsa(trsa_count)%y = trsa(trsa_count)%y -    &
2108                                                       1.0E-10_wp
2109                                  trsa(trsa_count)%origin_y =                  &
2110                                                  trsa(trsa_count)%origin_y - 1
2111                               ENDIF
2112
2113                            ENDIF
2114
2115                         ELSEIF ( ibc_mas_ns == 1 )  THEN
2116!
2117!--                         Agent absorption
2118                            agents(n)%agent_mask = .FALSE.
2119                            deleted_agents          = deleted_agents + 1
2120
2121                         ENDIF
2122                      ELSE
2123!
2124!--                      Store agent data in the transfer array, which will
2125!--                      be send to the neighbouring PE
2126                         trsa_count = trsa_count + 1
2127                         trsa(trsa_count) = agents(n)
2128                         agents(n)%agent_mask = .FALSE.
2129                         deleted_agents = deleted_agents + 1
2130
2131                      ENDIF
2132
2133                   ELSEIF ( j > nyn )  THEN
2134                      IF ( j > ny )  THEN
2135!
2136!--                      Apply boundary condition along y
2137                         IF ( ibc_mas_ns == 0 )  THEN
2138!
2139!--                         Cyclic condition
2140                            IF ( pdims(2) == 1 )  THEN
2141                               agents(n)%y        = agents(n)%y -              &
2142                                                    ( ny + 1 ) * dy
2143                               agents(n)%origin_y = agents(n)%origin_y -       &
2144                                                    ( ny + 1 ) * dy
2145                            ELSE
2146                               trna_count         = trna_count + 1
2147                               trna(trna_count)   = agents(n)
2148                               trna(trna_count)%y =                            &
2149                                          trna(trna_count)%y - ( ny + 1 ) * dy
2150                               trna(trna_count)%origin_y =                     &
2151                                         trna(trna_count)%origin_y -           &
2152                                         ( ny + 1 ) * dy
2153                               agents(n)%agent_mask = .FALSE.
2154                               deleted_agents          = deleted_agents + 1
2155                            ENDIF
2156
2157                         ELSEIF ( ibc_mas_ns == 1 )  THEN
2158!
2159!--                         Agent absorption
2160                            agents(n)%agent_mask = .FALSE.
2161                            deleted_agents = deleted_agents + 1
2162
2163                         ENDIF
2164                      ELSE
2165!
2166!--                      Store agent data in the transfer array, which will
2167!--                      be send to the neighbouring PE
2168                         trna_count = trna_count + 1
2169                         trna(trna_count) = agents(n)
2170                         agents(n)%agent_mask = .FALSE.
2171                         deleted_agents = deleted_agents + 1
2172
2173                      ENDIF
2174
2175                   ENDIF
2176                ENDIF
2177             ENDDO
2178          ENDDO
2179       ENDDO
2180
2181!
2182!--    Send front boundary, receive back boundary (but first exchange how many
2183!--    and chec if agent storage must be extended)
2184       IF ( pdims(2) /= 1 )  THEN
2185
2186          CALL MPI_SENDRECV( trsa_count,      1, MPI_INTEGER, psouth, 0,       &
2187                             trna_count_recv, 1, MPI_INTEGER, pnorth, 0,       &
2188                             comm2d, status, ierr )
2189
2190          ALLOCATE(rvna(MAX(1,trna_count_recv)))
2191!
2192!--       This MPI_SENDRECV should work even with odd mixture on 32 and 64 Bit
2193!--       variables in structure agent_type (due to the calculation of par_size)
2194          par_size = STORAGE_SIZE(trsa(1))/8
2195          CALL MPI_SENDRECV( trsa, trsa_count*par_size, MPI_BYTE,              &
2196                             psouth, 1, rvna,                                  &
2197                             trna_count_recv*par_size, MPI_BYTE, pnorth, 1,    &
2198                             comm2d, status, ierr )
2199
2200          IF ( trna_count_recv  > 0 ) THEN
2201             CALL mas_eh_add_agents_to_gridcell(rvna(1:trna_count_recv))
2202          ENDIF
2203
2204          DEALLOCATE(rvna)
2205
2206!
2207!--       Send back boundary, receive front boundary
2208          CALL MPI_SENDRECV( trna_count,      1, MPI_INTEGER, pnorth, 0,       &
2209                             trsa_count_recv, 1, MPI_INTEGER, psouth, 0,       &
2210                             comm2d, status, ierr )
2211
2212          ALLOCATE(rvsa(MAX(1,trsa_count_recv)))
2213!
2214!--       This MPI_SENDRECV should work even with odd mixture on 32 and 64 Bit
2215!--       variables in structure agent_type (due to the calculation of par_size)
2216          par_size = STORAGE_SIZE(trna(1))/8
2217          CALL MPI_SENDRECV( trna, trna_count*par_size, MPI_BYTE,              &
2218                             pnorth, 1, rvsa,                                  &
2219                             trsa_count_recv*par_size, MPI_BYTE, psouth, 1,    &
2220                             comm2d, status, ierr )
2221
2222          IF ( trsa_count_recv > 0 ) THEN
2223             CALL mas_eh_add_agents_to_gridcell(rvsa(1:trsa_count_recv))
2224          ENDIF
2225
2226          DEALLOCATE(rvsa)
2227
2228          number_of_agents = number_of_agents + trsa_count_recv
2229
2230          DEALLOCATE( trsa, trna )
2231
2232       ENDIF
2233
2234       DEALLOCATE( move_also_north )
2235       DEALLOCATE( move_also_south )
2236
2237#else
2238
2239       DO  ip = nxl, nxr, nxr-nxl
2240          DO  jp = nys, nyn
2241             number_of_agents = agt_count(jp,ip)
2242             IF ( number_of_agents <= 0 )  CYCLE
2243             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
2244             DO  n = 1, number_of_agents
2245!
2246!--             Apply boundary conditions
2247                IF ( agents(n)%x < 0.0_wp )  THEN
2248
2249                   IF ( ibc_mas_lr == 0 )  THEN
2250!
2251!--                   Cyclic boundary. Relevant coordinate has to be changed.
2252                      agents(n)%x = ( nx + 1 ) * dx + agents(n)%x
2253                      agents(n)%origin_x = ( nx + 1 ) * dx + &
2254                                  agents(n)%origin_x
2255                   ELSEIF ( ibc_mas_lr == 1 )  THEN
2256!
2257!--                   Agent absorption
2258                      agents(n)%agent_mask = .FALSE.
2259                      deleted_agents = deleted_agents + 1
2260                   ENDIF
2261
2262                ELSEIF ( agents(n)%x >= ( nx + 1 ) * dx )  THEN
2263
2264                   IF ( ibc_mas_lr == 0 )  THEN
2265!
2266!--                   Cyclic boundary. Relevant coordinate has to be changed.
2267                      agents(n)%x = agents(n)%x - ( nx + 1 ) * dx
2268
2269                   ELSEIF ( ibc_mas_lr == 1 )  THEN
2270!
2271!--                   Agent absorption
2272                      agents(n)%agent_mask = .FALSE.
2273                      deleted_agents = deleted_agents + 1
2274                   ENDIF
2275
2276                ENDIF
2277             ENDDO
2278          ENDDO
2279       ENDDO
2280
2281       DO  ip = nxl, nxr
2282          DO  jp = nys, nyn, nyn-nys
2283             number_of_agents = agt_count(jp,ip)
2284             IF ( number_of_agents <= 0 )  CYCLE
2285             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
2286             DO  n = 1, number_of_agents
2287
2288                IF ( agents(n)%y < 0.0_wp )  THEN
2289
2290                   IF ( ibc_mas_ns == 0 )  THEN
2291!
2292!--                   Cyclic boundary. Relevant coordinate has to be changed.
2293                      agents(n)%y = ( ny + 1 ) * dy + agents(n)%y
2294                      agents(n)%origin_y = ( ny + 1 ) * dy + &
2295                           agents(n)%origin_y
2296
2297                   ELSEIF ( ibc_mas_ns == 1 )  THEN
2298!
2299!--                   Agent absorption
2300                      agents(n)%agent_mask = .FALSE.
2301                      deleted_agents = deleted_agents + 1
2302                   ENDIF
2303
2304                ELSEIF ( agents(n)%y >= ( ny + 0.5_wp ) * dy )  THEN
2305
2306                   IF ( ibc_mas_ns == 0 )  THEN
2307!
2308!--                   Cyclic boundary. Relevant coordinate has to be changed.
2309                      agents(n)%y = agents(n)%y - ( ny + 1 ) * dy
2310
2311                   ELSEIF ( ibc_mas_ns == 1 )  THEN
2312!
2313!--                   Agent absorption
2314                      agents(n)%agent_mask = .FALSE.
2315                      deleted_agents = deleted_agents + 1
2316                   ENDIF
2317
2318                ENDIF
2319
2320             ENDDO
2321          ENDDO
2322       ENDDO
2323#endif
2324
2325!
2326!--    Accumulate the number of agents transferred between the subdomains)
2327       CALL mas_eh_ghost_exchange
2328
2329    END SUBROUTINE mas_eh_exchange_horiz
2330
2331!------------------------------------------------------------------------------!
2332! Description:
2333! ------------
2334!> Sends the agents from the three gridcells closest to the
2335!> north/south/left/right border of a PE to the corresponding neighbors ghost
2336!> layer (which is three grid boxes deep)
2337!------------------------------------------------------------------------------!
2338    SUBROUTINE mas_eh_ghost_exchange
2339
2340       IMPLICIT NONE
2341
2342#if defined( __parallel )
2343
2344       INTEGER(iwp) ::  ip          !< index variable along x
2345       INTEGER(iwp) ::  jp          !< index variable along y
2346       INTEGER(iwp) ::  agt_size    !< Bit size of agent datatype
2347       INTEGER(iwp) ::  ghla_count  !< ghost points left agent
2348       INTEGER(iwp) ::  ghna_count  !< ghost points north agent
2349       INTEGER(iwp) ::  ghra_count  !< ghost points right agent
2350       INTEGER(iwp) ::  ghsa_count  !< ghost points south agent
2351
2352       LOGICAL ::  ghla_empty      !< ghost points left agent
2353       LOGICAL ::  ghla_empty_rcv  !< ghost points left agent
2354       LOGICAL ::  ghna_empty      !< ghost points north agent
2355       LOGICAL ::  ghna_empty_rcv  !< ghost points north agent
2356       LOGICAL ::  ghra_empty      !< ghost points right agent
2357       LOGICAL ::  ghra_empty_rcv  !< ghost points right agent
2358       LOGICAL ::  ghsa_empty      !< ghost points south agent
2359       LOGICAL ::  ghsa_empty_rcv  !< ghost points south agent
2360
2361       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  ghla  !< agents received from right PE
2362       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  ghna  !< agents received from south PE
2363       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  ghra  !< agents received from left PE
2364       TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  ghsa  !< agents received from north PE
2365
2366       ghla_empty = .TRUE.
2367       ghna_empty = .TRUE.
2368       ghra_empty = .TRUE.
2369       ghsa_empty = .TRUE.
2370!
2371!--    reset ghost layer
2372       DO ip = nxlg, nxl-1
2373          DO jp = nysg, nyng
2374             agt_count(jp,ip) = 0
2375          ENDDO
2376       ENDDO
2377       DO ip = nxr+1, nxrg
2378          DO jp = nysg, nyng
2379             agt_count(jp,ip) = 0
2380          ENDDO
2381       ENDDO
2382       DO ip = nxl, nxr
2383          DO jp = nysg, nys-1
2384             agt_count(jp,ip) = 0
2385          ENDDO
2386       ENDDO
2387       DO ip = nxl, nxr
2388          DO jp = nyn+1, nyng
2389             agt_count(jp,ip) = 0
2390          ENDDO
2391       ENDDO
2392!
2393!--    Transfer of agents from left to right and vice versa
2394       IF ( pdims(1) /= 1 )  THEN
2395!
2396!--       Reset left and right ghost layers
2397          ghla_count  = 0
2398          ghra_count  = 0
2399!
2400!--       First calculate the storage necessary for sending
2401!--       and receiving the data.
2402          ghla_count = SUM(agt_count(nys:nyn,nxl:nxl+2))
2403          ghra_count = SUM(agt_count(nys:nyn,nxr-2:nxr))
2404!
2405!--       No cyclic boundaries for agents
2406          IF ( nxl == 0 .OR. ghla_count == 0 ) THEN
2407             ghla_count = 1
2408          ELSE
2409             ghla_empty = .FALSE.
2410          ENDIF
2411          IF ( nxr == nx .OR. ghra_count == 0 ) THEN
2412             ghra_count = 1
2413          ELSE
2414             ghra_empty = .FALSE.
2415          ENDIF
2416          ALLOCATE( ghla(1:ghla_count), ghra(1:ghra_count) )
2417          ghla = zero_agent
2418          ghra = zero_agent
2419!
2420!--       Get all agents that will be sent left into one array
2421          ghla_count = 0
2422          IF ( nxl /= 0 ) THEN
2423             DO ip = nxl, nxl+2
2424                DO jp = nys, nyn
2425
2426                   number_of_agents = agt_count(jp,ip)
2427                   IF ( number_of_agents <= 0 )  CYCLE
2428                   ghla(ghla_count+1:ghla_count+number_of_agents)              &
2429                       = grid_agents(jp,ip)%agents(1:number_of_agents)
2430                   ghla_count = ghla_count + number_of_agents
2431
2432                ENDDO
2433             ENDDO
2434          ENDIF
2435          IF ( ghla_count == 0 )  ghla_count = 1
2436!
2437!--       Get all agents that will be sent right into one array
2438          ghra_count = 0
2439          IF ( nxr /= nx ) THEN
2440             DO ip = nxr-2, nxr
2441                DO jp = nys, nyn
2442
2443                   number_of_agents = agt_count(jp,ip)
2444                   IF ( number_of_agents <= 0 )  CYCLE
2445                   ghra(ghra_count+1:ghra_count+number_of_agents)              &
2446                       = grid_agents(jp,ip)%agents(1:number_of_agents)
2447                   ghra_count = ghra_count + number_of_agents
2448
2449                ENDDO
2450             ENDDO
2451          ENDIF
2452          IF ( ghra_count == 0 ) ghra_count = 1
2453!
2454!--       Send/receive number of agents that
2455!--       will be transferred to/from left/right neighbor
2456          CALL MPI_SENDRECV( ghla_count,      1, MPI_INTEGER, pleft,  0,       &
2457                             ghra_count_recv, 1, MPI_INTEGER, pright, 0,       &
2458                             comm2d, status, ierr )
2459          ALLOCATE ( agt_gh_r(1:ghra_count_recv) )
2460!
2461!--       Send/receive number of agents that
2462!--       will be transferred to/from right/left neighbor
2463          CALL MPI_SENDRECV( ghra_count,      1, MPI_INTEGER, pright,  0,      &
2464                             ghla_count_recv, 1, MPI_INTEGER, pleft,   0,      &
2465                             comm2d, status, ierr )
2466!
2467!--       Send/receive flag that indicates if there are actually any agents
2468!--       in ghost  layer
2469          CALL MPI_SENDRECV( ghla_empty,     1, MPI_LOGICAL, pleft, 1,         &
2470                             ghra_empty_rcv, 1, MPI_LOGICAL, pright,1,         &
2471                             comm2d, status, ierr )
2472          CALL MPI_SENDRECV( ghra_empty,     1, MPI_LOGICAL, pright,1,         &
2473                             ghla_empty_rcv, 1, MPI_LOGICAL, pleft, 1,         &
2474                             comm2d, status, ierr )
2475
2476
2477          ALLOCATE ( agt_gh_l(1:ghla_count_recv) )
2478!
2479!--       Get bit size of one agent
2480          agt_size = STORAGE_SIZE(zero_agent)/8
2481!
2482!--       Send/receive agents to/from left/right neighbor
2483          CALL MPI_SENDRECV( ghla,     ghla_count      * agt_size, MPI_BYTE,   &
2484                                pleft, 1,                                      &
2485                             agt_gh_r, ghra_count_recv * agt_size, MPI_BYTE,   &
2486                                pright,1,                                      &
2487                             comm2d, status, ierr )
2488!
2489!--       Send/receive agents to/from left/right neighbor
2490          CALL MPI_SENDRECV( ghra,     ghra_count      * agt_size, MPI_BYTE,   &
2491                                pright,1,                                      &
2492                             agt_gh_l, ghla_count_recv * agt_size, MPI_BYTE,   &
2493                                pleft, 1,                                      &
2494                             comm2d, status, ierr )
2495!
2496!--       If agents were received, add them to the respective ghost layer cells
2497          IF ( .NOT. ghra_empty_rcv ) THEN
2498             CALL mas_eh_add_ghost_agents_to_gridcell(agt_gh_r)
2499          ENDIF
2500
2501          IF ( .NOT. ghla_empty_rcv ) THEN
2502             CALL mas_eh_add_ghost_agents_to_gridcell(agt_gh_l)
2503          ENDIF
2504
2505          DEALLOCATE( ghla, ghra, agt_gh_l, agt_gh_r )
2506
2507       ENDIF
2508
2509!
2510!--    Transfer of agents from south to north and vice versa
2511       IF ( pdims(2) /= 1 )  THEN
2512!
2513!--       Reset south and north ghost layers
2514          ghsa_count  = 0
2515          ghna_count  = 0
2516!
2517!--       First calculate the storage necessary for sending
2518!--       and receiving the data.
2519          ghsa_count = SUM(agt_count(nys:nys+2,nxlg:nxrg))
2520          ghna_count = SUM(agt_count(nyn-2:nyn,nxlg:nxrg))
2521!
2522!--       No cyclic boundaries for agents
2523          IF ( nys == 0 .OR. ghsa_count == 0 ) THEN
2524             ghsa_count = 1
2525          ELSE
2526             ghsa_empty = .FALSE.
2527          ENDIF
2528          IF ( nyn == ny .OR. ghna_count == 0 ) THEN
2529             ghna_count = 1
2530          ELSE
2531             ghna_empty = .FALSE.
2532          ENDIF
2533          ALLOCATE( ghsa(1:ghsa_count), ghna(1:ghna_count) )
2534          ghsa = zero_agent
2535          ghna = zero_agent
2536!
2537!--       Get all agents that will be sent south into one array
2538          ghsa_count = 0
2539          IF ( nys /= 0 ) THEN
2540             DO ip = nxlg, nxrg
2541                DO jp = nys, nys+2
2542
2543                   number_of_agents = agt_count(jp,ip)
2544                   IF ( number_of_agents <= 0 )  CYCLE
2545                   ghsa(ghsa_count+1:ghsa_count+number_of_agents)              &
2546                       = grid_agents(jp,ip)%agents(1:number_of_agents)
2547                   ghsa_count = ghsa_count + number_of_agents
2548
2549                ENDDO
2550             ENDDO
2551          ENDIF
2552          IF ( ghsa_count == 0 )  ghsa_count = 1
2553!
2554!--       Get all agents that will be sent north into one array
2555          ghna_count = 0
2556          IF ( nyn /= ny ) THEN
2557             DO ip = nxlg, nxrg
2558                DO jp = nyn-2, nyn
2559
2560                   number_of_agents = agt_count(jp,ip)
2561                   IF ( number_of_agents <= 0 )  CYCLE
2562                   ghna(ghna_count+1:ghna_count+number_of_agents)              &
2563                       = grid_agents(jp,ip)%agents(1:number_of_agents)
2564                   ghna_count = ghna_count + number_of_agents
2565
2566                ENDDO
2567             ENDDO
2568          ENDIF
2569          IF ( ghna_count == 0 ) ghna_count = 1
2570!
2571!--       Send/receive number of agents that
2572!--       will be transferred to/from south/north neighbor
2573          CALL MPI_SENDRECV( ghsa_count, 1, MPI_INTEGER, psouth, 0,            &
2574                             ghna_count_recv,   1, MPI_INTEGER, pnorth, 0,     &
2575                             comm2d, status, ierr )
2576          ALLOCATE ( agt_gh_n(1:ghna_count_recv) )
2577!
2578!--       Send/receive number of agents that
2579!--       will be transferred to/from north/south neighbor
2580          CALL MPI_SENDRECV( ghna_count, 1, MPI_INTEGER, pnorth, 0,            &
2581                             ghsa_count_recv,   1, MPI_INTEGER, psouth, 0,     &
2582                             comm2d, status, ierr )
2583!
2584!--       Send/receive flag that indicates if there are actually any agents
2585!--       in ghost  layer
2586          CALL MPI_SENDRECV( ghsa_empty,     1, MPI_LOGICAL, psouth, 1,        &
2587                             ghna_empty_rcv, 1, MPI_LOGICAL, pnorth, 1,        &
2588                             comm2d, status, ierr )
2589          CALL MPI_SENDRECV( ghna_empty,     1, MPI_LOGICAL, pnorth, 1,        &
2590                             ghsa_empty_rcv, 1, MPI_LOGICAL, psouth, 1,        &
2591                             comm2d, status, ierr )
2592
2593
2594          ALLOCATE ( agt_gh_s(1:ghsa_count_recv) )
2595!
2596!--       Get bit size of one agent
2597          agt_size = STORAGE_SIZE(zero_agent)/8
2598!
2599!--       Send/receive agents to/from south/north neighbor
2600          CALL MPI_SENDRECV( ghsa,     ghsa_count      * agt_size, MPI_BYTE,   &
2601                                psouth,1,                                      &
2602                             agt_gh_n, ghna_count_recv * agt_size, MPI_BYTE,   &
2603                                pnorth,1,                                      &
2604                             comm2d, status, ierr )
2605!
2606!--       Send/receive agents to/from south/north neighbor
2607          CALL MPI_SENDRECV( ghna,     ghna_count      * agt_size, MPI_BYTE,   &
2608                                pnorth,1,                                      &
2609                             agt_gh_s, ghsa_count_recv * agt_size, MPI_BYTE,   &
2610                                psouth,1,                                      &
2611                             comm2d, status, ierr )
2612!
2613!--       If agents were received, add them to the respective ghost layer cells
2614          IF ( .NOT. ghna_empty_rcv ) THEN
2615             CALL mas_eh_add_ghost_agents_to_gridcell(agt_gh_n)
2616          ENDIF
2617
2618          IF ( .NOT. ghsa_empty_rcv ) THEN
2619             CALL mas_eh_add_ghost_agents_to_gridcell(agt_gh_s)
2620          ENDIF
2621
2622          DEALLOCATE( ghna, ghsa, agt_gh_n, agt_gh_s )
2623
2624       ENDIF
2625
2626#endif
2627
2628    END SUBROUTINE mas_eh_ghost_exchange
2629
2630!------------------------------------------------------------------------------!
2631! Description:
2632! ------------
2633!> If an agent moves from one grid cell to another (on the current
2634!> processor!), this subroutine moves the corresponding element from the
2635!> agent array of the old grid cell to the agent array of the new grid
2636!> cell.
2637!------------------------------------------------------------------------------!
2638    SUBROUTINE mas_eh_move_agent
2639
2640       IMPLICIT NONE
2641
2642       INTEGER(iwp) ::  i              !< grid index (x) of agent position
2643       INTEGER(iwp) ::  ip             !< index variable along x
2644       INTEGER(iwp) ::  j              !< grid index (y) of agent position
2645       INTEGER(iwp) ::  jp             !< index variable along y
2646       INTEGER(iwp) ::  n              !< index variable for agent array
2647       INTEGER(iwp) ::  na_before_move !< number of agents per grid box before moving
2648       INTEGER(iwp) ::  aindex         !< dummy argument for number of new agent per grid box
2649
2650       TYPE(agent_type), DIMENSION(:), POINTER ::  agents_before_move !< agents before moving
2651
2652       DO  ip = nxl, nxr
2653          DO  jp = nys, nyn
2654
2655                na_before_move = agt_count(jp,ip)
2656                IF ( na_before_move <= 0 )  CYCLE
2657                agents_before_move => grid_agents(jp,ip)%agents(1:na_before_move)
2658
2659                DO  n = 1, na_before_move
2660                   i = agents_before_move(n)%x * ddx
2661                   j = agents_before_move(n)%y * ddy
2662
2663!--                For mas_eh_exchange_horiz to work properly agents need to be
2664!--                moved to the outermost gridboxes of the respective processor.
2665!--                If the agent index is inside the processor the following
2666!--                lines will not change the index
2667                   i = MIN ( i , nxr )
2668                   i = MAX ( i , nxl )
2669                   j = MIN ( j , nyn )
2670                   j = MAX ( j , nys )
2671
2672!
2673!--                Check if agent has moved to another grid cell.
2674                   IF ( i /= ip  .OR.  j /= jp )  THEN
2675!
2676!--                   If the agent stays on the same processor, the agent
2677!--                   will be added to the agent array of the new processor.
2678                      number_of_agents = agt_count(j,i)
2679                      agents => grid_agents(j,i)%agents(1:number_of_agents)
2680
2681                      aindex = number_of_agents+1
2682                      IF (  aindex > SIZE(grid_agents(j,i)%agents)  )     &
2683                      THEN
2684                         CALL mas_eh_realloc_agents_array(i,j)
2685                      ENDIF
2686
2687                      grid_agents(j,i)%agents(aindex) = agents_before_move(n)
2688                      agt_count(j,i) = aindex
2689
2690                      agents_before_move(n)%agent_mask = .FALSE.
2691                   ENDIF
2692                ENDDO
2693
2694          ENDDO
2695       ENDDO
2696
2697       RETURN
2698
2699    END SUBROUTINE mas_eh_move_agent
2700
2701!------------------------------------------------------------------------------!
2702! Description:
2703! ------------
2704!> If the allocated memory for the agent array do not suffice to add arriving
2705!> agents from neighbour grid cells, this subrouting reallocates the
2706!> agent array to assure enough memory is available.
2707!------------------------------------------------------------------------------!
2708    SUBROUTINE mas_eh_realloc_agents_array (i,j,size_in)
2709
2710       IMPLICIT NONE
2711
2712       INTEGER(iwp) :: old_size  !< old array size
2713       INTEGER(iwp) :: new_size  !< new array size
2714
2715       INTEGER(iwp), INTENT(in) ::  i  !< grid index (y)
2716       INTEGER(iwp), INTENT(in) ::  j  !< grid index (y)
2717
2718       INTEGER(iwp), INTENT(in), OPTIONAL ::  size_in  !< size of input array
2719
2720       TYPE(agent_type), DIMENSION(10) :: tmp_agents_s !< temporary static agent array
2721
2722       TYPE(agent_type), DIMENSION(:), ALLOCATABLE :: tmp_agents_d !< temporary dynamic agent array
2723
2724       old_size = SIZE(grid_agents(j,i)%agents)
2725
2726       IF ( PRESENT(size_in) )   THEN
2727          new_size = size_in
2728       ELSE
2729          new_size = old_size * ( 1.0_wp + alloc_factor_mas / 100.0_wp )
2730       ENDIF
2731
2732       new_size = MAX( new_size, min_nr_agent, old_size + 1 )
2733
2734       IF ( old_size <= 10 )  THEN
2735
2736          tmp_agents_s(1:old_size) = grid_agents(j,i)%agents(1:old_size)
2737
2738          DEALLOCATE(grid_agents(j,i)%agents)
2739          ALLOCATE(grid_agents(j,i)%agents(new_size))
2740
2741          grid_agents(j,i)%agents(1:old_size)         = tmp_agents_s(1:old_size)
2742          grid_agents(j,i)%agents(old_size+1:new_size) = zero_agent
2743
2744       ELSE
2745
2746          ALLOCATE(tmp_agents_d(new_size))
2747          tmp_agents_d(1:old_size) = grid_agents(j,i)%agents
2748
2749          DEALLOCATE(grid_agents(j,i)%agents)
2750          ALLOCATE(grid_agents(j,i)%agents(new_size))
2751
2752          grid_agents(j,i)%agents(1:old_size)         = tmp_agents_d(1:old_size)
2753          grid_agents(j,i)%agents(old_size+1:new_size) = zero_agent
2754
2755          DEALLOCATE(tmp_agents_d)
2756
2757       ENDIF
2758       agents => grid_agents(j,i)%agents(1:number_of_agents)
2759
2760       RETURN
2761    END SUBROUTINE mas_eh_realloc_agents_array
2762
2763!------------------------------------------------------------------------------!
2764! Description:
2765! ------------
2766!> Inquires prognostic model quantities at the position of each agent and
2767!> stores them in that agent for later output
2768!------------------------------------------------------------------------------!
2769    SUBROUTINE mas_get_prognostic_quantities
2770
2771       USE arrays_3d,                                                          &
2772           ONLY:  u, v, pt, exner
2773
2774!       USE chemistry_model_mod,                                                &
2775!           ONLY:  chem_species
2776
2777!       USE control_parameters,                                                 &
2778!              ONLY:  air_chemistry
2779
2780       IMPLICIT NONE
2781
2782       INTEGER(iwp) ::  i_offset  !<  index offset for windspeed measurement
2783       INTEGER(iwp) ::  il        !<  x-index
2784       INTEGER(iwp) ::  is        !<  subgrid box counter
2785       INTEGER(iwp) ::  j_offset  !<  index offset for windspeed measurement
2786       INTEGER(iwp) ::  jl        !<  y-index
2787       INTEGER(iwp) ::  kl        !<  z-index
2788       INTEGER(iwp) ::  nl        !<  agent counter
2789       INTEGER(iwp) ::  se        !<  subgrid box end index
2790       INTEGER(iwp) ::  si        !<  subgrid box start index
2791
2792       REAL(wp) ::  u_a  !< windspeed at agent position (x)
2793       REAL(wp) ::  v_a  !< windspeed at agent position (y)
2794
2795       DO  il = nxl, nxr
2796          DO  jl = nys, nyn
2797
2798             number_of_agents = agt_count(jl,il)
2799!
2800!--          If grid cell is empty, cycle
2801             IF ( number_of_agents <= 0 ) CYCLE
2802             kl = s_measure_height(jl,il)
2803
2804             agents => grid_agents(jl,il)%agents(1:number_of_agents)
2805!
2806!--          loop over the four subgrid boxes
2807             DO is = 0,3
2808!
2809!--             Set indices
2810                si = grid_agents(jl,il)%start_index(is)
2811                se = grid_agents(jl,il)%end_index(is)
2812                DO nl = si, se
2813!
2814!--                Calculate index offset in x-direction:
2815!--                Left value if wall right of grid box
2816!--                Right value if wall left of grid box
2817!--                Else the one that is closer to the agent
2818                   IF ( BTEST( obstacle_flags( jl, il+1 ), 6 ) ) THEN
2819                      i_offset = 0
2820                   ELSEIF ( BTEST( obstacle_flags( jl, il-1 ), 2 ) ) THEN
2821                      i_offset = 1
2822                   ELSE
2823                      i_offset = MERGE( 0, 1, BTEST(is,1) )
2824                   ENDIF
2825                   u_a = u( kl, jl, il + i_offset )
2826!
2827!--                Calculate index offset in y-direction:
2828!--                South value if wall north of grid box
2829!--                North value if wall south of grid box
2830!--                Else the one that is closer to the agent
2831                   IF ( BTEST( obstacle_flags( jl+1, il ), 4 ) ) THEN
2832                      j_offset = 0
2833                   ELSEIF ( BTEST( obstacle_flags( jl-1, il ), 0 ) ) THEN
2834                      j_offset = 1
2835                   ELSE
2836                      j_offset = MERGE( 0, 1, BTEST(is,0) )
2837                   ENDIF
2838                   v_a = v( kl, jl + j_offset, il )
2839!
2840!--                Calculate windspeed at agent postion
2841                   agents(nl)%windspeed = SQRT(u_a**2 + v_a**2)
2842!
2843!--                Calculate temperature at agent position
2844                   agents(nl)%t = pt(kl,jl,il) * exner(kl)
2845! !
2846! !--                Get PM10 concentration at agent position, if possible
2847!                    IF ( ind_pm10 == -9 ) THEN
2848!                       agents(nl)%pm10 = 0.0_wp
2849!                    ELSE
2850!                       agents(nl)%pm10 = chem_species(ind_pm10)%conc(kl,jl,il)
2851!                    ENDIF
2852! !
2853! !--                Get PM10 concentration at agent position, if possible
2854!                    IF ( ind_pm25 == -9 ) THEN
2855!                       agents(nl)%pm25 = 0.0_wp
2856!                    ELSE
2857!                       agents(nl)%pm25 = chem_species(ind_pm25)%conc(kl,jl,il)
2858!                    ENDIF
2859                ENDDO
2860
2861             ENDDO
2862
2863          ENDDO
2864       ENDDO
2865
2866    END SUBROUTINE mas_get_prognostic_quantities
2867
2868!------------------------------------------------------------------------------!
2869! Description:
2870! ------------
2871!> Adds an item to the priority queue (binary heap) at the correct position
2872!------------------------------------------------------------------------------!
2873    SUBROUTINE mas_heap_insert_item( id, priority )
2874
2875       IMPLICIT NONE
2876
2877       INTEGER(iwp) ::  cur_pos !< current position
2878       INTEGER(iwp) ::  id      !< mesh ID of item
2879
2880       REAL(wp) ::  priority !< item priority
2881
2882       TYPE(heap_item) ::  item !< heap item
2883
2884       item%mesh_id  = id
2885       item%priority = priority
2886!
2887!--    Extend heap, if necessary
2888       IF ( heap_count + 1 > SIZE(queue) ) THEN
2889          CALL mas_heap_extend
2890       ENDIF
2891!
2892!--    Insert item at first unoccupied postion (highest index) of heap
2893       cur_pos = heap_count
2894       queue(cur_pos) = item
2895!
2896!--    Sort while inserted item is not at top of heap
2897       DO WHILE ( cur_pos /= 0 )
2898!
2899!--       If priority < its parent's priority, swap them.
2900!--       Else, sorting is done.
2901          IF ( queue(cur_pos)%priority                                         &
2902              < queue(FLOOR((cur_pos)/2.))%priority )                          &
2903          THEN
2904             item = queue(cur_pos)
2905             queue(cur_pos) = queue(FLOOR((cur_pos)/2.))
2906             queue(FLOOR((cur_pos)/2.)) = item
2907             cur_pos = FLOOR((cur_pos)/2.)
2908          ELSE
2909             EXIT
2910          ENDIF
2911       ENDDO
2912!
2913!--    Item was added to heap, so the heap count increases
2914       heap_count = heap_count + 1
2915
2916    END SUBROUTINE mas_heap_insert_item
2917
2918!------------------------------------------------------------------------------!
2919! Description:
2920! ------------
2921!> Extends the size of the priority queue (binary heap)
2922!------------------------------------------------------------------------------!
2923    SUBROUTINE mas_heap_extend
2924
2925       IMPLICIT NONE
2926
2927       INTEGER(iwp) ::  soh !< size of heap
2928
2929       TYPE(heap_item), DIMENSION(:), ALLOCATABLE ::  dummy_heap !< dummy heap
2930
2931       soh = SIZE(queue)-1
2932       ALLOCATE(dummy_heap(0:soh))
2933       dummy_heap = queue
2934       DEALLOCATE(queue)
2935       ALLOCATE(queue(0:2*soh+1))
2936       queue(0:soh) = dummy_heap(0:soh)
2937
2938    END SUBROUTINE mas_heap_extend
2939
2940!------------------------------------------------------------------------------!
2941! Description:
2942! ------------
2943!> Removes first (smallest) element from the priority queue, reorders the rest
2944!> and returns the ID of the removed mesh point
2945!------------------------------------------------------------------------------!
2946    SUBROUTINE mas_heap_extract_item ( id )
2947
2948       IMPLICIT NONE
2949
2950       INTEGER(iwp) ::  id      !< ID of item extracted item
2951       INTEGER(iwp) ::  child   !< child of item in heap
2952       INTEGER(iwp) ::  cur_pos !< current position of item in heap
2953
2954       TYPE(heap_item) ::  dummy
2955!
2956!--    Get ID of mesh point with lowest priority (extracted item: top of heap)
2957       id = queue(0)%mesh_id
2958!
2959!--    Put last item in heap at first position
2960       queue(0) = queue(heap_count-1)
2961       cur_pos = 0
2962       DO
2963!
2964!--       If current item has no children, sorting is done
2965          IF( 2*cur_pos+1 > heap_count - 1 ) THEN
2966             EXIT
2967!
2968!--       If current item has only one child, check if item and its child are
2969!--       ordered correctly. Else, swap them.
2970          ELSEIF ( 2*cur_pos+2 > heap_count - 1 ) THEN
2971             IF ( queue(cur_pos)%priority > queue(2*cur_pos+1)%priority ) THEN
2972                dummy = queue(cur_pos)
2973                queue(cur_pos) = queue(2*cur_pos+1)
2974                queue(2*cur_pos+1) = dummy
2975                cur_pos = 2*cur_pos+1
2976             ELSE
2977                EXIT
2978             ENDIF
2979          ELSE
2980!
2981!--          determine the smaller child
2982             IF ( queue(2*cur_pos+1)%priority                                  &
2983                 >= queue(2*cur_pos+2)%priority )                              &
2984             THEN
2985                child = 2
2986             ELSE
2987                child = 1
2988             ENDIF
2989!
2990!--          Check if item and its smaller child are ordered falsely. If so,
2991!--          swap them. Else, sorting is done.
2992             IF ( queue(cur_pos)%priority > queue(2*cur_pos+child )%priority ) &
2993             THEN
2994                dummy = queue(cur_pos)
2995                queue(cur_pos) = queue(2*cur_pos+child)
2996                queue(2*cur_pos+child) = dummy
2997                cur_pos = 2*cur_pos+child
2998             ELSE
2999                EXIT
3000             ENDIF
3001          ENDIF
3002       ENDDO
3003!
3004!--    Top item was removed from heap, thus, heap_cout decreases by one
3005       heap_count = heap_count-1
3006
3007    END SUBROUTINE mas_heap_extract_item
3008
3009!------------------------------------------------------------------------------!
3010! Description:
3011! ------------
3012!> Initialization of Multi Agent System
3013!------------------------------------------------------------------------------!
3014    SUBROUTINE mas_init
3015
3016!       USE chem_gasphase_mod,                                                  &
3017!           ONLY:  nspec
3018
3019!       USE chemistry_model_mod,                                                &
3020!           ONLY:  chem_species
3021
3022       USE control_parameters,                                                 &
3023           ONLY:  coupling_char, initializing_actions, io_blocks, io_group
3024
3025       USE surface_mod,                                                        &
3026           ONLY:  get_topography_top_index, get_topography_top_index_ji
3027
3028       USE arrays_3d,                                                          &
3029           ONLY:  zu, zw
3030
3031       USE indices,                                                            &
3032           ONLY:  nzt 
3033
3034       IMPLICIT NONE
3035
3036       INTEGER(iwp) ::  i             !< grid cell (x)
3037       INTEGER(iwp) ::  ii            !< io-block counter
3038       INTEGER(iwp) ::  il            !< io-block counter
3039       INTEGER(iwp) ::  jl            !< io-block counter
3040       INTEGER(iwp) ::  kl            !< io-block counter
3041       INTEGER(iwp) ::  kdum            !< io-block counter
3042       INTEGER(iwp) ::  locdum            !< io-block counter
3043       INTEGER(iwp) ::  j             !< grid cell (y)
3044       INTEGER(iwp) ::  size_of_mesh  !< temporary value for read
3045       INTEGER(iwp) ::  size_of_pols  !< temporary value for read
3046       INTEGER(iwp) ::  ioerr         !< IOSTAT flag for IO-commands ( 0 = no error )
3047
3048       LOGICAL ::  navigation_data_present  !< Flag: check for input file
3049
3050       REAL(wp) ::  zdum  !< dummy for measurement height
3051       REAL(wp) ::  avg_agt_height = 1.8_wp
3052
3053
3054!
3055!--    Check the number of agent groups.
3056       IF ( number_of_agent_groups > max_number_of_agent_groups )  THEN
3057          WRITE( message_string, * ) 'max_number_of_agent_groups =',      &
3058                                     max_number_of_agent_groups ,         &
3059                                     '&number_of_agent_groups reset to ', &
3060                                     max_number_of_agent_groups
3061          CALL message( 'mas_init', 'PA0072', 0, 1, 0, 6, 0 )
3062          number_of_agent_groups = max_number_of_agent_groups
3063       ENDIF
3064
3065!
3066!--    Set some parameters
3067       d_sigma_rep_agent = 1.0_wp/sigma_rep_agent
3068       d_sigma_rep_wall  = 1.0_wp/sigma_rep_wall
3069       d_tau_accel_agent = 1.0_wp/tau_accel_agent
3070       IF ( dt_agent /= 999.0_wp ) THEN
3071          agent_own_timestep = .TRUE.
3072       ENDIF
3073
3074!
3075!--    Get index of first grid box above topography
3076       ALLOCATE( top_top_s(nysg:nyng,nxlg:nxrg),                               &
3077                 top_top_w(nysg:nyng,nxlg:nxrg),                               &
3078                 s_measure_height(nys:nyn,nxl:nxr) )
3079!
3080!--    Get first index above topography for scalar grid and last index in
3081!--    topography for z-component of wind
3082       DO il = nxlg, nxrg
3083          DO jl = nysg, nyng
3084             top_top_s(jl,il) = get_topography_top_index_ji(jl,il,'s') + 1
3085             top_top_w(jl,il) = get_topography_top_index_ji(jl,il,'w')
3086          ENDDO
3087       ENDDO
3088!
3089!--    Create 2D array containing the index at which measurements are done by
3090!--    agents. The height of this measurement is given by avg_agt_height.
3091       DO il = nxl, nxr
3092          DO jl = nys, nyn
3093
3094             kdum = top_top_w(jl,il)
3095             zdum = zw(kdum)
3096             zdum = zdum + avg_agt_height
3097             locdum = 0
3098!
3099!--          Locate minimum distance from u-grid to measurement height (zdum)
3100             DO kl = 1, nzt
3101                IF ( ABS(zu(kl)-zdum) < ABS(zu(locdum)-zdum) ) locdum = kl
3102             ENDDO
3103             s_measure_height(jl,il) = locdum
3104
3105          ENDDO
3106       ENDDO
3107! !
3108! !--    Get indices of PM10 and PM2.5 species, if active
3109!        IF ( air_chemistry ) THEN
3110!           DO il = 1, nspec
3111! print*,chem_species(il)%name
3112! !              IF ( spec_name(1:4) == 'PM10' ) THEN 
3113! !                 ind_pm10 = il
3114! !              ELSEIF ( spec_name(1:4) == 'PM25' ) THEN
3115! !                 ind_pm25 = il
3116! !              ENDIF
3117!
3118!           ENDDO
3119!        ENDIF
3120! stop
3121       CALL mas_create_obstacle_flags
3122
3123!
3124!--    Set default start positions, if necessary
3125       IF ( asl(1) == 9999999.9_wp )  asl(1) = 0.0_wp
3126       IF ( asr(1) == 9999999.9_wp )  asr(1) = ( nx + 1 ) * dx
3127       IF ( ass(1) == 9999999.9_wp )  ass(1) = 0.0_wp
3128       IF ( asn(1) == 9999999.9_wp )  asn(1) = ( ny + 1 ) * dy
3129       IF ( adx(1) == 9999999.9_wp .OR. adx(1) == 0.0_wp ) adx(1) = dx
3130       IF ( ady(1) == 9999999.9_wp .OR. ady(1) == 0.0_wp ) ady(1) = dy
3131
3132       DO  j = 2, number_of_agent_groups
3133          IF ( asl(j) == 9999999.9_wp )  asl(j) = asl(j-1)
3134          IF ( asr(j) == 9999999.9_wp )  asr(j) = asr(j-1)
3135          IF ( ass(j) == 9999999.9_wp )  ass(j) = ass(j-1)
3136          IF ( asn(j) == 9999999.9_wp )  asn(j) = asn(j-1)
3137          IF ( adx(j) == 9999999.9_wp .OR. adx(j) == 0.0_wp ) adx(j) = adx(j-1)
3138          IF ( ady(j) == 9999999.9_wp .OR. ady(j) == 0.0_wp ) ady(j) = ady(j-1)
3139       ENDDO
3140
3141!
3142!--    Check boundary condition and set internal variables
3143       SELECT CASE ( bc_mas_lr )
3144
3145          CASE ( 'cyclic' )
3146             ibc_mas_lr = 0
3147
3148          CASE ( 'absorb' )
3149             ibc_mas_lr = 1
3150
3151          CASE DEFAULT
3152             WRITE( message_string, * ) 'unknown boundary condition ',         &
3153                                        'bc_mas_lr = "', TRIM( bc_mas_lr ), '"'
3154             CALL message( 'mas_init', 'PA0073', 1, 2, 0, 6, 0 )
3155
3156       END SELECT
3157       SELECT CASE ( bc_mas_ns )
3158
3159          CASE ( 'cyclic' )
3160             ibc_mas_ns = 0
3161
3162          CASE ( 'absorb' )
3163             ibc_mas_ns = 1
3164
3165          CASE DEFAULT
3166             WRITE( message_string, * ) 'unknown boundary condition ',         &
3167                                        'bc_mas_ns = "', TRIM( bc_mas_ns ), '"'
3168             CALL message( 'mas_init', 'PA0074', 1, 2, 0, 6, 0 )
3169
3170       END SELECT
3171
3172!
3173!--    For the first model run of a possible job chain initialize the
3174!--    agents, otherwise read the agent data from restart file.
3175       IF ( TRIM( initializing_actions ) == 'read_restart_data'                &
3176            .AND.  read_agents_from_restartfile )  THEN
3177
3178!           CALL mas_read_restart_file
3179
3180       ELSE
3181!
3182!--       Read preprocessed data of navigation mesh and building polygons
3183!--       for agent pathfinding
3184          DO ii = 0, io_blocks-1
3185             IF ( ii == io_group )  THEN
3186!
3187!--             Check for naviation input file and open it
3188                INQUIRE( FILE='NAVIGATION_DATA' // TRIM( coupling_char ), EXIST=navigation_data_present )
3189                IF ( .NOT. navigation_data_present )  THEN
3190                   message_string = 'Input file NAVIGATION_DATA' //                &
3191                                     TRIM( coupling_char ) // ' for MAS missing. ' // &
3192                                     '&Please run agent_preprocessing before the job to create it.'
3193                   CALL message( 'mas_init', 'PA0525', 1, 2, 0, 6, 0 )
3194                ENDIF
3195                OPEN ( 119, FILE='NAVIGATION_DATA'//TRIM( coupling_char ),     &
3196                            FORM='UNFORMATTED', IOSTAT=ioerr )
3197!
3198!--             Read mesh data
3199                READ(119) size_of_mesh
3200                ALLOCATE( mesh(1:size_of_mesh))
3201                DO i = 1, size_of_mesh
3202                   READ(119) mesh(i)%polygon_id, mesh(i)%vertex_id,            &
3203                             mesh(i)%noc, mesh(i)%origin_id,                   &
3204                             mesh(i)%cost_so_far, mesh(i)%x,                   &
3205                             mesh(i)%y, mesh(i)%x_s, mesh(i)%y_s
3206                   ALLOCATE( mesh(i)%connected_vertices(1:mesh(i)%noc),        &
3207                             mesh(i)%distance_to_vertex(1:mesh(i)%noc) )
3208                   DO j = 1, mesh(i)%noc
3209                      READ(119) mesh(i)%connected_vertices(j),                 &
3210                                mesh(i)%distance_to_vertex(j)
3211                   ENDDO
3212                ENDDO
3213!
3214!--             Read polygon data
3215                READ(119) size_of_pols
3216                ALLOCATE( polygons(1:size_of_pols) )
3217                DO i = 1, size_of_pols
3218                   READ(119) polygons(i)%nov
3219                   ALLOCATE( polygons(i)%vertices(0:polygons(i)%nov+1) )
3220                   DO j = 0, polygons(i)%nov+1
3221                      READ(119) polygons(i)%vertices(j)%delete,                &
3222                                polygons(i)%vertices(j)%x,                     &
3223                                polygons(i)%vertices(j)%y
3224                   ENDDO
3225                ENDDO
3226                CLOSE(119)
3227
3228             ENDIF
3229#if defined( __parallel ) && ! defined ( __check )
3230             CALL MPI_BARRIER( comm2d, ierr )
3231#endif
3232          ENDDO
3233
3234!
3235!--       Allocate agent arrays and set attributes of the initial set of
3236!--       agents, which can be also periodically released at later times.
3237          ALLOCATE( agt_count  (nysg:nyng,nxlg:nxrg),                          &
3238                    grid_agents(nysg:nyng,nxlg:nxrg) )
3239!
3240!--       Allocate dummy arrays for pathfinding
3241          ALLOCATE( dummy_path_x(0:agt_path_size),                 &
3242                    dummy_path_y(0:agt_path_size) )
3243
3244          number_of_agents = 0
3245          sort_count_mas   = 0
3246          agt_count        = 0
3247
3248!
3249!--       initialize counter for agent IDs
3250          grid_agents%id_counter = 1
3251
3252!
3253!--       Initialize all agents with dummy values (otherwise errors may
3254!--       occur within restart runs). The reason for this is still not clear
3255!--       and may be presumably caused by errors in the respective user-interface.
3256          zero_agent%agent_mask = .FALSE.
3257          zero_agent%block_nr      = -1
3258          zero_agent%group         = 0
3259          zero_agent%id            = 0_idp
3260          zero_agent%path_counter  = agt_path_size
3261          zero_agent%age           = 0.0_wp
3262          zero_agent%age_m         = 0.0_wp
3263          zero_agent%dt_sum        = 0.0_wp
3264          zero_agent%clo           = 0.0_wp
3265          zero_agent%energy_storage= 0.0_wp
3266          zero_agent%force_x       = 0.0_wp
3267          zero_agent%force_y       = 0.0_wp
3268          zero_agent%origin_x      = 0.0_wp
3269          zero_agent%origin_y      = 0.0_wp
3270          zero_agent%speed_abs     = 0.0_wp
3271          zero_agent%speed_e_x     = 0.0_wp
3272          zero_agent%speed_e_y     = 0.0_wp
3273          zero_agent%speed_des     = random_normal(desired_speed, des_sp_sig)
3274          zero_agent%speed_x       = 0.0_wp
3275          zero_agent%speed_y       = 0.0_wp
3276          zero_agent%ipt           = 0.0_wp
3277          zero_agent%x             = 0.0_wp
3278          zero_agent%y             = 0.0_wp
3279          zero_agent%path_x        = 0.0_wp
3280          zero_agent%path_y        = 0.0_wp
3281          zero_agent%t_x           = 0.0_wp
3282          zero_agent%t_y           = 0.0_wp
3283
3284!
3285!--    Set a seed value for the random number generator to be exclusively
3286!--    used for the agent code. The generated random numbers should be
3287!--    different on the different PEs.
3288          iran_agent = iran_agent + myid
3289
3290          CALL mas_create_agent (PHASE_INIT)
3291
3292       ENDIF
3293
3294!
3295!--    To avoid programm abort, assign agents array to the local version of
3296!--    first grid cell
3297       number_of_agents = agt_count(nys,nxl)
3298       agents => grid_agents(nys,nxl)%agents(1:number_of_agents)
3299
3300    END SUBROUTINE mas_init
3301
3302!------------------------------------------------------------------------------!
3303! Description:
3304! ------------
3305!> Output of informative message about maximum agent number
3306!------------------------------------------------------------------------------!
3307    SUBROUTINE mas_last_actions
3308
3309       USE control_parameters,                                                 &
3310           ONLY:  message_string
3311
3312       IMPLICIT NONE
3313
3314       WRITE(message_string,'(A,I8,A)')                                        &
3315                         'The maximumn number of agents during this run was',  &
3316                         maximum_number_of_agents,                             &
3317                         '&Consider adjusting the INPUT parameter'//           &
3318                         '&dim_size_agtnum_manual accordingly for the next run.'
3319
3320       CALL message( 'mas_data_output_agents', 'PA0457', 0, 0, 0, 6, 0 )
3321
3322    END SUBROUTINE mas_last_actions
3323
3324!------------------------------------------------------------------------------!
3325! Description:
3326! ------------
3327!> Finds the shortest path from a start position to a target position using the
3328!> A*-algorithm
3329!------------------------------------------------------------------------------!
3330    SUBROUTINE mas_nav_a_star( start_x, start_y, target_x, target_y, nsteps )
3331
3332       IMPLICIT NONE
3333
3334       LOGICAL ::  target_reached !< flag
3335
3336       INTEGER(iwp) ::  cur_node     !< current node of binary heap
3337       INTEGER(iwp) ::  il           !< counter (x)
3338       INTEGER(iwp) ::  neigh_node   !< neighbor node
3339       INTEGER(iwp) ::  node_counter !< binary heap node counter
3340       INTEGER(iwp) ::  path_ag      !< index of agent path
3341       INTEGER(iwp) ::  som          !< size of mesh
3342       INTEGER(iwp) ::  steps        !< steps along the path
3343       INTEGER(iwp) ::  nsteps        !< number of steps
3344
3345       REAL(wp) ::  start_x      !< x-coordinate agent
3346       REAL(wp) ::  start_y      !< y-coordinate agent
3347       REAL(wp) ::  new_cost     !< updated cost to reach node
3348       REAL(wp) ::  new_priority !< priority of node to be added to queue
3349       REAL(wp) ::  rn_gate      !< random number for corner gate
3350       REAL(wp) ::  target_x     !< x-coordinate target
3351       REAL(wp) ::  target_y     !< y-coordinate target
3352!
3353!--    Coordinate Type
3354       TYPE coord
3355          REAL(wp) ::  x   !< x-coordinate
3356          REAL(wp) ::  x_s !< x-coordinate (shifted)
3357          REAL(wp) ::  y   !< y-coordinate
3358          REAL(wp) ::  y_s !< y-coordinate (shifted)
3359       END TYPE coord
3360
3361       TYPE(coord), DIMENSION(:), ALLOCATABLE, TARGET ::  path     !< path array
3362       TYPE(coord), DIMENSION(:), ALLOCATABLE, TARGET ::  tmp_path !< temporary path for resizing
3363
3364       node_counter = 0
3365!
3366!--    Create temporary navigation mesh including agent and target positions
3367       CALL mas_nav_create_tmp_mesh( start_x, start_y, target_x, target_y, som )
3368       tmp_mesh(som)%cost_so_far = 0.0_wp
3369!
3370!--    Initialize priority queue
3371       heap_count = 0_iwp
3372       ALLOCATE(queue(0:100))
3373       target_reached = .FALSE.
3374!
3375!--    Add starting point (agent position) to frontier (the frontier consists
3376!--    of all the nodes that are to be visited. The node with the smallest
3377!--    priority will be visited first. The priority consists of the distance
3378!--    from the start node to this node plus a minimal guess (direct distance)
3379!--    from this node to the goal). For the starting node, the priority is set
3380!--    to 0, as it's the only node thus far
3381       CALL mas_heap_insert_item(som,0.0_wp)
3382       cur_node = som
3383       DO WHILE ( heap_count > 0 )
3384!
3385!--       Step one: Pick lowest priority item from queue
3386          node_counter = node_counter + 1
3387          CALL mas_heap_extract_item(cur_node)
3388!
3389!--       Node 0 is the goal node
3390          IF ( cur_node == 0 ) THEN
3391             EXIT
3392          ENDIF
3393!
3394!--       Loop over all of cur_node's neighbors
3395          DO il = 1, tmp_mesh(cur_node)%noc
3396             neigh_node = tmp_mesh(cur_node)%connected_vertices(il)
3397!
3398!--          Check, if the way from the start node to this neigh_node via
3399!--          cur_node is shorter than the previously found shortest path to it.
3400!--          If so, replace said cost and add neigh_node to the frontier.
3401!--          cost_so_far is initialized as 1.d12 so that all found distances
3402!--          should be smaller.
3403             new_cost   = tmp_mesh(cur_node)%cost_so_far                       &
3404                         + tmp_mesh(cur_node)%distance_to_vertex(il)
3405             IF ( new_cost < tmp_mesh(neigh_node)%cost_so_far ) THEN
3406                tmp_mesh(neigh_node)%cost_so_far = new_cost
3407                tmp_mesh(neigh_node)%origin_id   = cur_node
3408!
3409!--             Priority in the queue is cost_so_far + heuristic to goal
3410                new_priority = new_cost                                        &
3411                              + heuristic(tmp_mesh(neigh_node)%x,              &
3412                                tmp_mesh(neigh_node)%y, tmp_mesh(0)%x,         &
3413                                tmp_mesh(0)%y)
3414                CALL mas_heap_insert_item(neigh_node,new_priority)
3415             ENDIF
3416          ENDDO
3417       ENDDO
3418!
3419!--    Add nodes to a path array. To do this, we must backtrack from the target
3420!--    node to its origin to its origin and so on until an node is reached that
3421!--    has no origin (%origin_id == -1). This is the starting node.
3422       DEALLOCATE(queue)
3423       cur_node = 0
3424       steps = 0
3425       ALLOCATE(path(1:100))
3426       DO WHILE ( cur_node /= -1 )
3427          steps = steps + 1
3428!
3429!--       Resize path array if necessary
3430          IF ( steps > SIZE(path) ) THEN
3431             ALLOCATE(tmp_path(1:steps-1))
3432             tmp_path(1:steps-1) = path(1:steps-1)
3433             DEALLOCATE(path)
3434             ALLOCATE(path(1:2*(steps-1)))
3435             path(1:steps-1) = tmp_path(1:steps-1)
3436             DEALLOCATE(tmp_path)
3437          ENDIF
3438          path(steps)%x = tmp_mesh(cur_node)%x
3439          path(steps)%y = tmp_mesh(cur_node)%y
3440          path(steps)%x_s = tmp_mesh(cur_node)%x_s
3441          path(steps)%y_s = tmp_mesh(cur_node)%y_s
3442          cur_node = tmp_mesh(cur_node)%origin_id
3443       ENDDO
3444!
3445!--    Add calculated intermittent targets to the path until either the
3446!--    target or the maximum number of intermittent targets is reached.
3447!--    Ignore starting point (reduce index by one), it is agent position.
3448       dummy_path_x = -1
3449       dummy_path_y = -1
3450       path_ag = 1
3451       steps = steps - 1
3452       nsteps = 0
3453       DO WHILE( steps > 0 .AND. path_ag <= agt_path_size )
3454!
3455!--       Each target point is randomly chosen along a line target along the
3456!--       bisector of the building corner that starts at corner_gate_start
3457!--       and has a width of corner_gate_width. This is to avoid clustering
3458!--       when opposing agent groups try to reach the same corner target.
3459          rn_gate = random_function(iran_agent) * corner_gate_width            &
3460                                                + corner_gate_start
3461          dummy_path_x(path_ag) = path(steps)%x + rn_gate                      &
3462                         * (path(steps)%x_s - path(steps)%x)
3463          dummy_path_y(path_ag) = path(steps)%y + rn_gate                      &
3464                         * (path(steps)%y_s - path(steps)%y)
3465          steps = steps - 1
3466          path_ag = path_ag + 1
3467          nsteps = nsteps + 1
3468       ENDDO
3469!
3470!--    Set current intermittent target of this agent
3471       DEALLOCATE(tmp_mesh, path)
3472
3473    END SUBROUTINE mas_nav_a_star
3474
3475!------------------------------------------------------------------------------!
3476! Description:
3477! ------------
3478!> Adds a connection between two points of the navigation mesh
3479!> (one-way: in_mp1 to in_mp2)
3480!------------------------------------------------------------------------------!
3481    SUBROUTINE mas_nav_add_connection ( in_mp1, id2, in_mp2 )
3482
3483       IMPLICIT NONE
3484
3485       LOGICAL ::  connection_established  !< Flag to indicate if connection has already been established
3486
3487       INTEGER(iwp) ::  id2  !< ID of in_mp2
3488       INTEGER(iwp) ::  il   !< local counter
3489       INTEGER(iwp) ::  noc1 !< number of connections in in_mp1
3490
3491       INTEGER, DIMENSION(:), ALLOCATABLE ::  dum_cv !< dummy array for connected_vertices
3492
3493       REAL(wp) ::  dist  !< Distance between the two points
3494
3495       REAL(wp), DIMENSION(:), ALLOCATABLE ::  dum_dtv
3496
3497       TYPE(mesh_point) ::  in_mp1  !< mesh point that gets a new connection
3498       TYPE(mesh_point) ::  in_mp2  !< mesh point in_mp1 will be connected to
3499
3500       connection_established = .FALSE.
3501!
3502!--    Check if connection has already been established
3503       noc1 = SIZE(in_mp1%connected_vertices)
3504       DO il = 1, in_mp1%noc
3505          IF ( in_mp1%connected_vertices(il) == id2 ) THEN
3506             connection_established = .TRUE.
3507             EXIT
3508          ENDIF
3509       ENDDO
3510
3511       IF ( .NOT. connection_established ) THEN
3512!
3513!--       Resize arrays, if necessary
3514          IF ( in_mp1%noc >= noc1 ) THEN
3515             ALLOCATE( dum_cv(1:noc1),dum_dtv(1:noc1) )
3516             dum_cv  = in_mp1%connected_vertices
3517             dum_dtv = in_mp1%distance_to_vertex
3518             DEALLOCATE( in_mp1%connected_vertices, in_mp1%distance_to_vertex )
3519             ALLOCATE( in_mp1%connected_vertices(1:2*noc1),                    &
3520                       in_mp1%distance_to_vertex(1:2*noc1) )
3521             in_mp1%connected_vertices         = -999
3522             in_mp1%distance_to_vertex         = -999.
3523             in_mp1%connected_vertices(1:noc1) = dum_cv
3524             in_mp1%distance_to_vertex(1:noc1) = dum_dtv
3525          ENDIF
3526
3527!
3528!--       Add connection
3529          in_mp1%noc = in_mp1%noc+1
3530          dist = SQRT( (in_mp1%x - in_mp2%x)**2 + (in_mp1%y - in_mp2%y)**2 )
3531          in_mp1%connected_vertices(in_mp1%noc) = id2
3532          in_mp1%distance_to_vertex(in_mp1%noc) = dist
3533       ENDIF
3534
3535    END SUBROUTINE mas_nav_add_connection
3536
3537!------------------------------------------------------------------------------!
3538! Description:
3539! ------------
3540!> Adds a vertex (curren position of agent or target) to the existing tmp_mesh
3541!------------------------------------------------------------------------------!
3542    SUBROUTINE mas_nav_add_vertex_to_mesh ( in_mp, in_id )
3543
3544       IMPLICIT NONE
3545
3546       LOGICAL ::  intersection_found !< flag
3547
3548       INTEGER(iwp) ::  jl    !< mesh point counter
3549       INTEGER(iwp) ::  pl    !< polygon counter
3550       INTEGER(iwp) ::  vl    !< vertex counter
3551       INTEGER(iwp) ::  pid_t !< polygon id of tested mesh point
3552       INTEGER(iwp) ::  vid_t !< vertex id of tested mesh point
3553       INTEGER(iwp) ::  in_id !< vertex id of tested mesh point
3554
3555       REAL(wp) ::  v1x !< x-coordinate of test vertex 1 for intersection test
3556       REAL(wp) ::  v1y !< y-coordinate of test vertex 1 for intersection test
3557       REAL(wp) ::  v2x !< x-coordinate of test vertex 2 for intersection test
3558       REAL(wp) ::  v2y !< y-coordinate of test vertex 2 for intersection test
3559       REAL(wp) ::  x   !< x-coordinate of current mesh point
3560       REAL(wp) ::  x_t !< x-coordinate of tested mesh point
3561       REAL(wp) ::  y   !< y-coordinate of current mesh point
3562       REAL(wp) ::  y_t !< y-coordinate of tested mesh point
3563
3564       TYPE(mesh_point) ::  in_mp !< Input mesh point
3565!
3566!--
3567       x = in_mp%x
3568       y = in_mp%y
3569       DO jl = 0, SIZE(tmp_mesh)-2
3570          IF ( in_id == jl ) CYCLE
3571!
3572!--       Ignore mesh points with 0 connections
3573          IF ( tmp_mesh(jl)%polygon_id /= -1 ) THEN
3574             IF ( tmp_mesh(jl)%noc == 0 ) CYCLE
3575          ENDIF
3576          x_t = tmp_mesh(jl)%x
3577          y_t = tmp_mesh(jl)%y
3578          pid_t = tmp_mesh(jl)%polygon_id
3579          vid_t = tmp_mesh(jl)%vertex_id
3580!
3581!--       If the connecting line between the target and a mesh point points
3582!--       into the mesh point's polygon, no connection will be
3583!--       established between the two points. This is the case if the
3584!--       previous (next) vertex of the polygon is right of the connecting
3585!--       line and the next (previous) vertex of the polygon is left of the
3586!--       connecting line.
3587          IF ( pid_t > 0 .AND. pid_t <= SIZE(polygons) ) THEN
3588             IF ( (((is_left(x,y,x_t,y_t,polygons(pid_t)%vertices(vid_t-1)%x,  &
3589                                       polygons(pid_t)%vertices(vid_t-1)%y)    &
3590                  .AND. is_right(x,y,x_t,y_t,                                  &
3591                                       polygons(pid_t)%vertices(vid_t+1)%x,    &
3592                                       polygons(pid_t)%vertices(vid_t+1)%y) )  &
3593                  .OR. (is_right(x,y,x_t,y_t,                                  &
3594                                       polygons(pid_t)%vertices(vid_t-1)%x,    &
3595                                       polygons(pid_t)%vertices(vid_t-1)%y)    &
3596                  .AND. is_left(x,y,x_t,y_t,                                   &
3597                                       polygons(pid_t)%vertices(vid_t+1)%x,    &
3598                                       polygons(pid_t)%vertices(vid_t+1)%y)))))&
3599             THEN
3600                CYCLE
3601             ENDIF
3602          ENDIF
3603!
3604!--       For each edge of each polygon, check if it intersects with the
3605!--       potential connection. If at least one intersection is found,
3606!--       no connection can be made
3607          intersection_found = .FALSE.
3608          DO pl = 1, SIZE(polygons)
3609             DO vl = 1, polygons(pl)%nov
3610                v1x = polygons(pl)%vertices(vl)%x
3611                v1y = polygons(pl)%vertices(vl)%y
3612                v2x = polygons(pl)%vertices(vl+1)%x
3613                v2y = polygons(pl)%vertices(vl+1)%y
3614                intersection_found = intersect(x,y,x_t,y_t,v1x,v1y,v2x,v2y)
3615                IF ( intersection_found ) THEN
3616                   EXIT
3617                ENDIF
3618             ENDDO
3619             IF ( intersection_found ) EXIT
3620          ENDDO
3621          IF ( intersection_found ) CYCLE
3622!
3623!--       If neither of the above two test was true, a connection will be
3624!--       established between the two mesh points.
3625          CALL mas_nav_add_connection(in_mp,jl, tmp_mesh(jl))
3626          CALL mas_nav_add_connection(tmp_mesh(jl),in_id, in_mp)
3627       ENDDO
3628       CALL mas_nav_reduce_connections(in_mp)
3629
3630    END SUBROUTINE mas_nav_add_vertex_to_mesh
3631
3632!------------------------------------------------------------------------------!
3633! Description:
3634! ------------
3635!> Creates a temporary copy of the navigation mesh to be used for pathfinding
3636!------------------------------------------------------------------------------!
3637    SUBROUTINE mas_nav_create_tmp_mesh( a_x, a_y, t_x, t_y, som )
3638
3639       IMPLICIT NONE
3640
3641       INTEGER(iwp) ::  som !< size of mesh
3642       INTEGER(iwp) ::  noc !< number of connetions
3643       INTEGER(iwp) ::  im  !< local mesh point counter
3644
3645       REAL(wp) ::  a_x !< x-coordinate agent
3646       REAL(wp) ::  a_y !< y-coordinate agent
3647       REAL(wp) ::  t_x !< x-coordinate target
3648       REAL(wp) ::  t_y !< y-coordinate target
3649!
3650!--    give tmp_mesh the size of mesh
3651       som = SIZE(mesh)+1
3652       ALLOCATE(tmp_mesh(0:som))
3653!
3654!--    give the allocatable variables in tmp_mesh their respctive sizes
3655       DO im = 1, som-1
3656          noc = mesh(im)%noc
3657          ALLOCATE(tmp_mesh(im)%connected_vertices(1:noc))
3658          ALLOCATE(tmp_mesh(im)%distance_to_vertex(1:noc))
3659       ENDDO
3660!
3661!--    copy mesh to tmp_mesh
3662       tmp_mesh(1:som-1) = mesh(1:som-1)
3663!
3664!--    Add target point ...
3665       CALL mas_nav_init_mesh_point(tmp_mesh(0),-1_iwp,-1_iwp,t_x, t_y)
3666       CALL mas_nav_add_vertex_to_mesh(tmp_mesh(0),0_iwp)
3667!
3668!--    ... and start point to temp mesh
3669       CALL mas_nav_init_mesh_point(tmp_mesh(som),-1_iwp,-1_iwp,a_x, a_y)
3670       CALL mas_nav_add_vertex_to_mesh(tmp_mesh(som),som)
3671
3672    END SUBROUTINE mas_nav_create_tmp_mesh
3673   
3674
3675!------------------------------------------------------------------------------!
3676! Description:
3677! ------------
3678!> Finds the shortest path from an agents' position to her target. As the
3679!> actual pathfinding algorithm uses the obstacle corners and then shifts them
3680!> outward after pathfinding, cases can uccur in which the connection between
3681!> these intermittent targets then intersect with obstacles. To remedy this
3682!> the pathfinding algorithm is then run on every two subsequent intermittent
3683!> targets iteratively and new intermittent targets may be added to the path
3684!> this way.
3685!------------------------------------------------------------------------------!
3686    SUBROUTINE mas_nav_find_path( nl )
3687
3688       IMPLICIT NONE
3689
3690       INTEGER(iwp) ::  nl            !< local agent counter
3691       INTEGER(iwp) ::  il            !< local counter
3692       INTEGER(iwp) ::  jl            !< local counter
3693       INTEGER(iwp) ::  kl            !< local counter
3694       INTEGER(iwp) ::  nsteps_total  !< number of steps on path
3695       INTEGER(iwp) ::  nsteps_dummy  !< number of steps on path
3696       
3697       REAL(wp), DIMENSION(0:30) ::  ld_path_x !< local dummy agent path to target (x)
3698       REAL(wp), DIMENSION(0:30) ::  ld_path_y !< local dummy agent path to target (y)
3699!
3700!--    Initialize agent path arrays
3701       agents(nl)%path_x    = -1
3702       agents(nl)%path_y    = -1
3703       agents(nl)%path_x(0) = agents(nl)%x
3704       agents(nl)%path_y(0) = agents(nl)%y
3705!
3706!--    Calculate initial path
3707       CALL mas_nav_a_star( agents(nl)%x,   agents(nl)%y,                      &
3708                            agents(nl)%t_x, agents(nl)%t_y, nsteps_total )
3709!
3710!--    Set the rest of the agent path that was just calculated
3711       agents(nl)%path_x(1:nsteps_total) = dummy_path_x(1:nsteps_total)
3712       agents(nl)%path_y(1:nsteps_total) = dummy_path_y(1:nsteps_total)
3713!
3714!--    Iterate through found path and check more intermittent targets need
3715!--    to be added. For this, run pathfinding between every two consecutive
3716!--    intermittent targets.
3717       DO il = 0, MIN(agt_path_size-1, nsteps_total-1)
3718!
3719!--       pathfinding between two consecutive intermittent targets
3720          CALL mas_nav_a_star( agents(nl)%path_x(il),   agents(nl)%path_y(il), &
3721                              agents(nl)%path_x(il+1), agents(nl)%path_y(il+1),&
3722                              nsteps_dummy )
3723          nsteps_dummy = nsteps_dummy - 1
3724!
3725!--       If additional intermittent targets are found, add them to the path
3726          IF ( nsteps_dummy > 0 ) THEN
3727             ld_path_x = -1
3728             ld_path_y = -1
3729             ld_path_x(il+1:il+nsteps_dummy) = dummy_path_x(1:nsteps_dummy)
3730             ld_path_y(il+1:il+nsteps_dummy) = dummy_path_y(1:nsteps_dummy)
3731             kl = 1
3732             DO jl = il+1,nsteps_total
3733               ld_path_x( il+nsteps_dummy+kl ) = agents(nl)%path_x(jl)
3734               ld_path_y( il+nsteps_dummy+kl ) = agents(nl)%path_y(jl)
3735               kl = kl + 1
3736               IF ( kl > agt_path_size ) EXIT
3737             ENDDO
3738             nsteps_total = MIN(nsteps_total + nsteps_dummy, agt_path_size)
3739             agents(nl)%path_x(il+1:nsteps_total) = ld_path_x(il+1:nsteps_total)
3740             agents(nl)%path_y(il+1:nsteps_total) = ld_path_y(il+1:nsteps_total)
3741          ENDIF
3742
3743       ENDDO
3744!
3745!--    reset path counter to first intermittent target
3746       agents(nl)%path_counter = 1
3747
3748    END SUBROUTINE mas_nav_find_path
3749
3750!------------------------------------------------------------------------------!
3751! Description:
3752! ------------
3753!> Reduces the size of connection array to the amount of actual connections
3754!> after all connetions were added to a mesh point
3755!------------------------------------------------------------------------------!
3756    SUBROUTINE mas_nav_reduce_connections ( in_mp )
3757
3758       IMPLICIT NONE
3759
3760       INTEGER(iwp) ::  noc  !< number of connections
3761
3762       INTEGER, DIMENSION(:), ALLOCATABLE ::  dum_cv   !< dummy connected_vertices
3763
3764       REAL(wp), DIMENSION(:), ALLOCATABLE ::  dum_dtv !< dummy distance_to_vertex
3765
3766       TYPE(mesh_point) ::  in_mp
3767
3768       noc = in_mp%noc
3769       ALLOCATE( dum_cv(1:noc),dum_dtv(1:noc) )
3770       dum_cv  = in_mp%connected_vertices(1:noc)
3771       dum_dtv = in_mp%distance_to_vertex(1:noc)
3772       DEALLOCATE( in_mp%connected_vertices, in_mp%distance_to_vertex )
3773       ALLOCATE( in_mp%connected_vertices(1:noc),                    &
3774                 in_mp%distance_to_vertex(1:noc) )
3775       in_mp%connected_vertices(1:noc) = dum_cv(1:noc)
3776       in_mp%distance_to_vertex(1:noc) = dum_dtv(1:noc)
3777
3778    END SUBROUTINE mas_nav_reduce_connections
3779
3780!------------------------------------------------------------------------------!
3781! Description:
3782! ------------
3783!> Initializes a point of the navigation mesh
3784!------------------------------------------------------------------------------!
3785    SUBROUTINE mas_nav_init_mesh_point ( in_mp, pid, vid, x, y )
3786
3787       IMPLICIT NONE
3788
3789       INTEGER(iwp) ::  pid !< polygon ID
3790       INTEGER(iwp) ::  vid !< vertex ID
3791
3792       REAL(wp) ::  x !< x-coordinate
3793       REAL(wp) ::  y !< y-coordinate
3794
3795       TYPE(mesh_point) ::  in_mp !< mesh point to be initialized
3796
3797       in_mp%origin_id          = -1
3798       in_mp%polygon_id         = pid
3799       in_mp%vertex_id          = vid
3800       in_mp%cost_so_far        = 1.d12
3801       in_mp%x                  = x
3802       in_mp%y                  = y
3803       in_mp%x_s                = x
3804       in_mp%y_s                = y
3805       ALLOCATE(in_mp%connected_vertices(1:100),                               &
3806                in_mp%distance_to_vertex(1:100))
3807       in_mp%connected_vertices = -999
3808       in_mp%distance_to_vertex = -999.
3809       in_mp%noc                = 0
3810
3811    END SUBROUTINE mas_nav_init_mesh_point
3812
3813!------------------------------------------------------------------------------!
3814! Description:
3815! ------------
3816!> Reading of namlist from parin file
3817!------------------------------------------------------------------------------!
3818    SUBROUTINE mas_parin
3819
3820       USE control_parameters,                                                 &
3821           ONLY: agent_time_unlimited, multi_agent_system_end,                 &
3822                 multi_agent_system_start
3823
3824       IMPLICIT NONE
3825
3826       CHARACTER (LEN=80) ::  line  !<
3827
3828       NAMELIST /agent_parameters/  a_rand_target,                             &
3829                                    adx,                                       &
3830                                    ady,                                       &
3831                                    agent_maximum_age,                         &
3832                                    agent_time_unlimited,                      &
3833                                    alloc_factor_mas,                          &
3834                                    asl,                                       &
3835                                    asn,                                       &
3836                                    asr,                                       &
3837                                    ass,                                       &
3838                                    at_x,                                      &
3839                                    at_y,                                      &
3840                                    bc_mas_lr,                                 &
3841                                    bc_mas_ns,                                 &
3842                                    coll_t_0,                                  &
3843                                    corner_gate_start,                         &
3844                                    corner_gate_width,                         &
3845                                    dim_size_agtnum_manual,                    &
3846                                    dim_size_factor_agtnum,                    &
3847                                    deallocate_memory_mas,                     &
3848                                    dist_to_int_target,                        &
3849                                    dt_agent,                                  &
3850                                    dt_arel,                                   &
3851                                    dt_write_agent_data,                       &
3852                                    end_time_arel,                             &
3853                                    max_dist_from_path,                        &
3854                                    min_nr_agent,                              &
3855                                    multi_agent_system_end,                    &
3856                                    multi_agent_system_start,                  &
3857                                    number_of_agent_groups,                    &
3858                                    radius_agent,                              &
3859                                    random_start_position_agents,              &
3860                                    read_agents_from_restartfile,              &
3861                                    repuls_agent,                              &
3862                                    repuls_wall,                               &
3863                                    scan_radius_agent,                         &
3864                                    sigma_rep_agent,                           &
3865                                    sigma_rep_wall,                            &
3866                                    step_dealloc_mas,                          &
3867                                    tau_accel_agent
3868
3869!
3870!--    Try to find agent package
3871       REWIND ( 11 )
3872       line = ' '
3873       DO WHILE ( INDEX( line, '&agent_parameters' ) == 0 )
3874          READ ( 11, '(A)', END=20 )  line
3875       ENDDO
3876       BACKSPACE ( 11 )
3877
3878!
3879!--    Read user-defined namelist
3880       READ ( 11, agent_parameters, ERR = 10, END = 20 )
3881
3882!
3883!--    Set flag that indicates that agents are switched on
3884       agents_active = .TRUE.
3885       GOTO 20
3886
3887 10    BACKSPACE( 11 )
3888       READ( 11 , '(A)') line
3889       CALL parin_fail_message( 'agent_parameters', line )
3890
3891 20    CONTINUE
3892
3893    END SUBROUTINE mas_parin
3894
3895!------------------------------------------------------------------------------!
3896! Description:
3897! ------------
3898!> Routine for the whole processor
3899!> Sort all agents into the 4 respective subgrid boxes
3900!------------------------------------------------------------------------------!
3901    SUBROUTINE mas_ps_sort_in_subboxes
3902
3903       IMPLICIT NONE
3904
3905       INTEGER(iwp) ::  i           !< grid box (x)
3906       INTEGER(iwp) ::  ip          !< counter (x)
3907       INTEGER(iwp) ::  is          !< box counter
3908       INTEGER(iwp) ::  j           !< grid box (y)
3909       INTEGER(iwp) ::  jp          !< counter (y)
3910       INTEGER(iwp) ::  m           !< sorting index
3911       INTEGER(iwp) ::  n           !< agent index
3912       INTEGER(iwp) ::  nn          !< agent counter
3913       INTEGER(iwp) ::  sort_index  !< sorting index
3914
3915       INTEGER(iwp), DIMENSION(0:3) ::  sort_count  !< number of agents in one subbox
3916
3917       TYPE(agent_type), DIMENSION(:,:), ALLOCATABLE ::  sort_agents  !< sorted agent array
3918
3919       DO  ip = nxl, nxr
3920          DO  jp = nys, nyn
3921             number_of_agents = agt_count(jp,ip)
3922             IF ( number_of_agents <= 0 )  CYCLE
3923             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
3924
3925             nn = 0
3926             sort_count = 0
3927             ALLOCATE( sort_agents(number_of_agents, 0:3) )
3928
3929             DO  n = 1, number_of_agents
3930                sort_index = 0
3931
3932                IF ( agents(n)%agent_mask )  THEN
3933                   nn = nn + 1
3934!
3935!--                Sorting agents with a binary scheme
3936!--                sort_index=11_2=3_10 -> agent at the left,south subgridbox
3937!--                sort_index=10_2=2_10 -> agent at the left,north subgridbox
3938!--                sort_index=01_2=1_10 -> agent at the right,south subgridbox
3939!--                sort_index=00_2=0_10 -> agent at the right,north subgridbox
3940!--                For this the center of the gridbox is calculated
3941                   i = (agents(n)%x + 0.5_wp * dx) * ddx
3942                   j = (agents(n)%y + 0.5_wp * dy) * ddy
3943
3944                   IF ( i == ip )  sort_index = sort_index + 2
3945                   IF ( j == jp )  sort_index = sort_index + 1
3946
3947                   sort_count(sort_index) = sort_count(sort_index) + 1
3948                   m = sort_count(sort_index)
3949                   sort_agents(m,sort_index) = agents(n)
3950                   sort_agents(m,sort_index)%block_nr = sort_index
3951                ENDIF
3952             ENDDO
3953
3954             nn = 0
3955             DO is = 0,3
3956                grid_agents(jp,ip)%start_index(is) = nn + 1
3957                DO n = 1,sort_count(is)
3958                   nn = nn + 1
3959                   agents(nn) = sort_agents(n,is)
3960                ENDDO
3961                grid_agents(jp,ip)%end_index(is) = nn
3962             ENDDO
3963
3964             number_of_agents = nn
3965             agt_count(jp,ip) = number_of_agents
3966             DEALLOCATE(sort_agents)
3967          ENDDO
3968       ENDDO
3969
3970    END SUBROUTINE mas_ps_sort_in_subboxes
3971
3972!------------------------------------------------------------------------------!
3973! Description:
3974! ------------
3975!> Move all agents not marked for deletion to lowest indices (packing)
3976!------------------------------------------------------------------------------!
3977    SUBROUTINE mas_ps_pack
3978
3979       IMPLICIT NONE
3980
3981       INTEGER(iwp) ::  n  !< agent counter
3982       INTEGER(iwp) ::  nn !< number of agents
3983!
3984!--    Find out elements marked for deletion and move data from highest index
3985!--    values to these free indices
3986       nn = number_of_agents
3987
3988       DO WHILE ( .NOT. agents(nn)%agent_mask )
3989          nn = nn-1
3990          IF ( nn == 0 )  EXIT
3991       ENDDO
3992
3993       IF ( nn > 0 )  THEN
3994          DO  n = 1, number_of_agents
3995             IF ( .NOT. agents(n)%agent_mask )  THEN
3996                agents(n) = agents(nn)
3997                nn = nn - 1
3998                DO WHILE ( .NOT. agents(nn)%agent_mask )
3999                   nn = nn-1
4000                   IF ( n == nn )  EXIT
4001                ENDDO
4002             ENDIF
4003             IF ( n == nn )  EXIT
4004          ENDDO
4005       ENDIF
4006
4007!
4008!--    The number of deleted agents has been determined in routines
4009!--    mas_boundary_conds, mas_droplet_collision, and mas_eh_exchange_horiz
4010       number_of_agents = nn
4011
4012    END SUBROUTINE mas_ps_pack 
4013
4014!------------------------------------------------------------------------------!
4015! Description:
4016! ------------
4017!> Sort agents in each sub-grid box into two groups: agents that already
4018!> completed the LES timestep, and agents that need further timestepping to
4019!> complete the LES timestep.
4020!------------------------------------------------------------------------------!
4021!    SUBROUTINE mas_ps_sort_timeloop_done
4022!
4023!       IMPLICIT NONE
4024!
4025!       INTEGER(iwp) :: end_index     !< agent end index for each sub-box
4026!       INTEGER(iwp) :: i             !< index of agent grid box in x-direction
4027!       INTEGER(iwp) :: j             !< index of agent grid box in y-direction
4028!       INTEGER(iwp) :: n             !< running index for number of agents
4029!       INTEGER(iwp) :: nb            !< index of subgrid boux
4030!       INTEGER(iwp) :: nf            !< indices for agents in each sub-box that already finalized their substeps
4031!       INTEGER(iwp) :: nnf           !< indices for agents in each sub-box that need further treatment
4032!       INTEGER(iwp) :: num_finalized !< number of agents in each sub-box that already finalized their substeps
4033!       INTEGER(iwp) :: start_index   !< agent start index for each sub-box
4034!
4035!       TYPE(agent_type), DIMENSION(:), ALLOCATABLE :: sort_agents  !< temporary agent array
4036!
4037!       DO  i = nxl, nxr
4038!          DO  j = nys, nyn
4039!
4040!             number_of_agents = agt_count(j,i)
4041!             IF ( number_of_agents <= 0 )  CYCLE
4042!
4043!             agents => grid_agents(j,i)%agents(1:number_of_agents)
4044!
4045!             DO  nb = 0, 3
4046!
4047!--             Obtain start and end index for each subgrid box
4048!                start_index = grid_agents(j,i)%start_index(nb)
4049!                end_index   = grid_agents(j,i)%end_index(nb)
4050!
4051!--             Allocate temporary array used for sorting
4052!                ALLOCATE( sort_agents(start_index:end_index) )
4053!
4054!--             Determine number of agents already completed the LES
4055!--             timestep, and write them into a temporary array
4056!                nf = start_index
4057!                num_finalized = 0
4058!                DO  n = start_index, end_index
4059!                   IF ( dt_3d - agents(n)%dt_sum < 1E-8_wp )  THEN
4060!                      sort_agents(nf) = agents(n)
4061!                      nf              = nf + 1
4062!                      num_finalized   = num_finalized + 1
4063!                   ENDIF
4064!                ENDDO
4065!
4066!--             Determine number of agents that not completed the LES
4067!--             timestep, and write them into a temporary array
4068!                nnf = nf
4069!                DO  n = start_index, end_index
4070!                   IF ( dt_3d - agents(n)%dt_sum > 1E-8_wp )  THEN
4071!                      sort_agents(nnf) = agents(n)
4072!                      nnf              = nnf + 1
4073!                   ENDIF
4074!                ENDDO
4075!
4076!--             Write back sorted agents
4077!                agents(start_index:end_index) =                          &
4078!                                        sort_agents(start_index:end_index)
4079!
4080!--             Determine updated start_index, used to masked already
4081!--             completed agents.
4082!                grid_agents(j,i)%start_index(nb) =                     &
4083!                                   grid_agents(j,i)%start_index(nb)    &
4084!                                 + num_finalized
4085!
4086!--             Deallocate dummy array
4087!                DEALLOCATE ( sort_agents )
4088!
4089!--             Finally, if number of non-completed agents is non zero
4090!--             in any of the sub-boxes, set control flag appropriately.
4091!                IF ( nnf > nf )                                             &
4092!                   grid_agents(j,i)%time_loop_done = .FALSE.
4093!
4094!             ENDDO
4095!          ENDDO
4096!       ENDDO
4097!
4098!    END SUBROUTINE mas_ps_sort_timeloop_done
4099
4100!------------------------------------------------------------------------------!
4101! Description:
4102! ------------
4103!> Calls social forces calculations
4104!------------------------------------------------------------------------------!
4105    SUBROUTINE mas_timestep_forces_call ( ip, jp )
4106
4107       IMPLICIT NONE
4108
4109       INTEGER(iwp) ::  ip  !< counter, x-direction
4110       INTEGER(iwp) ::  jp  !< counter, y-direction
4111       INTEGER(iwp) ::  n   !< loop variable over all agents in a grid box
4112
4113!
4114!--    Get direction for all agents in current grid cell
4115       CALL mas_agent_direction
4116
4117       DO n = 1, number_of_agents
4118
4119          force_x = 0.0_wp
4120          force_y = 0.0_wp
4121
4122          CALL mas_timestep_social_forces ( 'acceleration', n, ip, jp )
4123
4124          CALL mas_timestep_social_forces ( 'other_agents', n, ip, jp )
4125
4126          CALL mas_timestep_social_forces ( 'walls',        n, ip, jp )
4127!
4128!--       Update forces
4129          agents(n)%force_x = force_x
4130          agents(n)%force_y = force_y
4131       ENDDO
4132
4133    END SUBROUTINE mas_timestep_forces_call
4134
4135!------------------------------------------------------------------------------!
4136! Description:
4137! ------------
4138!> Euler timestep of agent transport
4139!------------------------------------------------------------------------------!
4140    SUBROUTINE mas_timestep
4141
4142       IMPLICIT NONE
4143
4144       INTEGER(iwp) ::  n !< loop variable over all agents in a grid box
4145
4146       REAL(wp) ::  abs_v !< absolute value of velocity
4147       REAL(wp) ::  abs_f !< absolute value of force
4148
4149       DO n = 1, number_of_agents
4150!
4151!--       Limit absolute force to a maximum to prevent unrealistic acceleration
4152          abs_f = SQRT((agents(n)%force_x)**2 + (agents(n)%force_y)**2)
4153          IF ( abs_f > 20. ) THEN
4154             agents(n)%force_x = agents(n)%force_x * 20. / abs_f
4155             agents(n)%force_y = agents(n)%force_y * 20. / abs_f
4156          ENDIF
4157!
4158!--       Update agent speed
4159          agents(n)%speed_x = agents(n)%speed_x + agents(n)%force_x * dt_agent
4160          agents(n)%speed_y = agents(n)%speed_y + agents(n)%force_y * dt_agent
4161!
4162!--       Reduction of agent speed to maximum agent speed
4163          abs_v = SQRT((agents(n)%speed_x)**2 + (agents(n)%speed_y)**2)
4164          IF ( abs_v > v_max_agent ) THEN
4165             agents(n)%speed_x = agents(n)%speed_x * v_max_agent / abs_v
4166             agents(n)%speed_y = agents(n)%speed_y * v_max_agent / abs_v
4167          ENDIF
4168!
4169!--       Update agent position
4170          agents(n)%x = agents(n)%x + agents(n)%speed_x * dt_agent
4171          agents(n)%y = agents(n)%y + agents(n)%speed_y * dt_agent
4172!
4173!--       Update absolute value of agent speed
4174          agents(n)%speed_abs = abs_v
4175!
4176!--       Increment the agent age and the total time that the agent
4177!--       has advanced within the agent timestep procedure
4178          agents(n)%age_m  = agents(n)%age
4179          agents(n)%age    = agents(n)%age    + dt_agent
4180          agents(n)%dt_sum = agents(n)%dt_sum + dt_agent
4181!
4182!--       Check whether there is still an agent that has not yet completed
4183!--       the total LES timestep
4184          IF ( ( dt_3d - agents(n)%dt_sum ) > 1E-8_wp )  THEN
4185             dt_3d_reached_l_mas = .FALSE.
4186          ENDIF
4187
4188       ENDDO
4189
4190    END SUBROUTINE mas_timestep
4191
4192!------------------------------------------------------------------------------!
4193! Description:
4194! ------------
4195!> Calculates the Social Forces (Helbing and Molnar, 1995) that the agent
4196!> experiences due to acceleration towards target and repulsion by obstacles
4197!------------------------------------------------------------------------------!
4198    SUBROUTINE mas_timestep_social_forces ( mode, nl, ip, jp )
4199
4200       IMPLICIT NONE
4201
4202       CHARACTER (LEN=*) ::  mode  !< identifier for the mode of calculation
4203
4204       INTEGER(iwp) ::  ij_dum      !< index of nearest wall
4205       INTEGER(iwp) ::  il          !< index variable along x
4206       INTEGER(iwp) ::  ip          !< index variable along x
4207       INTEGER(iwp) ::  jl          !< index variable along y
4208       INTEGER(iwp) ::  jp          !< index variable along y
4209       INTEGER(iwp) ::  nl          !< loop variable over all agents in a grid box
4210       INTEGER(iwp) ::  no          !< loop variable over all agents in a grid box
4211       INTEGER(iwp) ::  noa         !< amount of agents in a grid box
4212       INTEGER(iwp) ::  sc_x_end    !< index for scan for topography/other agents
4213       INTEGER(iwp) ::  sc_x_start  !< index for scan for topography/other agents
4214       INTEGER(iwp) ::  sc_y_end    !< index for scan for topography/other agents
4215       INTEGER(iwp) ::  sc_y_start  !< index for scan for topography/other agents
4216
4217       LOGICAL ::  corner_found  !< flag that indicates a corner has been found near agent
4218
4219       REAL(wp) ::  a_pl             !< factor for collision avoidance
4220       REAL(wp) ::  ax_semimaj       !< semiminor axis of repulsive ellipse
4221       REAL(wp) ::  b_pl             !< factor for collision avoidance
4222       REAL(wp) ::  c_pl             !< factor for collision avoidance
4223       REAL(wp) ::  coll_t           !< time at which the next collision would happen
4224       REAL(wp) ::  d_coll_t_0       !< inverse of collision cutoff time
4225       REAL(wp) ::  d_pl             !< factor for collision avoidance
4226       REAL(wp) ::  ddum_f           !< dummy devisor collision avoidance
4227       REAL(wp) ::  dist             !< distance to obstacle
4228       REAL(wp) ::  dist_sq          !< distance to obstacle squared
4229       REAL(wp) ::  pos_rel_x        !< relative position of two agents (x)
4230       REAL(wp) ::  pos_rel_y        !< relative position of two agents (y)
4231       REAL(wp) ::  r_sq             !< y-position
4232       REAL(wp) ::  sra              !< scan radius (agents)
4233       REAL(wp) ::  srw              !< local variable for scan radius (walls)
4234       REAL(wp) ::  v_rel_x          !< relative velocity (x); collision avoidance
4235       REAL(wp) ::  v_rel_y          !< relative velocity (y); collision avoidance
4236       REAL(wp) ::  x_a              !< x-position
4237       REAL(wp) ::  x_wall           !< x-position of wall
4238       REAL(wp) ::  y_a              !< y-position
4239       REAL(wp) ::  y_wall           !< y-position of wall
4240
4241       REAL(wp), PARAMETER ::  k_pl = 1.5  !< factor for collision avoidance
4242
4243       TYPE(agent_type), DIMENSION(:), POINTER ::  l_agts !< agents that repulse current agent
4244
4245!
4246!--    Initialization
4247       x_a = agents(nl)%x
4248       y_a = agents(nl)%y
4249
4250       SELECT CASE ( TRIM( mode ) )
4251!
4252!--       Calculation of force due to agent trying to approach desired velocity
4253          CASE ( 'acceleration' )
4254
4255             force_x = force_x + d_tau_accel_agent                             &
4256                          * ( agents(nl)%speed_des*agents(nl)%speed_e_x        &
4257                             -agents(nl)%speed_x )
4258
4259             force_y = force_y + d_tau_accel_agent                             &
4260                          * ( agents(nl)%speed_des*agents(nl)%speed_e_y        &
4261                             -agents(nl)%speed_y )
4262
4263!
4264!--       Calculation of repulsive forces by other agents in a radius around the
4265!--       current one
4266          CASE ( 'other_agents' )
4267
4268             sra = scan_radius_agent
4269             d_coll_t_0 = 1./coll_t_0
4270!
4271!--          Find relevant gridboxes (those that could contain agents within
4272!--          scan radius)
4273             sc_x_start = FLOOR( (x_a - sra) * ddx )
4274             sc_x_end   = FLOOR( (x_a + sra) * ddx )
4275             sc_y_start = FLOOR( (y_a - sra) * ddx )
4276             sc_y_end   = FLOOR( (y_a + sra) * ddx )
4277             IF ( sc_x_start < nxlg ) sc_x_start = nxlg
4278             IF ( sc_x_end   > nxrg ) sc_x_end   = nxrg
4279             IF ( sc_y_start < nysg ) sc_y_start = nysg
4280             IF ( sc_y_end   > nyng ) sc_y_end   = nyng
4281
4282             sra = sra**2
4283!
4284!--          Loop over all previously found relevant gridboxes
4285             DO il = sc_x_start, sc_x_end
4286                DO jl = sc_y_start, sc_y_end
4287                   noa = agt_count(jl,il)
4288                   IF ( noa <= 0 )  CYCLE
4289                   l_agts => grid_agents(jl,il)%agents(1:noa)
4290                   DO no = 1, noa
4291!
4292!--                   Skip self
4293                      IF ( jl == jp .AND. il == ip .AND. no == nl ) CYCLE
4294                      pos_rel_x = l_agts(no)%x - x_a
4295                      pos_rel_y = l_agts(no)%y - y_a
4296                      dist_sq = pos_rel_x**2 + pos_rel_y**2
4297                      IF ( dist_sq > sra ) CYCLE
4298                      r_sq    = (2*radius_agent)**2
4299                      v_rel_x   = agents(nl)%speed_x - l_agts(no)%speed_x
4300                      v_rel_y   = agents(nl)%speed_y - l_agts(no)%speed_y
4301!
4302!--                   Collision is already occuring, default to standard
4303!--                   social forces
4304                      IF ( dist_sq <= r_sq ) THEN
4305                         dist = SQRT(dist_sq) + 1.0d-12
4306                         ax_semimaj = .5_wp*SQRT( dist )
4307
4308                         force_x = force_x - 0.125_wp * repuls_agent           &
4309                                        * d_sigma_rep_agent / ax_semimaj       &
4310                                        * EXP( -ax_semimaj*d_sigma_rep_agent ) &
4311                                        * (pos_rel_x/dist)
4312
4313                         force_y = force_y - 0.125_wp * repuls_agent           &
4314                                        * d_sigma_rep_agent / ax_semimaj       &
4315                                        * EXP( -ax_semimaj*d_sigma_rep_agent ) &
4316                                        * (pos_rel_y/dist)
4317!
4318!--                   Currently no collision, calculate collision avoidance
4319!--                   force according to Karamouzas et al (2014, PRL 113,238701)
4320                      ELSE
4321!
4322!--                     factors
4323                         a_pl = v_rel_x**2 +  v_rel_y**2
4324                         b_pl = pos_rel_x*v_rel_x + pos_rel_y*v_rel_y
4325                         c_pl = dist_sq - r_sq
4326                         d_pl = b_pl**2 - a_pl*c_pl
4327!
4328!--                      If the two agents are moving non-parallel, calculate
4329!--                      collision avoidance social force
4330                         IF ( d_pl > 0.0_wp .AND.                              &
4331                            ( a_pl < -0.00001 .OR. a_pl > 0.00001 ) )          &
4332                         THEN
4333
4334                            d_pl   = SQRT(d_pl)
4335                            coll_t = (b_pl - d_pl)/a_pl
4336                            IF ( coll_t > 0.0_wp ) THEN
4337!
4338!--                            Dummy factor
4339                               ddum_f = 1. / ( a_pl * coll_t**2 )              &
4340                                           * ( 2. / coll_t + 1.0 * d_coll_t_0 )
4341!
4342!--                            x-component of social force
4343                               force_x = force_x - k_pl *                      &
4344                                         EXP( -coll_t * d_coll_t_0 ) *         &
4345                                         ( v_rel_x -                           &
4346                                           ( b_pl * v_rel_x -                  &
4347                                             a_pl * pos_rel_x ) / d_pl ) *     &
4348                                         ddum_f
4349!
4350!--                            y-component of social force
4351                               force_y = force_y - k_pl *                      &
4352                                         EXP( -coll_t * d_coll_t_0 ) *         &
4353                                         ( v_rel_y -                           &
4354                                           ( b_pl * v_rel_y -                  &
4355                                             a_pl * pos_rel_y ) / d_pl ) *     &
4356                                         ddum_f
4357
4358                            ENDIF
4359                         ENDIF
4360                      ENDIF
4361                   ENDDO
4362                ENDDO
4363             ENDDO
4364
4365          CASE ( 'walls' )
4366
4367             srw = scan_radius_wall
4368             corner_found = .FALSE.
4369!
4370!--          find relevant grid boxes (those that could contain topography
4371!--          within radius)
4372             sc_x_start = (x_a - srw) * ddx
4373             sc_x_end   = (x_a + srw) * ddx
4374             sc_y_start = (y_a - srw) * ddx
4375             sc_y_end   = (y_a + srw) * ddx
4376             IF ( sc_x_start < nxlg ) sc_x_start = nxlg
4377             IF ( sc_x_end   > nxrg ) sc_x_end   = nxrg
4378             IF ( sc_y_start < nysg ) sc_y_start = nysg
4379             IF ( sc_y_end   > nyng ) sc_y_end   = nyng
4380!
4381!--          Find "walls" ( i.e. topography steps (up or down) higher than one
4382!--          grid box ) that are perpendicular to the agent within the defined
4383!--          search radius. Such obstacles cannot be passed and a social force
4384!--          to that effect is applied.
4385!--          Walls only apply a force perpendicular to the wall to the agent.
4386!--          There is therefore a search for walls directly right, left, south
4387!--          and north of the agent. All other walls are ignored.
4388!--
4389!--          Check for wall left of current agent
4390             ij_dum = 0
4391             IF ( sc_x_start < ip ) THEN
4392                DO il = ip - 1, sc_x_start, -1
4393!
4394!--                Going left from the agent, check for a right wall
4395                   IF ( BTEST( obstacle_flags(jp,il), 2 ) ) THEN
4396!
4397!--                   obstacle found in grid box il, wall at right side
4398                      x_wall = (il+1)*dx
4399!
4400!--                   Calculate force of found wall on agent
4401                      CALL mas_timestep_wall_corner_force( x_a, x_wall, y_a,   &
4402                                                           y_a )
4403!
4404!--                   calculate new x starting index for later scan for corners
4405                      ij_dum = il + 1
4406                      EXIT
4407                   ENDIF
4408                ENDDO
4409             ENDIF
4410             IF ( ij_dum /= 0 ) sc_x_start = ij_dum 
4411
4412!
4413!--          Check for wall right of current agent
4414             ij_dum = 0
4415             IF ( sc_x_end > ip ) THEN
4416                DO il = ip + 1, sc_x_end
4417!
4418!--                Going right from the agent, check for a left wall
4419                   IF ( BTEST( obstacle_flags(jp,il), 6 ) ) THEN
4420!
4421!--                   obstacle found in grid box il, wall at left side
4422                      x_wall = il*dx
4423!
4424!--                   Calculate force of found wall on agent
4425                      CALL mas_timestep_wall_corner_force( x_a, x_wall, y_a,   &
4426                                                           y_a )
4427!
4428!--                   calculate new x end index for later scan for corners
4429                      ij_dum = il - 1
4430                      EXIT
4431                   ENDIF
4432                ENDDO
4433             ENDIF
4434             IF ( ij_dum /= 0 ) sc_x_end = ij_dum 
4435
4436!
4437!--          Check for wall south of current agent
4438             ij_dum = 0
4439             IF ( sc_y_start < jp ) THEN
4440                DO jl = jp - 1, sc_y_start, -1
4441!
4442!--                Going south from the agent, check for a north wall
4443                   IF ( BTEST( obstacle_flags(jl,ip), 0 ) ) THEN
4444!
4445!--                   obstacle found in grid box jl, wall at left side
4446                      y_wall = (jl+1)*dy
4447
4448                      CALL mas_timestep_wall_corner_force( x_a, x_a, y_a,      &
4449                                                           y_wall )
4450!
4451!--                   calculate new y starting index for later scan for corners
4452                      ij_dum = jl + 1
4453                      EXIT
4454                   ENDIF
4455                ENDDO
4456             ENDIF
4457             IF ( ij_dum /= 0 ) sc_y_start = ij_dum 
4458
4459!
4460!--          Check for wall north of current agent
4461             ij_dum = 0
4462             IF ( sc_y_end > jp ) THEN
4463                DO jl = jp + 1, sc_y_end 
4464!
4465!--                Going north from the agent, check for a south wall
4466                   IF ( BTEST( obstacle_flags(jl,ip), 4 ) ) THEN
4467!
4468!--                   obstacle found in grid box jl, wall at left side
4469                      y_wall = jl*dy
4470
4471                      CALL mas_timestep_wall_corner_force( x_a, x_a, y_a,      &
4472                                                           y_wall )
4473!
4474!--                   calculate new y end index for later scan for corners
4475                      ij_dum = jl - 1
4476                   ENDIF
4477                ENDDO
4478             ENDIF
4479             IF ( ij_dum /= 0 ) sc_y_end = ij_dum 
4480
4481!
4482!--          Scan for corners surrounding current agent.
4483!--          Only gridcells that are closer than the closest wall in each
4484!--          direction (n,s,r,l) are considered in the search since those
4485!--          further away would have a significantly smaller resulting force
4486!--          than the closer wall.
4487             DO il = sc_x_start, sc_x_end
4488                DO jl = sc_y_start, sc_y_end
4489                   IF ( il == ip .OR. jl == jp ) CYCLE
4490!
4491!--                corners left of agent
4492                   IF ( il < ip ) THEN
4493!
4494!--                   south left quadrant: look for north right corner
4495                      IF ( jl < jp ) THEN
4496                         IF ( BTEST( obstacle_flags(jl,il), 1 ) ) THEN
4497!
4498!--                         calculate coordinates of the found corner
4499                            x_wall = (il+1)*dx
4500                            y_wall = (jl+1)*dy
4501
4502                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4503                                                                 y_a, y_wall )
4504
4505                         ENDIF
4506!
4507!--                   north left quadrant: look for south right corner
4508                      ELSEIF ( jl > jp ) THEN
4509                         IF ( BTEST( obstacle_flags(jl,il), 3 ) ) THEN
4510!
4511!--                         calculate coordinates of the corner of said gridcell
4512!--                         that is closest to the current agent
4513                            x_wall = (il+1)*dx
4514                            y_wall = jl*dy
4515
4516                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4517                                                                 y_a, y_wall )
4518
4519                         ENDIF
4520                      ENDIF
4521                   ELSEIF ( il > ip ) THEN
4522!
4523!--                   south right quadrant: look for north left corner
4524                      IF ( jl < jp ) THEN
4525                         IF ( BTEST( obstacle_flags(jl,il), 7 ) ) THEN
4526!
4527!--                         calculate coordinates of the corner of said gridcell
4528!--                         that is closest to the current agent
4529                            x_wall = il*dx
4530                            y_wall = (jl+1)*dy
4531
4532                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4533                                                                 y_a, y_wall )
4534
4535                         ENDIF
4536!
4537!--                   north right quadrant: look for south left corner
4538                      ELSEIF ( jl > jp ) THEN
4539                         IF ( BTEST( obstacle_flags(jl,il), 5 ) ) THEN
4540!
4541!--                         calculate coordinates of the corner of said gridcell
4542!--                         that is closest to the current agent
4543                            x_wall = il*dx
4544                            y_wall = jl*dy
4545
4546                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4547                                                                 y_a, y_wall )
4548
4549                         ENDIF
4550                      ENDIF
4551                   ENDIF
4552                ENDDO
4553             ENDDO
4554
4555          CASE DEFAULT
4556
4557       END SELECT
4558
4559    END SUBROUTINE mas_timestep_social_forces
4560
4561!------------------------------------------------------------------------------!
4562! Description:
4563! ------------
4564!> Given a distance to the current agent, calculates the force a found corner
4565!> or wall exerts on that agent
4566!------------------------------------------------------------------------------!
4567    SUBROUTINE mas_timestep_wall_corner_force( xa, xw, ya, yw )
4568
4569       IMPLICIT NONE
4570
4571       REAL(wp) ::  dist_l     !< distance to obstacle
4572       REAL(wp) ::  force_d_x  !< increment of social force, x-direction
4573       REAL(wp) ::  force_d_y  !< increment of social force, x-direction
4574       REAL(wp) ::  xa         !< x-position of agent
4575       REAL(wp) ::  xw         !< x-position of wall
4576       REAL(wp) ::  ya         !< x-position of agent
4577       REAL(wp) ::  yw         !< y-position of wall
4578
4579       force_d_x = 0.0_wp
4580       force_d_y = 0.0_wp
4581!
4582!--    calculate coordinates of corner relative to agent
4583!--    postion and distance between corner and agent
4584       xw = xa - xw
4585       yw = ya - yw
4586       dist_l = SQRT( (xw)**2 + (yw)**2 )
4587!
4588!--    calculate x and y component of repulsive force
4589!--    induced by previously found corner
4590       IF ( dist_l > 0 ) THEN
4591          force_d_x = repuls_wall * d_sigma_rep_wall         &
4592                      * EXP( -dist_l * d_sigma_rep_wall )      &
4593                      * xw / (dist_l)
4594          force_d_y = repuls_wall * d_sigma_rep_wall         &
4595                      * EXP( -dist_l * d_sigma_rep_wall )      &
4596                      * yw / (dist_l)
4597       ENDIF
4598
4599! !--    forces that are located outside of a sight radius of
4600! !--    200 degrees (-> COS(100./180.*pi) = COS(.555*pi)) of
4601! !--    current agent are considered to have an effect of 50%
4602!        IF ( force_d_x * agents(nl)%speed_e_x +               &
4603!             force_d_y * agents(nl)%speed_e_y <               &
4604!             SQRT(force_d_x**2 + force_d_y**2) *              &
4605!             COS( .55555555 * 3.1415 ) )                      &
4606!        THEN
4607!           force_d_x = force_d_x * .5_wp
4608!           force_d_y = force_d_y * .5_wp
4609!        ENDIF
4610
4611!
4612!--    add force increment to total force of current agent
4613       force_x = force_x + force_d_x
4614       force_y = force_y + force_d_y
4615
4616    END SUBROUTINE mas_timestep_wall_corner_force
4617
4618!
4619!-- Calculates distance of point P to edge (A,B). If A = B, calculates
4620!-- point-to-point distance from A/B to P
4621    FUNCTION dist_point_to_edge ( a_x, a_y, b_x, b_y, p_x, p_y )
4622
4623       IMPLICIT NONE
4624
4625       REAL(wp)  :: ab_x                !< x-coordinate of vector from A to B
4626       REAL(wp)  :: ab_y                !< y-coordinate of vector from A to B
4627       REAL(wp)  :: ab_d                !< inverse length of vector from A to B
4628       REAL(wp)  :: ab_u_x              !< x-coordinate of vector with direction of ab and length 1
4629       REAL(wp)  :: ab_u_y              !< y-coordinate of vector with direction of ab and length 1
4630       REAL(wp)  :: ba_x                !< x-coordinate of vector from B to A
4631       REAL(wp)  :: ba_y                !< y-coordinate of vector from B to A
4632       REAL(wp)  :: ap_x                !< x-coordinate of vector from A to P
4633       REAL(wp)  :: ap_y                !< y-coordinate of vector from A to P
4634       REAL(wp)  :: bp_x                !< x-coordinate of vector from B to P
4635       REAL(wp)  :: bp_y                !< y-coordinate of vector from B to P
4636       REAL(wp)  :: a_x                 !< x-coordinate of point A of edge
4637       REAL(wp)  :: a_y                 !< y-coordinate of point A of edge
4638       REAL(wp)  :: b_x                 !< x-coordinate of point B of edge
4639       REAL(wp)  :: b_y                 !< y-coordinate of point B of edge
4640       REAL(wp)  :: p_x                 !< x-coordinate of point P
4641       REAL(wp)  :: p_y                 !< y-coordinate of point P
4642       REAL(wp)  :: dist_x              !< x-coordinate of point P
4643       REAL(wp)  :: dist_y              !< y-coordinate of point P
4644       REAL(wp)  :: dist_point_to_edge  !< y-coordinate of point P
4645
4646       ab_x = - a_x + b_x
4647       ab_y = - a_y + b_y
4648       ba_x = - b_x + a_x 
4649       ba_y = - b_y + a_y 
4650       ap_x = - a_x + p_x
4651       ap_y = - a_y + p_y
4652       bp_x = - b_x + p_x
4653       bp_y = - b_y + p_y
4654
4655       IF ( ab_x * ap_x + ab_y * ap_y <= 0. ) THEN
4656          dist_point_to_edge = SQRT((a_x - p_x)**2 + (a_y - p_y)**2)
4657       ELSEIF ( ba_x * bp_x + ba_y * bp_y <= 0. ) THEN
4658          dist_point_to_edge = SQRT((b_x - p_x)**2 + (b_y - p_y)**2)
4659       ELSE
4660          ab_d = 1./SQRT((ab_x)**2+(ab_y)**2)
4661          ab_u_x = ab_x*ab_d
4662          ab_u_y = ab_y*ab_d
4663          dist_x = ap_x - (ap_x*ab_u_x+ap_y*ab_u_y)*ab_u_x
4664          dist_y = ap_y - (ap_x*ab_u_x+ap_y*ab_u_y)*ab_u_y
4665          dist_point_to_edge = SQRT( dist_x**2 + dist_y**2 )
4666       ENDIF
4667
4668    END FUNCTION dist_point_to_edge
4669
4670!
4671!-- Returns the heuristic between points A and B (currently the straight
4672!-- distance)
4673    FUNCTION heuristic ( ax, ay, bx, by )
4674
4675       IMPLICIT NONE
4676
4677       REAL(wp)  :: ax           !< x-coordinate of point A
4678       REAL(wp)  :: ay           !< y-coordinate of point A
4679       REAL(wp)  :: bx           !< x-coordinate of point B
4680       REAL(wp)  :: by           !< y-coordinate of point B
4681       REAL(wp)  :: heuristic    !< return value
4682
4683       heuristic = SQRT(( ax - bx )**2 + ( ay - by )**2)
4684
4685    END FUNCTION heuristic 
4686
4687!
4688!-- Calculates if point P is left of the infinite
4689!-- line that contains A and B (direction: A to B)
4690!-- Concept: 2D rotation of two vectors
4691    FUNCTION is_left ( ax, ay, bx, by, px, py )
4692
4693       IMPLICIT NONE
4694
4695       LOGICAL  :: is_left !< return value; TRUE if P is left of AB
4696
4697       REAL(wp)  :: ax     !< x-coordinate of point A
4698       REAL(wp)  :: ay     !< y-coordinate of point A
4699       REAL(wp)  :: bx     !< x-coordinate of point B
4700       REAL(wp)  :: by     !< y-coordinate of point B
4701       REAL(wp)  :: px     !< x-coordinate of point P
4702       REAL(wp)  :: py     !< y-coordinate of point P
4703
4704       is_left = (bx-ax)*(py-ay)-(px-ax)*(by-ay) > 0
4705       IF ( (ABS(ax-px) < .001 .AND. ABS(ay-py) < .001) .OR.                  &
4706            (ABS(bx-px) < .001 .AND. ABS(by-py) < .001) )                     &
4707       THEN
4708          is_left = .FALSE.
4709       ENDIF
4710
4711       RETURN
4712
4713    END FUNCTION is_left 
4714
4715!
4716!-- Calculates if point P is right of the infinite
4717!-- line that contains A and B (direction: A to B)
4718!-- Concept: 2D rotation of two vectors
4719    FUNCTION is_right ( ax, ay, bx, by, px, py )
4720
4721       IMPLICIT NONE
4722
4723       LOGICAL  :: is_right !< return value; TRUE if P is right of AB
4724
4725       REAL(wp), INTENT(IN)  :: ax     !< x-coordinate of point A
4726       REAL(wp), INTENT(IN)  :: ay     !< y-coordinate of point A
4727       REAL(wp), INTENT(IN)  :: bx     !< x-coordinate of point B
4728       REAL(wp), INTENT(IN)  :: by     !< y-coordinate of point B
4729       REAL(wp), INTENT(IN)  :: px     !< x-coordinate of point P
4730       REAL(wp), INTENT(IN)  :: py     !< y-coordinate of point P
4731
4732       is_right = (bx-ax)*(py-ay)-(px-ax)*(by-ay) < 0
4733       IF ( (ABS(ax-px) < .001 .AND. ABS(ay-py) < .001) .OR.                  &
4734            (ABS(bx-px) < .001 .AND. ABS(by-py) < .001) )                     &
4735       THEN
4736          is_right = .FALSE.
4737       ENDIF
4738
4739       RETURN
4740
4741    END FUNCTION is_right 
4742
4743!
4744!-- Returns true if the line segments AB and PQ share an intersection
4745    FUNCTION intersect ( ax, ay, bx, by, px, py, qx, qy )
4746
4747       IMPLICIT NONE
4748
4749       LOGICAL  :: intersect !< return value; TRUE if intersection was found
4750       LOGICAL  :: la        !< T if a is left of PQ
4751       LOGICAL  :: lb        !< T if b is left of PQ
4752       LOGICAL  :: lp        !< T if p is left of AB
4753       LOGICAL  :: lq        !< T if q is left of AB
4754       LOGICAL  :: poss      !< flag that indicates if an intersection is still possible
4755       LOGICAL  :: ra        !< T if a is right of PQ
4756       LOGICAL  :: rb        !< T if b is right of PQ
4757       LOGICAL  :: rp        !< T if p is right of AB
4758       LOGICAL  :: rq        !< T if q is right of AB
4759
4760       REAL(wp)  :: ax     !< x-coordinate of point A
4761       REAL(wp)  :: ay     !< y-coordinate of point A
4762       REAL(wp)  :: bx     !< x-coordinate of point B
4763       REAL(wp)  :: by     !< y-coordinate of point B
4764       REAL(wp)  :: px     !< x-coordinate of point P
4765       REAL(wp)  :: py     !< y-coordinate of point P
4766       REAL(wp)  :: qx     !< x-coordinate of point Q
4767       REAL(wp)  :: qy     !< y-coordinate of point Q
4768
4769       intersect = .FALSE.
4770       poss      = .FALSE.
4771!
4772!--    Intersection is possible only if P and Q are on opposing sides of AB
4773       lp = is_left(ax,ay,bx,by,px,py)
4774       rq = is_right(ax,ay,bx,by,qx,qy)
4775       IF ( lp .AND. rq ) poss = .TRUE.
4776       IF ( .NOT. poss ) THEN
4777          lq = is_left(ax,ay,bx,by,qx,qy)
4778          rp = is_right(ax,ay,bx,by,px,py)
4779          IF ( lq .AND. rp ) poss = .TRUE.
4780       ENDIF
4781!
4782!--    Intersection occurs only if above test (poss) was true AND
4783!--    A and B are on opposing sides of PQ
4784       IF ( poss ) THEN
4785          la = is_left(px,py,qx,qy,ax,ay)
4786          rb = is_right(px,py,qx,qy,bx,by)
4787          IF ( la .AND. rb ) intersect = .TRUE.
4788          IF ( .NOT. intersect ) THEN
4789             lb = is_left(px,py,qx,qy,bx,by)
4790             ra = is_right(px,py,qx,qy,ax,ay)
4791             IF ( lb .AND. ra ) intersect = .TRUE.
4792          ENDIF
4793       ENDIF
4794
4795       RETURN
4796
4797    END FUNCTION intersect 
4798
4799!
4800!-- Gives a nuber randomly distributed around an average
4801    FUNCTION random_normal ( avg, variation )
4802
4803       IMPLICIT NONE
4804
4805       REAL(wp)  :: avg            !< x-coordinate of vector from A to B
4806       REAL(wp)  :: variation      !< y-coordinate of vector from A to B
4807       REAL(wp)  :: random_normal  !< y-coordinate of vector from A to B
4808
4809       REAL(wp), DIMENSION(12)  :: random_arr  !< inverse length of vector from A to B
4810
4811       CALL RANDOM_NUMBER(random_arr)
4812       random_normal = avg + variation*(SUM(random_arr)-6.)
4813
4814    END FUNCTION random_normal
4815
4816
4817 END MODULE multi_agent_system_mod
Note: See TracBrowser for help on using the repository browser.