vasturiano / d3-force-limit

A positioning hard limit force type for the d3-force simulation engine
https://observablehq.com/@vasturiano/d3-force-limit
MIT License
8 stars 3 forks source link

Constraining nodes to a sphere #6

Open jokroese opened 2 years ago

jokroese commented 2 years ago

I'm trying to constrain some nodes in 3D to a sphere. I'm using 3d-force-graph and hoping to do the constraining with d3-force-limit.

My current naive approach is here: https://codepen.io/jokroese/pen/ExQMrpj.

The problems are:

  1. if a node gets outside the sphere, it doesn't always get back inside the sphere. (Try pulling one of the nodes out of the sphere in the codepen example, ~50% of the time it will stay outside.)
  2. (Smaller issue) Though the nodes are mostly spread over the sphere, there is a "belt" of higher density at $x=0$.

Do you have suggestions on next steps for moving forward with this?

Possible options:

  1. I see that @Fil suggests a neater approach for this in 2D in #1. I could try to extend this to 3D.
  2. Use a different library that is more suited to this use case.
  3. Use d3-force-limit, but in a more thoughtful way.
Fil commented 2 years ago

Here's my suggestion:

Graph.d3Force("radius", forceRadius(gData.nodes, 300));

function forceRadius(nodes, R = 1) {
  return () => {
    for (const n of nodes) {
      const r = Math.hypot(n.x, n.y, n.z);
      const u = Math.pow(r ? Math.sqrt(R / r) : 1, 0.05);
      n.x *= u;
      n.y *= u;
      n.z *= u;
    }
  }
}

see https://observablehq.com/@fil/3d-graph-on-sphere

jokroese commented 2 years ago

Thanks @Fil, that looks great!

The only unusual thing is that dragging a node seems to remove the force. Do you know why that is? And can you see an obvious way to keep the force applied while dragging?

Fil commented 2 years ago

Dragging does not remove the force, but it pushes alpha up (the "temperature", if you will), making all the other forces stronger. You could change the parameter 0.05 to make it stronger with alpha if you wanted, but it would make the initial convergence less smooth.

Bennyyy27 commented 1 year ago

I really like this approach! Thanks for sharing. Do you know if there is there any way to "pythonize" this or a similar approach in python? Or a way to import my own adjacency list to this and export the 3D coordinates?

Thanks!