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

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