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

Last change on this file since 3634 was 3602, checked in by sward, 5 years ago

document_changes from previous commit

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