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

Last change on this file since 3165 was 3165, checked in by sward, 6 years ago

Added agent ID output

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