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

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

Added MAS end time, used time_since_reference_point, corrected tolerance_dp in nav_mesh

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