source: palm/tags/release-6.0/SOURCE/multi_agent_system_mod.f90 @ 3884

Last change on this file since 3884 was 3448, checked in by kanani, 5 years ago

Implementation of human thermal indices (from branch biomet_p2 at r3444)

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