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

Last change on this file since 4751 was 4623, checked in by raasch, 4 years ago

some switches calculated explicitly to avoid compiler warnings

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