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

Last change on this file since 3254 was 3248, checked in by sward, 6 years ago

Minor format changes

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