agentscript

0.10.11

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. They are also the end points of Links.

You do not call new Turtle(), instead class Turtles creates it's Turtle instances. I.e. class Turtles is a factory for all of it's Turtle instances. So don't do this:

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

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
createOne(initFcn)
create(num, initFcn)
closestTurtle(x, y, radius)
inPatches(patches)
inPatchRect(turtle, dx, dy, meToo)
inPatchRectXY(x, y, dx, dy, meToo)
inRadius(turtle, radius, meToo)
inCone(turtle, radius, coneAngle, 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.

TODO: Document Patch properties and methods.

new Patch()
Instance Members
neighbors
neighbors4

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
neighbors(patch)
neighbors4(patch)
importDataSet(dataSet, property, useNearest)
exportDataSet(property, Type)
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
protoMixin(agentProto, AgentClass)
newBreed(name)
isBreedSet()
isBaseSet()
withBreed(breed)
addAgent(o)
clear()
removeAgent(o)
setDefault(name, value)
getDefault(name)
setBreed(a)
ask(fcn)
askSet(fcn)

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
species
fromArray(array)
Instance Members
toArray()
isEmpty()
first()
last()
atIndex(i)
all(fcn)
props(key, type)
typedSample(obj)
uniq()
forLoop(fcn)
ask(fcn)
with(fcn)
clone()
sortBy(reporter, ascending)

The Model

Class Model 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 Turtle 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).

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 if autoTick = true in constructor.
new Model(worldOptions: (Object | World), autoTick: boolean)
Parameters
worldOptions ((Object | World) = World.defaultOptions()) Can be Object of min/max X,Y,Z values or an instance of World
autoTick (boolean = true) Automatically advancee tick count each step if true
Instance Members
reset(worldOptions)
reset(worldOptions)
tick()
tick()
startup()
startup()
setup()
setup()
step()
step()
patchBreeds(breedNames)
patchBreeds(breedNames)
turtleBreeds(breedNames)
turtleBreeds(breedNames)
linkBreeds(breedNames)
linkBreeds(breedNames)
setGeometry(name)

Class Model 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 Turtle 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).

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 if autoTick = true in constructor.
new Model(worldOptions: (Object | World), autoTick: boolean)
Parameters
worldOptions ((Object | World) = World.defaultOptions()) Can be Object of min/max X,Y,Z values or an instance of World
autoTick (boolean = true) Automatically advancee tick count each step if true
Instance Members
reset(worldOptions)
reset(worldOptions)
tick()
tick()
startup()
startup()
setup()
setup()
step()
step()
patchBreeds(breedNames)
patchBreeds(breedNames)
turtleBreeds(breedNames)
turtleBreeds(breedNames)
linkBreeds(breedNames)
linkBreeds(breedNames)
setGeometry(name)

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
getOptions()
randomPoint()
random3DPoint()
randomPatchPoint()
isOnWorld(x, y, z)
bboxTransform(minX, minY, maxX, maxY)

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
rgbaCssColor(r, g, b, a)
hslCssColor(h, s, l, 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.

imagePromise

src/utils.js

Return a Promise for getting an image.

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

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

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

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

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.

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

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

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.

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)

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)

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)

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)

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

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

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

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)

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)

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)

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

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

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

Return random item from an array

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