Language Functions - sandialabs/n2a GitHub Wiki

All backends are expected to support these functions, though exceptions may exist in practice. If a backend does support a function listed here, then it must follow the given semantics exactly. Any function not listed here has arbitrary semantics defined by the backend, and is less likely to be portable.

Most "three letter" functions have the same meaning as typically defined by the C standard library. The semantics of real-valued functions (that is, R->R) are extended to act as a visitor on the elements of matrix. Thus, cos(M) is the same as cos(m) for all elements m of M, and the return value is another matrix with the processed elements. Exceptions to this rule are noted below.

All angles are in radians unless noted otherwise.

A=connect(name,...)

Declares that A is a reference to a connected part. The list of part names is a hint about what this connection expects. Connections may be made to any part that has the right structure, even if it is not listed. Connection references are typically named capital letters at the start of the alphabet, but they can be named anything.

This is an abuse of notation rather than a true function. The compiler will issue an error if it encounters connect() in the final model. The user should replace connect() with the actual connection target.

abs(a)

Absolute value of a.

atan(a)
atan(y,x)

Inverse of the tangent function. If two parameters are given, the resulting angle can occur anywhere on the full circle. With only one parameter, the result is in the right half-cirle. If a vector is given, the first row will be treated as x and the second row as y.

ceil(a)

Returns the closest integer greater than or equal to a.

columns(M)

Get the number of columns in matrix M.

cos(angle)

Cosine of angle.

delay(value,delta,default)

Uses a buffer to delay input value for delta seconds. Outputs the default value until a delayed value becomes available. After that, the output remains at the last available value until another one arrives. Not the same as an exponential delay. Rather, this function uses storage proportional to the number of simulation steps spanned by delta, and returns exactly the same value as was input.

If no default is specified, then output is zero until first value becomes available.

If no delta is specified, then this function returns the value immediately. This will prevent a one-step delay from being optimized away by the compiler. For example:

a = b
c = a + 1

gets optimized to

c = b + 1

However, if your intention is to introduce one simulation cycle of delay in the value of b, then you can write:

a = delay(b)
c = a + 1

draw{shape}("filename",p,...)

Functions with the prefix "draw" produce visualizations. Function calls which share the same filename write to the same image buffer. The current image is flushed to disk when $t advances, and the buffer is cleared to start the next visualization. If both 2D and 3D drawing functions are called during a given cycle, then the 2D marks overlay the 3D rendering.

3D drawing follows the conventions of classic OpenGL. This includes how to position the camera, light the scene, and color objects. There are many online resources (of widely varying quality) to explain these concepts. Default values are set up for rendering a medium-sized neuron centered at the origin with its major axes on the xy plane. The gl* functions generate 4x4 transformation matrices that are useful for configuring 3D draw functions.

There is a use for the generic draw() function with no shape. The canvas configuration (such as size, background color or 3D projection matrix) becomes locked after the first drawX() call. Subsequent changes are held until the next cycle starts. It is not possible to predict or control which part evaluates first and thus which drawX() occurs first. One solution is to set the same canvas arguments on every drawX(), but this tedious. The real issue is how to configure the canvas properly in cycle 0. During the init cycle (and only then), there is a guarantee that the parent executes before any of its children. A generic call to draw() will configure the canvas without making marks on it. Within a single equation set, the compiler will attempt to order equations with generic draw() ahead of drawX() equations.

  • filename -- Format is determined by suffix. Video formats that support variable framerate will use the value of $t as timestamp. To specify a sequence of still images, include %d in the name. These will be stored in a subdirectory. For example, "frame%d.png" will be stored as jobDir/frame/0.png, 1.png, 2.png, and so on. When FFmpeg is available on your system, filename is fed directly as the URL for opening an output container, so a wide range of FFmpeg features become possible.

  • p -- Position of the shape, specified by a vector. For 2D drawing functions, origin is at upper-left. The first coordinate is horizontal position, increasing to the right. The second coordinate is vertical position, increasing downward. Both values are in [0,1] unless the raw flag is specified. For 3D drawing functions, the vector follows OpenGL conventions for world space. The default value for 3D is the origin, [0;0;0]. The raw flag does not apply to 3D coordinates. For generic draw(), p is ignored and should be omitted.

2D functions specify object color as a positional parameter, usually in last place. Default is opaque white. 3D functions use keyword arguments to specify material properties. In the simplest case, use "diffuse" to specify the object color. See below for a detailed list of material properties.

