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

Last change on this file since 3580 was 3525, checked in by kanani, 5 years ago

Changes related to clean-up of biometeorology (by dom_dwd_user)

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