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

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

Added multi agent system

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