agentscript

0.10.16

Class Turtle instances represent the dynamic, behavioral element of modeling. Each turtle knows the patch it is on, and interacts with that and other patches, as well as other turtles. Turtles are also the end points of Links.

You do not call new Turtle(), instead class Turtles creates Turtle instances via Turtles#create or Turtles#createOne

I.e. class Turtles is a factory for all of it's Turtle instances. So don't do this:

new Turtle()
Instance Members
canMove(distance)
die()
distance(agent)
distanceXY(x, y, z)
dx
dy
face(agent)
facexy(x, y)
forward(d)
handleEdge(x, y, z)
hatch(num, breed, init)
heading
heading
isLinkNeighbor(t)
left(angle)
linkNeighbors()
moveTo(agent)
otherEnd(l)
patch
patchAhead(distance)
patchAt(dx, dy)
patchAtHeadingAndDistance(heading, distance)
patchLeftAndAhead(angle, distance)
patchRightAndAhead(angle, distance)
right(angle)
rotate(angle)
setxy(x, y, z)
subtractHeading(heading)
towards(agent)
towardsXY(x, y)

A Turtle is an object living on the Patches world. Their coordinates are floats, unlike Patches with integer coordinates. They can morph between types of turtles (breeds) and storee information, both within themselves but also on Patches and Links.

The Turtles (plural) array, (AgentSet) is a collection of Turtle objects that the Turtles array creates and manages.

You do not create either individual Turtle objects, the Turtles array does. You also do not create the Turtles array, class Model does.

You use both, however, using the methods they both provide.

new Turtles(model: Model, AgentClass: (Turtle | Turtle3d), name: string, baseSet: (null | Turtles))

Extends AgentSet

Parameters
model (Model) The model I belong to
AgentClass ((Turtle | Turtle3d)) The Turtle class
name (string) The name of this new Turtles instance
baseSet ((null | Turtles) = null) Used to create a breed subclass
Instance Members
closestTurtle(x, y, radius)
create(num, initFcn, number)
createOne(initFcn)
inCone(turtle, radius, coneAngle, meToo)
inPatches(patches)
inPatchRect(turtle, dx, dy, meToo)
inPatchRectXY(x, y, dx, dy, meToo)
inRadius(turtle, radius, meToo)
layoutCircle(radius, center)

Class Link instances form a link between two Turtles, forming a graph with the Turtles being the nodes, and the Links the edges.

TODO: Document Link properties and methods.

new Link()

Links are a collection of all the Link objects between turtles.

new Links()

Extends AgentSet

Class Patch instances represent a square on the Patches grid. They hold variables that are in the patches the turtles live on. The set of all patches is the world on which the turtles live and the model runs.

You do not use new Patch, rather Class Model creates the patches for you, using the World data passed to the Model.

You never do this:

new Patch()
Instance Members
breedsHere(breed)
isOnEdge()
neighbors
neighbors4
turtlesHere

Patches are the world other AgentSets live on. They define a coord system from the Model's World values: minX, maxX, minY, maxY, (minZ, maxZ) (z optional) Patches form a grid of Patch objects which can store world data (elevation, fires, ant pheromones, buildings, roads, gis spatial data, water and so on)

Created by class Model. Used by modeler in their Model subclass

new Patches(model: Model, AgentClass: Patch, name: string)

Extends AgentSet

Parameters
model (Model) An instance of class Model
AgentClass (Patch) The Patch class managed by Patches
name (string) Name of the AgentSet
Instance Members
exportDataSet(property, Type)
importDataSet(dataSet, property, useNearest)
neighbors(patch)
neighbors4(patch)
patchIndex(x, y)

A model's Patches, Turtles, Links, are all subclasses of AgentSet.

AgentSets are AgentArrays that are factories for their own Agents. That means you do not call new Turtle(), rather Turtles will create the Turtle instances, adding them to itself.

Finally, a Breed is simply a subarray of Patches, Turtles, Links. Patches could have a Streets breed, Turtles could have Cops and Robbers breeds, and Links Spokes and Rim breeds

