The AHA Model  Revision: 12809
Reference implementation 04 (HEDG02_04)
the_environment Module Reference

Definition of environmental objects. More...

Data Types

type  spatial
 Definition of a spatial object. Spatial object determines the position of the agent, food items and other things in the simulated space. Here we use continuous 3D environment (real type coordinates) More...
 
type  spatial_moving
 Definition of a movable spatial object. It extends the the_environment::spatial object, but also adds its previous position history in stack-like arrays. The history is maintained with the commondata::add_to_history() subroutine, adding a single element on the top (end) of the history stack. More...
 
type  environment
 Definition of the overall environment. Environment is a general container for all habitats, patches and other similar objects where the whole life of the agents takes place. Environment just provides the limits for all these objects. More...
 
type  food_item
 Definition of a single food item. Food item is a spatial object that has specific location in space. It can be "created" and eaten ("disappear"). Food item is an immobile SPATIAL object that has a position in 3D space. More...
 
type  food_resource
 Definition of the super-type FOOD resource type. This is a superclass, several sub-classes can be defined for different kinds of food and prey objects. More...
 
type  predator
 Definition of the PREDATOR objects. Predator is a moving agent that hunts on the evolving AHA agents but its internal structure is very simplistic (although we can in principle doit as a full AHA complexity with genome, GOS etc...). More...
 
type  habitat
 Definition of the environment habitat HABITAT object. There can potentially be of several types of habitats (patches etc.), so the superclass HABITAT defines the most general properties and procedures. More specific procedures are defined in sub-objects. Such procedures can be overriden from super-object to sub-objects providing for procedure polymorphism. More...
 
interface  light_surface
 Calculate surface light intensity (that is subject to diel variation) for specific time step of the model. Irradiance can be stochastic if an optionallogical stochastic flag is set to TRUE. More...
 
interface  light_depth
 Calculate underwater background irradiance at specific depth. More...
 
interface  visual_range
 Calculate visual range of predator using Dag Aksnes's procedures srgetr(), easyr() and deriv(). More...
 
interface  visual_range_new
 Calculate visual range of predator using Dag Aksnes's procedures srgetr(), easyr() and deriv(). More...
 
interface  dist
 Internal distance calculation backend engine. More...
 
interface  join
 An alias for the the_environment::food_resources_collapse_global_object() method for joining food resources into a single global food resource out of the global array the_environment::global_habitats_available. See the_environment::unjoin() for how to unjoin an array of food resources back into an array. More...
 
interface  unjoin
 An alias to the_environment::food_resources_update_back_global_object() method to transfer (having been modified) food resource objects out from the single united object back to the global array the_environment::global_habitats_available. See the_environment::join() for how to join an array of food resources into a single global object. More...
 
interface  assemble
 Interface to the procedure to assemble the global array of habitat objects the_environment::global_habitats_available from a list of separate habitat object components. This call. More...
 
interface  disassemble
 Interface to the procedure to disassemble the global habitats objects array the_environment::global_habitats_available back into separate habitat object components. See the_environment::global_habitats_disassemble() for the backend implementation. More...
 
interface  operator(.cat.)
 Interface operator to concatenate two arrays of the spatial the_environment::spatial or spatial moving the_environment::spatial_moving objects. More...
 
interface  operator(.catloc.)
 Interface operator to concatenate the location components of two arrays ofthe_environment::spatial class objects. More...
 
