Foraging Toolkit

The foraging toolkit provides a set of tools for representing, simulating, analyzing and visualizing dynamic measurements of foraging agents.

The main reference is [1].

Visualization

collab.foraging.toolkit.visualization.animate_predictors(foragersDF: DataFrame, predictor: List[List[DataFrame]], predictor_name: str, forager_position_indices: List[int], forager_predictor_indices: List[int], grid_size: int, random_state: int | None = 0, size_multiplier: int | None = 10)[source]

A function to animate a computed predictor for specified foragers.

Parameters:
  • foragersDF (-) – flattened DataFrame of forager positions

  • predictor (-) – Nested list of DataFrames containing computed predictor scores, grouped by forager index and time

  • predictor_name (-) – Name of column containing predictor scores in predictor

  • forager_position_incices (-) – Index of foragers whose positions are to be plotted

  • forager_predictor_indices (-) – Index of foragers whose predictors are to be plotted

  • grid_size (-) – size of grid used to compute forager positions (used for setting x,y limits in figure)

  • random_state (-) – used to choose plot colors for each forager

  • size_multiplier (-) – used to select marker size in scatter plot

Returns :
  • ani : animation

collab.foraging.toolkit.visualization.plot_predictor(foragers: List[DataFrame], predictor: List[List[DataFrame]], predictor_name: str, forager_position_indices: List[int], forager_predictor_indices: List[int], time: List[int], grid_size: int, random_state: int | None = 0, size_multiplier: int | None = 10)[source]

A function to visualize a computed predictor for specified foragers and timeframes.

Parameters:
  • foragers (-) – list of DataFrames containing forager positions, grouped by forager index

  • predictor (-) – Nested list of DataFrames containing computed predictor scores, grouped by forager index and time

  • predictor_name (-) – Name of column containing predictor scores in predictor

  • forager_position_indices (-) – List of indices of foragers whose positions are to be plotted

  • forager_predictor_indices (-) – List of indices of foragers whose predictors are to be plotted

  • time (-) – Timeframes for which predictor scores are to be plotted

  • grid_size (-) – size of grid used to compute forager positions (used for setting x,y limits in figure)

  • random_state (-) – used to choose plot colors for each forager

  • size_multiplier (-) – used to select marker size in scatter plot

Returns :

NA

collab.foraging.toolkit.animate_foragers.animate_foragers(sim, width=800, height=800, point_size=15, plot_rewards=True, plot_traces=False, plot_visibility=0, plot_proximity=0, plot_communicate=0, plot_velocity=0, trace_multiplier=10, visibility_multiplier=10, proximity_multiplier=10, communicate_multiplier=10, velocity_multiplier=10, color_by_state=False, produce_object=False, autosize=False)[source]
collab.foraging.toolkit.animate_foragers.plot_coefs(selected_samples: Dict[str, Tensor], title: str, nbins=20, ann_start_y=100, ann_break_y=50, generate_object=False)[source]
collab.foraging.toolkit.animate_foragers.plot_distances(distances, title='')[source]
collab.foraging.toolkit.animate_foragers.plot_trajectories(df, title, ax=None, show_legend=True)[source]
collab.foraging.toolkit.animate_foragers.visualise_forager_predictors(outcome: Tensor, predictors: List[Tensor], predictor_names: List[str], outcome_name: str, sampling_rate: float = 1.0, titles=None)[source]

Local Windows

collab.foraging.toolkit.local_windows.generate_local_windows(foragers_object: dataObject) List[List[DataFrame]][source]

A wrapper function that calculates local_windows for a dataObject by calling _generate_local_windows with parameters inherited from the dataObject. :param foragers_object: dataObject containing foragers trajectory data

Must have local_windows_kwargs as an attribute

Returns:

Nested list of local_windows (DataFrames with “x”,”y” columns) grouped by forager index and time

The list of keyword arguments:
param window_size:

radius of local_windows. Default: 1.0

param sampling_fraction:

fraction of grid points to sample. It may be advisable to subsample grid points for speed

param random_seed:

random state for subsampling. Default: 0

param skip_incomplete_frames:

Defaults to False. If True, local_windows for all foragers are set to None whenever tracks for any forager is missing. This implies that frames with incomplete tracking would be skipped entirely from subsequent predictor/score computations. If False (default behavior) local_windows are set to None only for the missing foragers, and computations proceed as normal for other foragers in the frame

param grid_constraint:

