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

Last change on this file since 4180 was 4180, checked in by scharf, 5 years ago

removed comments in 'Former revisions' section that are older than 01.01.2019

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