Loopa

Loopa

Scripting docs

Lua scripts drive Loopa’s simulations through the sim API. This is the same documentation as in the app, under Documentation.

Overview#

Scripts run as Lua 5.4 on a background thread, separate from the UI, so loops and long computations will not freeze the app. The global sim table is the entry point: it lets you read and switch the active system, get and set parameters and initial conditions, advance the simulation, and inspect the resulting trajectory. Anything passed to print() streams to the console below in real time as the script runs. The type names used in the signatures below follow Lua's own vocabulary: string and number are plain text and numeric values, integer is a whole number, boolean is true or false, nil means no value, and table is Lua's one general purpose data structure, used both as an ordered list of values, for example {1.0, 2.0, 3.0}, and as a set of named fields, for example {x = 1.0, y = 2.0}.

print(sim.system())
print("t = " .. sim.time())

sim.setSystem(name)#

Signature
setSystem(name: string) -> nil

Switches the active system to the one whose name matches name (case-insensitive), and resets its state and time to its default initial conditions. The name must be one of the names returned by sim.systems() or shown in the canvas system picker; if no match is found, the call has no effect. Returns nothing.

sim.setSystem("Lorenz Attractor")

sim.system()#

Signature
system() -> string

Returns the display name of the currently active system, as a string, the same name shown in the canvas system picker and accepted by sim.setSystem.

print(sim.system())

sim.systems()#

Signature
systems() -> table

Returns a list of every system available to the script, both built-in and custom, as an array-like table. Each entry is itself a table describing one system, with a name field (its display name, a string), a dims field (the number of state dimensions, an integer), and a vars field (an array of state variable name strings).

for _, s in ipairs(sim.systems()) do
  print(s.name .. " (" .. s.dims .. "D)")
end

sim.setParameter(name, value)#

Signature
setParameter(name: string | integer, value: number) -> nil

Sets the value of the system parameter identified by name (a string matching one of the keys returned by sim.parameters()) to value (a number), clamped to that parameter's allowed range between min and max. Returns nothing; the new value takes effect on the next step or run.

sim.setParameter("rho", 28.0)
sim.setParameter(2, 28.0)

sim.getParameter(name)#

Signature
getParameter(name: string | integer) -> number

Returns the current numeric value of the parameter identified by name. If the active system has no parameter with that name, returns nil.

print(sim.getParameter("rho"))

sim.parameters()#

Signature
parameters() -> table

Returns every parameter of the active system as a table keyed by parameter name. Each value is itself a table describing that parameter, with value (its current number), min and max (the allowed range), and step (the increment used by the sliders in the sidebar).

for name, p in pairs(sim.parameters()) do
  print(name, p.index, p.value, p.min, p.max, p.step)
end

sim.setIC(...) / sim.setIC(table)#

Signature
setIC(x1: number, ..., xn: number) -> nil
setIC(values: table) -> nil

Sets the initial conditions that the simulation will start from on the next reset or run. Provide one number per state dimension, either as separate arguments, as in sim.setIC(1.0, 0.0, 0.0), or as a single array-like table of the same length, as in sim.setIC({1.0, 0.0, 0.0}). The number of values supplied must match sim.dims(). Returns nothing.

sim.setIC(1.0, 0.0, 0.0)
sim.setIC({1.0, 0.0, 0.0})

sim.getIC()#

Signature
getIC() -> table

Returns the initial conditions currently configured for the active system, as an array-like table of numbers, one entry per state dimension, in the same order as sim.vars().

print(table.concat(sim.getIC(), ", "))

sim.run(n)#

Signature
run(n: integer) -> table

Resets the simulation to its initial conditions and time zero, then advances it n steps, where n is a positive integer, accumulating the trajectory as it goes. Returns the resulting trajectory as an array-like table of points, in the same form as sim.trajectory().