Color values can be expressed as either an integer or a vector. Integers can be written in decimal or hexadecimal. Format is RGB: 8 bits per color channel, occupying the lower 24 bits of the integer, with red in the most significant position. An integer color is always fully opaque. A color vector has up to 4 elements, ordered as RGBA, with values in [0,1]. If the 4th element is omitted, it assumed to be fully opaque (A=1).

Keyword arguments for output file

  • format={name} -- Specifies the container/file format, overriding the file suffix if present. Name follows FFmpeg command-line convention.
  • codec={name} -- Specifies the encoding algorithm. Some containers support several different codecs. This overrides the default. Name follows FFmpeg command-line convention.
  • timeScale={multiplier} -- Rescales $t before converting it to a presentation time stamp (PTS). The default value of 0 causes the video to play at 24 frames per second, regardless of $t. Otherwise, the value must be positive. This sets the relationship between simtime and walltime when viewing the video, allowing you to slow playback to a reasonable speed. For example, with $t'=1ms and timeScale=33, the video plays at roughly 30 frames per second. That is, each millisecond of simtime occupies 33ms of walltime for the human watching the video.

Keyword arguments for canvas setup

  • hold=1 -- Instead of an image sequence, a single image accumulates marks over multiple cycles. Any changes to canvas configuration are ignored until hold becomes zero again.
  • clear={color} -- Initial color of blank canvas. Default is opaque black. It is possible to set a transparent background, and some image formats can represent this.
  • width={pixels} -- Size of image in pixels. If only one of height or width is specified, then the image is square. Default is 1024. Note that for some video formats, each dimension will be rounded up to the nearest multiple of 16 pixels.
  • height={pixels} -- See above.
  • view={matrix} -- The camera position. Strictly speaking, this is the inverse of the matrix that rotates and translates the camera into the world frame. Combines with projection matrix to fully specify the camera. Default value is identity, equivalent to the camera looking along the negative z axis, with y up and x to the right.
  • projection={matrix} -- The deformation between the camera and clip coordinates. The full camera matrix = projection * view. Default value sets orthographic projection within a cube 100um across, centered at the origin. This is comparable to viewing a single neuron through a microscope.

Keyword arguments for specific drawX() call

  • raw=1 -- For 2D drawing functions, interpret position and scale as integer pixel values.
  • diffuse={color} -- The main color of a 3D object. Reflects light based on angle and distance from source. This is the only material property that accepts a transparency component. Default is 80% gray at full opacity, [0.8;0.8;0.8;1].
  • ambient={color} -- Non-directional color of a 3D object. This is in response to non-directional light in the scene. At least one light source has to be set up to emit this kind of light for this color to show up. Default is 20% gray, [0.2;0.2;0.2].
  • emission={color} -- Amount of light the 3D object emits, regardless of incoming light. This can create a glow or fluorescent effect. This light will not be reflected by other objects. See drawLight() for how to add light sources to a scene. Default is black, [0;0;0].
  • specular={color} -- Shiny reflection color of a 3D object. A good rule-of-thumb is that metals (electrically conductive) reflect the same color as diffuse, while organic materials (non-conductive) reflect white. Default is black, [0;0;0]
  • shininess={scalar} -- The exponent on the specular reflection value of a 3D object. Larger values produce a sharper bright spot. Default is 0.
  • model={matrix} -- A matrix that projects the 3D base object into the world, following the model-view-projection convention in OpenGL. The model matrix can include modifications to shape such as scaling and rotation. While this matrix can move the object, 3D drawing functions also respect the position argument. That offset is applied last. Since transformations are applied right to left, this is equivalent to glTranslate(p)*model. If position is zero or omitted, then the model matrix is applied without change.

drawCube("filename",center)

Draws a cube in 3D. See draw() for general description of drawing functions. The base cube is centered at the origin with a width of 1 along each axis. For example, one edge has vertices at (0.5;0.5;0.5) and (0.5;0.5;-0.5).

  • center -- Optional translation. Default is (0;0;0). This is redundant with the model matrix. Parameters are applied as glTranslate(center)*model.

Keyword arguments

  • model -- Produces different width, height, depth and orientation. For example: model=glRotate(-10,0,0,1)*glScale(4,9,1) will produce a Monolith (per "2001 A Space Odyssey") that's leaning a bit to the right (assuming camera at default position).

drawCylinder("filename",p1,r1,p2,r2)