AgentSets are not created directly by modelers. Instead, class Model creates them along with their Breeds. You can easily skip this initially, instead simply understand AgentSets are the basis for Patches, Turtles, Links & Breeds

new AgentSet(model: Model, AgentClass: (Patch | Turtle | Link), name: String, baseSet: (Patches | Turtles | Links))

Extends AgentArray

Parameters
model (Model) Instance of Class Model to which I belong
AgentClass ((Patch | Turtle | Link)) Class of items stored in this AgentSet
name (String) Name of this AgentSet. Ex: Patches
baseSet ((Patches | Turtles | Links) = null) If a Breed, it's parent AgentSet
Static Members
species
Instance Members
addAgent(o)
ask(fcn)
askSet(fcn)
clear()
getDefault(name)
isBaseSet()
isBreedSet()
newBreed(name)
protoMixin(agentProto, AgentClass)
removeAgent(o)
setBreed(a)
setDefault(name, value)
withBreed(breed)

Subclass of Array with convenience methods used by NetLogo. Tipically the items in the array are Objects but can be any type.

new AgentArray(args: any)

Extends Array

Parameters
args (any) Zero or more items in Array
Static Members
fromArray(array)
species
Instance Members
all(fcn)
ask(fcn)
atIndex(i)
clone()
first()
forLoop(fcn)
isEmpty()
last()
props(key, type)
sortBy(reporter, ascending)
toArray()
typedSample(obj)
uniq()
with(fcn)

The Model

Class Model2D is the primary interface for modelers, integrating the Patches/Patch Turtles/Turtle and Links/Link AgentSets .. i.e.:

  • model.Patches: an array Patches of Patch instances
  • model.Turtles: an array Turtles of Turtle2D instances
  • model.Links: an array Links of Link instances
  • model.breed: a sub-array of any of the three above.
  • All of which are subclasses of AgentSet.

Note: Our default class Model differes only in that

Convention: Three abstract methods are provided by the modeler

  • Startup(): (Optional) Called once to import images, data etc
  • Setup(): Called to initialize the model state.
  • Step(): Step the model. Will advance ticks.
new Model2D(worldOptions: (Object | World))
Parameters
worldOptions ((Object | World) = World.defaultOptions()) Can be Object of min/max X,Y,Z values or an instance of World
Instance Members
linkBreeds(breedNames)
patchBreeds(breedNames)
reset(worldOptions)
setup()
startup()
step()
tick()
turtleBreeds(breedNames)

Model3D uses Model2D with one change:

Model3D is our default Model.

new Model3D(worldOptions: (Object | World))

Extends Model2D

Parameters
worldOptions ((Object | World) = World.defaultOptions()) Identical to Model2D

This is our default Model which simply re-exports Model3D Thus when using:

import Model from './Model.js'

..you will be using ./Model3D

Model
Parameters
worldOptions ((Object | World) = World.defaultOptions()) Identical to Model3D

Class World defines the coordinate system for the model. It has transforms for multiple coordinate systems.

The world is defined by an object with 6 properties:

     WorldOptions = {
         minX: integer,
         maxX: integer,
         minY: integer,
         maxY: integer,
         minZ: integer,
         maxZ: integer,
     }
new World(options: (World | WorldOptions | Object))
Parameters
options ((World | WorldOptions | Object) = {}) Object with overrides for class properties
Static Members
defaultOptions(maxX, maxY, maxZ)
defaultWorld(maxX, maxY, maxZ)
Instance Members
bboxTransform(minX, minY, maxX, maxY)
getOptions()
isOnWorld(x, y, z)
random3DPoint()
randomPatchPoint()
randomPoint()

The View

Basic 2D view.

TODO: Document this class

new TwoDraw(model: any, viewOptions: any, drawOptions: any)

Extends TwoView

Parameters
model (any)
viewOptions (any = {})
drawOptions (any = {})

Basic 3D view.

TODO: Document this class

new ThreeDraw(model: any, viewOptions: any, drawOptions: any)

Extends ThreeView

Parameters
model (any)
viewOptions (any = {})
drawOptions (any = {})

A general color module, supporting css string colors, canvas2d pixel colors, webgl and canvas2d Uint8ClampedArray r,g,b,a arrays.

