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

Last change on this file since 4072 was 3987, checked in by kanani, 5 years ago

clean up location, debug and error messages

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