Optional callable to model inaccessible points in the grid. This function takes as arguments: the grid (as a pd.DataFrame) and any additional kwargs, and returns a DataFrame of accessible grid points

param grid_constrain_params:

optional dictionary of kwargs for grid_constraint, to be passed to _get_grid

Predictors and Scores

collab.foraging.toolkit.derive.derive_predictors_and_scores(foragers_object: dataObject, local_windows_kwargs: Dict[str, Any], predictor_kwargs: Dict[str, Dict[str, Any]], score_kwargs: Dict[str, Dict[str, Any]], dropna: bool | None = True, add_scaled_values: bool | None = False) DataFrame[source]

A function that calculates a chosen set of predictors and scores for data by inferring their names from keys in predictor_kwargs & score_kwargs, and dynamically calling the corresponding functions. :param foragers_object: instance of dataObject class containing the trajectory data of foragers. :param local_window_kwargs: dictionary of keyword arguments for generate_local_windows function. :param predictor_kwargs: nested dictionary of keyword arguments for predictors to be computed.

Keys of predictor_kwargs set the name of the predictor to be computed. The predictor name can have underscores, however, the substring before the first underscore must correspond to the name of a predictor type in Collab. Thus, we can have multiple versions of the same predictor type (with different parameters) by naming them as follows: predictor_kwargs = {

“proximity_10” : {“optimal_dist”:10, “decay”:1, …}, “proximity_20” : {“optimal_dist”:20, “decay”:2, …}, “proximity_w_constraint” : {…,”interaction_constraint” : constraint_function,

“interaction_constraint_params”: {…}}

}

Parameters:
  • score_kwargs

    nested dictionary of keyword arguments for outcome variables (“scores”) to be computed. The substring before the first underscore in dictionary keys must correspond to the name of a score type in Collab, same as in predictor_kwargs score_kwargs = {

    ”nextStep_linear” : {“nonlinearity_exponent” : 1}, “nextStep_squared” : {“nonlinearity_exponent” : 2},

    }

  • dropna – set to True to drop NaN elements from the final DataFrame

  • add_scaled_values – set to True to compute scaled predictor scores and add them as additional columns in final DataFrame

Returns:

final, flattened DataFrame containing all computed predictors as columns

collab.foraging.toolkit.derive.get_list_of_predictors() List[str][source]

A function that returns a list of all available predictors in Collab.

collab.foraging.toolkit.derive.get_list_of_scores() List[str][source]

A function that returns a list of all available scores in Collab.

collab.foraging.toolkit.food.generate_food_predictor(foragers_object: dataObject, predictor_name: str)[source]

Generates food-based predictors for a group of foragers. Food is given by the presence of rewards in the environment. The value of the predictor is proportional to the rewards in the vicinity of the forager. The decay function can be customized.

Arguments: :param foragers_object: A data object containing information about the foragers, including their positions,

trajectories, and local windows. Such objects can be generated using object_from_data.

Parameters:

predictor_name – The name of the food predictor to be generated, used to fetch relevant parameters from foragers_object.predictor_kwargs and to store the computed values.

Returns:

A list of lists of pandas DataFrames where each DataFrame has been updated with the computed food predictor values.

Predictor-specific keyword arguments:
param interaction_length:

The maximum distance at which a reward can be considered by the predictor.

param decay_contribution_function:

The decay function for computing the value for each reward. The value of the food predictor will be equal to the total contribution from the individual rewards. The default value is the exponential decay function: f(dist) = exp(-decay_factor * dist). The default decay factor is 0.5, it can be customized by passing an additional decay_factor keyword argument.

collab.foraging.toolkit.proximity.generate_proximity_predictor(foragers_object: dataObject, predictor_name: str)[source]

Generates proximity-based predictors for a group of foragers by invoking the proximity predictor mechanism.

This function retrieves the relevant parameters from the provided foragers_object and uses them to compute the proximity predictor values. It relies on the _proximity_predictor function to handle the detailed calculations and updates.

Parameters:
  • foragers_object – A data object containing information about the foragers, including their positions, trajectories, and local windows. Such objects can be generated using object_from_data.

  • predictor_name – The name of the proximity predictor to be generated, used to fetch relevant parameters from foragers_object.predictor_kwargs and to store the computed values.

Returns:

A list of lists of pandas DataFrames where each DataFrame has been updated with the computed proximity predictor values.

Predictor-specific keyword arguments:

interaction_length: The maximum distance within which foragers can interact. interaction_constraint: An optional callable that imposes additional constraints on which

