agentscape
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

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

Examples

Tutorials

Examples

ants

boids

brownian-motion

predators-and-prey

traffic-congestion

All examples can be found here.

Installation

npm i agentscape

Quick Start - Random Walk

We will create a simple simulation where agents move randomly around a grid.

random-walk-example

We start by defining an agent which is a class that extends Entities.Agent. The agent must implement an act method that defines the agent's behavior for each step of the simulation.

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 and a Cell is grouped into a CellGrid. The Model must implement methods to initialize agent sets and a cell grid.

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.

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 objects and passed to the model constructor.

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.

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.

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.

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.

API

The auto-generated API documentation can be found here.

Package Sidebar

Install

npm i agentscape

Weekly Downloads

128

Version

1.2.0

License

MIT

Unpacked Size

502 kB

Total Files

151

Last publish

Collaborators

  • bgoodman