interface  operator(.within.)
 Interface operators .within. for testing whether a spatial object (first argument lies within an environment (second argument). Usage: More...
 
interface  operator(.contains.)
 Interface operators .contains. for testing whether an environment object (first argument) contains a SPATIAL object (second argument). Usage: More...
 
interface  operator(.above.)
 Interface operators .above. for spatial objects. Usage: More...
 
interface  operator(.below.)
 Interface operators .below. for spatial objects. Usage: More...
 
interface  operator(-)
 Interface operator "-" for the the_environment::environment spatial container objects. Return an environment object that is shrunk by a fixed value in the 2D XxY plane. See the_environment::environment_shrink_xy_fixed(). The operator can be used as follows: More...
 

Functions/Subroutines

elemental subroutine spatial_create_empty (this)
 These are public access functions, but probably we don't need to allow public access to functions inside generic interfaces. More...
 
subroutine environment_whole_build_vector (this, min_coord, max_coord)
 Create the highest level container environment. Set the size of the 3D environment container as two coordinate vectors setting the minimum and maximum coordinate limits: min_coord(1) for x, min_coord(2) for y, min_coord(3) for z The size of the environment should be set from parameter vectors in COMMONDATA. More...
 
subroutine environment_whole_build_object (this, min_coord, max_coord)
 Create the highest level container environment. Set the size of the 3D environment container as two coordinate vectors setting the minimum and maximum coordinate limits. The parameters min_coord and max_coord are SPATIAL objects. More...
 
subroutine environment_build_unlimited (this)
 Build an unlimited environment, with the spatial coordinates limited by the maximum machine supported values based on the intrinsic huge function. More...
 
type(environment) function environment_shrink_xy_fixed (this, shrink_value)
 Return an environment object that is shrunk by a fixed value in the 2D XxY plane. More...
 
type(spatial) function environment_get_minimum_obj (this)
 Function to get the minimum spatial limits (coordinates) of the environment. More...
 
type(spatial) function environment_get_maximum_obj (this)
 Function to get the maximum spatial limits (coordinates) of the environment. More...
 
elemental real(srp) function environment_get_minimum_depth (this)
 Get the minimum depth in this environment. More...
 
elemental real(srp) function environment_get_maximum_depth (this)
 Get the maximum depth in this environment. More...
 
pure type(spatial) function, dimension(dim_environ_cornersenvironment_get_corners_2dxy (this, ref_depth, offset)
 Get the corners of the environment in the 2D X Y plane. This is a very simplistic procedure that works only with the box environmental objects. More...
 
elemental logical function environment_check_located_within_3d (this, check_object)
 Check if a spatial object is actually within this environment. More...
 
type(spatial) function environment_random_uniform_spatial_3d (this)
 Generate a random spatial object with the uniform distribution within (i.e. bound to) this environment. More...
 
type(spatial) function environment_random_uniform_spatial_2d (this, fixdepth)
 Generate a random spatial object with the uniform distribution within (i.e. bound to) this environment, the third depth coordinate is fixed. More...
 
type(spatial) function, dimension(num) environment_random_uniform_spatial_vec_3d (this, num)
 Generate a vector of random spatial objects with the uniform distribution within (i.e. bound to) this environment. More...
 
type(spatial) function, dimension(size(fixdep_array)) environment_random_uniform_spatial_vec_2d (this, fixdep_array)
 Generate a vector of random spatial objects with the uniform distribution within (i.e. bound to) this environment. The third, depth coordinate is non-stochastic, and provided as an array parameter. More...
 
type(spatial) function, dimension(num) environment_random_gaussian_spatial_3d (this, num, centroid, variance)
 Generates a vector of random spatial object with Gaussian coordinates within (i.e. bound to) this environment. More...
 
type(spatial) function, dimension(num) environment_random_gaussian_spatial_2d (this, num, centroid, fixdepth, variance, variance_depth)
 Generates a vector of random spatial object with Gaussian coordinates within (i.e. bound to) this environment. The depth coordinate is set separately and can be non-random (fixed for the whole output array) or Gaussian with separate variance. More...
 
subroutine environment_get_nearest_point_in_outside_obj (this, outside_object, offset_into, point_spatial, point_dist)
 Get the spatial point position within this environment that is nearest to an arbitrary spatial object located outside of the this environment. If the spatial object is actually located in this environment, return its own position. More...
 
subroutine spatial_fix_position_3d_s (this, x, y, depth)
 Place spatial object into a 3D space, define the object's current coordinates. More...
 
elemental subroutine spatial_fix_position_3d_o (this, location)
 Place spatial object into a 3D space, define the object's current coordinates. More...
 
elemental subroutine spatial_make_missing (this)
 Assign all commondata::missing` coordinates to the_environment::spatial object. More...
 
elemental type(spatial) function spatial_get_current_pos_3d_o (this)
 Get the current spatial position of a SPATIAL object. More...
 
pure real(srp) function, dimension(dimensionality_defaultspatial_get_current_pos_3d_v (this, vector)
 Get the current spatial position of a SPATIAL object. More...
 
elemental real(srp) function spatial_get_current_pos_x_3d (this)
 Get the current X position of a SPATIAL object. More...
 
elemental real(srp) function spatial_get_current_pos_y_3d (this)
 Get the current Y position of a SPATIAL object. More...
 
elemental real(srp) function spatial_get_current_pos_d_3d (this)
 Get the current DEPTH position of a SPATIAL object. More...
 
real(srp) function spatial_calc_irradiance_at_depth (this, time_step_model)
 Calculate the illumination (background irradiance) at the depth of the spatial object at an arbitrary time step of the model. More...
 
real(srp) function spatial_visibility_visual_range_cm (this, object_area, contrast, time_step_model)
 Calculate the visibility range of a spatial object. Wrapper to the the_environment::visual_range() function. This function calculates the distance from which this object can be seen by a visual object (e.g. predator or prey). More...
 
pure integer function spatial_get_environment_in_pos (this, environments_array)
 Identify in which environment from the input list this spatial agent is currently in. Example call: More...
 
subroutine spatial_moving_fix_position_3d_v (this, x, y, depth)
 Place spatial movable object into a 3D space, define the object's current coordinates, but first save previous coordinates. More...
 
elemental subroutine spatial_moving_fix_position_3d_o (this, location)
 Place spatial movable object into a 3D space, define the object's current coordinates, but first save previous coordinates. More...
 
elemental subroutine spatial_moving_repeat_position_history_3d (this)
 Repeat (re-save) the current position into the positional history stack. More...
 
elemental real(srp) function spatial_distance_3d (this, other)
 Calculate the Euclidean distance between two spatial objects. This is a type-bound function. More...
 
pure type(spatial) function, dimension(:), allocatable spatial_stack2arrays (a, b)
 Concatenate two arrays of the_environment::spatial objects a and b. This procedure uses array slices which would be faster in most cases than the intrinsic [a,b] method. More...
 
pure type(spatial_moving) function, dimension(:), allocatable spatial_moving_stack2arrays (a, b)
 Concatenate two arrays of the_environment::spatial_moving objects a and b. This procedure uses array slices which would be faster in most cases than the intrinsic [a,b] method. More...
 
pure type(spatial) function, dimension(:), allocatable spatial_class_stack2arrays_locs (a, b)
 Concatenate the location components of two arrays of the_environment::spatial class objects a and b. This procedure uses array slices which would be faster in most cases than the intrinsic [a,b] method. More...
 
elemental real(srp) function dist3d (this, other)
 This is a non-type-bound version of the distance calculation function. More...
 
elemental real(srp) function spatial_self_distance_3d (this, from_history)
 Calculate the Euclidean distance between the current and previous position of a single spatial object. More...
 
elemental real(srp) function spatial_moving_self_distance_3d (this, from_history)
 Calculate the Euclidean distance between the current and previous position of a single spatial movable object. Optionally, it also calculates the total distance traversed during the from_history points from the history stack along with the distance from the current position and the last historical value. For example, to calculate the average distance throughout the whole history (HISTORY_SIZE_SPATIAL points) do this: More...
 
elemental subroutine spatial_moving_create_3d (this)
 Create a new spatial moving object. Initially it has no position, all coordinate values are MISSING or INVALID for real type coordinates. More...
 
elemental subroutine spatial_moving_clean_hstory_3d (this)
 Create a new empty history of positions for spatial moving object. Assign all values to the MISSING value code. More...
 
elemental subroutine spatial_moving_go_up (this, step)
 The spatial moving object ascends, goes up the depth with specific fixed step size. More...
 
elemental subroutine spatial_moving_go_down (this, step)
 The spatial moving object decends, goes down the depth with specific fixed step size. More...
 
subroutine spatial_moving_randomwalk_gaussian_step_3d (this, meanshift, cv_shift, environment_limits)
 Implements an optionally environment-restricted Gaussian random walk in 3D. More...
 
subroutine spatial_moving_randomwalk_gaussian_step_25d (this, meanshift_xy, cv_shift_xy, meanshift_depth, cv_shift_depth, environment_limits)
 Implements an optionally environment-restricted Gaussian random walk in a "2.5 dimensions", i.e. 2D x y with separate walk parameters for the third depth dimension. More...
 
subroutine spatial_moving_corwalk_gaussian_step_3d (this, target, meanshift, cv_shift, is_away, ci_lim, environment_limits, is_converged, debug_reps)
 Implements an optionally environment-restricted correlated directional Gaussian random walk in 3D towards (or away of) an the_environment::spatial class target object. More...
 
subroutine spatial_moving_corwalk_gaussian_step_25d (this, target, meanshift_xy, cv_shift_xy, meanshift_depth, cv_shift_depth, is_away, ci_lim, environment_limits, is_converged, debug_reps)
 Implements an optionally environment-restricted correlated directional Gaussian random walk in 3D towards (or away of) an the_environment::spatial class target object. More...
 
subroutine spatial_moving_dirwalk_gaussian_step_3d (this, target, meanshift, cv_shift, environment_limits)
 Implements an optionally environment-restricted directional Gaussian random walk in 3D towards a target the_environment::spatial class object. More...
 
subroutine spatial_moving_dirwalk_gaussian_step_25d (this, target, meanshift_xy, cv_shift_xy, meanshift_depth, cv_shift_depth, environment_limits)
 Implements an optionally environment-restricted directional Gaussian random walk in "2.5"-D towards a target the_environment::spatial class object. i.e. 2D x y with separate walk parameters for the third depth dimension. More...
 
subroutine rwalk3d_array (this, dist_array, cv_array, dist_all, cv_all, environment_limits, n_walks)
 Perform one or several steps of random walk by an array of the_environment::spatial_moving class objects. This is a 3D version with the same walk parameters for the horizontal XxY plane and depth. More...
 
subroutine rwalk25d_array (this, dist_array_xy, cv_array_xy, dist_array_depth, cv_array_depth, dist_all_xy, cv_all_xy, dist_all_depth, cv_all_depth, environment_limits, n_walks)
 Perform one or several steps of random walk by an array of the_environment::spatial_moving class objects. This is a 2.5D version with separate walk parameters for the horizontal XxY plane and depth. More...
 
elemental logical function spatial_check_located_within_3d (this, environment_limits)
 Function to check if this spatial object is located within an area set by an environmental object (parameter). This should be similar to an analogous function defined for the environment object. More...
 
elemental logical function spatial_check_located_below (this, check_object)
 Logical function to check if the argument spatial object(s) (check_object) is (are) located below the this reference spatial object. Elemental function that also works with arrays. Use as: More...
 
elemental logical function spatial_check_located_above (this, check_object)
 Logical function to check if the argument spatial object(s) (check_object) is (are) located above the this reference spatial object. Elemental function that also works with arrays. Use as: More...
 
type(spatial) function spatial_get_nearest_object (this, neighbours, number)
 Determine the nearest spatial object to this spatial object among an array of other spatial objects. More...
 
integer function spatial_get_nearest_id (this, neighbours, object)
 Determine the nearest spatial object to this spatial object among an array of other spatial objects. More...
 
subroutine habitat_make_init (this, coord_min, coord_max, label, otherrisks, eggmortality, predators_number, loc_predators, food_abundance, loc_food, sizes_food)
 Make an instance of the habitat object (an environment superset). More...
 
character(len=label_length) function habitat_name_get (this)
 Return the name of the habitat. More...
 
real(srp) function habitat_get_risk_mortality (this)
 Get the mortality risk associated with this habitat. More...
 
real(srp) function habitat_get_risk_mortality_egg (this)
 Get the egg mortality risk associated with this habitat. More...
 
subroutine habitat_save_predators_csv (this, csv_file_name, is_success)
 Save the predators with their characteristics into a CSV file. More...
 
subroutine save_dynamics (maxdepth, csv_file_name, is_success)
 Save diagnostics data that shows the dynamics of the light and the average depth of the food items, light at the average depth of the food items etc at each time step of the model. More...
 
type(spatial) function environment_centre_coordinates_3d (this, nodepth)
 Determine the centroid of the environment. More...
 
real(srp) function, private visual_range_scalar (irradiance, prey_area, prey_contrast)
 Wrapper for calculating visual range of a fish predator using the Dag Aksnes's procedures srgetr(), easyr() and deriv(). See srgetr() for computational details. More...
 
real(srp) function, dimension(size(prey_area)), private visual_range_vector (irradiance, prey_area, prey_contrast_vect, prey_contrast)
 Wrapper for calculating visual range of a fish predator using the Dag Aksnes's procedures srgetr(), easyr() and deriv(). See srgetr() for computational details. More...
 
elemental real(srp) function visual_range_fast (irradiance, prey_area, prey_contrast)
 Wrapper for calculating visual range of a fish predator using the Dag Aksnes's procedures srgetr(), easyr() and deriv(). This is a new elemental and parallel-ready visual range function wrapper making use the elemental-procedures based computational backend. See notes on visual_range_scalar() and srgetr() for computational details. More...
 
elemental real(srp) function, private light_surface_deterministic (tstep)
 Calculate deterministic surface light at specific time step of the model. Light (surlig) is calculated from a sine function. Light intensity just beneath the surface is modelled by assuming a 50 % loss by scattering at the surface: More...
 
real(srp) function, private light_surface_stochastic_scalar (tstep, is_stochastic)
 Calculate stochastic surface light at specific time step of the model. Light (surlig) is calculated from a sine function. Light intensity just beneath the surface is modelled by assuming a 50 % loss by scattering at the surface: More...
 
real(srp) function, dimension(size(tstep)), private light_surface_stochastic_vector (tstep, is_stochastic)
 Calculate stochastic surface light at specific time step of the model. More...
 
real(srp) function, private light_depth_integer (depth, surface_light, is_stochastic)
 Calculate underwater light at specific depth given specific surface light. More...
 
real(srp) function, private light_depth_real (depth, surface_light, is_stochastic)
 Calculate underwater light at specific depth given specific surface light. More...
 
elemental real(srp) function dist_scalar (x1, x2, y1, y2, z1, z2)
 Calculate distance between 3D or 2D points. This is a function engine for use within type bound procedures. Example (dist_scalar): More...
 
pure real(srp) function dist_vector_nd (cvector1, cvector2)
 Calculate distance between N-dimensional points. This is a function engine for use within other type bound procedures. More...
 
pure real(srp) function dist2_vector (cvector1, cvector2)
 Calculate the squared distance between two N-dimensional points. More...
 
pure real(srp) function vect_magnitude (vector)
 Calculate the magnitude of an arbitrary N-dimensional vector. This is a raw vector backend. More...
 
elemental real(srp) function dist2step (average_distance, dimensionality)
 Calculate the unit step along a single coordinate axis given the average distance between any two points in a N-dimensional Gaussian random walk. More...
 
elemental subroutine food_item_create (this)
 Create a single food item at an undefined position with default size. More...
 
elemental subroutine food_item_make (this, location, size, iid)
 Make a single food item, i.e. place it into a specific position in the model environment space and set the size. More...
 
logical function food_item_capture_success_stochast (this, prob)
 Stochastic outcome of this food item capture by an agent. Returns TRUE if the food item is captured. More...
 
real(srp) function food_item_capture_probability_calc (this, distance, time_step_model)
 Calculate the probability of capture of this food item by a predator agent depending on the distance between the agent and this food item. More...
 
real(srp) function food_item_visibility_visual_range (this, object_area, contrast, time_step_model)
 Calculate the visibility range of this food item. Wrapper to the the_environment::visual_range() function. This function calculates the distance from which this food item can be seen by a predator (i.e. the default predator's visual range). More...
 
real(srp) function minimum_depth_visibility (target_range, depth_range_min, depth_range_max, object_area, object_contrast, time_step_model)
 Find the depth at which the visibility of a spatial object becomes smaller than a specific distance value target_range. More...
 
elemental subroutine food_item_disappear (this)
 Make the food item "disappear" and take the "eaten" state, i.e. impossible for consumption by the agents. More...
 
elemental logical function food_item_is_eaten_unavailable (this)
 Logical check-indicator function for the food item being eaten and not available. More...
 
elemental logical function food_item_is_available (this)
 Logical check-indicator function for the food item being available. More...
 
elemental real(srp) function food_item_get_size (this)
 Get the size component of the food item object. More...
 
elemental real(srp) function size2mass_food (radius)
 Calculate the mass of a food item, the non-OO backend. More...
 
elemental real(srp) function mass2size_food (mass)
 Calculate the size (radius) of a food item, a reverse function of the_environment::size2mass_food(): More...
 
elemental real(srp) function food_item_get_mass (this)
 Calculate and get the mass of the food item. More...
 
elemental subroutine food_item_set_iid (this, iid)
 Set unique id for the food item object. More...
 
elemental subroutine food_item_clone_assign (this, the_other)
 Clone the properties of this food item to another food item. More...
 
elemental integer function food_item_get_iid (this)
 Get the unique id of the food item object. More...
 
pure subroutine food_resource_make (this, label, abundance, locations, sizes)
 Make food resource object. This class standard constructor. More...
 
elemental integer function food_resource_get_abundance (this)
 Get the number of food items in the food resource. More...
 
elemental character(len=label_length) function food_resource_get_label (this)
 Get the label of the this food resource. More...
 
pure subroutine food_resource_destroy_deallocate (this)
 Delete and deallocate food resource object. This class standard destructor. More...
 
pure type(spatial) function, dimension(size(this%food)) food_resource_locate_3d (this)
 Get the location object array (array of SPATIAL objects) of a food resource object. More...
 
real(srp) function food_resource_calc_average_distance_items (this, n_sample)
 Calculate the average distance between food items within a resource. e.g. to compare it with the agent's random walk step size. More...
 
subroutine food_resource_replenish_food_items_all (this, replace)
 Replenish and restore food resource. The food resource is replenished by substituting randomly selected replace food items or all items if replace is omitted or exceeds the actual number of food items. Unlike the the_environment::food_resource::make() method, the sizes and the positions of the food items within the resource are reused from the previous positions (previously explicitly set set by the the_environment::food_resource::make() method). More...
 
subroutine food_resource_migrate_move_items (this, max_depth, time_step_model)
 This subroutine implements the migration of all the food items in the resource according to the plankton migration pattern from the G1 model (HED18). Briefly, the movement of each of the food items has two components: More...
 
subroutine food_resource_rwalk_items_default (this)
 Perform a random walk step for all food items within the food resource. The walk is performed with the default parameters: More...
 
subroutine migrate_food_vertical (habitats, time_step_model)
 Migrate food items in a whole array of food resources. The array is normally the the_environment::global_habitats_available. More...
 
subroutine rwalk_food_step (habitats)
 Perform a random walk of food items in a whole array of food resources. The array is normally the the_environment::global_habitats_available. This procedure is a wrapper for the_environment::food_resource::rwalk() to do a walk on a whole array of habitats and linked food resources. More...
 
real(srp) function center_depth_sinusoidal (tstep, depth)
 This function calculates the target depth for the sinusoidal vertical migration pattern of the food items at each time step of the model. See the_environment::food_resource_migrate_move_items() for the calling procedure. More...
 
subroutine food_resource_save_foods_csv (this, csv_file_name, is_success)
 Save characteristics of food items in the resource into a CSV file. More...
 
elemental subroutine food_resource_sort_by_size (this, reindex)
 Sort the food resource objects within the array by their sizes. The two subroutines below are a variant of the recursive quick-sort algorithm adapted for sorting real components of the the FOOD_RESOURCE object. More...
 
pure subroutine food_resource_reset_iid_all (this, start_iid)
 Reset individual iid for the food resource. Individual iids must normally coincide with the array order index. If it is changed after sorting, iids no longer reflect the correct index. So this subroutine resets iids to be coinciding with each food item index. More...
 
subroutine reindex_food_resources (resource_1, resource_2, resource_3, resource_4, resource_5, resource_6, resource_7, resource_8, resource_9, resource_10, resource_11, resource_12, resource_13, resource_14, resource_15, resource_16, resource_17, resource_18, resource_19, resource_20)
 Reset and reindex iids for an input list of several food resources. As the result of this subroutine all food items across all the resources within the whole list will have unique iids. More...
 
subroutine food_resources_collapse (food_resource_collapsed, resource_1, resource_2, resource_3, resource_4, resource_5, resource_6, resource_7, resource_8, resource_9, resource_10, resource_11, resource_12, resource_13, resource_14, resource_15, resource_16, resource_17, resource_18, resource_19, resource_20, reindex, label)
 Collapse several food resources into one. The collapsed resource can then go into the perception system. The properties of the component resources are retained in the collapsed resource. More...
 
type(food_resource) function food_resources_collapse_global_object (reindex, label)
 Join food resources into a single global food resource out of the global array the_environment::global_habitats_available. See the_environment::unjoin() for how to unjoin an array of food resources back into an array. The joined resource can then go into the perception system. The properties of the component resources are retained in the collapsed resource. More...
 
subroutine food_resources_update_back (food_resource_collapsed, resource_1, resource_2, resource_3, resource_4, resource_5, resource_6, resource_7, resource_8, resource_9, resource_10, resource_11, resource_12, resource_13, resource_14, resource_15, resource_16, resource_17, resource_18, resource_19, resource_20, reindex)
 Transfer back the resulting food resources into their original objects out from a collapsed object from food_resources_collapse. More...
 
subroutine food_resources_update_back_global_object (food_resource_collapsed, reindex)
 Transfer the (having been modified) food resource objects from the single united object food_resource_collapsed back to the global array the_environment::global_habitats_available array. See the_environment::join() for how to join an array of food resources into a single global object. More...
 
subroutine global_habitats_assemble (habitat_1, habitat_2, habitat_3, habitat_4, habitat_5, habitat_6, habitat_7, habitat_8, habitat_9, habitat_10, habitat_11, habitat_12, habitat_13, habitat_14, habitat_15, habitat_16, habitat_17, habitat_18, habitat_19, habitat_20, reindex)
 Assemble the global habitats objects array the_environment::global_habitats_available from a list of separate habitat objects. This call. More...
 
subroutine global_habitats_disassemble (habitat_1, habitat_2, habitat_3, habitat_4, habitat_5, habitat_6, habitat_7, habitat_8, habitat_9, habitat_10, habitat_11, habitat_12, habitat_13, habitat_14, habitat_15, habitat_16, habitat_17, habitat_18, habitat_19, habitat_20, reindex)
 Disassemble the global habitats objects array the_environment::global_habitats_available into separate habitat object. More...
 
subroutine spatial_neighbours_distances (this, neighbours, dist, index_vector, ranks, rank_max, error_flag)
 Calculate the distances between this spatial object and an array of its neighbours. Optionally output the distances, sorting index vector and rankings vector for each of these neighbours. Optionally do only partial indexing, up to the order rank_max for computational speed. Procedure ARRAY_INDEX() from HEDTOOLS is used as the computational backend for partial segmented indexing. More...
 
elemental subroutine predator_make_init (this, body_size, attack_rate, position, label)
 Initialise a predator object. More...
 
subroutine predator_label_set (this, label)
 Set label for the predator, if not provided, set it random. More...
 
elemental real(srp) function predator_get_body_size (this)
 Accessor function for the predator body size (length). More...
 
elemental real(srp) function predator_get_attack_rate (this)
 Accessor function for the predator attack rate. More...
 
real(srp) function predator_capture_risk_calculate_fish (this, prey_spatial, prey_length, prey_distance, is_freezing, time_step_model, debug_plot_file)
 Calculates the risk of capture of the fish with the spatial location defined by prey_spatial and the body length equal to prey_length. This is a backend function bound to the predator rather than prey object. More...
 
subroutine predator_capture_risk_calculate_fish_group (this, prey_spatial, prey_length, is_freezing, time_step_model, risk, risk_indexed, index_dist)
 Calculates the risk of capture by a specific predator of an array of the fish agents with the spatial locations array defined by prey_spatial and the body length array prey_length. This subroutine takes account of both the predator dilution and confusion effects and risk adjusted by the distance towards the predator. More...
 
real(srp) function predator_visibility_visual_range (this, object_area, contrast, time_step_model)
 Calculate the visibility range of this predator. Wrapper to the the_environment::visual_range() function. This function calculates the distance from which this predator can be seen by a visual object (e.g. the agent). More...
 
real(srp) function distance_average (spatial_objects, sample_size)
 Calculates the average nearest neighbour distance amongst an array of spatial objects (class) by sampling sample_size of them. The sample size sample_size is optional, if not provided set to SAMPLE_SIZE_DEFAULT=25. More...
 
Visual range calculation backend.

The subroutines the_environment::srgetr(), the_environment::easyr() and the_environment::deriv() should be better isolated into a separate module or form a submodule, but it is not used here as submodules are a F2008 feature not supported by all compiler systems. Anyway, submodule is not essential here.

Note
Note that all these backend procedures are now pure and therefore parallel-safe.
elemental subroutine, private srgetr (r, c, C0, Ap, Vc, Ke, Eb, IER)
 Obtain visual range by solving the non-linear equation by means of Newton-Raphson iteration and derivation in subroutine the_environment::deriv(). Initial value is calculated in the_environment::easyr(). The calculation is based on the model described in Aksnes & Utne (1997) Sarsia 83:137-147. More...
 
elemental subroutine, private easyr (r, C0, Ap, Vc, Ke, Eb)
 Obtain a first estimate of visual range by using a simplified expression of visual range. See srgetr() for more details. More...
 
elemental subroutine, private deriv (r, F1, FDER, c, C0, Ap, Vc, Ke, Eb)
 Derivation of equation for visual range of a predator. See the_environment::srgetr() for more details. More...
 
Computational geometry backend: <strong>polygon2D</strong>

Rudimentary computational geometry (geo_) procedures, based on 2D polygons (poly2d) with fixed depth or depth ignored.

Note
Manually constructed using 2D X x Y vectors ignoring the depth dimension.
subroutine geo_poly2d_dist_point_to_section (point, sectp1, sectp2, min_dist, point_segment)
 Calculates the minimum distance from a the_environment::spatial class object to a line segment delimited by two the_environment::spatial class endpoints in the 2D XY plane (the depth coordinate is ignored). (The algorithm is partially based on this.) More...
 
subroutine geo_poly3d_dist_point_to_section (point, sectp1, sectp2, min_dist, point_segment)
 Calculates the minimum distance from a the_environment::spatial class object to a line segment delimited by two the_environment::spatial class endpoints in the 3D XY space. (The algorithm is partially based on this.) More...
 
type(spatial) function offset_dist (obj_a, obj_b, offset)
 Calculate a the_environment::spatial target with an offset. More...
 

Variables

character(len= *), parameter, private modname = "(THE_ENVIRONMENT)"
 
integer, parameter, private dimensionality_default = 3
 Default dimensionality of the environment universe. More...
 
integer, parameter dim_environ_corners = 4
 The number of corners for an environment object in the 2D X*x*Y plane. More...
 
type(habitat), dimension(:), allocatable, public global_habitats_available
 A list (array) of all the the_environment::habitat objects available to the agents. This single array should encompass all the locations that the agent can potentially be in (e.g. migrate from one to another). More...
 

Detailed Description

Definition of environmental objects.

THE_ENVIRONMENT module

This module defines various environment objects and primitives, starting from the basic primitive a spatial object the_environment::spatial. This object represents a point in a three-dimensional space. The agent class hierarchy starts from this spatial primitive as the agent is a spatial object.

Function/Subroutine Documentation

◆ spatial_create_empty()

elemental subroutine the_environment::spatial_create_empty ( class(spatial), intent(inout)  this)

These are public access functions, but probably we don't need to allow public access to functions inside generic interfaces.

We do not need specific functions outside of this module, always use generic functions. Create an empty spatial object. The object's starting coordinates get all MISSING values.

Definition at line 939 of file m_env.f90.

◆ environment_whole_build_vector()

subroutine the_environment::environment_whole_build_vector ( class(environment), intent(inout)  this,
real(srp), dimension(3), intent(in)  min_coord,
real(srp), dimension(3), intent(in)  max_coord 
)

Create the highest level container environment. Set the size of the 3D environment container as two coordinate vectors setting the minimum and maximum coordinate limits: min_coord(1) for x, min_coord(2) for y, min_coord(3) for z The size of the environment should be set from parameter vectors in COMMONDATA.

Parameters
min_coordMinimum coordinate bound for the environment.
max_coordMaximum coordinate bound for the environment.
Note
This version accepts simple arrays as the environment coordinates.
Warning
Not-extensible version. TODO: Do we need it? Deprecate? There is a generic function build that should normally be used.

Definition at line 958 of file m_env.f90.

◆ environment_whole_build_object()

subroutine the_environment::environment_whole_build_object ( class(environment), intent(inout)  this,
type(spatial), intent(in)  min_coord,
type(spatial), intent(in)  max_coord 
)

Create the highest level container environment. Set the size of the 3D environment container as two coordinate vectors setting the minimum and maximum coordinate limits. The parameters min_coord and max_coord are SPATIAL objects.

Parameters
min_coordMinimum coordinate bound for the environment, SPATIAL object.
max_coordMaximum coordinate bound for the environment, SPATIAL object.
Note
This version accepts SPATIAL objects as the environment coordinates.

Definition at line 988 of file m_env.f90.

◆ environment_build_unlimited()

subroutine the_environment::environment_build_unlimited ( class(environment), intent(inout)  this)

Build an unlimited environment, with the spatial coordinates limited by the maximum machine supported values based on the intrinsic huge function.

Definition at line 1005 of file m_env.f90.

◆ environment_shrink_xy_fixed()

type(environment) function the_environment::environment_shrink_xy_fixed ( class(environment), intent(in)  this,
real(srp), intent(in)  shrink_value 
)

Return an environment object that is shrunk by a fixed value in the 2D XxY plane.

Here is an illustration of the function. The outer box is the input environment, the inner box is the shrunken environment that is returned. The shrinkage value is fixed, defined by the second function parameter. The depth is ignored in this function working with the simplistic box-like environment objects.

 min_coord is obtained   +---------------------+
 by coordinate addition; | +                   |
                         |   +-------------+   |
                         |   |             |   |
                         |-->|             |<--|
                         |   |             |   |
                         |   |             |   |
                         |   +-------------+   |
                         |                   - |  max_coord is obtained by
                         +---------------------+  coordinate subtraction.

There is a user defined operator - (minus), that can be used as follows:

temp_hab = habitat_safe - 0.5_srp
Warning
Valid only for the simplistic box-like environments; should be reimplemented if the environment is implemented as an arbitrary polyhedron.

Definition at line 1047 of file m_env.f90.

◆ environment_get_minimum_obj()

type(spatial) function the_environment::environment_get_minimum_obj ( class(environment), intent(in)  this)

Function to get the minimum spatial limits (coordinates) of the environment.

Returns
The minimum spatial bound of the environment, as a SPATIAL object.

Definition at line 1066 of file m_env.f90.

◆ environment_get_maximum_obj()

type(spatial) function the_environment::environment_get_maximum_obj ( class(environment), intent(in)  this)

Function to get the maximum spatial limits (coordinates) of the environment.

Returns
The maximum spatial bound of the environment, as a SPATIAL object.

Definition at line 1082 of file m_env.f90.

◆ environment_get_minimum_depth()

elemental real(srp) function the_environment::environment_get_minimum_depth ( class(environment), intent(in)  this)

Get the minimum depth in this environment.

Returns
The maximum depth of this environment

Definition at line 1095 of file m_env.f90.

◆ environment_get_maximum_depth()

elemental real(srp) function the_environment::environment_get_maximum_depth ( class(environment), intent(in)  this)

Get the maximum depth in this environment.

Returns
The maximum depth of this environment

Definition at line 1106 of file m_env.f90.

◆ environment_get_corners_2dxy()

pure type(spatial) function, dimension(dim_environ_corners) the_environment::environment_get_corners_2dxy ( class(environment), intent(in)  this,
real(srp), intent(in), optional  ref_depth,
real(srp), intent(in), optional  offset 
)

Get the corners of the environment in the 2D X Y plane. This is a very simplistic procedure that works only with the box environmental objects.

Warning
Should be reimplemented if the environment is implemented as an arbitrary polyhedron.
Parameters
[in]ref_depthref_depth optional parameter setting the fixed depth for the returned corner objects. If not provided, a fixed default value equal to the local parameter REF_DEPTH_DEF=0.0 is used.
[in]offsetoffset The offset that can be set to make the borders and corners of the environment inside at a fixed value. If offset is absent, the actual corners of the environment are returned. The offset parameter works as the shrink2d function (the_environment::environment::shrink2d()`.
              .---------------------.
              | +                   |
              |   *-------------*   |
              |   |             |   |
              |   |             |<--| offset shrinks corners
              |   |             |   |
              |   |             |   |
              |   *-------------*   |
              |                   - |
              .---------------------.
Returns
Returns an array of the environment corners in the 2D X x Y plane. The number of corners for the environment object in the 2D X x Y plane is defined by the parameter constant the_environment::dim_environ_corners.

Implementation details

The corners 1,2,3,4 of the simplistic box-like environmental object are defined as follows:

   (1:minX,minY) ----- (2:maxX,minY)
    |                         |
   (4:minX,maxY) ----- (3:maxX,maxY)

These four points are returned as the the_environment::spatial class objects.

Warning
The order of the points is important because it is also used in the nearest_target procedure the_environment::environment_get_nearest_point_in_outside_obj().

Definition at line 1120 of file m_env.f90.

◆ environment_check_located_within_3d()

elemental logical function the_environment::environment_check_located_within_3d ( class(environment), intent(in)  this,
class(spatial), intent(in)  check_object 
)

Check if a spatial object is actually within this environment.

Returns
TRUE if the spatial object is located within the environment.
Parameters
check_objectA spatial object (SPATIAL or any extension) to check. There is a user-defined operator:
if ( environment .contains. object ) then

Definition at line 1207 of file m_env.f90.

◆ environment_random_uniform_spatial_3d()

type(spatial) function the_environment::environment_random_uniform_spatial_3d ( class(environment), intent(in)  this)

Generate a random spatial object with the uniform distribution within (i.e. bound to) this environment.

Returns
uniformly distributed random SPATIAL object bound to this environment.

Definition at line 1239 of file m_env.f90.

◆ environment_random_uniform_spatial_2d()

type(spatial) function the_environment::environment_random_uniform_spatial_2d ( class(environment), intent(in)  this,
real(srp), intent(in)  fixdepth 
)

Generate a random spatial object with the uniform distribution within (i.e. bound to) this environment, the third depth coordinate is fixed.

Returns
uniformly distributed random SPATIAL object bound to this environment.

Definition at line 1261 of file m_env.f90.

◆ environment_random_uniform_spatial_vec_3d()

type(spatial) function, dimension(num) the_environment::environment_random_uniform_spatial_vec_3d ( class(environment), intent(in)  this,
integer, intent(in)  num 
)

Generate a vector of random spatial objects with the uniform distribution within (i.e. bound to) this environment.

Parameters
thedimension(size) of the vector to generate
Returns
uniformly distributed random SPATIAL object bound to this environment.
Warning
Intel Fortran porting note. This whole array function does not work under Intel Fortran 13, issues stack overflow runtime error, although compiles without issues: loc_food_here = thisuniform(thisfoodnumber_food_items).

Definition at line 1290 of file m_env.f90.

◆ environment_random_uniform_spatial_vec_2d()

type(spatial) function, dimension(size(fixdep_array)) the_environment::environment_random_uniform_spatial_vec_2d ( class(environment), intent(in)  this,
real(srp), dimension(:), intent(in)  fixdep_array 
)

Generate a vector of random spatial objects with the uniform distribution within (i.e. bound to) this environment. The third, depth coordinate is non-stochastic, and provided as an array parameter.

Parameters
thedimension(size) of the vector to generate
Returns
uniformly distributed random SPATIAL object bound to this environment.

Implementation details

We call the type bound uniform_s=>environment_random_uniform_spatial_3d to get a vector of uniformly-distributed spatial objects.

Definition at line 1331 of file m_env.f90.

◆ environment_random_gaussian_spatial_3d()

type(spatial) function, dimension(num) the_environment::environment_random_gaussian_spatial_3d ( class(environment), intent(in)  this,
integer, intent(in)  num,
class(spatial), intent(in), optional  centroid,
real(srp), intent(in), optional  variance 
)

Generates a vector of random spatial object with Gaussian coordinates within (i.e. bound to) this environment.

Parameters
numthe dimension(size) of the vector to generate
centroidOptional centroid of the Gaussian scatter. If not provided, will select random uniformly distributed point.
varianceGaussian variance parameter.
Returns
Gaussian ranrom SPATIAL object bound to this environment.

Implementation details

First, check optional centroid and set local centroid.

The centroid that is provided is accepted only if it is within this environment.

If a centroid is provided but is outside of the environment, reset it to random uniform.

Now, generate Gaussian spatial objects and fill the output array.

First, generate random Gaussian coordinanes for a temporary spatial object.

Make sure this spatial object is within the bounding environment.

Finally, set assign the output array component to this object.

Definition at line 1370 of file m_env.f90.

◆ environment_random_gaussian_spatial_2d()

type(spatial) function, dimension(num) the_environment::environment_random_gaussian_spatial_2d ( class(environment), intent(in)  this,
integer, intent(in)  num,
class(spatial), intent(in), optional  centroid,
real(srp), intent(in), optional  fixdepth,
real(srp), intent(in), optional  variance,
real(srp), intent(in), optional  variance_depth 
)

Generates a vector of random spatial object with Gaussian coordinates within (i.e. bound to) this environment. The depth coordinate is set separately and can be non-random (fixed for the whole output array) or Gaussian with separate variance.

Parameters
numthe dimension(size) of the vector to generate
centroidOptional centroid of the Gaussian scatter. If not provided, will select random uniformly distributed point.
fixdepthOptional fixed depth for the generated Gaussian objects.
varianceGaussian variance parameter.
variance_depthGaussian variance parameter for the fixed depth.
Returns
Gaussian random SPATIAL object bound to this environment.

Implementation details

First, check optional centroid parameter and set local centroid.

Make sure fixdepth is within the allowed environmental range.

If fixed depth is provided, we use the centroid but take the depth from the fixdepth parameter.

And check if the resulting centroid is within this environment. If not, make it random uniform making use of the fixed depth.

If the fixdepth is not conformant with this environment, use centroid provided and discard the fixdepth parameter

And check if the resulting centroid is within this environment, if not, discard both the centroid and the fixed depth parameters and use random uniform centroid as the last resort.

If fixed depth is not provided, however, we use the fixed depth from the centroid

The centroid that is provided is accepted only if it is within this environment.

If a centroid is provided but is outside of the environment, reset it to random uniform.

Check if it's conformant with the environment. Use if if okay.

If the depth provided is not conformant, discard and use random.

Finally, if neither centroid nor depth is provided, use random uniform.

Check if separate variance parameter for the depth is provided. This sets if stochastic depth is to be generated.

If separate depth variance parameter is provided, depth is stochastic Gaussian. Generate Gaussian spatial objects and fill the output array.

First, generate random Gaussian coordinanes for a temporary spatial object.

Finally, set assign the output array component to this object.

If there is no separate variance parameter for the depth, depth fixed deterministic, identical in for the whole array. Set the fixed depth.

Now, generate Gaussian spatial objects and fill the output array.

First, generate random Gaussian coordinanes for a temporary spatial object.

Finally, set assign the output array component to this object.

Definition at line 1450 of file m_env.f90.

Here is the call graph for this function:

◆ environment_get_nearest_point_in_outside_obj()

subroutine the_environment::environment_get_nearest_point_in_outside_obj ( class(environment), intent(in)  this,
class(spatial), intent(in)  outside_object,
real(srp), intent(in), optional  offset_into,
type(spatial), intent(out), optional  point_spatial,
real(srp), intent(out), optional  point_dist 
)

Get the spatial point position within this environment that is nearest to an arbitrary spatial object located outside of the this environment. If the spatial object is actually located in this environment, return its own position.

Note
This function is necessary for the implementation of migration behaviour across two or several environments or habitats: it allows to set the (nearest) target point in the desired target environment.
Warning
Valid only for the simplistic box-like environments; should be reimplemented if the environment is implemented as an arbitrary polyhedron.
Parameters
[in]outside_objectoutside_object is the outside object, the minimum distances to the environment and the closest point are evaluated for this object.
[in]offset_intooffset_into optional offset guaranteeing that the nearest point is located more or less deeply within the this target environment rather than just at the border of the environment. This parameter is useful if the nearest point in the environment actually sets the target point, to which the agent represented by the outside_object spatial is relocating. In such a case, the agent is therefore moving into the environment, at a distance offset_into rather than just to the edge of this target environment. This is illustrated by the below:
              .----------------------. this environment
              | +                    |
              |   *--------------*   |
              |   | target point |   |          outside_object
              |   | is inside   (*)<------------<*=><
              |   |              |   |
              |   |             >|---|<-------- offset_into
              |   *--------------*   |
              |                    - |
              .------------------ ---.
[out]point_spatial
Returns
The point within the this environment that is the nearest to the outside_object the_environment::spatial class target object.

Implementation notes

First, check if the outside object is actually located within the target environment.

  • If so, the distance between the object and the environment is zero. This is a degenerate case that is treated separately: the nearest point within the environment coincides with the location of the outside object itself.

If the object is indeed outside, determine the four corners of the this environment. These corners are delimiting the outside of the this environment. The reference depth is set to the depth of the outside object.

@nolte Note that if the offset_into offset parameter is set, the corners are adjusted to this offset value, so that they are actually inside the this environment object.

Calculate the distances and the nearest points between the outside object and the four outer segments (1,2), (2,3), (3,4), (4,1).

Warning
This fast but unsafe implementation requires the same order of points to be set also in the the_environment::environment_get_corners_2dxy(). For arbitrary order of points, a full cross loop is needed, with the sizes of the segment_nearest_obj segment_distance arrays set to the square DIM_ENVIRON_CORNERS * DIM_ENVIRON_CORNERS.
   1, 2               1------------2
   2, 3               |            |
   3, 4               |            |
   4, 1               4------------3

Finally, the returned nearest point is the point where the distance between the outside point and any of the outer segments of the environment reaches the minimum value.

Definition at line 1632 of file m_env.f90.

◆ spatial_fix_position_3d_s()

subroutine the_environment::spatial_fix_position_3d_s ( class(spatial), intent(inout)  this,
real(srp), intent(in)  x,
real(srp), intent(in)  y,
real(srp), intent(in)  depth 
)

Place spatial object into a 3D space, define the object's current coordinates.

Parameters
coordinatesThe spatial objects will now get these coordinates.
Note
This is actually the constructor for the SPATIAL object giving it its value and existence.
This version takes scalar coordinates as the argument.
Warning
This implementation is not extensible.

Definition at line 1756 of file m_env.f90.

◆ spatial_fix_position_3d_o()

elemental subroutine the_environment::spatial_fix_position_3d_o ( class(spatial), intent(inout)  this,
type(spatial), intent(in)  location 
)

Place spatial object into a 3D space, define the object's current coordinates.

Parameters
locationSPATIAL location that will be assigned to the current spatial object.
Note
This is actually the constructor for the SPATIAL object giving it its value and existence.
This version takes a SPATIAL object as argument.

Definition at line 1776 of file m_env.f90.

◆ spatial_make_missing()

elemental subroutine the_environment::spatial_make_missing ( class(spatial), intent(inout)  this)

Assign all commondata::missing` coordinates to the_environment::spatial object.

Definition at line 1792 of file m_env.f90.

◆ spatial_get_current_pos_3d_o()

elemental type(spatial) function the_environment::spatial_get_current_pos_3d_o ( class(spatial), intent(in)  this)

Get the current spatial position of a SPATIAL object.

Returns
Current spatial coordinates as a SPATIAL object.
Note
This function returns SPATIAL type object (3D coordinates).
This is a standard extensible version.

Definition at line 1806 of file m_env.f90.

◆ spatial_get_current_pos_3d_v()

pure real(srp) function, dimension(dimensionality_default) the_environment::spatial_get_current_pos_3d_v ( class(spatial), intent(in)  this,
logical, intent(in)  vector 
)

Get the current spatial position of a SPATIAL object.

Parameters
vectorflag indicating if we return a 3D vector rather than SPATIAL type object. Note: We need this logical parameter to avoid ambiguity in calling the generic function: ‘Error: 'spatial_get_current_pos_3d’ and 'spatial_get_current_pos_3d_v' for GENERIC 'now' at (1) are ambiguous`. The parameter itself is not used. So, for vector-output must always be TRUE.
Returns
Current spatial coordinates as a 3-dimensional array.
Note
This function returns array of 3D coordinates.
Warning
This function is non extensible.
Note
The vector form of the location function is particularly convenient for data output into the LOGGER module that does not accept object data, but does accept simple array data, e.g.:
call LOG_DBG ("location=" // &
tostr(proto_parents%individual(ind)%location(.true.)))

Definition at line 1836 of file m_env.f90.

◆ spatial_get_current_pos_x_3d()

elemental real(srp) function the_environment::spatial_get_current_pos_x_3d ( class(spatial), intent(in)  this)

Get the current X position of a SPATIAL object.

Returns
x_pos current X coordinate of the SPATIAL object.
Note
Not sure if really much needed.

Definition at line 1859 of file m_env.f90.

◆ spatial_get_current_pos_y_3d()

elemental real(srp) function the_environment::spatial_get_current_pos_y_3d ( class(spatial), intent(in)  this)

Get the current Y position of a SPATIAL object.

Returns
x_pos current X coordinate of the SPATIAL object.
Note
Not sure if really much needed.

Definition at line 1872 of file m_env.f90.

◆ spatial_get_current_pos_d_3d()

elemental real(srp) function the_environment::spatial_get_current_pos_d_3d ( class(spatial), intent(in)  this)

Get the current DEPTH position of a SPATIAL object.

Returns
x_pos current X coordinate of the SPATIAL object.
Note
Not sure if really much needed.

Definition at line 1885 of file m_env.f90.

◆ spatial_calc_irradiance_at_depth()

real(srp) function the_environment::spatial_calc_irradiance_at_depth ( class(spatial), intent(in)  this,
integer, intent(in), optional  time_step_model 
)

Calculate the illumination (background irradiance) at the depth of the spatial object at an arbitrary time step of the model.

Warning
Cannot implement a generic function accepting also vectors of this objects as only elemental object-bound array functions are allowed by the standard. This function cannot be elemental, so passed-object dummy argument must always be scalar.

Implementation details

Check optional time step parameter. If unset, use global commondata::global_time_step_model_current.

Calculate ambient illumination / irradiance at the depth of this food item at the given time step.

Definition at line 1901 of file m_env.f90.

◆ spatial_visibility_visual_range_cm()

real(srp) function the_environment::spatial_visibility_visual_range_cm ( class(spatial), intent(in)  this,
real(srp), intent(in), optional  object_area,
real(srp), intent(in), optional  contrast,
integer, intent(in), optional  time_step_model 
)

Calculate the visibility range of a spatial object. Wrapper to the the_environment::visual_range() function. This function calculates the distance from which this object can be seen by a visual object (e.g. predator or prey).

Warning
Cannot implement a generic function accepting also vectors of this objects as only elemental object-bound array functions are allowed by the standard. This function cannot be elemental, so passed-object dummy argument must always be scalar.
Parameters
[in]object_areaobject_area is the mandatory area of the spatial object (m).
Note
object_area has optional attribute here with the base the_environemnt::spatial class object can be only optional because it is optional in all extension classes (the_environment::food_item, the_environment::predator, the_body::condition,the_neurobio::spatialobj_percept_comp). However, it is actually mandatory here and not providing object size results in wrong calculations. Such a case is logged with the commondata::ltag_error logger tag.
Parameters
[in]contrastcontrast is optional inherent contrast of this spatial object. the default contrast of all objects is defined by the commondata::preycontrast_default parameter.
[in]time_step_modeloptional time step of the model, if absent gets the current time step as defined by the value of commondata::global_time_step_model_current.
Returns
The maximum distance (m) from which this object can be seen.

PROCNAME is the procedure name for logging and debugging

Implementation details

Check if optional object area parameter is present. For a base the_environment::spatial object, providing explicit value is mandatory. If object area is absent, commondata::missing value is used as a default, which results in wrong calculations.

  • Such a case is logged with the commondata::ltag_error logger tag. (check logger errors with grep ERROR: *log).

Check optional contrast parameter. If unset, use global commondata::preycontrast_default.

Check optional time step parameter. If unset, use global commondata::global_time_step_model_current.

Calculate ambient illumination / irradiance at the depth of this object at the given time step.

Return visual range to see this spatial object: its visibility range.

Definition at line 1938 of file m_env.f90.

◆ spatial_get_environment_in_pos()

pure integer function the_environment::spatial_get_environment_in_pos ( class(spatial), intent(in)  this,
class(environment), dimension(:), intent(in), optional  environments_array 
)

Identify in which environment from the input list this spatial agent is currently in. Example call:

ienv = object%find_environment( [habitat_safe, habitat_dangerous] )
Note
Because the habitat object is an extension of the environment, this method also works with the habitats.

Determining the environment object the agent is currently in can be done by the_environment::spatial::find_environment() method in this way:

   ...
   environment_limits = Global_Habitats_Available(                        &
                  this_agent%find_environment(Global_Habitats_Available) )
   ...

This uses the the_environment::global_habitats_available global array containing all available environments, initialised in the_evolution::init_environment_objects().

Parameters
[in]environments_arrayenvironments_array An array of environment objects, where the this object can be. If this parameter is omitted, the environment objects are obtained from the default global array the_environment::global_habitats_available.
Warning
The environment objects within the array must be non-overlapping, otherwise, the results are undefined due to parallel algorithm.
Returns
Returns the number of the environment from the input array, where this spatial object is currently in.

Implementation details

First, determine the size of the input array of the environments among which the check is done.

Also, initialise the return value to zero.

Then cycle over all the input environments whether the this spatial object is within it.

The .within. operator is used for checking (defined by the_environment::environment_check_located_within_3d()). Then, return the number of the environment within the input array and exit.

If the environments_array array is not provided, default habitats are obtained from the the_environment::global_habitats_available global array .

Definition at line 2039 of file m_env.f90.

◆ spatial_moving_fix_position_3d_v()

subroutine the_environment::spatial_moving_fix_position_3d_v ( class(spatial_moving), intent(inout)  this,
real(srp), intent(in)  x,
real(srp), intent(in)  y,
real(srp), intent(in)  depth 
)

Place spatial movable object into a 3D space, define the object's current coordinates, but first save previous coordinates.

Parameters
xThe spatial objects will now get these coordinates.
yThe spatial objects will now get these coordinates.
depthThe spatial objects will now get these coordinates.

Implementation details

Save previous coordinates into the history stacks.

Finally, position the object now with the coordinates provided.

Definition at line 2121 of file m_env.f90.

◆ spatial_moving_fix_position_3d_o()

elemental subroutine the_environment::spatial_moving_fix_position_3d_o ( class(spatial_moving), intent(inout)  this,
type(spatial), intent(in)  location 
)

Place spatial movable object into a 3D space, define the object's current coordinates, but first save previous coordinates.

Parameters
locationThe spatial objects will now get these coordinates.

Implementation details

Save previous coordinates into the history stacks.

Finally, position the object now with the coordinates provided.

Definition at line 2144 of file m_env.f90.

◆ spatial_moving_repeat_position_history_3d()

elemental subroutine the_environment::spatial_moving_repeat_position_history_3d ( class(spatial_moving), intent(inout)  this)

Repeat (re-save) the current position into the positional history stack.

Note
Re-saving the current position is necessary to keep the full positional history even for the the_behavior::behaviour's that do not involve spatial displacement (movement).

Definition at line 2168 of file m_env.f90.

◆ spatial_distance_3d()

elemental real(srp) function the_environment::spatial_distance_3d ( class(spatial), intent(in)  this,
class(spatial), intent(in)  other 
)

Calculate the Euclidean distance between two spatial objects. This is a type-bound function.

Returns
distance Euclidean distance between two spatial objects.
Parameters
otheranother spatial object that we measure distance between.
Note
Note that this version uses the vector-based backend for calculation. The vector-based backend is equivalent to the scalar-based, but might be more general as it easily works with other dimensionality (e.g. 2D or 4D). The negative side is that the vector-based backend cannot be used to make an elemental function. Example: x_dist = objectdistance(other_object)

Implementation details

Calculate the distance between these two spatial objects.

Note
Note that this version uses the vector-based backend for calculation. The vector-based backend is equivalent to the scalar-based, but might be more general as it easily works with other dimensionality (e.g. 2D or 4D). The negative side is that the vector-based backend cannot be used to make an elemental function.

Definition at line 2190 of file m_env.f90.

◆ spatial_stack2arrays()

pure type(spatial) function, dimension(:), allocatable the_environment::spatial_stack2arrays ( type(spatial), dimension(:), intent(in)  a,
type(spatial), dimension(:), intent(in)  b 
)

Concatenate two arrays of the_environment::spatial objects a and b. This procedure uses array slices which would be faster in most cases than the intrinsic [a,b] method.

Note
There is a user defined operator .cat. making use of this procedure that can be used like this:
object1%location() .cat. object2%location()
Warning
This is the the_environment::spatial type version. All input and output parameters are defined as type, so this is not class-safe.
Parameters
[in]aa first array
[in]bb second array
Returns
an array [a, b]

Definition at line 2223 of file m_env.f90.

◆ spatial_moving_stack2arrays()

pure type(spatial_moving) function, dimension(:), allocatable the_environment::spatial_moving_stack2arrays ( type(spatial_moving), dimension(:), intent(in)  a,
type(spatial_moving), dimension(:), intent(in)  b 
)

Concatenate two arrays of the_environment::spatial_moving objects a and b. This procedure uses array slices which would be faster in most cases than the intrinsic [a,b] method.

Note
There is a user defined operator .cat. making use of this procedure that can be used like this:
object1%location() .cat. object2%location()
Warning
This is the the_environment::spatial_moving type version. All input and output parameters are defined as type, so this is not class-safe.
Parameters
[in]aa first array
[in]bb second array
Returns
an array [a, b]

Definition at line 2250 of file m_env.f90.

◆ spatial_class_stack2arrays_locs()

pure type(spatial) function, dimension(:), allocatable the_environment::spatial_class_stack2arrays_locs ( class(spatial), dimension(:), intent(in)  a,
class(spatial), dimension(:), intent(in)  b 
)

Concatenate the location components of two arrays of the_environment::spatial class objects a and b. This procedure uses array slices which would be faster in most cases than the intrinsic [a,b] method.

Note
There is a user defined operator .cat. making use of this procedure that can be used like this:
all_objects%position%( object1 .catloc. object2 )
Warning
Unlike the the_environment::spatial_stack2arrays() and the_environment::spatial_moving_stack2arrays() methods, this procedure is class-safe and can be used with any class upwards, but it concatenates only the location data (returns type the_environment::spatial).
Parameters
[in]aa first array
[in]bb second array
Returns
an array [a, b]

Definition at line 2280 of file m_env.f90.

◆ dist3d()

elemental real(srp) function the_environment::dist3d ( class(spatial), intent(in)  this,
class(spatial), intent(in)  other 
)

This is a non-type-bound version of the distance calculation function.

Note
Note that this is an elemental function that can also accept arrays (but these must be conforming). Example:
x_dist = dist3d(object, other_object) # scalar variant
d=dist3d( habitat_safe%food%food(1:3), &
habitat_safe%food%food(4:6) ) # vector variant
Returns
distance Euclidean distance between two spatial objects.
Parameters
[in]otherother another spatial object that we measure distance between.

Implementation details

Calculate the distance between these two spatial objects.

Note
Note that this version uses the scalar-based backend for calculation. The scalar-based backend is equivalent to the vector-based one, but is linked with the 3D space only (has to be re-implemented in case of 2D or 4D space). But its positive side is that it is an elemental function that can be used to make further elemental functions.

Definition at line 2306 of file m_env.f90.

◆ spatial_self_distance_3d()

elemental real(srp) function the_environment::spatial_self_distance_3d ( class(spatial), intent(in)  this,
integer, intent(in), optional  from_history 
)

Calculate the Euclidean distance between the current and previous position of a single spatial object.

Parameters
from_historyWe have to calculate total distance from this point in the spatial stack history (< HISTORY_SIZE_SPATIAL). Not used here, always 0.0.
Returns
distance Euclidean distance between two spatial objects.

Implementation details

The distance between two positions of an immobile object is zero in all cases. It is a fixed value in this procedure.

Definition at line 2334 of file m_env.f90.

◆ spatial_moving_self_distance_3d()

elemental real(srp) function the_environment::spatial_moving_self_distance_3d ( class(spatial_moving), intent(in)  this,
integer, intent(in), optional  from_history 
)

Calculate the Euclidean distance between the current and previous position of a single spatial movable object. Optionally, it also calculates the total distance traversed during the from_history points from the history stack along with the distance from the current position and the last historical value. For example, to calculate the average distance throughout the whole history (HISTORY_SIZE_SPATIAL points) do this:

object_name%way(history_size_spatial - 1) / history_size_spatial

This is because for N points in history we can calculate N-1 distances, but the sample size is N, that is N-1 plus an additional distance between the latest historical point and the current position.

Parameters
from_historyWe have to calculate total distance from this point in the spatial stack history (< HISTORY_SIZE_SPATIAL)
Returns
distance Euclidean distance between two spatial objects.

Implementation details

We get the history size from the history stack size (history), alternatively, can get from the HISTORY_SIZE_SPATIAL parameter directly.

Check if we are asked to calculate distance traversed using the history stack. If the number provided exceed the limit, set maximum. If no history requested (parameter not present or 0) calculate the distance between the current point and the latest historical point.

Note
If we have history stack of size N, we can calculate maximum N-1 historical distances between N successive points.

Calculate the distance between the current position and the last historical stack record.

Now cycle backwards through the from_history steps of the history stack and calculate the sum = total distance traversed.

Definition at line 2367 of file m_env.f90.

◆ spatial_moving_create_3d()

elemental subroutine the_environment::spatial_moving_create_3d ( class(spatial_moving), intent(inout)  this)

Create a new spatial moving object. Initially it has no position, all coordinate values are MISSING or INVALID for real type coordinates.

Note
This is the constructor for SPATIAL_MOVING object type that makes it into existence and gives it its value.

Implementation details

Assign MISSING values to the new object, use interface function and type constructor.

This also cleanups the history stack, i.e. fills it with MISSING values.

Definition at line 2435 of file m_env.f90.

◆ spatial_moving_clean_hstory_3d()

elemental subroutine the_environment::spatial_moving_clean_hstory_3d ( class(spatial_moving), intent(inout)  this)

Create a new empty history of positions for spatial moving object. Assign all values to the MISSING value code.

Implementation details

Set all historical stack arrays to MISSING.

Definition at line 2453 of file m_env.f90.

◆ spatial_moving_go_up()

elemental subroutine the_environment::spatial_moving_go_up ( class(spatial_moving), intent(inout)  this,
real(srp), intent(in), optional  step 
)

The spatial moving object ascends, goes up the depth with specific fixed step size.

Parameters
[in]stepstep is the step size for the upwards walk. If it is too large (the object would extend beyond its current environment), it is adjusted autiomatically.

Implementation details

Calculate the minimum depth in the environment currently occupied by the spatial object.

Check if the target depth is likely to go beyond the environment depth limits and reduce the upwnward walk step size accordingly. Namely, if the depth coordinate of the object minus the depth step exceeds the minimum depth, the step is reduced to be within the available environment: $ d_{o} - D_{min} - \varepsilon $, where $ D_{min} $ is the maximum depth, $ d_{o} $ is the current depth of the object and $ \varepsilon $ is a very small constant defined by the parameter commondata::zero to guarantee the object remains within the current environment.

Relocate the object so that its X and Y coordinates remain intact but the depth reduces by the step size.

Definition at line 2467 of file m_env.f90.

◆ spatial_moving_go_down()

elemental subroutine the_environment::spatial_moving_go_down ( class(spatial_moving), intent(inout)  this,
real(srp), intent(in), optional  step 
)

The spatial moving object decends, goes down the depth with specific fixed step size.

Parameters
[in]stepstep is the step size for the upwards walk. If it is too large (the object would extend beyond its current environment), it is adjusted autiomatically.

Implementation details

Calculate the maximum depth in the environment currently occupied by the spatial object.

Check if the target depth is likely to go beyond the environment depth limits and reduce the downward walk step size accordingly. Namely, if the depth coordinate of the object plus the depth step exceeds the maximum depth, the step is reduced to be within the available environment: $ D_{max} - d_{o} - \varepsilon $, where $ D_{max} $ is the maximum depth, $ d_{o} $ is the current depth of the object and $ \varepsilon $ is a very small constant defined by the parameter commondata::zero to guarantee the object remains within the current environment.

Relocate the object so that its X and Y coordinates remain intact but the depth reduces by the step size.

Definition at line 2530 of file m_env.f90.

◆ spatial_moving_randomwalk_gaussian_step_3d()

subroutine the_environment::spatial_moving_randomwalk_gaussian_step_3d ( class(spatial_moving), intent(inout)  this,
real(srp), intent(in)  meanshift,
real(srp), intent(in)  cv_shift,
class(environment), intent(in), optional  environment_limits 
)

Implements an optionally environment-restricted Gaussian random walk in 3D.

Parameters
meanshiftthe mean shift along any of the three dimensions.
cv_shiftthe coefficient of variation for a single elementary shift in any of the three dimensions.
environment_limitsLimits of the environment area available for the random walk. The moving object cannot get beyond this limit.

The moving object walks in three dimensions. The process is simple, first shift along the x axis for some random Gaussian length (with the mean meanshift and the variance/CV cv_shift) then walk another Gaussian length the y axis. The, walk in the same manner along the z axis. The optional restriction is that the whole walk must not exceed specific spatial location set by the environment parameter.

Implementation details

First, we get the current coordinates of the spatial object.

And set a temporary spatial test object with the new coordinates, advancing/adding our random walk step. This is done via the .radd. operator and calling RNORM (see HEDTOOLS).

Environment restriction part of the random walk, if environment_limits parameter object is provided. Here the object is not allowed to go beyond its bounding environment: get new position while outside of the target environment.

  • Loop while this new test spatial object is outside of our target environment. It must be strictly within.

Finally, change the current position of the this object to the position defined by the test_object. The standard function position for the SPATIAL_MOVINGis used, that keeps the movement history.

Definition at line 2604 of file m_env.f90.

Here is the call graph for this function:

◆ spatial_moving_randomwalk_gaussian_step_25d()

subroutine the_environment::spatial_moving_randomwalk_gaussian_step_25d ( class(spatial_moving), intent(inout)  this,
real(srp), intent(in)  meanshift_xy,
real(srp), intent(in)  cv_shift_xy,
real(srp), intent(in)  meanshift_depth,
real(srp), intent(in)  cv_shift_depth,
class(environment), intent(in), optional  environment_limits 
)

Implements an optionally environment-restricted Gaussian random walk in a "2.5 dimensions", i.e. 2D x y with separate walk parameters for the third depth dimension.

Parameters
meanshiftthe mean shift along any of the three dimensions.
cv_shiftthe coefficient of variation for a single elementary shift in any of the three dimensions.
environment_limitsLimits of the environment area available for the random walk. The moving object cannot get beyond this limit.

The moving object walks in three dimensions. The process is simple, first shift along the x axis for some random Gaussian length (with the mean meanshift and the variance/CV cv_shift) then walk another Gaussian length the y axis. The, walk in the same manner along the z axis. But here z axis has separate walk parameters (meanshift and cv_shift) that are much smaller than the x and y parameters. The optional restriction is that the whole walk must not exceed specific spatial location set by the environment parameter.

Note
The mean and CV is different for the 2D x y movement and the third dimension depth movement.

Implementation details

First, we get the current coordinates of the spatial object.

And set a temporary spatial test object with the new coordinates, advancing/adding our random walk step. This is done via the .radd. operator and calling the RNORM function (see HEDTOOLS).

Environment restriction part of the random walk, if environment_limits parameter object is provided. Here the object is not allowed to go beyond its bounding environment: get new position while outside of the target environment.

  • Loop while this new test spatial object is outside of our target environment. It must be strictly within.

Finally, change the current position of the this object to the position defined by the test_object. The standard function position for the SPATIAL_MOVINGis used, that keeps the movement history.

Definition at line 2686 of file m_env.f90.

Here is the call graph for this function:

◆ spatial_moving_corwalk_gaussian_step_3d()

subroutine the_environment::spatial_moving_corwalk_gaussian_step_3d ( class(spatial_moving), intent(inout)  this,
class(spatial), intent(in)  target,
real(srp), intent(in)  meanshift,
real(srp), intent(in)  cv_shift,
logical, intent(in), optional  is_away,
real(srp), intent(in), optional  ci_lim,
class(environment), intent(in), optional  environment_limits,
logical, intent(out), optional  is_converged,
integer, intent(out), optional  debug_reps 
)

Implements an optionally environment-restricted correlated directional Gaussian random walk in 3D towards (or away of) an the_environment::spatial class target object.

The moving object walks in three dimensions towards (or away of) a the_environment::spatial class target. Here is an example of walks:

Correlated Gaussian random walk in 3D
Parameters
[in]targettarget The target of the random walk.
[in]meanshiftmeanshift the mean shift along any of the three dimensions.
[in]cv_shiftcv_shift the coefficient of variation for a single elementary shift in any of the three dimensions.
[in]is_awayis_away optional logical flag, if set to TRUE, the walk is actually directed out of the target, so that the object is going to maximise rather than minimise the distance to the target.
[in]ci_limci_lim This parameter sets the convergence criterion; it is the confidence interval limit for the distance between the object and the target. The walk is considered "converged" if the distance between the object and the target is smaller than ci_lim std. deviations of the average step distance (set by meanshift). The default value is the 95% confidence interval (1.95996).
[in]environment_limitsenvironment_limits optional limits of the environment area available for the random walk. The moving object cannot get beyond this limit.
[out]is_convergedis_converged optional logical flag for the "converged" state, i.e. the distance between the object and the target is smaller than ci_lim standard deviations of the average step distance.
[out]debug_repsdebug_reps optional internal counter for repeated samplings of random positions for prospective spatial advancement of the object. If the counter reaches a too high value, a "no convergence" state is reached. In case of the avoiding environmentally limited walk, when the object maximises its distance from the target, such a condition may indicate that there is no further space to avoid the target in the available environment.

Implementation details

First, check if the convergence criterion is reached. The walk is considered "converged" if the distance between the object and the target is smaller than ci_lim std. deviations of the average step distance (which is set by meanshift).

If the convergence condition is met, the object does not change its position any more, no further walks are performed.

If the convergence condition is not yet met, the current coordinates of the spatial object are recorded.

Then a temporary spatial test object (test_object) is set the new coordinates for the spatial moving object, advancing to a random walk step. This is done by randomly adding or subtracting a Gaussian step size with the mean meanshift and variance defined by cv_shift along all three spatial coordinates.

A series of conditions is then checked, the main is that the new position defined by the temporary spatial object should be such that the distance from the target must be smaller (if the object is intended to moved towards the target) or larger (if the object is intended to move away of the target).

Environment restriction is also applied if environment_limits parameter is provided: the object is not allowed to go beyond its bounding environment in such a case.

There is also a safeguard against poor convergence: If the number of iterations exceeds a fixed value (CONVERG local parameter), force to exit from the condition loops without changing the object position (i.e. no walk is done).

Finally, change the current position of the this object to the position defined by the test_object. Such a change is done only if the non-convergence condition is not detected.

At the end, check and return the optional intent[out] parameters is_converged and debug_reps.

Definition at line 2765 of file m_env.f90.

Here is the call graph for this function:

◆ spatial_moving_corwalk_gaussian_step_25d()

subroutine the_environment::spatial_moving_corwalk_gaussian_step_25d ( class(spatial_moving), intent(inout)  this,
class(spatial), intent(in)  target,
real(srp), intent(in)  meanshift_xy,
real(srp), intent(in)  cv_shift_xy,
real(srp), intent(in)  meanshift_depth,
real(srp), intent(in)  cv_shift_depth,
logical, intent(in), optional  is_away,
real(srp), intent(in), optional  ci_lim,
class(environment), intent(in), optional  environment_limits,
logical, intent(out), optional  is_converged,
integer, intent(out), optional  debug_reps 
)

Implements an optionally environment-restricted correlated directional Gaussian random walk in 3D towards (or away of) an the_environment::spatial class target object.

The moving object walks in three dimensions towards (or away of) a the_environment::spatial class target.

Correlated Gaussian random walk in 3D
Parameters
[in]targettarget The target of the random walk.
[in]meanshift_xymeanshift_xy the mean shift along any of the three dimensions.
[in]cv_shift_xycv_shift_xy the coefficient of variation for a single elementary shift in any of the three dimensions.
[in]meanshift_depthmeanshift_depth the mean shift along any of the three dimensions.
[in]cv_shift_depthcv_shift_depth the coefficient of variation for a single elementary shift in any of the three dimensions.
[in]is_awayis_away optional logical flag, if set to TRUE, the walk is actually directed out of the target, so that the object is going to maximise rather than minimise the distance to the target.
[in]ci_limci_lim This parameter sets the convergence criterion; it is the confidence interval limit for the distance between the object and the target. The walk is considered "converged" if the distance between the object and the target is smaller than ci_lim std. deviations of the average step distance (set by meanshift). The default value is the 95% confidence interval (1.95996).
[in]environment_limitsenvironment_limits optional limits of the environment area available for the random walk. The moving object cannot get beyond this limit.
[out]is_convergedis_converged optional logical flag for the "converged" state, i.e. the distance between the object and the target is smaller than ci_lim standard deviations of the average step distance.
[out]debug_repsdebug_reps optional internal counter for repeated samplings of random positions for prospective spatial advancement of the object. If the counter reaches a too high value, a "no convergence" state is reached. In case of the avoiding environmentally limited walk, when the object maximises its distance from the target, such a condition may indicate that there is no further space to avoid the target in the available environment.

Implementation details

First, check if the convergence criterion is reached. The walk is considered "converged" if the distance between the object and the target is smaller than ci_lim std. deviations of the average step distance (which is set by meanshift).

If the convergence condition is met, the object does not change its position any more, no further walks are performed.

If the convergence condition is not yet met, the current coordinates of the spatial object are recorded.

Then a temporary spatial test object (test_object) is set the new coordinates for the spatial moving object, advancing to a random walk step. This is done by randomly adding or subtracting a Gaussian step size with the mean meanshift and variance defined by cv_shift along all three spatial coordinates.

A series of conditions is then checked, the main is that the new position defined by the temporary spatial object should be such that the distance from the target must be smaller (if the object is intended to moved towards the target) or larger (if the object is intended to move away of the target).

Environment restriction is also applied if environment_limits parameter is provided: the object is not allowed to go beyond its bounding environment in such a case.

There is also a safeguard against poor convergence: If the number of iterations exceeds a fixed value (CONVERG local parameter), force to exit from the condition loops without changing the object position (i.e. no walk is done).

Finally, change the current position of the this object to the position defined by the test_object. Such a change is done only if the non-convergence condition is not detected.

At the end, check and return the optional intent[out] parameters is_converged and debug_reps.

Definition at line 3007 of file m_env.f90.

Here is the call graph for this function:

◆ spatial_moving_dirwalk_gaussian_step_3d()

subroutine the_environment::spatial_moving_dirwalk_gaussian_step_3d ( class(spatial_moving), intent(inout)  this,
class(spatial), intent(in)  target,
real(srp), intent(in)  meanshift,
real(srp), intent(in)  cv_shift,
class(environment), intent(in), optional  environment_limits 
)

Implements an optionally environment-restricted directional Gaussian random walk in 3D towards a target the_environment::spatial class object.

The moving object walks in three dimensions towards a target. The process is simple, first shift along the x axis for some random Gaussian length (with the mean meanshift and the variance/CV cv_shift) in the direction that minimises the coordinate-bound distance from the target. If the target is located at a distance not exceeding the meanshift we have got towards the target. Then the process is repeated for the y and z axes. The optional restriction is that the whole walk must not exceed specific spatial location set by the environment parameter.

Note
This dirwalk is a obsolete suboptimal implementation See the_environment::spatial_moving_corwalk_gaussian_step_3d() and the_environment::spatial_moving_corwalk_gaussian_step_25d() for a better alternative.
Parameters
[in]targetThe target of the random walk, the walk should converge to the target within finite number of steps.
[in]meanshiftthe mean shift along any of the three dimensions.
[in]cv_shiftthe coefficient of variation for a single elementary shift in any of the three dimensions.
[in]environment_limitsLimits of the environment area available for the random walk. The moving object cannot get beyond this limit.

Implementation details

First, we get the current coordinates of the spatial object.

And set a temporary spatial test object with the new coordinates, advancing/adding our random walk step. This is done via the updated_position sub-function.

Environment restriction part of the random walk, if environment_limits parameter object is provided. Here the object is not allowed to go beyond its bounding environment.

Loop while this new test spatial object is outside our target environment. It must be strictly within.

(if the test_object is outside the environment, we create new randomly updated coordinates.)

Finally, change the current position of the this object to the position defined by the test_object. The standard function position for the SPATIAL_MOVINGis used, that keeps the movement history.

Definition at line 3288 of file m_env.f90.

Here is the call graph for this function:

◆ spatial_moving_dirwalk_gaussian_step_25d()

subroutine the_environment::spatial_moving_dirwalk_gaussian_step_25d ( class(spatial_moving), intent(inout)  this,
class(spatial), intent(in)  target,
real(srp), intent(in)  meanshift_xy,
real(srp), intent(in)  cv_shift_xy,
real(srp), intent(in)  meanshift_depth,
real(srp), intent(in)  cv_shift_depth,
class(environment), intent(in), optional  environment_limits 
)

Implements an optionally environment-restricted directional Gaussian random walk in "2.5"-D towards a target the_environment::spatial class object. i.e. 2D x y with separate walk parameters for the third depth dimension.

The moving object walks in three dimensions towards a target. The process is simple, first shift along the x axis for some random Gaussian length (with the mean meanshift and the variance/CV cv_shift) in the direction that minimises the coordinate-bound distance from the target. If the target is located at a distance not exceeding the meanshift we have got towards the target. Then the process is repeated for the y and z axes. The optional restriction is that the whole walk must not exceed specific spatial location set by the environment parameter.

Note
This dirwalk is a obsolete suboptimal implementation See the_environment::spatial_moving_corwalk_gaussian_step_3d() and the_environment::spatial_moving_corwalk_gaussian_step_25d() for a better alternative.
Parameters
[in]targetThe target of the random walk, the walk should converge to the target within finite number of steps.
[in]meanshift_xythe mean shift along the X and Y dimensions.
[in]cv_shift_xythe coefficient of variation for a single elementary shift the X and Ydimensions.
[in]meanshift_depththe mean shift along the depth dimension.
[in]cv_shift_depththe coefficient of variation for a single elementary shift in the depth dimension.
[in]environment_limitsLimits of the environment area available for the random walk. The moving object cannot get beyond this limit.

Implementation details

First, we get the current coordinates of the spatial object.

And set a temporary spatial test object with the new coordinates, advancing/adding our random walk step. This is done via the updated_position sub-function.

Environment restriction part of the random walk, if environment_limits parameter object is provided. Here the object is not allowed to go beyond its bounding environment.

Loop while this new test spatial object is outside our target environment. It must be strictly within.

(if the test_object is outside the environment, we create new randomly updated coordinates.)

Finally, change the current position of the this object to the position defined by the test_object. The standard function position for the SPATIAL_MOVINGis used, that keeps the movement history.

Definition at line 3410 of file m_env.f90.

Here is the call graph for this function:

◆ rwalk3d_array()

subroutine the_environment::rwalk3d_array ( class(spatial_moving), dimension(:), intent(inout)  this,
real(srp), dimension(:), intent(in), optional  dist_array,
real(srp), dimension(:), intent(in), optional  cv_array,
real(srp), intent(in), optional  dist_all,
real(srp), intent(in), optional  cv_all,
class(environment), intent(in), optional  environment_limits,
integer, intent(in), optional  n_walks 
)

Perform one or several steps of random walk by an array of the_environment::spatial_moving class objects. This is a 3D version with the same walk parameters for the horizontal XxY plane and depth.

Parameters
[in,out]this[in] this is an array of the_environment::spatial class objects.
[in]dist_arraystep_size_array an array of step sizes for each object.
[in]cv_arraycv_array Coefficients of variation for the walk.
[in]dist_alldist_all the value of the walk step size that is identical in all objects in the array.
[in]cv_allcv_all the value of the walk coefficient of variation that is identical in all objects in the array.
[in]environment_limitsenvironment_limits Limits of the environment area available for the random walk. The moving object cannot get beyond this limit. If this parameter is not provided, the environmental limits are obtained automatically from the global array the_environment::global_habitats_available.
[in]n_walksn_walk optional number of walk steps that should be performed, default just one.

Implementation details

  • Calculate the distance array size.

calculate the step size along the axes from the distance array.

  • Calculate the random permutation of individual indices.
    Warning
    Random order here is a prototype for testing for use in behaviour selection by population members.
  • Perform Gaussian random walks for each of the individuals in a random order that is set by the pop_permutation array.
  • if the input objects array is of the_environment::food_item, also check if it is available (not eaten) using the the_environment::food_item::is_available() method.
  • in the default class case, no such check is made.

Definition at line 3522 of file m_env.f90.

Here is the call graph for this function:

◆ rwalk25d_array()

subroutine the_environment::rwalk25d_array ( class(spatial_moving), dimension(:), intent(inout)  this,
real(srp), dimension(:), intent(in), optional  dist_array_xy,
real(srp), dimension(:), intent(in), optional  cv_array_xy,
real(srp), dimension(:), intent(in), optional  dist_array_depth,
real(srp), dimension(:), intent(in), optional  cv_array_depth,
real(srp), intent(in), optional  dist_all_xy,
real(srp), intent(in), optional  cv_all_xy,
real(srp), intent(in), optional  dist_all_depth,
real(srp), intent(in), optional  cv_all_depth,
class(environment), intent(in), optional  environment_limits,
integer, intent(in), optional  n_walks 
)

Perform one or several steps of random walk by an array of the_environment::spatial_moving class objects. This is a 2.5D version with separate walk parameters for the horizontal XxY plane and depth.

Parameters
[in,out]this[in] this is an array of the_environment::spatial class objects.
[in]dist_array_xydist_array_xy an array of step sizes for each object.
[in]cv_array_xycv_array_xy Coefficients of variation for the walk.
[in]dist_array_depthdist_array_depth an array of step sizes for each object.
[in]cv_array_depthcv_array_depth Coefficients of variation for the walk.
[in]dist_all_xydist_all_xy the value of the walk step size for horizontal plane that is identical in all objects in the array.
[in]cv_all_xycv_all_xy the value of the walk coefficient of variation in the horizontal plane that is identical in all objects within the array.
[in]dist_all_depthdist_all_depth the value of the walk step size for the depth plane that is identical in all objects in the array.
[in]cv_all_depthcv_all_depth the value of the walk coefficient of variation in the depth plane that is identical in all objects in the array.
[in]environment_limitsenvironment_limits Limits of the environment area available for the random walk. The moving object cannot get beyond this limit. If this parameter is not provided, the environmental limits are obtained automatically from the global array the_environment::global_habitats_available.
[in]n_walksn_walk optional number of walk steps that should be performed, default just one.

Implementation details

  • Calculate the distance array size.

If the depth walk step distance is not provided as a parameter, 1/2 of the default step size is used as the default value. Thus, it is assumed that the extent of random movements of the agents in the horizontal plane is greater than vertical movements.

  • Calculate the step size along the axes from the distance array.
  • Calculate the random permutation of individual indices.
    Warning
    Random order here is a prototype for testing for use in behaviour selection by population members.
  • Perform Gaussian random walks for each of the objects in a random order that is set by the pop_permutation array.
  • in the default class case, no such check is made.

Definition at line 3672 of file m_env.f90.

Here is the call graph for this function:

◆ spatial_check_located_within_3d()

elemental logical function the_environment::spatial_check_located_within_3d ( class(spatial), intent(in)  this,
class(environment), intent(in)  environment_limits 
)

Function to check if this spatial object is located within an area set by an environmental object (parameter). This should be similar to an analogous function defined for the environment object.

Parameters
environment_limitsthe_environment::environment object that sets the limits that we check the current spatial object to be within.
Returns
Logical flag TRUE if the the_environment::spatial object is within the environment_limits environment.
Note
Can be used as a user-defined operator:
if ( object .within. environment ) then
We need it to implement environment-restricted Gaussian random walk.

Definition at line 3891 of file m_env.f90.

◆ spatial_check_located_below()

elemental logical function the_environment::spatial_check_located_below ( class(spatial), intent(in)  this,
class(spatial), intent(in)  check_object 
)

Logical function to check if the argument spatial object(s) (check_object) is (are) located below the this reference spatial object. Elemental function that also works with arrays. Use as:

reference_object%is_below(check_object)

See also the user-defined operator .below.. The .below. operator can be used in two ways:

  • as an expression, with both scalar and array values:
    parents%ind(i) .below. parents%ind(i)%perceive_food%foods_seen
  • in if blocks, only scalars:
    if ( parents%ind(i) .below. parents%ind(i)%perceive_food%foods_seen(1) )

Definition at line 3924 of file m_env.f90.

◆ spatial_check_located_above()

elemental logical function the_environment::spatial_check_located_above ( class(spatial), intent(in)  this,
class(spatial), intent(in)  check_object 
)

Logical function to check if the argument spatial object(s) (check_object) is (are) located above the this reference spatial object. Elemental function that also works with arrays. Use as:

reference_object%is_above(check_object)

See also the user-defined operator .above.. The .above. operator can be used in two ways:

  • as an expression, with both scalar and array values:
    parents%ind(i) .above. parents%ind(i)%perceive_food%foods_seen
  • in if blocks, only scalars:
    if ( parents%ind(i) .above. parents%ind(i)%perceive_food%foods_seen(1) )

Definition at line 3956 of file m_env.f90.

◆ spatial_get_nearest_object()

type(spatial) function the_environment::spatial_get_nearest_object ( class(spatial), intent(in)  this,
class(spatial), dimension(:), intent(in)  neighbours,
integer, intent(out), optional  number 
)

Determine the nearest spatial object to this spatial object among an array of other spatial objects.

Note
These two functions closely related, they return the nearest object and its id

However, each of them can also return the other output parameter as an intent(out) optional argument (in the subroutine style). For example the_environment::spatial_get_nearest_object() returns the nearest object but can also provide its id as an intent(out) dummy parameter. This is done for convenience of the function use.

Parameters
neighboursthe array of spatial objects that we search for the nearest one.
numberOptional number of the nearest object within the neighbours array.
Returns
Returns the nearest spatial object among the array.
Note
This function returns the nearest spatial object itself with optionally its number. See also the next function spatial_get_nearest_id.

Implementation details

Calculate an array of distances between this object and the neighbouring objects using the_environment::spatial::distance().

Locate the index of the minimum distance.

And return the the_environment::spatial::location() function result for this neighbour as the resultant object.

Also return the optional nearest neighbour index number if requested.

Definition at line 3992 of file m_env.f90.

◆ spatial_get_nearest_id()

integer function the_environment::spatial_get_nearest_id ( class(spatial), intent(in)  this,
class(spatial), dimension(:), intent(in)  neighbours,
type(spatial), intent(out), optional  object 
)

Determine the nearest spatial object to this spatial object among an array of other spatial objects.

Note
These two functions closely related, they return the nearest object and its id

However, each of them can also return the other output parameter as an intent(out) optional argument (in the subroutine style). For example the_environment::spatial_get_nearest_object() returns the nearest object but can also provide its id as an intent(out) dummy parameter. This is done for convenience of the function use.

Parameters
neighboursthe array of spatial objects that we search for the nearest one.
objectoptional spatial object that is the nearest neighbour to this object.
Returns
The id number of the nearest object within the neighbours array
Note
This function returns the id number of the nearest spatial object and optionally the object itself. See also the previous function spatial_get_nearest_object.

Implementation details

Calculate an array of distances between this object and the neighbouring objects. Note that we cannot use a whole-array single-liner as distance is a type bound function.

Return the index of the nearest neighbour.

Also return the optional nearest neighbour object itself if requested.

Definition at line 4063 of file m_env.f90.

◆ habitat_make_init()

subroutine the_environment::habitat_make_init ( class(habitat), intent(inout)  this,
type(spatial), intent(in)  coord_min,
type(spatial), intent(in)  coord_max,
character (len=*), intent(in), optional  label,
real(srp), intent(in), optional  otherrisks,
real(srp), intent(in), optional  eggmortality,
integer  predators_number,
type(spatial), dimension(:), optional  loc_predators,
integer  food_abundance,
type(spatial), dimension(:), optional  loc_food,
real(srp), dimension(:), optional  sizes_food 
)

Make an instance of the habitat object (an environment superset).

Make / build habitat object and set parameters or defaults.

Warning
This subroutine seems to become quite long and difficult to understand. It also combines several tasks, making habitat limits, then array of predators then food resource. On the other hand, this init procedure is normally called only once. TODO: Consider splitting to a few shorter task-specific pieces.

Implementation details

A. Build the <strong>general properties</strong> of the habitat

Build the physical spatial environment for this habitat, set the habitat coordinate limits.

Set label if provided or default random label otherwise.

B. Build the <strong>population of predators</strong> in the habitat

Set the number of predators.

Allocate the local array of predator locations.

If we are provided with the array of spatial locations of each of the predators, we set the local array loc_pred_here from it.

If the array of locations is not present, construct uniform random distriibution of the predators locations within the present environment (bounded uniformly distributed locations). Now use the type bound function uniform.

Now we can allocate the array of predators in the habitat.

Note
Note that we have to allocate predators here, unlike the food resource part below as predators are just a raw array in this type definition. In contrast, food resource is an object itself with its own make procedure (that does allocation).

Make each of the predators using the call parameters of the object bound init function make (attack_rate, position, label).

Note
Note that the attack rate is assumed to be Gaussian among the predators. Also, we do two separate loops for speed (avoid multiple repeated if's within cycles)

If we happen to get zero variance, do deterministic predators.

Generate Gaussian stochastic predators with the object bound make procedure.

Deallocate the local array of predator locations, we do not need them any more further.

C. Build the <strong>food resource(s)</strong> of the habitat

Set the number of food items in the food resource within the habitat.

Allocate the local array of food item locations.

If the array of locations is not present, construct uniform random distribution of the predators locations within the present environment (bounded uniformly distributed locations). Now use the type bound function uniform.

And also allocate the local array of food sizes

If the food size array sizes_food is provided, use it, if not, make a Gaussian stochastic food with parameters from COMMONDATA.

if we happened to get zero variance, do deterministic food resource.

Otherwise, generate random Gaussian array of food sizes.

Make the food resource now using the standard object-bound make function.

Note
Note that the food resource label is composed of FOOD_ and the remaining part of the habitat label.
Note that we do not allocate the food resource object in this procedure as it is allocated automatically by the food-resource-bound subroutine make.

Deallocate temporary array at the end.

Definition at line 4116 of file m_env.f90.

Here is the call graph for this function:

◆ habitat_name_get()

character(len=label_length) function the_environment::habitat_name_get ( class(habitat), intent(in)  this)

Return the name of the habitat.

Returns
The habitat name (text string label).

Definition at line 4342 of file m_env.f90.

◆ habitat_get_risk_mortality()

real(srp) function the_environment::habitat_get_risk_mortality ( class(habitat), intent(in)  this)

Get the mortality risk associated with this habitat.

Returns
The mortality risk in this population that is not linked with explicit predation.

Definition at line 4353 of file m_env.f90.

◆ habitat_get_risk_mortality_egg()

real(srp) function the_environment::habitat_get_risk_mortality_egg ( class(habitat), intent(in)  this)

Get the egg mortality risk associated with this habitat.

Returns
The mortality risk in this population that is not linked with explicit predation.

Definition at line 4365 of file m_env.f90.

◆ habitat_save_predators_csv()

subroutine the_environment::habitat_save_predators_csv ( class(habitat), intent(inout)  this,
character(len=*), intent(in), optional  csv_file_name,
logical, intent(out), optional  is_success 
)

Save the predators with their characteristics into a CSV file.

Parameters
[in]csv_file_namecsv_file_name optional file name to save the predators. Generated automatically if not provided.

Implementation notes

First, check if the optional CSV file name is provided, if not, generate it automatically.

Second, save the predators data using the CSV_MATRIX_WRITE() from HEDTOOLS.

The CSV output data file can be optionally compressed with the commondata::cmd_zip_output command if commondata::is_zip_outputs is set to TRUE.

Definition at line 4377 of file m_env.f90.

Here is the call graph for this function:

◆ save_dynamics()

subroutine the_environment::save_dynamics ( real(srp), intent(in), optional  maxdepth,
character(len=*), intent(in)  csv_file_name,
logical, intent(out), optional  is_success 
)

Save diagnostics data that shows the dynamics of the light and the average depth of the food items, light at the average depth of the food items etc at each time step of the model.

Code to generate plots from these data with gnuplot. Only 1 to 100s rows are plotted, pattern is sinusoidal.

set datafile separator ","
set xlabel "Time steps of the model"
set ylabel "SURFACE_LIGHT"
plot "init_dynamics.csv" every ::1::100 using 1:2 with lines, \
"init_dynamics.csv" every ::1::100 using 1:3 with lines, \
"init_dynamics.csv" every ::1::100 using 1:4 with lines, \
"init_dynamics.csv" every ::1::100 using 1:5 with lines
Parameters
[in]maxdepthmaxdepth is an optional maximum depth, if absent, is set to the global maximum depth (autodetected) across all habitats.
[in]csv_file_namecsv_file_name is the file name to save the data. The file format is CSV.
[out]is_successis_success Flag showing that data save was successful (if TRUE).

The following data are saved in the CSV file:

  1. TIMESTEP – the time step of the model
  2. SURFACE_LIGHT – light at the surface
  3. LIGHT_DEP_10 – light at 1/10 of the maximum depth
  4. LIGHT_DEP_HLF – light at 1/2 of the maximum depth
  5. LIGHT_DEP_MAX – light at the maximum depth
  6. MEAN_DEPTH – the mean depth of the food items (target depth)
  7. LIGHT_MDEPTH – light at the mean depth of the food items.
  8. FOOD_VIS_SURF – visibility range of a standard food item at the surface (zero depth)
  9. FOOD_VIS_10 – visibility range of a standard food item at 1/10 of maximum depth
  10. FOOD_VIS_HLF – visibility range of a standard food item at a half of the maximum depth.
  11. FOOD_VIS_DPMAX – visibility range of a standard food item at the maximum depth
  12. FOOD_VIS_MDEPT – visibility range of a standard food item at the target mean depth MEAN_DEPTH
  13. DEP_VR_UND_200 – depth at which the visibility of the standard average food item falls below 100 cm
  14. DEP_VR_UND_100 – depth at which the visibility of the standard average food item falls below 100 cm
  15. DEP_VR_UND_020 – depth at which the visibility of the standard average food item falls below 20 cm
  16. DEP_VR_UND_005 – depth at which the visibility of the standard average food item falls below 5 cm

Definition at line 4460 of file m_env.f90.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ environment_centre_coordinates_3d()

type(spatial) function the_environment::environment_centre_coordinates_3d ( class(environment), intent(in)  this,
logical, intent(in), optional  nodepth 
)

Determine the centroid of the environment.

Returns
habitat centre coordinates, spatial object type
Parameters
nodepthLogical flag indicating that depth should not change.

Definition at line 4677 of file m_env.f90.

◆ visual_range_scalar()

real(srp) function, private the_environment::visual_range_scalar ( real(srp), intent(in)  irradiance,
real(srp), intent(in), optional  prey_area,
real(srp), intent(in), optional  prey_contrast 
)
private

Wrapper for calculating visual range of a fish predator using the Dag Aksnes's procedures srgetr(), easyr() and deriv(). See srgetr() for computational details.

Note
Note that this is a scalar version. The measurement unit here is meter, might need conversion if other units are used.
Parameters
[in]irradiancebackground irradiance at specific depth
[in]prey_areaprey area, m^2
[in]prey_contrastoptional prey inherent contrast or default parameter if not present.
Returns
Returns visual range of the fish predator.

Example call:

visual_range( light_depth( 30., light_surface(100,.true.) ) )

Specific implementations

See specific implementations:

Notable parameters

VISUAL_RANGE_MAX_OVERFLOW

VISUAL_RANGE_MAX_OVERFLOW = 1300.0_HRP The maximum ceiling value of visual range (cm) calculable using srgetr() under the commondata::q_prec_128 numerical precision model (referred as commondata::hrp). This value is set to the visual range in the cases of numerical overflow.

Note
The real 128 bit limit (commondata::q_prec_128) is sufficient to calculate visual range up to the fish length of approximately 700 cm (area 153.9 cm^2). At this level, the maximum visual range is 1343.34 cm. This would be sufficient for non-whales.

error_msg

Local error message, character array:

  • 1 = NO_CONVERGENCE
  • 2 = DIVISION_ZERO
  • 3 = NEGATIVE_RANGE

Implementation notes

The computational backend for the visual range computation srgetr(), easyr() and deriv() now uses the commondata::q_prec_128 128 bit numerical precision model. This precision is sufficient to calculate visual range up to the the object radius of approximately 700 cm (area 153.9 cm^2) without x86 FPU overflow errors. At this level, the maximum visual range is 1343.34 cm.

Visual range plots

The visual range plots below are generated by HEDTOOLS/tools/visrange_plot.f90.

Calculation details

First, check if background irradiance is below commondata::zero and just return zero visual range.

Check if prey area dummy parameter is provided, if not, use the default value commondata::preyarea_default.

Check if prey contrast dummy parameter is provided, if not, use the default value commondata::preycontrast_default.

Call the main computational backend the_environment::srgetr() Note that the_environment::srgetr() and the whole computational backend are in commondata::hrp precision to reduce numerical rounding and avoid overflow errors.

The visual range calculation backend srgetr() seems computationally suboptimal and with large object size leads to numerical overflow, so the visual range is -Infinity. This is corrected in two steps. (1) in deriv(), a problematic part of the computation now checks proactively for potential overflow (comparing to log(huge()) for the current FPU precision level), so no NaNs or Infinity are produced and no FPU invalid arithmetic errors occur. This is reported to the logger.

If the visual range value returned by srgetr is negative, we reset it to the maximum overflow ceiling value VISUAL_RANGE_MAX_OVERFLOW. It has previously be set to easyr() approximation, but that was grossly wrong (hugely overestimating). It is safer to just limit visual range for detecting bigger objects to such a fixed value.

Finally, do explicit conversion of the final return value from the high commondata::hrp to the standard precision commondata::srp.

Definition at line 4730 of file m_env.f90.

Here is the caller graph for this function:

◆ visual_range_vector()

real(srp) function, dimension(size(prey_area)), private the_environment::visual_range_vector ( real(srp), intent(in)  irradiance,
real(srp), dimension(:), intent(in)  prey_area,
real(srp), dimension(size(prey_area)), intent(in), optional  prey_contrast_vect,
real(srp), intent(in), optional  prey_contrast 
)
private

Wrapper for calculating visual range of a fish predator using the Dag Aksnes's procedures srgetr(), easyr() and deriv(). See srgetr() for computational details.

Note
This is a vector version, prey_area is mandatory and also defines the vector size for all other vector parameters including the returned function value vector. This is useful for selecting among a swarm of prey with different sizes when vector is processed. The measurement unit here is meter. Might need conversion if other units are used.
Parameters
[in]irradiancebackground irradiance at specific depth
[in]prey_areaprey area, m^2; Mandatory parameter.
[in]prey_contrast_vectoptional prey inherent contrast or default parameter if not present. This parameter sets individual vector prey contrast, so can be used for providing stochastic contrast data for each object.
[in]prey_contrastoptional prey inherent contrast or default parameter if not present. This parameter sets common scalar prey contrast for the whole vector.
Returns
Returns visual range of the fish predator.

Specific implementations

See specific implementations:

Implementation notes

The computational backend for the visual range computation srgetr(), easyr() and deriv() now uses the commondata::q_prec_128 128 bit numerical precision model. This precision is sufficient to calculate visual range up to the the object radius of approximately 700 cm (area 153.9 cm^2) without FPU overflow errors. At this level, the maximum visual range is 1343.34 cm.

Visual range plots

The visual range plots below are generated by HEDTOOLS/tools/visrange_plot.f90.

Check if prey contrast dummy parameter is provided, if not, use the default value commondata::preycontrast_default.

Note that the function can use either a (possibly stochastic) vector or a scalar value (same for all) parameters for prey contrast as optional arguments. Scalar value takes precedence if both are provided.

Calculation of the visual range

The main body of calculation is actually a loop calling the scalar-based function the_environment::visual_range_scalar().

Definition at line 4898 of file m_env.f90.

◆ visual_range_fast()

elemental real(srp) function the_environment::visual_range_fast ( real(srp), intent(in)  irradiance,
real(srp), intent(in), optional  prey_area,
real(srp), intent(in), optional  prey_contrast 
)

Wrapper for calculating visual range of a fish predator using the Dag Aksnes's procedures srgetr(), easyr() and deriv(). This is a new elemental and parallel-ready visual range function wrapper making use the elemental-procedures based computational backend. See notes on visual_range_scalar() and srgetr() for computational details.

Parameters
[in]irradiancebackground irradiance at specific depth
[in]prey_areaprey area, m^2
[in]prey_contrastoptional prey inherent contrast or default parameter if not present.
Returns
Returns visual range of the fish predator
Warning
It is simplified, e.g. no error reporting is done. Nonetheless, debugging the old code has shown that it works okay up to the MAX_LOG non-whale size limit. Use the non-elemental version whenever debugging or logging is required! The parameter prey_contrast to the vector-based function call must be an scalar. Otherwise a segmentation fault runtime error results. Vector-based call is analogous to calling visual_range_vector with prey_contrast_vect parameter.

Specific implementations

See specific implementations:

Implementation details

This version of the visual_range procedure does not call the error correction code and does not report errors into the logger. However, this allows declaring it as elemental.

Note
Note that srgetr() and the whole computational backend are now in commondata::hrp precision to avoid numerical overflow errors.

Finally, do explicit conversion from commondata::hrp to commondata::srp.

Definition at line 5009 of file m_env.f90.

◆ srgetr()

elemental subroutine, private the_environment::srgetr ( real(hrp), intent(out)  r,
real(hrp), intent(in)  c,
real(hrp), intent(in)  C0,
real(hrp), intent(in)  Ap,
real(hrp), intent(in)  Vc,
real(hrp), intent(in)  Ke,
real(hrp), intent(in)  Eb,
integer, intent(out), optional  IER 
)
private

Obtain visual range by solving the non-linear equation by means of Newton-Raphson iteration and derivation in subroutine the_environment::deriv(). Initial value is calculated in the_environment::easyr(). The calculation is based on the model described in Aksnes & Utne (1997) Sarsia 83:137-147.

Note
Programmed and tested 29 January 2001 Dag L Aksnes.
This subroutine is left almost intact with only the most crucial changes. (a) added commondata::hrp precision specifier (128 bit precision model) to real type specifiers and _HRP for literal constants; (b) restored diagnostic IER output from archival Hed11.f90. (c) added explicit intent and declared the procedures as pure that is required for being parallel-friendly.
Parameters
[in]RSTstart value of r calculated by the_environment::easyr();
[in]cbeam attenuation coefficient (m-1);
[in]C0prey inherent contrast;
[in]Apprey area (m^2);
[in]Vcparameter characterising visual capacity (d.l.)
[in]thisparameter is denoted E' in Aksnes & Utne;
[in]Kesaturation parameter (uE m-2 s-1);
[in]Ebbackground irradiance at depth DEPTH;
[out]rthe predator's visual range (when F1=0);
[out]IER1 = No convergence after IEND steps, error return; 2 = Return in case of zero divisor; 3 = r out of allowed range (negative); 0 = valid r returned.

Notable variables:

  • F1 function value of equation in deriv;
  • FDER the derivative of the function.

Definition at line 5148 of file m_env.f90.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ easyr()

elemental subroutine, private the_environment::easyr ( real(hrp), intent(out)  r,
real(hrp), intent(in)  C0,
real(hrp), intent(in)  Ap,
real(hrp), intent(in)  Vc,
real(hrp), intent(in)  Ke,
real(hrp), intent(in)  Eb 
)
private

Obtain a first estimate of visual range by using a simplified expression of visual range. See srgetr() for more details.

Note
This subroutine is left almost intact, only (a) added commondata::hrp for real type (HRP is high real precision (128 bit) and is defined in commondata).

Definition at line 5237 of file m_env.f90.

Here is the caller graph for this function:

◆ deriv()

elemental subroutine, private the_environment::deriv ( real(hrp), intent(inout)  r,
real(hrp), intent(out)  F1,
real(hrp), intent(out)  FDER,
real(hrp), intent(in)  c,
real(hrp), intent(in)  C0,
real(hrp), intent(in)  Ap,
real(hrp), intent(in)  Vc,
real(hrp), intent(in)  Ke,
real(hrp), intent(in)  Eb 
)
private

Derivation of equation for visual range of a predator. See the_environment::srgetr() for more details.

Note
This is a high precision version. But higher precision alone is not sufficient to prevent numerical exponentiation overflow.
This subroutine is left almost intact, only (a) added commondata::hrp for literal constants and real type (HRP is the high real precision (128 bit) and is defined in commondata), (b) added numerical overflow safeguard code based on MAX_LOG exponentiability limit; added logging of overflow using LOG_MSG.
Parameters
[out]F1function value of equation in the_environment::deriv();
[out]FDERthe derivative of the function;
[in,out]rthe predator's visual range (when F1=0).

Input parameters:

See explanation in calling routine the_environment::srgetr().

The function and the derivative is calculated on the basis of the log-transformed expression.

Implementation notes

MAX_LOG is a parameter determining the safe limit of exp function overflow in the current float point precision model, well below this. We cannot calculate precise exponent of a value exceeding this parameter. The maximum possible exponentiation-able value is set to the maximum 128-bit real value kind Q_PREC_128, this bottom line value would set a safe limit for HRP calculations. A benefit of this approach is that it doesn't require IEEE exception handling that depends on not fully portable IEEE modules.

Note
The real 128 bit limit (Q_PREC_128) is sufficient to calculate visual range up to the fish length of approximately 700 cm (area 153.9 cm2). At this level, the maximum visual range is 1343.34 cm. This would be sufficient for non-whales.

Definition at line 5270 of file m_env.f90.

Here is the caller graph for this function:

◆ light_surface_deterministic()

elemental real(srp) function, private the_environment::light_surface_deterministic ( integer, intent(in), optional  tstep)
private

Calculate deterministic surface light at specific time step of the model. Light (surlig) is calculated from a sine function. Light intensity just beneath the surface is modelled by assuming a 50 % loss by scattering at the surface:

\[ L_{t} = L_{max} 0.5 sin(\pi dt / \Omega ) \]

.

Returns
surface light intensity.
Parameters
tsteptime step of the model, limited by maximum commondata::lifespan.
Note
This is a deterministic version. Code for wxMaxima for quickcalc:
surlig(a, span) := 500*0.5*(1.01+sin(3.14*2.*50*a/(1.*span)));
surlig(a, span) := 500*0.5*(1.01+sin(3.14*2.*50*a/span));
wxplot2d(surlig(a, 14000), [a,0, 1400]);
Note that this is an elemental function that accepts both scalar and array parameter.

Definition at line 5359 of file m_env.f90.

Here is the caller graph for this function:

◆ light_surface_stochastic_scalar()

real(srp) function, private the_environment::light_surface_stochastic_scalar ( integer, intent(in), optional  tstep,
logical, intent(in)  is_stochastic 
)
private

Calculate stochastic surface light at specific time step of the model. Light (surlig) is calculated from a sine function. Light intensity just beneath the surface is modelled by assuming a 50 % loss by scattering at the surface:

\[ L_{t} = L_{max} 0.5 sin(\pi dt / \Omega ) \]

. This deterministic value sets the mean for the stochastic final value, which is Gaussian with CV equal to DAYLIGHT_CV.

Returns
surface light intensity
Parameters
tsteptime step of the model, limited by maximum commondata::lifespan.
is_stochasticlogical indicator for stochastic light intensity if TRUE, then Gaussian stochastic version is used, if FALSE, deterministic is used. Code for wxMaxima for quickcalc:
surlig(a, span) := 500*0.5*(1.01+sin(3.14*2.*50*a/(1.*span)));
wxplot2d(surlig(a, 14000), [a,0, 1400]);

Definition at line 5399 of file m_env.f90.

◆ light_surface_stochastic_vector()

real(srp) function, dimension(size(tstep)), private the_environment::light_surface_stochastic_vector ( integer, dimension(:), intent(in)  tstep,
logical, intent(in)  is_stochastic 
)
private

Calculate stochastic surface light at specific time step of the model.

Parameters
tsteptime step of the model, limited by maximum commondata::lifespan.
Returns
surface light intensity.
Parameters
is_stochasticlogical indicator for stochastic light intensity if TRUE, then Gaussian stochastic version is used, if FALSE, deterministic is used.
Note
This function accepts vector arguments.
Warning
Note that the tstep array parameter is mandatory here (otherwise the generic interface is ambiguous).

Implementation details

If is_stochastic flag is TRUE, then the light intensity is a random Gaussian vector with each element mean equal to the deterministic value and coefficient of variation DAYLIGHT_CV.

If is_stochastic flag is FALSE, deterministic vector value is used.

Definition at line 5447 of file m_env.f90.

◆ light_depth_integer()

real(srp) function, private the_environment::light_depth_integer ( integer, intent(in)  depth,
real(srp), intent(in), optional  surface_light,
logical, intent(in), optional  is_stochastic 
)
private

Calculate underwater light at specific depth given specific surface light.

Underwater light is attenuated following Beer’s law,

\[ E_{b}(z,t) = L_{t} e^{-K z} , \]

where $ E_{b}(z,t) $ is background irradiance at depth z at time t and K is the attenuation coefficient for downwelling irradiance. The value of K in the old code was set very high to allow the vertical dynamics to take place within 30 depth cells.

Returns
Eb background irradiance at specific depth.
Parameters
[in]depthThe integer depth horizon where we get background
[in]surface_lightIrradiance at the surface, normally calculated at specific time point of the model with the the_environment::light_surface() function. If this parameter is absent, surface light at the current time step is obtained. The time step in such case is obtained from commondata::global_time_step_model_current.
[in]is_stochasticstochastic indicator for the surface light in the_environment::light_surface() function. If this parameter is absent, the default commondata::daylight_stochastic parameter value is used.
Note
Note that this function accepts integer depth, a separate function should be used for physical real type depth.
Note that it is an elemental function that accepts both scalar and array parameters.
Note
Note that the commondata::lightdecay parameter is in cm.

Definition at line 5507 of file m_env.f90.

◆ light_depth_real()

real(srp) function, private the_environment::light_depth_real ( real(srp), intent(in)  depth,
real(srp), intent(in), optional  surface_light,
logical, intent(in), optional  is_stochastic 
)
private

Calculate underwater light at specific depth given specific surface light.

Underwater light is attenuated following Beer’s law,

\[ E_{b}(z,t) = L_{t} e^{-K z} , \]

where $ E_{b}(z,t) $ is background irradiance at depth z at time t and K is the attenuation coefficient for downwelling irradiance.

Returns
Eb background irradiance at specific depth.
Parameters
[in]depthThe integer depth horizon where we get background.
[in]surface_lightIrradiance at the surface, normally calculated at specific time point of the model with the the_environment::light_surface() function. If this parameter is absent, surface light at the current time step is obtained. The time step in such case is obtained from commondata::global_time_step_model_current.
[in]is_stochasticstochastic indicator for the surface light in the_environment::light_surface() function. If this parameter is absent, the default commondata::daylight_stochastic parameter value is used.
Note
Note that this function accepts real depth.
Note
Note that the commondata::lightdecay parameter is in cm.
wxMaxima quick code for plotting (assuming surface light 500.0):
wxplot2d( 500.0*exp(-0.002 * d), [d, 0., 3000.] );

Definition at line 5582 of file m_env.f90.

◆ dist_scalar()

elemental real(srp) function the_environment::dist_scalar ( real(srp), intent(in)  x1,
real(srp), intent(in)  x2,
real(srp), intent(in)  y1,
real(srp), intent(in)  y2,
real(srp), intent(in), optional  z1,
real(srp), intent(in), optional  z2 
)

Calculate distance between 3D or 2D points. This is a function engine for use within type bound procedures. Example (dist_scalar):

dist(1.0,10.0, 2.0,20.0, 3.0,30.0 )
Note
This version accepts individual scalar coordinates.
Note that it is an elemental function, accepting also arrays (should have equal size and shape for elemental operations).
Note
3D distance is calculated only if z1 and z2 are provided, otherwise an orphaned z coordinate is ignored.

Definition at line 5633 of file m_env.f90.

◆ dist_vector_nd()

pure real(srp) function the_environment::dist_vector_nd ( real(srp), dimension(:), intent(in)  cvector1,
real(srp), dimension(:), intent(in)  cvector2 
)

Calculate distance between N-dimensional points. This is a function engine for use within other type bound procedures.

Returns
the distance between two N-dimensional vectors.
Parameters
cvectorN-dimensional vectors for the two points we calculate the distance between. For a 3D case the vercors look like: x = cvector(1), y = cvector(2), z = cvector(3). Example dist_vector:
dist( [1.0, 2.0, 3.0], [10.0, 20.0, 30.0] )
Note
This version accepts vectors of coordinates for each of the two objects.
Warning
The shapes and sizes of the two arrays must be equal

Definition at line 5666 of file m_env.f90.

◆ dist2_vector()

pure real(srp) function the_environment::dist2_vector ( real(srp), dimension(:), intent(in)  cvector1,
real(srp), dimension(:), intent(in)  cvector2 
)

Calculate the squared distance between two N-dimensional points.

Note
This function is useful in some cases when squared distances are used to save on calculation of square root.

Definition at line 5683 of file m_env.f90.

Here is the caller graph for this function:

◆ vect_magnitude()

pure real(srp) function the_environment::vect_magnitude ( real(srp), dimension(:), intent(in)  vector)

Calculate the magnitude of an arbitrary N-dimensional vector. This is a raw vector backend.

Parameters
[in]vectorvector a vector in N dimensions.
Returns
The magnitude of the vector.

Vector length is trivially calculated as the euclidean norm:

\[ \left \| x \right \| = \sum x_{i}^{2} . \]

Definition at line 5699 of file m_env.f90.

◆ dist2step()

elemental real(srp) function the_environment::dist2step ( real(srp), intent(in)  average_distance,
integer, intent(in), optional  dimensionality 
)

Calculate the unit step along a single coordinate axis given the average distance between any two points in a N-dimensional Gaussian random walk.

Returns
Unit step length along a single x,y,or z axis
Parameters
average_distanceThe average distance traversed by the moving point during a single step of the Gaussian random walk.
dimensionalityThe dimensionality of the random walk Example: dist2step Generate a Gaussian random walk in 3D with discrete step size, i.e. the true distance between the points (rather than coordinate shifts) equal to 10.0:
call moving_zzz%rwalk( dist2step(10.0), 0.5 )

Definition at line 5724 of file m_env.f90.

Here is the caller graph for this function:

◆ food_item_create()

elemental subroutine the_environment::food_item_create ( class(food_item), intent(inout)  this)

Create a single food item at an undefined position with default size.

This also cleanups the history stack, i.e. fills it with MISSING values.

Definition at line 5751 of file m_env.f90.

◆ food_item_make()

elemental subroutine the_environment::food_item_make ( class(food_item), intent(inout)  this,
type(spatial), intent(in)  location,
real(srp), intent(in), optional  size,
integer, intent(in)  iid 
)

Make a single food item, i.e. place it into a specific position in the model environment space and set the size.

Parameters
Locationof the food item as a SPATIAL type container
sizeThis is the optional size of the food item. If absent then default food size is used as defined in COMMONDATA
iidid for the food item. Note: There are no random iids for food items, iid should agree with the item index within the food resource object.

Implementation details

We here just set the location of the food object using standard interface function position.

Also, clean up the history stack, i.e. fills it with MISSING values.

Then we set the food item size. Check if optional size is provided and left untouched if not.

Note
Note that if the value provided is very small (e.g. zero or below), a minimum default value is used as a "floor".

This food item is NOT eaten from creation, so set the status FALSE.

Set the individual id iid.

Definition at line 5786 of file m_env.f90.

◆ food_item_capture_success_stochast()

logical function the_environment::food_item_capture_success_stochast ( class(food_item), intent(in)  this,
real(srp), intent(in), optional  prob 
)

Stochastic outcome of this food item capture by an agent. Returns TRUE if the food item is captured.

In this version, food item capture depends only on the fixed probability set by default as FOOD_ITEM_CAPTURE_PROBABILITY. Could also implement more complex patterns, e.g. dependent on the food item size (e.g. capture probability increases with food item size).

Parameters
[in]probfixed probability of food item capture. return@ TRUE if capture success.
Warning
This function does not change the state of the food item object, only returns success.
This function cannot be made elemental / puredue to random number call.

Implementation details

Check if prob is present, if not, use default parameter FOOD_ITEM_CAPTURE_PROBABILITY value, assuming this food item is in proximity of the predator agent (see function capture_probability.

First check if this food item is available, if it is not, this may mean it was an error (e.g. only available food items should get into the agent perception object).

Note
Note that the probability of capture is fixed by the input value and does not currently depend on the properties of the food item itself. TODO: make option to depend on this food item properties, e.g. its size.

Definition at line 5840 of file m_env.f90.

Here is the call graph for this function:

◆ food_item_capture_probability_calc()

real(srp) function the_environment::food_item_capture_probability_calc ( class(food_item), intent(in)  this,
real(srp), intent(in), optional  distance,
integer, intent(in), optional  time_step_model 
)

Calculate the probability of capture of this food item by a predator agent depending on the distance between the agent and this food item.

Capture probability is determined on the basis of a non-parametric relationship (interpolation) between the distance between the predator agent and this food item. It is equal to the the baseline value set by commondata::food_item_capture_probability parameter at the distance 0.0 and approaches a nearly zero value set by the parameter commondata::food_item_capture_probability_min = 0.1, at the distance equal to the visual range of the agent.

Parameters
[in]distanceoptional distance to the food item.
[in]time_step_modeloptional time step of the model, if absent, obtained from the global variable commondata::global_time_step_model_current.
Returns
The probability of capture of this food item.

Implementation details

Visual range

First, the visual range for a predator $ R_{v} $ to detect this food item is calculated using the_environment::food_item_visibility_visual_range().

The probability of capture of this food item by a predator is obtained by a nonparametric function that is based on nonlinear interpolation.

Interpolation grid abscissa

The distance for calculating the probability of capture of this food item by a predator is expressed in terms of the predator's visual range. The interpolation grid abscissa is set to the distance zero, half of the visual range ( $ 1/2 R_{v} $) and full visual range ( $ R_{v} $) of the predator agent.

Interpolation grid ordinate

It is assumed that the probability of capture of this food item is equal to the commondata::food_item_capture_probability parameter at the distance zero, and reduces to 0.8 of this value at $ 1/2 R_{v} $, and further reduces to commondata::food_item_capture_probability_min = 0.1 at the full visual range distance ( $ R_{v} $).

Note
Interpolation plot command: htintrpl.exe [0.0 0.5 1.0] [0.85, 0.68, 0.1] (0.68=0.85*0.8).

Optional distance parameter

Check optional distance dummy parameter and set local value or default (half a visual range) if the parameter is not provided.

Also check if the distance provided is longer than the visual range so this food item cannot be detected by the agent. There should be normally no such cases, if this occurs, it may point to a bug.

If this is the case, set the capture probability to zero and exit.

Finally, he distance provided should not be equal to the missing value commondata::missing. Return zero capture probability in such a case.

Final calculations

Finally, the probability of capture of this food item by a predator is obtained by nonlinear (DDPINTERPOL) interpolation of the distance value expressed in terms of the visual range over the grid set by interpol_abscissa and interpol_ordinate. There is an additional condition 0 < p < 1 that is enforced by commondata::within().

Extended debugging outputs

Log the capture probability visual range calculated, along with the distance and the visual range.

Interpolation plots can be saved in the debug mode using this plotting command: commondata::debug_interpolate_plot_save().

Definition at line 5897 of file m_env.f90.

Here is the call graph for this function:

◆ food_item_visibility_visual_range()

real(srp) function the_environment::food_item_visibility_visual_range ( class(food_item), intent(in)  this,
real(srp), intent(in), optional  object_area,
real(srp), intent(in), optional  contrast,
integer, intent(in), optional  time_step_model 
)

Calculate the visibility range of this food item. Wrapper to the the_environment::visual_range() function. This function calculates the distance from which this food item can be seen by a predator (i.e. the default predator's visual range).

Warning
The visual_range procedures use meter for units, this auto-converts to cm.
Cannot implement a generic function accepting also vectors of this objects as only elemental object-bound array functions are allowed by the standard. This function cannot be elemental, so passed-object dummy argument must always be scalar.
Parameters
[in]object_areaobject_area is optional area of the food item (m). If not provided, obtained from the this object size attribute (the_environment::food_item::size).
[in]contrastcontrast is optional inherent visual contrast of the food item. the default contrast of all objects is defined by the commondata::preycontrast_default parameter.
[in]time_step_modeloptional time step of the model, if absent gets the current time step as defined by the value of commondata::global_time_step_model_current.

Implementation details

Calculate ambient illumination / irradiance at the depth of this food item at the given time step.

Return visual range of a predator to see this food item.

Definition at line 6036 of file m_env.f90.

Here is the call graph for this function:

◆ minimum_depth_visibility()

real(srp) function the_environment::minimum_depth_visibility ( real(srp), intent(in)  target_range,
real(srp), intent(in), optional  depth_range_min,
real(srp), intent(in), optional  depth_range_max,
real(srp), intent(in), optional  object_area,
real(srp), intent(in), optional  object_contrast,
integer, intent(in), optional  time_step_model 
)

Find the depth at which the visibility of a spatial object becomes smaller than a specific distance value target_range.

Note
This is a diagnostic function.
Parameters
[in]target_rangetarget_range This is the target visual range (visibility) value: this function calculates the depth at which visibility becomes smaller than this target range.
[in]depth_range_min!>
[in]depth_range_minsets the optimisation range for depth, this is the minimum depth where the search is done. This is an optional parameter, if absent, is set to the global minimum depth in the global habitats array commondata::global_habitats_available.
[in]depth_range_max!>
[in]depth_range_maxsets the optimisation range for depth, this is the maximum depth where the search is done. This is an optional parameter, if absent, is set to the global maximum depth in the global habitats array commondata::global_habitats_available.
[in]object_areaobject_area is the optional area of the spatial object (m) for which the depth is calculated. If absent, is calculated for the default average food item commondata::food_item_size_default.
[in]object_contrastobject_contrast optional contrast of the spatial object for which the calculation is done; if absent is set from the default commondata::preycontrast_default.
[in]time_step_modeltime_step_model is the time step of the model. If absent, is obtained from the global variable commondata::global_time_step_model_current.

Implementation details

The depth when the visibility of the spatial object becomes smaller than the target distance target_range is calculated using the Brent's commondata::zeroin() optimisation algorithm, see Brent, R., (1973). Algorithms for Minimization Without Derivatives, Prentice-Hall, Inc.

The function for calculating the visibility of this spatial object for optimisation by zeroin is calculated by visibility_loc(). This function is local to this function and is further wrapped into also local visibility_loc_diff() (it is set as the parameter f to commondata::zeroin()).

If the the depth cannot be calculated, further checks are done and an appropriate limiting value is set for this function return.

Definition at line 6100 of file m_env.f90.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ food_item_disappear()

elemental subroutine the_environment::food_item_disappear ( class(food_item), intent(inout)  this)

Make the food item "disappear" and take the "eaten" state, i.e. impossible for consumption by the agents.

Definition at line 6253 of file m_env.f90.

◆ food_item_is_eaten_unavailable()

elemental logical function the_environment::food_item_is_eaten_unavailable ( class(food_item), intent(in)  this)

Logical check-indicator function for the food item being eaten and not available.

Returns
Logical indicator TRUE if the food item is eaten and not available any more.

Definition at line 6265 of file m_env.f90.

◆ food_item_is_available()

elemental logical function the_environment::food_item_is_available ( class(food_item), intent(in)  this)

Logical check-indicator function for the food item being available.

Returns
Logical indicator TRUE if the food item is present in the environment and therefore available.
Note
It is the opposite of the above function the_environment::food_item::is_unavailable().

Definition at line 6286 of file m_env.f90.

◆ food_item_get_size()

elemental real(srp) function the_environment::food_item_get_size ( class(food_item), intent(in)  this)

Get the size component of the food item object.

Returns
item_size The size of the food item.

Definition at line 6304 of file m_env.f90.

◆ size2mass_food()

elemental real(srp) function the_environment::size2mass_food ( real(srp), intent(in)  radius)

Calculate the mass of a food item, the non-OO backend.

The food item mass depends on the density of the food and its volume

\[ \rho \cdot \frac{4}{3}\pi r^{3} , \]

where $ \rho $ is the food density and

\[ V = \frac{4}{3}\pi r^{3} \]

is the food item volume.

Note
Food item density is set by commondata::food_item_density parameter.

Definition at line 6322 of file m_env.f90.

Here is the caller graph for this function:

◆ mass2size_food()

elemental real(srp) function the_environment::mass2size_food ( real(srp), intent(in)  mass)

Calculate the size (radius) of a food item, a reverse function of the_environment::size2mass_food():

\[ = \sqrt[3]{ \frac{M}{\rho \cdot 4/3 \pi} } , \]

where $ M $ is the food item mass, $ \rho $ is its density.

Note
Food item density is set by commondata::food_item_density parameter.

Definition at line 6337 of file m_env.f90.

◆ food_item_get_mass()

elemental real(srp) function the_environment::food_item_get_mass ( class(food_item), intent(in)  this)

Calculate and get the mass of the food item.

Returns
item_mass The mass of the food item.
Note
This is an OO frontend/wrapper.

Implementation details

The food item mass depends on the density of the food and its volume

\[ \rho \cdot \frac{4}{3}\pi r^{3} , \]

where $ \rho $ is the food density and

\[ V = \frac{4}{3}\pi r^{3} \]

is the food item volume.

Definition at line 6349 of file m_env.f90.

Here is the call graph for this function:

◆ food_item_set_iid()

elemental subroutine the_environment::food_item_set_iid ( class(food_item), intent(inout)  this,
integer, intent(in)  iid 
)

Set unique id for the food item object.

Parameters
iidindividual id number for the food item.

Definition at line 6367 of file m_env.f90.

◆ food_item_clone_assign()

elemental subroutine the_environment::food_item_clone_assign ( class(food_item), intent(in)  this,
class(food_item), intent(inout)  the_other 
)

Clone the properties of this food item to another food item.

Note
Note that the this food item serves as the source and the other, as the destination for cloning. So when used like this food_item_sourceclone( cloned_to_this_destination_item )
Parameters
[in,out]the_otherparam[inout] the_other Target food item to which the properties of the this item are cloned. It is declared as a polymorphic class so can get an extension type.

Implementation details

Use make method to transfer all the properties from this to the_other.

Definition at line 6383 of file m_env.f90.

◆ food_item_get_iid()

elemental integer function the_environment::food_item_get_iid ( class(food_item), intent(in)  this)

Get the unique id of the food item object.

Returns
iid the individual id number of this food item.

Definition at line 6401 of file m_env.f90.

◆ food_resource_make()

pure subroutine the_environment::food_resource_make ( class(food_resource), intent(inout)  this,
character(len=*), intent(in)  label,
integer, intent(in)  abundance,
type(spatial), dimension(:), intent(in)  locations,
real(srp), dimension(:), intent(in)  sizes 
)

Make food resource object. This class standard constructor.

Parameters
labelLabel for this food resource object.
abundancethe number of food items in the resource.
locationsAn array of SPATIAL locations of each food item.
sizesAn array of sizes of each food item.

Implementation details

First, we allocate the array of the food item objects with the size of abundance parameter.

Set label from input data.

Set abundance from input data.

Create all food items in the resource,

Set locations and food item sizes from input data vectors.

Definition at line 6417 of file m_env.f90.

◆ food_resource_get_abundance()

elemental integer function the_environment::food_resource_get_abundance ( class(food_resource), intent(in)  this)

Get the number of food items in the food resource.

Returns
The number of food items in this food resource.

Definition at line 6465 of file m_env.f90.

◆ food_resource_get_label()

elemental character(len=label_length) function the_environment::food_resource_get_label ( class(food_resource), intent(in)  this)

Get the label of the this food resource.

Returns
The label of this food resource.

Definition at line 6476 of file m_env.f90.

◆ food_resource_destroy_deallocate()

pure subroutine the_environment::food_resource_destroy_deallocate ( class(food_resource), intent(inout)  this)

Delete and deallocate food resource object. This class standard destructor.

Definition at line 6487 of file m_env.f90.

◆ food_resource_locate_3d()

pure type(spatial) function, dimension(size(this%food)) the_environment::food_resource_locate_3d ( class(food_resource), intent(in)  this)

Get the location object array (array of SPATIAL objects) of a food resource object.

Returns
locate_array an array of SPATIAL location objects for all food items within the resource.

Definition at line 6506 of file m_env.f90.

◆ food_resource_calc_average_distance_items()

real(srp) function the_environment::food_resource_calc_average_distance_items ( class(food_resource), intent(in)  this,
integer, intent(in), optional  n_sample 
)

Calculate the average distance between food items within a resource. e.g. to compare it with the agent's random walk step size.

Definition at line 6527 of file m_env.f90.

Here is the call graph for this function:

◆ food_resource_replenish_food_items_all()

subroutine the_environment::food_resource_replenish_food_items_all ( class(food_resource), intent(inout)  this,
integer, intent(in), optional  replace 
)

Replenish and restore food resource. The food resource is replenished by substituting randomly selected replace food items or all items if replace is omitted or exceeds the actual number of food items. Unlike the the_environment::food_resource::make() method, the sizes and the positions of the food items within the resource are reused from the previous positions (previously explicitly set set by the the_environment::food_resource::make() method).

Warning
This method is not used to build the food resource for the first time ("init"). Use the_environment::food_resource::make() to do this instead. This method is only for modifying the existing food resource object.
Parameters
[in]replacereplace Optional number of food items that replace those those that have been eaten in the population, this replace number cannot make the food resource population size bigger than the previous value.

Implementation notes

Implementation differs depending on full (replase absent) or partial replenishment (replace present).

  • If the replace parameter is set, a maximum of this number of eaten food items will be returned to the food resource, i.e. set the "not eaten" status.

First count food items that are eaten.

  • If the number of food items replaced (replace) exceeds this value n_eaten we reset all eaten food items as "not eaten."
  • Otherwise, the number of food items defined by replace will be replaced randomly (set not eaten) in the eaten. To do this:
  • allocate a temporary array of the size equal to this number of eaten items, initialised to commondata::unknown.
  • put indexes of all eaten food items into the idx_eaten_items array.
  • reorder idx_eaten_items in a random order
  • finally, reset the first replace food items as not eaten
  • If replace parameter is not present, just reset the the_environment::food_resource::food::eaten indicator of each food item to FALSE. Thus, the food resource is just reset to a fully available state.
Note
Note that the food items within the food resource retain their sizes and positions unchanged. If fully stochastic resource is required or its size needs to be altered, use the the_environment::food_resource::make() method.

Definition at line 6561 of file m_env.f90.

◆ food_resource_migrate_move_items()

subroutine the_environment::food_resource_migrate_move_items ( class(food_resource), intent(inout)  this,
real(srp), intent(in), optional  max_depth,
integer, intent(in), optional  time_step_model 
)

This subroutine implements the migration of all the food items in the resource according to the plankton migration pattern from the G1 model (HED18). Briefly, the movement of each of the food items has two components:

  • deterministic: regular vertical migration movement;
  • stochastic: small scale random Gaussian displacement.

Global habitats array

If the habitats are assembled into the global array the_environment::global_habitats_available and the migration is done on the original habitat-bound food resource objects, these original habitat objects and the global array require constant synchronisation with the the_environment::assemble() and the_environment::disassemble() procedures. Here is an example:

call disassemble( habitat_test1, habitat_test2 )
call habitat_test1%food%migrate_vertical()
call habitat_test2%food%migrate_vertical()
call assemble ( habitat_test1, habitat_test2 )

To avoid this, a separate procedure that works directly on an array of habitat objects is implemented: the_environment::migrate_food_vertical(). Its use is more efficient:

call migrate_food_vertical( Global_Habitats_Available )
Parameters
[in]max_depthmax_depth optional maximum depth of deterministic vertical migration; if this parameter is absent, the maximum depth in the habitat container for this food resource is used
[in]time_step_modeltime_step_model Optional time step of the model. If absent, the time step is obtained from the global array commondata::global_habitats_available.

Implementation notes

Checks and preparations

First, the procedure checks if the maximum depth for the vertical migration of food items is provided. If not, the maximum depth is determined as the maximum depth in the habitat of a single randomly chosen food item in this resource (see the_environment::spatial::find_environment()). Because a single food resource is nested within a specific habitat, all items are located in this environment, so the maximum depth is the same for all items of the resource.

Thus, habitat_res keeps the number of the habitat in the global array the_environment::global_habitats_available

Second, a check is done if the time step is provided. If no, the global time step from commondata::global_time_step_model_current is used.

Deterministic move

The depth centre of the food item vertical distribution is determined using the code from the HED18 model with minimum adaptations. This code is isolated into the the_environment::center_depth_sinusoidal() function.

Once the target depth for the food items is known, all the food resource is moved up or down to the target depth.

Stochastic walk

The second phase of the food item migration involves a stochastic random walk of each of the food items. This stochastic movement is described by the following parameters of the the_environment::spatial_moving::rwalk():

Note
Note that the stochastic random walk coincides with the default the_environment::food_resource::rwalk() method. The code is retained independently here because the parameters might not coincide with the default walk. Otherwise use call the default
call this%rwalk()

Definition at line 6660 of file m_env.f90.

Here is the call graph for this function:

◆ food_resource_rwalk_items_default()

subroutine the_environment::food_resource_rwalk_items_default ( class(food_resource), intent(inout)  this)

Perform a random walk step for all food items within the food resource. The walk is performed with the default parameters:

Implementation notes

First, the habitat number within the global habitats array the_environment::global_habitats_available is determined for a single randomly chosen food item within this resource. Because the food resource is bound to the habitat, this identifies the habitat.

Then, all food items within the resource are subjected to Gaussian random walk the_environment::spatial_moving::rwalk() with the following parameters:

Definition at line 6769 of file m_env.f90.

◆ migrate_food_vertical()

subroutine the_environment::migrate_food_vertical ( class(habitat), dimension(:), intent(inout)  habitats,
integer, intent(in), optional  time_step_model 
)

Migrate food items in a whole array of food resources. The array is normally the the_environment::global_habitats_available.

call migrate_food_vertical( Global_Habitats_Available )
Note
This is a not type-bound procedure.

Global habitats array

All the habitat objects are normally assembled into the global array the_environment::global_habitats_available. If so, this procedure makes it unnecessary to synchronise the habitat objects with the global array constantly by calling the_environment::habitat::disassemble() and the_environment::habitat::assemble() procedures whenever the habitat objects are changed (foods migrated). It makes the migration change directly on the global array.

The the_environment::food_resource::migrate_vertical() method that operates directly on food resource object in such case would require constant synchronisation/update between the global array and each habitat-bound food resource object, e.g.:

call disassemble( habitat_test1, habitat_test2 )
call habitat_test1%food%migrate_vertical()
call habitat_test2%food%migrate_vertical()
call assemble ( habitat_test1, habitat_test2 )
Parameters
[in,out]habitats[inout] habitats is an array of habitats
[in]time_step_modeltime_step_model Optional time step of the model. If absent, the time step is obtained from the global array commondata::global_time_step_model_current.

Implementation notes

A check is done if the time step is provided. If no, the global time step from commondata::global_time_step_model_current is used.

Then food resources within each of the habitats within the habitats array is subjected to the the_environment::food_resource::migrate_vertical() method.

Definition at line 6834 of file m_env.f90.

◆ rwalk_food_step()

subroutine the_environment::rwalk_food_step ( class(habitat), dimension(:), intent(inout)  habitats)

Perform a random walk of food items in a whole array of food resources. The array is normally the the_environment::global_habitats_available. This procedure is a wrapper for the_environment::food_resource::rwalk() to do a walk on a whole array of habitats and linked food resources.

call rwalk_food_step( Global_Habitats_Available )
Note
This is a not type-bound procedure.
Parameters
[in,out]habitats[inout] habitats is an array of habitats

Implementation notes

All the food resources within each of the habitats within the habitats array is subjected to the the_environment::food_resource::rwalk() method.

Definition at line 6874 of file m_env.f90.

◆ center_depth_sinusoidal()

real(srp) function the_environment::center_depth_sinusoidal ( integer, intent(in)  tstep,
real(srp), intent(in)  depth 
)

This function calculates the target depth for the sinusoidal vertical migration pattern of the food items at each time step of the model. See the_environment::food_resource_migrate_move_items() for the calling procedure.

Note
The depth centre of the food item vertical distribution is determined using the code from the HED18 model with minimum adaptations. This function isolates this HED18 code. The pattern coincides with the COPDVM = 1 in the HED18 model. Different pattern(s) is easy to add in separate procedures.
This procedure is isolated into a separate one, so diagnostic data/plots can be saved.
Parameters
[in]tsteptstep time step of the model.
[in]depthdepth sets the maximum target depth for vertical migration.
Returns
The target depth for the regular migration of the food items.

Verbatim code from HED18:

do a = 1, flifespan
!find center of copepod distribution
copsindepth = sin(3.14*a*2.*dielcycles/(flifespan+1.))
copcenterdepth = int(depth/2 + 0.33*depth*copsindepth)

Definition at line 6902 of file m_env.f90.

Here is the caller graph for this function:

◆ food_resource_save_foods_csv()

subroutine the_environment::food_resource_save_foods_csv ( class(food_resource), intent(in)  this,
character(len=*), intent(in), optional  csv_file_name,
logical, intent(out), optional  is_success 
)

Save characteristics of food items in the resource into a CSV file.

Implementation notes

First, check if the optional CSV file name is provided, if not, generate it automatically.

Then, data for the food resource is saved using the CSV_MATRIX_WRITE() procedure from HEDTOOLS.

The CSV output data file can be optionally compressed with the commondata::cmd_zip_output command if commondata::is_zip_outputs is set to TRUE.

Definition at line 6929 of file m_env.f90.

Here is the call graph for this function:

◆ food_resource_sort_by_size()

elemental subroutine the_environment::food_resource_sort_by_size ( class(food_resource), intent(inout)  this,
logical, intent(in), optional  reindex 
)

Sort the food resource objects within the array by their sizes. The two subroutines below are a variant of the recursive quick-sort algorithm adapted for sorting real components of the the FOOD_RESOURCE object.

Parameters
[in]reindexis a logical flag enabling re-indexing the food resource after it is sorted. The default is NOT to reindex.

Definition at line 6990 of file m_env.f90.

Here is the call graph for this function:

◆ food_resource_reset_iid_all()

pure subroutine the_environment::food_resource_reset_iid_all ( class(food_resource), intent(inout)  this,
integer, intent(in), optional  start_iid 
)

Reset individual iid for the food resource. Individual iids must normally coincide with the array order index. If it is changed after sorting, iids no longer reflect the correct index. So this subroutine resets iids to be coinciding with each food item index.

Parameters
start_iidis an optional parameters that sets the starting value for reindexing. For example, indexing from 1000 rather than 1.
Warning
Always reindex food resource after food items have been sorted!

Definition at line 7085 of file m_env.f90.

◆ reindex_food_resources()

subroutine the_environment::reindex_food_resources ( class(food_resource), intent(inout), optional  resource_1,
class(food_resource), intent(inout), optional  resource_2,
class(food_resource), intent(inout), optional  resource_3,
class(food_resource), intent(inout), optional  resource_4,
class(food_resource), intent(inout), optional  resource_5,
class(food_resource), intent(inout), optional  resource_6,
class(food_resource), intent(inout), optional  resource_7,
class(food_resource), intent(inout), optional  resource_8,
class(food_resource), intent(inout), optional  resource_9,
class(food_resource), intent(inout), optional  resource_10,
class(food_resource), intent(inout), optional  resource_11,
class(food_resource), intent(inout), optional  resource_12,
class(food_resource), intent(inout), optional  resource_13,
class(food_resource), intent(inout), optional  resource_14,
class(food_resource), intent(inout), optional  resource_15,
class(food_resource), intent(inout), optional  resource_16,
class(food_resource), intent(inout), optional  resource_17,
class(food_resource), intent(inout), optional  resource_18,
class(food_resource), intent(inout), optional  resource_19,
class(food_resource), intent(inout), optional  resource_20 
)

Reset and reindex iids for an input list of several food resources. As the result of this subroutine all food items across all the resources within the whole list will have unique iids.

Parameters
[in,out]resource_1,resource_2,...a list of food resources to reindex
Note
The calculation does not use an array of food resources because this can create problems in setting input dummy parameters in the array constructor. It just accepts raw resource objects and does all the operations directly on them. The number of food resources is probably never big, so the hard-coded limit of 20 components would probably never be exceeded. But the object list implementation is rather wordy, code-duplicating and prone to editing bugs. The main aim of this wordy, code-dubbing and mistype-prone approach was to allow easy passage of the whole original resource objects back from the collapsed object retaining all the changes that were introduced (e.g. the eaten status) while the resource objects were processed as the joined super-object. TODO: Perhaps it could be reimplemented in a better style using an extension object type.
Warning
Note that this is not a type-bound subroutine. It should not be declared in the FOOD_RESOURCE type.
Note
See notes on food_resources_collapse(), food_resources_update_back() and reindex_food_resources().

Definition at line 7135 of file m_env.f90.

◆ food_resources_collapse()

subroutine the_environment::food_resources_collapse ( class(food_resource), intent(out)  food_resource_collapsed,
class(food_resource), intent(in), optional  resource_1,
class(food_resource), intent(in), optional  resource_2,
class(food_resource), intent(in), optional  resource_3,
class(food_resource), intent(in), optional  resource_4,
class(food_resource), intent(in), optional  resource_5,
class(food_resource), intent(in), optional  resource_6,
class(food_resource), intent(in), optional  resource_7,
class(food_resource), intent(in), optional  resource_8,
class(food_resource), intent(in), optional  resource_9,
class(food_resource), intent(in), optional  resource_10,
class(food_resource), intent(in), optional  resource_11,
class(food_resource), intent(in), optional  resource_12,
class(food_resource), intent(in), optional  resource_13,
class(food_resource), intent(in), optional  resource_14,
class(food_resource), intent(in), optional  resource_15,
class(food_resource), intent(in), optional  resource_16,
class(food_resource), intent(in), optional  resource_17,
class(food_resource), intent(in), optional  resource_18,
class(food_resource), intent(in), optional  resource_19,
class(food_resource), intent(in), optional  resource_20,
logical, intent(in), optional  reindex,
character(len=*), intent(in), optional  label 
)

Collapse several food resources into one. The collapsed resource can then go into the perception system. The properties of the component resources are retained in the collapsed resource.

Parameters
[out]food_resource_collapsedoutput resource object that is formed by joining the list of component resource objects.
[in]resource_1,resource_2,...a list of component resource objects.
[in]reindexlogical flag to reindex the joined resource (TRUE) upon joining. The default is no reindexing.
[in]labelLabel for the joined food resource, if absent set to 'tmp_object'.

Implementation notes

The calculations in this procedure does not use an array of food resources because this can create problems in setting input dummy parameters in the array constructor. It just accepts raw resource objects and does all the operations directly on them. The number of food resources is probably never big, so the hard-coded limit of 20 components would probably never be exceeded. But the object list implementation is rather wordy, code-duplicating and prone to editing bugs. The main aim of this wordy, code-dubbing and mistype-prone approach was to allow easy passage of the whole original resource objects back from the collapsed object retaining all the changes that were introduced (e.g. the eaten status) while the resource objects were processed as the joined super-object. TODO: Perhaps it could be reimplemented in a better style using an extension object type. The joined food resource object retains the original component ID's. If common unique iids are needed, reindex method should be called upon joining! This is performed now using the optional 'reindex' parameter. If the food items are re-sorted within the joined food resource, their iid's no longer correspond to the original id's. Therefore, unjoining will result in totally new order and id's and the stacking of the original component resources is broken: correct unjoining is then impossible.

Usage example

This example shows how to use the join and unjoin methods to collapse and split back food resources.

! Join two resources into `joined_food_res_tmp`
call joined_food_res_tmp%join( habitat_safe%food, &
habitat_dangerous%food, &
reindex=.true. )
! We can then work with the collapsed resource, e.g. get
! the perception and use the "eat" method.
call proto_parents%individual(ind)%see_food(joined_food_res_tmp)
call proto_parents%individual(ind)%do_eat_food_item( &
food_item_selected, joined_food_res_tmp)
! after this we use the "unjoin" method to get back the
! original component food resources, they are now in an updated
! state, e.g. the "eaten" flag is transferred from the collapsed
! food resource object back to the component objects.
call joined_food_res_tmp%unjoin( habitat_safe%food, &
habitat_dangerous%food, &
reindex=.true. )
! destroy the temporary collapsed resource object.
call joined_food_res_tmp%destroy()

Note
See notes on food_resources_collapse(), food_resources_update_back() and reindex_food_resources().

Implementation details

For each food resource that is provided in the list we take the temporary transfer arrays for parameter copying from the component food resource into the food_resource_collapsed.

Make this food resource from the component objects that are provided.

And add extra object component arrays that do not get modified by make: the eaten status and the id number (iid).

If the reindex flag is present and is TRUE, do reindexing the new joined food resource.

Definition at line 7350 of file m_env.f90.

◆ food_resources_collapse_global_object()

type(food_resource) function the_environment::food_resources_collapse_global_object ( logical, intent(in), optional  reindex,
character(len=*), intent(in), optional  label 
)

Join food resources into a single global food resource out of the global array the_environment::global_habitats_available. See the_environment::unjoin() for how to unjoin an array of food resources back into an array. The joined resource can then go into the perception system. The properties of the component resources are retained in the collapsed resource.

Note
This procedure is intended to use a short interface name join, see the_environment::join().
A similar procedure using a list of input component resources is implemented in the_environment::food_resources_collapse().
Parameters
[in]reindexreindex logical flag to reindex the joined resource (TRUE) upon joining. The default is no reindexing.
[in]labellabel Label for the joined food resource, if absent set to 'tmp_object'.
Returns
A collapsed food resource joining the input array.

Implementation details

This procedure builds the output food_resource_collapsed resource object from scratch fully substituting the normal make the_environment::food_resource::make() method. Check out the main method the_environment::food_resource::make() in case of reimplementation.

Make a label for the collapsed object, if not present as a dummy parameter, set to 'tmp_object'.

  • Allocate the food items array for the collapsed food resource.
  • Set the abundance for the new output object equal to the sum across all the components.
  • Create all the food items in the new object using the the_environment::food_item::create() method.
  • Finally, copy individual food items from the component resources into the new joined resource looping over all resources and appending arrays.
  • If the reindex flag is present and is TRUE, do reindexing the new joined food resource.

Definition at line 7914 of file m_env.f90.

◆ food_resources_update_back()

subroutine the_environment::food_resources_update_back ( class(food_resource), intent(in)  food_resource_collapsed,
class(food_resource), intent(inout), optional  resource_1,
class(food_resource), intent(inout), optional  resource_2,
class(food_resource), intent(inout), optional  resource_3,
class(food_resource), intent(inout), optional  resource_4,
class(food_resource), intent(inout), optional  resource_5,
class(food_resource), intent(inout), optional  resource_6,
class(food_resource), intent(inout), optional  resource_7,
class(food_resource), intent(inout), optional  resource_8,
class(food_resource), intent(inout), optional  resource_9,
class(food_resource), intent(inout), optional  resource_10,
class(food_resource), intent(inout), optional  resource_11,
class(food_resource), intent(inout), optional  resource_12,
class(food_resource), intent(inout), optional  resource_13,
class(food_resource), intent(inout), optional  resource_14,
class(food_resource), intent(inout), optional  resource_15,
class(food_resource), intent(inout), optional  resource_16,
class(food_resource), intent(inout), optional  resource_17,
class(food_resource), intent(inout), optional  resource_18,
class(food_resource), intent(inout), optional  resource_19,
class(food_resource), intent(inout), optional  resource_20,
logical, intent(in), optional  reindex 
)

Transfer back the resulting food resources into their original objects out from a collapsed object from food_resources_collapse.

Parameters
[in,out]resource_1,resource_2,...a list of food resources to restore from the joined state.
[in]reindexlogical flag to reindex the joined resource (TRUE) upon joining. Default is no reindexing.
Note
The calculation does not use an array of food resources because this can create problems in setting input dummy parameters in the array constructor. It just accepts raw resource objects and does all the operations directly on them. The number of food resources is probably never big, so the hard-coded limit of 20 components would probably never be exceeded. But the object list implementation is rather wordy, code-duplicating and prone to editing bugs. The main aim of this wordy, code-dubbing and mistype-prone approach was to allow easy passage of the whole original resource objects back from the collapsed object retaining all the changes that were introduced (e.g. the eaten status) while the resource objects were processed as the joined super-object. TODO: Perhaps it could be reimplemented in a better style using an extension object type.
Warning
The un-joined food resource objects retain the joined object ID's. If individual id indexing are required, reindex method should be called for each of the unjoined food resource object upon joining!
Note
See notes on food_resources_collapse(), food_resources_update_back() and reindex_food_resources().

Implementation details

For each food item within the resource we copy all the object component values from the collapsed object to the original component object.

If reindex is explicitly set to TRUE, we reindex the component resources upon unjoining.

Definition at line 8023 of file m_env.f90.

◆ food_resources_update_back_global_object()

subroutine the_environment::food_resources_update_back_global_object ( type(food_resource), intent(in)  food_resource_collapsed,
logical, intent(in), optional  reindex 
)

Transfer the (having been modified) food resource objects from the single united object food_resource_collapsed back to the global array the_environment::global_habitats_available array. See the_environment::join() for how to join an array of food resources into a single global object.

Parameters
[in]food_resource_collapsedA collapsed food resource previously joining the input array.
[in]reindexreindex logical flag to reindex the unjoined resource (TRUE) upon unjoining. The default is no reindexing.

Implementation details

This procedure restores individual food resources into the global array the_environment::global_habitats_available array from the collapsed resource food_resource_collapsed.

For each food item within the resource we copy all the object component values from the collapsed object to the original component object.

If reindex is explicitly set to TRUE, we reindex the component resources upon unjoining.

Definition at line 8636 of file m_env.f90.

◆ global_habitats_assemble()

subroutine the_environment::global_habitats_assemble ( type(habitat), intent(in), optional  habitat_1,
type(habitat), intent(in), optional  habitat_2,
type(habitat), intent(in), optional  habitat_3,
type(habitat), intent(in), optional  habitat_4,
type(habitat), intent(in), optional  habitat_5,
type(habitat), intent(in), optional  habitat_6,
type(habitat), intent(in), optional  habitat_7,
type(habitat), intent(in), optional  habitat_8,
type(habitat), intent(in), optional  habitat_9,
type(habitat), intent(in), optional  habitat_10,
type(habitat), intent(in), optional  habitat_11,
type(habitat), intent(in), optional  habitat_12,
type(habitat), intent(in), optional  habitat_13,
type(habitat), intent(in), optional  habitat_14,
type(habitat), intent(in), optional  habitat_15,
type(habitat), intent(in), optional  habitat_16,
type(habitat), intent(in), optional  habitat_17,
type(habitat), intent(in), optional  habitat_18,
type(habitat), intent(in), optional  habitat_19,
type(habitat), intent(in), optional  habitat_20,
logical, intent(in), optional  reindex 
)

Assemble the global habitats objects array the_environment::global_habitats_available from a list of separate habitat objects. This call.

assemble(hab_a, hab_b, hab_c)

is equivalent to

global_habitats_available = [ hab_a, hab_b, hab_c ]
Note
But note that the reindex parameter allows automatic reindexing of the global array the_environment::global_habitats_available.
Parameters
[in]habitat_1[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_2[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_3[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_4[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_5[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_6[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_7[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_8[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_9[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_10[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_11[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_12[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_13[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_14[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_15[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_16[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_17[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_18[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_19[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]habitat_20[inout] habitat_1, ... a list (up to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]reindexreindex logical flag to reindex the global joined food resource array (TRUE) linked to each of the habitats upon assemble. Default is no reindexing.

Implementation notes

  • Stage 1: Calculate how many habitat objects are there in the input parameter list.

Stage 2: Allocate the the_environment::global_habitats_available global array of habitat objects the above number of elements.

  • Stage 3: Build the global array of habitat objects one by one from the input list of individual habitat objects.
  • Stage 4: Optionally reindex each element of the the global array the_environment::global_habitats_available.

Definition at line 8701 of file m_env.f90.

◆ global_habitats_disassemble()

subroutine the_environment::global_habitats_disassemble ( type(habitat), intent(out)  habitat_1,
type(habitat), intent(out), optional  habitat_2,
type(habitat), intent(out), optional  habitat_3,
type(habitat), intent(out), optional  habitat_4,
type(habitat), intent(out), optional  habitat_5,
type(habitat), intent(out), optional  habitat_6,
type(habitat), intent(out), optional  habitat_7,
type(habitat), intent(out), optional  habitat_8,
type(habitat), intent(out), optional  habitat_9,
type(habitat), intent(out), optional  habitat_10,
type(habitat), intent(out), optional  habitat_11,
type(habitat), intent(out), optional  habitat_12,
type(habitat), intent(out), optional  habitat_13,
type(habitat), intent(out), optional  habitat_14,
type(habitat), intent(out), optional  habitat_15,
type(habitat), intent(out), optional  habitat_16,
type(habitat), intent(out), optional  habitat_17,
type(habitat), intent(out), optional  habitat_18,
type(habitat), intent(out), optional  habitat_19,
type(habitat), intent(out), optional  habitat_20,
logical, intent(in), optional  reindex 
)

Disassemble the global habitats objects array the_environment::global_habitats_available into separate habitat object.

Parameters
[out]habitat_1[inout] habitat_1, ... a list (from 2 to 20) of food resources to restore from the joined state.
Warning
elementary habitats in the list are strictly type, extension (class) objects are not supported.
Parameters
[in]reindexreindex logical flag to reindex the joined food resource (TRUE) linked to each of the habitats upon disassemble. Default is no reindexing.

Definition at line 8972 of file m_env.f90.

◆ spatial_neighbours_distances()

subroutine the_environment::spatial_neighbours_distances ( class(spatial), intent(in)  this,
class(spatial), dimension(:), intent(in)  neighbours,
real(srp), dimension(:), intent(out), optional  dist,
integer, dimension(:), intent(out), optional  index_vector,
integer, dimension(:), intent(out), optional  ranks,
integer, intent(in), optional  rank_max,
logical, intent(out), optional  error_flag 
)

Calculate the distances between this spatial object and an array of its neighbours. Optionally output the distances, sorting index vector and rankings vector for each of these neighbours. Optionally do only partial indexing, up to the order rank_max for computational speed. Procedure ARRAY_INDEX() from HEDTOOLS is used as the computational backend for partial segmented indexing.

Parameters
[in]neighboursan array of spatial objects that we sort by distance from this target object.
[out]distoptional vector of the distance between each of the neighbours and this spatial object.
[out]index_vectora vector for sort order indexing of the neighbours. see documentation for ARRAY_INDEX() in HEDTOOLS for more details on sort order indexing.
[out]ranksoptional vector of rank ordering scores of each of the distances.
[in]rank_maxsets the maximum limit on the objects to rank/index we are interested in, i.e. for partial indexing (see manual for ARRAY_INDEX).
[out]error_flagoptional error flag, normally should be FALSE.
Warning
Cannot be made pure because of I/O calls.

Implementation details

First, calculate the distances between this object ant all of its neighbours. This is done using the parallel do concurrent construct from F2008.

Iterative vector sorting and ranking indexes can be slow to calculate when there are many neighbours. So we need to know are they really necessary (parameters present). Also check that all vectors have the same sizes.

Partial indexing is used if rank_max parameter is provided. This will avoid full indexing of all objects which may be much faster for big arrays.

Then calculate ranks if we need them.

If we need ranks, calculate both index vector and ranks

Use partial indexing if rank_max parameter is provided. This will avoid full indexing of all objects which may be much faster for big arrays.

Full indexing otherwise.

Definition at line 9216 of file m_env.f90.

◆ predator_make_init()

elemental subroutine the_environment::predator_make_init ( class(predator), intent(inout)  this,
real(srp), intent(in)  body_size,
real(srp), intent(in)  attack_rate,
type(spatial), intent(in), optional  position,
character(len=*), intent(in), optional  label 
)

Initialise a predator object.

Parameters
body_sizethe body size of the predator.
attack_ratebaseline attack rate of the predator.
environmentThe environment within which the predator is located initially.
labeloptional label for the predator.

Implementation details

We first create an empty spatial sub-object for the predator.

Set the body size parameter, with a limitation that it must exceed zero.

Set the capture attack rate parameter, limited to be within the range [0:1].

Set the initial position if it is provided (will remain MISSING as initialised in create method above otherwise).

Finally, set label for the predator if provided, empty if absent.

Definition at line 9328 of file m_env.f90.

◆ predator_label_set()

subroutine the_environment::predator_label_set ( class(predator), intent(inout)  this,
character(len=*), optional  label 
)

Set label for the predator, if not provided, set it random.

Parameters
labeloptional label for the predator.

Definition at line 9370 of file m_env.f90.

◆ predator_get_body_size()

elemental real(srp) function the_environment::predator_get_body_size ( class(predator), intent(in)  this)

Accessor function for the predator body size (length).

Definition at line 9386 of file m_env.f90.

◆ predator_get_attack_rate()

elemental real(srp) function the_environment::predator_get_attack_rate ( class(predator), intent(in)  this)

Accessor function for the predator attack rate.

Definition at line 9396 of file m_env.f90.

◆ predator_capture_risk_calculate_fish()

real(srp) function the_environment::predator_capture_risk_calculate_fish ( class(predator), intent(in)  this,
class(spatial), intent(in)  prey_spatial,
real(srp), intent(in)  prey_length,
real(srp), intent(in), optional  prey_distance,
logical, intent(in), optional  is_freezing,
integer, intent(in), optional  time_step_model,
character(len=*), intent(in), optional  debug_plot_file 
)

Calculates the risk of capture of the fish with the spatial location defined by prey_spatial and the body length equal to prey_length. This is a backend function bound to the predator rather than prey object.

Note
This procedure calculates the probability of capture from the the predator object side:
predator%risk_fish( agent%location, agent%get_length() )
It is not possible for the predator-object-bound function to determine the properties of the prey agent (that is the dummy parameter) as these parameters are defined in the_neurobio module later in the class hierarchy. For example, body mass of the agent is set in the_body::condition whereas the perception object bound function the_neurobio::perception::has_pred is defined in the the_neurobio::perception class. This is why the properties of the prey, the length and the distance, are set via mandatory dummy parameters. The capture probability should normally be calculated for the agent the other way round using the frontend function the_neurobio::perception::risk_pred():
agent%risk_pred( predator )
Parameters
[in]prey_spatialprey_spatial the spatial position of a fish/agent prey.
[in]prey_lengthprey_length the length of the prey fish agent.
[in]prey_distanceprey_distance optional distance between the this predator and the prey fish agent.
[in]is_freezingis_freezing Optional logical indicator that the prey fish agent is immobile.
[in]time_step_modeltime_step_model optional time step of the model.
[in]debug_plot_filedebug_plot_file optional file name for the debug nonparametric function (interpolation) plot.
Returns
The probability of successful capture of the prey by the this predator

Check optional parameters

Check optional time step parameter. If unset, use global variable commondata::global_time_step_model_current.

Check the distance to the prey dummy parameter. If present, the dummy parameter for the distance is used.

However, if the dummy parameter is not provided, the distance between the this predator and the prey spatial object is calculated using the spatial::distance() function.

Check optional debug plot file name, if absent, a random name is generated based on the predator's iid. However, the prey agent's iid cannot yet be determined as it is defined in the following module layers. Threfore, it should be provided, if necessary, via the optional file name parameter.

Implementation details

Calculate the visibility of the prey fish object

First, calculate the illumination (background irradiance) at the depth of the prey spatial object.

Second, calculate the fish prey area (m) that will later go into the visual range calculation backend engine.

Third, calculate the visual range for the predator for detecting the fish prey object defined by the prey_spatial spatial object. It is assumed here that the predator is much larger than the agent prey.

At the figure above, $ VR_{p} $ is the visual range for the agent to detect the predator and $ VR_{a} $ is the visual range for the predator to see the agent prey. This is why he calculations of the capture probability are based on the latter, $ VR_{a} $, the visibility of the prey for the predator.

Check prey agent visibility

Check if the prey agent is visible to the predator. Predator can only attack a prey agent that it can see. Otherwise zero predation risk is returned

Calculate the predation risk

Calculation is conducted differently depending on whether the agent is moving or immobile (freezing). Because the dimensionality of the interpolation grid arrays can be different in these two cases (requiring different declarations) they are isolated into two Fortran named block constructs.

Freezing (immobile) agent

Calculations of the predation risk for a freezing agent are conducted in the named block construct FREEZING.

  • Calculate the interpolation grid that is then used to calculate the predation risk.
    • The interpolation abscissa is defined by the visual range: from zero, half, 0.75 of the visual range and a full visual range. It is assumed that tha ability of the predator to locate and attack an immobile (freezing) agent is much smaller than a moving agent.
  • The interpolation grid ordinate determines the nonparametric relationship between the distance between the predator and prey and the predation risk, i.e. the probability of successful capture of the prey fish agent. The probability of capture at the zero distance is fixed and equal to the predator's inherent attack rate (the the_environment::predator::attack_rate data component) that is always less than the theoretically possible probability 1.0, whereas at the end of the visual range, the probability of capture is zero. Therefore, the interpolation function is defined by the two middle points: 0.5 and 0.75 of the visual range:
  • Finally, the probability of capture of the target prey fish agent is a nonparametric function of the distance between the predator and the prey calculated using the above grid arrays. There is an additional condition that this probability must be 0 < p < 1 that is enforced by commondata::within().
    Produce plot with:
         htintrpl.exe  [0 0.5 0.75 1] [1 0.1 0.01 0] [0.5] [nonlinear]
  • Interpolation plots can be saved in the debug mode using this plotting command: commondata::debug_interpolate_plot_save().

Normal moving agent

Calculations of the predation risk for the normal moving agent are conducted in the named block construct NORMAL_MOVING.

  • Calculate the interpolation grid that is then used to calculate the predation risk.
    • The interpolation abscissa is defined by the visual range: zero, distance half of the visual range, full visual range.
  • The interpolation grid ordinate determines the nonparametric relationship between the distance between the predator and prey and the predation risk, i.e. the probability of successful capture of the prey fish agent. The probability of capture at the zero distance is fixed and equal to the predator's inherent attack rate (the the_environment::predator::attack_rate data component) that is always less than the theoretically possible probability 1.0, whereas at the end of the visual range, the probability of capture is much lower and is defined by the commondata::predator_attack_capture_probability_min parameter. Therefore, there is only one value that can be set independently: the probability of capture at the distance equal to 1/2 of the visual range: it is defined as the parameter constant commondata::predator_attack_capture_probability_half.
  • Finally, the probability of capture of the target prey fish agent is a nonparametric function of the distance between the predator and the prey calculated using the above grid arrays. There is an additional condition that this probability must be 0 < p < 1 that is enforced by commondata::within().
    Produce plot with:
         htintrpl.exe  [0 0.5 0.75 1] [1 0.1 0.01 0] [0.5] [nonlinear]
  • Interpolation plots can be saved in the debug mode using this plotting command: commondata::debug_interpolate_plot_save().

Extended debugging outputs

Log the capture probability visual range calculated, along with the distance and the visual range.

Definition at line 9428 of file m_env.f90.

◆ predator_capture_risk_calculate_fish_group()

subroutine the_environment::predator_capture_risk_calculate_fish_group ( class(predator), intent(in)  this,
class(spatial), dimension(:), intent(in)  prey_spatial,
real(srp), dimension(:), intent(in)  prey_length,
logical, dimension(:), intent(in), optional  is_freezing,
integer, intent(in), optional  time_step_model,
real(srp), dimension(:), intent(out), optional  risk,
real(srp), dimension(:), intent(out), optional  risk_indexed,
integer, dimension(:), intent(out), optional  index_dist 
)

Calculates the risk of capture by a specific predator of an array of the fish agents with the spatial locations array defined by prey_spatial and the body length array prey_length. This subroutine takes account of both the predator dilution and confusion effects and risk adjusted by the distance towards the predator.

Note
This procedure accepts prey agents as a series of separate component arrays: prey_spatial, prey_length, is_freezing rather than a sigle the_individual::individual_agent type/class. This is done because the agent class hierarchy is defined specifically in the upstream modules and is not yet accessible at this level. The procedure here has the bare minimum requirements for the prey agents: the class the_environment::spatial.
Parameters
[in]prey_spatialprey_spatial the spatial position of a fish/agent prey.
[in]prey_lengthprey_length the length of the prey fish agent.
[in]is_freezingis_freezing Optional logical indicator that the prey fish agent is immobile.
[in]time_step_modeltime_step_model optional time step of the model.
[out]riskrisk is an optional array of predation risk estimates for each agent in the group. The values of the risk for all agents that are not visible to the predator get zero risk. Note that this array has the normal order of the objects as in the input arrays, i.e. as in the normal array of the agents.
[out]risk_indexedrisk_indexed is an optional array of predation risk estimates for each agent in the group. Risk for all agents that are not visible to the predator get zero risk. Note that this array is in the "raw" order, as the distances between the predator and the agents (not the normal order of the agents within the input group). Therefore, to translate this "raw" order it to the normal order, one requires the partial index array index_dist. The nature of the partial indexing dictates that only values with the index in the range from 1 to commondata::predator_risk_group_select_index_partial, i.e. the nearest neighbours of the predator make sense. All other index values are commondata::unknown.
Warning
The size of this array cannot be smaller than the partial indexing parameter commondata::predator_risk_group_select_index_partial
Parameters
[out]index_distindex_dist optional partial index array that shows the partial sorting of the agents with respect to their distance to the predator. Note that The nature of the partial indexing dictates that only values with the index in the range from 1 to commondata::predator_risk_group_select_index_partial, i.e. the nearest neighbours of the predator make sense. All other index values are commondata::unknown.
Warning
The size of this array cannot be smaller than the partial indexing parameter commondata::predator_risk_group_select_index_partial

Implementation details

Alternative indexing schemes

Two kinds of indexing of the output adjusted risk are possible to get: normal and "raw". The array in the normal order (risk) is provided with the same indexing as the input arrays (e.g. the array of the prey agents. The array in the "raw" order risk_indexed is arranged in the order of the distances between the predator and the prey agents (the first is the nearest). The latter "raw" array can be transformed to the normal ordering using the index_dist indexing array. See partial array indexing procedure in HEDTOOLS. The table below presents an example of the two modes of ordering.

"raw" normal Adjusted risk
1 249 0.571031094
2 433 0.445715338
3 272 0.202977672
4 713 0.113853760
5 359 0.086924118
6 665 0.000000000

An example of the code requesting the normal array of risks. This array is arranges in the same order as as the prey prey_spatial:

call habitat_safe%predators(i)%risk_fish_group( &
prey_spatial=proto_parents%individual, &
prey_length=proto_parents%individual%body_length, &
risk = group_risk_array )

An example of the code requesting "raw" indexed array of risks along with the partial index array:

call this_predator%risk_fish_group( &
prey_spatial = this%individual%location(), &
prey_length = this%individual%get_length(), &
is_freezing = this%individual%freeze%is_executed(), &
time_step_model = time_step_model_here, &
risk_indexed = p_risk, &
index_dist = prey_index )

Notable local variables

The calculations potentially involve looping over a huge array of potential prey agents, even though not all of them are at a close enough distance to the predator to have any risk. Only the agents that are within the visibility range (i.e. can be visible to the predator) count here out of the huge whole-population array. Finding the agents neighbouring to the predator benefits from partial indexing. Only a small small subarray within the input array of spatial prey agent objects is indexed and analysed. The maximum size of such a subarray is defined by the partial index size: commondata::predator_risk_group_select_index_partial (so all the work subarrays benefiting from partial indexing have such number of elements).

  • dist_index is the partial array sorting index, see ARRAY_INDEX() procedure from HEDTOOLS for more details. Note that This vector comes into the the_environment::neighbours() spatial indexing procedure and must have the full size of the spatial array being indexed. So its size here is equal to the prey_spatialarray size.

risk_adjusted is an array of predation risk estimates for each agent in the group. Risk for all agents that are not visible to the predator get null risk. This is the main array that is indexed exactly as the output.

  • risk_adjusted_indexed is an array of predation risk estimates for each agent in the group. Risk for all agents that are not visible to the predator get null risk. This array that is indexed in the order of the distances between the predator and each of the nearest agents. Translation of the true index array order to this raw order requires the indexing array dist_index.
  • risk_agent_is_visible is a logical flag array indicating that the i-th prey agent in the visual field of the predator is visible (i.e. within the visual range). Array limited by the maximum index size commondata::predator_risk_group_select_index_partial.
  • risk_agent_visibility is the visibility range of each prey agent in proximity of this predator. Array limited by the maximum index size commondata::predator_risk_group_select_index_partial.
  • risk_agent_rank is the integer rank order of each agent in the visual field of the predator with respect to the distance from the predator. Only agents visible to the predator (distance < maximum visibility range) count. One potential caveat is that because the prey agents are stochastic, there can be cases when a tiny agent is the nearest to the predator, but its visibility range is very small, smaller than the distance to the predator. Such agent is not counted and has undefined (commondata::unknown) risk_agent_rank.
  • rank_visible is the overall counter and the total number of "ranked" prey agents, i.e. those that are "visible".
  • risk_agent_baseline is the baseline risk of predation for each of the prey agents in proximity of the predator. Array limited by the index size commondata::predator_risk_group_select_index_partial.

Checks and preparations

Initialise index and rank values. Uninitialised index arrays may result in invalid memory reference in ARRAY_INDEX (it is not safe by design, see notes on the HEDTOOLS array indexing procedures.

Check if the optional is_freezing parameter array is provided. If not, it is assumed that the prey agents are NOT freezing.

Check optional time step parameter. If unset, use global commondata::global_time_step_model_current.

Check the size of the input arrays of prey agents, prey length and freezing indicztors. The sizes of all three arrays must be equal.

However, if they have different sizes, log warning, this may point to a potential bug.

Step 1

First, we get, up to the maximum order (fast partial indexing) of commondata::predator_risk_group_select_index_partial, neighbouring agents that are in proximity of this predator. Here we get partial index vector for the input array of objects: dist_index.

If the index_dist optional parameter is present in the list of parameters, it returns the indexing vector dist_index.

Step 2

Get a vector of agents sorted by their distances from the predator and calculate the baseline risk of predation for each of the agents using the the_environment::predator::risk_fish() method. The size of the array is limited by the maximum partial rank index commondata::predator_risk_group_select_index_partial, so only this number of nearest agents is taken into account. The other are too far at this moment and have null risk anyway (probably).

The boolean flag array risk_agent_is_visible indicating that this i-th agent is within the "neighbours" group is also set to TRUE.

The baseline risk of predation is the risk not taking account of the predator dilution effect by the other agent's group members in proximity.

  • First, calculate the visibility (visual range) of each neighbouring prey agent.
  • The risk of predation is non-zero only for those agents which are located from the predator at a distance smaller than their visibility distance, otherwise they fall outside of the visual range of the predator.
  • Such agents are marked with the risk_agent_is_visible boolean vector value TRUE.
  • Each of such visible agent is also assigned the consecutive rank, with the nearest agent having the rank 1 while the furtherst agent having the rank N (N is less than the maximum indexing rank commondata::predator_risk_group_select_index_partial). This is illustrated by the following plot.
    Calculation of predation risk in a group of prey agents
    Here the prey agents P1, P3 and P4 are invisible to the predator (in the centre) because their visibility ranges are smaller that the distance towards the predator. P2 has the rank R=1 as it has the smallest distance to the predator among all the agents that are visible (P2, P5, P6). Notably, the agent P1 is invisible due to small body size that leads to very short visibility range (even though it is actually the closest to the predator!) and therefore zero baseline probability capture at the distance to the predator (a plot of the relationship between the distance and the baseline probability of capture is also overlaid at the agent P1).
  • For all visible agents, the baseline risk of predation is calculated using the the_environment::predator::risk_fish() method. The baseline risk of predation is the risk not taking account of the predator confusion and dilution effect by the other agent's group members in proximity.
    Note
    Note that the baseline risk is zero if the distance to the predator exceeds the visual range, it is done automatically in the_environment::predator::risk_fish().
  • The step 2 is finalised by checking if there were any prey agents visible to the predator. If none were visible, return from the procedure with the consequence that all adjusted risk values are equal to the initialisation value risk_adjusted = 0.0. This situation is also logged in the DEBUG mode.

Step 3

Given that at the step 2 we have defined which of the prey agents in the group are actually visible to the predator, their rank order with respect to the distance, and the total number of such visible agents, this final step calculates the array of the adjusted risk values.

This can be done in several ways:

These procedires are implemented as subroutines within this main the_environment::predator_capture_risk_calculate_fish_group().

Calculate the raw indexed array of the risk that is intended to be returned (output) along with the partial index.

Finally, in the DEBUG mode also save debug data to CSV file. Below is an example data from one simulation using the fixed predation adjustment effect adjust_risk_nonpar_fixed().

AGENT VISIBLE RANK VISIBILITY DISTANCE RISK_BASE RISK_ADJ
P1 1 1 297.934 148.458 0.597635 0.597635
P2 1 2 310.591 238.575 0.375258 0.179290
P3 0 -9999 305.785 306.733 0 0
P4 0 -9999 296.327 309.332 0 0
P5 1 3 338.934 316.221 0.192204 0.034169
P6 0 -9999 283.830 318.537 0 0
P7 1 4 343.421 339.065 0 0
P8 0 -9999 311.020 366.969 0 0
P9 0 -9999 360.617 378.106 0 0
P10 0 -9999 312.113 395.021 0 0
P11 0 -9999 322.244 435.172 0 0
P12 0 -9999 335.271 442.236 0 0
P13 0 -9999 309.192 456.375 0 0
P14 0 -9999 269.335 477.448 0 0
P15 0 -9999 349.299 486.160 0 0
P16 0 -9999 273.446 501.956 0 0
P17 0 -9999 311.889 516.109 0 0
P18 0 -9999 361.142 533.081 0 0
P19 0 -9999 277.595 547.986 0 0
P20 0 -9999 267.683 561.175 0 0
Note
Note that the prey agents 3 and 4 are closer to the predator than 7, but are not visible due to small visibility range (small body sizes).

Finally, calculate the optional output arrays if the are requested as optional parameters: risk and risk_indexed

Definition at line 9726 of file m_env.f90.

Here is the call graph for this function:

◆ predator_visibility_visual_range()

real(srp) function the_environment::predator_visibility_visual_range ( class(predator), intent(in)  this,
real(srp), intent(in), optional  object_area,
real(srp), intent(in), optional  contrast,
integer, intent(in), optional  time_step_model 
)

Calculate the visibility range of this predator. Wrapper to the the_environment::visual_range() function. This function calculates the distance from which this predator can be seen by a visual object (e.g. the agent).

Warning
The visual_range procedures use meter for units, this auto-converts to cm.
Cannot implement a generic function accepting also vectors of this objects as only elemental object-bound array functions are allowed by the standard. This function cannot be elemental, so passed-object dummy argument must always be scalar.
Parameters
[in]object_areaobject_area optional area of the spatial object, m. if not provided (normally), calculated from the the_environment::predator::body_size attribute of this predator object.
[in]contrastcontrast is optional inherent visual contrast of the predator. the default contrast of all objects is defined by the commondata::preycontrast_default parameter.
[in]time_step_modeloptional time step of the model, if absent gets the current time step as defined by the value of commondata::global_time_step_model_current.
Returns
The maximum distance from which this predator can be seen.

Implementation details

Checks. Check optional object area, the default value, if this parameter is absent, the area is calculated from the the_environment::predator::body_size attribute of the predator object with inline conversion to m. Note that the body side area of a fish object is calculated from the body length using the commondata::length2sidearea_fish() function.

Check optional contrast parameter. If unset, use global commondata::preycontrast_default.

Check optional time step parameter. If unset, use global commondata::global_time_step_model_current.

Calculate ambient illumination / irradiance at the depth of this predator object at the given time step using the the_environment::spatial::illumination() method.

Return visual range for (to detect) this predator using the_environment::visual_range() wrapper function.

Definition at line 10463 of file m_env.f90.

◆ distance_average()

real(srp) function the_environment::distance_average ( class(spatial), dimension(:), intent(in)  spatial_objects,
integer, intent(in), optional  sample_size 
)

Calculates the average nearest neighbour distance amongst an array of spatial objects (class) by sampling sample_size of them. The sample size sample_size is optional, if not provided set to SAMPLE_SIZE_DEFAULT=25.

Parameters
spatial_objectsAn array of spatial class objects for which we calculate the average nearest neighbour distance.
sample_sizeOptional sample size for the calculation.
Returns
Returns a (sample-based) estimate of the mean nearest neighbour distance among an array of the spatial objects.

Notable local variables

  • SAMPLE_SIZE_DEFAULT is the local default sample size
  • SAMPLE_SIZE_WARN is the minimum warning sample size that results in warning logging.

MAX_ARRAY_DIMENSIONALITY: the maximum dimensionality of the input array of spatial objects for doing full non-sampling based calculations.

Maximum size of the input array of spatial objects for full element by element selection without random sampling. This maximum dimensionality can be obtained by solving this square equation:

\[ M = x^{2}+x , \]

where $ M $ is the maximum number of permutations. So, the maximum dimensionality of the input array of objects is

\[ \frac{\sqrt{4\cdot M + 1} + 1}{2} . \]

The value obtained is then rounded to the nearest whole integer using nint.

Note
Note that for the standard default SAMPLE_SIZE_DEFAULT=25, MAX_ARRAY_DIMENSIONALITY equals 6.

Implementation details

Check the array size. Big and small arrays are treated differently.

If the array size is zero or one, there is no sense calculating average nearest neighbour distance, just return zero and log warning.

If the array size is small enough, do full element by element selection and permutation. We do not then really use the sample_size (or N) parameter.

Do full N x N permutations in such a case.

Note
Note that we here do full crossing rather than half cutting j=i+1,array_size. Nearest neighbour distance are not transitive.

In all other cases do random sampling from the input array of spatial objects and calculate sample-based average nearestneighbour distance.

Set the maximum sample size not exceeding 1/2 of all possible permutations in case the input object array is relatively large. The default value 1/2 of all possible permutations may be quite big with a huge array, but the logic behind the decision is that the requested sample size was also big.

Note
Note that we have to convert integer(LONG) to the default integer using the intrinsic function int to make it acceptable for the TOSTR function from HEDTOOLS. Hopefully the final max_permutations would not be too huge.

If the requested sample size is very small, just do a warning. The logic behind NOT changing N to, e.g. SAMPLE_SIZE_DEFAULT is that if a small N was requested, this must have serious grounds, e.g. if the agent is basing its decision making process on an incomplete information. So the small value is left as small as requested.

Initialise the output mean distance with zero.

Do permutations, using PERMUTE named do-block:

  • We sample a single random spatial objects from the available array.
    Note
    Note that we have to convert integer(LONG) to the defaultinteger using the intrinsic function int to make it acceptable for the RAND_I function from HEDTOOLS. Hopefully the final array_size would not be too huge.
  • Get an array of all other objects excluding the already sampled.
    Note
    There seems to be no class-safe way to do whole-array assignments of SPATIAL objects for high speed, e.g. using the index slice: [ [(j, j=1,i-1)], [(j,j=i+1,array_size)] ] as we use the type-bound function location and position to copy arays. So using the explicit old-fashioned do-loop here.
  • Then we find the nearest neighbour of the i-th object out from the input array of spatial objects.
  • Calculate the distance between the (randomly selected) ith object and its nearest neighbour spatial_object_nearest_neighbour and update the overall sum.

Finally, calculate the mean distance over all these permutations.

Definition at line 10541 of file m_env.f90.

Here is the caller graph for this function:

◆ geo_poly2d_dist_point_to_section()

subroutine the_environment::geo_poly2d_dist_point_to_section ( class(spatial), intent(in)  point,
class(spatial), intent(in)  sectp1,
class(spatial), intent(in)  sectp2,
real(srp), intent(out)  min_dist,
type(spatial), intent(out), optional  point_segment 
)

Calculates the minimum distance from a the_environment::spatial class object to a line segment delimited by two the_environment::spatial class endpoints in the 2D XY plane (the depth coordinate is ignored). (The algorithm is partially based on this.)

Parameters
[in]pointpoint is the reference point to which the distance is calculated
[in]sectp1sectp1 is the first end of the line segment.
[in]sectp2sectp2 is the second end point of the line segment.
[out]min_distmin_dist is the output minimum distance between the reference point and the line segment delimited by sectp1 and sectp2.
[out]point_segmentpoint_segment is the optional output coordinates of the nearest point PN on the P1 P2 segment returned in the form of the_environment::spatial type object. But note that the third depth coordinate of this object is copied from the input point object.

Implementation details

A scheme of the calculation is presented on this figure:

Calculation of the distance from a spatial object to a line segment

First, calculate the squared distance between the end points of the line segment P1 and P2 using the backend function the_environment::dist2_vector() that accepts vectors of arbitrary dimensionality: $ D^{2}(\mathbf{p1},\mathbf{p2}) $

  • if the distance between the end points is zero, the line segment actually has zero length and the distance between the spatial object P0 and the segment is trivial to determine: $ D_{min} = D(\mathbf{p_0},\mathbf{p_1}) = D(\mathbf{p_0},\mathbf{p_2}) $.

Second, determine the reference value $ r $ (a normalised distance from P1 to the closest point) that is calculated as follows:

\[ r = \frac{\left|\mathbf{p}_{0} - \mathbf{p}_{1}\right| \cdot \left|\mathbf{p}_{2} - \mathbf{p}_{1}\right|}{D^{2}(\mathbf{p_1},\mathbf{p_2})} , \]

where $ D^{2}(\mathbf{p_1},\mathbf{p_2}) $ is the distance between the end points P1 and P2, and the numerator is the dot product of the vectors $ \left|\mathbf{p}_{0} - \mathbf{p}_{1}\right| $ and $ \left|\mathbf{p}_{2} - \mathbf{p}_{1}\right| $.

  • The $ r < 0 $ indicates that the projection of the spatial object P0 onto the P1 P2 line is located in front of the P1 end, thus the minimum distance is calculated as

    \[ D_{min} = D(\mathbf{p_0},\mathbf{p_1}) . \]

    Also, the nearest point PN coordinates coincide with the X and Y coordinates of P1.
  • If $ r > 1 $, the projection of the spatial object P0 on the line P1 P2 is behind the P2 end, so the minimum distance is

    \[ D_{min} = D(\mathbf{p_0},\mathbf{p_2}) . \]

    Also, the nearest point PN coordinates coincide with the X and Y coordinates of P2.
  • In other cases, the spatial object P0 projects to a specific point on the P1 P2 line. The distance between the spatial object P0 and this projection is calculated as:

    \[ D_{min}= \frac{\left | (y_2-y_1)x_0-(x_2-x_2)y_0+x_2y_1-y_2x_1 \right |}{D^2(\mathbf{p_1},\mathbf{p_2})} , \]

    where $ (x_0, y_0) $ are the coordinates of the spatial object P0, $ (x_1, y_1) $ are the coordinates of the point P1 and $ (x_2, y_2) $ are the coordinates of the point P2. The nearest point PN coordinates are calculated as

    \[ \left | \mathbf{p_1}+(\mathbf{p_2}-\mathbf{p_1}) r \right | . \]

Definition at line 10769 of file m_env.f90.

Here is the call graph for this function:

◆ geo_poly3d_dist_point_to_section()

subroutine the_environment::geo_poly3d_dist_point_to_section ( class(spatial), intent(in)  point,
class(spatial), intent(in)  sectp1,
class(spatial), intent(in)  sectp2,
real(srp), intent(out)  min_dist,
type(spatial), intent(out), optional  point_segment 
)

Calculates the minimum distance from a the_environment::spatial class object to a line segment delimited by two the_environment::spatial class endpoints in the 3D XY space. (The algorithm is partially based on this.)

Parameters
[in]pointpoint is the reference point to which the distance is calculated
[in]sectp1sectp1 is the first end of the line segment.
[in]sectp2sectp2 is the second end point of the line segment.
[out]min_distmin_dist is the output minimum distance between the reference point and the line segment delimited by sectp1 and sectp2.
[out]point_segmentpoint_segment is the optional output coordinates of the nearest point PN on the P1 P2 segment returned in the form of the_environment::spatial type object.

Implementation details

A scheme of the calculation is presented on this figure:

Calculation of the distance from a spatial object to a line segment

First, calculate the squared distance between the end points of the line segment P1 and P2 using the backend function the_environment::dist2_vector() that accepts vectors of arbitrary dimensionality: $ D^{2}(\mathbf{p1},\mathbf{p2}) $

  • if the distance between the end points is zero, the line segment actually has zero length and the distance between the spatial object P0 and the segment is trivial to determine: $ D_{min} = D(\mathbf{p_0},\mathbf{p_1}) = D(\mathbf{p_0},\mathbf{p_2}) $.

Second, determine the reference value $ r $ (a normalised distance from P1 to the closest point) that is calculated as follows:

\[ r = \frac{\left|\mathbf{p}_{0} - \mathbf{p}_{1}\right| \cdot \left|\mathbf{p}_{2} - \mathbf{p}_{1}\right|}{D^{2}(\mathbf{p_1},\mathbf{p_2})} , \]

where $ D^{2}(\mathbf{p_1},\mathbf{p_2}) $ is the distance between the end points P1 and P2, and the numerator is the dot product of the vectors $ \left|\mathbf{p}_{0} - \mathbf{p}_{1}\right| $ and $ \left|\mathbf{p}_{2} - \mathbf{p}_{1}\right| $.

  • The $ r < 0 $ indicates that the projection of the spatial object P0 onto the P1 P2 line is located in front of the P1 end, thus the minimum distance is calculated as

    \[ D_{min} = D(\mathbf{p_0},\mathbf{p_1}) . \]

  • If $ r > 1 $, the projection of the spatial object P0 on the line P1 P2 is behind the P2 end, so the minimum distance is

    \[ D_{min} = D(\mathbf{p_0},\mathbf{p_2}) . \]

  • In other cases, the spatial object P0 projects to a specific point on the P1 P2 line, that has these spatial coordinates:

It is then trivial to calculate the distance between the spatial object P0 and this projection point.

Definition at line 10872 of file m_env.f90.

Here is the call graph for this function:

◆ offset_dist()

type(spatial) function the_environment::offset_dist ( class(spatial), intent(in)  obj_a,
class(spatial), intent(in)  obj_b,
real(srp), intent(in)  offset 
)

Calculate a the_environment::spatial target with an offset.

This function calculate the coordinates of a point C in between two objects, a reference object A and a target object B, but at a smaller distance with specific offset $ \Delta $ from the target B.

Parameters
[in]obj_aobj_a reference spatial object (A)
[in]obj_btarget spatial object(B)
[in]obj_bobj_a reference spatial object (A)
[in]obj_btarget spatial object(B)
[in]offsetoffset distance offset for the target object
Returns
Returns the coordinates of the updated target object C that is located at a smaller distance from A, by the value of the offset parameter. If the distance between A and B is smaller that the offset value the returned error spatial object has commondata::missing coordinates. There is no error code variable with intent(out) to keep the function pure.

The coordinate $ x_c $ of the new target C are defined as:

\[ x_c = x_a + dist(A,B)-\Delta \cdot \frac {x_b-x_a} {dist(A,B)} , \]

where $ x_a, x_b $ are the x coordinates of the points A and B and $ dist(A,B) $ is the distance between A and B. The y and depth coordinates of the point C are defined in the same way.

Definition at line 10988 of file m_env.f90.

Variable Documentation

◆ modname

character (len=*), parameter, private the_environment::modname = "(THE_ENVIRONMENT)"
private

Definition at line 25 of file m_env.f90.

◆ dimensionality_default

integer, parameter, private the_environment::dimensionality_default = 3
private

Default dimensionality of the environment universe.

Definition at line 28 of file m_env.f90.

◆ dim_environ_corners

integer, parameter the_environment::dim_environ_corners = 4

The number of corners for an environment object in the 2D X*x*Y plane.

Warning
Valid only in the simplistic box-like implementation of environment objects and should be reimplemented if the environment is set as an arbitrary polyhedron.

Definition at line 34 of file m_env.f90.

◆ global_habitats_available

type(habitat), dimension(:), allocatable, public the_environment::global_habitats_available

A list (array) of all the the_environment::habitat objects available to the agents. This single array should encompass all the locations that the agent can potentially be in (e.g. migrate from one to another).

It is then very important that the separate habitat objects that are defined in the model are actually different data entities than the global array. If any change is made to the habitat objects after the global array was assembled, these must be synchronised with the array and vice versa.

To determine where the agent (or any other spatial object) is currently located within use the the_environment::spatial::find_environment() method. The simplest form of assembling the global array is

allocate(global_habitats_available(2))
global_habitats_available = [habitat_safe, habitat_dangerous]

A more powerful alternative is using the the_environment::assemble() procedure:

call assemble(habitat_safe, habitat_dangerous, reindex=.TRUE.)

See the_environment::assemble() and the_environment::disassemble() procedures for more information on creating the global array of habitat objects and disassembling individual habitat objects back (updating the internal data components and arrays for each of the individual habitats.

Here is an example of the steps necessary to use joined food resource from several assembled habitats:

! 1. Assemble the global array of habitat objects
! Global_Habitats_Available.
call assemble( habitat_test1, habitat_test2, &
habitat_test3, habitat_test4 )
! 2. Join returns a single food resource object out of those in the
! global array Global_Habitats_Available
joined_food_res2 = join( reindex=.true. )
! 3. Modify the joined single food resource object in some way.
! Here it just resets the sizes of the food items for a part
! of the data.
joined_food_res2%food( 1:size(habitat_test1%food%food) )%size = 100.0
! 4. Unjoin updates the food resources from the single global object
! back to the global array Global_Habitats_Available.
call unjoin( joined_food_res2, reindex=.TRUE. )
! 5. To complete unjoin, the updated food habitat and resource data
! should be transferred back to the original separate habitat objects
! usint `disassemble`
call disassemble( habitat_test1, habitat_test2, &
habitat_test3, habitat_test4 )
Note
Determining the environment object the agent is currently in can be done by the_environment::spatial::find_environment() method in this way:
            ...
                    environment_limits = Global_Habitats_Available(       &
                                           this_agent%find_environment(   &
                                             Global_Habitats_Available) )
            ...
Using a list of the_environment::habitat's rather than the_environment::environment's because the agent dwells in a habitat object and extended properties (e.g. habitat name) are easily available in such a case.
Warning
It is not possible to define this global variable in the commondata module because all environmental objects are defined in a higher level hierarchy module the_environment.
This array must be initialised immediately after creating the environmental objects / habitats: the_evolution::init_environment_objects().
This global array definition cannot be moved to the start of the module (for convenience), this results in the "object used before it is defined" compiler error.

Definition at line 680 of file m_env.f90.