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

Last change on this file since 4177 was 4168, checked in by suehring, 5 years ago

Replace get_topography_top_index functions by pre-calculated arrays in order to save computational resources

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