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

Last change on this file since 4466 was 4444, checked in by raasch, 4 years ago

bugfix: cpp-directives for serial mode added

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