多体力
🌐 Many-body force
多体(或 n 体)力作用于所有节点之间。它可以用于模拟引力(吸引),如果强度为正值,或者电荷(排斥),如果强度为负值。该实现使用四叉树和Barnes–Hut 近似来显著提高性能;精度可以通过theta参数进行自定义。
🌐 The many-body (or n-body) force applies mutually amongst all nodes. It can be used to simulate gravity (attraction) if the strength is positive, or electrostatic charge (repulsion) if the strength is negative. This implementation uses a quadtree and the Barnes–Hut approximation to greatly improve performance; the accuracy can be customized using the theta parameter.
与只影响两个相连节点的链接力不同,电荷力是全局性的:每个节点都会影响每个其他节点,即使它们在不连通的子图上。
🌐 Unlike the link force, which only affect two linked nodes, the charge force is global: every node affects every other node, even if they are on disconnected subgraphs.
forceManyBody()
来源 · 使用默认参数创建一个新的多体力。
const manyBody = d3.forceManyBody().strength(-100);manyBody.strength(strength)
来源 · 如果指定了 strength,则将强度访问器设置为指定的数字或函数,重新计算每个节点的强度访问器,并返回此力。正值会使节点彼此吸引,类似于重力,而负值会使节点彼此排斥,类似于静电荷。如果未指定 strength,则返回当前的强度访问器,默认值为:
function strength() {
return -30;
}对于模拟中的每个node,都会调用强度访问器,并传递node及其从零开始的index。所得的数字随后会被内部存储,这样每个节点的强度只有在力被初始化或当此方法以新的strength调用时才会重新计算,而不是在每次施加力的时候都计算。
🌐 The strength accessor is invoked for each node in the simulation, being passed the node and its zero-based index. The resulting number is then stored internally, such that the strength of each node is only recomputed when the force is initialized or when this method is called with a new strength, and not on every application of the force.
manyBody.theta(theta)
来源 · 如果指定了 theta,则将 Barnes–Hut 近似标准设置为指定数值并返回此力。如果未指定 theta,则返回当前值,默认为 0.9。
为了加速计算,该力实现了 Barnes–Hut 近似,每次应用的时间复杂度为 O(n log n),其中 n 是 节点 的数量。对于每次应用,使用 四叉树 存储当前的节点位置;然后,对于每个节点,计算所有其他节点对该节点的组合力。对于距离较远的节点簇,可以通过将该簇视为一个较大的单一节点来近似电荷力。theta 参数决定了近似的精度:如果四叉树单元宽度 w 与节点到该单元质心距离 l 的比值 w / l 小于 theta,则该单元中的所有节点都被视为一个单一节点,而不是分别处理。
🌐 To accelerate computation, this force implements the Barnes–Hut approximation which takes O(n log n) per application where n is the number of nodes. For each application, a quadtree stores the current node positions; then for each node, the combined force of all other nodes on the given node is computed. For a cluster of nodes that is far away, the charge force can be approximated by treating the cluster as a single, larger node. The theta parameter determines the accuracy of the approximation: if the ratio w / l of the width w of the quadtree cell to the distance l from the node to the cell’s center of mass is less than theta, all nodes in the given cell are treated as a single node rather than individually.
manyBody.distanceMin(distance)
来源 · 如果指定了distance,则设置此力被考虑的节点之间的最小距离。如果未指定distance,则返回当前的最小距离,默认为1。最小距离确立了两个相邻节点之间力的上限,以避免不稳定性。特别地,它可以避免在两个节点完全重合时出现无限强的力;在这种情况下,力的方向是随机的。
manyBody.distanceMax(distance)
来源 · 如果指定了 distance,则设置在此力作用下节点之间考虑的最大距离。如果未指定 distance,则返回当前的最大距离,默认值为无穷大。指定有限的最大距离可以提高性能,并生成更局部化的布局。