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

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

Changed C_SIZEOF to STORAGE_SIZE

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