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

Last change on this file since 4309 was 4307, checked in by maronga, 4 years ago

your commit message

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