I have a dictionary that provides a mapping from real number tuples to an identifying integer. Given a list of tuples containing numbers that are within a tolerance of, but not exactly equal to those in the dictionary, I would like to produce a list of the corresponding integers.
Example:
tdict = {(0.334, 0.333, 0.333):1, (0.167, 0.666, 0.167):2, (0.5, 0.5, 0):3}
tlist = [(0.333, 0.333, 0.333), (0.16667, 0.6666667, 0.17), (0.34, 0.33, 0.33), (0.5001, 0.4999, 0.0)]
tol = 0.01
Running the code I want should produce the result
ilist = [1,2,1,3]
since all numbers in each of the tuples are within the given tolerance of those in the corresponding tuples in tdict. I could do this by iterating over tdict.keys() and comparing to each one individually, but I feel like there should be a better way. What is the most efficient way to get the corresponding integers to these tuples? It doesn’t have to involve a dictionary, that just seemed most natural to me. I’m using Python 3.
You obviously want to project points in 3D-space on a 3D grid with a certain grid spacing (which is directly related to your tolerance value) and create some kind of histogram. Write yourself a projection function: It takes an arbitrary 3-element list/tuple (a vector describing a point in space) as argument and projects it onto a certain grid point. You do this for filling up your dictionary as well as for reading it out. Furthermore, regarding the keys in your dictionary, I think you should go with tuples of integers instead of floats, because I am not sure if floats can ever be identical.
This is an implementation example:
What it does: it creates 20 random vectors in 3D space (all coordinates between 0 and 1). It populates a 3D grid using these points in space. The grid has a spacing of 0.3 in each dimension. Each of these 20 points in space is assigned to a certain voxel (just a word for a 3D pixel) in the grid. Each assignment increased the counter of the corresponding voxel by 1 (rendering the grid to be a histogram). Then, another random set of 20 vectors is used to read out the voxels. These points are again projected onto voxels, but this time the counter is just returned instead of increased. Execution test:
Execution with your data:
It prints
[1, 2, 1, 3]as desired. I haven’t thought deeply about the relationspacing=3*tolerance. It likely is wrong. I only know that there is a deterministic relation. Proving/finding this formula is left for you as an exercise 🙂