Index
TrypColonies.Figure_observablesTrypColonies.agentTrypColonies.parametersTrypColonies.parameters_physicalTrypColonies.plot_parametersTrypColonies.adsorb!TrypColonies.ana_order_para_circleTrypColonies.ana_order_para_vicsekTrypColonies.angle_between_vecTrypColonies.angular_metricTrypColonies.area_gainTrypColonies.calc_repulsionTrypColonies.calculate_outgoing_vecTrypColonies.chemotactic_alignmentTrypColonies.chose_interaction_radiusTrypColonies.create_buttonsTrypColonies.create_data_path_vectorTrypColonies.create_exp_scalar_gridTrypColonies.create_gridsTrypColonies.create_noise_disTrypColonies.create_para_structTrypColonies.create_para_struct_vecTrypColonies.create_sweep_para_vecTrypColonies.create_veloctiy_disTrypColonies.cross_2dTrypColonies.find_data_pathTrypColonies.find_free_neighbour_pointsTrypColonies.find_neighbour_agentsTrypColonies.find_right_tangent_pointsTrypColonies.find_surounding_pointsTrypColonies.find_tangent_pointsTrypColonies.foldersizeTrypColonies.get_reflected_vecTrypColonies.indexTrypColonies.initialize_systemTrypColonies.length_vecTrypColonies.make_para_dict_listTrypColonies.make_sys_interactive!TrypColonies.moving_avgTrypColonies.nearby_neighboursTrypColonies.path_tracingTrypColonies.periodic_boundary_correctionTrypColonies.radial_density_cTrypColonies.radial_distributionTrypColonies.reconstruct_grid!TrypColonies.reconstruct_grid_from_scratchTrypColonies.remove_fields_dict!TrypColonies.res_scalingTrypColonies.save_grid_changes!TrypColonies.scale_color_mapTrypColonies.scale_time_stepTrypColonies.strenghten_boundary!TrypColonies.sweep_and_save_parallel_tTrypColonies.update_grid!TrypColonies.update_position!TrypColonies.@h
Functions
TrypColonies.Figure_observables — Type
mutable struct Figure_observablesA structure to hold various observables for visualizing simulation data.
Fields
Time::Observable{Int64}: An observable for the current time step.V_a::Observable{CircularBuffer{Point2f}}: An observable for a circular buffer of 2D points represent a correlation function.V_a_length::Observable{Int64}: An observable for the length ofV_a.X::Observable{Vector{Float64}}: An observable for the x-coordinates of agents.Y::Observable{Vector{Float64}}: An observable for the y-coordinates of agents.U::Observable{Vector{Float64}}: An observable for the x-components of agent velocities.V::Observable{Vector{Float64}}: An observable for the y-components of agent velocities.N::Observable{Int64}: An observable for the number of agents.Grid_contour::Observable{Matrix{Int64}}: An observable for the grid which the agents move on.Theta::Observable{Vector{Float64}}: An observable for the angles of agents.Isrunning::Observable{Bool}: An observable to indicate if the simulation is running.Color_scaled: An observable for the scaled color values to make non-dynamic or dynamic colorscaling possible.
TrypColonies.agent — Type
agentA struct representing an agent in a grid. It holds the agent's current position in the grid as well as its direction of movement.
Fields
x_pos::Int64: The x-coordinate of the agent's position in the grid.y_pos::Int64: The y-coordinate of the agent's position in the grid.dir_x::Float64: The x-component of the agent's direction vector.dir_y::Float64: The y-component of the agent's direction vector.
TrypColonies.parameters — Type
parametersDefines the parameters for the simulation with default values and possible options for certain fields.
Fields
pa_ph::parameters_physical: A struct containing physical parameters for the simulation.interaction_radius::Int64: The radius within which agents interact. Default is 7.boundary_conditions::String: The type of boundary conditions. Default is "periodic".geometry::String: The geometry of the simulation area. Default is "circle".start_config::String: The initial configuration of agents. Default is "random".start_config_gradient::String: The initial configuration of the gradient. Default is "random".boundary_moveable::Bool: Whether the boundary is moveable. Default is true.path_tracing::Bool: Whether to trace the path of agents. Default is true.sliding_movement::Bool: Whether the boundary allows sliding. Default is false.repulsion_flag::Bool: Whether repulsion is enabled. Default is false.repulsion_range::Int64: The range of repulsion. Default is 3.chemotaxis_flag::Bool: Whether chemotaxis is enabled. Default is true.size::Tuple{Int, Int}: The dimensions of the simulation grid. Default ispa_ph.N_abm.xc_w::LinRange{Float64, Int64}: A linear range of x coordinates for the grid.yc_w::LinRange{Float64, Int64}: A linear range of y coordinates for the grid.arrow_to_grid_fac_x::Float64: The scaling factor for x coordinates from arrows to grid.arrow_to_grid_fac_y::Float64: The scaling factor for y coordinates from arrows to grid.velocity::Float64: The initial velocity of agents. Default ispa_ph.walker_step_size.timesteps::Int64: The number of timesteps the simulation runs. Default is calculated frompa_ph.total_timeandpa_ph.Δt_walker.velocity_variance::Float64: The variance in agent velocities. Default ispa_ph.walker_step_size * pa_ph.velo_var_relative.growth_rate::Float64: The growth rate. Default ispa_ph.growth_rate.
Usage Notes
- Use
reflectiveboundary conditions only when agents cannot leave the grid space; otherwise, the simulation may crash silently. - The
geometryfield allows for simulating different environmental layouts, which can significantly affect agent behavior and interactions. - The
start_configfield determines the initial placement of agents, which can influence the dynamics of the simulation from the outset.
This struct is used to configure and initialize the simulation environment, affecting how agents move, interact, and evolve over time.
TrypColonies.parameters_physical — Type
parameters_physicalA struct representing the physical parameters for a simulation involving walkers and diffusion processes. This struct is initialized with default values and includes various fields related to the simulation's spatial and temporal properties.
Fields
N::Tuple{Int, Int}: The number of grid points in the x and y directions in the gradient grid. Default is(1000, 1000).scale_fac::UInt: The scaling factor between the gradient grid where the diffusion is calculated and the one of the ABM. Default is4.L::Tuple{Float64, Float64}: The physical dimensions of the simulation domain in the x and y directions. Default is(0.015, 0.015).agent_number::Int64: The number of agents in the simulation. Default is250000.walker_speed_phy::Float64: The physical speed of the walkers in m/s. Default is5*10^-6.Diff_coe::Float64: The diffusion coefficient in m^2/s. Default is7*10^-10.total_time::Float64: The total simulation time in s. Default is200.0.growth_rate::Float64: The growth rate in 1/s. Default is1.157*10^-5.walker_step_size::Int: The step size for the walkers on the ABM grid. Default is3.decay_rate::Float64: The decay rate in 1/s. Default is0.001.adsorption_rate::Float64: The adsorption rate/amount in 1/s . Default is0.001.Diameter_colony::Float64: The diameter of the colony in m. Default is0.003.noise_dis::Any: The distribution for noise. Default isNormal.noise_strength::Number: The stdd of the noise distribution. Default is0.5.velocity_dis::Any: The distribution for velocity. Default isNormal.velo_var_relative::Float64: The relative variance in velocity. Default is1.5.grid_strength::Int64: The strength of the grid. Default is100.grid_recover_rate::Float64: The recovery rate of the grid. Default is10.0.radius_tanget::Int64: The radius to calculate the tangent which is needed to calculate the reflection on walls. Default is6.radius_collision::Int64: The radius for collision interactions. Default is5.N_abm::Tuple{Int, Int}: The number of grid points in the ABM grid, calculated asN .* scale_fac.dx::Float64: The grid spacing in the x direction, calculated asL[1]/N[1].dy::Float64: The grid spacing in the y direction, calculated asL[2]/N[2].xc::LinRange{Float64, Int64}: A linear range of x coordinates from0.0toL[1]withN[1]points.yc::LinRange{Float64, Int64}: A linear range of y coordinates from0.0toL[2]withN[2]points.Δt_diff_min::Float64: The minimum time step for diffusion, calculated as(minimum((L./(N)))^2*2)/(8*Diff_coe+minimum((L./(N)))^2*decay_rate)(see Von Neumann stability analysis).Δt_walker_min::Float64: The minimum time step for walkers, calculated as(minimum((L./(N_abm)))*walker_step_size)/walker_speed_phy.Δt_diff::Float64: The time step for diffusion, calculated usingscale_time_step.Δt_walker::Float64: The time step for walkers, calculated usingscale_time_step.ratio_walker_diff::Int: The ratio of walker time steps to diffusion time steps, calculated usingscale_time_step.time_steps_to_compute::Int: The total number of time steps to compute, calculated asround(Int, total_time/Δt_diff).
TrypColonies.plot_parameters — Type
plot_parametersA structure defining parameters for plotting with default values.
Fields
framerate: The number of frames per second in the animation. Default is 60.theme: The plotting theme, usingAttributes. Default istheme_ggplot2().fontsize: The font size for text elements. Default is 22.arrow_tip_size: The size of the arrow tips. Default is 12.arrow_tail_length: The length of the arrow tails. Default is 5.refresh_delay: The delay between refreshes in seconds. Default is 0.05.res: The resolution of the plot as a tuple (width, height). Default is (1400, 2000).Color_arrows: The color scheme for arrows. Default is the full range ofColorSchemes.hsv.Color_heatmap: The color scheme for heatmaps. Default is indices 50 to 100 ofColorSchemes.bone.timesteps_corfunc: The number of timesteps for the correlation function. Default is 100.cor_func: The correlation function for circles. Default isorder_parameter_circle.
Usage
This struct is used to configure the visual aspects and functionalities of plots, including animations, color schemes, and correlation calculations.
TrypColonies.adsorb! — Function
adsorb!(grids::Tuple{Matrix{Int64}, Matrix{Float64}}, full_agent_list, para::parameters, time_step::Int64 = 1)Updates the gradient grid based on the positions of agents and their adsorption rates.
Arguments
grids::Tuple{Matrix{Int64}, Matrix{Float64}}: A tuple containing two matrices. The second matrix represents the concentration of a chemical.full_agent_list: A list of agents, which can be either a CircularBuffer of vectors of agents or a vector of vectors of agents.para::parameters: A struct containing various parameters, including adsorption rate and time step for the agents.time_step::Int64: The current time step (default is 1).
Description
This function updates the gradient grid by increasing the concentration at the positions of the agents. The amount of increase is determined by the adsorption rate and the time step specified in the para parameter.
TrypColonies.ana_order_para_circle — Method
ana_order_para_circle(data, para::parameters; time_steady::Float64=0.7) -> Float64Calculates the average order parameter over a specified steady-state period.
Arguments
data::save_model_data: An tuple contain an array as first element where each array element represents data points over time.para::parameters: A structure containing parameters required for theorder_parameter_circlefunction.time_steady::Float64: A fraction of the total time steps to consider as the steady-state period (default is 0.7).
Returns
Float64: The average order parameter over the steady-state period.
Example
data = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
para = parameters(...)
result = ana_order_para_circle(data, para)
# result is the average order parameter over the steady-state periodTrypColonies.ana_order_para_vicsek — Method
ana_order_para_vicsek(data, para::parameters; time_steady=0.7) -> Float64Calculates the average order parameter for the Vicsek model over the steady-state period of the simulation.
Arguments
data: A collection of data points, wheredata[1]contains the time series data for which the order parameter is to be calculated.para::parameters: A struct containing the parameters required by theorder_parameterfunction.time_steady::Float64=0.7(optional): The fraction of the total time steps to be considered as the steady-state period. Default is 0.7.
Returns
Float64: The average order parameter over the steady-state period.
Example Usage
data = [...] # Assume this is the data collected from the simulation
para = parameters(...) # Assume this is the parameters struct
average_order = ana_order_para_vicsek(data, para, time_steady=0.8)TrypColonies.angle_between_vec — Method
angle_between_vec(v1::Vector{<:Real}, v2::Vector{<:Real}) -> RealCalculates the signed angle between two 2D vectors v1 and v2 using the arctangent of the 2D cross product and the dot product.
Arguments
v1::Vector{Real}: The first 2D vector.v2::Vector{Real}: The second 2D vector.
Returns
Real: The angle between the two vectors in radians.
Example
v1 = [1.0, 0.0]
v2 = [0.0, 1.0]
angle = angle_between_vec(v1, v2)
# angle is π/2 (1.5707963267948966 radians)TrypColonies.angular_metric — Method
angular_metric(agent_list::Vector{agent}, grid::AbstractArray, para::parameters; steps::Int = 360)Calculates the angular distribution of non-zero pixels in the grid relative to the center.
Arguments
agent_list::Vector{agent}: A vector containing the agents.grid::AbstractArray: The grid representing the simulation space.para::parameters: A struct containing various parameters, including the size of the grid.steps::Int: The number of angular steps to divide the circle into (default is 360).
Description
This function calculates the angular distribution of non-zero pixels in the grid relative to the center. It performs the following steps:
- Initializes a vector for the angular metric.
- Calculates the center of the grid.
- Determines the size of each angular step in radians.
- Iterates over each pixel in the grid and calculates the vector from the center to the pixel.
- Calculates the angle of the vector and determines the corresponding sector.
- Increments the count for the sector.
- Adjusts the first and last sectors to account for discretization artifacts by taking their mean.
- Returns the angular metric.
TrypColonies.area_gain — Method
area_gain(agent_list::Vector{agent}, grids::Tuple{AbstractArray,AbstractArray}, para::parameters)Calculate the realtive gain in area walkable by agents in the grid.
Arguments
agent_list::Vector{agent}: A list of agents.grids::Tuple{AbstractArray, AbstractArray}: A tuple containing the grids.para::parameters: The parameters for the simulation.
Returns
area_gain::Float64: The ratio of the current area covered by agents to the original area.
Description
This function calculates the realtive gain in area covered by agents in the grid. It compares the current area walkable by agents to the original area walkable by agents at the start of the simulation. The original area is calculated using a newly created grid with the same parameters, and the current area is calculated using the provided grid.
Example
agent_list = [...] # List of agents
grids = (grid1, grid2) # Tuple of grids
para = parameters(...) # Simulation parameters
gain = area_gain(agent_list, grids, para)TrypColonies.calc_repulsion — Method
calc_repulsion(all_list, index_rep, old_agent) -> Vector{Float64}Calculates the hard repulsion vector for an agent based on the positions of other agents in its vicinity. The function normalizes the repulsion vectors and sums them to determine the overall direction of repulsion.
Arguments
all_list: A list containing various attributes of all agents created by the functionfind_neighbour_agents. The x and y positions of the agents are expected to be at indices 4 and 5, respectively.index_rep: A list of indices representing the agents that are considered for repulsion.old_agent: An agent struct containing the current direction of the agent (dir_xanddir_y).
Returns
Vector{Float64}: A normalized vector representing the direction of repulsion. If no repulsion is detected, it returns the normalized direction of theold_agent.
Example Usage
all_list = [...] # Assume this is a list containing agent attributes
index_rep = [1, 2, 3] # Indices of agents to consider for repulsion
old_agent = Agent(1, 2, 0.5, 0.5) # Assume this is an agent struct with direction fields
repulsion_vector = calc_repulsion(all_list, index_rep, old_agent)TrypColonies.calculate_outgoing_vec — Method
Calculates outgoing path of incoming particle, using raytracing formular and generic conventions: #
TrypColonies.chemotactic_alignment — Method
chemotactic_alignment(grad_x, grad_y, Y_pos, X_pos, X_dir, Y_dir, biggest_grad, para::parameters)Aligns the direction of an agent based on the chemotactic gradient.
Arguments
grad_x: The gradient of the chemical concentration in the x direction.grad_y: The gradient of the chemical concentration in the y direction.Y_pos: The y position of the agent.X_pos: The x position of the agent.X_dir: The x component of the agent's direction.Y_dir: The y component of the agent's direction.biggest_grad: The largest gradient value for normalization.para::parameters: A struct containing various parameters, including the scale factor.
Description
This function aligns the direction of an agent based on the chemotactic gradient. It performs the following steps:
- Scales the agent's position based on the scale factor.
- Ensures the scaled positions are not zero.
- Calculates the gradient direction at the agent's position.
- Computes the amplitude of the gradient and the angle between the agent's direction and the gradient direction.
- Scales the angle by the amplitude of the gradient.
- Constructs a rotation matrix based on the scaled angle.
- Rotates the agent's direction using the rotation matrix.
- Returns the new direction of the agent.
Example
grad_x = rand(10, 10)
grad_y = rand(10, 10)
Y_pos = 5
X_pos = 5
X_dir = 1.0
Y_dir = 0.0
biggest_grad = 1.0
para = parameters(pa_ph = pa_ph(scale_fac = 1.0))
chemotactic_alignment(grad_x, grad_y, Y_pos, X_pos, X_dir, Y_dir, biggest_grad, para)TrypColonies.chose_interaction_radius — Method
chose_interaction_radius(parameters::parameters) -> Float64Determines the interaction radius to be used based on the given parameters. If the repulsion_flag is set, it compares the repulsion_range with the interaction_radius and returns the larger of the two. If the repulsion_flag is not set, it simply returns the interaction_radius.
Arguments
parameters::parameters: A struct containing the simulation parameters, including:repulsion_flag::Bool: A flag indicating whether repulsion is considered.repulsion_range::Int: The range of repulsion.interaction_radius::Int: The default interaction radius.
Returns
Int64: The chosen interaction radius based on the given parameters.
```
TrypColonies.create_buttons — Method
create_buttons(f::Figure, fig_obs::Figure_observables, Parameters::parameters) -> (Button, Observable{parameters})Creates interactive UI elements, including a start/stop button and a grid of sliders, to control simulation parameters in a graphical figure.
Arguments
f::Figure: The main figure where the UI elements will be added.fig_obs::Figure_observables: An observable object that includes the running state of the simulation.Parameters::parameters: A struct containing the initial parameters for the simulation.
Returns
(Button, Observable{parameters}): A tuple containing the start/stop button and an observable parameter struct that updates based on the slider values.
Example Usage
f = Figure()
fig_obs = Figure_observables(Isrunning = Observable(false))
Parameters = parameters(...) # Assume this is the parameters struct with initial values
pause_button, para_obs = create_buttons(f, fig_obs, Parameters)TrypColonies.create_data_path_vector — Method
create_data_path_vector(data_path) -> Vector{String}Creates a vector of full data paths by reading the contents of the specified directory or directories, excluding certain files.
Arguments
data_path: A string representing a single directory path or a vector of directory paths.
Returns
Vector{String}: A vector of full paths to the data files in the specified directory or directories, excluding "settings.csv", "settings.jls", and "analysis".
Example Usage
data_path = "C:\data"
full_data_paths = create_data_path_vector(data_path)
data_paths = ["C:\data1", "C:\data2"]
full_data_paths = create_data_path_vector(data_paths)TrypColonies.create_exp_scalar_grid — Method
create_exp_scalar_grid(para::parameters) -> Matrix{Float64}Creates a scalar grid based on a Gaussian distribution centered in the middle of the grid. The gradient values are calculated using the specified parameters.
Arguments
para::parameters: A struct containing the parameters for the grid, including:size::Tuple{Int, Int}: The dimensions of the grid.
Returns
Matrix{Float64}: A 2D array representing the gradient grid, with values following a Gaussian distribution.
Example Usage
parameters = parameters(size=(100, 100))
grad_grid = create_exp_scalar_grid(parameters)This function is useful for creating a scalar field that can be used in simulations where agents respond to spatial gradients, such as chemotaxis or other gradient-based behaviors.
TrypColonies.create_grids — Method
create_grid(para::parameters) -> Matrix{Int64}Create a grid based on the specified parameters. The function initializes a grid of zeros and modifies it according to the geometry specified in Parameters. The grid can be shaped into a square, channel, circle, or a smaller circle, with negative values (defined by Parameters.grid_strength) in the entire grid except for the specified geometry shape.
Arguments
- `para::parameters`: A struct containing the grid parameters. It must have the following fields:
- `size::Tuple{Int64, Int64}`: The dimensions of the grid.
- `geometry::String`: The shape of the grid, which can be "square", "channel", "circle", or "circle_small".
- `grid_strength::Int64`: The negative value to be applied to the grid's border or outside the specified shape.Returns
Matrix{Int64}: The generated grid with the specified geometry and dimensions.
Examples
params = parameters(size=(100, 100), geometry="square", grid_strength=5)
grid = create_grid(params)This function supports creating grids with different geometries to simulate various environments or constraints.
TrypColonies.create_noise_dis — Method
`create_noise_dis(parameters::parameters)`Create a noise distribution object based on the simulation parameters.
Arguments
parameters::parameters: A struct containing the simulation parameters. This must include:noise_dis: The type of distribution to use for noise. Expected to be eitherUniformorNormal.noise_strength: A parameter (η) that defines the strength of the noise. For aUniformdistribution, it defines the range[-η, η]. For aNormaldistribution, it defines the standard deviation σ with a mean of 0.
Returns
- A distribution object corresponding to the specified noise distribution and strength. If
noise_strengthis 0,
it returns a Normal distribution with mean 0 and standard deviation 0.
Example
parameters = parameters(noise_dis=Uniform, noise_strength=0.5)
noise_distribution = create_noise_dis(parameters)
This will create a Uniform(-0.5, 0.5) distribution for noise.Notes
The function supports creating Uniform and Normal distributions based on the noise_dis parameter in parameters. If noise_strength (η) is set to 0, the function defaults to creating a Normal(0.0, 0.0) distribution, effectively adding no noise.
TrypColonies.create_para_struct — Method
create_para_struct(settings::Dict) -> parameters::parametersConstructs a parameters struct from a dictionary of settings, dynamically generating the struct fields and their values based on the input dictionary. This function uses metaprogramming to parse and evaluate a string representation of the struct initialization.
Arguments
settings::Dict: A dictionary where keys are the names of the parameters (as symbols or strings) and values are the
corresponding values for these parameters. The values can be of any type, including String.
Returns
- A new instance of the
parametersstruct with fields and values corresponding to the entries in thesettingsdictionary.
If some keys are missing in the dictionary, the default values from the parameters struct definiton will be used.
Examples
settings = Dict(:radius_collision => 2, :size => (10,))
para_struct = create_para_struct(settings)This will create an instance of the parameters struct with radius_collision set to 2, size set to (10,10).
TrypColonies.create_para_struct_vec — Method
create_para_struct_vec(data_used) -> Vector{Vector{parameters}}Creates a vector of parameter structures from the given data. The function handles both 1-dimensional and 2-dimensional data inputs.
Arguments
data_used: The input data from which parameter structures are to be created. It can be a 1-dimensional or 2-dimensional array.
Returns
Vector{Vector{parameters}}: A vector of vectors, where each inner vector contains parameter structures created from the input data.
Example Usage
data_used = DataFrame(...) # Assume this is a DataFrame with the necessary data
para_vec = create_para_struct_vec(data_used)TrypColonies.create_sweep_para_vec — Method
create_sweep_para_vec(data_used::DataFrame) -> Array{Array{Float64}}Generates a vector of sweep parameter vectors based on the input data.
Arguments
data_used::DataFrame: An DataFrame where each row contains the sweep parameter information, including the sweep parameter name, start value, increment, and number of steps.
Returns
Array{Array{Float64}}: A vector of vectors, where each inner vector contains the sweep parameter values for a specific row in the input data.
Example
data_used = Dataframe(
(sweep_parameter="param1", param1=0.0, parameter_increment=0.1, parameter_steps=5,...),
(sweep_parameter="param2", param2=1.0, parameter_increment=0.2, parameter_steps=3,...)
)
sweep_para_vec = create_sweep_para_vec(data_used)
# sweep_para_vec is now [[0.0, 0.1, 0.2, 0.3, 0.4], [1.0, 1.2, 1.4]]TrypColonies.create_veloctiy_dis — Method
create_velocity_dis(parameters::parameters) -> DistributionCreates a velocity distribution for agents based on the simulation parameters.
Arguments
parameters::parameters: A struct containing the simulation parameters, which must include:velocity_dis: The type of distribution to use (UniformorNormal).velocity_variance: The variance of the velocity distribution.velocity: The mean velocity of the agents.
Returns
Distribution: A truncated distribution object representing the velocity distribution of agents. The distribution is truncated at the lower bound of 0 to ensure that velocity values are non-negative.
Behavior
- If both
velocityandvelocity_varianceare 0, aNormaldistribution with mean 0 and variance 0 is returned. - If
velocity_disisUniform, a truncatedUniformdistribution ranging from(velocity - variance)to(velocity + variance)is created. - If
velocity_disisNormal, a truncatedNormaldistribution with the specified mean (velocity) and variance (velocity_variance) is created. - The truncation ensures that the resulting velocity values are always non-negative, as negative velocities are not physically meaningful in this context.
Example
parameters = parameters(velocity_dis=Normal, velocity_variance=1.0, velocity=5.0)
velocity_distribution = create_velocity_dis(parameters)TrypColonies.cross_2d — Method
cross_2d(v1::Vector{<:Real}, v2::Vector{<:Real}) -> RealCalculates the 2D cross product (also known as the perp product) of two 2D vectors.
Arguments
v1::Vector{Real}: The first 2D vector.v2::Vector{Real}: The second 2D vector.
Returns
Real: The scalar result of the 2D cross product.
Example
v1 = [1.0, 2.0]
v2 = [3.0, 4.0]
result = cross_2d(v1, v2)
# result is -2.0TrypColonies.find_data_path — Method
find_data_path(data_paths; local=false) -> StringFinds and returns the path to the data directory. If local is set to true, it checks for a directory named "data" in the current working directory and returns the path specified by data_paths["local_data"] if found. If local is false or the local "data" directory is not found, it iterates through the data_paths dictionary and returns the first path that corresponds to an existing directory.
Arguments
data_paths::Dict{String,String}: A dictionary where keys are descriptive names of the paths and values are the actual paths to data directories.local::Bool=false(optional): A flag to indicate whether to look for a local "data" directory first.
Returns
String: The path to the data directory that was found.
Throws
ArgumentError: Iflocalistruebut no local "data" directory is found.
Examples
data_paths = Dict("local_data" => "./data", "remote_data" => "/mnt/data")
path = find_data_path(data_paths, local=true)This function is useful for applications that need to flexibly switch between local and remote data sources.
TrypColonies.find_free_neighbour_points — Method
find_free_neighbour_points(grid::Matrix{Int64}, tryp::agent, Parameters::parameters) -> Tuple{Bool, Int64, Int64}Finds a free neighboring point around a given agent's position in a grid, considering specified boundary conditions.
Arguments
grid::Matrix{Int64}: A 2D grid representing the environment, where 0 indicates a free space and other values indicate occupied spaces.tryp::agent: An agent object with fieldsx_posandy_posindicating its current position in the grid.Parameters::parameters: A parameters object containing simulation parameters, includingboundary_conditionswhich can be "periodic" andsizeindicating the size of the grid.
Returns
sucess::Bool: A boolean indicating whether a free neighboring point was found.X_pos_new::Int64: The x-coordinate of the found free neighboring point. Returns the agent's original x-coordinate if no free point is found.Y_pos_new::Int64: The y-coordinate of the found free neighboring point. Returns the agent's original y-coordinate if no free point is found.
Description
This function attempts to find a free (unoccupied) neighboring point around the agent's current position. It randomly shuffles the directions to check for free spaces to ensure unbiased movement direction. If the boundary_conditions are set to "periodic", it will apply periodic boundary corrections to wrap around the grid edges. The function returns whether a free space was found and the coordinates of that space.
TrypColonies.find_neighbour_agents — Method
find_neighbour_agents(parameters, agent_list, i, interaction_radius, grid) -> Vector{Vector{Float64}}Finds the neighboring agents within a specified interaction radius for a given agent and returns their directional vectors, distances, and relative positions.
Arguments
parameters: A struct containing the simulation parameters, including boundary conditions and grid size.agent_list: A list of agents, where each agent has attributes such asx_pos,y_pos,dir_x, anddir_y.i: The index of the agent for which neighbors are being found.interaction_radius: The radius within which to search for neighboring agents.grid: A 2D array representing the grid, where each cell contains the index of an agent or 0 if the cell is empty.
Returns
Vector{Vector{Float64}}: A vector containing five vectors:dir_x_list: The x-components of the direction vectors of the neighboring agents.dir_y_list: The y-components of the direction vectors of the neighboring agents.dist_list: The distances from the given agent to each neighboring agent.pos_x_list: The x-coordinates of the neighboring agents relative to the given agent.pos_y_list: The y-coordinates of the neighboring agents relative to the given agent.
Example Usage
parameters = Parameters(boundary_conditions="periodic", size=(100, 100))
agent_list = [Agent(10, 10, 1.0, 0.0), Agent(12, 12, -1.0, 0.0)] # Example agents
grid = zeros(Int64, 100, 100)
grid[10, 10] = 1
grid[12, 12] = 2
neighbors = find_neighbour_agents(parameters, agent_list, 1, 5, grid)
endThis function is useful for simulations where agents interact with their neighbors within a certain radius, such as in flocking or swarming behaviors. It calculates the direction vectors, distances, and relative positions of neighboring agents, which can be used to update the agent's direction based on the interactions.
TrypColonies.find_right_tangent_points — Method
Finds and returns the two most distant tangent points from a given array of tangent points.
This function is designed to process an array of tangent points, each represented as a Vector{Int64} containing two elements (coordinates). It calculates the pairwise distances between all points in the array using a helper function length_vec to determine the length of the vector formed by two points. The function then identifies and returns the pair of points that are the most distant from each other, which are considered the "right" tangent points for further processing.
Arguments
tangent_points::Vector{Vector{Int64}}: An array of points, each point is a vector of two integers representing its coordinates.
Returns
Vector{Vector{Int64}}: An array containing the two most distant tangent points from the input array.
Example
tangent_points = [[1, 2], [3, 4], [5, 6]]
right_tangent_points = find_right_tangent_points(tangent_points)
# right_tangent_points will contain the two points that are furthest apartTrypColonies.find_surounding_points — Method
Returns all grid points surrounding the collision point in a radius of r The discretization going from the continuous circle to the discrete points on the grid is done with the stepwidth: steps
TrypColonies.find_tangent_points — Method
Reurn the gridpoints from the list of gridpoints in circle, which are the first ones of the boundary by checking when there is a change in the value list of points from -1 to 0 or vice versa. The last gridpoint that has the value -1 will be used as the probable point on the boundary between occupied and free space.
TrypColonies.foldersize — Function
foldersize
Calculates the size of a directory in megabytes. If recursive is set to true, it computes the total size by recursively summing the sizes of all files within the directory and its subdirectories. If recursive is false, it returns the size of the directory itself, which may not be meaningful as directories typically have a small, fixed size.
Parameters:
dirpath::String = pwd(): The path to the directory whose size is to be calculated.Defaults to the current working directory.recursive::Bool = true: A flag indicating whether the size calculation should be recursive. Defaults totrue.
Returns:
Float64: The size of the directory in megabytes.
Example Usage:
size = foldersize("/path/to/directory", recursive=true)This function is useful for monitoring disk usage by directories, especially in applications where managing data storage is critical.
TrypColonies.get_reflected_vec — Method
Return the normalized reflected vector from the tangent to the next boundary of a given grid point. Function includes a fallback option, if no unambiguous tangent is defined by two points, the original orientation is just reversed.
TrypColonies.index — Method
index(; iteration::Int=1, parameter_step::Int=1, parameter=data_used) -> IntMap a (parameter_step, iteration) pair from a sweep configuration to a single linear 1-based index.
The mapping assumes sweep results are stored in blocks by parameter_step, with all iterations for one step placed contiguously.
Keyword Arguments
iteration::Int: Iteration number within a parameter step (1-based).parameter_step::Int: Parameter step in the sweep (1-based).parameter: Object that providesparameter_stepsanditerations; the first element of each is used as the corresponding upper bound.
Returns
Int: Linear index for the selected run.
Throws
ArgumentError: Ifiterationorparameter_stepis outside valid bounds.
Example
idx = index(iteration=3, parameter_step=2, parameter=data_used)TrypColonies.initialize_system — Method
initialize_system!(grids::Tuple{Matrix{Int64}, Matrix{Float64}}, Parameters::parameters)Initializes the simulation system by setting up the initial configuration of agents and grid states.
Arguments
grids::Tuple{Matrix{Int64}, Matrix{Float64}}: A tuple containing two matrices. The first matrix represents the grid to be initialized.Parameters::parameters: A struct containing various parameters, including the number of timesteps and other simulation parameters.
Description
This function initializes the system by setting up the initial configuration of agents and grid states. It performs the following steps:
- Initializes an empty list of agents.
- Creates a list to store the state of agents for each timestep.
- Calls
random_start_config!to set up the initial configuration of the grid and agents. - Copies the initial agent list to all timesteps.
- Initializes a sparse matrix vector to save grid changes.
- Saves the initial grid state to the sparse matrix vector.
Example
grids = (Matrix{Int64}(undef, 10, 10), Matrix{Float64}(undef, 10, 10))
Parameters = parameters(pa_ph = pa_ph(time_steps_to_compute = 100), timesteps = 100)
initialize_system(grids, Parameters)Returns
grids: The initialized grids. agentlistfull: A list of agent states for each timestep. gridvecsparse: A vector of sparse matrices to save grid changes.
TrypColonies.length_vec — Method
length_vec
Calculates and returns the Euclidean length (magnitude) of a 2-dimensional vector represented by a Vector{Int64}.
Parameters:
vec::Vector{Int64}: A vector with two elements wherevec[1]is the x-component andvec[2]is the y-component of the vector.
Returns:
Float64: The Euclidean length of the vector.
Example Usage:
vector = [3, 4]
length = length_vec(vector) # Returns 5.0TrypColonies.make_para_dict_list — Method
make_para_dict_list(sweep_dict_original::Dict)Generate a list of parameter dictionaries for simulation runs based on the original sweep parameters dictionary.
Arguments
sweep_dict_original::Dict: A dictionary containing the original sweep parameters.
It must include keys for sweep_parameter, parameter_steps, iterations, and parameter_increment. The sweep_parameter key should match one of the keys in the dictionary that will be varied across simulations.
Returns
Array{Dict}: An array of dictionaries, each representing a set of parameters for a single simulation run.
The specified sweep parameter is incremented across these dictionaries according to the parameter_steps and parameter_increment specified in the original dictionary.
Throws
- An error if the
sweep_parameterspecified insweep_dict_originaldoes not exist in the dictionary keys.
Example
sweep_dict_original = Dict(
"sweep_parameter" => "agent_number",
"parameter_steps" => 5,
"iterations" => 10,
"parameter_increment" => 2,
"other_param" => 1
)
para_dict_list = make_para_dict_list(sweep_dict_original)This function is useful for creating parameter sweeps for simulations, where one wants to vary a single parameter across a range of values while keeping other parameters constant.
TrypColonies.make_sys_interactive! — Method
make_sys_interactive!
Transforms a grid system into an interactive one by initializing a circular buffer to store agent states, allowing for dynamic updates.
Parameters:
grids: The grids on which agents operate. This function does not modify the grid but returns it for consistency in the interface.agent_list_full: A list (vector) of agents. These agents are the initial state of the system.buffer_length::Int=5(optional): The length of the circular buffer. This determines how many past states of the agent list can be stored. Default is 5.
Returns:
grids: The same grid passed as input, returned unchanged.agent_list_cicular: A circular buffer filled with deep copies of the first agent inagent_list_full.
This buffer allows for storing and accessing past states of the system.
TrypColonies.moving_avg — Function
moving_avg(X::Vector, numofele::Int=length(X)÷2)Calculates the moving average of a vector.
Arguments
X::Vector: The input vector for which the moving average is to be calculated.numofele::Int: The number of elements to consider for the moving average (default is half the length ofX).
Description
This function calculates the moving average of the input vector X. It performs the following steps:
- Determines the number of elements to look behind and ahead for the moving average.
- Initializes an output vector
Yof the same length asX. - Iterates over each element in
Xand calculates the moving average for a range of elements around it. - Stores the calculated moving average in the output vector
Y.
Example
X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numofele = 3
moving_avg(X, numofele)Returns
Y::Vector: The vector containing the moving average values.
TrypColonies.nearby_neighbours — Method
nearby_neighbours(Agent_list::Vector{agent}, Grid::AbstractArray, Parameters::parameters)Legacy function to calculate the number of nearby neighbours for each agent within a specified interaction range as an heatmap to then calculate the average nearby topology of an agent.
Arguments
Agent_list::Vector{agent}: A vector containing the agents.Grid::AbstractArray: The grid representing the simulation space.Parameters::parameters: A struct containing various parameters, including the interaction radius.
Description
This function calculates the number of nearby neighbours for each agent within a specified interaction range. It performs the following steps:
- Initializes a sum grid to accumulate the number of neighbours.
- Iterates over each agent and extracts a sub-grid around the agent's position within the interaction range.
- Replaces positive values in the sub-grid with 1 and negative values with 0.
- Sets the agent's own position in the sub-grid to 0.
- Adds the sub-grid to the sum grid.
- Returns the rotated sum grid.
Example
```julia Agentlist = [agent(xpos=5, ypos=5), agent(xpos=10, ypos=10)] Grid = rand(-1:1, 20, 20) Parameters = parameters(interactionradius=2)
nearbyneighbours(Agentlist, Grid, Parameters) Returns sum_grid: A grid representing the number of nearby neighbours for each agent.
TrypColonies.path_tracing — Method
- Function Name:
path_tracing - Description: This function simulates the movement of an agent (
tryp) through a grid, step by step, to determine the point at which it first encounters a wall. It returns the X and Y positions on the grid where the first wall is encountered, along with the distance already walked. - Parameters:
grid::Matrix{Int64}: The grid through which the agent moves, represented as a matrix of integers.tryp::agent: The agent attempting to move through the grid. It contains properties like direction (dir_x,dir_y) and position (x_pos,y_pos).velocity: The speed at which the agent attempts to move through the grid.parameters::parameters: Additional parameters affecting the simulation, such as boundary conditions.
- Returns: The function returns a tuple containing the X and Y indices of the first wall grid point encountered and the remaining distance the agent can walk.
- Algorithm:
- Initialize the agent's direction and position.
- Iterate through the steps based on the agent's velocity.
- Update the agent's position at each step, rounding to the nearest grid point.
- If periodic boundary conditions are specified, adjust the position accordingly.
- Check if the current grid point is a wall (
grid[Y_step_i, X_step_i] < 0). If so, move the agent back to the previous position and adjust for periodic boundary conditions if necessary. - Return the final position and the distance walked before encountering the wall.
TrypColonies.periodic_boundary_correction — Method
periodic_boundary_correction(x_pos::Int64, y_pos::Int64, size::Tuple{Int64,Int64}) -> Tuple{Int64, Int64}Corrects the positions (x_pos, y_pos) of an object within a 2D grid to ensure they fall within the grid's boundaries, assuming periodic boundary conditions. This means that if an object moves beyond one edge of the grid, it re-enters the grid from the opposite edge, similar to a toroidal (doughnut-shaped) space.
Arguments
x_pos::Int64: The x-coordinate of the object's position.y_pos::Int64: The y-coordinate of the object's position.size::Tuple{Int64,Int64}: A tuple representing the size of the grid, where the first element is the width (x dimension) and the second element is the height (y dimension).
Returns
Tuple{Int64, Int64}: The corrected position of the object as a tuple of(x_pos, y_pos).
Examples
# Given a grid of size 10x10
grid_size = (10, 10)
# An object at position (11, 5) would wrap around to (1, 5)
periodic_boundary_correction(11, 5, grid_size) # returns (1, 5)
# An object at position (0, 10) would wrap around to (10, 10)
periodic_boundary_correction(0, 10, grid_size) # returns (10, 10)TrypColonies.radial_density_c — Method
radial_density_c(agent_list::Vector{agent}, grids::Tuple{AbstractArray,AbstractArray}, para::parameters)Calculate the radial density of agents in a grid.
Arguments
agent_list::Vector{agent}: A list of agents.grids::Tuple{AbstractArray, AbstractArray}: A tuple containing the grids.para::parameters: The parameters for the simulation.
Returns
dist_vec_equal_oc::Vector{Float64}: A vector representing the normalized radial density of agents.
Description
This function calculates the radial density of agents in a grid by comparing all possible available grid points where agents can be with the points where they actually are. It sorts these points by their distance from the center of the grid and normalizes the counts of these distances to provide a radial density distribution.
Example
agent_list = [...] # List of agents
grids = (grid1, grid2) # Tuple of grids
para = parameters(...) # Simulation parameters
density = radial_density_c(agent_list, grids, para)TrypColonies.radial_distribution — Method
radial_distribution(agent_list::Vector{agent}, size::Tuple{Int, Int})Calculates the radial distribution of agents from the center of the grid.
Arguments
- agent_list::Vector{agent} : A vector of agent objects.
size::Tuple{Int, Int}: A tuple containing the dimensions of the grid.
Description
This function calculates the radial distribution of agents from the center of the grid. It performs the following steps:
- Calculates the center of the grid.
- Computes the relative positions of the agents with respect to the center.
- Calculates the Euclidean distance of each agent from the center.
- Bins the distances and normalizes by 1/(2r+1) to get the radial distribution.
Example
x_pos = [1, 3, 5, 7]
y_pos = [2, 4, 6, 8]
size = (10, 10)
radial_distribution(x_pos, y_pos, size)Returns
Vector{Int}: The radial distributionVector{Float}: The distance vector, useable for histogram plotting
TrypColonies.reconstruct_grid! — Method
reconstruct_grid!(Grid_vec_sparse::Vector{SparseMatrixCSC{Int64, Int64}}, Timestep::Int, start_grid::AbstractArray{Int})Update start_grid in-place by adding the non-zero values from a specific timestep's sparse matrix in Grid_vec_sparse.
Arguments
Grid_vec_sparse: A vector of sparse matrices (SparseMatrixCSC{Int64, Int64}), each representing the grid at a different timestep.Timestep: The specific timestep (index intoGrid_vec_sparse) from which to take the non-zero values.start_grid: An array to be updated in-place. It represents the grid before updating, and it will be modified to include the non-zero values from the specified timestep's sparse matrix.
Description
This function iterates over all non-zero elements of the sparse matrix at the specified Timestep in Grid_vec_sparse. For each non-zero element, it increments the corresponding element in start_grid by the value of the non-zero element. This operation modifies start_grid in-place, effectively reconstructing or updating the grid state by applying the changes from the specified timestep.
Examples
# Example usage
Grid_vec_sparse = [sparse([1, 2], [1, 2], [1, 1]), sparse([1, 2], [1, 2], [2, 2])]
Timestep = 2
start_grid = zeros(Int, 2, 2)
reconstruct_grid!(Grid_vec_sparse, Timestep, start_grid)
# start_grid is now [0 2; 0 2] (2x2 matrix of integersTrypColonies.reconstruct_grid_from_scratch — Function
reconstruct_grid_from_scratch(Grid_vec_sparse::Vector{SparseMatrixCSC{Int64, Int64}}, Timestep::Int = length(Grid_vec_sparse)) -> Matrix{Int64}Reconstructs the grid state from scratch up to a specified timestep using a sequence of sparse matrices.
Arguments
Grid_vec_sparse: A vector ofSparseMatrixCSC{Int64, Int64}objects, each representing the grid changes at a specific timestep.Timestep: (Optional) The timestep up to which the grid should be reconstructed. Defaults to the last available timestep inGrid_vec_sparse.
Returns
A Matrix{Int64} representing the reconstructed grid state up to the specified timestep.
Description
This function reconstructs the grid state by starting with the grid state at the first timestep and then applying changes from each subsequent timestep up to the specified Timestep. It uses the reconstruct_grid! function to apply changes in-place to the grid state.
TrypColonies.remove_fields_dict! — Method
remove_fields_dict(dict::Dict{String, Any}) -> Dict{String, Any}Removes keys from the given dictionary dict that are not present in the parameters structure.
Arguments
dict::Dict{String, Any}: The dictionary from which keys will be removed.
Returns
Dict{String, Any}: The modified dictionary with only the keys that are present in theparametersstructure.
Example
parameters = (a=1, b=2)
dict = Dict("a" => 1, "b" => 2, "c" => 3)
new_dict = remove_fields_dict(dict)
# new_dict is now Dict("a" => 1, "b" => 2)This function is useful for ensuring that a dictionary contains only valid keys before using it to set parameters in a simulation.
TrypColonies.res_scaling — Method
res_scaling(image_number; factor::Real = 3.0, plots::Int = 1)Calculate the scaled width and height of an image based on the given factor and number of plots.
Arguments
image_number::Int: The number of the image to be scaled.factor::Real: The scaling factor for the image dimensions. Default is 3.0.plots::Int: The number of plots to be considered in the width calculation. Default is 1.
Returns
width::Int: The scaled width of the image.height::Int: The scaled height of the image.
Example
width, height = res_scaling(10, factor=2.5, plots=2)TrypColonies.save_grid_changes! — Method
save_grid_changes!(Grid_1::Union{Matrix{Int64}, Real}, Grid_2::Matrix{Int64}, Grid_vec::Vector{SparseMatrixCSC{Int64, Int64}})Subtracts Grid_1 from Grid_2 and appends the result to Grid_vec.
Arguments
Grid_1: A matrix of integers or a real number. Represents the initial state of the grid.Grid_2: A matrix of integers. Represents the updated state of the grid.Grid_vec: A vector of sparse integer matrices. This vector is updated with the changes.
Notes
- This function modifies
Grid_vecin place by appending the difference betweenGrid_2andGrid_1. - If
Grid_1is a real number, it is subtracted from each element ofGrid_2before the result is appended toGrid_vec.
TrypColonies.scale_color_map — Method
This function counteracts the dynamic scaling of colormaps in Makie if min and max values change over the course of an animation. It is given a Max value (min value = 0) and shrinks the colormap dynamically if the data does not reach the max value.
TrypColonies.scale_time_step — Method
scale_time_step(dt_diff::Float64, dt_walker::Float64) -> Tuple{Float64, Float64}Scales the time step dt_diff to be compatible with dt_walker.
Arguments
dt_diff::Float64: The differential time step.dt_walker::Float64: The walker time step.
Returns
Tuple{Float64, Float64}: A tuple containing the scaleddt_diffand the originaldt_walker.
Description
This function adjusts the differential time step dt_diff to ensure it is compatible with the walker time step dt_walker. If dt_diff is greater than or equal to dt_walker, it is set to dt_walker. Otherwise, it is adjusted to be a divisor of dt_walker with a tolerance for floating-point precision.
TrypColonies.strenghten_boundary! — Method
strenghten_boundary!(grids::Tuple{Matrix{Int64}, Matrix{Float64}}, Parameters::parameters)Strengthens the boundary of the grid by recovering the grid values based on a recovery rate.
Arguments
grids::Tuple{Matrix{Int64}, Matrix{Float64}}: A tuple containing two matrices. The first matrix represents the grid to be strengthened.Parameters::parameters: A struct containing various parameters, including grid size, recovery rate, and grid strength.
Description
This function iterates over the grid and increases the grid values that are negative but greater than the negative grid strength. The increase is determined by a Poisson distribution with a mean equal to the grid recovery rate. If the updated grid value exceeds the negative grid strength, it is capped at the negative grid strength.
Example
grids = (Matrix{Int64}(undef, 10, 10), Matrix{Float64}(undef, 10, 10))
Parameters = parameters(size = (10, 10), grid_recover_rate = 0.1, grid_strength = 5)
strenghten_boundary!(grids, Parameters)TrypColonies.sweep_and_save_parallel_t — Function
sweep_and_save_parallel_t(para_dict_list, full_data_path, offset=100000; threads=4)Run simulations in parallel and save the results.
Arguments
para_dict_list::Vector{Dict}: A list of parameter dictionaries for each simulation.full_data_path::String: The path where the simulation data will be saved.offset::Int: An offset for the file naming of the saved data. Default is 100000.threads::Int: The number of threads to use for parallel execution. Default is 4.
Description
This function runs multiple simulations in parallel using the specified number of threads. Each simulation is initialized with parameters from para_dict_list. The simulation involves updating grids and agent lists over a series of time steps. Data is sampled at specified intervals and stored in vectors. After the simulation, the data is serialized and saved to full_data_path with filenames based on the task index and offset.
Example
para_dict_list = [...] # List of parameter dictionaries
full_data_path = "path/to/save/data"
sweep_and_save_parallel_t(para_dict_list, full_data_path, offset=100000, threads=4) TrypColonies.update_grid! — Method
update_grid!(grid::Matrix{Int}, Parameters::parameters, grid_t::Matrix{Int}, grid_vec_sparse::Vector{SparseMatrixCSC{Int64, Int64}})Updates the simulation grid by strengthening boundaries and saving grid changes.
Arguments
grid: The current state of the simulation grid as a matrix of integers.Parameters: A struct containing simulation parameters, such as grid size and boundary strength.grid_t: A reference grid state used for comparison when saving changes.grid_vec_sparse: A vector of sparse matrices where changes to the grid are stored.
Description
This function performs two main operations on the simulation grid:
- It calls
strengthen_boundary!to modify the grid's boundaries based on theParameters. This typically involves making the boundaries more negative (stronger) according to a predefined strength parameter. - It calls
save_grid_changes!to compare the current grid state (grid) with a reference state (grid_t) and records the differences ingrid_vec_sparse. This step is crucial for tracking the evolution of the grid over time in an efficient manner.
TrypColonies.update_position! — Function
update_position!(grid::Matrix{Int64}, full_agent_list, Parameters::parameters, timestep=1)Updates the positions of agents on a grid based on their velocities and directions.
Arguments
grid::Matrix{Int64}: A 2D grid representing the environment where each cell can be empty (0), occupied by an agent (positive non-zero) or part of unmoveable space (negative non-zero).full_agent_list: A collection of agents. Can be aCircularBuffer{Vector{agent}}for interactive/infinite simulations or a simpleVector{agent}for static/finite simulations.Parameters::parameters: A struct containing simulation parameters, including velocity distribution, boundary conditions, and whether path tracing is enabled.timestep=1: The current timestep of the simulation. Defaults to 1.
Behavior
- Determines the velocity distribution for agents based on the provided parameters.
- Draws a random velocity for each agent from the distribution.
- Decides on the agent list to use based on the type of simulation (interactive/infinite vs. static/finite).
- Iterates through each agent, calculating their new position based on their velocity and direction.
- If
path_tracingis disabled, agents move directly to their new position if it's empty, respecting boundary conditions. - If
path_tracingis enabled, calculates a path for the agent and moves them along this path and interacts with the non movable space, also respecting boundary conditions and handling sliding boundary conditions if enabled. - Updates the grid to reflect the new positions of the agents.
- Updates the non movable space if the boundary is moveable.
Note
- This function modifies the
gridandfull_agent_listin place. - Agents are assumed to be immutable; thus, to update an agent's position, a new agent with the updated position is created and replaced in the list.
TrypColonies.@h — Macro
@h methodname
Outputs documentations in jupyternotenbooks in VScode as markdown without bugs.
Example of how to use the @h macro:
@h res_scalingOutputs documentations in jupyternotenbooks in VScode as markdown without bugs.