Module

Hylograph.ForceEngine.Setup

Package
purescript-hylograph-simulation
Repository
afcondon/purescript-hylograph-simulation

Declarative Force Setup

Unified system for declaratively configuring force simulations. Replaces the older ForceSpec (too simple) and Config.* modules (wrong abstraction layer).

Key features:

  • Static or dynamic (per-node, or per-link) parameter values
  • Optional filters to apply forces selectively
  • Idempotent applySetup that works for both initial setup and updates

Example:

mySetup = setup "physics"
  [ manyBody "charge" # withStrength (static (-30.0))
  , collide "collision" # withRadius (dynamic _.r)
  , positionX "gridX" # withX (dynamic _.gridX) # withStrength (static 0.1)
  , positionY "gridY" # withY (dynamic _.gridY) # withStrength (static 0.1)
  ]

-- Apply to simulation (idempotent - can call repeatedly)
applySetup mySetup sim

-- Update: just call applySetup with new config
applySetup (mySetup # removeForce "charge") sim

A force is one constructor of ForceConfig, carrying a record of exactly the parameters that force has. The smart constructors (manyBody, collide, ...) and the with... builders are the intended way to make one; a builder that does not apply to a force leaves it unchanged.

Seven forces are d3-force's. Five are not (towards, rectCollide, contain, cohesion, directional), nor is a many-body force scoped by group, nor a collision with a filter or scaled by alpha. Both engines run all of them: applySetup here is the default engine (hylograph-forces, PureScript, no D3), and Hylograph.ForceEngine.Setup.WASM.applySetup is the Rust/WASM kernel.

#Value Source

data Value node a

A value that is one constant, or computed from each element it applies to: Value node a per node, Value (LinkEnds node) a per link.

Constructors

#static Source

static :: forall node a. a -> Value node a

Create a static value

#dynamic Source

dynamic :: forall node a. (node -> a) -> Value node a

Create a dynamic (per-node, or per-link) value

#valueToNumber Source

valueToNumber :: forall node. Value node Number -> Number

Extract a number from a Value (for static values only, dynamic returns default) Used internally; prefer the accessor pattern for dynamic values

#LinkEnds Source

type LinkEnds node = { index :: Int, source :: node, target :: node }

What a per-link value is computed from: the nodes at the link's two ends and the link's position in the simulation's link array.

#LinkStrength Source

data LinkStrength node

How strong each link's spring is.

Constructors

  • LinkStrength (Value (LinkEnds node) Number)

    A constant, or computed per link.

  • ByDegree

    d3-force's own default: 1 / min(links at the source, links at the target), so that heavily linked nodes are not pulled apart.

#ForceConfig Source

data ForceConfig node

Configuration for a single force: one constructor per kind of force, each with a record of that force's own parameters. Parameterized by node type for dynamic values and filters.

Constructors

#ManyBodyConfig Source

type ManyBodyConfig node = { distanceMax :: Number, distanceMin :: Number, filter :: Maybe (node -> Boolean), name :: String, scope :: ManyBodyScope node, strength :: Value node Number, theta :: Number }

Charge: every node repels (negative) or attracts (positive) every other.

#ManyBodyScope Source

data ManyBodyScope node

Which pairs of nodes a many-body force acts between. A node whose group is Nothing is in no group: it has no same-group pairs, and is in a different group from everyone.

Constructors

#CollideConfig Source

type CollideConfig node = { alphaScaled :: Boolean, filter :: Maybe (node -> Boolean), iterations :: Int, name :: String, radius :: Value node Number, strength :: Number }

Circles that must not overlap.

A node the filter leaves out collides with nothing. With alphaScaled the strength used is strength * alpha, so the collision weakens as the simulation cools and gives way to forces that hold a node at a place; without it (d3's collide) a collision is as hard at rest as in flight.

#LinkConfig Source

type LinkConfig node = { distance :: Value (LinkEnds node) Number, iterations :: Int, name :: String, strength :: LinkStrength node }

Springs along the simulation's links.

#CenterConfig Source

type CenterConfig = { name :: String, strength :: Number, x :: Number, y :: Number }

Move the mean position of all nodes toward a point.

#PositionConfig Source

type PositionConfig node = { filter :: Maybe (node -> Boolean), name :: String, strength :: Value node Number, target :: Value node Number }

Pull toward an x (PositionXForce) or a y (PositionYForce).

#RadialConfig Source

type RadialConfig node = { filter :: Maybe (node -> Boolean), name :: String, radius :: Value node Number, strength :: Value node Number, x :: Number, y :: Number }

Pull toward a circle of a given radius around (x, y).

#TowardsConfig Source

type TowardsConfig node = { filter :: Maybe (node -> Boolean), name :: String, strength :: Value node Number, target :: node -> Maybe { x :: Number, y :: Number } }

A spring from each node to its own target point: v += (target - position) * strength * alpha. Nothing leaves a node alone. For morphing between layouts: on the WASM engine the targets can be replaced between ticks without re-applying the setup (Hylograph.ForceEngine.Setup.WASM.retarget); on the default engine, apply the setup again.

#RectCollideConfig Source

type RectCollideConfig node = { filter :: Maybe (node -> Boolean), halfHeight :: Value node Number, halfWidth :: Value node Number, iterations :: Int, name :: String, scope :: ManyBodyScope node, strength :: Number, throughSqueeze :: Boolean }

Axis-aligned rectangles (for labels) that must not overlap: an overlapping pair is pushed apart along the axis on which it overlaps least, the larger rectangle moving less. A pinned rectangle (fx, fy) is never moved, and what overlaps it takes the whole push.

A node the filter leaves out collides with nothing. scope restricts the pairs by group: only two nodes of the same group, or only two nodes not of the same group (labels against dots, say, and not each other).

throughSqueeze: a rectangle pushed from both sides on an axis goes through one of them instead of staying where the pushes cancel (the way it is already moving, else with the stronger side). That is what resolves crowded wide rectangles, and it wants nothing else pressing them together: under a pull that does not die away, a rectangle is walked through its neighbour. The rule in full is on Hylograph.Forces.RectCollide.

#ContainConfig Source

type ContainConfig node = { halfHeight :: Value node Number, halfWidth :: Value node Number, hard :: Boolean, name :: String, radius :: Value node Number, region :: node -> Maybe Int, regions :: Array Region, strength :: Number }

Keep nodes inside regions. Each node is confined to regions !! i where region node == Just i (Nothing: free). What is kept inside is the node's body: a rectangle of halfWidth by halfHeight grown all round by radius (a circle when the half-extents are 0, as they are by default; in a circular region a rectangle counts as the circle round it). strength (0 to 1) steers a node that is about to leave back toward the nearest allowed point; hard also clamps positions into the region after each tick, so that no node is ever drawn outside.

#Region Source

data Region

A region nodes can be confined to.

Constructors

#CohesionConfig Source

type CohesionConfig node = { filter :: Maybe (node -> Boolean), group :: node -> Maybe Int, name :: String, strength :: Value node Number }

Pull each node toward the centroid of its group: v += (centroid - position) * strength * alpha. Nothing: in no group.

#DirectionalConfig Source

type DirectionalConfig node = { axis :: { x :: Number, y :: Number }, gap :: Value (LinkEnds node) Number, hard :: Boolean, iterations :: Int, name :: String, strength :: Value (LinkEnds node) Number }

Over the simulation's links: push each link's target to be at least gap beyond its source along axis (children below parents, with axis (0, 1)). Links already that far apart are left alone.

As a force it is scaled by alpha and shared with everything else that pushes, so the gap it leaves can be well short of the one asked for. With hard the links are also projected after each tick, so that the gap asked for is the gap kept: a link short of its gap moves its target along the axis by the shortfall (its source back, if the target is pinned and the source is not).

#forceName Source

forceName :: forall node. ForceConfig node -> String

Get the name of a force config

#forceType Source

forceType :: forall node. ForceConfig node -> ForceType

Which kind of force a config is

#manyBody Source

manyBody :: forall node. String -> ForceConfig node

Create a many-body (charge) force Default: repulsive with strength -30

#collide Source

collide :: forall node. String -> ForceConfig node

Create a collision force Default: radius 1, strength 1

#center Source

center :: forall node. String -> ForceConfig node

Create a centering force Default: center at (0, 0), strength 1

#positionX Source

positionX :: forall node. String -> ForceConfig node

Create an X-positioning force Default: x = 0, strength 0.1

#positionY Source

positionY :: forall node. String -> ForceConfig node

Create a Y-positioning force Default: y = 0, strength 0.1

#radial Source

radial :: forall node. String -> ForceConfig node

Create a radial force Default: radius 100, center (0,0), strength 0.1

#towards Source

towards :: forall node. String -> (node -> Maybe { x :: Number, y :: Number }) -> ForceConfig node

Create a force pulling each node toward its own point. Default: strength 0.1. A node whose target is Nothing is left alone.

#rectCollide Source

rectCollide :: forall node. String -> ForceConfig node

Create a rectangle collision force. Default: half-width 1, half-height 1, strength 1, 1 iteration, every pair, a squeezed rectangle stays put.

#contain Source

contain :: forall node. String -> Region -> ForceConfig node

Create a containment force keeping every node in one region. Default: radius 0, strength 1, with the hard limit on. For several regions use withRegions and withRegion.

#containEach Source

containEach :: forall node. String -> Array Region -> (node -> Maybe Int) -> ForceConfig node

Create a containment force keeping each node in a region of its own: node n in regions !! i where region n == Just i, and free where it is Nothing. Defaults as contain.

#cohesion Source

cohesion :: forall node. String -> (node -> Maybe Int) -> ForceConfig node

Create a group cohesion force. Default: strength 0.1.

#directional Source

directional :: forall node. String -> ForceConfig node

Create a directional link constraint. Default: gap 30 along (0, 1) (targets below sources), strength 1, soft (withHardLimit true makes the gap exact).

#withStrength Source

withStrength :: forall node. Value node Number -> ForceConfig node -> ForceConfig node

Set strength.

Per node (dynamic) for ManyBody, PositionX/Y, Radial, Towards and Cohesion. Collide, Center, RectCollide and Contain have one strength: a static sets it, a dynamic is ignored. For Link and Directional a static sets every link's strength and a dynamic, being a function of a node, is ignored: use withLinkStrength.

#withRadius Source

withRadius :: forall node. Value node Number -> ForceConfig node -> ForceConfig node

Set radius (Collide and Radial; the node's own radius for Contain)

#withX Source

withX :: forall node. Value node Number -> ForceConfig node -> ForceConfig node

Set X: the target of PositionX (per node if dynamic), or the centre of Center and Radial (static only).

#withY Source

withY :: forall node. Value node Number -> ForceConfig node -> ForceConfig node

Set Y: the target of PositionY (per node if dynamic), or the centre of Center and Radial (static only).

#withDistance Source

withDistance :: forall node. Value node Number -> ForceConfig node -> ForceConfig node

Set every link's distance (for Link; static only: a dynamic here is a function of a node and is ignored, use withLinkDistance).

#withTheta Source

withTheta :: forall node. Number -> ForceConfig node -> ForceConfig node

Set theta (Barnes-Hut approximation, for ManyBody)

#withIterations Source

withIterations :: forall node. Int -> ForceConfig node -> ForceConfig node

Set iterations (for Collide, Link, RectCollide, Directional)

#withFilter Source

withFilter :: forall node. (node -> Boolean) -> ForceConfig node -> ForceConfig node

Add a filter predicate: the force only applies to matching nodes. For ManyBody (a filtered-out node exerts no charge but is still pushed), Collide and RectCollide (a filtered-out node collides with nothing), PositionX, PositionY, Radial, Towards and Cohesion.

#withDistanceMin Source

withDistanceMin :: forall node. Number -> ForceConfig node -> ForceConfig node

Set distance min (for ManyBody)

#withDistanceMax Source

withDistanceMax :: forall node. Number -> ForceConfig node -> ForceConfig node

Set distance max (for ManyBody)

#withLinkDistance Source

withLinkDistance :: forall node. Value (LinkEnds node) Number -> ForceConfig node -> ForceConfig node

Set link distance per link, from the nodes at its two ends (for Link)

#withLinkStrength Source

withLinkStrength :: forall node. Value (LinkEnds node) Number -> ForceConfig node -> ForceConfig node

Set strength per link, from the nodes at its two ends (Link, Directional)

#withDegreeStrength Source

withDegreeStrength :: forall node. ForceConfig node -> ForceConfig node

Give links d3-force's default strength, 1 / min(links at the source, links at the target) (for Link)

#withTarget Source

withTarget :: forall node. (node -> Maybe { x :: Number, y :: Number }) -> ForceConfig node -> ForceConfig node

Set each node's target point (for Towards)

#withAlphaScaling Source

withAlphaScaling :: forall node. Boolean -> ForceConfig node -> ForceConfig node

Make a collision's strength follow alpha, so that it yields as the simulation cools (for Collide). Off by default.

#withHalfWidth Source

withHalfWidth :: forall node. Value node Number -> ForceConfig node -> ForceConfig node

Set the rectangles' half-width (for RectCollide; the half-width of the node's body for Contain)

#withHalfHeight Source

withHalfHeight :: forall node. Value node Number -> ForceConfig node -> ForceConfig node

Set the rectangles' half-height (for RectCollide; the half-height of the node's body for Contain)

#withThroughSqueeze Source

withThroughSqueeze :: forall node. Boolean -> ForceConfig node -> ForceConfig node

Let a rectangle that is pushed from both sides go through one of them (for RectCollide). Off by default. See RectCollideConfig.

#withRegions Source

withRegions :: forall node. Array Region -> ForceConfig node -> ForceConfig node

Set the regions (for Contain); withRegion says which node is in which

#withRegion Source

withRegion :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig node

Assign each node a region by its index in the regions array, or Nothing to leave it free (for Contain)

#withHardLimit Source

withHardLimit :: forall node. Boolean -> ForceConfig node -> ForceConfig node

Turn the correction after each tick on or off. For Contain it is the clamp into the region (off, the region only steers); for Directional it is the projection that makes the gap exact (off, the default there, the gap is only pushed towards).

#withGroup Source

withGroup :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig node

Set each node's group (for Cohesion)

#withinGroups Source

withinGroups :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig node

Restrict a ManyBody or RectCollide force to pairs of nodes in the same group

#betweenGroups Source

betweenGroups :: forall node. (node -> Maybe Int) -> ForceConfig node -> ForceConfig node

Restrict a ManyBody or RectCollide force to pairs of nodes in different groups (a node in no group is in a different group from everyone)

#withGap Source

withGap :: forall node. Value (LinkEnds node) Number -> ForceConfig node -> ForceConfig node

Set the gap each link's target must be beyond its source, per link if dynamic (for Directional)

#withAxis Source

withAxis :: forall node. { x :: Number, y :: Number } -> ForceConfig node -> ForceConfig node

Set the direction targets are pushed in; it need not be a unit vector (for Directional)

#linkValues Source

linkValues :: forall node. Value (LinkEnds node) Number -> Array (LinkEnds node) -> Array Number

One number per link.

#linkStrengths Source

linkStrengths :: forall row. LinkStrength (SimulationNode row) -> Array (LinkEnds (SimulationNode row)) -> Array Number

One strength per link. ByDegree is d3-force's default, 1 / min(links at the source, links at the target).

#recipe Source

recipe :: forall row. ForceConfig (SimulationNode row) -> ForceRecipe row

What a force of a setup is to the default engine: how to make it once the nodes and links are known.

  • per node (dynamic): every strength, radius, target and half-extent;
  • filters: a filtered-out node has strength 0 (ManyBody, PositionX/Y, Radial, Towards, Cohesion) or collides with nothing (Collide);
  • per link: distance, strength, gap, and ByDegree.

#linkProblem Source

linkProblem :: forall row. Setup (SimulationNode row) -> Array (SimulationNode row) -> Links -> Maybe String

What is wrong with the links, for this setup: node not found: <id> for the first link end that is no node's id, if the setup has a force that acts along the links (Link, Directional). Nothing if every end is there, or if no force would look. This is the one condition under which applySetup fails, on either engine.

#Setup Source

type Setup node = { forces :: Array (ForceConfig node), name :: String, params :: SetupParams }

Complete setup: forces + simulation params

#SetupParams Source

type SetupParams = { alpha :: Number, alphaDecay :: Number, alphaMin :: Number, alphaTarget :: Number, velocityRetention :: Number }

Simulation parameters

#defaultParams Source

defaultParams :: SetupParams

Default simulation parameters

#setup Source

setup :: forall node. String -> Array (ForceConfig node) -> Setup node

Create a setup with default params

#setupWithParams Source

setupWithParams :: forall node. String -> Array (ForceConfig node) -> SetupParams -> Setup node

Create a setup with custom params

#getForces Source

getForces :: forall node. Setup node -> Array (ForceConfig node)

Get forces from setup

#getParams Source

getParams :: forall node. Setup node -> SetupParams

Get params from setup

#addForce Source

addForce :: forall node. ForceConfig node -> Setup node -> Setup node

Add a force to the setup

#removeForce Source

removeForce :: forall node. String -> Setup node -> Setup node

Remove a force by name

#updateForce Source

updateForce :: forall node. ForceConfig node -> Setup node -> Setup node

Update a force by name (replace if exists)

#withAlpha Source

withAlpha :: forall node. Number -> Setup node -> Setup node

Set alpha

#withAlphaDecay Source

withAlphaDecay :: forall node. Number -> Setup node -> Setup node

Set alpha decay

#withAlphaTarget Source

withAlphaTarget :: forall node. Number -> Setup node -> Setup node

Set alpha target

#withAlphaMin Source

withAlphaMin :: forall node. Number -> Setup node -> Setup node

Set alpha min

#withVelocityRetention Source

withVelocityRetention :: forall node. Number -> Setup node -> Setup node

Set the share of its velocity a node keeps from one tick to the next (0.4 by default). 1 loses nothing; 0 stops every node dead each tick.

#withVelocityDecay Source

withVelocityDecay :: forall node. Number -> Setup node -> Setup node

Deprecated: the old name of withVelocityRetention, kept so that existing code compiles. It does exactly what it always did: the number is the share of velocity KEPT each tick, not the share lost, which is the opposite of what d3 means by velocityDecay.

#applySetup Source

applySetup :: forall row linkRow. Setup (SimulationNode row) -> Simulation row linkRow -> Effect Unit

Apply a setup to a simulation.

This is idempotent - calling with the same setup does minimal work:

  • Forces in setup but not simulation: create and add
  • Forces in simulation but not setup: remove

Every force is made afresh for the simulation's current nodes and links: dynamic values, filters, groups and regions are evaluated then, once per node or per link. Apply the setup again after changing what they read. Each tick applies the forces in order of their names.

Throws, before changing anything, if a link names a node that is not among the nodes and the setup has a force along the links (node not found: <id>, as d3-force says it). tryApplySetup returns that as a value instead.

The setup's params (alpha, alphaMin, alphaDecay, alphaTarget, velocityRetention) become the simulation's, replacing what it was created with.

Example:

-- Initial setup
applySetup mySetup sim

-- Later: update setup (just call again)
applySetup (mySetup # removeForce "charge") sim

#tryApplySetup Source

tryApplySetup :: forall row linkRow. Setup (SimulationNode row) -> Simulation row linkRow -> Effect (Either String Unit)

applySetup, with the one thing that can go wrong as a value: Left names the first link end that is no node's id (node not found: <id>), and the simulation is left as it was.

#GUPResult Source

type GUPResult node = { entered :: Array node, exited :: Array node, updated :: Array node }

Result of a node data update with enter/update/exit categorization

  • entered: Nodes newly added to simulation (use for enter animations)
  • updated: Existing nodes that were modified (simulation state preserved)
  • exited: Nodes removed from simulation (use for exit animations)

#GUPLinkResult Source

type GUPLinkResult :: Row Type -> Typetype GUPLinkResult linkRow = { entered :: Array { source :: NodeID, target :: NodeID | linkRow }, exited :: Array { source :: NodeID, target :: NodeID | linkRow }, updated :: Array { source :: NodeID, target :: NodeID | linkRow } }

Result of a link data update with enter/update/exit categorization Links are keyed by (source, target) pair

#applySetupWithData Source

applySetupWithData :: forall row linkRow. Setup (SimulationNode row) -> Array (SimulationNode row) -> Array { source :: NodeID, target :: NodeID | linkRow } -> Simulation row linkRow -> Effect { links :: GUPLinkResult linkRow, nodes :: GUPResult (SimulationNode row) }

Apply setup with new nodes and links, using GUP (General Update Pattern) semantics.

This function handles three concerns:

  1. Force configuration (same as applySetup)
  2. Node GUP: diff desired nodes vs current, merge simulation state for updates
  3. Link GUP: diff desired links vs current

Simulation state preservation (for updated nodes):

  • x, y: Current position (preserved)
  • vx, vy: Current velocity (preserved)
  • fx, fy: Pinned position (preserved)
  • All other fields: Taken from desired nodes

Example usage:

-- Stop simulation before transition
Sim.stop sim

-- Apply new configuration and data
result <- applySetupWithData mySetup newNodes newLinks sim

-- Use result for animations
animateEnter result.nodes.entered
animateExit result.nodes.exited

-- Restart simulation
Sim.reheat sim

#NodeGUPInternal Source

type NodeGUPInternal node = { entered :: Array node, exited :: Array node, merged :: Array node, updated :: Array node }

Internal result type that includes the merged array

#computeNodeGUP Source

computeNodeGUP :: forall row. Array (SimulationNode row) -> Array (SimulationNode row) -> NodeGUPInternal (SimulationNode row)

Compute node GUP: which nodes are entering, updating, exiting For updates, merge simulation state (x, y, vx, vy, fx, fy) from current into desired

#computeLinkGUP Source

computeLinkGUP :: forall linkRow. Array { source :: NodeID, target :: NodeID | linkRow } -> Array { source :: NodeID, target :: NodeID | linkRow } -> GUPLinkResult linkRow

Compute link GUP: which links are entering, updating, exiting Links are keyed by (source, target) pair

#mergeSimulationState Source

mergeSimulationState :: forall row. SimulationNode row -> SimulationNode row -> SimulationNode row

Merge simulation-managed state from current node into desired node

Preserves: x, y, vx, vy, fx, fy (simulation-managed) Takes from desired: everything else (application data)

#addForceToSim Source

addForceToSim :: forall row linkRow. ForceConfig (SimulationNode row) -> Simulation row linkRow -> Effect Unit

Add a single force to simulation (without full setup). Throws if a link names a node that is not among the nodes.

#removeForceFromSim Source

removeForceFromSim :: forall row linkRow. String -> Simulation row linkRow -> Effect Unit

Remove a single force from simulation by name