AgentJS agent-based modelling in the browser

Guide

How an AgentJS model is put together, and the three things people most often get wrong.

The parts

A model can also be written as a plain object and built by runModel(config), with no model code: see Models as plain objects.

Three things to know

  1. The environment does not move agents for you. A MovingAgent moves itself in step(). To make the environment apply its boundary (wrapping, say) and update its index, call environment.moveAgent(agent, agent.position) afterwards, as the first example does.
  2. A scheduler holds its own list of agents. Add an agent to the environment and to the scheduler: space.addAgent(a); scheduler.addAgent(a);.
  3. Drawing only reads. The examples draw with p5.js in instance mode, and the model never calls p5. You can run the same model in Node.js with no drawing at all.

In the browser, without a build step

The library is one ES module. It imports @tensorflow/tfjs by name, which a browser cannot resolve on its own, so a page needs an import map. If the page uses no NSMnum or other ML classes, point it at an empty module; this site ships one as lib/no-tfjs.js. Pages with NSMnum point it at TensorFlow.js on cdnjs.

<script type="importmap">
{ "imports": {
    "@prayas_abhinav/agentjs-core": "./lib/agentjs.es.js",
    "@tensorflow/tfjs": "./lib/no-tfjs.js"
} }
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.4/p5.min.js"></script>
<script type="module">
  import { ContinuousSpace } from '@prayas_abhinav/agentjs-core';
  // ...
</script>

Serve the folder over HTTP (python3 -m http.server will do); modules do not load from a file: address.

In Node.js

Build once with npm run build:framework, then import dist/index.es.js. The quick start runs this way. A parameter sweep is a loop around a function that builds and runs a fresh model for each value:

import { MovingAgent, ContinuousSpace, RandomScheduler } from '@prayas_abhinav/agentjs-core';

// A parameter sweep is a loop: build a fresh model for each value, run it, and record what you measure
function run(maxSpeed) {
  const space = new ContinuousSpace({ width: 500, height: 500, boundaryType: 'periodic', enableSpatialIndex: true, maxObjectsPerNode: 10, maxTreeDepth: 6 });
  const scheduler = new RandomScheduler(42);               // a seed makes a run repeatable
  for (let i = 0; i < 50; i++) {
    const walker = new MovingAgent(`walker-${i}`, {}, { x: 250, y: 250 }, { maxSpeed });
    space.addAgent(walker);
    scheduler.addAgent(walker);
  }
  for (let step = 0; step < 100; step++) {
    for (const walker of space.getAllAgents()) walker.wander(1);
    scheduler.step();
    for (const walker of space.getAllAgents()) space.moveAgent(walker, walker.position);
  }
  const far = space.getAllAgents().reduce((sum, walker) => sum + space.distance(walker.position, { x: 250, y: 250 }), 0);
  return far / space.getAgentCount();
}

for (const maxSpeed of [1, 2, 3, 4]) console.log(`maxSpeed ${maxSpeed}: mean distance from the start ${run(maxSpeed).toFixed(1)}`);

Step through the model by hand and measure what you want; for rows of positions, TrajectoryExporter works with an AgentManager:

import { AgentManager, MovingAgent, TrajectoryExporter } from '@prayas_abhinav/agentjs-core';

const manager = new AgentManager();
for (let i = 0; i < 5; i++) manager.addAgent(new MovingAgent(`agent-${i}`, { energy: 100 }, { x: i * 10, y: 0 }));

const exporter = new TrajectoryExporter({ fields: ['energy'], sampleRate: 1 });
const energy = [];                                         // your own numbers, collected in your own loop

for (let step = 0; step < 20; step++) {
  for (const agent of manager.getAllAgents()) agent.wander(1);
  manager.stepAll();                                       // calls step() on every active agent
  exporter.recordTrajectoryStep(manager, step);
  energy.push(manager.getAllAgents().reduce((sum, agent) => sum + agent.getProperty('energy'), 0) / manager.getAgentCount());
}

const csv = exporter.exportTrajectoriesCSV();              // a string: write it to a file yourself
console.log(csv.split('\n').slice(0, 3).join('\n'));
console.log(`${csv.split('\n').length - 1} rows; mean energy at the end ${energy[energy.length - 1]}`);