Draws a cylinder in 3D. See draw() for general description of drawing functions. The start and end of the cylinder may be different sizes, and openings of the tube may be capped in different ways. This supports, for example, creating visualizations of a neuron soma and dendritic processes. Since the segments need to be chained end-to-end, you might set the start cap to none (open) and the end cap to rounded. This lets the cylinders fit together and make small bends without opening up a gap in the overall surface.

  • p1 -- Start position.
  • r1 -- Radius of cylinder at start. If zero, then draws a cone with the tip at p1.
  • p2 -- End position. Must be different than p1, or nothing will be drawn.
  • r2 -- Radius of cylinder at end. If zero, then draws a cone with the tip at p2. Default value is to match r1 (straight tube).

Keyword arguments

  • cap1={0,1,2} -- Indicates how to fill the hole at the start of the cylinder. 0=open, 1=flat, 2=rounded. Default is 0.
  • cap2={0,1,2} -- Indicates how to fill the hole at the end of the cylinder. See above.
  • steps={count} -- How many sides the tube should have. This controls level of effort and quality of the rendering. Default is 6.
  • stepsCap={count} -- How many rings should the hemisphere on the end have. This controls level of effort and quality of the rendering. Default is steps/4. A value of 0 produces a cone.

Currently does not accept "model" as a keyword argument, since the shape is fully specified by positional arguments.

drawDisc("filename",center,radius,color)

Draws a filled circle in 2D, with no separate stroke for the border. See draw() for general description of drawing functions.

  • radius -- Size of circle, scaled the same way as center. A value of 1 means radius (not diameter) is full width of image. If mode is "raw", then radius is in pixels. Default value is 0, which produces the smallest possible disc (a single pixel) regardless of scaling mode.

drawLight("filename",index)

Sets up a light source at the given position in 3D. See draw() for general description of drawing functions. Lights function similarly to basic canvas setup. They must be in place before any 3D objects are drawn. If a light is changed after the first 3D object is drawn, the change takes effect at the start of the next cycle. If no lights are explicitly specified, then a single default light is created automatically.

Lights can be configured in roughly four ways, based on how direction and position are handled. An ambient light provides non-directional illumination in the scene. This is created by setting the ambient color to something besides black. Any light can have an ambient component. A "sun" light is positioned at infinity, so only the direction matters, not location. All rays in the scene are parallel. A "spot" light emits a cone from its position in a given direction, and the light may also dim with distance from the center of the cone. A point light shines in all directions. It's similar to a spotlight but without falloff or a limiting cone. All four configurations can be created with various combinations of the keyword arguments. The default is a point light.

  • index -- An integer value identifying the source. You can create any number of these, but only the first 8 are guaranteed to exist. The indices do not need to be contiguous.

Keyword arguments

  • on={0 or 1} -- Turns the light on or off. Default is 1 (on). This argument is only needed if you want to disable a light created by a previous call to drawLight().
  • position={vector or 0} -- In world coordinates. If this is instead set to the scalar 0, then this is a sun lamp shining from infinity, and only direction matters. Default is [0;0;1].
  • direction={vector} -- Where a spotlight or sun are pointing. Default is along the negative z-axis, [0;0;-1]
  • ambient={color} -- Color of non-directional light, reflected by the ambient surface property of 3D objects. Default is black, [0;0;0].
  • diffuse={color} -- Color of directional light reflected by the diffuse surface property of 3D objects. Default is white, [1;1;1].
  • specular={color} -- Color of directional light that produces shiny reflections on 3D objects. Default is white, [1;1;1].
  • spotExponent={scalar} -- A vector from the light to the object will form an angle with the direction vector. This parameter determines how intensity falls off as a function of that angle. This causes a spotlight to soften as the object moves away from the center of the cone. Default is 0 (no falloff).
  • spotCutoff={angle in degrees} -- Hard limit on the angle between the object and the direction vector. This creates a cone, outside of which the light stops. Can be in [0,90], or 180 to disable cutoff checking. Default is 180.
  • attenuation0={scalar} -- Light can decrease power over distance according to the formula 1 / (a0 + a1r + a2r2). Default value is 1 (no attenuation).
  • attenuation1={scalar} -- See above. This kind of fall off can occur from traveling through an absorbent material like air. Default is 0 (no attenuation).
  • attenuation2={scalar} -- See above. This kind of fall off occurs even in a vacuum, due to spreading the energy over an ever-increasing amount of area. Default is 0 (no attenuation).

drawPlane("filename",center)