local traj = sim.run(2000)
print(#traj .. " points")

sim.step(n)#

Signature
step(n: integer) -> table

Advances the simulation a further n steps, where n is a positive integer, from wherever it currently is, without resetting first. Returns only the newly produced segment of the trajectory, an array-like table covering just these new points, leaving everything accumulated so far untouched and still accessible through sim.trajectory().

sim.run(500)
local seg = sim.step(100)
print(#seg .. " new points")

sim.trajectory()#

Signature
trajectory() -> table

Returns the full trajectory accumulated since the last reset, as an array-like table of points. Each point is a table with a t field (the simulation time at that point, a number) plus one field per state variable, named after the entries of sim.vars(), for example x, y and z for a three-dimensional system.

local traj = sim.trajectory()
for _, pt in ipairs(traj) do
  print(pt.t, pt.x, pt.y, pt.z)
end

sim.time()#

Signature
time() -> number

Returns the simulation's current time as a number: how far it has advanced past zero since the last reset, measured in the same units as sim.timeStep().

print(sim.time())

sim.state()#

Signature
state() -> table

Returns the simulation's current state as a table with one named field per state variable, for example x, y and z for a three-dimensional system, using the names returned by sim.vars(). This reflects the most recent point reached by sim.run, sim.step, or the last reset.

local s = sim.state()
print(s.x, s.y, s.z)

sim.reset()#

Signature
reset() -> nil

Resets the simulation's state and time back to its configured initial conditions, the values returned by sim.getIC(), and discards everything accumulated so far, without running any steps. After this call, sim.time() returns zero and sim.trajectory() returns an empty table. Returns nothing.

sim.run(1000)
sim.reset()
print(sim.time())  -- 0

sim.dims()#

Signature
dims() -> integer

Returns the number of state dimensions of the active system, as an integer, for example 3 for the Lorenz Attractor or 1 for a one-dimensional map such as the Logistic Map. This is the same value as the dims field returned by sim.systems().

print(sim.dims())  -- e.g. 3 for Lorenz

sim.vars()#

Signature
vars() -> table

Returns the names of the active system's state variables, as an array-like table of strings, in the order they appear in sim.state(), in each point of sim.trajectory(), and in sim.getIC()/sim.setIC(); for example {"x", "y", "z"} for the Lorenz Attractor.

for i, v in ipairs(sim.vars()) do
  print(i, v)
end

sim.timeStep()#

Signature
timeStep() -> number

Returns the integration time step, written dt, used by the active system's solver, as a number. Each step taken by sim.run or sim.step advances the simulation's time by this amount.

print(sim.timeStep())

sim.setNoise(intensity)#

Signature
setNoise(intensity: number) -> nil
noise() -> number

Adds Gaussian noise to the script’s simulation, like the Noise option in the app: after every step, each state variable gets a random normal perturbation scaled by intensity × √Δt. setNoise(0) turns it off and noise() returns the current intensity. It applies to step and run, not to the analysis functions.

sim.setNoise(0.5)
local t = sim.run(2000)
print(sim.noise())
sim.setNoise(0)

sim.defaultIC()#

Signature
defaultIC() -> table

Returns the active system's built-in default initial conditions, as an array-like table of numbers, one per state dimension. These are the values the system starts from when first selected, before any call to sim.setIC.

print(table.concat(sim.defaultIC(), ", "))

sim.fixedPoints(xmin, xmax, ymin, ymax [, gridSize])#

Signature
fixedPoints(
  xmin: number,
  xmax: number,
  ymin: number,
  ymax: number,
  gridSize: integer = 12
) -> table

Searches the rectangular region bounded by xmin, xmax, ymin and ymax in the plane of the first two state variables for fixed points, also called equilibria, seeding Newton's method from a grid of starting points spread across that region. The optional gridSize, an integer that defaults to 12, sets how many starting points are sampled along each axis; larger values can find more isolated fixed points at the cost of speed. Returns an array-like table of results, where each entry is a table with named coordinate fields such as x and y, a position field holding those same coordinates as an array, and a type field holding one of the strings "stable", "unstable", "saddle", "center", or "unknown". Returns an empty table for one-dimensional systems or systems that do not support equilibrium analysis.

local fps = sim.fixedPoints(-5, 5, -5, 5)
print(#fps .. " fixed points found")
for _, fp in ipairs(fps) do
  print(fp.x, fp.y, fp.type)
end

sim.poincare([dim [, value]])#

Signature
poincare(
  dim: integer | string = dims,
  value: number = 0
) -> table

Computes a Poincaré section from the trajectory accumulated so far, so call sim.run() or sim.step() first. It detects upward crossings of the plane where the chosen state variable equals the given value, interpolating linearly between trajectory points. The dimension is a 1-based index or a variable name string and defaults to the last state variable; the crossing value defaults to 0. Returns an array-like table of crossing points, each with a t field and one field per state variable.

sim.setSystem("Lorenz Attractor")
sim.run(20000)
local pts = sim.poincare("z", 27)
for _, p in ipairs(pts) do
  print(p.t, p.x, p.y)
end

sim.lyapunovExponent([steps [, transient]])#

Signature
lyapunovExponent(
  steps: integer = 5000,
  transient: integer = 1000
) -> number

Estimates the active system's maximum Lyapunov exponent from its current state, using the two-trajectory separation method: a reference trajectory and a slightly perturbed copy of it are run side by side, and the average rate at which they pull apart, or come together, is measured. The optional steps, an integer that defaults to 5000, sets the total number of steps measured, and transient, an integer that defaults to 1000, sets how many initial steps are discarded first so the trajectory can settle onto the attractor before measuring begins. Returns a single number: positive values indicate sensitive dependence on initial conditions, that is, chaos; values close to zero indicate marginal or periodic behaviour; and negative values indicate stable, non-chaotic behaviour.

sim.setSystem("Lorenz Attractor")
sim.setIC(1.0, 1.0, 1.0)
local le = sim.lyapunovExponent(10000, 2000)
print(string.format("MLE = %.4f", le))

sim.basin(xDim, yDim, xmin, xmax, ymin, ymax [, resolution])#

Signature
basin(
  xDim: integer = 0,
  yDim: integer = 1,
  xmin: number = -10,
  xmax: number = 10,
  ymin: number = -10,
  ymax: number = 10,
  resolution: integer = 24
) -> table

Computes a basin-of-attraction map over a rectangular grid of initial conditions in the plane spanned by xDim and yDim, zero-based state indices defaulting to 0 and 1, bounded by xmin, xmax, ymin and ymax, each defaulting to -10 and 10, sampled at resolution points per axis, an integer defaulting to 24. Every other state variable is held at the active system's current value. Each grid point is integrated forward and clustered by its long-term mean position: points that diverge are labelled -1, and points that settle near a previously seen cluster share its label, starting from 0. Returns a table with resolution, the grid size per axis; clusters, the number of distinct attractors found; and labels, a flat row-major array of resolution times resolution integers giving each grid point's cluster label or -1. Available only for systems that support basin-of-attraction analysis.

local b = sim.basin(0, 1, -5, 5, -5, 5, 32)
print(b.clusters .. " attractors found")
print(b.labels[1])

sim.bifurcation(paramName, pmin, pmax [, samples [, dim]])#

Signature
bifurcation(
  paramName: string | integer,
  pmin: number = 0,
  pmax: number = 1,
  samples: integer = 200,
  dim: integer = 0
) -> table

Sweeps the named parameter from pmin to pmax across samples evenly spaced values, an integer defaulting to 200, and for each value runs the system from its current state, discards an initial transient, then records the local maxima of the first state variable, the same long-term behaviour shown in the app's bifurcation diagram. Returns an array-like table of points, each a table with param, the parameter value at that sample, and value, the recorded state value. Works for both continuous and discrete systems, provided the named parameter exists on the active system.

local pts = sim.bifurcation("rho", 0, 50, 400)
for _, p in ipairs(pts) do
  print(p.param, p.value)
end

sim.manifold([xmin, xmax, ymin, ymax])#

Signature
manifold(
  xmin: number = -10,
  xmax: number = 10,
  ymin: number = -10,
  ymax: number = 10
) -> table

Locates the active system's equilibria within the rectangular region bounded by xmin, xmax, ymin and ymax, each defaulting to -10 and 10, classifies each one, and traces the stable and unstable manifold curves passing through any saddle points found, by integrating forward and backward in time from points near each saddle. Returns a table with equilibria, an array of tables each holding x, y, type, one of "stable", "unstable", "saddle", "node", "spiral" or "center", and the eigenvalues lambda1 and lambda2; stable, an array of branches, each itself an array of tables with x and y tracing a stable manifold curve; and unstable, the equivalent array of unstable manifold branches. Available only for systems that support manifold analysis, generally two-dimensional continuous systems with equilibria.

local m = sim.manifold(-5, 5, -5, 5)
for _, eq in ipairs(m.equilibria) do
  print(eq.x, eq.y, eq.type)
end
print(#m.stable .. " stable branches")

sim.orbitDiagram(paramName, pmin, pmax [, samples])#

Signature
orbitDiagram(
  paramName: string,
  pmin: number = 0,
  pmax: number = 1,
  samples: integer = 400
) -> table

Sweeps the named parameter from pmin to pmax across samples evenly spaced values, an integer defaulting to 400, and for each value iterates the discrete map from its current state, discards an initial transient, then records the long-term values of the first state variable, the same long-term behaviour shown in the app's orbit diagram. Returns an array-like table of points, each a table with param, the parameter value at that sample, and value, the recorded state value. Available only for discrete systems.

sim.setSystem("Logistic Map")
local pts = sim.orbitDiagram("r", 2.4, 4.0, 600)
for _, p in ipairs(pts) do
  print(p.param, p.value)
end

sim.psd([dimension])#

Signature
psd(dimension: integer = 0) -> table

Computes the power spectral density of the recorded trajectory's dimension-th state variable, a zero-based index defaulting to 0, using a windowed FFT over the most recent samples. Requires sim.run or sim.step to have been called first so a trajectory is available. Returns an array-like table of points, each a table with frequency, the frequency in cycles per unit time, and db, the spectral power at that frequency in decibels. Available only for systems that support power spectral density analysis.

sim.run(5000)
local spectrum = sim.psd(0)
for _, p in ipairs(spectrum) do
  print(p.frequency, p.db)
end

sim.recurrence([threshold [, maxPoints]])#

Signature
recurrence(
  threshold: number = 1.0,
  maxPoints: integer = 200
) -> table

Builds a recurrence plot from the recorded trajectory: pairs of points whose distance in state space is below threshold, defaulting to 1.0, are marked as recurrent. The trajectory is first subsampled down to at most maxPoints points, an integer defaulting to 200, for performance. Requires sim.run or sim.step to have been called first so a trajectory is available. Returns a table with n, the size of the subsampled trajectory used; threshold, the distance threshold applied; recurrenceRate, the fraction of point pairs marked as recurrent; and matrix, a flat row-major array of n times n values, each either 0 or 1. Available only for systems that support recurrence analysis.

sim.run(5000)
local r = sim.recurrence(0.5, 150)
print(string.format("rate = %.3f", r.recurrenceRate))
print(r.matrix[1])

sim.sensitivity([perturbation [, steps]])#

Signature
sensitivity(
  perturbation: number = 1e-6,
  steps: integer = 1000
) -> table

Measures sensitive dependence on initial conditions by running two copies of the active system side by side from its current state, one of them shifted by perturbation in its first state variable, a small number defaulting to 1e-6, for steps integration steps, an integer defaulting to 1000, and recording how their separation grows over time, the same measurement shown in the app's sensitivity analysis. Returns an array-like table of points, each a table with t, the elapsed time, and logDistance, the natural logarithm of the distance between the two trajectories at that time. Available only for systems that support sensitivity analysis.

local pts = sim.sensitivity(1e-6, 2000)
for _, p in ipairs(pts) do
  print(p.t, p.logDistance)
end

sim.periodicOrbits([sectionDim [, maxCount]])#

Signature
periodicOrbits(
  sectionDim: integer = 2,
  maxCount: integer = 4
) -> table

Searches for periodic orbits of the active system, the same search shown in the app's periodic orbits analysis. For flows, close returns of a long trajectory to a Poincaré section are refined with Newton's method; sectionDim selects the state variable whose mean value defines the section, a zero-based index defaulting to the third variable, or the first in two dimensions, and maxCount is the largest number of section crossings per orbit, an integer defaulting to 4. For maps, maxCount is the largest period searched, defaulting to 8, and sectionDim is ignored. Returns a table with autonomous, false when the system depends explicitly on time and no search is possible, and orbits, an array-like table in which each orbit has period, crossings, stable, symbols, its symbolic itinerary of L and R, maxMultiplier, multipliers, an array of Floquet multipliers each with re and im, and points, an array of states along the orbit. Available only for systems that support periodic orbit search.

local r = sim.periodicOrbits(2, 4)
for _, o in ipairs(r.orbits) do
  print(string.format("T = %.4f %s %s", o.period, o.symbols,
    o.stable and "stable" or "unstable"))
end

sim.continuation(paramName [, pmin, pmax [, dimension]])#

Signature
continuation(
  paramName: string,
  pmin: number = min,
  pmax: number = max,
  dimension: integer = 0
) -> table

Follows branches of equilibria of the active system, or fixed points for maps, as the parameter paramName varies from pmin to pmax, which default to the parameter's range, using pseudo-arclength continuation, the same computation shown in the app's equilibrium continuation analysis. dimension, a zero-based index defaulting to 0, selects the state variable reported as value. Returns a table with branches, an array of branches in which each point has param, value, stable and state, the full equilibrium state; events, an array of detected bifurcations, each with type, one of fold, hopf, branchPoint, periodDoubling, neimarkSacker or cycleFold, param, value, state and frequency, the angular frequency at a Hopf or Neimark–Sacker point; and cycles, the limit cycles born at Hopf points of flows, an array of branches in which each point has param, period, stable, and max and min, the largest and smallest value of every state variable along the cycle. Available for continuous systems with equilibria and for smooth maps, with at least one parameter.

local c = sim.continuation("rho", 1, 100)
for _, e in ipairs(c.events) do
  print(e.type, e.param, e.value)
end
print(#c.branches .. " branches")

sim.parameterPlane(xParam, xmin, xmax, yParam, ymin, ymax [, resolution [, metric]])#

Signature
parameterPlane(
  xParam: string,
  xmin: number = min,
  xmax: number = max,
  yParam: string,
  ymin: number = min,
  ymax: number = max,
  resolution: integer = 32,
  metric: string = "lyapunov"
) -> table

Sweeps two parameters at once over a resolution by resolution grid, an integer defaulting to 32, from xmin to xmax for xParam and from ymin to ymax for yParam, which default to the parameters' ranges, and evaluates metric at each point, the same computation shown in the app's parameter plane analysis. metric is lyapunov, the largest Lyapunov exponent; period, the period of the attractor where -1 marks chaos and 0 an equilibrium; or rotation, the rotation number, available only for circle maps. Returns a table with resolution, metric, x and y, the grid coordinates, values, an array of rows from ymin to ymax, each an array of values from xmin to xmax, and, for flows, curves, an array of Hopf and fold curves in the plane, each with type, hopf or fold, and points, an array of {x, y} parameter pairs. Large grids can take a while. Available only for systems with at least two parameters.

local p = sim.parameterPlane("sigma", 1, 50, "rho", 1, 100, 24)
local chaotic = 0
for _, row in ipairs(p.values) do
  for _, v in ipairs(row) do
    if v > 0.01 then chaotic = chaotic + 1 end
  end
end
print(chaotic .. " chaotic cells")

sim.lyapunovSpectrum([steps [, transient]])#

Signature
lyapunovSpectrum(
  steps: integer = 100000,
  transient: integer = 5000
) -> table

Computes the full Lyapunov spectrum of the active system from its default initial conditions, the same computation shown in the app's Lyapunov spectrum analysis. A trajectory and a set of tangent vectors are advanced together for steps integration steps, or iterations for maps, an integer defaulting to 100000, after a transient of transient steps, defaulting to 5000, with the tangent vectors re-orthonormalized at every step. Returns a table with exponents, an array of all exponents from largest to smallest, in units of one over time for flows and per iteration for maps; kaplanYorke, the Kaplan–Yorke dimension of the attractor; and neutral, the one-based index of the exponent along the flow, or nil for maps. Available for flows that support Lyapunov analysis and for maps.

local s = sim.lyapunovSpectrum(200000)
for i, e in ipairs(s.exponents) do
  print(i, string.format("%.4f", e))
end
print(string.format("D = %.3f", s.kaplanYorke))

sim.zeroOneTest([dim [, samples]])#

Signature
zeroOneTest(
  dim: integer = 0,
  samples: integer = 2000
) -> table

Runs the 0–1 test for chaos (Gottwald–Melbourne) on the active system, as in the app’s Lyapunov exponent analysis. dim is the zero-based index of the observed variable, 0 by default, and samples is the length of the time series, 2000 by default. Returns a table with k, near 1 for chaotic and near 0 for regular dynamics, and verdict: "chaotic" when k ≥ 0.8, "regular" when k ≤ 0.2, "indeterminate" in between, or "undefined" if the trajectory diverged.

local r = sim.zeroOneTest()
print(string.format("K = %.3f (%s)", r.k, r.verdict))

sim.defineSystem(definition)#

Signature
defineSystem(definition: table) -> string

Defines and registers a new custom system from the table definition, then returns its name as a string so it can immediately be passed to sim.setSystem and sim.apply. The table's fields are: name, a required string giving the system's display name; type, an optional string, either "continuous" (the default) or "discrete", choosing whether the equations describe an ODE written as dx/dt = ... or an iterated map written as x[n+1] = ...; dims, a required integer giving the number of state dimensions; vars, a required table of strings, one per dimension, giving the state variable names; equations, a required table of strings, one per dimension, each an expression written in terms of the variable names, any parameter names, and, for continuous systems, t; parameters, an optional array of parameter definitions, each itself a table with name, value, min, max and optionally step; and ic, an optional table of numbers, one per dimension, giving the system's default initial conditions. For continuous systems, the optional fields solver ("rk4", "rk45" or "verlet", "rk45" by default) and timeStep (0.01 by default) choose the integrator and its step, as in the custom system editor.

local name = sim.defineSystem({
  name = "Logistic Map",
  type = "discrete",
  dims = 1,
  vars = {"x"},
  equations = {"r * x * (1 - x)"},
  parameters = {{name = "r", value = 3.5, min = 0, max = 4}},
  ic = {0.5},
})
sim.setSystem(name)
sim.apply()

sim.apply()#

Signature
apply() -> nil

Pushes the script's current state, namely its selected system from sim.system(), its parameter values from sim.parameters(), and its initial conditions from sim.getIC(), back to the main simulation canvas as a new tab. The main window switches to that system, applies its parameters and initial conditions, switches between continuous and discrete mode if the system requires it, and restarts the simulation. On mobile, the overlay editor updates the canvas directly; on desktop, the script editor window signals the main window over a platform channel. Returns nothing.

sim.setSystem("Lorenz Attractor")
sim.setParameter("rho", 35.0)
sim.setIC(0.1, 0.0, 0.0)
sim.apply()

Example#

sim.setSystem("Lorenz Attractor")
sim.setParameter("rho", 28.0)
sim.setParameter("sigma", 10.0)
sim.setParameter("beta", 2.667)
sim.setIC(1.0, 1.0, 1.0)

print("rho sweep:")
for rho = 20, 40, 2 do
  sim.setParameter("rho", rho)
  local t = sim.run(1000)
  local mx = -math.huge
  for _, pt in ipairs(t) do
    if pt.x > mx then mx = pt.x end
  end
  print(string.format("  rho=%.1f  max_x=%.4f", rho, mx))
end