force

    Deterministic force-directed layouts on indexed nodes.

    layout
    force
    barnes-hut
    Download zip
    Author
    Version
    0.1.1
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    58

    No dependencies

    #gaato/force

    A force-directed graph layout for MoonBit, following d3-force. Give it a number of nodes and the edges between them, and it computes positions. You bring the drawing: SVG, a canvas, a terminal or anything else. Nodes are indices 0..<n, and edges are pairs of indices.

    It runs on JS, native and Wasm GC, and gives the same positions on all three for the same seed (Simulation::new(n, seed=s), 1 by default), so a layout computed on a server matches one computed in a browser.

    #Install

    moon add gaato/force

    #Lay out a graph

    Make a simulation of n nodes, add forces, and tick until it cools down:

    ///|
    test "lay out a path of three nodes" {
    let sim = @force.Simulation::new(3)
    sim.add_force(@force.link([(0, 1), (1, 2)]))
    sim.add_force(@force.many_body())
    sim.add_force(@force.center())
    while sim.alpha > sim.alpha_min {
    sim.tick()
    }
    // Draw node i at (sim.xs()[i], sim.ys()[i]).
    let ends = (sim.xs()[0] - sim.xs()[2], sim.ys()[0] - sim.ys()[2])
    assert_true(ends.0 * ends.0 + ends.1 * ends.1 > 0)
    }

    For a static picture, tick until alpha drops below alpha_min, then draw. For an animation, call tick once per frame from your render loop and redraw. tick never stops by itself, so you decide when to stop.

    #Forces

    ConstructorWhat it doesd3 equivalent
    link(edges)Pulls connected nodes toward a distanceforceLink
    many_body()Repels (or attracts) every pair, with Barnes–Hut approximationforceManyBody
    center()Keeps the layout's centre of mass in placeforceCenter
    collide()Keeps nodes from overlappingforceCollide
    x(), y()Pulls nodes toward a coordinate on one axisforceX, forceY

    Settings that d3 lets you give per node take a Values: All(v) for every node, or Each(array) with one value per node (per link, for link).

    ///|
    test "per-node settings" {
    let sim = @force.Simulation::new(3)
    sim.add_force(@force.many_body(strength=All(-30)))
    sim.add_force(@force.collide(radius=Each([4, 8, 12])))
    sim.tick(iterations=10)
    }

    Defaults and formulas match d3's: the initial spiral layout, alpha cooling, velocity decay and each force's defaults. Settings tuned for d3 carry over.

    add_force checks a force against the simulation, and raises ForceError without installing anything when it does not fit: an Each of the wrong length, a link to a missing node, or a negative radius.

    #Differences from d3

    • Nodes are indices, not mutable objects. Read positions with xs() and ys(), and change them with set_position(i, x=, y=), set_velocity(i, vx=, vy=) and pin.
    • There is no timer and there are no events: call tick from your own loop.
    • Forces have no names or live setters. To change one, call clear_forces and add them again.

    #License

    Apache-2.0. See LICENSE.

    ForceError

    pub(all) suberror ForceError {
    LengthMismatch(setting~ : String, expected~ : Int, actual~ : Int)
    NodeOutOfRange(node~ : Int, count~ : Int)
    InvalidSetting(setting~ : String, value~ : Double)
    } derive(Eq,
    Debug
    )

    A force that Simulation::add_force refused.

    ForceError::equal

    fn ForceError::equal(ForceError, ForceError) -> Bool

    Exposes equal and not_equal as methods of ForceError.

    ForceError::not_equal

    fn ForceError::not_equal(x : ForceError, y : ForceError) -> Bool

    Exposes equal and not_equal as methods of ForceError.

    ForceError::to_repr

    Exposes to_repr as a method of ForceError, for debug output.

    Force

    type Force

    A force, as configured. Build one with link, many_body, center, collide, x or y, and install it with Simulation::add_force, which checks it against the simulation.

    Simulation

    pub struct Simulation {
    alpha : Double
    alpha_min : Double
    alpha_decay : Double
    alpha_target : Double
    velocity_decay : Double
    // private fields
    }

    Indexed structure-of-arrays state. Use setters to edit nodes; array getters return read-only views. Construct a new simulation to change node count.

    Simulation::add_force

    fn Simulation::add_force(self : Simulation, force : Force) -> Unit raise ForceError

    Installs force after the ones already installed; tick applies them in that order. Raises, installing nothing, when the force does not fit this simulation: an Each of the wrong length, a link to a missing node, or a negative radius or iteration count.

    Simulation::clear_forces

    fn Simulation::clear_forces(self : Simulation) -> Unit

    Removes every installed force; add them again to change one.

    Simulation::new

    fn Simulation::new(n : Int, seed? : UInt) -> Simulation raise ForceError

    A simulation of n nodes, placed in d3's phyllotaxis spiral and at rest, with no forces. seed fixes the small random nudges that separate coincident nodes, so a run is the same on every backend.

    test {
    let sim = @force.Simulation::new(3)
    sim.add_force(@force.link([(0, 1), (1, 2)]))
    sim.add_force(@force.many_body())
    sim.tick(iterations=300)
    inspect(sim.node_count(), content="3")
    }

    Simulation::node_count

    fn Simulation::node_count(self : Simulation) -> Int

    The number of nodes, fixed when the simulation is made.

    Simulation::pin

    fn Simulation::pin(self : Simulation, i : Int, x? : Double, y? : Double) -> Unit

    Set either fixed coordinate; omitted axes are released. Applied at tick end.

    Simulation::set_alpha

    fn Simulation::set_alpha(self : Simulation, value : Double) -> Unit

    Sets the current alpha, the strength forces apply at; 1 at the start. Set it back up to reheat a simulation after changing it.

    Simulation::set_alpha_decay

    fn Simulation::set_alpha_decay(self : Simulation, value : Double) -> Unit

    Sets how fast alpha moves towards alpha_target on each tick, as a fraction of the gap; by default it reaches alpha_min in 300 ticks.

    Simulation::set_alpha_min

    fn Simulation::set_alpha_min(self : Simulation, value : Double) -> Unit

    Sets the alpha below which a caller should stop ticking; 0.001 by default. tick itself does not stop there.

    Simulation::set_alpha_target

    fn Simulation::set_alpha_target(self : Simulation, value : Double) -> Unit

    Sets the alpha that each tick moves alpha towards; 0 by default.

    Simulation::set_position

    fn Simulation::set_position(self : Simulation, i : Int, x~ : Double, y~ : Double) -> Unit

    Moves node i, which must be below node_count, like an array index.

    Simulation::set_velocity

    fn Simulation::set_velocity(self : Simulation, i : Int, vx~ : Double, vy~ : Double) -> Unit

    Sets node i's velocity; i must be below node_count.

    Simulation::set_velocity_decay

    fn Simulation::set_velocity_decay(self : Simulation, value : Double) -> Unit

    Sets the fraction of velocity lost on each tick, like friction; 0.4 by default.

    Simulation::tick

    fn Simulation::tick(self : Simulation, iterations? : Int) -> Unit

    Manual d3 tick: cool, apply ordered forces, damp velocities, integrate/pin. alpha_min is a stopping threshold for callers, not a clamp in tick.

    Simulation::vxs

    fn Simulation::vxs(self : Simulation) -> ArrayView[Double]

    Each node's x velocity, indexed by node.

    Simulation::vys

    fn Simulation::vys(self : Simulation) -> ArrayView[Double]

    Each node's y velocity, indexed by node.

    Simulation::xs

    fn Simulation::xs(self : Simulation) -> ArrayView[Double]

    Each node's x position, indexed by node.

    Simulation::ys

    fn Simulation::ys(self : Simulation) -> ArrayView[Double]

    Each node's y position, indexed by node.

    Values

    pub(all) enum Values {
    All(Double)
    Each(Array[Double])
    } derive(Eq,
    Debug
    )

    A setting given either once for every node (or link), or once per node.

    test {
    let _ = @force.many_body(strength=All(-30))
    let _ = @force.x(target=Each([0, 100, 200]))
    }

    Values::equal

    fn Values::equal(Values, Values) -> Bool

    Exposes equal and not_equal as methods of Values.

    Values::not_equal

    fn Values::not_equal(x : Values, y : Values) -> Bool

    Exposes equal and not_equal as methods of Values.

    Values::to_repr

    Exposes to_repr as a method of Values, for debug output.

    center

    fn center(x? : Double, y? : Double, strength? : Double) -> Force

    Moves every node together so that their mean is at (x, y), as d3's forceCenter.

    collide

    fn collide(radius? : Values, strength? : Double, iterations? : Int) -> Force

    Keeps nodes from overlapping, treating each as a circle of radius, as d3's forceCollide.
    fn link(edges : Array[(Int, Int)], distance? : Values, strength? : Values, iterations? : Int) -> Force

    Pulls linked nodes toward distance apart, as d3's forceLink.

    Without strength, each link gets d3's default: one over the smaller degree of its two ends. Each settings take one value per link.

    many_body

    fn many_body(strength? : Values, theta? : Double, distance_min? : Double, distance_max? : Double) -> Force

    Makes nodes repel (or, with a positive strength, attract) each other, as d3's forceManyBody, with a Barnes–Hut approximation of accuracy theta.
    fn x(target? : Values, strength? : Values) -> Force

    Pulls each node toward the vertical line at target, as d3's forceX.
    fn y(target? : Values, strength? : Values) -> Force

    Pulls each node toward the horizontal line at target, as d3's forceY.