Draws a flat square in 3D. See draw() for general description of drawing functions. The base object is in the x-y plane, centered at the origin, facing along the positive z axis, with a width and height of 1.

  • center -- Optional translation. Default is [0;0;0]. This is redundant with the model matrix. Parameters are applied as glTranslate(center)*model.

Keyword arguments

  • model -- Produces different width, height and orientation.

drawSegment("filename",p1,p2,width,color)

Draws a line between two points in 2D. See draw() for general description of drawing functions.

  • p1,p2 -- Start and end points for line segment.

  • width -- Total thickness of line, scaled the same way as p1 or p2. A value of 1 means full width of image. If mode is "raw", then width is in pixels. Default value is 0, which produces the thinnest possible line (a single pixel) regardless of scaling mode.

drawSphere("filename",center,radius)

Draws a ball in 3D. See draw() for general description of drawing functions.

  • center -- Optional translation. Default is [0;0;0]. This is redundant with the model matrix. Parameters are applied as glTranslate(center)*model*glScale(radius).

  • radius -- Optional uniform scaling. Default is 1. See above for how parameters are applied.

Keyword arguments

  • steps -- Number of subdivision levels to use. 0 means basic icosphere, a 20-face polyhedron. Each level after that adds one subdivision. This cuts the edges in half with new vertices. One step of subdivision creates 4 new faces to replace each previous face. Be careful! The number of faces is 20*4steps, so steps=10 is about 20 million faces. Default is 1 (80 faces).
  • model -- This enables you to turn the sphere into an ellipse at some orientation. For example: model=glRotate(45,0,0,1)*glScale(1,2,1) will make a sphere elongated on the y axis then rotated 45 degrees around the z axis.

drawSquare("filename",center,width,height,color)

Draws a filled rectangle in 2D, with no separate stroke for the border. See draw() for general description of drawing functions.

  • width,height -- Size of block, scaled the same way as center. A value of 1 means full width of image. If mode is "raw", then values are in pixels rather than a portion of image width. Default value is 0, which produces the smallest possible block (a single pixel) regardless of scaling mode.

equal(A,B)

Tests for matrix equality. Only true if A and B have the same shape and every corresponding element is equal.

event(expression,delta,"trigger")

Indicates that expression satisfied the trigger condition at a time delta seconds in the past. This function has two effects. It wakes the instance in which it appears, and returns 1 during the first cycle following the delivery of the event. Returns 0 in all subsequent cycles, until another event is received.

  • expression -- Typically a variable from a connected part, which we wish to monitor for some change. May also be a more complex expression. For example, it may compare a variable to a certain threshold value.

  • delta -- Number of seconds from when the expression triggers the event until it wakes this instance. Simulators should make best effort to wake the instance at the exact time, but the actual delivery of the event could be earlier or later than the requested delta. For example, a fixed-step simulator may quantize delta to the nearest time step. Also note that in larger (cluster) computers, events may arrive out of order or even get lost in transit. Handling of anachronistic events is simulator specific.
    Default if delta is unspecified is to process the event in the next regularly scheduled cycle for this part (no-care). You can also specify no-care with any negative number.
    A delta value of 0 means no simulation time should pass. If possible, the simulator will insert a cycle 0 seconds after the current one.

  • trigger -- A constant string which indicates which kind of change to monitor for. Default is "rise".

    • "rise" -- Trigger an event when the value of expression changes from 0 to nonzero.
    • "fall" -- Trigger when the value goes from nonzero to 0.
    • "change" -- Any difference in value, of any magnitude or sign.
    • "nonzero" -- An event is generated every cycle in which expression is nonzero, even if the value is not changing.

exp(a)

Raise the base of the natural logarithm to the power a, that is, ea.

floor(a)

Returns the closest integer less than or equal to a.

gaussian(sigma)

Returns a random draw from a Gaussian distribution with mean 0 and variance sigma2. See uniform().

  • sigma – Scales the random value and determines dimensionality of the result. If sigma is a scalar, the result is a scalar. If sigma is a matrix, the result is effectively sigma*g, where g is vector of Gaussian draws with variance 1. If sigma is a vector, it is treated as the diagonal of a matrix. Default sigma is 1.
    Notice that sigma is not the covariance of the distribution, but rather the square-root of the covariance.

glFrustum(left,right,bottom,top,near,far)

Returns a 4x4 perspective projection matrix. The frustum is defined in the camera's local coordinate frame (view space rather than world space). This prepares a value for the "projection" argument of 3D draw(). See the OpenGL man page for how the matrix is generated.

  • left,right -- The edges of the near plane on the x axis.

  • top,bottom -- The edges of the near plane on the y axis.

  • near,far -- Distance to the near and far planes along the z axis. Both planes have the same shape described by the {left,right,top,bottom} parameters, except the far plane is larger in area because it is projected from the near plane. Both values are positive.

