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

Last change on this file since 3247 was 3246, checked in by sward, 6 years ago

Added error handling for wrong input parameters

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