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

Last change on this file since 4398 was 4346, checked in by motisi, 4 years ago

Introduction of wall_flags_total_0, which currently sets bits based on static topography information used in wall_flags_static_0

  • Property svn:keywords set to Id
File size: 196.5 KB
Line 
1!> @file multi_agent_system_mod.f90
2!--------------------------------------------------------------------------------!
3! This file is part of PALM-4U.
4!
5! PALM-4U is free software: you can redistribute it and/or modify it under the
6! terms of the GNU General Public License as published by the Free Software
7! Foundation, either version 3 of the License, or (at your option) any later
8! version.
9!
10! PALM-4U is distributed in the hope that it will be useful, but WITHOUT ANY
11! WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12! A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13!
14! You should have received a copy of the GNU General Public License along with
15! PALM. If not, see <http://www.gnu.org/licenses/>.
16!
17! Copyright 2016-2019 Leibniz Universitaet Hannover
18!------------------------------------------------------------------------------!
19!
20! Current revisions:
21! ------------------
22!
23!
24! Former revisions:
25! -----------------
26! $Id: multi_agent_system_mod.f90 4346 2019-12-18 11:55:56Z gronemeier $
27! Removed wall_flags_static_0 from USE statements as it's not used within
28! the module
29!
30! 4329 2019-12-10 15:46:36Z motisi
31! Renamed wall_flags_0 to wall_flags_static_0
32!
33! 4307 2019-11-26 14:12:36Z maronga
34! Activated output of iPT
35!
36! 4182 2019-08-22 15:20:23Z scharf
37! Corrected "Former revisions" section
38!
39! 4168 2019-08-16 13:50:17Z suehring
40! Replace function get_topography_top_index by topo_top_ind
41!
42! 3987 2019-05-22 09:52:13Z kanani
43! Introduce alternative switch for debug output during timestepping
44!
45! 3885 2019-04-11 11:29:34Z kanani
46! Changes related to global restructuring of location messages and introduction
47! of additional debug messages
48!
49! 3876 2019-04-08 18:41:49Z knoop
50! replaced nspec by nvar: only variable species should bconsidered, fixed species are not relevant
51!
52! 3766 2019-02-26 16:23:41Z raasch
53! save attribute added to local targets to avoid outlive pointer target warning
54!
55! 3665 2019-01-10 08:28:24Z raasch
56! unused variables removed
57!
58! 3159 2018-07-20 11:20:01Z sward
59! Initial revision
60!
61!
62!
63! Authors:
64! --------
65! @author sward
66!
67!
68! Description:
69! ------------
70!> Multi Agent System for the simulation of pedestrian movement in urban
71!> environments
72!------------------------------------------------------------------------------!
73 MODULE multi_agent_system_mod
74
75    USE, INTRINSIC ::  ISO_C_BINDING
76
77    USE basic_constants_and_equations_mod,                                     &
78        ONLY:  pi
79
80    USE control_parameters,                                                    &
81        ONLY:  biometeorology,                                                 &
82               debug_output_timestep,                                          &
83               dt_3d,                                                          &
84               dt_write_agent_data,                                            &
85               message_string,                                                 &
86               time_since_reference_point
87
88    USE cpulog,                                                                &
89        ONLY:  cpu_log, log_point, log_point_s
90
91    USE grid_variables,                                                        &
92        ONLY:  ddx, ddy, dx, dy
93
94    USE indices,                                                               &
95        ONLY:  nx, nxl, nxlg, nxr, nxrg, ny, nyn, nyng, nys, nysg, nzb,        &
96               topo_top_ind
97               
98    USE random_function_mod,                                                   &
99        ONLY:  random_function
100
101    USE kinds
102
103    USE pegrid
104
105    CHARACTER(LEN=15) ::  bc_mas_lr = 'absorb'  !< left/right boundary condition
106    CHARACTER(LEN=15) ::  bc_mas_ns = 'absorb'  !< north/south boundary condition
107
108    INTEGER(iwp) ::  deleted_agents = 0                !< number of deleted agents per time step
109    INTEGER(iwp) ::  dim_size_agtnum_manual = 9999999  !< namelist parameter (see documentation)
110    INTEGER(iwp) ::  heap_count                        !< number of items in binary heap (for pathfinding)
111    INTEGER(iwp) ::  ibc_mas_lr                        !< agent left/right boundary condition dummy
112    INTEGER(iwp) ::  ibc_mas_ns                        !< agent north/south boundary condition dummy
113!    INTEGER(iwp) ::  ind_pm10 = -9                     !< chemical species index of PM10
114!    INTEGER(iwp) ::  ind_pm25 = -9                     !< chemical species index of PM2.5
115    INTEGER(iwp) ::  iran_agent = -1234567             !< number for random generator
116    INTEGER(iwp) ::  min_nr_agent = 2                  !< namelist parameter (see documentation)
117    INTEGER(iwp) ::  ghla_count_recv                   !< number of agents in left ghost layer
118    INTEGER(iwp) ::  ghna_count_recv                   !< number of agents in north ghost layer
119    INTEGER(iwp) ::  ghra_count_recv                   !< number of agents in right ghost layer
120    INTEGER(iwp) ::  ghsa_count_recv                   !< number of agents in south ghost layer
121    INTEGER(iwp) ::  maximum_number_of_agents = 0      !< maximum number of agents during run
122    INTEGER(iwp) ::  nr_move_north                     !< number of agts to move north during exchange_horiz
123    INTEGER(iwp) ::  nr_move_south                     !< number of agts to move south during exchange_horiz
124    INTEGER(iwp) ::  number_of_agents = 0              !< number of agents for each grid box (3d array is saved on agt_count)
125    INTEGER(iwp) ::  number_of_agent_groups = 1        !< namelist parameter (see documentation)
126    INTEGER(iwp) ::  sort_count_mas = 0                !< counter for sorting agents
127    INTEGER(iwp) ::  agt_path_size = 15                !< size of agent path array
128    INTEGER(iwp) ::  step_dealloc_mas = 100            !< namelist parameter (see documentation)
129    INTEGER(iwp) ::  total_number_of_agents            !< total number of agents in the whole model domain
130
131    INTEGER(iwp), PARAMETER ::  NR_2_direction_move = 10000 !< parameter for agent exchange
132    INTEGER(iwp), PARAMETER ::  PHASE_INIT    = 1           !< phase parameter
133    INTEGER(iwp), PARAMETER ::  PHASE_RELEASE = 2           !< phase parameter
134
135    INTEGER(iwp), PARAMETER ::  max_number_of_agent_groups = 100 !< maximum allowed number of agent groups
136
137    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  agt_count         !< 3d array of number of agents of every grid box
138    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  s_measure_height  !< k-index(s-grid) for measurement
139    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  top_top_s         !< k-index of first s-gridpoint above topography
140    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  top_top_w         !< k-index of first v-gridpoint above topography
141    INTEGER(iwp), DIMENSION(:,:), ALLOCATABLE ::  obstacle_flags    !< flags to identify corners and edges of topography that cannot be crossed by agents
142
143    LOGICAL ::  deallocate_memory_mas = .TRUE.          !< namelist parameter (see documentation)
144    LOGICAL ::  dt_3d_reached_mas                       !< flag: agent timestep has reached model timestep
145    LOGICAL ::  dt_3d_reached_l_mas                     !< flag: agent timestep has reached model timestep
146    LOGICAL ::  agents_active = .FALSE.                 !< flag for agent system
147    LOGICAL ::  random_start_position_agents = .TRUE.   !< namelist parameter (see documentation)
148    LOGICAL ::  read_agents_from_restartfile = .FALSE.  !< namelist parameter (see documentation)
149    LOGICAL ::  agent_own_timestep = .FALSE.            !< namelist parameter (see documentation)
150
151    LOGICAL, DIMENSION(max_number_of_agent_groups) ::  a_rand_target = .FALSE. !< namelist parameter (see documentation)
152
153    REAL(wp) ::  agent_maximum_age = 9999999.9_wp          !< namelist parameter (see documentation)
154    REAL(wp) ::  agent_substep_time = 0.0_wp               !< time measurement during one LES timestep
155    REAL(wp) ::  alloc_factor_mas = 20.0_wp                !< namelist parameter (see documentation)
156    REAL(wp) ::  coll_t_0 = 3.                             !< namelist parameter (see documentation)
157    REAL(wp) ::  corner_gate_start = 0.5_wp                !< namelist parameter (see documentation)
158    REAL(wp) ::  corner_gate_width = 1.0_wp                !< namelist parameter (see documentation)
159    REAL(wp) ::  dim_size_factor_agtnum = 1.0_wp           !< namelist parameter (see documentation)
160    REAL(wp) ::  d_sigma_rep_agent                         !< inverse of sigma_rep_agent
161    REAL(wp) ::  d_sigma_rep_wall                          !< inverse of sigma_rep_wall
162    REAL(wp) ::  d_tau_accel_agent                         !< inverse of tau_accel_agent
163    REAL(wp) ::  desired_speed = 1.2_wp                    !< namelist parameter (see documentation)
164    REAL(wp) ::  des_sp_sig = .2_wp                        !< namelist parameter (see documentation)
165    REAL(wp) ::  dist_target_reached = 2.0_wp              !< distance at which target counts as reached
166    REAL(wp) ::  dist_to_int_target = .25_wp               !< namelist parameter (see documentation)
167    REAL(wp) ::  dt_agent = 0.02_wp                        !< namelist parameter (see documentation)
168    REAL(wp) ::  dt_arel = 9999999.9_wp                    !< namelist parameter (see documentation)
169    REAL(wp) ::  end_time_arel = 9999999.9_wp              !< namelist parameter (see documentation)
170    REAL(wp) ::  force_x                                   !< dummy value for force on current agent in x-direction
171    REAL(wp) ::  force_y                                   !< dummy value for force on current agent in y-direction
172    REAL(wp) ::  max_dist_from_path = 0.25_wp              !< distance from current path at which a new path is calculated
173    REAL(wp) ::  radius_agent = .25_wp                     !< namelist parameter (see documentation)
174    REAL(wp) ::  repuls_agent = 1.5_wp                     !< namelist parameter (see documentation)
175    REAL(wp) ::  repuls_wall = 7.0_wp                      !< namelist parameter (see documentation)
176    REAL(wp) ::  scan_radius_agent = 3.0_wp                !< namelist parameter (see documentation)
177    REAL(wp) ::  scan_radius_wall = 2.0_wp                 !< namelist parameter (see documentation)
178    REAL(wp) ::  sigma_rep_agent = 0.3_wp                  !< namelist parameter (see documentation)
179    REAL(wp) ::  sigma_rep_wall = 0.1_wp                   !< namelist parameter (see documentation)
180    REAL(wp) ::  tau_accel_agent = 0.5_wp                  !< namelist parameter (see documentation)
181    REAL(wp) ::  time_arel = 0.0_wp                        !< time for agent release
182    REAL(wp) ::  time_write_agent_data = 0.0_wp            !< write agent data at current time on file
183    REAL(wp) ::  v_max_agent = 1.3_wp                      !< namelist parameter (see documentation)
184
185    REAL(wp), DIMENSION(:), ALLOCATABLE ::  dummy_path_x  !<  dummy path (x-coordinate)
186    REAL(wp), DIMENSION(:), ALLOCATABLE ::  dummy_path_y  !<  dummy path (y-coordinate)
187
188    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  adx = 9999999.9_wp  !< namelist parameter (see documentation)
189    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  ady = 9999999.9_wp  !< namelist parameter (see documentation)
190    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  asl = 9999999.9_wp  !< namelist parameter (see documentation)
191    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  asn = 9999999.9_wp  !< namelist parameter (see documentation)
192    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  asr = 9999999.9_wp  !< namelist parameter (see documentation)
193    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  ass = 9999999.9_wp  !< namelist parameter (see documentation)
194    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  at_x = 9999999.9_wp !< namelist parameter (see documentation)
195    REAL(wp), DIMENSION(max_number_of_agent_groups) ::  at_y = 9999999.9_wp !< namelist parameter (see documentation)
196!
197!-- Type for the definition of an agent
198    TYPE agent_type
199        INTEGER(iwp) ::  block_nr             !< number for sorting
200        INTEGER(iwp) ::  group                !< number of agent group
201        INTEGER(idp) ::  id                   !< particle ID (64 bit integer)
202        INTEGER(iwp) ::  path_counter         !< current target along path (path_x/y)
203        LOGICAL      ::  agent_mask           !< if this parameter is set to false the agent will be deleted
204        REAL(wp)     ::  age                  !< age of agent
205        REAL(wp)     ::  age_m                !< age of agent
206        REAL(wp)     ::  dt_sum               !< sum of agents subtimesteps
207        REAL(wp)     ::  clo                  !< clothing index
208        REAL(wp)     ::  energy_storage       !< energy stored by agent
209        REAL(wp)     ::  clothing_temp        !< energy stored by agent
210        REAL(wp)     ::  actlev               !< metabolic + work energy of the person
211        REAL(wp)     ::  age_years            !< physical age of the person
212        REAL(wp)     ::  weight               !< total weight of the person (kg)
213        REAL(wp)     ::  height               !< height of the person (m)
214        REAL(wp)     ::  work                 !< workload of the agent (W)
215        INTEGER(iwp) ::  sex                  !< agents gender: 1 = male, 2 = female
216        REAL(wp)     ::  force_x              !< force term x-direction
217        REAL(wp)     ::  force_y              !< force term y-direction
218        REAL(wp)     ::  origin_x             !< origin x-position of agent
219        REAL(wp)     ::  origin_y             !< origin y-position of agent
220        REAL(wp)     ::  pm10                 !< PM10 concentration at agent position
221        REAL(wp)     ::  pm25                 !< PM25 concentration at agent position
222        REAL(wp)     ::  speed_abs            !< absolute value of agent speed
223        REAL(wp)     ::  speed_e_x            !< normalized speed of agent in x
224        REAL(wp)     ::  speed_e_y            !< normalized speed of agent in y
225        REAL(wp)     ::  speed_des            !< agent's desired speed
226        REAL(wp)     ::  speed_x              !< speed of agent in x
227        REAL(wp)     ::  speed_y              !< speed of agent in y
228        REAL(wp)     ::  ipt                  !< instationary thermal index iPT (degree_C)
229        REAL(wp)     ::  windspeed            !< absolute value of windspeed at agent position
230        REAL(wp)     ::  x                    !< x-position
231        REAL(wp)     ::  y                    !< y-position
232        REAL(wp)     ::  t                    !< temperature
233        REAL(wp)     ::  t_x                  !< x-position
234        REAL(wp)     ::  t_y                  !< y-position
235        REAL(wp), DIMENSION(0:15) ::  path_x  !< agent path to target (x)
236        REAL(wp), DIMENSION(0:15) ::  path_y  !< agent path to target (y)
237    END TYPE agent_type
238
239    TYPE(agent_type), DIMENSION(:), POINTER ::  agents               !< Agent array for this grid cell
240    TYPE(agent_type)                        ::  zero_agent           !< zero agent to avoid weird thing
241    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  move_also_north  !< for agent exchange between PEs
242    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  move_also_south  !< for agent exchange between PEs
243    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_l         !< ghost layer left of pe domain
244    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_n         !< ghost layer north of pe domain
245    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_r         !< ghost layer right of pe domain
246    TYPE(agent_type), DIMENSION(:), ALLOCATABLE ::  agt_gh_s         !< ghost layer south of pe domain
247!
248!-- Type for 2D grid on which agents are stored
249    TYPE  grid_agent_def
250        INTEGER(iwp), DIMENSION(0:3)            ::  start_index        !< start agent index for current block
251        INTEGER(iwp), DIMENSION(0:3)            ::  end_index          !< end agent index for current block
252        INTEGER(iwp)                            ::  id_counter         !< agent id counter (removeable?)
253        LOGICAL                                 ::  time_loop_done     !< timestep loop for agent advection
254        TYPE(agent_type), POINTER, DIMENSION(:) ::  agents             !< Particle array for this grid cell
255    END TYPE grid_agent_def
256
257    TYPE(grid_agent_def), DIMENSION(:,:), ALLOCATABLE, TARGET ::  grid_agents !< 2D grid on which agents are stored
258!
259!-- Item in a priority queue (binary heap)
260    TYPE heap_item
261       INTEGER(iwp) ::  mesh_id       !< id of the submitted mesh point
262       REAL(wp)     ::  priority      !< priority of the mesh point (= distance so far + heuristic to goal)
263    END TYPE heap_item
264
265    TYPE(heap_item), DIMENSION(:), ALLOCATABLE ::  queue  !< priority queue realized as binary heap
266!
267!-- Type for mesh point in visibility graph
268    TYPE  mesh_point
269        INTEGER(iwp)                            ::  polygon_id          !< Polygon the point belongs to
270        INTEGER(iwp)                            ::  vertex_id           !< Vertex in the polygon
271        INTEGER(iwp)                            ::  noc                 !< number of connections
272        INTEGER(iwp)                            ::  origin_id           !< ID of previous mesh point on path (A*)
273        INTEGER(iwp), DIMENSION(:), ALLOCATABLE ::  connected_vertices  !< Index of connected vertices
274        REAL(wp)                                ::  cost_so_far         !< Cost to reach this mesh point (A*)
275        REAL(wp)                                ::  x                   !< x-coordinate
276        REAL(wp)                                ::  y                   !< y-coordinate
277        REAL(wp)                                ::  x_s                 !< corner shifted outward from building by 1m (x)
278        REAL(wp)                                ::  y_s                 !< corner shifted outward from building by 1m (y)
279        REAL(wp), DIMENSION(:), ALLOCATABLE     ::  distance_to_vertex  !< Distance to each vertex
280    END TYPE mesh_point
281
282    TYPE(mesh_point), DIMENSION(:), ALLOCATABLE ::  mesh     !< navigation mesh
283    TYPE(mesh_point), DIMENSION(:), ALLOCATABLE ::  tmp_mesh !< temporary navigation mesh
284!
285!-- Vertex of a polygon
286    TYPE  vertex_type
287        LOGICAL               ::  delete  !< Flag to mark vertex for deletion
288        REAL(wp)              ::  x       !< x-coordinate
289        REAL(wp)              ::  y       !< y-coordinate
290    END TYPE vertex_type
291!
292!-- Polygon containing a number of vertices
293    TYPE  polygon_type
294        INTEGER(iwp)                                 ::  nov       !< Number of vertices in this polygon
295        TYPE(vertex_type), DIMENSION(:), ALLOCATABLE ::  vertices  !< Array of vertices
296    END TYPE polygon_type
297
298    TYPE(polygon_type), DIMENSION(:), ALLOCATABLE ::  polygons  !< Building data in polygon form
299
300    SAVE
301
302    PRIVATE
303!
304!-- Public functions
305    PUBLIC mas_init, mas_last_actions, mas_parin, multi_agent_system
306
307!
308!-- Public parameters, constants and initial values
309    PUBLIC agents_active
310
311    INTERFACE mas_parin
312       MODULE PROCEDURE mas_parin
313    END INTERFACE mas_parin
314
315    INTERFACE mas_init
316       MODULE PROCEDURE mas_init
317    END INTERFACE mas_init
318
319    INTERFACE mas_last_actions
320       MODULE PROCEDURE mas_last_actions
321    END INTERFACE mas_last_actions
322
323    INTERFACE multi_agent_system
324       MODULE PROCEDURE multi_agent_system
325    END INTERFACE multi_agent_system
326
327    CONTAINS
328
329
330!------------------------------------------------------------------------------!
331! Description:
332! ------------
333!> Multi Agent System:
334!> executes a number of agents sub-timesteps until the model timestep is reached.
335!> The agent timestep is usually smaller than the model timestep
336!------------------------------------------------------------------------------!
337 SUBROUTINE multi_agent_system
338
339    USE biometeorology_mod,                                                    &
340        ONLY:  bio_calc_ipt,                                                   &
341               bio_calculate_mrt_grid,                                         &
342               bio_get_thermal_index_input_ij
343
344
345    IMPLICIT NONE
346
347    INTEGER(iwp)       ::  i                  !< counter
348    INTEGER(iwp)       ::  ie                 !< counter
349    INTEGER(iwp)       ::  is                 !< counter
350    INTEGER(iwp)       ::  j                  !< counter
351    INTEGER(iwp)       ::  je                 !< counter
352    INTEGER(iwp)       ::  js                 !< counter
353    INTEGER(iwp), SAVE ::  mas_count = 0      !< counts the mas-calls
354    INTEGER(iwp)                :: a     !< agent iterator
355    !-- local meteorological conditions
356    REAL(wp)                    :: tmrt  !< mean radiant temperature        (degree_C)
357    REAL(wp)                    :: ta    !< air temperature                 (degree_C)
358    REAL(wp)                    :: vp    !< vapour pressure                 (hPa)
359    REAL(wp)                    :: v     !< wind speed    (local level)     (m/s)
360    REAL(wp)                    :: pair  !< air pressure                    (hPa)
361
362
363    LOGICAL       ::  first_loop_stride   !< flag for first loop stride of agent sub-timesteps
364    LOGICAL, SAVE ::  first_call = .TRUE. !< first call of mas flag for output
365
366
367    IF ( debug_output_timestep )  CALL debug_message( 'multi_agent_system', 'start' )
368
369    CALL cpu_log( log_point(9), 'mas', 'start' )
370!
371!-- Initialize variables for the next (sub-) timestep, i.e., for marking
372!-- those agents to be deleted after the timestep
373    deleted_agents = 0
374    agent_substep_time = 0.0_wp
375!
376!-- If necessary, release new set of agents
377    IF ( time_arel >= dt_arel  .AND.  end_time_arel > time_since_reference_point )  THEN
378
379       CALL mas_create_agent(PHASE_RELEASE)
380!
381!--    The MOD function allows for changes in the output interval with
382!--    restart runs.
383       time_arel = MOD( time_arel, MAX( dt_arel, dt_3d ) )
384
385    ENDIF
386
387    first_loop_stride = .TRUE.
388    grid_agents(:,:)%time_loop_done = .TRUE.
389!
390!-- Set timestep variable
391    IF ( .NOT. agent_own_timestep ) dt_agent = dt_3d
392!
393!-- Timestep loop for agent transport.
394!-- This loop has to be repeated until the transport time of every agent
395!-- (within the total domain!) has reached the LES timestep (dt_3d).
396!-- Timestep scheme is Euler-forward
397    DO
398!
399!--    Write agent data at current time on file.
400       time_write_agent_data = time_write_agent_data + dt_agent
401       agent_substep_time    = agent_substep_time    + dt_agent
402       IF ( time_write_agent_data >= dt_write_agent_data )  THEN
403#if defined( __netcdf )
404          IF ( first_loop_stride ) CALL mas_get_prognostic_quantities
405          CALL mas_data_output_agents ( first_call )
406#else
407          WRITE( message_string, * ) 'NetCDF is needed for agent output. ',    &
408                                     'Set __netcdf in compiler options'
409          CALL message( 'multi_agent_system', 'PA0071', 1, 2, 0, 6, 0 )
410#endif
411          IF(first_call) first_call = .FALSE.
412          time_write_agent_data = time_write_agent_data - dt_write_agent_data
413       ENDIF
414!
415!--    Flag is true by default, will be set to false if an agent has not yet
416!--    reached the model timestep
417       grid_agents(:,:)%time_loop_done = .TRUE.
418
419!
420!--    First part of agent transport:
421!--    Evaluate social forces for all agents at current positions
422       CALL cpu_log( log_point_s(9), 'mas_social_forces', 'start' )
423       DO  i = nxl, nxr
424          DO  j = nys, nyn
425
426             number_of_agents = agt_count(j,i)
427!
428!--          If grid cell is empty, cycle
429             IF ( number_of_agents <= 0 ) CYCLE
430
431             agents => grid_agents(j,i)%agents(1:number_of_agents)
432!
433!--          Evaluation of social forces
434             CALL mas_timestep_forces_call(i,j)
435
436          ENDDO
437       ENDDO
438       CALL cpu_log( log_point_s(9), 'mas_social_forces', 'stop' )
439!
440!--    Second part of agent transport:
441!--    timestep
442       CALL cpu_log( log_point_s(16), 'mas_timestep', 'start' )
443       DO  i = nxl, nxr
444          DO  j = nys, nyn
445
446             number_of_agents = agt_count(j,i)
447!
448!--          If grid cell is empty, flag must be true
449             IF ( number_of_agents <= 0 )  THEN
450                grid_agents(j,i)%time_loop_done = .TRUE.
451                CYCLE
452             ENDIF
453
454             agents => grid_agents(j,i)%agents(1:number_of_agents)
455
456             agents(1:number_of_agents)%agent_mask = .TRUE.
457!
458!--          Initialize the variable storing the total time that an agent
459!--          has advanced within the timestep procedure
460             IF ( first_loop_stride )  THEN
461                agents(1:number_of_agents)%dt_sum = 0.0_wp
462             ENDIF
463!
464!--          Initialize the switch used for the loop exit condition checked
465!--          at the end of this loop. If at least one agent has failed to
466!--          reach the LES timestep, this switch will be set false in
467!--          mas_transport.
468             dt_3d_reached_l_mas = .TRUE.
469!
470!--          Timestep
471             CALL mas_timestep
472!
473!--          Delete agents that have been simulated longer than allowed
474             CALL mas_boundary_conds( 'max_sim_time' )
475!
476!--          Delete agents that have reached target area
477             CALL mas_boundary_conds( 'target_area' )
478!
479!---         If not all agents of the actual grid cell have reached the
480!--          LES timestep, this cell has to to another loop iteration. Due to
481!--          the fact that agents can move into neighboring grid cell,
482!--          these neighbor cells also have to perform another loop iteration
483             IF ( .NOT. dt_3d_reached_l_mas )  THEN
484                js = MAX(nys,j-1)
485                je = MIN(nyn,j+1)
486                is = MAX(nxl,i-1)
487                ie = MIN(nxr,i+1)
488                grid_agents(js:je,is:ie)%time_loop_done = .FALSE.
489             ENDIF
490
491          ENDDO
492       ENDDO
493       CALL cpu_log( log_point_s(16), 'mas_timestep', 'stop' )
494
495!
496!--    Find out, if all agents on every PE have completed the LES timestep
497!--    and set the switch corespondingly
498       dt_3d_reached_l_mas = ALL(grid_agents(:,:)%time_loop_done)
499#if defined( __parallel )
500       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
501       CALL MPI_ALLREDUCE( dt_3d_reached_l_mas, dt_3d_reached_mas, 1, MPI_LOGICAL, &
502                           MPI_LAND, comm2d, ierr )
503#else
504       dt_3d_reached_mas = dt_3d_reached_l_mas
505#endif
506
507!
508!--    Increment time since last release
509       IF ( dt_3d_reached_mas )  time_arel = time_arel + dt_3d
510
511!
512!--    Move Agents local to PE to a different grid cell
513       CALL cpu_log( log_point_s(18), 'mas_move_exch_sort', 'start' )
514       CALL mas_eh_move_agent
515!
516!--    Horizontal boundary conditions including exchange between subdmains
517       CALL mas_eh_exchange_horiz
518!
519!--    Pack agents (eliminate those marked for deletion),
520!--    determine new number of agents
521       CALL mas_ps_sort_in_subboxes
522       CALL cpu_log( log_point_s(18), 'mas_move_exch_sort', 'stop' )
523!
524!--    Initialize variables for the next (sub-) timestep, i.e., for marking
525!--    those agents to be deleted after the timestep
526       deleted_agents = 0
527
528       IF ( biometeorology )  THEN
529!
530!--       Fill out the MRT 2D grid from appropriate source (RTM, RRTMG,...)
531          CALL bio_calculate_mrt_grid ( .FALSE. )
532!
533!--       Call of human thermal comfort mod (and UV exposure)
534          DO  i = nxl, nxr
535             DO  j = nys, nyn
536
537                number_of_agents = agt_count(j,i)
538!
539!--             If grid cell gets empty, cycle
540                IF ( number_of_agents <= 0 )  CYCLE
541
542                agents => grid_agents(j,i)%agents(1:number_of_agents)
543!
544!--             Evaluation of social forces
545!                CALL bio_dynamic( i, j )
546!
547!--             Determine local meteorological conditions
548                CALL bio_get_thermal_index_input_ij ( .FALSE., i, j, ta, vp,  &
549                                                      v, pair, tmrt )
550
551                DO  a = 1, number_of_agents
552!
553!--                Calculate instationary thermal indices based on local tmrt
554
555                   CALL bio_calc_ipt ( ta, vp, v, pair, tmrt,                 &
556                                       agents(a)%dt_sum,                      &
557                                       agents(a)%energy_storage,              &
558                                       agents(a)%clothing_temp,               &
559                                       agents(a)%clo,                         &
560                                       agents(a)%actlev,                      &
561                                       agents(a)%age_years,                   &
562                                       agents(a)%weight,                      &
563                                       agents(a)%height,                      &
564                                       agents(a)%work,                        &
565                                       agents(a)%sex,                         &
566                                       agents(a)%ipt )
567                END DO
568
569             ENDDO
570          ENDDO
571       ENDIF
572
573       IF ( dt_3d_reached_mas )  EXIT
574
575       first_loop_stride = .FALSE.
576    ENDDO   ! timestep loop
577
578!
579!-- Deallocate unused memory
580    IF ( deallocate_memory_mas  .AND.  mas_count == step_dealloc_mas )  THEN
581       CALL mas_eh_dealloc_agents_array
582       mas_count = 0
583    ELSEIF ( deallocate_memory_mas )  THEN
584       mas_count = mas_count + 1
585    ENDIF
586
587    CALL cpu_log( log_point(9), 'mas', 'stop' )
588
589    IF ( debug_output_timestep )  CALL debug_message( 'multi_agent_system', 'end' )
590
591
592 END SUBROUTINE multi_agent_system
593
594!------------------------------------------------------------------------------!
595! Description:
596! ------------
597!> Calculation of the direction vector from each agent to its current
598!> intermittent target
599!------------------------------------------------------------------------------!
600    SUBROUTINE mas_agent_direction
601
602       IMPLICIT NONE
603
604       LOGICAL ::  path_flag !< true if new path must be calculated
605
606       INTEGER(iwp) ::  n  !< loop variable over all agents in a grid box
607       INTEGER(iwp) ::  pc !< agent path counter
608
609       REAL(wp) ::  abs_dir         !< length of direction vector (for normalization)
610!       REAL(wp) ::  d_curr_target   !< rounding influence expressed as x speed component
611!       REAL(wp) ::  d_prev_target   !< rounding influence expressed as x speed component
612       REAL(wp) ::  dir_x           !< direction of agent (x)
613       REAL(wp) ::  dir_y           !< direction of agent (y)
614!       REAL(wp) ::  dist_round = 3. !< distance at which agents start rounding a corner
615       REAL(wp) ::  dtit            !< distance to intermittent target
616!       REAL(wp) ::  round_fac  = 0.2 !< factor for rounding influence
617!       REAL(wp) ::  speed_round_x   !< rounding influence expressed as x speed component
618!       REAL(wp) ::  speed_round_y   !< rounding influence expressed as x speed component
619
620!
621!--    loop over all agents in the current grid box
622       DO n = 1, number_of_agents
623          path_flag = .FALSE.
624          pc = agents(n)%path_counter
625!
626!--       If no path was calculated for agent yet, do it
627          IF ( pc >= 999 ) THEN
628             CALL mas_nav_find_path(n)
629             pc = agents(n)%path_counter
630!
631!--       Check if new path must be calculated and if so, do it
632          ELSE
633!
634!--          Case one: Agent has come close enough to intermittent target.
635!--                    -> chose new int target and calculate rest of path if no
636!--                       new intermittent targets are left
637             dtit = SQRT((agents(n)%x - agents(n)%path_x(pc))**2               &
638                       + (agents(n)%y - agents(n)%path_y(pc))**2)
639             IF ( dtit < dist_to_int_target ) THEN
640                agents(n)%path_counter = agents(n)%path_counter + 1
641                pc = agents(n)%path_counter
642!
643!--             Path counter out of scope (each agent can store a maximum of 15
644!--             intermittent targets on the way to her final target); new path
645!--             must be calculated
646                IF ( pc >= SIZE(agents(n)%path_x) ) THEN
647                   path_flag = .TRUE.
648                ENDIF
649!
650!--          Case two: Agent too far from path
651!--                    -> set flag for new path to be calculated
652             ELSEIF ( dist_point_to_edge(agents(n)%path_x(pc-1),               &
653                                         agents(n)%path_y(pc-1),               &
654                                         agents(n)%path_x(pc),                 &
655                                         agents(n)%path_y(pc),                 &
656                                         agents(n)%x, agents(n)%y)             &
657                      > max_dist_from_path )                                   &
658             THEN
659                path_flag = .TRUE.
660             ENDIF
661!
662!--          If either of the above two cases was true, calculate new path and
663!--          reset 0th path point. This point (the last target the agent had)
664!--          is needed for the agents rounding of corners and the calculation
665!--          of her deviation from her current path
666             IF ( path_flag ) THEN
667                CALL mas_nav_find_path(n)
668                pc = agents(n)%path_counter
669             ENDIF
670          ENDIF
671!
672!--       Normalize direction vector
673          abs_dir             = 1.0d-12
674          dir_x               = agents(n)%path_x(pc) - agents(n)%x
675          dir_y               = agents(n)%path_y(pc) - agents(n)%y
676          abs_dir             = SQRT(dir_x**2 + dir_y**2)+1.0d-12
677!--         needed later for corner rounding
678!           dir_x               = dir_x/abs_dir
679!           dir_y               = dir_y/abs_dir
680!           dir_x               = dir_x + speed_round_x
681!           dir_y               = dir_y + speed_round_y
682!           abs_dir             = SQRT(dir_x**2 + dir_y**2)+1.0d-12
683          agents(n)%speed_e_x = dir_x/abs_dir
684          agents(n)%speed_e_y = dir_y/abs_dir
685       ENDDO
686
687!
688!-- corner rounding; to be added
689!
690!--       Calculate direction change due to rounding of corners
691
692!           speed_round_x = 0.
693!           speed_round_y = 0.
694!           
695!           d_curr_target = SQRT( (agents(n)%path_x(pc) - agents(n)%x)**2 +      &
696!                                 (agents(n)%path_y(pc) - agents(n)%y)**2 )
697!           d_prev_target = SQRT( (agents(n)%path_x(pc-1) - agents(n)%x)**2 +    &
698!                                 (agents(n)%path_y(pc-1) - agents(n)%y)**2 )
699! !
700! !--       Agent is close to next target and that target is not the final one
701!           IF ( d_curr_target < dist_round .AND. dist_round <                   &
702!                           SQRT( (agents(n)%path_x(pc) - agents(n)%t_x)**2 +    &
703!                                 (agents(n)%path_y(pc) - agents(n)%t_y)**2 ) )  &
704!           THEN
705!              speed_round_x = (agents(n)%path_x(pc+1) - agents(n)%path_x(pc)) / &
706!                              ABS( agents(n)%path_x(pc)                         &
707!                                 - agents(n)%path_x(pc+1)) * round_fac *        &
708!                              SIN( pi/dist_round*d_curr_target )
709!              speed_round_y = (agents(n)%path_y(pc+1) - agents(n)%path_y(pc)) / &
710!                              ABS( agents(n)%path_y(pc)                         &
711!                                 - agents(n)%path_y(pc+1)) * round_fac *        &
712!                              SIN( pi/dist_round*d_curr_target )
713!           ENDIF
714!
715!           IF ( d_prev_target < dist_round ) THEN
716!              IF ( agents(n)%path_x(pc) /= agents(n)%path_x(pc+1) ) THEN
717!                 speed_round_x = speed_round_x +                                   &
718!                                 (agents(n)%path_x(pc) - agents(n)%path_x(pc+1)) / &
719!                                 ABS( agents(n)%path_x(pc)                         &
720!                                    - agents(n)%path_x(pc+1)) * round_fac *        &
721!                                 SIN( pi/dist_round*d_prev_target )
722!              ENDIF
723!             
724!              IF ( agents(n)%path_y(pc) /= agents(n)%path_y(pc+1) ) THEN
725!                 speed_round_y = speed_round_y +                                   &
726!                              (agents(n)%path_y(pc) - agents(n)%path_y(pc+1)) / &
727!                              ABS( agents(n)%path_y(pc)                         &
728!                                 - agents(n)%path_y(pc+1)) * round_fac *        &
729!                              SIN( pi/dist_round*d_prev_target )
730!              ENDIF
731             
732!           ENDIF
733
734
735    END SUBROUTINE mas_agent_direction
736
737!------------------------------------------------------------------------------!
738! Description:
739! ------------
740!> Boundary conditions for maximum time, target reached and out of domain
741!------------------------------------------------------------------------------!
742    SUBROUTINE mas_boundary_conds( location )
743
744       IMPLICIT NONE
745
746       CHARACTER (LEN=*) ::  location !< Identifier
747
748       INTEGER(iwp) ::  n   !< agent number
749       INTEGER(iwp) ::  grp !< agent group
750
751       REAL(wp) ::  dist_to_target !< distance to target
752
753       IF ( location == 'max_sim_time' )  THEN
754
755!
756!--       Delete agents that have been simulated longer than allowed
757          DO  n = 1, number_of_agents
758
759             IF ( agents(n)%age > agent_maximum_age  .AND.                     &
760                  agents(n)%agent_mask )                                       &
761             THEN
762                agents(n)%agent_mask  = .FALSE.
763                deleted_agents = deleted_agents + 1
764             ENDIF
765
766          ENDDO
767       ENDIF
768
769       IF ( location == 'target_area' )  THEN
770
771!
772!--       Delete agents that entered target region
773          DO  n = 1, number_of_agents
774             grp = agents(n)%group
775             dist_to_target = SQRT((agents(n)%x-at_x(grp))**2                  &
776                                 + (agents(n)%y-at_y(grp))**2)
777             IF ( dist_to_target < dist_target_reached ) THEN
778                agents(n)%agent_mask  = .FALSE.
779                deleted_agents = deleted_agents + 1
780             ENDIF
781
782          ENDDO
783       ENDIF
784
785    END SUBROUTINE mas_boundary_conds
786
787!------------------------------------------------------------------------------!
788! Description:
789! ------------
790!> Release new agents at their respective sources
791!------------------------------------------------------------------------------!
792    SUBROUTINE mas_create_agent (phase)
793
794       IMPLICIT  NONE
795
796       INTEGER(iwp) ::  alloc_size  !< relative increase of allocated memory for agents
797       INTEGER(iwp) ::  i           !< loop variable ( agent groups )
798       INTEGER(iwp) ::  ip          !< index variable along x
799       INTEGER(iwp) ::  jp          !< index variable along y
800       INTEGER(iwp) ::  loop_stride !< loop variable for initialization
801       INTEGER(iwp) ::  n           !< loop variable ( number of agents )
802       INTEGER(iwp) ::  new_size    !< new size of allocated memory for agents
803       INTEGER(iwp) ::  rn_side     !< index of agent path
804
805       INTEGER(iwp), INTENT(IN) ::  phase       !< mode of inititialization
806
807       INTEGER(iwp), DIMENSION(nysg:nyng,nxlg:nxrg) ::  local_count !< start address of new agent
808       INTEGER(iwp), DIMENSION(nysg:nyng,nxlg:nxrg) ::  local_start !< start address of new agent
809
810       LOGICAL ::  first_stride !< flag for initialization
811
812       REAL(wp) ::  pos_x       !< increment for agent position in x
813       REAL(wp) ::  pos_y       !< increment for agent position in y
814       REAL(wp) ::  rand_contr  !< dummy argument for random position
815       REAL(wp) ::  rn_side_dum !< index of agent path
816
817       TYPE(agent_type),TARGET ::  tmp_agent !< temporary agent used for initialization
818
819!
820!--    Calculate agent positions and store agent attributes, if
821!--    agent is situated on this PE
822       DO  loop_stride = 1, 2
823          first_stride = (loop_stride == 1)
824          IF ( first_stride )   THEN
825             local_count = 0           ! count number of agents
826          ELSE
827             local_count = agt_count   ! Start address of new agents
828          ENDIF
829
830          DO  i = 1, number_of_agent_groups
831
832             pos_y = ass(i)
833
834             DO WHILE ( pos_y <= asn(i) )
835
836                IF ( pos_y >= nys * dy  .AND.                                  &
837                           pos_y <  ( nyn + 1 ) * dy  )                        &
838                THEN
839
840                   pos_x = asl(i)
841
842            xloop: DO WHILE ( pos_x <= asr(i) )
843
844                      IF ( pos_x >= nxl * dx  .AND.                            &
845                                 pos_x <  ( nxr + 1) * dx )                    &
846                      THEN
847
848                         tmp_agent%agent_mask = .TRUE.
849                         tmp_agent%group         = i
850                         tmp_agent%id            = 0_idp
851                         tmp_agent%block_nr      = -1
852                         tmp_agent%path_counter  = 999 !SIZE(tmp_agent%path_x)
853                         tmp_agent%age           = 0.0_wp
854                         tmp_agent%age_m         = 0.0_wp
855                         tmp_agent%dt_sum        = 0.0_wp
856                         tmp_agent%clo           = -999.0_wp
857                         tmp_agent%energy_storage= 0.0_wp
858                         tmp_agent%ipt           = 99999.0_wp
859                         tmp_agent%clothing_temp = -999._wp      !< energy stored by agent (W)
860                         tmp_agent%actlev        = 134.6862_wp   !< metabolic + work energy of the person
861                         tmp_agent%age_years     = 35._wp        !< physical age of the person
862                         tmp_agent%weight        = 75._wp        !< total weight of the person (kg)
863                         tmp_agent%height        = 1.75_wp       !< height of the person (m)
864                         tmp_agent%work          = 134.6862_wp   !< workload of the agent (W)
865                         tmp_agent%sex           = 1             !< agents gender: 1 = male, 2 = female
866                         tmp_agent%force_x       = 0.0_wp
867                         tmp_agent%force_y       = 0.0_wp
868                         tmp_agent%origin_x      = pos_x
869                         tmp_agent%origin_y      = pos_y
870                         tmp_agent%speed_abs     = 0.0_wp
871                         tmp_agent%speed_e_x     = 0.0_wp
872                         tmp_agent%speed_e_y     = 0.0_wp
873                         tmp_agent%speed_des     = random_normal(desired_speed,&
874                                                                 des_sp_sig)
875                         tmp_agent%speed_x       = 0.0_wp
876                         tmp_agent%speed_y       = 0.0_wp
877                         tmp_agent%x             = pos_x
878                         tmp_agent%y             = pos_y
879                         tmp_agent%path_x        = -1.0_wp
880                         tmp_agent%path_y        = -1.0_wp
881                         tmp_agent%t_x           = - pi
882                         tmp_agent%t_y           = - pi
883!
884!--                      Determine the grid indices of the agent position
885                         ip = tmp_agent%x * ddx
886                         jp = tmp_agent%y * ddy
887!
888!--                      Give each agent its target
889                         IF ( a_rand_target(i) ) THEN
890!
891!--                         Agent shall receive random target just outside
892!--                         simulated area
893                            rn_side_dum = random_function(iran_agent)
894                            rn_side     = FLOOR(4.*rn_side_dum)
895                            IF ( rn_side < 2 ) THEN
896                               IF ( rn_side == 0 ) THEN
897                                  tmp_agent%t_y = -2*dy
898                               ELSE
899                                  tmp_agent%t_y = (ny+3)*dy
900                               ENDIF
901                               tmp_agent%t_x = random_function(iran_agent) *   &
902                                               (nx+1)*dx
903                            ELSE
904                               IF ( rn_side == 2 ) THEN
905                                  tmp_agent%t_x = -2*dx
906                               ELSE
907                                  tmp_agent%t_x = (nx+3)*dx
908                               ENDIF
909                               tmp_agent%t_y = random_function(iran_agent) *   &
910                                               (ny+1)*dy
911                            ENDIF
912!
913!--                      Agent gets target of her group
914                         ELSE
915                            tmp_agent%t_x = at_x(i)
916                            tmp_agent%t_y = at_y(i)
917                         ENDIF
918
919                         local_count(jp,ip) = local_count(jp,ip) + 1
920
921                         IF ( .NOT. first_stride )  THEN
922                            grid_agents(jp,ip)%agents(local_count(jp,ip))      &
923                                              = tmp_agent
924                         ENDIF
925
926                      ENDIF
927
928                      pos_x = pos_x + adx(i)
929
930                   ENDDO xloop
931
932                ENDIF
933
934                pos_y = pos_y + ady(i)
935
936             ENDDO
937
938          ENDDO
939
940!
941!--       Allocate or reallocate agents array to new size
942          IF ( first_stride )  THEN
943             DO  ip = nxlg, nxrg
944                DO  jp = nysg, nyng
945                   IF ( phase == PHASE_INIT )  THEN
946                      IF ( local_count(jp,ip) > 0 )  THEN
947                         alloc_size = MAX( INT( local_count(jp,ip) *           &
948                            ( 1.0_wp + alloc_factor_mas / 100.0_wp ) ),        &
949                            min_nr_agent )
950                      ELSE
951                         alloc_size = min_nr_agent
952                      ENDIF
953                      ALLOCATE(grid_agents(jp,ip)%agents(1:alloc_size))
954                      DO  n = 1, alloc_size
955                         grid_agents(jp,ip)%agents(n) = zero_agent
956                      ENDDO
957                   ELSEIF ( phase == PHASE_RELEASE )  THEN
958                      IF ( local_count(jp,ip) > 0 )  THEN
959                         new_size   = local_count(jp,ip) + agt_count(jp,ip)
960                         alloc_size = MAX( INT( new_size * ( 1.0_wp +          &
961                            alloc_factor_mas / 100.0_wp ) ), min_nr_agent )
962                         IF( alloc_size > SIZE( grid_agents(jp,ip)%agents) )   &
963                         THEN
964                            CALL mas_eh_realloc_agents_array(ip,jp,alloc_size)
965                         ENDIF
966                      ENDIF
967                   ENDIF
968                ENDDO
969             ENDDO
970          ENDIF
971
972       ENDDO
973
974       local_start = agt_count+1
975       agt_count   = local_count
976
977!
978!--    Calculate agent IDs
979       DO  ip = nxl, nxr
980          DO  jp = nys, nyn
981             number_of_agents = agt_count(jp,ip)
982             IF ( number_of_agents <= 0 )  CYCLE
983             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
984
985             DO  n = local_start(jp,ip), number_of_agents  !only new agents
986
987                agents(n)%id = 10000_idp**2 * grid_agents(jp,ip)%id_counter +  &
988                               10000_idp * jp + ip
989!
990!--             Count the number of agents that have been released before
991                grid_agents(jp,ip)%id_counter = grid_agents(jp,ip)%id_counter  &
992                                                + 1
993
994             ENDDO
995
996          ENDDO
997       ENDDO
998
999!
1000!--    Add random fluctuation to agent positions.
1001       IF ( random_start_position_agents )  THEN
1002          DO  ip = nxl, nxr
1003             DO  jp = nys, nyn
1004                number_of_agents = agt_count(jp,ip)
1005                IF ( number_of_agents <= 0 )  CYCLE
1006                agents => grid_agents(jp,ip)%agents(1:number_of_agents)
1007!
1008!--             Move only new agents. Moreover, limit random fluctuation
1009!--             in order to prevent that agents move more than one grid box,
1010!--             which would lead to problems concerning agent exchange
1011!--             between processors in case adx/ady are larger than dx/dy,
1012!--             respectively. 
1013                DO  n = local_start(jp,ip), number_of_agents
1014                   IF ( asl(agents(n)%group) /= asr(agents(n)%group) )  THEN
1015                      rand_contr = ( random_function( iran_agent ) - 0.5_wp ) *&
1016                                     adx(agents(n)%group)
1017                      agents(n)%x = agents(n)%x +                        &
1018                              MERGE( rand_contr, SIGN( dx, rand_contr ),       &
1019                                     ABS( rand_contr ) < dx                    &
1020                                   ) 
1021                   ENDIF
1022                   IF ( ass(agents(n)%group) /= asn(agents(n)%group) )  THEN
1023                      rand_contr = ( random_function( iran_agent ) - 0.5_wp ) *&
1024                                     ady(agents(n)%group)
1025                      agents(n)%y = agents(n)%y +                        &
1026                              MERGE( rand_contr, SIGN( dy, rand_contr ),       &
1027                                     ABS( rand_contr ) < dy )
1028                   ENDIF
1029                ENDDO
1030!
1031!--             Delete agents that have been simulated longer than allowed
1032                CALL mas_boundary_conds( 'max_sim_time' )
1033!
1034!--             Delete agents that have reached target area
1035                CALL mas_boundary_conds( 'target_area' )
1036
1037             ENDDO
1038          ENDDO
1039!
1040!--       Exchange agents between grid cells and processors
1041          CALL mas_eh_move_agent
1042          CALL mas_eh_exchange_horiz
1043
1044       ENDIF
1045!
1046!--    In case of random_start_position_agents, delete agents identified by
1047!--    mas_eh_exchange_horiz and mas_boundary_conds. Then sort agents into
1048!--    blocks, which is needed for a fast interpolation of the LES fields
1049!--    on the agent position.
1050       CALL mas_ps_sort_in_subboxes
1051
1052!
1053!--    Determine the current number of agents
1054       number_of_agents = 0
1055       DO  ip = nxl, nxr
1056          DO  jp = nys, nyn
1057             number_of_agents = number_of_agents + agt_count(jp,ip)
1058          ENDDO
1059       ENDDO
1060!
1061!--    Calculate the number of agents of the total domain
1062#if defined( __parallel )
1063       IF ( collective_wait )  CALL MPI_BARRIER( comm2d, ierr )
1064       CALL MPI_ALLREDUCE( number_of_agents, total_number_of_agents, 1, &
1065       MPI_INTEGER, MPI_SUM, comm2d, ierr )
1066#else
1067       total_number_of_agents = number_of_agents
1068#endif
1069
1070       RETURN
1071
1072    END SUBROUTINE mas_create_agent
1073
1074!------------------------------------------------------------------------------!
1075! Description:
1076! ------------
1077!> Creates flags that indicate if a gridbox contains edges or corners. These
1078!> flags are used for agents to check if obstacles are close to them.
1079!------------------------------------------------------------------------------!
1080    SUBROUTINE mas_create_obstacle_flags
1081
1082       USE arrays_3d,                                                          &
1083           ONLY:  zw
1084
1085       IMPLICIT NONE
1086
1087       INTEGER(iwp) ::  il
1088       INTEGER(iwp) ::  jl
1089
1090       ALLOCATE(obstacle_flags(nysg:nyng,nxlg:nxrg))
1091
1092       obstacle_flags = 0
1093
1094       DO il = nxlg, nxrg
1095          DO jl = nysg, nyng
1096!
1097!--          Exclude cyclic topography boundary
1098             IF ( il < 0 .OR. il > nx .OR. jl < 0 .OR. jl > ny ) CYCLE
1099!
1100!--          North edge
1101             IF ( jl < nyng ) THEN
1102                IF ( ( top_top_s(jl,il) - top_top_s(jl+1,il) ) > 1 .AND.       &
1103                     ( zw( top_top_w(jl,il) ) -                                &
1104                       zw( top_top_w(jl+1,il) ) ) > .51_wp )                   &
1105                THEN
1106                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 0 )
1107                ENDIF
1108             ENDIF
1109!
1110!--          North right corner
1111             IF ( jl < nyng .AND. il < nxrg ) THEN
1112                IF ( ( top_top_s(jl,il) - top_top_s(jl+1,il) )   > 1 .AND.     &
1113                     ( top_top_s(jl,il) - top_top_s(jl+1,il+1) ) > 1 .AND.     &
1114                     ( top_top_s(jl,il) - top_top_s(jl,il+1) )   > 1 .AND.     &
1115                     ( zw( top_top_w(jl,il) ) -                                &
1116                       zw( top_top_w(jl+1,il+1) ) ) > .51_wp )                 &
1117                THEN
1118                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 1 )
1119                ENDIF
1120             ENDIF
1121!
1122!--          Right edge
1123             IF ( il < nxrg ) THEN
1124                IF ( ( top_top_s(jl,il) - top_top_s(jl,il+1) ) > 1 .AND.       &
1125                     ( zw( top_top_w(jl,il) ) -                                &
1126                       zw( top_top_w(jl,il+1) ) ) > .51_wp )                   &
1127                THEN
1128                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 2 )
1129                ENDIF
1130             ENDIF
1131!
1132!--          South right corner
1133             IF ( jl > nysg .AND. il < nxrg ) THEN
1134                IF ( ( top_top_s(jl,il) - top_top_s(jl,il+1) )   > 1 .AND.     &
1135                     ( top_top_s(jl,il) - top_top_s(jl-1,il+1) ) > 1 .AND.     &
1136                     ( top_top_s(jl,il) - top_top_s(jl-1,il) )   > 1 .AND.     &
1137                     ( zw(top_top_w(jl,il)) -                                  &
1138                       zw( top_top_w(jl-1,il+1) ) ) > .51_wp )                 &
1139                THEN
1140                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 3 )
1141                ENDIF
1142             ENDIF
1143!
1144!--          South edge
1145             IF ( jl > nysg ) THEN
1146                IF ( ( top_top_s(jl,il) - top_top_s(jl-1,il) ) > 1 .AND.       &
1147                     ( zw( top_top_w(jl,il) ) -                                &
1148                       zw( top_top_w(jl-1,il) ) ) > .51_wp )                   &
1149                THEN
1150                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 4 )
1151                ENDIF
1152             ENDIF
1153!
1154!--          South left corner
1155             IF ( jl > nysg .AND. il > nxlg ) THEN
1156                IF ( ( top_top_s(jl,il) - top_top_s(jl-1,il) )   > 1 .AND.     &
1157                     ( top_top_s(jl,il) - top_top_s(jl-1,il-1) ) > 1 .AND.     &
1158                     ( top_top_s(jl,il) - top_top_s(jl,il-1) )   > 1 .AND.     &
1159                     ( zw( top_top_w(jl,il) ) -                                &
1160                       zw(top_top_w(jl-1,il-1) ) ) > .51_wp )                  &
1161                THEN
1162                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 5 )
1163                ENDIF
1164             ENDIF
1165!
1166!--          Left edge
1167             IF ( il > nxlg ) THEN
1168                IF ( ( top_top_s(jl,il) - top_top_s(jl,il-1) ) > 1 .AND.       &
1169                     ( zw(top_top_w(jl,il) ) -                                 &
1170                       zw(top_top_w(jl,il-1) ) ) > .51_wp )                 &
1171                THEN
1172                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 6 )
1173                ENDIF
1174             ENDIF
1175!
1176!--          North left corner
1177             IF ( jl < nyng .AND. il > nxlg ) THEN
1178                IF ( ( top_top_s(jl,il) - top_top_s(jl,il-1) )   > 1 .AND.     &
1179                     ( top_top_s(jl,il) - top_top_s(jl+1,il-1) ) > 1 .AND.     &
1180                     ( top_top_s(jl,il) - top_top_s(jl+1,il) )   > 1 .AND.     &
1181                     ( zw( top_top_w(jl,il) ) -                                &
1182                       zw( top_top_w(jl+1,il-1) ) ) > .51_wp )                 &
1183                THEN
1184                   obstacle_flags(jl,il) = IBSET( obstacle_flags(jl,il), 7 )
1185                ENDIF
1186             ENDIF
1187
1188          ENDDO
1189       ENDDO
1190
1191    END SUBROUTINE mas_create_obstacle_flags
1192
1193!------------------------------------------------------------------------------!
1194! Description:
1195! ------------
1196!> Write agent data in netCDF format
1197!------------------------------------------------------------------------------!
1198    SUBROUTINE mas_data_output_agents( ftest )
1199
1200       USE control_parameters,                                                 &
1201           ONLY:  agt_time_count, biometeorology, end_time, message_string,    &
1202                  multi_agent_system_end, multi_agent_system_start
1203
1204       USE netcdf_interface,                                                   &
1205           ONLY:  nc_stat, id_set_agt, id_var_time_agt,        &
1206                  id_var_agt, netcdf_handle_error
1207
1208       USE pegrid
1209
1210#if defined( __netcdf )
1211       USE NETCDF
1212#endif
1213       USE mas_global_attributes,                                              &
1214           ONLY:  dim_size_agtnum
1215
1216       IMPLICIT NONE
1217
1218       INTEGER(iwp) ::  agt_size !< Agent size in bytes
1219       INTEGER(iwp) ::  dummy    !< dummy
1220       INTEGER(iwp) ::  ii       !< counter (x)
1221       INTEGER(iwp) ::  ip       !< counter (x)
1222       INTEGER(iwp) ::  jp       !< counter (y)
1223       INTEGER(iwp) ::  n        !< counter (number of PEs)
1224       INTEGER(iwp) ::  noa      !< number of agents
1225       INTEGER(iwp) ::  noa_rcv  !< received number of agents
1226       INTEGER(iwp) ::  out_noa  !< number of agents for output
1227
1228       INTEGER(iwp), DIMENSION(0:numprocs-1) ::  noa_arr !< number of agents on each PE
1229!
1230!--    SAVE attribute required to avoid compiler warning about pointer outlive the pointer target
1231       TYPE(agent_type), DIMENSION(:), ALLOCATABLE, TARGET, SAVE ::  trf_agents !< all agents on current PE
1232       TYPE(agent_type), DIMENSION(:), ALLOCATABLE, TARGET, SAVE ::  out_agents !< all agents in entire domain
1233
1234       LOGICAL, INTENT (INOUT) :: ftest
1235
1236       LOGICAL, SAVE :: agt_dimension_exceeded = .FALSE.
1237
1238       CALL cpu_log( log_point_s(17), 'mas_data_output', 'start' )
1239!
1240!--    Get total number of agents and put all agents on one PE in one array
1241       noa = 0
1242       DO  ip = nxl, nxr
1243          DO  jp = nys, nyn
1244             noa  = noa  + agt_count(jp,ip)
1245          ENDDO
1246       ENDDO
1247       IF(noa > 0) THEN
1248          ALLOCATE(trf_agents(1:noa))
1249          dummy = 1
1250          DO  ip = nxl, nxr
1251             DO  jp = nys, nyn
1252                IF ( agt_count(jp,ip) == 0 ) CYCLE
1253                agents => grid_agents(jp,ip)%agents(1:agt_count(jp,ip))
1254                trf_agents(dummy:(dummy-1+agt_count(jp,ip))) = agents
1255                dummy = dummy + agt_count(jp,ip)
1256             ENDDO
1257          ENDDO
1258       ENDIF
1259#if defined( __parallel )
1260!
1261!--    Gather all agents on PE0 for output
1262       IF ( myid == 0 )  THEN
1263          noa_arr(0) = noa
1264!
1265!--       Receive data from all other PEs.
1266          DO  n = 1, numprocs-1
1267              CALL MPI_RECV( noa_arr(n), 1, MPI_INTEGER,                       &
1268                              n, 0, comm2d, status, ierr )
1269          ENDDO
1270       ELSE
1271          CALL MPI_SEND( noa, 1, MPI_INTEGER, 0, 0, comm2d, ierr )
1272       ENDIF
1273       CALL MPI_BARRIER( comm2d, ierr )
1274       agt_size = STORAGE_SIZE(zero_agent)/8
1275       IF ( myid == 0 )  THEN
1276!
1277!--       Receive data from all other PEs.
1278          out_noa = SUM(noa_arr)
1279          IF ( out_noa > 0 ) THEN
1280             ALLOCATE( out_agents(1:out_noa) )
1281             IF ( noa > 0 ) THEN
1282                out_agents(1:noa) = trf_agents
1283             ENDIF
1284             noa_rcv = noa
1285             DO n = 1, numprocs-1
1286                IF ( noa_arr(n) > 0 ) THEN
1287                   CALL MPI_RECV( out_agents(noa_rcv+1), noa_arr(n)*agt_size,  &
1288                                  MPI_BYTE, n, 0, comm2d, status, ierr )
1289                   noa_rcv = noa_rcv + noa_arr(n)
1290                ENDIF
1291             ENDDO
1292          ELSE
1293             ALLOCATE( out_agents(1:2) )
1294             out_agents = zero_agent
1295             out_noa    = 2
1296          ENDIF
1297       ELSE
1298          IF ( noa > 0 ) THEN
1299             CALL MPI_SEND( trf_agents(1), noa*agt_size, MPI_BYTE, 0, 0,       &
1300                                        comm2d, ierr )
1301          ENDIF
1302       ENDIF
1303!
1304!--    A barrier has to be set, because otherwise some PEs may
1305!--    proceed too fast so that PE0 may receive wrong data on
1306!--    tag 0
1307       CALL MPI_BARRIER( comm2d, ierr )
1308#endif
1309       IF ( myid == 0 ) THEN
1310#if defined( __parallel )
1311          agents => out_agents
1312#else
1313          agents => trf_agents
1314#endif
1315
1316#if defined( __netcdf )
1317!
1318!--       Update maximum number of agents
1319          maximum_number_of_agents = MAX(maximum_number_of_agents, out_noa)
1320!
1321!--       Output in netCDF format
1322          IF ( ftest ) THEN
1323!
1324!--          First, define size of agent number dimension from amount of agents
1325!--          released, release interval, time of agent simulation and max
1326!--          age of agents
1327             dim_size_agtnum = MIN( MIN( multi_agent_system_end, end_time )    &
1328                                       - multi_agent_system_start,             &
1329                                    agent_maximum_age)
1330
1331             DO ii = 1, number_of_agent_groups
1332                dim_size_agtnum = dim_size_agtnum                              &
1333                                + (FLOOR( ( asr(ii)-asl(ii) ) / adx(ii) ) + 1) &
1334                                * (FLOOR( ( asn(ii)-ass(ii) ) / ady(ii) ) + 1) &
1335                                * (FLOOR( dim_size_agtnum / dt_arel )     + 1) &
1336                                * dim_size_factor_agtnum
1337                dim_size_agtnum = MIN( dim_size_agtnum, dim_size_agtnum_manual )
1338             ENDDO
1339             CALL check_open( 118 )
1340          ENDIF
1341
1342!
1343!--       Update the NetCDF time axis
1344          agt_time_count = agt_time_count + 1
1345
1346          IF ( .NOT. agt_dimension_exceeded ) THEN
1347!
1348!--          if number of agents to be output exceeds dimension, set flag and
1349!--          print warning
1350             IF ( out_noa > dim_size_agtnum ) THEN
1351
1352                agt_dimension_exceeded = .TRUE.
1353                WRITE(message_string,'(A,F11.1,2(A,I8))')                      &
1354                                'Number of agents exceeds agent dimension.' // &
1355                                '&Starting at time_since_reference_point = ',  &
1356                                time_since_reference_point,                    &
1357                                ' s, &data may be missing.'//                  &
1358                                '&Number of agents:     ', out_noa,            &
1359                                '&Agent dimension size: ', dim_size_agtnum
1360
1361                CALL message( 'mas_data_output_agents',                        &
1362                              'PA0420', 0, 1, 0, 6, 0 )
1363
1364             ENDIF
1365          ENDIF
1366
1367!
1368!--       reduce number of output agents to dimension size, if necessary
1369          IF ( agt_dimension_exceeded ) THEN
1370
1371             out_noa = MIN( out_noa, dim_size_agtnum )
1372
1373          ENDIF
1374
1375          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_time_agt,                 &
1376                                  (/ time_since_reference_point + agent_substep_time /),            &
1377                                  start = (/ agt_time_count /),                &
1378                                  count = (/ 1 /) )
1379          CALL netcdf_handle_error( 'mas_data_output_agents', 1 )
1380
1381!
1382!--       Output agent attributes
1383
1384          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(1), agents%id,        &
1385                                  start = (/ 1, agt_time_count /),             &
1386                                  count = (/ out_noa /) )
1387          CALL netcdf_handle_error( 'mas_data_output_agents', 2 )
1388 
1389          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(2), agents%x,         &
1390                                  start = (/ 1, agt_time_count /),             &
1391                                  count = (/ out_noa /) )
1392          CALL netcdf_handle_error( 'mas_data_output_agents', 3 )
1393
1394          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(3), agents%y,         &
1395                                  start = (/ 1, agt_time_count /),             &
1396                                  count = (/ out_noa /) )
1397          CALL netcdf_handle_error( 'mas_data_output_agents', 4 )
1398
1399          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(4), agents%windspeed, &
1400                                  start = (/ 1, agt_time_count /),             &
1401                                  count = (/ out_noa /) )
1402          CALL netcdf_handle_error( 'mas_data_output_agents', 5 )
1403
1404          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(5), agents%t,         &
1405                                  start = (/ 1, agt_time_count /),             &
1406                                  count = (/ out_noa /) )
1407          CALL netcdf_handle_error( 'mas_data_output_agents', 6 )
1408
1409          nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(6), agents%group,     &
1410                                  start = (/ 1, agt_time_count /),             &
1411                                  count = (/ out_noa /) )
1412          CALL netcdf_handle_error( 'mas_data_output_agents', 7 )
1413
1414
1415          IF ( biometeorology )  THEN
1416             nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(7), agents%ipt,    &
1417                                     start = (/ 1, agt_time_count /),          &
1418                                     count = (/ out_noa /) )
1419             CALL netcdf_handle_error( 'mas_data_output_agents', 8 ) 
1420          ENDIF
1421         
1422
1423         
1424!           nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(8), agents%pm10,      &
1425!                                   start = (/ 1, agt_time_count /),             &
1426!                                   count = (/ out_noa /) )
1427!           CALL netcdf_handle_error( 'mas_data_output_agents', 9 )
1428!
1429!           nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(9), agents%pm25,      &
1430!                                   start = (/ 1, agt_time_count /),             &
1431!                                   count = (/ out_noa /) )
1432!           CALL netcdf_handle_error( 'mas_data_output_agents', 10 )
1433!
1434!
1435!           nc_stat = NF90_PUT_VAR( id_set_agt, id_var_agt(9), agents%uv,        &
1436!                                   start = (/ 1, agt_time_count /),             &
1437!                                   count = (/ out_noa /) )
1438!           CALL netcdf_handle_error( 'mas_data_output_agents', 10 )
1439
1440          CALL cpu_log( log_point_s(17), 'mas_data_output', 'stop' )
1441
1442
1443#endif
1444
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, exner
2766
2767       IMPLICIT NONE
2768
2769       INTEGER(iwp) ::  i_offset  !<  index offset for windspeed measurement
2770       INTEGER(iwp) ::  il        !<  x-index
2771       INTEGER(iwp) ::  is        !<  subgrid box counter
2772       INTEGER(iwp) ::  j_offset  !<  index offset for windspeed measurement
2773       INTEGER(iwp) ::  jl        !<  y-index
2774       INTEGER(iwp) ::  kl        !<  z-index
2775       INTEGER(iwp) ::  nl        !<  agent counter
2776       INTEGER(iwp) ::  se        !<  subgrid box end index
2777       INTEGER(iwp) ::  si        !<  subgrid box start index
2778
2779       REAL(wp) ::  u_a  !< windspeed at agent position (x)
2780       REAL(wp) ::  v_a  !< windspeed at agent position (y)
2781
2782       DO  il = nxl, nxr
2783          DO  jl = nys, nyn
2784
2785             number_of_agents = agt_count(jl,il)
2786!
2787!--          If grid cell is empty, cycle
2788             IF ( number_of_agents <= 0 ) CYCLE
2789             kl = s_measure_height(jl,il)
2790
2791             agents => grid_agents(jl,il)%agents(1:number_of_agents)
2792!
2793!--          loop over the four subgrid boxes
2794             DO is = 0,3
2795!
2796!--             Set indices
2797                si = grid_agents(jl,il)%start_index(is)
2798                se = grid_agents(jl,il)%end_index(is)
2799                DO nl = si, se
2800!
2801!--                Calculate index offset in x-direction:
2802!--                Left value if wall right of grid box
2803!--                Right value if wall left of grid box
2804!--                Else the one that is closer to the agent
2805                   IF ( BTEST( obstacle_flags( jl, il+1 ), 6 ) ) THEN
2806                      i_offset = 0
2807                   ELSEIF ( BTEST( obstacle_flags( jl, il-1 ), 2 ) ) THEN
2808                      i_offset = 1
2809                   ELSE
2810                      i_offset = MERGE( 0, 1, BTEST(is,1) )
2811                   ENDIF
2812                   u_a = u( kl, jl, il + i_offset )
2813!
2814!--                Calculate index offset in y-direction:
2815!--                South value if wall north of grid box
2816!--                North value if wall south of grid box
2817!--                Else the one that is closer to the agent
2818                   IF ( BTEST( obstacle_flags( jl+1, il ), 4 ) ) THEN
2819                      j_offset = 0
2820                   ELSEIF ( BTEST( obstacle_flags( jl-1, il ), 0 ) ) THEN
2821                      j_offset = 1
2822                   ELSE
2823                      j_offset = MERGE( 0, 1, BTEST(is,0) )
2824                   ENDIF
2825                   v_a = v( kl, jl + j_offset, il )
2826!
2827!--                Calculate windspeed at agent postion
2828                   agents(nl)%windspeed = SQRT(u_a**2 + v_a**2)
2829!
2830!--                Calculate temperature at agent position
2831                   agents(nl)%t = pt(kl,jl,il) * exner(kl)
2832
2833                ENDDO
2834
2835             ENDDO
2836
2837          ENDDO
2838       ENDDO
2839
2840    END SUBROUTINE mas_get_prognostic_quantities
2841
2842!------------------------------------------------------------------------------!
2843! Description:
2844! ------------
2845!> Adds an item to the priority queue (binary heap) at the correct position
2846!------------------------------------------------------------------------------!
2847    SUBROUTINE mas_heap_insert_item( id, priority )
2848
2849       IMPLICIT NONE
2850
2851       INTEGER(iwp) ::  cur_pos !< current position
2852       INTEGER(iwp) ::  id      !< mesh ID of item
2853
2854       REAL(wp) ::  priority !< item priority
2855
2856       TYPE(heap_item) ::  item !< heap item
2857
2858       item%mesh_id  = id
2859       item%priority = priority
2860!
2861!--    Extend heap, if necessary
2862       IF ( heap_count + 1 > SIZE(queue) ) THEN
2863          CALL mas_heap_extend
2864       ENDIF
2865!
2866!--    Insert item at first unoccupied postion (highest index) of heap
2867       cur_pos = heap_count
2868       queue(cur_pos) = item
2869!
2870!--    Sort while inserted item is not at top of heap
2871       DO WHILE ( cur_pos /= 0 )
2872!
2873!--       If priority < its parent's priority, swap them.
2874!--       Else, sorting is done.
2875          IF ( queue(cur_pos)%priority                                         &
2876              < queue(FLOOR((cur_pos)/2.))%priority )                          &
2877          THEN
2878             item = queue(cur_pos)
2879             queue(cur_pos) = queue(FLOOR((cur_pos)/2.))
2880             queue(FLOOR((cur_pos)/2.)) = item
2881             cur_pos = FLOOR((cur_pos)/2.)
2882          ELSE
2883             EXIT
2884          ENDIF
2885       ENDDO
2886!
2887!--    Item was added to heap, so the heap count increases
2888       heap_count = heap_count + 1
2889
2890    END SUBROUTINE mas_heap_insert_item
2891
2892!------------------------------------------------------------------------------!
2893! Description:
2894! ------------
2895!> Extends the size of the priority queue (binary heap)
2896!------------------------------------------------------------------------------!
2897    SUBROUTINE mas_heap_extend
2898
2899       IMPLICIT NONE
2900
2901       INTEGER(iwp) ::  soh !< size of heap
2902
2903       TYPE(heap_item), DIMENSION(:), ALLOCATABLE ::  dummy_heap !< dummy heap
2904
2905       soh = SIZE(queue)-1
2906       ALLOCATE(dummy_heap(0:soh))
2907       dummy_heap = queue
2908       DEALLOCATE(queue)
2909       ALLOCATE(queue(0:2*soh+1))
2910       queue(0:soh) = dummy_heap(0:soh)
2911
2912    END SUBROUTINE mas_heap_extend
2913
2914!------------------------------------------------------------------------------!
2915! Description:
2916! ------------
2917!> Removes first (smallest) element from the priority queue, reorders the rest
2918!> and returns the ID of the removed mesh point
2919!------------------------------------------------------------------------------!
2920    SUBROUTINE mas_heap_extract_item ( id )
2921
2922       IMPLICIT NONE
2923
2924       INTEGER(iwp) ::  id      !< ID of item extracted item
2925       INTEGER(iwp) ::  child   !< child of item in heap
2926       INTEGER(iwp) ::  cur_pos !< current position of item in heap
2927
2928       TYPE(heap_item) ::  dummy
2929!
2930!--    Get ID of mesh point with lowest priority (extracted item: top of heap)
2931       id = queue(0)%mesh_id
2932!
2933!--    Put last item in heap at first position
2934       queue(0) = queue(heap_count-1)
2935       cur_pos = 0
2936       DO
2937!
2938!--       If current item has no children, sorting is done
2939          IF( 2*cur_pos+1 > heap_count - 1 ) THEN
2940             EXIT
2941!
2942!--       If current item has only one child, check if item and its child are
2943!--       ordered correctly. Else, swap them.
2944          ELSEIF ( 2*cur_pos+2 > heap_count - 1 ) THEN
2945             IF ( queue(cur_pos)%priority > queue(2*cur_pos+1)%priority ) THEN
2946                dummy = queue(cur_pos)
2947                queue(cur_pos) = queue(2*cur_pos+1)
2948                queue(2*cur_pos+1) = dummy
2949                cur_pos = 2*cur_pos+1
2950             ELSE
2951                EXIT
2952             ENDIF
2953          ELSE
2954!
2955!--          determine the smaller child
2956             IF ( queue(2*cur_pos+1)%priority                                  &
2957                 >= queue(2*cur_pos+2)%priority )                              &
2958             THEN
2959                child = 2
2960             ELSE
2961                child = 1
2962             ENDIF
2963!
2964!--          Check if item and its smaller child are ordered falsely. If so,
2965!--          swap them. Else, sorting is done.
2966             IF ( queue(cur_pos)%priority > queue(2*cur_pos+child )%priority ) &
2967             THEN
2968                dummy = queue(cur_pos)
2969                queue(cur_pos) = queue(2*cur_pos+child)
2970                queue(2*cur_pos+child) = dummy
2971                cur_pos = 2*cur_pos+child
2972             ELSE
2973                EXIT
2974             ENDIF
2975          ENDIF
2976       ENDDO
2977!
2978!--    Top item was removed from heap, thus, heap_cout decreases by one
2979       heap_count = heap_count-1
2980
2981    END SUBROUTINE mas_heap_extract_item
2982
2983!------------------------------------------------------------------------------!
2984! Description:
2985! ------------
2986!> Initialization of Multi Agent System
2987!------------------------------------------------------------------------------!
2988    SUBROUTINE mas_init
2989
2990       USE control_parameters,                                                 &
2991           ONLY:  coupling_char, initializing_actions, io_blocks, io_group
2992
2993       USE arrays_3d,                                                          &
2994           ONLY:  zu, zw
2995
2996       USE indices,                                                            &
2997           ONLY:  nzt 
2998
2999       IMPLICIT NONE
3000
3001       INTEGER(iwp) ::  i             !< grid cell (x)
3002       INTEGER(iwp) ::  ii            !< io-block counter
3003       INTEGER(iwp) ::  il            !< io-block counter
3004       INTEGER(iwp) ::  jl            !< io-block counter
3005       INTEGER(iwp) ::  kl            !< io-block counter
3006       INTEGER(iwp) ::  kdum            !< io-block counter
3007       INTEGER(iwp) ::  locdum            !< io-block counter
3008       INTEGER(iwp) ::  j             !< grid cell (y)
3009       INTEGER(iwp) ::  size_of_mesh  !< temporary value for read
3010       INTEGER(iwp) ::  size_of_pols  !< temporary value for read
3011       INTEGER(iwp) ::  ioerr         !< IOSTAT flag for IO-commands ( 0 = no error )
3012
3013       LOGICAL ::  navigation_data_present  !< Flag: check for input file
3014
3015       REAL(wp) ::  zdum  !< dummy for measurement height
3016       REAL(wp) ::  avg_agt_height = 1.8_wp
3017
3018
3019!
3020!--    Check the number of agent groups.
3021       IF ( number_of_agent_groups > max_number_of_agent_groups )  THEN
3022          WRITE( message_string, * ) 'max_number_of_agent_groups =',      &
3023                                     max_number_of_agent_groups ,         &
3024                                     '&number_of_agent_groups reset to ', &
3025                                     max_number_of_agent_groups
3026          CALL message( 'mas_init', 'PA0072', 0, 1, 0, 6, 0 )
3027          number_of_agent_groups = max_number_of_agent_groups
3028       ENDIF
3029
3030!
3031!--    Set some parameters
3032       d_sigma_rep_agent = 1.0_wp/sigma_rep_agent
3033       d_sigma_rep_wall  = 1.0_wp/sigma_rep_wall
3034       d_tau_accel_agent = 1.0_wp/tau_accel_agent
3035       IF ( dt_agent /= 999.0_wp ) THEN
3036          agent_own_timestep = .TRUE.
3037       ENDIF
3038
3039!
3040!--    Get index of first grid box above topography
3041       ALLOCATE( top_top_s(nysg:nyng,nxlg:nxrg),                               &
3042                 top_top_w(nysg:nyng,nxlg:nxrg),                               &
3043                 s_measure_height(nys:nyn,nxl:nxr) )
3044!
3045!--    Get first index above topography for scalar grid and last index in
3046!--    topography for z-component of wind
3047       DO il = nxlg, nxrg
3048          DO jl = nysg, nyng
3049             top_top_s(jl,il) = topo_top_ind(jl,il,0) + 1
3050             top_top_w(jl,il) = topo_top_ind(jl,il,3)
3051          ENDDO
3052       ENDDO
3053!
3054!--    Create 2D array containing the index at which measurements are done by
3055!--    agents. The height of this measurement is given by avg_agt_height.
3056       DO il = nxl, nxr
3057          DO jl = nys, nyn
3058
3059             kdum = top_top_w(jl,il)
3060             zdum = zw(kdum)
3061             zdum = zdum + avg_agt_height
3062             locdum = 0
3063!
3064!--          Locate minimum distance from u-grid to measurement height (zdum)
3065             DO kl = 1, nzt
3066                IF ( ABS(zu(kl)-zdum) < ABS(zu(locdum)-zdum) ) locdum = kl
3067             ENDDO
3068             s_measure_height(jl,il) = locdum
3069
3070          ENDDO
3071       ENDDO
3072
3073       CALL mas_create_obstacle_flags
3074
3075!
3076!--    Set default start positions, if necessary
3077       IF ( asl(1) == 9999999.9_wp )  asl(1) = 0.0_wp
3078       IF ( asr(1) == 9999999.9_wp )  asr(1) = ( nx + 1 ) * dx
3079       IF ( ass(1) == 9999999.9_wp )  ass(1) = 0.0_wp
3080       IF ( asn(1) == 9999999.9_wp )  asn(1) = ( ny + 1 ) * dy
3081       IF ( adx(1) == 9999999.9_wp .OR. adx(1) == 0.0_wp ) adx(1) = dx
3082       IF ( ady(1) == 9999999.9_wp .OR. ady(1) == 0.0_wp ) ady(1) = dy
3083
3084       DO  j = 2, number_of_agent_groups
3085          IF ( asl(j) == 9999999.9_wp )  asl(j) = asl(j-1)
3086          IF ( asr(j) == 9999999.9_wp )  asr(j) = asr(j-1)
3087          IF ( ass(j) == 9999999.9_wp )  ass(j) = ass(j-1)
3088          IF ( asn(j) == 9999999.9_wp )  asn(j) = asn(j-1)
3089          IF ( adx(j) == 9999999.9_wp .OR. adx(j) == 0.0_wp ) adx(j) = adx(j-1)
3090          IF ( ady(j) == 9999999.9_wp .OR. ady(j) == 0.0_wp ) ady(j) = ady(j-1)
3091       ENDDO
3092
3093!
3094!--    Check boundary condition and set internal variables
3095       SELECT CASE ( bc_mas_lr )
3096
3097          CASE ( 'cyclic' )
3098             ibc_mas_lr = 0
3099
3100          CASE ( 'absorb' )
3101             ibc_mas_lr = 1
3102
3103          CASE DEFAULT
3104             WRITE( message_string, * ) 'unknown boundary condition ',         &
3105                                        'bc_mas_lr = "', TRIM( bc_mas_lr ), '"'
3106             CALL message( 'mas_init', 'PA0073', 1, 2, 0, 6, 0 )
3107
3108       END SELECT
3109       SELECT CASE ( bc_mas_ns )
3110
3111          CASE ( 'cyclic' )
3112             ibc_mas_ns = 0
3113
3114          CASE ( 'absorb' )
3115             ibc_mas_ns = 1
3116
3117          CASE DEFAULT
3118             WRITE( message_string, * ) 'unknown boundary condition ',         &
3119                                        'bc_mas_ns = "', TRIM( bc_mas_ns ), '"'
3120             CALL message( 'mas_init', 'PA0074', 1, 2, 0, 6, 0 )
3121
3122       END SELECT
3123
3124!
3125!--    For the first model run of a possible job chain initialize the
3126!--    agents, otherwise read the agent data from restart file.
3127       IF ( TRIM( initializing_actions ) == 'read_restart_data'                &
3128            .AND.  read_agents_from_restartfile )  THEN
3129
3130!           CALL mas_read_restart_file
3131
3132       ELSE
3133!
3134!--       Read preprocessed data of navigation mesh and building polygons
3135!--       for agent pathfinding
3136          DO ii = 0, io_blocks-1
3137             IF ( ii == io_group )  THEN
3138!
3139!--             Check for naviation input file and open it
3140                INQUIRE( FILE='NAVIGATION_DATA' // TRIM( coupling_char ), EXIST=navigation_data_present )
3141                IF ( .NOT. navigation_data_present )  THEN
3142                   message_string = 'Input file NAVIGATION_DATA' //                &
3143                                     TRIM( coupling_char ) // ' for MAS missing. ' // &
3144                                     '&Please run agent_preprocessing before the job to create it.'
3145                   CALL message( 'mas_init', 'PA0525', 1, 2, 0, 6, 0 )
3146                ENDIF
3147                OPEN ( 119, FILE='NAVIGATION_DATA'//TRIM( coupling_char ),     &
3148                            FORM='UNFORMATTED', IOSTAT=ioerr )
3149!
3150!--             Read mesh data
3151                READ(119) size_of_mesh
3152                ALLOCATE( mesh(1:size_of_mesh))
3153                DO i = 1, size_of_mesh
3154                   READ(119) mesh(i)%polygon_id, mesh(i)%vertex_id,            &
3155                             mesh(i)%noc, mesh(i)%origin_id,                   &
3156                             mesh(i)%cost_so_far, mesh(i)%x,                   &
3157                             mesh(i)%y, mesh(i)%x_s, mesh(i)%y_s
3158                   ALLOCATE( mesh(i)%connected_vertices(1:mesh(i)%noc),        &
3159                             mesh(i)%distance_to_vertex(1:mesh(i)%noc) )
3160                   DO j = 1, mesh(i)%noc
3161                      READ(119) mesh(i)%connected_vertices(j),                 &
3162                                mesh(i)%distance_to_vertex(j)
3163                   ENDDO
3164                ENDDO
3165!
3166!--             Read polygon data
3167                READ(119) size_of_pols
3168                ALLOCATE( polygons(1:size_of_pols) )
3169                DO i = 1, size_of_pols
3170                   READ(119) polygons(i)%nov
3171                   ALLOCATE( polygons(i)%vertices(0:polygons(i)%nov+1) )
3172                   DO j = 0, polygons(i)%nov+1
3173                      READ(119) polygons(i)%vertices(j)%delete,                &
3174                                polygons(i)%vertices(j)%x,                     &
3175                                polygons(i)%vertices(j)%y
3176                   ENDDO
3177                ENDDO
3178                CLOSE(119)
3179
3180             ENDIF
3181#if defined( __parallel ) && ! defined ( __check )
3182             CALL MPI_BARRIER( comm2d, ierr )
3183#endif
3184          ENDDO
3185
3186!
3187!--       Allocate agent arrays and set attributes of the initial set of
3188!--       agents, which can be also periodically released at later times.
3189          ALLOCATE( agt_count  (nysg:nyng,nxlg:nxrg),                          &
3190                    grid_agents(nysg:nyng,nxlg:nxrg) )
3191!
3192!--       Allocate dummy arrays for pathfinding
3193          ALLOCATE( dummy_path_x(0:agt_path_size),                 &
3194                    dummy_path_y(0:agt_path_size) )
3195
3196          number_of_agents = 0
3197          sort_count_mas   = 0
3198          agt_count        = 0
3199
3200!
3201!--       initialize counter for agent IDs
3202          grid_agents%id_counter = 1
3203
3204!
3205!--       Initialize all agents with dummy values (otherwise errors may
3206!--       occur within restart runs). The reason for this is still not clear
3207!--       and may be presumably caused by errors in the respective user-interface.
3208          zero_agent%agent_mask = .FALSE.
3209          zero_agent%block_nr      = -1
3210          zero_agent%group         = 0
3211          zero_agent%id            = 0_idp
3212          zero_agent%path_counter  = agt_path_size
3213          zero_agent%age           = 0.0_wp
3214          zero_agent%age_m         = 0.0_wp
3215          zero_agent%dt_sum        = 0.0_wp
3216          zero_agent%clo           = 0.0_wp
3217          zero_agent%energy_storage= 0.0_wp
3218          zero_agent%force_x       = 0.0_wp
3219          zero_agent%force_y       = 0.0_wp
3220          zero_agent%origin_x      = 0.0_wp
3221          zero_agent%origin_y      = 0.0_wp
3222          zero_agent%speed_abs     = 0.0_wp
3223          zero_agent%speed_e_x     = 0.0_wp
3224          zero_agent%speed_e_y     = 0.0_wp
3225          zero_agent%speed_des     = random_normal(desired_speed, des_sp_sig)
3226          zero_agent%speed_x       = 0.0_wp
3227          zero_agent%speed_y       = 0.0_wp
3228          zero_agent%ipt           = 0.0_wp
3229          zero_agent%x             = 0.0_wp
3230          zero_agent%y             = 0.0_wp
3231          zero_agent%path_x        = 0.0_wp
3232          zero_agent%path_y        = 0.0_wp
3233          zero_agent%t_x           = 0.0_wp
3234          zero_agent%t_y           = 0.0_wp
3235
3236!
3237!--    Set a seed value for the random number generator to be exclusively
3238!--    used for the agent code. The generated random numbers should be
3239!--    different on the different PEs.
3240          iran_agent = iran_agent + myid
3241
3242          CALL mas_create_agent (PHASE_INIT)
3243
3244       ENDIF
3245
3246!
3247!--    To avoid programm abort, assign agents array to the local version of
3248!--    first grid cell
3249       number_of_agents = agt_count(nys,nxl)
3250       agents => grid_agents(nys,nxl)%agents(1:number_of_agents)
3251
3252    END SUBROUTINE mas_init
3253
3254!------------------------------------------------------------------------------!
3255! Description:
3256! ------------
3257!> Output of informative message about maximum agent number
3258!------------------------------------------------------------------------------!
3259    SUBROUTINE mas_last_actions
3260
3261       USE control_parameters,                                                 &
3262           ONLY:  message_string
3263
3264       IMPLICIT NONE
3265
3266       WRITE(message_string,'(A,I8,A)')                                        &
3267                         'The maximumn number of agents during this run was',  &
3268                         maximum_number_of_agents,                             &
3269                         '&Consider adjusting the INPUT parameter'//           &
3270                         '&dim_size_agtnum_manual accordingly for the next run.'
3271
3272       CALL message( 'mas_data_output_agents', 'PA0457', 0, 0, 0, 6, 0 )
3273
3274    END SUBROUTINE mas_last_actions
3275
3276!------------------------------------------------------------------------------!
3277! Description:
3278! ------------
3279!> Finds the shortest path from a start position to a target position using the
3280!> A*-algorithm
3281!------------------------------------------------------------------------------!
3282    SUBROUTINE mas_nav_a_star( start_x, start_y, target_x, target_y, nsteps )
3283
3284       IMPLICIT NONE
3285
3286       LOGICAL ::  target_reached !< flag
3287
3288       INTEGER(iwp) ::  cur_node     !< current node of binary heap
3289       INTEGER(iwp) ::  il           !< counter (x)
3290       INTEGER(iwp) ::  neigh_node   !< neighbor node
3291       INTEGER(iwp) ::  node_counter !< binary heap node counter
3292       INTEGER(iwp) ::  path_ag      !< index of agent path
3293       INTEGER(iwp) ::  som          !< size of mesh
3294       INTEGER(iwp) ::  steps        !< steps along the path
3295       INTEGER(iwp) ::  nsteps        !< number of steps
3296
3297       REAL(wp) ::  start_x      !< x-coordinate agent
3298       REAL(wp) ::  start_y      !< y-coordinate agent
3299       REAL(wp) ::  new_cost     !< updated cost to reach node
3300       REAL(wp) ::  new_priority !< priority of node to be added to queue
3301       REAL(wp) ::  rn_gate      !< random number for corner gate
3302       REAL(wp) ::  target_x     !< x-coordinate target
3303       REAL(wp) ::  target_y     !< y-coordinate target
3304!
3305!--    Coordinate Type
3306       TYPE coord
3307          REAL(wp) ::  x   !< x-coordinate
3308          REAL(wp) ::  x_s !< x-coordinate (shifted)
3309          REAL(wp) ::  y   !< y-coordinate
3310          REAL(wp) ::  y_s !< y-coordinate (shifted)
3311       END TYPE coord
3312
3313       TYPE(coord), DIMENSION(:), ALLOCATABLE, TARGET ::  path     !< path array
3314       TYPE(coord), DIMENSION(:), ALLOCATABLE, TARGET ::  tmp_path !< temporary path for resizing
3315
3316       node_counter = 0
3317!
3318!--    Create temporary navigation mesh including agent and target positions
3319       CALL mas_nav_create_tmp_mesh( start_x, start_y, target_x, target_y, som )
3320       tmp_mesh(som)%cost_so_far = 0.0_wp
3321!
3322!--    Initialize priority queue
3323       heap_count = 0_iwp
3324       ALLOCATE(queue(0:100))
3325       target_reached = .FALSE.
3326!
3327!--    Add starting point (agent position) to frontier (the frontier consists
3328!--    of all the nodes that are to be visited. The node with the smallest
3329!--    priority will be visited first. The priority consists of the distance
3330!--    from the start node to this node plus a minimal guess (direct distance)
3331!--    from this node to the goal). For the starting node, the priority is set
3332!--    to 0, as it's the only node thus far
3333       CALL mas_heap_insert_item(som,0.0_wp)
3334       cur_node = som
3335       DO WHILE ( heap_count > 0 )
3336!
3337!--       Step one: Pick lowest priority item from queue
3338          node_counter = node_counter + 1
3339          CALL mas_heap_extract_item(cur_node)
3340!
3341!--       Node 0 is the goal node
3342          IF ( cur_node == 0 ) THEN
3343             EXIT
3344          ENDIF
3345!
3346!--       Loop over all of cur_node's neighbors
3347          DO il = 1, tmp_mesh(cur_node)%noc
3348             neigh_node = tmp_mesh(cur_node)%connected_vertices(il)
3349!
3350!--          Check, if the way from the start node to this neigh_node via
3351!--          cur_node is shorter than the previously found shortest path to it.
3352!--          If so, replace said cost and add neigh_node to the frontier.
3353!--          cost_so_far is initialized as 1.d12 so that all found distances
3354!--          should be smaller.
3355             new_cost   = tmp_mesh(cur_node)%cost_so_far                       &
3356                         + tmp_mesh(cur_node)%distance_to_vertex(il)
3357             IF ( new_cost < tmp_mesh(neigh_node)%cost_so_far ) THEN
3358                tmp_mesh(neigh_node)%cost_so_far = new_cost
3359                tmp_mesh(neigh_node)%origin_id   = cur_node
3360!
3361!--             Priority in the queue is cost_so_far + heuristic to goal
3362                new_priority = new_cost                                        &
3363                              + heuristic(tmp_mesh(neigh_node)%x,              &
3364                                tmp_mesh(neigh_node)%y, tmp_mesh(0)%x,         &
3365                                tmp_mesh(0)%y)
3366                CALL mas_heap_insert_item(neigh_node,new_priority)
3367             ENDIF
3368          ENDDO
3369       ENDDO
3370!
3371!--    Add nodes to a path array. To do this, we must backtrack from the target
3372!--    node to its origin to its origin and so on until an node is reached that
3373!--    has no origin (%origin_id == -1). This is the starting node.
3374       DEALLOCATE(queue)
3375       cur_node = 0
3376       steps = 0
3377       ALLOCATE(path(1:100))
3378       DO WHILE ( cur_node /= -1 )
3379          steps = steps + 1
3380!
3381!--       Resize path array if necessary
3382          IF ( steps > SIZE(path) ) THEN
3383             ALLOCATE(tmp_path(1:steps-1))
3384             tmp_path(1:steps-1) = path(1:steps-1)
3385             DEALLOCATE(path)
3386             ALLOCATE(path(1:2*(steps-1)))
3387             path(1:steps-1) = tmp_path(1:steps-1)
3388             DEALLOCATE(tmp_path)
3389          ENDIF
3390          path(steps)%x = tmp_mesh(cur_node)%x
3391          path(steps)%y = tmp_mesh(cur_node)%y
3392          path(steps)%x_s = tmp_mesh(cur_node)%x_s
3393          path(steps)%y_s = tmp_mesh(cur_node)%y_s
3394          cur_node = tmp_mesh(cur_node)%origin_id
3395       ENDDO
3396!
3397!--    Add calculated intermittent targets to the path until either the
3398!--    target or the maximum number of intermittent targets is reached.
3399!--    Ignore starting point (reduce index by one), it is agent position.
3400       dummy_path_x = -1
3401       dummy_path_y = -1
3402       path_ag = 1
3403       steps = steps - 1
3404       nsteps = 0
3405       DO WHILE( steps > 0 .AND. path_ag <= agt_path_size )
3406!
3407!--       Each target point is randomly chosen along a line target along the
3408!--       bisector of the building corner that starts at corner_gate_start
3409!--       and has a width of corner_gate_width. This is to avoid clustering
3410!--       when opposing agent groups try to reach the same corner target.
3411          rn_gate = random_function(iran_agent) * corner_gate_width            &
3412                                                + corner_gate_start
3413          dummy_path_x(path_ag) = path(steps)%x + rn_gate                      &
3414                         * (path(steps)%x_s - path(steps)%x)
3415          dummy_path_y(path_ag) = path(steps)%y + rn_gate                      &
3416                         * (path(steps)%y_s - path(steps)%y)
3417          steps = steps - 1
3418          path_ag = path_ag + 1
3419          nsteps = nsteps + 1
3420       ENDDO
3421!
3422!--    Set current intermittent target of this agent
3423       DEALLOCATE(tmp_mesh, path)
3424
3425    END SUBROUTINE mas_nav_a_star
3426
3427!------------------------------------------------------------------------------!
3428! Description:
3429! ------------
3430!> Adds a connection between two points of the navigation mesh
3431!> (one-way: in_mp1 to in_mp2)
3432!------------------------------------------------------------------------------!
3433    SUBROUTINE mas_nav_add_connection ( in_mp1, id2, in_mp2 )
3434
3435       IMPLICIT NONE
3436
3437       LOGICAL ::  connection_established  !< Flag to indicate if connection has already been established
3438
3439       INTEGER(iwp) ::  id2  !< ID of in_mp2
3440       INTEGER(iwp) ::  il   !< local counter
3441       INTEGER(iwp) ::  noc1 !< number of connections in in_mp1
3442
3443       INTEGER, DIMENSION(:), ALLOCATABLE ::  dum_cv !< dummy array for connected_vertices
3444
3445       REAL(wp) ::  dist  !< Distance between the two points
3446
3447       REAL(wp), DIMENSION(:), ALLOCATABLE ::  dum_dtv
3448
3449       TYPE(mesh_point) ::  in_mp1  !< mesh point that gets a new connection
3450       TYPE(mesh_point) ::  in_mp2  !< mesh point in_mp1 will be connected to
3451
3452       connection_established = .FALSE.
3453!
3454!--    Check if connection has already been established
3455       noc1 = SIZE(in_mp1%connected_vertices)
3456       DO il = 1, in_mp1%noc
3457          IF ( in_mp1%connected_vertices(il) == id2 ) THEN
3458             connection_established = .TRUE.
3459             EXIT
3460          ENDIF
3461       ENDDO
3462
3463       IF ( .NOT. connection_established ) THEN
3464!
3465!--       Resize arrays, if necessary
3466          IF ( in_mp1%noc >= noc1 ) THEN
3467             ALLOCATE( dum_cv(1:noc1),dum_dtv(1:noc1) )
3468             dum_cv  = in_mp1%connected_vertices
3469             dum_dtv = in_mp1%distance_to_vertex
3470             DEALLOCATE( in_mp1%connected_vertices, in_mp1%distance_to_vertex )
3471             ALLOCATE( in_mp1%connected_vertices(1:2*noc1),                    &
3472                       in_mp1%distance_to_vertex(1:2*noc1) )
3473             in_mp1%connected_vertices         = -999
3474             in_mp1%distance_to_vertex         = -999.
3475             in_mp1%connected_vertices(1:noc1) = dum_cv
3476             in_mp1%distance_to_vertex(1:noc1) = dum_dtv
3477          ENDIF
3478
3479!
3480!--       Add connection
3481          in_mp1%noc = in_mp1%noc+1
3482          dist = SQRT( (in_mp1%x - in_mp2%x)**2 + (in_mp1%y - in_mp2%y)**2 )
3483          in_mp1%connected_vertices(in_mp1%noc) = id2
3484          in_mp1%distance_to_vertex(in_mp1%noc) = dist
3485       ENDIF
3486
3487    END SUBROUTINE mas_nav_add_connection
3488
3489!------------------------------------------------------------------------------!
3490! Description:
3491! ------------
3492!> Adds a vertex (curren position of agent or target) to the existing tmp_mesh
3493!------------------------------------------------------------------------------!
3494    SUBROUTINE mas_nav_add_vertex_to_mesh ( in_mp, in_id )
3495
3496       IMPLICIT NONE
3497
3498       LOGICAL ::  intersection_found !< flag
3499
3500       INTEGER(iwp) ::  jl    !< mesh point counter
3501       INTEGER(iwp) ::  pl    !< polygon counter
3502       INTEGER(iwp) ::  vl    !< vertex counter
3503       INTEGER(iwp) ::  pid_t !< polygon id of tested mesh point
3504       INTEGER(iwp) ::  vid_t !< vertex id of tested mesh point
3505       INTEGER(iwp) ::  in_id !< vertex id of tested mesh point
3506
3507       REAL(wp) ::  v1x !< x-coordinate of test vertex 1 for intersection test
3508       REAL(wp) ::  v1y !< y-coordinate of test vertex 1 for intersection test
3509       REAL(wp) ::  v2x !< x-coordinate of test vertex 2 for intersection test
3510       REAL(wp) ::  v2y !< y-coordinate of test vertex 2 for intersection test
3511       REAL(wp) ::  x   !< x-coordinate of current mesh point
3512       REAL(wp) ::  x_t !< x-coordinate of tested mesh point
3513       REAL(wp) ::  y   !< y-coordinate of current mesh point
3514       REAL(wp) ::  y_t !< y-coordinate of tested mesh point
3515
3516       TYPE(mesh_point) ::  in_mp !< Input mesh point
3517!
3518!--
3519       x = in_mp%x
3520       y = in_mp%y
3521       DO jl = 0, SIZE(tmp_mesh)-2
3522          IF ( in_id == jl ) CYCLE
3523!
3524!--       Ignore mesh points with 0 connections
3525          IF ( tmp_mesh(jl)%polygon_id /= -1 ) THEN
3526             IF ( tmp_mesh(jl)%noc == 0 ) CYCLE
3527          ENDIF
3528          x_t = tmp_mesh(jl)%x
3529          y_t = tmp_mesh(jl)%y
3530          pid_t = tmp_mesh(jl)%polygon_id
3531          vid_t = tmp_mesh(jl)%vertex_id
3532!
3533!--       If the connecting line between the target and a mesh point points
3534!--       into the mesh point's polygon, no connection will be
3535!--       established between the two points. This is the case if the
3536!--       previous (next) vertex of the polygon is right of the connecting
3537!--       line and the next (previous) vertex of the polygon is left of the
3538!--       connecting line.
3539          IF ( pid_t > 0 .AND. pid_t <= SIZE(polygons) ) THEN
3540             IF ( (((is_left(x,y,x_t,y_t,polygons(pid_t)%vertices(vid_t-1)%x,  &
3541                                       polygons(pid_t)%vertices(vid_t-1)%y)    &
3542                  .AND. is_right(x,y,x_t,y_t,                                  &
3543                                       polygons(pid_t)%vertices(vid_t+1)%x,    &
3544                                       polygons(pid_t)%vertices(vid_t+1)%y) )  &
3545                  .OR. (is_right(x,y,x_t,y_t,                                  &
3546                                       polygons(pid_t)%vertices(vid_t-1)%x,    &
3547                                       polygons(pid_t)%vertices(vid_t-1)%y)    &
3548                  .AND. is_left(x,y,x_t,y_t,                                   &
3549                                       polygons(pid_t)%vertices(vid_t+1)%x,    &
3550                                       polygons(pid_t)%vertices(vid_t+1)%y)))))&
3551             THEN
3552                CYCLE
3553             ENDIF
3554          ENDIF
3555!
3556!--       For each edge of each polygon, check if it intersects with the
3557!--       potential connection. If at least one intersection is found,
3558!--       no connection can be made
3559          intersection_found = .FALSE.
3560          DO pl = 1, SIZE(polygons)
3561             DO vl = 1, polygons(pl)%nov
3562                v1x = polygons(pl)%vertices(vl)%x
3563                v1y = polygons(pl)%vertices(vl)%y
3564                v2x = polygons(pl)%vertices(vl+1)%x
3565                v2y = polygons(pl)%vertices(vl+1)%y
3566                intersection_found = intersect(x,y,x_t,y_t,v1x,v1y,v2x,v2y)
3567                IF ( intersection_found ) THEN
3568                   EXIT
3569                ENDIF
3570             ENDDO
3571             IF ( intersection_found ) EXIT
3572          ENDDO
3573          IF ( intersection_found ) CYCLE
3574!
3575!--       If neither of the above two test was true, a connection will be
3576!--       established between the two mesh points.
3577          CALL mas_nav_add_connection(in_mp,jl, tmp_mesh(jl))
3578          CALL mas_nav_add_connection(tmp_mesh(jl),in_id, in_mp)
3579       ENDDO
3580       CALL mas_nav_reduce_connections(in_mp)
3581
3582    END SUBROUTINE mas_nav_add_vertex_to_mesh
3583
3584!------------------------------------------------------------------------------!
3585! Description:
3586! ------------
3587!> Creates a temporary copy of the navigation mesh to be used for pathfinding
3588!------------------------------------------------------------------------------!
3589    SUBROUTINE mas_nav_create_tmp_mesh( a_x, a_y, t_x, t_y, som )
3590
3591       IMPLICIT NONE
3592
3593       INTEGER(iwp) ::  som !< size of mesh
3594       INTEGER(iwp) ::  noc !< number of connetions
3595       INTEGER(iwp) ::  im  !< local mesh point counter
3596
3597       REAL(wp) ::  a_x !< x-coordinate agent
3598       REAL(wp) ::  a_y !< y-coordinate agent
3599       REAL(wp) ::  t_x !< x-coordinate target
3600       REAL(wp) ::  t_y !< y-coordinate target
3601!
3602!--    give tmp_mesh the size of mesh
3603       som = SIZE(mesh)+1
3604       ALLOCATE(tmp_mesh(0:som))
3605!
3606!--    give the allocatable variables in tmp_mesh their respctive sizes
3607       DO im = 1, som-1
3608          noc = mesh(im)%noc
3609          ALLOCATE(tmp_mesh(im)%connected_vertices(1:noc))
3610          ALLOCATE(tmp_mesh(im)%distance_to_vertex(1:noc))
3611       ENDDO
3612!
3613!--    copy mesh to tmp_mesh
3614       tmp_mesh(1:som-1) = mesh(1:som-1)
3615!
3616!--    Add target point ...
3617       CALL mas_nav_init_mesh_point(tmp_mesh(0),-1_iwp,-1_iwp,t_x, t_y)
3618       CALL mas_nav_add_vertex_to_mesh(tmp_mesh(0),0_iwp)
3619!
3620!--    ... and start point to temp mesh
3621       CALL mas_nav_init_mesh_point(tmp_mesh(som),-1_iwp,-1_iwp,a_x, a_y)
3622       CALL mas_nav_add_vertex_to_mesh(tmp_mesh(som),som)
3623
3624    END SUBROUTINE mas_nav_create_tmp_mesh
3625   
3626
3627!------------------------------------------------------------------------------!
3628! Description:
3629! ------------
3630!> Finds the shortest path from an agents' position to her target. As the
3631!> actual pathfinding algorithm uses the obstacle corners and then shifts them
3632!> outward after pathfinding, cases can uccur in which the connection between
3633!> these intermittent targets then intersect with obstacles. To remedy this
3634!> the pathfinding algorithm is then run on every two subsequent intermittent
3635!> targets iteratively and new intermittent targets may be added to the path
3636!> this way.
3637!------------------------------------------------------------------------------!
3638    SUBROUTINE mas_nav_find_path( nl )
3639
3640       IMPLICIT NONE
3641
3642       INTEGER(iwp) ::  nl            !< local agent counter
3643       INTEGER(iwp) ::  il            !< local counter
3644       INTEGER(iwp) ::  jl            !< local counter
3645       INTEGER(iwp) ::  kl            !< local counter
3646       INTEGER(iwp) ::  nsteps_total  !< number of steps on path
3647       INTEGER(iwp) ::  nsteps_dummy  !< number of steps on path
3648       
3649       REAL(wp), DIMENSION(0:30) ::  ld_path_x !< local dummy agent path to target (x)
3650       REAL(wp), DIMENSION(0:30) ::  ld_path_y !< local dummy agent path to target (y)
3651!
3652!--    Initialize agent path arrays
3653       agents(nl)%path_x    = -1
3654       agents(nl)%path_y    = -1
3655       agents(nl)%path_x(0) = agents(nl)%x
3656       agents(nl)%path_y(0) = agents(nl)%y
3657!
3658!--    Calculate initial path
3659       CALL mas_nav_a_star( agents(nl)%x,   agents(nl)%y,                      &
3660                            agents(nl)%t_x, agents(nl)%t_y, nsteps_total )
3661!
3662!--    Set the rest of the agent path that was just calculated
3663       agents(nl)%path_x(1:nsteps_total) = dummy_path_x(1:nsteps_total)
3664       agents(nl)%path_y(1:nsteps_total) = dummy_path_y(1:nsteps_total)
3665!
3666!--    Iterate through found path and check more intermittent targets need
3667!--    to be added. For this, run pathfinding between every two consecutive
3668!--    intermittent targets.
3669       DO il = 0, MIN(agt_path_size-1, nsteps_total-1)
3670!
3671!--       pathfinding between two consecutive intermittent targets
3672          CALL mas_nav_a_star( agents(nl)%path_x(il),   agents(nl)%path_y(il), &
3673                              agents(nl)%path_x(il+1), agents(nl)%path_y(il+1),&
3674                              nsteps_dummy )
3675          nsteps_dummy = nsteps_dummy - 1
3676!
3677!--       If additional intermittent targets are found, add them to the path
3678          IF ( nsteps_dummy > 0 ) THEN
3679             ld_path_x = -1
3680             ld_path_y = -1
3681             ld_path_x(il+1:il+nsteps_dummy) = dummy_path_x(1:nsteps_dummy)
3682             ld_path_y(il+1:il+nsteps_dummy) = dummy_path_y(1:nsteps_dummy)
3683             kl = 1
3684             DO jl = il+1,nsteps_total
3685               ld_path_x( il+nsteps_dummy+kl ) = agents(nl)%path_x(jl)
3686               ld_path_y( il+nsteps_dummy+kl ) = agents(nl)%path_y(jl)
3687               kl = kl + 1
3688               IF ( kl > agt_path_size ) EXIT
3689             ENDDO
3690             nsteps_total = MIN(nsteps_total + nsteps_dummy, agt_path_size)
3691             agents(nl)%path_x(il+1:nsteps_total) = ld_path_x(il+1:nsteps_total)
3692             agents(nl)%path_y(il+1:nsteps_total) = ld_path_y(il+1:nsteps_total)
3693          ENDIF
3694
3695       ENDDO
3696!
3697!--    reset path counter to first intermittent target
3698       agents(nl)%path_counter = 1
3699
3700    END SUBROUTINE mas_nav_find_path
3701
3702!------------------------------------------------------------------------------!
3703! Description:
3704! ------------
3705!> Reduces the size of connection array to the amount of actual connections
3706!> after all connetions were added to a mesh point
3707!------------------------------------------------------------------------------!
3708    SUBROUTINE mas_nav_reduce_connections ( in_mp )
3709
3710       IMPLICIT NONE
3711
3712       INTEGER(iwp) ::  noc  !< number of connections
3713
3714       INTEGER, DIMENSION(:), ALLOCATABLE ::  dum_cv   !< dummy connected_vertices
3715
3716       REAL(wp), DIMENSION(:), ALLOCATABLE ::  dum_dtv !< dummy distance_to_vertex
3717
3718       TYPE(mesh_point) ::  in_mp
3719
3720       noc = in_mp%noc
3721       ALLOCATE( dum_cv(1:noc),dum_dtv(1:noc) )
3722       dum_cv  = in_mp%connected_vertices(1:noc)
3723       dum_dtv = in_mp%distance_to_vertex(1:noc)
3724       DEALLOCATE( in_mp%connected_vertices, in_mp%distance_to_vertex )
3725       ALLOCATE( in_mp%connected_vertices(1:noc),                    &
3726                 in_mp%distance_to_vertex(1:noc) )
3727       in_mp%connected_vertices(1:noc) = dum_cv(1:noc)
3728       in_mp%distance_to_vertex(1:noc) = dum_dtv(1:noc)
3729
3730    END SUBROUTINE mas_nav_reduce_connections
3731
3732!------------------------------------------------------------------------------!
3733! Description:
3734! ------------
3735!> Initializes a point of the navigation mesh
3736!------------------------------------------------------------------------------!
3737    SUBROUTINE mas_nav_init_mesh_point ( in_mp, pid, vid, x, y )
3738
3739       IMPLICIT NONE
3740
3741       INTEGER(iwp) ::  pid !< polygon ID
3742       INTEGER(iwp) ::  vid !< vertex ID
3743
3744       REAL(wp) ::  x !< x-coordinate
3745       REAL(wp) ::  y !< y-coordinate
3746
3747       TYPE(mesh_point) ::  in_mp !< mesh point to be initialized
3748
3749       in_mp%origin_id          = -1
3750       in_mp%polygon_id         = pid
3751       in_mp%vertex_id          = vid
3752       in_mp%cost_so_far        = 1.d12
3753       in_mp%x                  = x
3754       in_mp%y                  = y
3755       in_mp%x_s                = x
3756       in_mp%y_s                = y
3757       ALLOCATE(in_mp%connected_vertices(1:100),                               &
3758                in_mp%distance_to_vertex(1:100))
3759       in_mp%connected_vertices = -999
3760       in_mp%distance_to_vertex = -999.
3761       in_mp%noc                = 0
3762
3763    END SUBROUTINE mas_nav_init_mesh_point
3764
3765!------------------------------------------------------------------------------!
3766! Description:
3767! ------------
3768!> Reading of namlist from parin file
3769!------------------------------------------------------------------------------!
3770    SUBROUTINE mas_parin
3771
3772       USE control_parameters,                                                 &
3773           ONLY: agent_time_unlimited, multi_agent_system_end,                 &
3774                 multi_agent_system_start
3775
3776       IMPLICIT NONE
3777
3778       CHARACTER (LEN=80) ::  line  !<
3779
3780       NAMELIST /agent_parameters/  a_rand_target,                             &
3781                                    adx,                                       &
3782                                    ady,                                       &
3783                                    agent_maximum_age,                         &
3784                                    agent_time_unlimited,                      &
3785                                    alloc_factor_mas,                          &
3786                                    asl,                                       &
3787                                    asn,                                       &
3788                                    asr,                                       &
3789                                    ass,                                       &
3790                                    at_x,                                      &
3791                                    at_y,                                      &
3792                                    bc_mas_lr,                                 &
3793                                    bc_mas_ns,                                 &
3794                                    coll_t_0,                                  &
3795                                    corner_gate_start,                         &
3796                                    corner_gate_width,                         &
3797                                    dim_size_agtnum_manual,                    &
3798                                    dim_size_factor_agtnum,                    &
3799                                    deallocate_memory_mas,                     &
3800                                    dist_to_int_target,                        &
3801                                    dt_agent,                                  &
3802                                    dt_arel,                                   &
3803                                    dt_write_agent_data,                       &
3804                                    end_time_arel,                             &
3805                                    max_dist_from_path,                        &
3806                                    min_nr_agent,                              &
3807                                    multi_agent_system_end,                    &
3808                                    multi_agent_system_start,                  &
3809                                    number_of_agent_groups,                    &
3810                                    radius_agent,                              &
3811                                    random_start_position_agents,              &
3812                                    read_agents_from_restartfile,              &
3813                                    repuls_agent,                              &
3814                                    repuls_wall,                               &
3815                                    scan_radius_agent,                         &
3816                                    sigma_rep_agent,                           &
3817                                    sigma_rep_wall,                            &
3818                                    step_dealloc_mas,                          &
3819                                    tau_accel_agent
3820
3821!
3822!--    Try to find agent package
3823       REWIND ( 11 )
3824       line = ' '
3825       DO WHILE ( INDEX( line, '&agent_parameters' ) == 0 )
3826          READ ( 11, '(A)', END=20 )  line
3827       ENDDO
3828       BACKSPACE ( 11 )
3829
3830!
3831!--    Read user-defined namelist
3832       READ ( 11, agent_parameters, ERR = 10, END = 20 )
3833
3834!
3835!--    Set flag that indicates that agents are switched on
3836       agents_active = .TRUE.
3837       GOTO 20
3838
3839 10    BACKSPACE( 11 )
3840       READ( 11 , '(A)') line
3841       CALL parin_fail_message( 'agent_parameters', line )
3842
3843 20    CONTINUE
3844
3845    END SUBROUTINE mas_parin
3846
3847!------------------------------------------------------------------------------!
3848! Description:
3849! ------------
3850!> Routine for the whole processor
3851!> Sort all agents into the 4 respective subgrid boxes
3852!------------------------------------------------------------------------------!
3853    SUBROUTINE mas_ps_sort_in_subboxes
3854
3855       IMPLICIT NONE
3856
3857       INTEGER(iwp) ::  i           !< grid box (x)
3858       INTEGER(iwp) ::  ip          !< counter (x)
3859       INTEGER(iwp) ::  is          !< box counter
3860       INTEGER(iwp) ::  j           !< grid box (y)
3861       INTEGER(iwp) ::  jp          !< counter (y)
3862       INTEGER(iwp) ::  m           !< sorting index
3863       INTEGER(iwp) ::  n           !< agent index
3864       INTEGER(iwp) ::  nn          !< agent counter
3865       INTEGER(iwp) ::  sort_index  !< sorting index
3866
3867       INTEGER(iwp), DIMENSION(0:3) ::  sort_count  !< number of agents in one subbox
3868
3869       TYPE(agent_type), DIMENSION(:,:), ALLOCATABLE ::  sort_agents  !< sorted agent array
3870
3871       DO  ip = nxl, nxr
3872          DO  jp = nys, nyn
3873             number_of_agents = agt_count(jp,ip)
3874             IF ( number_of_agents <= 0 )  CYCLE
3875             agents => grid_agents(jp,ip)%agents(1:number_of_agents)
3876
3877             nn = 0
3878             sort_count = 0
3879             ALLOCATE( sort_agents(number_of_agents, 0:3) )
3880
3881             DO  n = 1, number_of_agents
3882                sort_index = 0
3883
3884                IF ( agents(n)%agent_mask )  THEN
3885                   nn = nn + 1
3886!
3887!--                Sorting agents with a binary scheme
3888!--                sort_index=11_2=3_10 -> agent at the left,south subgridbox
3889!--                sort_index=10_2=2_10 -> agent at the left,north subgridbox
3890!--                sort_index=01_2=1_10 -> agent at the right,south subgridbox
3891!--                sort_index=00_2=0_10 -> agent at the right,north subgridbox
3892!--                For this the center of the gridbox is calculated
3893                   i = (agents(n)%x + 0.5_wp * dx) * ddx
3894                   j = (agents(n)%y + 0.5_wp * dy) * ddy
3895
3896                   IF ( i == ip )  sort_index = sort_index + 2
3897                   IF ( j == jp )  sort_index = sort_index + 1
3898
3899                   sort_count(sort_index) = sort_count(sort_index) + 1
3900                   m = sort_count(sort_index)
3901                   sort_agents(m,sort_index) = agents(n)
3902                   sort_agents(m,sort_index)%block_nr = sort_index
3903                ENDIF
3904             ENDDO
3905
3906             nn = 0
3907             DO is = 0,3
3908                grid_agents(jp,ip)%start_index(is) = nn + 1
3909                DO n = 1,sort_count(is)
3910                   nn = nn + 1
3911                   agents(nn) = sort_agents(n,is)
3912                ENDDO
3913                grid_agents(jp,ip)%end_index(is) = nn
3914             ENDDO
3915
3916             number_of_agents = nn
3917             agt_count(jp,ip) = number_of_agents
3918             DEALLOCATE(sort_agents)
3919          ENDDO
3920       ENDDO
3921
3922    END SUBROUTINE mas_ps_sort_in_subboxes
3923
3924!------------------------------------------------------------------------------!
3925! Description:
3926! ------------
3927!> Move all agents not marked for deletion to lowest indices (packing)
3928!------------------------------------------------------------------------------!
3929    SUBROUTINE mas_ps_pack
3930
3931       IMPLICIT NONE
3932
3933       INTEGER(iwp) ::  n  !< agent counter
3934       INTEGER(iwp) ::  nn !< number of agents
3935!
3936!--    Find out elements marked for deletion and move data from highest index
3937!--    values to these free indices
3938       nn = number_of_agents
3939
3940       DO WHILE ( .NOT. agents(nn)%agent_mask )
3941          nn = nn-1
3942          IF ( nn == 0 )  EXIT
3943       ENDDO
3944
3945       IF ( nn > 0 )  THEN
3946          DO  n = 1, number_of_agents
3947             IF ( .NOT. agents(n)%agent_mask )  THEN
3948                agents(n) = agents(nn)
3949                nn = nn - 1
3950                DO WHILE ( .NOT. agents(nn)%agent_mask )
3951                   nn = nn-1
3952                   IF ( n == nn )  EXIT
3953                ENDDO
3954             ENDIF
3955             IF ( n == nn )  EXIT
3956          ENDDO
3957       ENDIF
3958
3959!
3960!--    The number of deleted agents has been determined in routines
3961!--    mas_boundary_conds, mas_droplet_collision, and mas_eh_exchange_horiz
3962       number_of_agents = nn
3963
3964    END SUBROUTINE mas_ps_pack 
3965
3966!------------------------------------------------------------------------------!
3967! Description:
3968! ------------
3969!> Sort agents in each sub-grid box into two groups: agents that already
3970!> completed the LES timestep, and agents that need further timestepping to
3971!> complete the LES timestep.
3972!------------------------------------------------------------------------------!
3973!    SUBROUTINE mas_ps_sort_timeloop_done
3974!
3975!       IMPLICIT NONE
3976!
3977!       INTEGER(iwp) :: end_index     !< agent end index for each sub-box
3978!       INTEGER(iwp) :: i             !< index of agent grid box in x-direction
3979!       INTEGER(iwp) :: j             !< index of agent grid box in y-direction
3980!       INTEGER(iwp) :: n             !< running index for number of agents
3981!       INTEGER(iwp) :: nb            !< index of subgrid boux
3982!       INTEGER(iwp) :: nf            !< indices for agents in each sub-box that already finalized their substeps
3983!       INTEGER(iwp) :: nnf           !< indices for agents in each sub-box that need further treatment
3984!       INTEGER(iwp) :: num_finalized !< number of agents in each sub-box that already finalized their substeps
3985!       INTEGER(iwp) :: start_index   !< agent start index for each sub-box
3986!
3987!       TYPE(agent_type), DIMENSION(:), ALLOCATABLE :: sort_agents  !< temporary agent array
3988!
3989!       DO  i = nxl, nxr
3990!          DO  j = nys, nyn
3991!
3992!             number_of_agents = agt_count(j,i)
3993!             IF ( number_of_agents <= 0 )  CYCLE
3994!
3995!             agents => grid_agents(j,i)%agents(1:number_of_agents)
3996!
3997!             DO  nb = 0, 3
3998!
3999!--             Obtain start and end index for each subgrid box
4000!                start_index = grid_agents(j,i)%start_index(nb)
4001!                end_index   = grid_agents(j,i)%end_index(nb)
4002!
4003!--             Allocate temporary array used for sorting
4004!                ALLOCATE( sort_agents(start_index:end_index) )
4005!
4006!--             Determine number of agents already completed the LES
4007!--             timestep, and write them into a temporary array
4008!                nf = start_index
4009!                num_finalized = 0
4010!                DO  n = start_index, end_index
4011!                   IF ( dt_3d - agents(n)%dt_sum < 1E-8_wp )  THEN
4012!                      sort_agents(nf) = agents(n)
4013!                      nf              = nf + 1
4014!                      num_finalized   = num_finalized + 1
4015!                   ENDIF
4016!                ENDDO
4017!
4018!--             Determine number of agents that not completed the LES
4019!--             timestep, and write them into a temporary array
4020!                nnf = nf
4021!                DO  n = start_index, end_index
4022!                   IF ( dt_3d - agents(n)%dt_sum > 1E-8_wp )  THEN
4023!                      sort_agents(nnf) = agents(n)
4024!                      nnf              = nnf + 1
4025!                   ENDIF
4026!                ENDDO
4027!
4028!--             Write back sorted agents
4029!                agents(start_index:end_index) =                          &
4030!                                        sort_agents(start_index:end_index)
4031!
4032!--             Determine updated start_index, used to masked already
4033!--             completed agents.
4034!                grid_agents(j,i)%start_index(nb) =                     &
4035!                                   grid_agents(j,i)%start_index(nb)    &
4036!                                 + num_finalized
4037!
4038!--             Deallocate dummy array
4039!                DEALLOCATE ( sort_agents )
4040!
4041!--             Finally, if number of non-completed agents is non zero
4042!--             in any of the sub-boxes, set control flag appropriately.
4043!                IF ( nnf > nf )                                             &
4044!                   grid_agents(j,i)%time_loop_done = .FALSE.
4045!
4046!             ENDDO
4047!          ENDDO
4048!       ENDDO
4049!
4050!    END SUBROUTINE mas_ps_sort_timeloop_done
4051
4052!------------------------------------------------------------------------------!
4053! Description:
4054! ------------
4055!> Calls social forces calculations
4056!------------------------------------------------------------------------------!
4057    SUBROUTINE mas_timestep_forces_call ( ip, jp )
4058
4059       IMPLICIT NONE
4060
4061       INTEGER(iwp) ::  ip  !< counter, x-direction
4062       INTEGER(iwp) ::  jp  !< counter, y-direction
4063       INTEGER(iwp) ::  n   !< loop variable over all agents in a grid box
4064
4065!
4066!--    Get direction for all agents in current grid cell
4067       CALL mas_agent_direction
4068
4069       DO n = 1, number_of_agents
4070
4071          force_x = 0.0_wp
4072          force_y = 0.0_wp
4073
4074          CALL mas_timestep_social_forces ( 'acceleration', n, ip, jp )
4075
4076          CALL mas_timestep_social_forces ( 'other_agents', n, ip, jp )
4077
4078          CALL mas_timestep_social_forces ( 'walls',        n, ip, jp )
4079!
4080!--       Update forces
4081          agents(n)%force_x = force_x
4082          agents(n)%force_y = force_y
4083       ENDDO
4084
4085    END SUBROUTINE mas_timestep_forces_call
4086
4087!------------------------------------------------------------------------------!
4088! Description:
4089! ------------
4090!> Euler timestep of agent transport
4091!------------------------------------------------------------------------------!
4092    SUBROUTINE mas_timestep
4093
4094       IMPLICIT NONE
4095
4096       INTEGER(iwp) ::  n !< loop variable over all agents in a grid box
4097
4098       REAL(wp) ::  abs_v !< absolute value of velocity
4099       REAL(wp) ::  abs_f !< absolute value of force
4100
4101       DO n = 1, number_of_agents
4102!
4103!--       Limit absolute force to a maximum to prevent unrealistic acceleration
4104          abs_f = SQRT((agents(n)%force_x)**2 + (agents(n)%force_y)**2)
4105          IF ( abs_f > 20. ) THEN
4106             agents(n)%force_x = agents(n)%force_x * 20. / abs_f
4107             agents(n)%force_y = agents(n)%force_y * 20. / abs_f
4108          ENDIF
4109!
4110!--       Update agent speed
4111          agents(n)%speed_x = agents(n)%speed_x + agents(n)%force_x * dt_agent
4112          agents(n)%speed_y = agents(n)%speed_y + agents(n)%force_y * dt_agent
4113!
4114!--       Reduction of agent speed to maximum agent speed
4115          abs_v = SQRT((agents(n)%speed_x)**2 + (agents(n)%speed_y)**2)
4116          IF ( abs_v > v_max_agent ) THEN
4117             agents(n)%speed_x = agents(n)%speed_x * v_max_agent / abs_v
4118             agents(n)%speed_y = agents(n)%speed_y * v_max_agent / abs_v
4119          ENDIF
4120!
4121!--       Update agent position
4122          agents(n)%x = agents(n)%x + agents(n)%speed_x * dt_agent
4123          agents(n)%y = agents(n)%y + agents(n)%speed_y * dt_agent
4124!
4125!--       Update absolute value of agent speed
4126          agents(n)%speed_abs = abs_v
4127!
4128!--       Increment the agent age and the total time that the agent
4129!--       has advanced within the agent timestep procedure
4130          agents(n)%age_m  = agents(n)%age
4131          agents(n)%age    = agents(n)%age    + dt_agent
4132          agents(n)%dt_sum = agents(n)%dt_sum + dt_agent
4133!
4134!--       Check whether there is still an agent that has not yet completed
4135!--       the total LES timestep
4136          IF ( ( dt_3d - agents(n)%dt_sum ) > 1E-8_wp )  THEN
4137             dt_3d_reached_l_mas = .FALSE.
4138          ENDIF
4139
4140       ENDDO
4141
4142    END SUBROUTINE mas_timestep
4143
4144!------------------------------------------------------------------------------!
4145! Description:
4146! ------------
4147!> Calculates the Social Forces (Helbing and Molnar, 1995) that the agent
4148!> experiences due to acceleration towards target and repulsion by obstacles
4149!------------------------------------------------------------------------------!
4150    SUBROUTINE mas_timestep_social_forces ( mode, nl, ip, jp )
4151
4152       IMPLICIT NONE
4153
4154       CHARACTER (LEN=*) ::  mode  !< identifier for the mode of calculation
4155
4156       INTEGER(iwp) ::  ij_dum      !< index of nearest wall
4157       INTEGER(iwp) ::  il          !< index variable along x
4158       INTEGER(iwp) ::  ip          !< index variable along x
4159       INTEGER(iwp) ::  jl          !< index variable along y
4160       INTEGER(iwp) ::  jp          !< index variable along y
4161       INTEGER(iwp) ::  nl          !< loop variable over all agents in a grid box
4162       INTEGER(iwp) ::  no          !< loop variable over all agents in a grid box
4163       INTEGER(iwp) ::  noa         !< amount of agents in a grid box
4164       INTEGER(iwp) ::  sc_x_end    !< index for scan for topography/other agents
4165       INTEGER(iwp) ::  sc_x_start  !< index for scan for topography/other agents
4166       INTEGER(iwp) ::  sc_y_end    !< index for scan for topography/other agents
4167       INTEGER(iwp) ::  sc_y_start  !< index for scan for topography/other agents
4168
4169       LOGICAL ::  corner_found  !< flag that indicates a corner has been found near agent
4170
4171       REAL(wp) ::  a_pl             !< factor for collision avoidance
4172       REAL(wp) ::  ax_semimaj       !< semiminor axis of repulsive ellipse
4173       REAL(wp) ::  b_pl             !< factor for collision avoidance
4174       REAL(wp) ::  c_pl             !< factor for collision avoidance
4175       REAL(wp) ::  coll_t           !< time at which the next collision would happen
4176       REAL(wp) ::  d_coll_t_0       !< inverse of collision cutoff time
4177       REAL(wp) ::  d_pl             !< factor for collision avoidance
4178       REAL(wp) ::  ddum_f           !< dummy devisor collision avoidance
4179       REAL(wp) ::  dist             !< distance to obstacle
4180       REAL(wp) ::  dist_sq          !< distance to obstacle squared
4181       REAL(wp) ::  pos_rel_x        !< relative position of two agents (x)
4182       REAL(wp) ::  pos_rel_y        !< relative position of two agents (y)
4183       REAL(wp) ::  r_sq             !< y-position
4184       REAL(wp) ::  sra              !< scan radius (agents)
4185       REAL(wp) ::  srw              !< local variable for scan radius (walls)
4186       REAL(wp) ::  v_rel_x          !< relative velocity (x); collision avoidance
4187       REAL(wp) ::  v_rel_y          !< relative velocity (y); collision avoidance
4188       REAL(wp) ::  x_a              !< x-position
4189       REAL(wp) ::  x_wall           !< x-position of wall
4190       REAL(wp) ::  y_a              !< y-position
4191       REAL(wp) ::  y_wall           !< y-position of wall
4192
4193       REAL(wp), PARAMETER ::  k_pl = 1.5  !< factor for collision avoidance
4194
4195       TYPE(agent_type), DIMENSION(:), POINTER ::  l_agts !< agents that repulse current agent
4196
4197!
4198!--    Initialization
4199       x_a = agents(nl)%x
4200       y_a = agents(nl)%y
4201
4202       SELECT CASE ( TRIM( mode ) )
4203!
4204!--       Calculation of force due to agent trying to approach desired velocity
4205          CASE ( 'acceleration' )
4206
4207             force_x = force_x + d_tau_accel_agent                             &
4208                          * ( agents(nl)%speed_des*agents(nl)%speed_e_x        &
4209                             -agents(nl)%speed_x )
4210
4211             force_y = force_y + d_tau_accel_agent                             &
4212                          * ( agents(nl)%speed_des*agents(nl)%speed_e_y        &
4213                             -agents(nl)%speed_y )
4214
4215!
4216!--       Calculation of repulsive forces by other agents in a radius around the
4217!--       current one
4218          CASE ( 'other_agents' )
4219
4220             sra = scan_radius_agent
4221             d_coll_t_0 = 1./coll_t_0
4222!
4223!--          Find relevant gridboxes (those that could contain agents within
4224!--          scan radius)
4225             sc_x_start = FLOOR( (x_a - sra) * ddx )
4226             sc_x_end   = FLOOR( (x_a + sra) * ddx )
4227             sc_y_start = FLOOR( (y_a - sra) * ddx )
4228             sc_y_end   = FLOOR( (y_a + sra) * ddx )
4229             IF ( sc_x_start < nxlg ) sc_x_start = nxlg
4230             IF ( sc_x_end   > nxrg ) sc_x_end   = nxrg
4231             IF ( sc_y_start < nysg ) sc_y_start = nysg
4232             IF ( sc_y_end   > nyng ) sc_y_end   = nyng
4233
4234             sra = sra**2
4235!
4236!--          Loop over all previously found relevant gridboxes
4237             DO il = sc_x_start, sc_x_end
4238                DO jl = sc_y_start, sc_y_end
4239                   noa = agt_count(jl,il)
4240                   IF ( noa <= 0 )  CYCLE
4241                   l_agts => grid_agents(jl,il)%agents(1:noa)
4242                   DO no = 1, noa
4243!
4244!--                   Skip self
4245                      IF ( jl == jp .AND. il == ip .AND. no == nl ) CYCLE
4246                      pos_rel_x = l_agts(no)%x - x_a
4247                      pos_rel_y = l_agts(no)%y - y_a
4248                      dist_sq = pos_rel_x**2 + pos_rel_y**2
4249                      IF ( dist_sq > sra ) CYCLE
4250                      r_sq    = (2*radius_agent)**2
4251                      v_rel_x   = agents(nl)%speed_x - l_agts(no)%speed_x
4252                      v_rel_y   = agents(nl)%speed_y - l_agts(no)%speed_y
4253!
4254!--                   Collision is already occuring, default to standard
4255!--                   social forces
4256                      IF ( dist_sq <= r_sq ) THEN
4257                         dist = SQRT(dist_sq) + 1.0d-12
4258                         ax_semimaj = .5_wp*SQRT( dist )
4259
4260                         force_x = force_x - 0.125_wp * repuls_agent           &
4261                                        * d_sigma_rep_agent / ax_semimaj       &
4262                                        * EXP( -ax_semimaj*d_sigma_rep_agent ) &
4263                                        * (pos_rel_x/dist)
4264
4265                         force_y = force_y - 0.125_wp * repuls_agent           &
4266                                        * d_sigma_rep_agent / ax_semimaj       &
4267                                        * EXP( -ax_semimaj*d_sigma_rep_agent ) &
4268                                        * (pos_rel_y/dist)
4269!
4270!--                   Currently no collision, calculate collision avoidance
4271!--                   force according to Karamouzas et al (2014, PRL 113,238701)
4272                      ELSE
4273!
4274!--                     factors
4275                         a_pl = v_rel_x**2 +  v_rel_y**2
4276                         b_pl = pos_rel_x*v_rel_x + pos_rel_y*v_rel_y
4277                         c_pl = dist_sq - r_sq
4278                         d_pl = b_pl**2 - a_pl*c_pl
4279!
4280!--                      If the two agents are moving non-parallel, calculate
4281!--                      collision avoidance social force
4282                         IF ( d_pl > 0.0_wp .AND.                              &
4283                            ( a_pl < -0.00001 .OR. a_pl > 0.00001 ) )          &
4284                         THEN
4285
4286                            d_pl   = SQRT(d_pl)
4287                            coll_t = (b_pl - d_pl)/a_pl
4288                            IF ( coll_t > 0.0_wp ) THEN
4289!
4290!--                            Dummy factor
4291                               ddum_f = 1. / ( a_pl * coll_t**2 )              &
4292                                           * ( 2. / coll_t + 1.0 * d_coll_t_0 )
4293!
4294!--                            x-component of social force
4295                               force_x = force_x - k_pl *                      &
4296                                         EXP( -coll_t * d_coll_t_0 ) *         &
4297                                         ( v_rel_x -                           &
4298                                           ( b_pl * v_rel_x -                  &
4299                                             a_pl * pos_rel_x ) / d_pl ) *     &
4300                                         ddum_f
4301!
4302!--                            y-component of social force
4303                               force_y = force_y - k_pl *                      &
4304                                         EXP( -coll_t * d_coll_t_0 ) *         &
4305                                         ( v_rel_y -                           &
4306                                           ( b_pl * v_rel_y -                  &
4307                                             a_pl * pos_rel_y ) / d_pl ) *     &
4308                                         ddum_f
4309
4310                            ENDIF
4311                         ENDIF
4312                      ENDIF
4313                   ENDDO
4314                ENDDO
4315             ENDDO
4316
4317          CASE ( 'walls' )
4318
4319             srw = scan_radius_wall
4320             corner_found = .FALSE.
4321!
4322!--          find relevant grid boxes (those that could contain topography
4323!--          within radius)
4324             sc_x_start = (x_a - srw) * ddx
4325             sc_x_end   = (x_a + srw) * ddx
4326             sc_y_start = (y_a - srw) * ddx
4327             sc_y_end   = (y_a + srw) * ddx
4328             IF ( sc_x_start < nxlg ) sc_x_start = nxlg
4329             IF ( sc_x_end   > nxrg ) sc_x_end   = nxrg
4330             IF ( sc_y_start < nysg ) sc_y_start = nysg
4331             IF ( sc_y_end   > nyng ) sc_y_end   = nyng
4332!
4333!--          Find "walls" ( i.e. topography steps (up or down) higher than one
4334!--          grid box ) that are perpendicular to the agent within the defined
4335!--          search radius. Such obstacles cannot be passed and a social force
4336!--          to that effect is applied.
4337!--          Walls only apply a force perpendicular to the wall to the agent.
4338!--          There is therefore a search for walls directly right, left, south
4339!--          and north of the agent. All other walls are ignored.
4340!--
4341!--          Check for wall left of current agent
4342             ij_dum = 0
4343             IF ( sc_x_start < ip ) THEN
4344                DO il = ip - 1, sc_x_start, -1
4345!
4346!--                Going left from the agent, check for a right wall
4347                   IF ( BTEST( obstacle_flags(jp,il), 2 ) ) THEN
4348!
4349!--                   obstacle found in grid box il, wall at right side
4350                      x_wall = (il+1)*dx
4351!
4352!--                   Calculate force of found wall on agent
4353                      CALL mas_timestep_wall_corner_force( x_a, x_wall, y_a,   &
4354                                                           y_a )
4355!
4356!--                   calculate new x starting index for later scan for corners
4357                      ij_dum = il + 1
4358                      EXIT
4359                   ENDIF
4360                ENDDO
4361             ENDIF
4362             IF ( ij_dum /= 0 ) sc_x_start = ij_dum 
4363
4364!
4365!--          Check for wall right of current agent
4366             ij_dum = 0
4367             IF ( sc_x_end > ip ) THEN
4368                DO il = ip + 1, sc_x_end
4369!
4370!--                Going right from the agent, check for a left wall
4371                   IF ( BTEST( obstacle_flags(jp,il), 6 ) ) THEN
4372!
4373!--                   obstacle found in grid box il, wall at left side
4374                      x_wall = il*dx
4375!
4376!--                   Calculate force of found wall on agent
4377                      CALL mas_timestep_wall_corner_force( x_a, x_wall, y_a,   &
4378                                                           y_a )
4379!
4380!--                   calculate new x end index for later scan for corners
4381                      ij_dum = il - 1
4382                      EXIT
4383                   ENDIF
4384                ENDDO
4385             ENDIF
4386             IF ( ij_dum /= 0 ) sc_x_end = ij_dum 
4387
4388!
4389!--          Check for wall south of current agent
4390             ij_dum = 0
4391             IF ( sc_y_start < jp ) THEN
4392                DO jl = jp - 1, sc_y_start, -1
4393!
4394!--                Going south from the agent, check for a north wall
4395                   IF ( BTEST( obstacle_flags(jl,ip), 0 ) ) THEN
4396!
4397!--                   obstacle found in grid box jl, wall at left side
4398                      y_wall = (jl+1)*dy
4399
4400                      CALL mas_timestep_wall_corner_force( x_a, x_a, y_a,      &
4401                                                           y_wall )
4402!
4403!--                   calculate new y starting index for later scan for corners
4404                      ij_dum = jl + 1
4405                      EXIT
4406                   ENDIF
4407                ENDDO
4408             ENDIF
4409             IF ( ij_dum /= 0 ) sc_y_start = ij_dum 
4410
4411!
4412!--          Check for wall north of current agent
4413             ij_dum = 0
4414             IF ( sc_y_end > jp ) THEN
4415                DO jl = jp + 1, sc_y_end 
4416!
4417!--                Going north from the agent, check for a south wall
4418                   IF ( BTEST( obstacle_flags(jl,ip), 4 ) ) THEN
4419!
4420!--                   obstacle found in grid box jl, wall at left side
4421                      y_wall = jl*dy
4422
4423                      CALL mas_timestep_wall_corner_force( x_a, x_a, y_a,      &
4424                                                           y_wall )
4425!
4426!--                   calculate new y end index for later scan for corners
4427                      ij_dum = jl - 1
4428                   ENDIF
4429                ENDDO
4430             ENDIF
4431             IF ( ij_dum /= 0 ) sc_y_end = ij_dum 
4432
4433!
4434!--          Scan for corners surrounding current agent.
4435!--          Only gridcells that are closer than the closest wall in each
4436!--          direction (n,s,r,l) are considered in the search since those
4437!--          further away would have a significantly smaller resulting force
4438!--          than the closer wall.
4439             DO il = sc_x_start, sc_x_end
4440                DO jl = sc_y_start, sc_y_end
4441                   IF ( il == ip .OR. jl == jp ) CYCLE
4442!
4443!--                corners left of agent
4444                   IF ( il < ip ) THEN
4445!
4446!--                   south left quadrant: look for north right corner
4447                      IF ( jl < jp ) THEN
4448                         IF ( BTEST( obstacle_flags(jl,il), 1 ) ) THEN
4449!
4450!--                         calculate coordinates of the found corner
4451                            x_wall = (il+1)*dx
4452                            y_wall = (jl+1)*dy
4453
4454                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4455                                                                 y_a, y_wall )
4456
4457                         ENDIF
4458!
4459!--                   north left quadrant: look for south right corner
4460                      ELSEIF ( jl > jp ) THEN
4461                         IF ( BTEST( obstacle_flags(jl,il), 3 ) ) THEN
4462!
4463!--                         calculate coordinates of the corner of said gridcell
4464!--                         that is closest to the current agent
4465                            x_wall = (il+1)*dx
4466                            y_wall = jl*dy
4467
4468                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4469                                                                 y_a, y_wall )
4470
4471                         ENDIF
4472                      ENDIF
4473                   ELSEIF ( il > ip ) THEN
4474!
4475!--                   south right quadrant: look for north left corner
4476                      IF ( jl < jp ) THEN
4477                         IF ( BTEST( obstacle_flags(jl,il), 7 ) ) THEN
4478!
4479!--                         calculate coordinates of the corner of said gridcell
4480!--                         that is closest to the current agent
4481                            x_wall = il*dx
4482                            y_wall = (jl+1)*dy
4483
4484                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4485                                                                 y_a, y_wall )
4486
4487                         ENDIF
4488!
4489!--                   north right quadrant: look for south left corner
4490                      ELSEIF ( jl > jp ) THEN
4491                         IF ( BTEST( obstacle_flags(jl,il), 5 ) ) THEN
4492!
4493!--                         calculate coordinates of the corner of said gridcell
4494!--                         that is closest to the current agent
4495                            x_wall = il*dx
4496                            y_wall = jl*dy
4497
4498                            CALL mas_timestep_wall_corner_force( x_a, x_wall,  &
4499                                                                 y_a, y_wall )
4500
4501                         ENDIF
4502                      ENDIF
4503                   ENDIF
4504                ENDDO
4505             ENDDO
4506
4507          CASE DEFAULT
4508
4509       END SELECT
4510
4511    END SUBROUTINE mas_timestep_social_forces
4512
4513!------------------------------------------------------------------------------!
4514! Description:
4515! ------------
4516!> Given a distance to the current agent, calculates the force a found corner
4517!> or wall exerts on that agent
4518!------------------------------------------------------------------------------!
4519    SUBROUTINE mas_timestep_wall_corner_force( xa, xw, ya, yw )
4520
4521       IMPLICIT NONE
4522
4523       REAL(wp) ::  dist_l     !< distance to obstacle
4524       REAL(wp) ::  force_d_x  !< increment of social force, x-direction
4525       REAL(wp) ::  force_d_y  !< increment of social force, x-direction
4526       REAL(wp) ::  xa         !< x-position of agent
4527       REAL(wp) ::  xw         !< x-position of wall
4528       REAL(wp) ::  ya         !< x-position of agent
4529       REAL(wp) ::  yw         !< y-position of wall
4530
4531       force_d_x = 0.0_wp
4532       force_d_y = 0.0_wp
4533!
4534!--    calculate coordinates of corner relative to agent
4535!--    postion and distance between corner and agent
4536       xw = xa - xw
4537       yw = ya - yw
4538       dist_l = SQRT( (xw)**2 + (yw)**2 )
4539!
4540!--    calculate x and y component of repulsive force
4541!--    induced by previously found corner
4542       IF ( dist_l > 0 ) THEN
4543          force_d_x = repuls_wall * d_sigma_rep_wall         &
4544                      * EXP( -dist_l * d_sigma_rep_wall )      &
4545                      * xw / (dist_l)
4546          force_d_y = repuls_wall * d_sigma_rep_wall         &
4547                      * EXP( -dist_l * d_sigma_rep_wall )      &
4548                      * yw / (dist_l)
4549       ENDIF
4550
4551! !--    forces that are located outside of a sight radius of
4552! !--    200 degrees (-> COS(100./180.*pi) = COS(.555*pi)) of
4553! !--    current agent are considered to have an effect of 50%
4554!        IF ( force_d_x * agents(nl)%speed_e_x +               &
4555!             force_d_y * agents(nl)%speed_e_y <               &
4556!             SQRT(force_d_x**2 + force_d_y**2) *              &
4557!             COS( .55555555 * 3.1415 ) )                      &
4558!        THEN
4559!           force_d_x = force_d_x * .5_wp
4560!           force_d_y = force_d_y * .5_wp
4561!        ENDIF
4562
4563!
4564!--    add force increment to total force of current agent
4565       force_x = force_x + force_d_x
4566       force_y = force_y + force_d_y
4567
4568    END SUBROUTINE mas_timestep_wall_corner_force
4569
4570!
4571!-- Calculates distance of point P to edge (A,B). If A = B, calculates
4572!-- point-to-point distance from A/B to P
4573    FUNCTION dist_point_to_edge ( a_x, a_y, b_x, b_y, p_x, p_y )
4574
4575       IMPLICIT NONE
4576
4577       REAL(wp)  :: ab_x                !< x-coordinate of vector from A to B
4578       REAL(wp)  :: ab_y                !< y-coordinate of vector from A to B
4579       REAL(wp)  :: ab_d                !< inverse length of vector from A to B
4580       REAL(wp)  :: ab_u_x              !< x-coordinate of vector with direction of ab and length 1
4581       REAL(wp)  :: ab_u_y              !< y-coordinate of vector with direction of ab and length 1
4582       REAL(wp)  :: ba_x                !< x-coordinate of vector from B to A
4583       REAL(wp)  :: ba_y                !< y-coordinate of vector from B to A
4584       REAL(wp)  :: ap_x                !< x-coordinate of vector from A to P
4585       REAL(wp)  :: ap_y                !< y-coordinate of vector from A to P
4586       REAL(wp)  :: bp_x                !< x-coordinate of vector from B to P
4587       REAL(wp)  :: bp_y                !< y-coordinate of vector from B to P
4588       REAL(wp)  :: a_x                 !< x-coordinate of point A of edge
4589       REAL(wp)  :: a_y                 !< y-coordinate of point A of edge
4590       REAL(wp)  :: b_x                 !< x-coordinate of point B of edge
4591       REAL(wp)  :: b_y                 !< y-coordinate of point B of edge
4592       REAL(wp)  :: p_x                 !< x-coordinate of point P
4593       REAL(wp)  :: p_y                 !< y-coordinate of point P
4594       REAL(wp)  :: dist_x              !< x-coordinate of point P
4595       REAL(wp)  :: dist_y              !< y-coordinate of point P
4596       REAL(wp)  :: dist_point_to_edge  !< y-coordinate of point P
4597
4598       ab_x = - a_x + b_x
4599       ab_y = - a_y + b_y
4600       ba_x = - b_x + a_x 
4601       ba_y = - b_y + a_y 
4602       ap_x = - a_x + p_x
4603       ap_y = - a_y + p_y
4604       bp_x = - b_x + p_x
4605       bp_y = - b_y + p_y
4606
4607       IF ( ab_x * ap_x + ab_y * ap_y <= 0. ) THEN
4608          dist_point_to_edge = SQRT((a_x - p_x)**2 + (a_y - p_y)**2)
4609       ELSEIF ( ba_x * bp_x + ba_y * bp_y <= 0. ) THEN
4610          dist_point_to_edge = SQRT((b_x - p_x)**2 + (b_y - p_y)**2)
4611       ELSE
4612          ab_d = 1./SQRT((ab_x)**2+(ab_y)**2)
4613          ab_u_x = ab_x*ab_d
4614          ab_u_y = ab_y*ab_d
4615          dist_x = ap_x - (ap_x*ab_u_x+ap_y*ab_u_y)*ab_u_x
4616          dist_y = ap_y - (ap_x*ab_u_x+ap_y*ab_u_y)*ab_u_y
4617          dist_point_to_edge = SQRT( dist_x**2 + dist_y**2 )
4618       ENDIF
4619
4620    END FUNCTION dist_point_to_edge
4621
4622!
4623!-- Returns the heuristic between points A and B (currently the straight
4624!-- distance)
4625    FUNCTION heuristic ( ax, ay, bx, by )
4626
4627       IMPLICIT NONE
4628
4629       REAL(wp)  :: ax           !< x-coordinate of point A
4630       REAL(wp)  :: ay           !< y-coordinate of point A
4631       REAL(wp)  :: bx           !< x-coordinate of point B
4632       REAL(wp)  :: by           !< y-coordinate of point B
4633       REAL(wp)  :: heuristic    !< return value
4634
4635       heuristic = SQRT(( ax - bx )**2 + ( ay - by )**2)
4636
4637    END FUNCTION heuristic 
4638
4639!
4640!-- Calculates if point P is left of the infinite
4641!-- line that contains A and B (direction: A to B)
4642!-- Concept: 2D rotation of two vectors
4643    FUNCTION is_left ( ax, ay, bx, by, px, py )
4644
4645       IMPLICIT NONE
4646
4647       LOGICAL  :: is_left !< return value; TRUE if P is left of AB
4648
4649       REAL(wp)  :: ax     !< x-coordinate of point A
4650       REAL(wp)  :: ay     !< y-coordinate of point A
4651       REAL(wp)  :: bx     !< x-coordinate of point B
4652       REAL(wp)  :: by     !< y-coordinate of point B
4653       REAL(wp)  :: px     !< x-coordinate of point P
4654       REAL(wp)  :: py     !< y-coordinate of point P
4655
4656       is_left = (bx-ax)*(py-ay)-(px-ax)*(by-ay) > 0
4657       IF ( (ABS(ax-px) < .001 .AND. ABS(ay-py) < .001) .OR.                  &
4658            (ABS(bx-px) < .001 .AND. ABS(by-py) < .001) )                     &
4659       THEN
4660          is_left = .FALSE.
4661       ENDIF
4662
4663       RETURN
4664
4665    END FUNCTION is_left 
4666
4667!
4668!-- Calculates if point P is right of the infinite
4669!-- line that contains A and B (direction: A to B)
4670!-- Concept: 2D rotation of two vectors
4671    FUNCTION is_right ( ax, ay, bx, by, px, py )
4672
4673       IMPLICIT NONE
4674
4675       LOGICAL  :: is_right !< return value; TRUE if P is right of AB
4676
4677       REAL(wp), INTENT(IN)  :: ax     !< x-coordinate of point A
4678       REAL(wp), INTENT(IN)  :: ay     !< y-coordinate of point A
4679       REAL(wp), INTENT(IN)  :: bx     !< x-coordinate of point B
4680       REAL(wp), INTENT(IN)  :: by     !< y-coordinate of point B
4681       REAL(wp), INTENT(IN)  :: px     !< x-coordinate of point P
4682       REAL(wp), INTENT(IN)  :: py     !< y-coordinate of point P
4683
4684       is_right = (bx-ax)*(py-ay)-(px-ax)*(by-ay) < 0
4685       IF ( (ABS(ax-px) < .001 .AND. ABS(ay-py) < .001) .OR.                  &
4686            (ABS(bx-px) < .001 .AND. ABS(by-py) < .001) )                     &
4687       THEN
4688          is_right = .FALSE.
4689       ENDIF
4690
4691       RETURN
4692
4693    END FUNCTION is_right 
4694
4695!
4696!-- Returns true if the line segments AB and PQ share an intersection
4697    FUNCTION intersect ( ax, ay, bx, by, px, py, qx, qy )
4698
4699       IMPLICIT NONE
4700
4701       LOGICAL  :: intersect !< return value; TRUE if intersection was found
4702       LOGICAL  :: la        !< T if a is left of PQ
4703       LOGICAL  :: lb        !< T if b is left of PQ
4704       LOGICAL  :: lp        !< T if p is left of AB
4705       LOGICAL  :: lq        !< T if q is left of AB
4706       LOGICAL  :: poss      !< flag that indicates if an intersection is still possible
4707       LOGICAL  :: ra        !< T if a is right of PQ
4708       LOGICAL  :: rb        !< T if b is right of PQ
4709       LOGICAL  :: rp        !< T if p is right of AB
4710       LOGICAL  :: rq        !< T if q is right of AB
4711
4712       REAL(wp)  :: ax     !< x-coordinate of point A
4713       REAL(wp)  :: ay     !< y-coordinate of point A
4714       REAL(wp)  :: bx     !< x-coordinate of point B
4715       REAL(wp)  :: by     !< y-coordinate of point B
4716       REAL(wp)  :: px     !< x-coordinate of point P
4717       REAL(wp)  :: py     !< y-coordinate of point P
4718       REAL(wp)  :: qx     !< x-coordinate of point Q
4719       REAL(wp)  :: qy     !< y-coordinate of point Q
4720
4721       intersect = .FALSE.
4722       poss      = .FALSE.
4723!
4724!--    Intersection is possible only if P and Q are on opposing sides of AB
4725       lp = is_left(ax,ay,bx,by,px,py)
4726       rq = is_right(ax,ay,bx,by,qx,qy)
4727       IF ( lp .AND. rq ) poss = .TRUE.
4728       IF ( .NOT. poss ) THEN
4729          lq = is_left(ax,ay,bx,by,qx,qy)
4730          rp = is_right(ax,ay,bx,by,px,py)
4731          IF ( lq .AND. rp ) poss = .TRUE.
4732       ENDIF
4733!
4734!--    Intersection occurs only if above test (poss) was true AND
4735!--    A and B are on opposing sides of PQ
4736       IF ( poss ) THEN
4737          la = is_left(px,py,qx,qy,ax,ay)
4738          rb = is_right(px,py,qx,qy,bx,by)
4739          IF ( la .AND. rb ) intersect = .TRUE.
4740          IF ( .NOT. intersect ) THEN
4741             lb = is_left(px,py,qx,qy,bx,by)
4742             ra = is_right(px,py,qx,qy,ax,ay)
4743             IF ( lb .AND. ra ) intersect = .TRUE.
4744          ENDIF
4745       ENDIF
4746
4747       RETURN
4748
4749    END FUNCTION intersect 
4750
4751!
4752!-- Gives a nuber randomly distributed around an average
4753    FUNCTION random_normal ( avg, variation )
4754
4755       IMPLICIT NONE
4756
4757       REAL(wp)  :: avg            !< x-coordinate of vector from A to B
4758       REAL(wp)  :: variation      !< y-coordinate of vector from A to B
4759       REAL(wp)  :: random_normal  !< y-coordinate of vector from A to B
4760
4761       REAL(wp), DIMENSION(12)  :: random_arr  !< inverse length of vector from A to B
4762
4763       CALL RANDOM_NUMBER(random_arr)
4764       random_normal = avg + variation*(SUM(random_arr)-6.)
4765
4766    END FUNCTION random_normal
4767
4768
4769 END MODULE multi_agent_system_mod
Note: See TracBrowser for help on using the repository browser.