Skip to content

Instantly share code, notes, and snippets.

@mschauer
Last active September 29, 2022 14:16
Show Gist options
  • Save mschauer/62adf04be80d7d02d753b458b16cc594 to your computer and use it in GitHub Desktop.
Save mschauer/62adf04be80d7d02d753b458b16cc594 to your computer and use it in GitHub Desktop.
Antisocial dance (naive/knn)
# using naive search
using GLMakie, LinearAlgebra
using StaticArrays
rot(θ) = @SMatrix [cos(θ) -sin(θ); sin(θ) cos(θ) ]
x = [Point2f(0,1), Point2f(1,0), Point2f(3, 0)]
xnew = copy(x)
δ = 0.001
xall = [copy(x)]
i = 1
for iter in 1:20000
global x, xnew, xall
for i in eachindex(x)
n = argmin(i==j ? Inf : norm(x[j] .- x[i]) for j in eachindex(x) )
Δ = x[i] - x[n]
a = norm(Δ)
if a < 1e-7
xnew[i] = x[i] + δ*((Point2f(-Δ[2], Δ[1]))/a)
else
xnew[i] = x[n] + rot(δ/a)*Δ
end
end
xnew, x = x, xnew
iter % 100 == 0 && push!(xall, copy(x))
end
fig = scatterlines(getindex.(xall, 1), markersize=1.5, linewidth=0.1)
for i in 2:3; scatterlines!(getindex.(xall, i), markersize=1.5, linewidth=0.1); end
fig
# animation settings
n_frames = 100
framerate = 30
iter = LinRange(1, length(xall), n_frames)
points = Observable(xall[1])
scene = scatter(points, markersize=15.0)
xlims!(scene.axis, (-5,5))
ylims!(scene.axis, (-5,5))
Makie.record(scene, "antisocial.mp4", iter; framerate = framerate) do i
points[] = xall[round(Int,i)]
end
# using NearestNeighbors.jl
using GLMakie, LinearAlgebra, Random, NearestNeighbors, ProgressMeter
using StaticArrays
rot(θ) = @SMatrix [cos(θ) -sin(θ); sin(θ) cos(θ) ]
#x = [Point2f(0,1), Point2f(1,0), Point2f(3, 0)]
x = rand(Point2f, 1000)
Random.seed!(1)
#append!(x, x .+ 0.01*rand(Point2f, 4))
xnew = copy(x)
δ = 0.001
xall = [copy(x)]
i = 1
# animation settings
n_frames = 100
framerate = 30
iter = LinRange(1, length(xall), n_frames)
points = Observable(x)
scene = scatter(points, markersize=15.0)
xlims!(scene.axis, (-5,5))
ylims!(scene.axis, (-5,5))
display(scene)
ProgressMeter.@showprogress for iter in 1:50000
global x, xnew, xall
kdtree = KDTree(x)
for i in eachindex(x)
n, a = nn(kdtree, x[i], x -> x == i)
#n = argmin(i==j ? Inf : norm(x[j] .- x[i]) for j in eachindex(x) )
# a = norm(Δ)
Δ = x[i] - x[n]
if a < 1e-7
xnew[i] = x[i] + δ*((Point2f(-Δ[2], Δ[1]))/a)
else
xnew[i] = x[n] + rot(δ/a)*Δ
end
end
xnew, x = x, xnew
iter % 100 == 0 && push!(xall, copy(x))
if iter % 1000 == 0
# points[] = x
end
end
fig = scatterlines(getindex.(xall, 1), markersize=1.5, linewidth=0.1)
for i in 2:3; scatterlines!(getindex.(xall, i), markersize=1.5, linewidth=0.1); end
fig
# animation settings
n_frames = 200
framerate = 30
iter = LinRange(1, length(xall), n_frames)
points = Observable(xall[1])
scene = scatter(points, markersize=15.0)
xlims!(scene.axis, (-10,10))
ylims!(scene.axis, (-10,10))
Makie.record(scene, "antisocial.mp4", iter; framerate = framerate) do i
points[] = xall[round(Int,i)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment