openrndr / orx

A growing library of assorted data structures, algorithms and utilities for OPENRNDR
https://openrndr.org
BSD 2-Clause "Simplified" License
119 stars 35 forks source link

Feature request: allow the KDTree to return the KNN points indices instead of coordinates. #288

Open Brainkite opened 1 year ago

Brainkite commented 1 year ago

Motivation

The KDtree queries should allow to return the indices of the points instead of the coords. Do you think this implementation could be easily updated for this feature or the structure is incompatible with idices tracking?

Help make it happen!

I am not willing to submit a PR to implement this change.

AlexandreBrown commented 1 year ago

Hello @edwinRNDR ,
We would also be interested in this kind of feature since for us finding which index corresponds to the outputed nearest neighbors x,y,z is not stable and a pain at the moment. It would be much more efficient and stable if the lib could return the indexes.
Any chance this could be added to the lib?
Cheers

edwinRNDR commented 1 year ago

Hey. I will have a look at getting that functionality in but I have limited capacity to get this done.

In case you need a quick solution that's relatively inexpensive you can use a hash map.

import org.openrndr.application
import org.openrndr.extra.kdtree.kdTree
import org.openrndr.extra.noise.scatter

fun main() {
    application {
        program {
            val p = drawer.bounds.scatter(100.0)
            val kd = p.kdTree()
            val indices = p.withIndex().associate { it.value to it.index }

            extend {
                val nearestIndices = kd.findKNearest(mouse.position, 3).map { indices[it] ?: error("mystery point") }
            }
        }
    }
}
AlexandreBrown commented 1 year ago

Thank you @edwinRNDR , we were getting unstable hashmap due to the key we were using (we tried using maps of maps with double as key and we also tried to have a list of double as key) but we didn't try a data class with the x,y,z.
We tested your map approach and it is super stable thanks to the data class hashcode stability.
Thank you for your quick response this was very helpful.
Cheers!
PS: I can help contribute to this repo to add the indices, won't have time now but in a few months I will be more free to contribute.