GoJS API
/ to search
    Preparing search index...

    Class ForceDirectedLayout

    Force-directed layout treats the graph as if it were a system of physical bodies with repulsive electrical, attractional gravitational, and spring forces acting on them and between them.

    Electrical forces come both from the field at the vertex's location as well as from neighboring vertexes and are quadratic by distance. Gravitational forces come from the field at the vertex's location and are constant. Spring forces are only exerted between two different vertexes that are connected by an edge and are linear by distance.

    The electrical forces on a vertex are the sum of the electrical charge times the electrical field at that location (electricalCharge, electricalFieldX, electricalFieldY) and the electrical forces of all nearby vertexes divided by the square of the distance between them. You can easily assign the electrical charge for all vertexes by assigning defaultElectricalCharge. By default there is no electrical field, so all forces are due to nearby charged vertexes. For efficiency, infinityDistance determines a cut-off distance between vertexes for which to consider any influence.

    The gravitational forces on a vertex are the sum of the gravitational mass times the gravitational field at that location (gravitationalMass, gravitationalFieldX, gravitationalFieldY). You can easily assign the gravitational mass for all vertexes by assigning defaultGravitationalMass. By default there is no gravitational field.

    The spring forces on a vertex are only exerted by the edges connecting it with other vertexes. The force along an edge is the stiffness of the spring times the difference of the distance between the vertexes and the nominal length of the spring (springStiffness, springLength) divided by the distance between the vertexes. When the distance is less than the nominal length, the force pushes the vertexes apart; when the distance is greater, the force pulls them together. You can easily assign the spring length and stiffness for all edges by assigning defaultSpringLength and defaultSpringStiffness.

    When the distance between two vertexes is less than one unit, this uses a random number generator to decide which direction the forces should go. For layouts that start with all of the vertexes at the same location, this results in potentially dramatically different results. Set randomNumberGenerator to null in order to produce reproducible results given the same initial vertex locations.

    The algorithm seeks a configuration of the bodies with locally minimal energy, i.e. vertex positions such that the sum of the forces on each vertex is zero. This is achieved by repeatedly computing the forces on each vertex, moving them, and repeating. Computations stop when no vertex moves more than epsilonDistance or when maxIterations have happened.

    The layout cannot guarantee that it provides optimal positioning of nodes. Nodes will normally not overlap each other, but when there is a dense interconnectivity overlaps might not be avoidable.

    If you want to experiment interactively with most of the properties, try the Force Directed Layout sample. See samples that make use of ForceDirectedLayout in the samples index.

    This layout makes use of a LayoutNetwork of ForceDirectedVertexes and ForceDirectedEdges that normally correspond to the Nodes and Links of the Diagram.

    Hierarchy (View Summary)

    Index

    Constructors

    Accessors

    • get arrangementOrigin(): Point

      Gets or sets the top-left point for where the graph should be positioned when laid out. The default value for this property is the Point(0, 0). Setting this property to a new value invalidates this layout. This property is likely to be set by many Layouts that belong to a Group when the layout is performed.

      Returns Point

    • get arrangementSpacing(): Size

      Gets or sets the space between which the layout will position the connected graphs that together compose the network. This defaults to Size(100, 100). These distances are used during a clustered layout; afterwards the normal force-directed layout will likely cause the size of any space between connected graphs to change, perhaps considerably.

      Returns Size

    • get boundsComputation(): ((part: Part, lay: Layout, rect: Rect) => Rect) | null

      Gets or sets a function that determines the initial size and position in document coordinates of a LayoutVertex corresponding to a Node. This function is called by getLayoutBounds. The default value for this property is null, in which case the GraphObject.actualBounds of the Node is used. Setting this property to a new value invalidates this layout.

      The non-null value must be a function that takes 3 arguments. The first argument will be the Part whose bounds the Layout should use. The second argument will be this Layout. The third argument will be a Rect that must be modified and returned The return value must be in document coordinates. You may find it convenient to call GraphObject.getDocumentBounds to get the bounds in document coordinates of an object within the node.

      Returns ((part: Part, lay: Layout, rect: Rect) => Rect) | null

      since

      2.0

    • get comments(): boolean

      Gets or sets whether this layout should find all Nodes whose category is "Comment" and whose anchors are nodes represented in the network, and add ForceDirectedVertexes representing those balloon comments as nodes in the network. The default value is false.

      Returns boolean

    • get currentIteration(): number

      This read-only property returns the current iteration count, valid during a call to doLayout.

      Returns number

    • get defaultCommentElectricalCharge(): number

      Gets or sets the default value computed by electricalCharge. The initial value is 5.

      Returns number

    • get defaultCommentSpringLength(): number

      Gets or sets the default value computed by springLength. The initial value is 10.

      Returns number

    • get defaultElectricalCharge(): number

      Gets or sets the default value computed by electricalCharge. The initial value is 150.

      Returns number

    • get defaultGravitationalMass(): number

      Gets or sets the default value computed by gravitationalMass. The initial value is zero.

      Returns number

    • get defaultSpringLength(): number

      Gets or sets the default value computed by springLength. The initial value is 50.

      Returns number

    • get defaultSpringStiffness(): number

      Gets or sets the default value computed by springStiffness. The initial value is 0.05.

      Returns number

    • get diagram(): Diagram | null

      Gets the Diagram that owns this layout, if it is the value of Diagram.layout.

      If this property and group are non-null, the Group should be in this Diagram.

      Returns Diagram | null

      see

      group

    • get epsilonDistance(): number

      Gets or sets approximately how far a node must move in order for the iterations to continue. The default value is 1. The value must be larger than zero.

      Returns number

    • get group(): Group | null

      Gets the Group that uses this layout, if it is the value of a group's Group.layout.

      If this property is set to a Group, the diagram is automatically set to be the Group's Diagram.

      Returns Group | null

    • get infinityDistance(): number

      Gets or sets a threshold for the distance beyond which the electrical charge forces may be ignored. If NaN, there is no distance cutoff and all vertices contribute to electrical forces (via Barnes-Hut approximation). Setting a finite value can be useful for incremental layouts where you want to limit the influence of distant nodes. The default value is Infinity. If set, the value must be larger than 1.

      Returns number

    • get isInitial(): boolean

      Gets or sets whether this layout is performed on an initial layout. The default value is true. Setting this property to false causes isValidLayout to be set to true so that the diagram does not perform this layout.

      If you set both isInitial and isOngoing to false, there will be no automatic layout invalidation, because invalidateLayout will not set isValidLayout to false. To get your nodes to appear, you will need to explicitly set or data-bind their Part.location or GraphObject.position to real Point values, because automatic layout will not assign any positions.

      Another way of controlling when layouts are invalidated is by setting Part.isLayoutPositioned or Part.layoutConditions.

      Returns boolean

    • get isOngoing(): boolean

      Gets or sets whether this layout can be invalidated by invalidateLayout. Set this to false to prevent actions such as adding or removing Parts from invalidating this layout. The default value is true. Setting this property does not invalidate this layout.

      If you set both isInitial and isOngoing to false, there will be no automatic layout invalidation, because invalidateLayout will not set isValidLayout to false. To get your nodes to appear, you will need to explicitly set or data-bind their Part.location or GraphObject.position to real Point values, because automatic layout will not assign any positions.

      Another way of controlling when layouts are invalidated is by setting Part.isLayoutPositioned or Part.layoutConditions.

      Returns boolean

    • get isRealtime(): boolean | null

      Gets or sets whether this layout be performed in real-time, before the end of a transaction. All layouts that are invalidated will be performed at the end of a transaction. The default value is null. A null value is treated as true for a Diagram.layout but false for a Group.layout. Setting this property does not invalidate this layout.

      Returns boolean | null

    • get isRouting(): boolean

      Gets or sets whether this layout routes Links. The default value is true. When false, this layout will not explicitly set the Link.points, and the default routing of each individual Link will take place after the Nodes are moved by commitLayout. Setting this property does not invalidate this layout.

      Some layouts ignore links, in which case this property is ignored.

      Returns boolean

    • get isValidLayout(): boolean

      Gets or sets whether this layout needs to be performed again (if false). Instead of setting this property directly, it is normal to set it to false by calling invalidateLayout, since that also requests performing a layout in the near future.

      Returns boolean

    • get isViewportSized(): boolean

      Gets or sets whether this layout depends on the Diagram.viewportBounds's size. If set to true, the layout will invalidate when the Diagram's viewport changes size. This only applies to diagram layouts, not to group layouts, and only when Diagram.autoScale is set to AutoScale.None.

      The default value is false. Setting this property to true will invalidate this layout.

      It is possible that a viewport-sized layout will trigger the Diagram to require scrollbars, which modifies the Diagram.viewportBounds, which will in turn trigger another layout. This is uncommon, but possible with GridLayout if the results require a vertical scrollbar, and that vertical scrollbar shrinks the viewport width enough that a grid column can no longer fit. When designing custom layouts, one should be careful that this behavior does not result in an infinite loop.

      Returns boolean

    • get maxIterations(): number

      Gets or sets the maximum number of iterations to perform when doing the force-directed auto layout. The value must be non-negative. The default value is 300.

      Returns number

    • get maxPrelayoutIterations(): number

      Gets or sets the maximum number of iterations to perform when doing the force-directed spring-based prelayout. The value must be non-negative. The default value is 100.

      Returns number

    • get moveLimit(): number

      Gets or sets how far a vertex may be moved in an iteration. A large value will generally produce the highest-qaulity layout, though it may cause nodes to move unnecessarily far during incremental operations. The default value is Infinity.

      Returns number

    • get prelayoutQuality(): number

      Gets or sets the quality of the prelayout operation. The value must be greater than or equal to zero, with 0 meaning no prelayout operation and Infinity meaning the highest quality possible prelayout. Lower values will reduce memory usage: if the value is Infinity or greater than the size of the graph, the algorithm will use quadratic space; if the value is 1 linear space will be used.

      The default value is NaN, which will attempt to find a good value based on the number of nodes and links in each connected subgraph.

      Returns number

    • get prelayoutSpread(): number

      Gets or sets the of the prelayout operation. Increasing this number will cause the graph to be significantly more spread out, which is particularly useful in graphs with large node sizes. Decreasing this number may reduce the number of long links in the graph. The default value is 10.

      Returns number

    • get randomNumberGenerator(): { random: () => number } | null

      Gets or sets a random number generator. The default value uses cryptographically secure random numbers via crypto.getRandomValues(). Set this to Math to use Math.random() instead, or set this to null in order to use an instance of an internal repeatable pseudo-random number generator, which will become the new value of this property.

      The new value must be either null or an Object with a method named "random" taking zero arguments and returning a random number between zero (inclusive) and one (exclusive).

      Returns { random: () => number } | null

    • get setsPortSpots(): boolean

      Gets or sets whether the fromSpot and the toSpot of every Link should be set to Spot.Default. The default value is true.

      Returns boolean

    • get theta(): number

      Gets or sets the Barnes-Hut theta threshold for the force-directed layout. This controls the trade-off between accuracy and performance in the Barnes-Hut approximation. Lower values (closer to 0) give more accurate force calculations but are slower. Higher values give faster but less accurate results. The default value is 1.5.

      Returns number

      since

      4.0

    Methods

    • A convenient way of converting the Diagram|Group|Iterable argument to doLayout to an actual collection of eligible Parts. The resulting Set will not include any Nodes or Links for which Part.canLayout is false. If the argument includes a Group for which Group.layout is null, the resulting Set will include the member parts of that group rather than that group itself. You will not need to call collectParts if you call makeNetwork, because that method does effectively the same thing when building the LayoutNetwork.

      Typical usage:

      public doLayout(coll) {
      // COLL might be a Diagram or a Group or some Iterable<Part>
      const it = this.collectParts(coll).iterator;
      while (it.next()) {
      const node = it.value;
      if (node instanceof go.Node) {
      . . . position the node . . .
      }
      }
      }

      Parameters

      Returns Set<Part>

    • Set the fromSpot and toSpot on each Link, position each Node according to the vertex position, and then position/route the Links.

      This calls the commitNodes and commitLinks methods, the latter only if isRouting is true. You should not call this method -- it is a "protected virtual" method. Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Returns void

    • Routes the links.

      This is called by commitLayout. This is only called if Layout.isRouting is true. See also commitNodes. Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Returns void

    • Commit the position of all nodes.

      This is called by commitLayout. See also commitLinks. Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Returns void

    • Returns the electrical field in the X direction acting on a vertex at the given point. By default there is no electrical field at any location.

      Used to define an external electrical field at a point independent of the vertex charges. A vertex L is acted upon by a force in the X direction of proportional to electricalFieldX(L.center.x, L.center.y) * electricalCharge(L). Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Parameters

      • x: number
      • y: number

      Returns number

      the default implementation returns zero.

    • Returns the electrical field in the Y direction acting on a vertex at the given point. By default there is no electrical field at any location.

      Used to define an external electrical field at a point independent of the vertex charges. A vertex L is acted upon by a force in the Y direction of proportional to electricalFieldY(L.center.x, L.center.y) * electricalCharge(L). Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Parameters

      • x: number
      • y: number

      Returns number

      the default implementation returns zero.

    • This method is called by layouts to determine the size and initial position of the nodes that it is laying out. Normally this just returns the part's GraphObject.actualBounds. However, if boundsComputation has been set to a function, that function will be called in order to return the bounds of the given Part in document coordinates that the layout should pretend it has.

      Parameters

      • part: Part

        the Part being laid out

      • Optionalrect: Rect

        an optional Rect that will be modified and returned

      Returns Rect

      a Rect in document coordinates

      since

      2.0

    • This returns the gravitational field in the X direction acting on a vertex at the given point. By default there is no gravitational field at any location.

      Used to define an external gravitational field at a point independent of the vertex masses. A vertex L is acted upon by a force in the X direction of proportional to gravitationalFieldX(L.center.x, L.center.y) * gravitationalMass(L). Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Parameters

      • x: number
      • y: number

      Returns number

      the default implementation returns zero.

    • This returns the gravitational field in the Y direction acting on a vertex at the given point. By default there is no gravitational field at any location.

      Used to define an external gravitational field at a point independent of the vertex masses. A vertex L is acted upon by a force in the Y direction of proportional to gravitationalFieldY(L.center.x, L.center.y) * gravitationalMass(L). Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Parameters

      • x: number
      • y: number

      Returns number

      the default implementation returns zero.

    • Compute the desired value of arrangementOrigin if this Layout is being performed for a Group. This is typically called near the beginning of the implementation of doLayout: this.arrangementOrigin = this.initialOrigin(this.arrangementOrigin); if the layout wants to respect the pre-layout location of the Group when deciding where to position its member nodes.

      Parameters

      Returns Point

    • If isOngoing is true and if an initial layout has not yet been performed, set the isValidLayout property to false, and ask to perform another layout in the near future. If isInitial is true, this layout is invalidated only when the Diagram.model is replaced, not under the normal circumstances such as when parts are added or removed or due to other calls to Layout._invalidateLayout.

      If you set both isInitial and isOngoing to false, there will be no automatic layout invalidation, because this method will not set isValidLayout to false. However you can still set isValidLayout explicitly.

      This is typically called when a layout property value has changed, or when a Part is added or removed or changes visibility, if Part.layoutConditions includes the pertinent flags.

      Returns void

    • This predicate returns true if the vertex should not be moved by the layout algorithm but still have an effect on nearby and connected vertexes. The default implementation returns ForceDirectedVertex.isFixed. Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Parameters

      Returns boolean

      returns true if the node should not be moved by the layout algorithm.

    • Determines whether a spring-based prelayout should be performed before the main force-directed layout operation. In general this should occur when the network has not already been laid out either by ForceDirectedLayout or some other algorithm.

      By default, this function will return true if any node in the network has a NaN position, likely meaning it has not been positioned yet, or if a large number of nodes in the network in the network overlap. This function can be overriden to provide custom logic for determining whether a prelayout should be performed.

      Returns boolean

      since

      3.0

    • Determines whether the layout should calculate electrical forces between two given vertexes, for example, for layouts that should stop moving vertexes once they no longer physically overlap.

      By default, this always returns true.

      Returns boolean

      since

      3.0

    • Returns the length of the spring representing an edge. The two vertexes connected by the edge E are acted upon by a force of proportional to springStiffness(E) * (getNodeDistance(E.fromVertex, E.toVertex) - springLength(E)) divided by the distance between the vertexes. Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Parameters

      Returns number

      Returns the length of the edge representing a link, the value of ForceDirectedEdge.length if it's a number, or else the value of defaultSpringLength.

    • Returns the stiffness of the spring representing an edge.

      The spring force between two vertexes connected by an edge is linearly proportional by distance to the difference between the springLength and the distance. When the distance is greater than the length, the force pulls the vertexes closer to each other. When the distance is less than the length, the force pushes them apart.

      The two vertexes connected by the edge E are acted upon by a force of proportional to springStiffness(E) * (getNodeDistance(E.fromVertex, E.toVertex) - springLength(E)) divided by the distance between the vertexes. Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Parameters

      Returns number

      Returns the stiffness of the edge representing a link, the value of ForceDirectedEdge.stiffness if it's a number, or else the value of defaultSpringStiffness.

    • When using a LayoutNetwork, update the "physical" node positionings and link routings. This should be called by doLayout when this layout uses a network. This calls commitLayout to actually set Node positions and route Links. This performs the changes within a transaction. Please read the Learn page on Extensions for how to override methods and how to call this base method.

      Returns void