glLookAt(eye,center,up)

Returns a 4x4 matrix that will position the camera at "eye", looking toward "center", with vertical axis aligned with "up". This prepares a value for the "view" argument of 3D draw(). See the OpenGL man page for how the matrix is generated.

  • eye -- Location of the camera as a 3-vector.

  • center -- Location to look at, as a 3-vector.

  • up -- A direction vector that the vertical axis of the camera should align with. It doesn't have to be exactly perpendicular to the direction the camera points, because this function will perform some normalizations (cross products) to produce an orthonormal frame.

glOrtho(left,right,bottom,top,near,far)

Returns a 4x4 orthographic projection matrix that defines a rectangular region of space visible to the camera. The rectangle is defined in the camera's local coordinate frame (view space rather than world space). This prepares a value for the "projection" argument of 3D draw(). See the OpenGL man page for how the matrix is generated.

  • left,right -- Position of sides on the x axis.

  • bottom,top -- Position of sides on the y axis.

  • near,far -- Position of sides on the z axis. Negative numbers are behind viewer. (This violates the convention that the camera points toward the negative z axis, but this is how OpenGL has defined the function for decades.)

glPerspective(fovy,aspect,near,far)

Returns a 4x4 perspective projection matrix. The frustum is defined in the camera's local coordinate frame (view space rather than world space). This prepares a value for the "projection" argument of 3D draw(). See the OpenGL man page for how the matrix is generated.

  • fovy -- The viewing angle in degrees.

  • aspect -- The ratio width/height, where width and height are usually the pixel size of the canvas.

  • near -- Distance from camera to the near clip plane. Must be positive.

  • far -- Distance from camera to the far clip plane. Must be positive.

glRotate(angle,axis)
glRotate(angle,x,y,z)

Returns a 4x4 matrix that rotates objects around the given axis following the right-hand rule. That is, if you grasp the axis with your right hand such that your thumb points in the direction of the vector, then a positive number rotates in the direction your fingers curl. This prepares a value for the "model" argument of 3D draw(). See the OpenGL man page for how the matrix is generated.

  • angle -- In degrees.

  • axis -- A 3-vector.

  • x,y,z -- The axis as individual components.

glScale(scales)
glScale(sx,sy,sz)

Returns a 4x4 matrix that changes the size of an object along each of the 3 principle directions. The scaling along each axis need not be the same as the others. This prepares a value for the "model" argument of 3D draw(). See the OpenGL man page for how the matrix is generated.

  • scales -- A 3-vector of the scale along each axis.

  • sx,sy,sz -- The scales as individual components.

glTranslate(position)
glTranslate(x,y,z)

Returns a 4x4 matrix that shifts the position of an object. This prepares a value for the "model" argument of 3D draw(). See the OpenGL man page for how the matrix is generated.

  • position -- A 3-vector.

  • x,y,z -- The position as individual components.

grid(i,nx,ny,nz)

Returns a point in space as a 3-vector. Output is scaled to fit in a unit cube.

  • i -- The index of the current element. Typically this would be $index.
  • nx,ny,nz -- The number of elements along each dimension. Default is 1.

Keyword arguments

  • raw=1 -- Returns a vector of integer indices rather than tessellating a unit cube. Used for finer control over the offset of the resulting coordinates, typically something of the form: $xyz=grid(...)&scaling+offset

In default mode, this function assumes you are tessellating a region of space by equal-sized blocks, and that each element is at the center of its block. Thus, grid($index,10) would produce x coordinates: 0.05,0.15,0.25...,0.95. (Without additional parameters, the y and z coordinate would both be 0.5.) You may multiply the output of grid() by a matrix or add an offset vector to obtain other patterns. If you wish to achieve a different ordering of the dimensions (for example z-major) then multiply by a permutation matrix.

image("filename",color,time)

Reads a 2D pixel raster from the file, and returns a matrix of the given color channel. Note that some video formats allow the number of pixels to vary between frames.

  • filename -- Follows FFmpeg URL conventions.

  • color -- String that names a color channel. Default is "Y".

    • R, G, B -- Linear sRGB space
    • R', G', B' -- Non-linear sRGB space with gamma=2.4
    • X, Y, Z -- CIE XYZ space
    • H, S, V -- Hue, saturation, value. Based on linear sRGB.
  • time -- In seconds, based on presentation time stamp (PTS) in the video file. The first frame is the reference point for time 0, and all subsequent frames are relative to that. Given two sequential frames A and B, with times a and b, frame A will be returned for the entire period [a,b). If time is omitted, the system will step to the next frame each simulation cycle. If this is a single still image, time is ignored. If this is an image sequence, frame period is assumed to be 1 second.

