Skip to content

First simulation ​

Create a Scenario, combine it with a graph and facilities in a Simulation, and call run() with explicit seed and time settings. Inputs are JSON-compatible data; no application-specific conversion is built into grABM.

Use the library ​

After installation, build the library in this checkout:

sh
npm run build:packages

This complete input models one person, a home, a shop, and a 100-metre walking edge. Both facilities are open for the whole run. Shopping is the only preferred activity; the stay probability is explicitly zero. Demographic labels describe the profile; the specified decision template determines the shopping trip.

ts
import type { SimulationInputData } from '@grabm/abm'

/** One person leaves home at minute 10 to visit a shop over a 100-metre walking edge. */
export const input: SimulationInputData = {
  graph: {
    nodes: [
      { id: 'a', position: { xM: 0, yM: 0, zM: 0 }, kind: 'place' },
      { id: 'b', position: { xM: 100, yM: 0, zM: 0 }, kind: 'place' },
    ],
    edges: [
      {
        id: 'edge',
        sourceNodeId: 'a',
        targetNodeId: 'b',
        direction: 'both',
        modes: ['walk'],
        lengthM: 100,
        capacityPersonsPerHour: 1000,
      },
    ],
  },
  facilities: [
    {
      id: 'home',
      name: 'Home',
      accessNodeId: 'a',
      capacity: 1,
      availability: [{ startMinute: 0, endMinute: 120 }],
      attractiveness: 1,
      activities: { home: 1 },
      tags: ['home'],
    },
    {
      id: 'shop',
      name: 'Shop',
      accessNodeId: 'b',
      capacity: 1,
      availability: [{ startMinute: 0, endMinute: 120 }],
      attractiveness: 1,
      activities: { shopping: 1 },
      tags: ['shopping'],
    },
  ],
  scenario: {
    profiles: [
      {
        id: 'resident',
        demographics: { lifeStage: 'adult' },
        preferences: { shopping: 1 },
        availableModes: ['walk'],
        decisionTemplates: [
          {
            id: 'shopping-choice',
            minute: { kind: 'fixed', value: 10 },
            dwellMinutes: { kind: 'fixed', value: 20 },
            activityIds: ['shopping'],
          },
        ],
      },
    ],
    population: { cohorts: [{ id: 'resident', profileId: 'resident', count: 1 }] },
    mobility: {
      modes: { walk: { enabled: true, speedMps: 1.4 } },
      congestion: { modes: [] },
    },
    behavior: {
      anchorAssignment: {},
      choice: { stayProbability: 0 },
      defaultDwellMinutes: { kind: 'fixed', value: 30 },
      dwellMinutesByActivity: { shopping: { kind: 'fixed', value: 20 } },
    },
  },
  run: {
    seed: 42,
    startMinute: 0,
    durationMinutes: 120,
    observationIntervalMinutes: 5,
  },
}

Execute that data, calculate analytics, and round-trip the result through persistence:

ts
import {
  Scenario,
  Simulation,
  simulationInputSchema,
  encodeRun,
  decodeRun,
} from '@grabm/abm'
import { analyzeRun } from '@grabm/abm/analytics'

/** Caller supplies graph, facilities, scenario configuration, and run settings. */
export async function simulate(data: unknown) {
  const input = simulationInputSchema.parse(data)
  const simulation = new Simulation({
    graph: input.graph,
    facilities: input.facilities,
    scenario: new Scenario(input.scenario),
  })
  try {
    const result = await simulation.run(input.run)
    const analysis = analyzeRun(result)
    const restored = decodeRun(encodeRun(result).json)
    return { result, analysis, restored }
  } finally {
    simulation.dispose()
  }
}

With the two snippets saved as input.ts and quickstart.ts, call:

ts
import { input } from './input.ts'
import { simulate } from './quickstart.ts'

const { result } = await simulate(input)
console.log(result.agents.length) // 1
console.log(result.trips[0]?.destinationFacilityId) // "shop"
console.log(result.trips[0]?.outcome) // "completed"

The trip departs at minute 10 and arrives at approximately 11.19. One edge traversal is recorded. analysis contains metrics, and restored equals the original result. Inspect warnings, decisions, and diagnosticBuckets even when execution succeeds.

Follow this person through the queue in the event-by-event walkthrough.

Use your own input ​

Provide graph, facilities, scenario, and run as described in the JSON schema guide. Coordinates and lengths are metres; times are minutes. Node IDs and edge references define connectivity.

Scenario validates population and behavior independently of the environment. Simulation.run() checks the complete input, including facility and graph references. simulationInputSchema.parse(input) offers the same complete validation for JSON. Constructors detach their inputs; Scenario.toJSON() returns a detached normalized copy. To edit a scenario, construct a new one.

Identical normalized inputs, seed, and engine version reproduce the result. Repeated runs on one simulation start fresh; overlapping runs reject. Dispose the simulation when the host is finished with it.

Continue with profiles, workers, playback, analytics, or persistence. An external application implementation demonstrates host integration.

Documentation for the grABM library.