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

Last change on this file since 3860 was 3833, checked in by forkel, 5 years ago

removed USE chem_gasphase_mod from chem_modules, apply USE chem_gasphase for nvar, nspec, cs_mech and spc_names instead

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