agentscape
Version:
Agentscape is a library for creating agent-based simulations. It provides a simple API for defining agents and their behavior, and for defining the environment in which the agents interact. Agentscape is designed to be flexible and extensible, allowing
380 lines (280 loc) • 10.8 kB
Markdown
# Agentscape
Agentscape is a library for creating agent-based simulations. It provides a simple API for defining agents and their behavior, and for defining the environment in which the agents interact. Agentscape is designed to be flexible and extensible, allowing users to create a wide variety of simulations.
> [API Docs](https://ben_goodman.gitlab.io/agentscape/)
>
> [Examples](https://gitlab.com/ben_goodman/apps/agent-based-modelling)
>
> [Tutorials](https://gitlab.com/ben_goodman/agentscape/-/tree/main/docs/tutorials?ref_type=heads)
## Examples
### [Ant Colony](https://apps.ben.website/ants)

### [Boids](https://apps.ben.website/boids)

### [Brownian Motion](https://apps.ben.website/brownian-motion)

### [Predators and prey](https://apps.ben.website/predators-and-prey)

### [Traffic Congestion](https://apps.ben.website/traffic-congestion)

> All examples can be found [here](https://gitlab.com/ben_goodman/apps/agent-based-modelling).
## Installation
```bash
npm i agentscape
```
## Quick Start - Random Walk
We will create a simple simulation where agents move randomly around a grid.

We start by defining an agent which is a class that extends [`Entities.Agent`](https://ben_goodman.gitlab.io/agentscape/classes/Entities.Agent.html). The agent must implement an `act` method that defines the agent's behavior for each step of the simulation.
```typescript
import { Entities } from 'agentscape'
import { Color } from 'agentscape/number'
import { CellGrid } from 'agentscape/structures'
export default class Agent extends Entities.Agent {
// we'll keep track of the random
// angle the agent turns each step
public theta: number
// agents have a random number generator
// and a default color (blue)
override color = Color.random(this.rng)
act(grid: CellGrid<Entities.Cell>) {
this.theta = this.rng.uniformFloat(0, 90) - this.rng.uniformFloat(0, 90)
this.rotation.increment(this.theta,'deg')
// agents can move in the direction they are facing
// or to a specific location.
this.move(grid)
}
}
```
Next, we define a model that contains the agents and the grid. A model consists of zero or more agent sets and one grid of cells.
Agents are grouped into an [`AgentSet`](https://ben_goodman.gitlab.io/agentscape/classes/Structures.AgentSet.html) and a [`Cell`](https://ben_goodman.gitlab.io/agentscape/classes/Entities.Cell.html) is grouped into a [`CellGrid`](https://ben_goodman.gitlab.io/agentscape/classes/Structures.CellGrid.html). The [`Model`](https://ben_goodman.gitlab.io/agentscape/classes/Model.html) must implement methods to initialize agent sets and a cell grid.
```typescript
import { Model, ModelConstructor } from 'agentscape/model'
import { Cell } from 'agentscape/entities'
import { Angle } from 'agentscape/number'
import { CellGrid, AgentSet } from 'agentscape/structures'
import Agent from './Agent'
export default class RandomWalk extends Model<Cell, Agent> {
gridSize = 10
agentCount = 10
randomSeed = 0
constructor(opts: ModelConstructor) {
super(opts)
this.setRandomSeed(this.randomSeed)
}
initAgents() {
// creates an AgentSet using a factory function
// that creates agents with random starting rotations.
const _default = AgentSet.fromFactory(
this.agentCount,
(_, randomSeed) => new Agent({
initialPosition: [
Math.floor(this.gridSize / 2),
Math.floor(this.gridSize / 2)
],
rotation: Angle.random(this.rng),
randomSeed
}),
{
// the agent factory's RNG can be
// seeded to ensure reproducibility
randomSeed: this.randomSeed
}
)
return {_default}
}
initGrid() {
// creates a grid of cells with periodic boundary conditions
// uses the default cell class
return CellGrid.default(
this.gridSize,
{
boundaryCondition: 'periodic'
}
)
}
}
```
Finally, we create an instance of the model and run the simulation.
```typescript
import RandomWalkModel from './Model'
const documentRoot = document.getElementById('root') as HTMLDivElement
const model = new RandomWalkModel({
documentRoot,
renderWidth: 800,
id: 'random-walk',
autoPlay: false,
frameRate: 10,
})
model.start()
```
### Adding Parameters
We can add parameters to the model that can be controlled by the user. Parameters are defined as an array of [`ControlVariable`](https://ben_goodman.gitlab.io/agentscape/interfaces/UI.ControlVariable.html) objects and passed to the model constructor.
```typescript
import { ControlVariableConfig } from 'agentscape/ui/Controls'
import RandomWalkModel from './Model'
const documentRoot = document.getElementById('root') as HTMLDivElement
const parameters: ControlVariableConfig[] = [
{
label: 'Grid Size',
name: 'gridSize',
default: 10
},
{
label: 'Number of Agents',
name: 'agentCount',
default: 10
},
{
label: 'Random Seed',
name: 'randomSeed',
default: 0
}
]
const model = new RandomWalkModel({
documentRoot,
renderWidth: 500,
title: 'Random Walk',
id: 'random-walk',
parameters,
frameRate: 10,
autoPlay: false
})
model.start()
```
The parameters can be accessed in the scope of the model class as properties by using the `@ControlVariable` decorator.
```typescript
import { ControlVariable, Model, ModelConstructor } from 'agentscape/model'
import { Cell } from 'agentscape/entities'
import { Angle } from 'agentscape/number'
import { CellGrid, AgentSet } from 'agentscape/structures'
import Agent from './Agent'
export default class RandomWalk extends Model<Cell, Agent> {
@ControlVariable()
gridSize: number
@ControlVariable()
agentCount: number
@ControlVariable()
randomSeed: number
constructor(opts: ModelConstructor) {
super(opts)
this.setRandomSeed(this.randomSeed)
}
initAgents() {
const _default = AgentSet.fromFactory(
this.agentCount,
(_, randomSeed) => new Agent({
initialPosition: [
Math.floor(this.gridSize / 2),
Math.floor(this.gridSize / 2)
],
rotation: Angle.random(this.rng),
randomSeed
}),
{
randomSeed: this.randomSeed
}
)
return {_default}
}
initGrid() {
return CellGrid.default(
this.gridSize,
{
boundaryCondition: 'periodic'
}
)
}
}
```
### Adding Output
In addition to rendering the simulation, we can also display data via charts.
- Histogram
- Time Series
- Scatter Plot
We will use a histogram to display the cumulative distribution of agent rotations.
First, instantiate a new Histogram in the model constructor.
```typescript
import { Histogram } from 'agentscape/ui/charts'
export default class RandomWalk extends Model<Cell, Agent> {
@ControlVariable()
gridSize: number
@ControlVariable()
agentCount: number
@ControlVariable()
randomSeed: number
turningAngleDistribution: Histogram
turningAngleCumulative: number[] = []
constructor(opts: ModelConstructor) {
super(opts)
this.setRandomSeed(this.randomSeed)
this.turningAngleDistribution = new Histogram({
root: opts.documentRoot,
title: 'Turning Angle Distribution',
axisLabels: {
x: 'Angle',
y: 'Frequency',
}
})
}
...etc
}
```
Then, using the model's `postUpdate` method, we can update the histogram with the turning angle of each agent at each step of the simulation. We do this by getting the turning angle (theta) of each agent and pushing it to the `turningAngleCumulative` array. We then apply the data to the histogram.
```typescript
export default class RandomWalk extends Model<Cell, Agent> {
@ControlVariable()
gridSize: number
@ControlVariable()
agentCount: number
@ControlVariable()
randomSeed: number
turningAngleDistribution: Histogram
turningAngleCumulative: number[] = []
constructor(opts: ModelConstructor) {
super(opts)
this.setRandomSeed(this.randomSeed)
this.turningAngleDistribution = new Histogram({
root: opts.documentRoot,
title: 'Turning Angle Distribution',
axisLabels: {
x: 'Angle',
y: 'Frequency',
}
})
}
initAgents() {
const _default = AgentSet.fromFactory(
this.agentCount,
(_, randomSeed) => new Agent({
initialPosition: [
Math.floor(this.gridSize / 2),
Math.floor(this.gridSize / 2)
],
rotation: Angle.random(this.rng),
randomSeed
}),
{
randomSeed: this.randomSeed
}
)
return {_default}
}
initGrid() {
return CellGrid.default(
this.gridSize,
{
boundaryCondition: 'periodic'
}
)
}
postUpdate(): () => void {
return () => {
this.turningAngleCumulative.push(...this.agents._default.map((agent) => agent.theta ))
this.turningAngleDistribution.applyData(this.turningAngleCumulative, 1)
}
}
}
```
The complete code the Random Walk example can be found [here](https://gitlab.com/ben_goodman/apps/agent-based-modelling/random-walk).
## API
The auto-generated API documentation can be found [here](https://ben_goodman.gitlab.io/agentscape/).