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

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

Added missing preprocessor directive, corrected default value for restarts

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