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

Last change on this file since 3241 was 3241, checked in by raasch, 6 years ago

various changes to avoid compiler warnings (mainly removal of unused variables)

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