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

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

Reworked agent pathfinding and modified output

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