CSS Color Strings.

CSS colors in HTML are strings, see Mozillas Color Reference, taking one of 7 forms:

  • Names: over 140 color case-insensitive names like Red, Green, CadetBlue, etc.
  • Hex, short and long form: #0f0, #ff10a0
  • RGB: rgb(255, 0, 0), rgba(255, 0, 0, 0.5)
  • HSL: hsl(120, 100%, 50%), hsla(120, 100%, 50%, 0.8)

See this wikipedia article on differences between HSL and HSB/HSV.

Color
Static Members
hslCssColor(h, s, l, a)
rgbaCssColor(r, g, b, a)

Interaction

A NetLogo-like mouse handler.

TODO: Example usage.

new Mouse(canvas: any, world: any, callback: any)
Parameters
canvas (any)
world (any)
callback (any = (evt,mouse)=>{})

Data

A DataSet is an object with width/height and an array of numbers of length = width * height.

The array can be a TypedArray or a JavaScript Array.

new DataSet(width: number, height: number, data: array)
Parameters
width (number) The integer width of the array
height (number) The integer height of the array
data (array) The array of numbers of length width * height
Static Members
emptyDataSet(width, height, Type)

Utilities

An assortment of helper functions. To use: import * as util from src/utils.js.

Clamp a float to be between [min, max).

clamp(v: number, min: number, max: number): number
Parameters
v (number) value to clamp between min & max
min (number) min value
max (number) max value
Returns
number: a float between min/max

createCanvas

src/utils.js

Create a blank 2D canvas of a given width/height.

createCanvas(width: number, height: number, offscreen: boolean): Canvas
Parameters
width (number) The canvas height in pixels
height (number) The canvas width in pixels
offscreen (boolean = offscreenOK()) If true, return "Offscreen" canvas
Returns
Canvas: The resulting Canvas object

createCtx

src/utils.js

As above, but returing the 2D context object instead of the canvas. Note ctx.canvas is the canvas for the ctx, and can be use as an image.

createCtx(width: number, height: number, offscreen: boolean): Context2D
Parameters
width (number) The canvas height in pixels
height (number) The canvas width in pixels
offscreen (boolean = offscreenOK()) If true, return "Offscreen" canvas
Returns
Context2D: The resulting Canvas's 2D context

Convert from degrees to radians

degToRad
Parameters
degrees (number) a value in degrees: in [0, 360)
Returns
number: the value as radians: in [0, 2PI)

headingToRad

src/utils.js

Convert from heading to radians

headingToRad(heading: number): number
Parameters
heading (number) a value in degrees: in [0, 360)
Returns
number: a value in radians: in [0, 2PI)

imagePromise

src/utils.js

Return a Promise for getting an image.

use: imagePromise('./path/to/img').then(img => imageFcn(img)) or: await imagePromise('./path/to/img')

imagePromise(url: URL): Promise
Parameters
url (URL) string for path to image
Returns
Promise: A promise resolving to the image

A true modulus function, differing from the % remainder operation.

mod
Parameters
v (number) The value to calculate the modulus of
n (number) The number relative to which the modulus is calculated.
Returns
number: The value of v mod n

Return random item from an array

oneOf
Parameters
array (any)
An (Array) array to choose from
Returns
any: The chosen item

precision

src/utils.js

Round a number to be of a given decimal precision. If the number is an array, round each item in the array

precision(num: (number | Array), digits: number): number
Parameters
num ((number | Array)) The number to convert/shorten
digits (number = 4) The number of decimal digits
Returns
number: The resulting number

Convert from radians to degrees

radToDeg
Parameters
radians (number) a value in radians: in [0, 2PI)
Returns
number: the value as degrees: in [0, 360)

radToHeading

src/utils.js

Convert from radians to heading

Heading is 0-up (y-axis), clockwise angle measured in degrees. Radians is euclidean: 0-right (x-axis), counterclockwise in radians

radToHeading(radians: number): number
Parameters
radians (number) a value in radians: in [0, 2PI)
Returns
number: a value in degrees: in [0, 360)

randomCentered

src/utils.js

Return a random float centered around r, in [-r/2, r/2)

