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

Last change on this file since 4339 was 4329, checked in by motisi, 4 years ago

Renamed wall_flags_0 to wall_flags_static_0

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