input("filename",line,column)

Retrieves a value from the named file, or from standard input (stdin) if filename is the empty string. This function is designed for streaming input, so it only reads the file in the forward direction. The stream must be formatted as a row of numbers separated by delimiter characters (one of space, tab, or comma) and terminated by the OS-specific combination of LF and CR characters. A column may be empty (a delimiter may be followed immediately by another delimiter), in which case the effective value is 0.

  • line -- indicates number of line terminations (CR/LF combinations) that must precede the current row of data. It starts at zero and increases monotonically. Header rows are not included in the count. Passing a number less than or equal to the previous value retrieves the same line from the file (no movement). Passing a number greater than the previous value cause the system to read forward until the requested line is received. In general, the passed value will be truncated to the integer less than or equal to it. If you wish to retrieve a new line per time step of the simulation, pass round($t/$t').

  • column -- indicates position within the row of data. Must be in [0, columns-1]. If omitted or less than 0, returns a horizontal vector of all current values. If greater than columns-1, the last column will be returned. If there are no columns (or file could not be opened), return value is 0. The column position may also be specified with a string, in which case the system will try to match the name to parsed column headers. If this fails, the return value is 0.

Keyword arguments

  • time=1 -- causes the line parameter to be interpreted as a number of seconds. If the input file has labeled columns, then this function will search for a column with a commonly-used name for time ("t", "$t", "date", "time"). Otherwise, the first column is used. The time value must increase monotonically. Returns values from the line closest to, but not greater than, the requested time. Column index will be interpreted as if the time column has been removed. If a vector is returned, it will not include time.
  • smooth=1 -- same behavior as "time", except the returned value will be interpolated between the two rows bracketing the requested time.

log(a)

Returns the natural logarithm (base e) of a.

matrix("filename")

Returns a matrix from the named file. Several different formats are automatically recognized. Typically the backend will cache the matrix in memory to minimize access time.

max(a,b,...)

Return the most positive of the given values.

min(a,b,...)

Return the least positive of the given values.

Mcount("filename","key",...)

Returns number of children under a node in an "M" data file. If the node is empty or missing, returns 0. See Mmatrix for parameter details.

Mkey("filename",index,"key",...)

Returns the key of a child node in an "M" data file. See Mmatrix for parameter details. The combination of Mcount and Mkey make is possible to enumerate the children of a node, even when they have arbitrary keys.

  • key -- Specifies the path to the parent node.

  • index -- An integer that specifies position in the sequence of child nodes. Children are sorted in M order. Specifically, all keys with numeric values sort ahead of all alpha keys. Numeric keys are further sorted by numeric values, while alpha keys are sorted by standard character-code order. If index is not in [0, count-1], the return value is "".

Keyword arguments:

  • int=1 -- Indicates that key should be interpreted as an integer rather than a string. This allows the output of Mkey to be used some places where strings are not allowed. An invalid conversion will return 0.

Mmatrix("filename","key",...)

Returns matrix from a node in an "M" data file. The immediate children of this node should be formatted as a sparse matrix, where the first level of keys are row indices and the second level of keys are column indices along with their values.

This function supports accessing data directly from the metadata section of a model. "M" is the file format in which models are stored. It is a restricted form of YAML. Hierarchical structures are stored and manipulated in memory following the example of the MUMPS programming language.

  • filename -- Path to the data file, either absolute or relative to job directory where model is running.

  • key -- A sequence of strings or integers giving the path to the desired node. Each separate key may be a single path element or may combine several path elements using a delimiter. The effective path will concatenate all of these. Blank path elements between delimiters are ignored ("bob..sam" is treated the same as "bob.sam"). Numeric keys are truncated to produce an integer value.

Keyword arguments:

  • delimiter="character" -- Sets the delimiter for splitting path elements. Default is "."
  • inherit="path" -- Activates $inherit processing on the data file. When the file is opened for the first time, and if path is a non-empty string, then any node that has $inherit as a child key will be collated with other data files. This is similar to how inheritance works for models. "path" may supply both files and directories that will be used like a repository. Path elements are separated by forward slashes. Multiple paths can be specified, separated by colon. For example, "../../data/dir:../../misc/file".

Mnumber("filename","key",...)

Returns value of a node in an "M" data file, interpreted as a number. If node is missing or conversion fails, the return value is 0. See Mmatrix for parameter details.

Mstring("filename","key",...)

Returns value of a node in an "M" data file. If node is missing, the return value is "". See Mmatrix for parameter details.

norm(M,n)

The n-norm of the matrix M as if it were unwound to a vector.

  • 0 -- Counts the number of nonzero elements.
  • 1 -- "Manhattan distance"
  • 2 -- "Euclidean distance"
  • INFINITY -- Finds the maximum of the absolute values.
  • Any other positive n -- (sum abs(a)n)1/n

Default is n=2.

output("filename",expression,column)

Writes the value of expression to an output stream. Also returns the value of expression, so a call to output() may be embedded in a larger expression. Output is organized as a table, where columns are separated by tabs, and rows end with the operating-system-specific combination of CR and LF. Each row contains all the values output in a given simulation cycle.

The reference implementation (Internal backend) aims for sparsity. Columns headings are output in the cycle they first appear, so there may be several headers in the output file. $t is automatically added as the first column, and its presence (rather than a numeral) indicates a header row. Previously emitted column headings will not be repeated. Other backends may have different behavior. In general, they should output a header row at some point during the run, and include a time indication as the first column.

  • filename -- Path to the file being written. If this parameter is "" or simply omitted, then output goes to standard-out.

  • expression -- Evaluated to a real number and printed in the specified column. Also returned as the result of this function. The expression must evaluate to a real number. In particular, strings are forbidden. If a matrix is passed, then each of its elements is emitted as a separate column, with (r,c) appended to the base column name.

  • column -- A string which names a column in the table, or an integer column index. Non-integer numbers will be truncated. If two different calls use the same column name, they may or may not be folded into a single column, depending on the backend. If value is "" or omitted, the associated column in the table gets an automatically-generated unique name based on part names and indices.

The simplest form is a single parameter: output(expression). This writes expression to standard-out with an automatically-generated column name.

Keyword arguments -- If several different output() statements reference the same file, then a keyword argument specified in one statement applies to all of them. It is good practice to only set these in one place. If conflicting values are specified in two different statements, only one will have an effect. Which one is arbitrary.

  • raw=1 -- No header is emitted, and column numbering skips the time column. The first position after the time column is numbered 0, the second position is numbered 1, and so on.
  • scale -- UCUM unit string. Must have the same base SI units as column data. Ideally, all columns share the same base unit. Passed as a hint to plotting software. The plotter is expected to re-scale the value of each data point.
  • timeScale -- UCUM unit string. Must have seconds as the base unit. Passed as a hint to plotting software. The plotter is expected to re-scale the time associated with each data point, and perhaps print the units on time axis.
  • title -- Of the overall plot.
  • xlabel -- Explains the meaning of the horizontal axis. This is almost always time. The units are provided separately by "timeScale".
  • ylabel -- Explains the meaning of the vertical axis. Units are provided separately by "scale".
  • xmin -- Set lower bound on horizontal axis (time). Passed as a hint to the plotter. Should not include units. Instead, treat as a multiple of "timeScale". It effectively refers to values on the horizontal axis after scaling.
  • xmax -- Set upper bound on horizontal axis (time). See comments on xmin.
  • ymin -- Set lower bound on vertical axis. See comments on xmin. Treat as a multiple of "scale".
  • ymax -- Set upper bound on vertical axis. See comments on ymin.

Some keyword arguments apply only to the current column.

  • color={string or number} -- Value is an HTML-style color name or number. Passed as a hint to plotting software. The plotter is expected to set the line color for the current column.
  • hue={number} -- Value is a color angle in [0,1], following the convention of the HSL or HSV color space. Behaves similarly to "color" above. The plotter is expected to supply appropriate saturation and brightness values.
  • width -- Line stroke width for the given column. 0 means the narrowest line possible.
  • dash={list of numbers, separated by colons} -- Defines a dash pattern as a sequence of lengths: mark, skip, mark, skip ...

pow(a,b)

Normally written as a^b, but this form allows the optional keyword argument "median=value" to specify a hint for fixed-point arithmetic.

pulse(t,width,period,rise,fall)

Outputs square-wave, sawtooth or triangular patterns over time. The shape is configurable. Each pulse follows this pattern: rise, top, fall, bottom. The wave starts at 0 and rises to 1 in a straight line over some amount time, possibly zero time. Then the wave stays at 1 for a time. Next it falls back to 0, and finally remains at 0 until the next pulse starts.

  • t = Time value within context of the pulse function. Time 0 is the start of the pulse. Negative values produce 0 as output.

  • width = Duration of the top portion of the wave. Zero or negative means no width, suitable for triangular or sawtooth wave. Default is infinity.

  • period = Time between start of each pulse. Zero or negative means the pulse is one-shot (no repeat). For positive values, a new pulse starts at each time period*n, where n is a non-negative integer. Default is 0.

  • rise = Duration of rise from 0 to 1. Zero or negative means instantaneous rise, suitable for square wave. Default is 0.

  • fall = Duration of drop from 1 to 0. Zero or negative means instantaneous fall, suitable for square wave. Default is 0.

round(a)

Returns the integer closest to a, with ties going to the integer closest to positive infinity.

rows(M)

Get the number of rows in matrix M.

sat(a)
sat(a,bound)
sat(a,lower,upper)

Saturation function. Equivalent to max(lower,min(upper,a)). When no additional arguments are given, lower=-1 and upper=1. When one additional argument is given, lower=-bound and upper=bound.

sgn(a)

Signum of a. Specifically:

1 @ a>0
0 @ a==0
-1 @ a<0

sin(angle)

Sine of angle.

sphere(sigma)

Returns a uniform distribution of random points contained within an ellipsoid. Similar to uniform(), except that the point cloud is not rectangular.

  • sigma – Scales the random value and determines dimensionality. The result is effectively sigma*u, where u is vector drawn uniformly from a spheroid of radius 1. If sigma is a vector, it is treated as the diagonal of a matrix. The dimensionality of the spheroid will match the number of nonzero elements in the vector. If sigma is a scalar, it is treated as a vector of 3 equal radii. Default is 1.

spreadsheet("filename","anchor",row,column)

Retrieves data from a spreadsheet file, typically MS Excel.

  • filename -- Path to the data file, either absolute or relative to job directory where model is running.

  • anchor -- A standard cell reference string in the form {Sheet name}!{column letter}{row number}. For example, "Sales!B2". Specifies the reference point on which all retrieval operations are based. If omitted, then operations are based on cell A1 of the default sheet.

  • row,column -- Zero-based offset from anchor. Default is zero.

Keyword arguments:

  • info={"rows", "columns", "rowsInColumn", "columnsInRow"} -- Instead of retrieving a cell value, this returns information about the available data. "rows" and "columns" refer to region starting at the anchor that encompasses all non-empty cells. "rowsInColumn" gives distance to the first empty cell in the column starting at the anchor. Likewise, "columnsInRow" returns distance to the first empty cell in the row starting at the anchor.
  • prefix -- Value is a string. Causes this function to return a string rather than a number. The return value consists of the prefix followed by a string version of the cell contents. Prefix may be "".

sumSquares(M)

Equivalent to norm(M,2)^2, but omitting the idempotent square-root and square operations.

tan(angle)

Tangent of angle.

tanh(angle)

Hyperbolic tangent of angle.

uniform(sigma)

Returns a random number in [0,sigma) with uniform distribution. See gaussian().

  • sigma -- Scales the random value and determines dimensionality of the result. If sigma is a scalar, the result is a scalar. If sigma is a matrix, the result is effectively sigma*u, where u is vector of uniform draws in [0,1). If sigma is a vector, it is treated as the diagonal of a matrix. Default sigma is 1.

uniform(lo,hi,step)

Returns a quantized value drawn uniformly from a range, calculated as lo+u*step where u is a random whole number. Typically this function is used to generate random integers, in which case all the parameters are integers.

  • lo -- The lowest value returned.
  • hi -- Returned value does not exceed hi. It can only reach hi if hi==lo+u*step for some whole number u.
  • step -- Distance between return values. Default is 1.

unitmap(M,row,column)

Maps the elements of matrix M to a unit square, such that the requested row and column are both in [0,1]. This allows, for example, a neural network structure to be agnostic about the exact dimensions of an image. The matrix is treated as a set of rectangular samples that cover the unit square. This is related to the mapping given by grid(). The value at a given position is determined by bilinear interpolation between the four nearest neighbors in M. Along the edges of M, interpolation is between the two nearest elements. Likewise, any request outside the unit square is fulfilled by the nearest pair of elements.

⚠️ **GitHub.com Fallback** ⚠️