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

Last change on this file since 3597 was 3593, checked in by kanani, 5 years ago

Bugfix for missing array allocation (biometeorology_mod), remove degree symbol (biometeorology_mod, indoor_model_mod, multi_agent_system_mod, surface_mod, wind_turbine_model_mod)

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