randomCentered
Parameters
r (number) The center float
Returns
number: a float in [-r/2, r/2)

randomFloat

src/utils.js

Returns a random float in [0, max)

randomFloat
Parameters
max (number) The max float to return
Returns
number: a float in [0, max)

randomFloat2

src/utils.js

Returns a random float in [min, max)

randomFloat2
Parameters
min (number) The min float to return
max (number) The max float to return
Returns
number: a float in [min, max)

randomInt

src/utils.js

Returns an int in [0, max), equal or grater than 0, less than max

randomInt
Parameters
max (number) The max integer to return
Returns
number: an integer in [0, max)

randomInt2

src/utils.js

Returns an int in [min, max), equal or grater than min, less than max

randomInt2
Parameters
min (number) The min integer to return
max (number) The max integer to return
Returns
number: an integer in [min, max)

randomSeed

src/utils.js

Install a seeded random generator as Math.random Uses an optimized version of the Park-Miller PRNG.

Math.random will return a sequence of "random" numbers in a known sequence. Useful for testing to see if the same results occur in multiple runs of a model with the same parameters.

randomSeed(seed: number)
Parameters
seed (number = 123456)

Repeats the function f(i, a) i in 0, n-1. a is an optional array, default a new empty Array returns a, only needed if f() places data in a

repeat(n: number, f: function, a: Array): Array
Parameters
n (number) An integer number of times to run f()
f (function) The function called.
a (Array = []) An optional array for use by f()
Returns
Array: The result of calling f() n times

sampleModel

src/utils.js

Return an object with samples of the models components. Useful for testing Models without needing a View, just data.

sampleModel(model: Model): Object
Parameters
model (Model) A model to sample
Returns
Object: An object with all the samples

setCtxImage

src/utils.js

Fill this context with the given image, resizing it to img size if needed.

setCtxImage(ctx: Context2D, img: Image)
Parameters
ctx (Context2D) a canvas 2D context
img (Image) the Image to install in this ctx

subtractHeadings

src/utils.js

Subtract two headings, returning the smaller difference.

Computes the difference between the given headings, that is, the number of degrees in the smallest angle by which heading2 could be rotated to produce heading1 See NetLogo's subtract-headings for explanation

subtractHeadings
Parameters
head1 (number) The first heading in degrees
head0 (number) The second heading in degrees
Returns
number: The smallest andle from head0 to head1

timeoutLoop

src/utils.js

Use timeoutPromise for an animation loop. Calls the fcn each step Stops after steps calls, negative means run forever

timeoutLoop(fcn: function, steps: number, ms: number)
Parameters
fcn (function) The function to be called.
steps (number = -1) How many times.
ms (number = 0) Number of ms between calls.

timeoutPromise

src/utils.js

Return promise for pause of ms. Use: await timeoutPromise(ms)

timeoutPromise(ms: number): Promise
Parameters
ms (number = 1000) Number of ms to pause
Returns
Promise: A promise to wait this number of ms

Merge a module's obj key/val pairs into to the global/window namespace. Primary use is to make console logging easier when debugging modules.

toWindow(obj: Object)
Parameters
obj (Object) Object who's key/val pairs will be installed in window.

Class Turtle3D subclasses Turtles, adding 3D methods using Three.js's Object3D module. See NetLogo who's 3D semantics we follow.

Just as with Turtle, you do not call new Turtle3D(), instead class Turtles creates Turtle3D instances via Model modifying the Turtles/Turtle3D initialization.

3D is the default. To revert to 2D, see Model2D

Again, class Turtles is a factory for all of it's Turtle3D instances. So don't do this:

new Turtle3D()

Extends Turtle2D

xhrPromise

src/utils.js

Return Promise for ajax/xhr data.

type: 'arraybuffer', 'blob', 'document', 'json', 'text'. method: 'GET', 'POST' use: xhrPromise('./path/to/data').then(data => dataFcn(data))

xhrPromise(url: UTL, type: string, method: string): any
Parameters
url (UTL) A URL path to the data to be retrieved
type (string = 'text') The type of the data
method (string = 'GET') The retrieval method
Returns
any: The resulting data of the given type