foragers can interact based on custom logic.

interaction_constraint_params: Optional parameters to pass to the interaction_constraint

function.

proximity_contribution_function: A callable function used to compute proximity scores based on distance.

Defaults to _piecewise_proximity_function.

Additional keyword arguments for the proximity function. The _piecewise_proximity_function function has the following parameters:

param repulsion_radius:

The distance threshold below which the score becomes negative. Defaults to 1.5.

param optimal_distance:

The distance where proximity reaches its peak. Defaults to 4.

param proximity_decay:

The rate at which proximity decays beyond the optimal range. Defaults to 1.

collab.foraging.toolkit.communication.generate_communication_predictor(foragers_object: dataObject, predictor_name: str)[source]

Generates communication-based predictors for a group of foragers. When a forager is in the vicinity of food, it can communicate this information with the other foragers. The predictor value is proportional to the proximity of the communicating partner, but only if that partner is close to a food source. The predictor can be customized by providing a custom communication function (default: exponential decay) and/or a custom interaction function (default: closeness to food).

Arguments: :param foragers_object: A data object containing information about the foragers, including their positions,

trajectories, and local windows. Such objects can be generated using object_from_data.

Parameters:

predictor_name – The name of the food predictor to be generated, used to fetch relevant parameters from foragers_object.predictor_kwargs and to store the computed values.

Returns:

A list of lists of pandas DataFrames where each DataFrame has been updated with the computed food predictor values.

Predictor-specific keyword arguments:
param interaction_length:

The maximum distance to the communicating partner.

param interaction_constraint:

An optional callable that imposes additional constraints on which foragers can interact based on custom logic. Default is constraint_filter_close_to_reward

param interaction_constraint_params:

Optional parameters to pass to the interaction_constraint function. For constraint_filter_close_to_reward, this includes finders_tolerance - the maximal distance of the communicating partner to the food source.

param communication_contribution_function:

The decay function for computing the strength of the communication.

The value of the communication predictor will be equal to the total contribution from the individual communicating partners.

The default value is the exponential decay function: f(dist) = exp(-decay_factor * dist). The default decay factor is 0.5, it can be customized by passing an additional decay_factor keyword argument.

collab.foraging.toolkit.access.generate_access_predictor(foragers_object: dataObject, predictor_name: str)[source]

Generates access-based predictors for a group of foragers. Access is defined as the ability of a forager to reach a specific location in space. For a homogeneous environment, the value of the predictor is inversely proportional to the distance between the forager and the target location. The decay function can be customized.

Arguments: :param foragers_object: A data object containing information about the foragers, including their positions,

trajectories, and local windows. Such objects can be generated using object_from_data.

Parameters:

predictor_name – The name of the access predictor to be generated, used to fetch relevant parameters from foragers_object.predictor_kwargs and to store the computed values.

Returns:

A list of lists of pandas DataFrames where each DataFrame has been updated with the computed access predictor values.

Predictor-specific keyword arguments:
param decay_contribution_function:

The decay function used to compute the value of the access predictor. The default value is the exponential decay function: f(dist) - exp(-decay_factor * dist). The default decay factor is 0.5, it can be customized by passing an additional decay_factor keyword argument.

collab.foraging.toolkit.next_step_score.generate_nextStep_score(foragers_object: dataObject, score_name: str)[source]

A wrapper function that computes next_step_score only taking foragers_object as argument, and calling _generate_next_step_score under the hood.

The next step score computes a score for how far grid points are from the next position of a forager. If the next position of the forager is unavailable, nan values are assigned to the scores.

The formula for the score is:

next_step_score(i,t,x,y) = 1 - (d_scaled) ** n where d_scaled = (d - min(d)) / (max(d) - min(d))

Here d is the vector of distances of grid points in the local window of forager i at time t from the position of forager i at time t+1.

Parameters:

foragers_object – dataObject containing positional data, local_windows, score_kwargs

:param score_name : name of column to save the calculated nextStep scores under

Returns:

Nested list of calculated scores, grouped by foragers and time

:keyword : param nonlinearity_exponent: Nonlinearity in nextStep score calculation. Default value n=1

References

[1]

Rafal Urbaniak, Marjorie Xie, and Emily Mackevicius. Linking cognitive strategy, neural mechanism, and movement statistics in group foraging behaviors. Scientific Reports, 14(1):21770, September 2024. doi:10.1038/s41598-024-71931-0.