Skip to content

Optimize grabm simulations ​

Genetic Assembly selects designs; grabm measures their behavior. Keep the integration in your application or example, so both libraries remain independent. The Graph optimization example uses Genetic Assembly 0.5.0.

Define a comparable problem ​

Fix homes, population, authored activity demand, and the simulation horizon before searching. A candidate may change bounded junction positions, valid edge connectivity, and optional facilities. It must not remove people or requested activities to improve its scores.

Reconstruct every design deterministically from named decisions. Validate coordinates, minimum node spacing, edge endpoints, and connectivity before simulation. Report invalid designs explicitly. Throw an evaluation error for runtime failures; do not reinterpret crashes as successful low-cost candidates.

The example uses 100 agents, eight fixed homes, up to six junctions, and four optional facilities serving two activity types. The planar site is 1,000 metres wide; nodes must remain at least 20 metres apart. Each agent requests two activities within a 480-minute horizon.

Measure simulation outcomes ​

Return finite metrics from the completed simulation:

  • Travel burden: sum travel minutes for fulfilled requests, add a 480-minute penalty for each unfulfilled request, then divide by all 200 requested activities.
  • Demand fulfilled: fulfilled requests divided by all requested activities, expressed as a percentage.
  • Construction proxy: installed edge length in metres + 100 × installed junctions + 500 × installed facilities. These are illustrative comparison units, not money.

Minimize travel and cost; maximize fulfilled demand. The unfulfilled-demand penalty prevents a design from improving travel merely by removing service. Use the same search seeds for every candidate (42 and 43 here). Validate finalists independently (142 and 143); retain both sets of evidence and label them separately.

Own workers once ​

Use Genetic Assembly's evaluator pool to run one candidate simulation per slot. Inside that slot, use grabm's local simulation engine; do not start another independent pool. The optimizer owns slot reuse, queue bounds, failure propagation, and cancellation. Initialize fresh simulation inputs and state for every evaluation.

ts
import { Optimizer, defineWorkerStudy } from '@genetic-assembly/sdk'
// Application adapter for this Vite example; the SDK core has no Vite dependency.
import SolverWorker from '@genetic-assembly/sdk/solver-worker?worker'

const optimizer = new Optimizer({
  evaluationConcurrency: workerCount,
  solverWorkerFactory: () => new SolverWorker(),
})
const study = defineWorkerStudy(
  spec,
  () =>
    new Worker(new URL('./evaluation.worker.ts', import.meta.url), { type: 'module' }),
  {
    validate: validateDesign,
    materialize: buildInput,
  },
)
const baseline = await (await optimizer.baseline(study)).completed()
const run = await optimizer.run(study, {
  populationSize: 24,
  generations: 12,
  seed: 42,
})

The example defaults its worker slider to browser-reported capacity, capped at the SDK's 64-worker limit, and permits values down to one. Worker count must not change decisions or simulation seeds. The solver itself runs in its own WASM worker. The explicit Vite worker import lets the application bundler emit the public SDK worker and its WASM asset, including under a non-root base path. It avoids relocating the worker into Vite's dependency prebundle, where relative WASM resolution breaks. Neither library core requires Vite; other applications supply solverWorkerFactory using their bundler's worker and asset conventions.

Observe SDK history ​

Follow run.events() for phases, active/queued evaluations, completed generations, and terminal status. Read exact surviving populations and fronts using run.generations(). Read aggregated candidates using run.candidates({generation}); use collectPages to retrieve every page. Do not infer generation membership from record timing or recalculate historical fronts in the application.

Population Pareto fronts and cumulative “best discovered so far” fronts answer different questions. The example charts the latter and keeps independent finalist validation in a separate view. SDK snapshots link candidate IDs to their decisions and measurements, allowing tables, charts, objective values, and the graph preview to select the same design.

Prepare playback on selection ​

Keep candidate decisions and measurements during search, rather than every agent trace. Selecting a candidate runs one replay with a documented seed. Reconstruct the graph from those exact decisions. A single-seed replay illustrates behavior; it is not the multi-seed aggregate objective score.

While the solver runs, show its progress in the playback scrubber area and preview evaluated designs at completed generations. After completion or cancellation, prepare the selected candidate's playback. Show playback preparation in that same area until ready. Terminate the previous replay worker and use a selection token so stale results cannot replace the latest selection.

Reuse grabm's playback controller and optional “Skip inactive time” toggle, initially off. Render agents with the theme accent token, and refresh Three.js materials on grabm:themechange. Dispose the optimizer, replay worker, controls, and renderer when navigating away. Keep completed history available after cancellation.

The implementation and its model/browser checks live under examples/optimization/. General operation, error, event, archive, and service contracts are documented in Genetic Assembly.

Packaging and portability ​

The vendored SDK tarball is a pinned release artifact, with integrity recorded in the lockfile; builds do not require the Genetic Assembly checkout. Once coordinated packages are published, a registry version can replace the tarball without changing the integration.

The public solverWorkerFactory accepts a module worker created by the application. Use the public solver-worker entry and configure your bundler to emit its WASM asset; Vite-specific query imports are optional. Application-specific graph decisions, objective metrics, charts, and packed playback stay under the example; neither library needs a dependency on the other library's private implementation.

Use OptimizationHandle (which extends OperationHandle<OptimizationResults>) to observe a search independently of its execution mode. Local and service optimizers share RunOptions, defaults, per-run concurrency overrides, and validate: false semantics. status() and cancel() return OperationStatus; wait(signal) stops observation when aborted without cancelling the work. Service setup still needs a prepared study and credentials; local setup supplies executable model code and owns its workers.

Documentation for the grABM library.