thomasp85 / particles

A particle simulation engine based on a port of d3-force
Other
118 stars 9 forks source link

Issue with polygon_constraint #8

Closed nfarmer01 closed 2 years ago

nfarmer01 commented 3 years ago

Hoping to simulate particles moving in an enclosed, reflective polygon. Noting that particles in simulation with imposed polygon_constraint have velocity set at zero upon hitting boundary. In the resultant GIF, it appears that particles on the right and bottom are reflecting off the boundary, whereas particles on the top and left are sticking and forming a line along those two boundaries. Is there a way to maintain particle velocities and just reflect off the boundary?

Waschina commented 3 years ago

Hi @thomasp85 , first of all, thank you for this great R-package - it is super fun using it. I am applying it to simulate movement of microorganisms.

I experienced a similar issue as @nfarmer01 mentioned above. Specifically, it seems that some particles remain stuck at polygon boundaries. Here is an example (I tried to keep it as minimal as possible):

library(particles)
library(tidygraph)

# a triangle
fences <- cbind(sin(seq(from = 0, to = 2*pi, length.out = 4)) * 50,
                cos(seq(from = 0, to = 2*pi, length.out = 4)) * 50)

# 50 particles
nodes <- data.frame(id = 1:50)

# particles simulation: random movement within fences
sim <- tbl_graph(nodes = nodes, directed = F, node_key = "id") %>%
  simulate() %>%
  wield(random_force) %>%
  wield(collision_force) %>%
  impose(polygon_constraint,
         polygon = fences) %>%
  evolve() %>% 
  as_tbl_graph()

plot(sim)

Since some particles seem to stick to the diagonal edges but not the horizontal edge; the underlying issue might be problem with numeric accuracy of the particles coordinates. I tried to trace it back in the source code and responsible seem to be this line:

https://github.com/thomasp85/particles/blob/b410f9e2df18731028e6244101d74d6fe3fa1348/R/polygon_constraint.R#L72

When I use the function mgcv::in.out(…) with the polygon and the particles coordinates; the results indicate that some particles are outside the polygon although they should be inside due the polygon_constraint in the particles simulation.

particle_coords <- as.matrix(as.data.frame(sim)[,c("x","y")])
mgcv::in.out(fences, particle_coords)

Would it be possible, to ensure that particles that are pulled back into the polygon with the function points_to_path are also recognized by mgcv::in.out to be within the polygon boundaries?

thomasp85 commented 3 years ago

Hi — I'm currently not focusing my time on particles. I'd be happy to review a PR but other wise you'd have to wait a bit for fix🙂

Waschina commented 3 years ago

Sure, I understand and can try to come up with a fix.