Cloud of Points Tree /Nearest Neighbor

Hi guys;
I'm using a binary tree to construct a tree of two dimensional points .here is how i construct the tree :
the tree is constructed by successive subdivision of the Plan by semi-Lines accross a given point.
the first subdivision is done by say a horizantal line across a given point.the plan is then split into two regions : the upper and lower half plans. the points in the upper plan will be in the right subtree and those in the lower plan will go into the left subtree.
in the next step the plan will be subdiveded by a VERTICAL semi-line at this time : the points at the left of this line will be placed in the left subtree and those on the right will be placed to right subtree.
Now i managed to write an insert() method for this :
static Tree insert(Point p, Tree a, boolean vertical)
     if (a == null)
     return new Tree(null, p, null);
     boolean estAGauche =
     (vertical) ? (p.x < a.p.x) : (p.y < a.p.y);
     if (estAGauche)
     Tree g = insert(p, a.filsG, !vertical);
     return new Tree(g, a.p, a.filsD);
     else
     Tree d = insert(p, a.filsD, !vertical);
     return new Tree(a.filsG, a.p, d);
     static Tree insert(Point p, Tree a)
     return insert(p, a, false);
     }Now i want to tackle another problem : given the tree is filled with a cloud of points.
if i pick a given point in the cloud ,i want to find the nearest neighbor of this point using the tree construct i described above.
is this possible ? How can I implement it ?
Many thanks for helping !

this is because i will be dealing with a verylarge
number of points so efficiency here is definitelya
crucial issue...what do you think josiah ?Well, I've used that little algorithm for a global
map with, say, 1e6 known points
and the response was always almost intantaneous. It
depends on the distribution
of your known points, i.e. you can easily draw
pathetic situations on a piece of
paper but on average the nearest point is found
withing a few searches (after
finding those two lines using an O(log(n)) binary
search ...
Two dimensional locality doesn't help you much when
you're using quad-trees;
as has been said before in this thread: two nearest
points may be miles apart
in the tree.
What does help (altough not much) is, after sorting
the points on increasing Y
values, do a minor sort using Gray-codes on the X
coordinate. But that's for a
later discussion ;-)
kind regards,
Jos
Well, I've used that little algorithm for a global
map with, say, 1e6 known points
and the response was always almost intantaneous. It
depends on the distribution
of your known points, i.e. you can easily draw
pathetic situations on a piece of
paper but on average the nearest point is found
withing a few searches (after
finding those two lines using an O(log(n)) binary
search ...
What you say is very encouraging so i will try your little algorithm for sure.
any way At this first stage of my application i'm not demanding some extra ordinary work to be acheived , and this one would be surely very sufficient..
Two dimensional locality doesn't help you much when
you're using quad-trees;
as has been said before in this thread: two nearest
points may be miles apart
in the tree.
you right !
What does help (altough not much) is, after sorting
the points on increasing Y
values, do a minor sort using Gray-codes on the X
coordinate. But that's for a
later discussion ;-)
something interesting i'll be patiently waiting for ;)
kind regards,
JosMany thanks ,

Similar Messages

  • Mountains and nearest neighbor do not mix

    Note - this is not an Oracle question - but something as food for thought. Appropriate I think as graph is now a big component of the product...
    While on vacation in Colorado last week, we decided to head up to Crested Butte to see a local play production. My wife, searching for a local motel on a site I will not name, found one with great ratings that was quite reasonable and about "30 miles" away. Not being from Colorado, she went ahead and booked it, and then told me where it was. I shook my head. That is no where near 30 miles away, at least by road - it is on the other side of the mountain!
    Obviously this company uses a point to point with nearest neighbor "as the crow flies" method. While simple points might work reasonably well for small areas, say in a city road grid, it is a horrible solution for larger areas and places like Colorado. With mountains that take hours to drive around, those 30 miles or so turn out to be 90 miles of road and take about 3 hours to drive based on posted speeds!
    Needless to say, I was upset. After spending almost an hour on the phone to get this all straightened out and the bill credited, I thought I'd point this out. Not only for "buyer beware" - but mainly as a good example of what not to do when designing map-based systems for consumers. KISS is usually a good approach, but in this case it is a horrible one when a road network with speeds AKA network data model graph solution is required.
    Bryan

    Good point.
    Thinking further, even in a city grid you have one-way streets, parks, longer blocks, etc., which can make the real distance (by road) much further than "as the crow flies". So I'm not sure nn is really good for any such "close to me" analysis tool.
    And yes thanks, had a great vacation. Miss the cool weather from my native state!
    Bryan

  • Nearest Neighbor Query takes 7 minutes

    Hello there, First time poster on the forums. 
    I've been looking into spatial comparison recently and have come across a few problems. The query I run takes 7 minutes to return the nearest neighbor. 
    My table that has the Geographical locations is of the following structure and has 1.7 million rows. 
    CREATE TABLE [dbo].[PostCodeData](
    [OutwardCode] [varchar](4) NOT NULL,
    [InwardCode] [varchar](3) NOT NULL,
    [Longitude] [float] NULL,
    [Latitude] [float] NULL,
    [GeoLocation] [geography] NULL,
    CONSTRAINT [PK_PostCodeData] PRIMARY KEY CLUSTERED
    [OutwardCode] ASC,
    [InwardCode] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    I have another table with many records on which I only have a Geography point (which I call Geolocation) and I'm trying to get the postcode from the PostCodeData table based on the nearest [GeoLocation] naturally.
    This is my query at the moment :
    SELECT top 2 [PostCode]
    ,[Geolocation]
    , (select top 1 pc.InwardCode from PostCodeData pc order by pc.GeoLocation.STDistance(bg.Geolocation)) found_post_code
    FROM [tbl_potatoes] bg
    where bg.Geolocation is not null
    This query is taking 7 minutes and as you can see I'm only doing this for 2 (top 2) records from the burning_glass table. What would happen if I wanted to process the whole table which has like 700k rows.
    What I've tried: 
    1. Created a spatial index.
    2. Followed a post somewhere on these forums about applying it as a hint (WITH: WITH (INDEX(ixs_postcode)))
    It didn't let me apply the hint and gave the following error : 
    Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query without specifying any hints and without using SET FORCEPLAN.
    Any help is appreciated. 

    Just before the end of the day yesterday, a colleague of mine spotted the missing 'Where' in the subquery and we added it in.
    The query now looks as such : 
    UPDATE top(200) tbl_potatoes
    SET PostCode =
    select top 1 pc.OutwardCode
    from PostCodeData pc
    where pc.GeoLocation.STDistance(Geolocation) < 1000
    order by pc.GeoLocation.STDistance(Geolocation)
    WHERE Geolocation is not null;
    The problem is, this query still takes a while. It now takes 3min27seconds for 200 rows. Not that this bit of math would be accurate in any way however if it takes 207seconds to do 200 rows, to do 300,00 it will most likely take somewhere between 80 to 90
    hours. 
    This is hardly going to be something that is going to work.
    That was the update - the SELECT statement :
    SELECT top 200 [PostCode]
    ,[Geolocation]
    , (select top 1 pc.OutwardCode
    from PostCodeData pc
    where pc.GeoLocation.STDistance(bg.Geolocation) < 1000
    order by pc.GeoLocation.STDistance(bg.Geolocation)) found_post_code
    FROM [tbl_potatoes] pot
    where Geolocation is not null
    Takes just 23seconds for 200 records. Meaning it would take around 10 hours for 300k.
    I tried Isaacs second example where he uses the STBuffer(10000) but it leads even more time in the select statement and quite frankly I don't get what is going on in his 3rd example where he talks about his declarative syntax.

  • K Nearest Neighbor Algorithm Code in Java

    I am looking for a code in Java for K nearest neighbor algorithm (considering clusters if possible which is able to detect outlier clusters).
    Thanks!
    Edited by: win13 on Oct 1, 2007 11:54 AM
    Edited by: win13 on Oct 1, 2007 12:00 PM

    interface MS{ // metric space
      double dist(MS p); // distance between this point and argument
    MS[] kNN(MS data, MS target, int k){
      MS[] res = new MS[k]; double[] d = new double[k];
      int n = 0; // number of element in the res
      // check inputs for validity
      if(data.length == 0 || k<=0) return res; // bail on bad input
      double dd = target.dist(data[0]); // load first one into list
      res[n] = data[0]; d[n++] = dd;
      // go through all other data points
      for(int i = 1; i<data.length; i++){
        if( n<k || d[k-1] > (dd = target.dist(data))){ //add one
    if(n<k){res[n] = data[i]; d[n++] = dd;}
    int j = n-1;
    while(j>0 && dd < data[j-1]){ // slide big data up
    res[j] = res[j-1]; d[j] = d[j-1]; j--;
    res[j] = data[i]; d[j] = dd;
    return res;
    As I said, I don't feel that this code is that difficult. I would be more concerned as to whether the data admits the particular definition of outlier that you have selected.
    It is a mistake to assume that one particular definition of a cluster or an outlier will work in all cases. For example using the definition you supply, if you have one single mega cluster of a thousand elements located within a foot of one another here on earth and you have about 10 other "clusters', each with but a single element, each a single light year apart but all somewhere out near the andromeda galaxy, you will conclude that cluster centers are on the average about one light year apart but that there is one bad outlier, that one way over there on earth.
    But, hey it's your data. Go nuts.
    Just for the record, I don't typically test code that I type into the forum so what I have supplied may not even compile and certainly should not be assumed to be correct. You will need to read it, and treat it as an outline for the code that you will need to write.
    Enjoy                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Exporting a movie with the settings "nearest neighbor"

    Hello everybody!
    I am trying to upscale a movie from an old video game. The resolution is 320x240 and should be upscaled to 1440x1080. The problem is that I don't want Adobe Premiere Pro 6 to upscale it using a chroma subsampling method (http://ingomar.wesp.name/2011/04/dosbox-gameplay-video-capture.html), instead I want to use something similar to the option "nearest neigbor" (the one you have in Adobe Photoshop when you resize images). Why I want this is because I want to keep the pixels from the video game sharp. Is this possible to do?

    And if you take a screen cap, import it into Photoshop and upscale by a factor 4 (with Nearest Neighbour) the result is amazing!
    Actually, I find that up-rezzing with the Nearest Neighbor algorithm to be about the lowest quality of any of the algorithms. It came first, and is basically a holdover from about PS version 2.5. Bicubic interpolation was added later, and then Bicubic Smoother and Bicubic Sharper.
    However, I am always working with continuous tone, high-rez digital photographs, and not screen-caps, so perhaps my material is not the ultimate to judge Nearest Neighbor?
    Still, for a 16x increase, about the only thing that I can suggest (and this is for Stills, and not Video) would be Genuine Fractals (once Human Softaware, but acquired by another company). Still, that is beyond the max limit that I would be comfortable with.
    Others have mentioned Red Giant's Magic Bullet Instant HD, and I would download the trial, then test. That might be "as good as it get."
    Good luck,
    Hunt

  • What's the arrow in the cloud that points upward or downward?

    What's the arrow in the cloud that points upward or downward?

    So if the down arrow means it's available to download, what do I do to actually download it?   I'm trying to download two apps and have same problem on both.

  • The nearest neighbor interpolation problem

    Hello,
    After my Photoshop CS6 update I have problem with the Nearest Neighbor interpolation. It was working correctly before. I was setting the General and Free Transform preferences first and rotating pictures by 45 degrees then. It was always giving me pixel-perfect results in PS CS6. Now that stopped working. Am I missing something? I have made video showing my results and all the steps I am making:
    How about you? What your results are after rotating any picture by 45 degrees in the Nearest Neighbor interpolation mode? I would be happy to know what is wrong now and how to achieve good results. I will appreciate any help.

    What your results are after rotating any picture by 45 degrees in the Nearest Neighbor interpolation mode?
    The same mess with Ps 13.0.1 on OS X 10.6.8.
    Very interesting that the Free Transform looks good until it is actually commited.
    I don't know whether it was different in 13.0

  • Nearest neighbor search with quadtrees

    hi guys;
    i'm interested in implementing an algorithm to watch for possible collisions between celestial planets...
    this algorihm consists of checking for a given planet with coordinates(x,y) if some other planet in the system came closer than a given distance...this algorithm should perform better than the naive one which consists of cheking the distance against every other planet and which is o(n) (n is the number of planets in the system)
    it would be preferable to use a quadtree for a nearest neighbor search algorithm to implement this collision watch algorithm...
    please help me ! some sample code would be very welcomed
    thanks

    [url http://forum.java.sun.com/thread.jsp?thread=571601&forum=31]Cross-post.

  • Convert a Cloud of points to surface in IGES format (Reverce engineering)

    Hi,
         I have aquired some 3 dimentional points into an excel spread sheet. I need to create a surface in IGES format using these points. Is there a ready made Vi that can do this?
    Thanks,
    Regards,
    Shapoor

    See this thread for a way to create the surface inside labview using mathscript.
    http://forums.ni.com/ni/board/message?board.id=170&thread.id=356342&view=by_date_ascending&page=5
    I have no idea how to group the surface output arrays (3 or 4 points per surface) or the IGES format.

  • Nearest Neighbor Interpolation

    I'm trying to enable this in After Effects, it seems silly that it's not included standard like it is in Photoshop.  I suppose I could get around it by exporting the image sequence with a restrictive palette, but it distorts the colors more than necessary, and it is an extra unnecssary step I'd like to avoid.
    So, if someone could give me a clue as to how to get this working in AE, either through a menu option I'm not seeing, an effect or a plug-in, that'd be great.
    If not, if someone could let me know if it were possible to make a plug in that does this, if someone would be willing to make said plug-in or direct me to a community that specializes in plug-ins, that'd be fantastic.
    And in terms of effects, using a simple choke is great, but it only effects the alpha layer of the animation, not the inside.  There was another effect I used, though I can't remember what it was (you set it to a certain amount of color levels, and that just picks random colors to fill in, so not cool).
    I'm working with pixel art, and everything works perfect except for the fact that it blurs pixels that it shouldn't be blurring.

    You have no reason to be rude. 
    I've been using Aftter Effects for several years, I know my way around it, however, this particular issue escapes me. There isn't a reliable answer anywhere, hense why I asked the series of questions.  I do realize that pixel art isn't After Effects intended usage, however, it contains many other features that makes animation quick and easy for multiple sprites that use similar animations.  Except I either have to accept the blurring pixels or take an unnecessary amount of time to correct them.  All which could be avoided if I could just find a way to remove the blurring.  Interpolation can be applied after pixels have already been rendered,  I know this, because there are many programs that can apply this to images that already exist (though they resize them, which is fine, because I end up doing that anyways).  So a plugin that handles this inside of after effects shouldn't be that far-fetched.  Perhaps you could learn a thing or two about interpolation, Here is a good place to start. http://en.wikipedia.org/wiki/Image_scaling
    And rather than assuming I have limited experience, you could've just been an adult and said "I don't know" or just not have said anything at all.  Your post was insulting, and not the least bit helpful.

  • K-nearest neighbors in MLT - any example?

    Hi, 
    There are currently no example on the LabVIEW MLT about the k-NN vi.
    We would like to use k-NN and would like to refer to some examples. 
    We couldn't get the distance control VI to work, and we are a bit puzzled by the fact that "examples" only accepts 1D arrays (our data is 2400 vectors, each of size 1x256).
    Our understanding of the VI is that "distance" specifies which type of norm, "examples" is the labeled data, "sample" is the new, unlabeled data. 
    When running with the current setup, there seems to be an error with the distance control.
    Thanks for your help in advance, 
    N&A
    Attachments:
    kNN pb.PNG ‏9 KB

    Hi Pallikaranai,
    I attempted several more times to work with the MLT but couldn't find any way, even getting onto NI themselves who tried to help but couldn't. But, I did get help from a LabVIEW user and a paper that was able to help me use a method which would be quite similar to KNN. Basically I had databases of 'knocking' or 'tapping' data and I wanted to compare my live signal to these databases to see if it was a 'tap' or a 'knock'.
    I put my live signal and database amplitudes thorugh this method:
    Wavelet transform
    Covariance
    SVD
    find log base 10 of Vector S of SVD
    find Mean, Max and  Min values of this and add togther to find Value X
    compare this value X to the same values of the databses after they were put through the same method and the smallest difference was the database
    that the event belonged in.
    I have also attached my code for my DB showing how I did it in LabVIEW. I hope its of help, it might not at all. NI had a look over this method themselves too
    and they said it should be ok. Are you applying to a signal yourself or anything similar?
    Attachments:
    SampleSignals.vi ‏223 KB

  • Nearest linear to a point?

    Hello,
    Is there a way to find the nearest linear to a point?
    I will be receiving data in various formats containing x,y locations and no relevant attribution to the LRS route network I have created (no route ids, etc.)
    I will need to eventually create LRS points from these features which will contain logmile info. If I can associate a linear to the point, I know how to do the rest. I have not been successful in figuring out how to do this without knowing which particular linear to work with.
    I need SQL that will just return the nearest linear to a point. Is it possible in 8.1.7?
    Thanks
    Dave

    Hi David,
    Did you index more than two dimensions of the geometry column in gps_lrs?
    If you did, then that could be the cause of this error. You can only use SDO_FILTER if geometries are indexed in more than 2D. The reason for this is that except for the R-tree indexing mechanism (which can only return approximate answers), all exact match answers only work in 2 dimensions (so sdo_nn would only return the nearest neighbor in two dimensions, which may not be the accurate answer you would expect from sdo_nn).
    If you've indexed the measure dimension, i.e. if your lrs geometry is a 2d geometry plus a measure and you've indexed all three dimensions (assuming you are using r-tree indexing) then this would be a bad thing.
    Hope this helps,
    dan

  • Nearest Point of Interest

    My Oracle Version: 8.1.6
    OS: Sun Solaris
    In spatial examples (http://otn.oracle.com/sample_code/products/spatial/sample_code_index.htm), we are dealing with only porsche dealer's spatial data and the query bellow will give us two lucky porsche dealers.
    select a.id, b.geo_address.firmname, b.geo_address.addrline, b.geo_address.lastline, a.phone, a.fax,
    b.location.sdo_point.x, b.location.sdo_point.y from
    porsche_dealer a, porsche_spatial b where
    a.id=b.id and
    mdsys.locator_within_distance(b.location, mdsys.sdo_geometry(2001, NULL,
    mdsys.sdo_point_type(x,y,NULL), NULL,
    NULL), 'sdo_num_res=2 LAYER_GTYPE=POINT') = 'TRUE';
    Unfortunately, I have Dealer Spatial information in a single table where all the dealers are differentiated by a column say dealer_make and it contains values like 'HONDA' , 'PORSCHE' etc.
    Now my question is how do I find nearest Honda dealer or nearest PORSCHE Dealer?
    Above query will not work if I am near the porsche dealership and ask for a nearest Honda dealership.
    Is there any other way to find a certain number of nearest Honda dealers? I can not use SDO_WITHIN_DISTANCE query because I have no idea where the dealership is so that I can give distance?
    Any Ideas
    I really appreciate your help!
    Arun.
    null

    Hi Arun,
    You have a caught on to a significant gotcha in 8.1.6 regarding nearest neighbor - enough people have had the same issue that in 9i you'll be able to do the query simply and elegantly. In 8.1.6 it is a little less elegant.
    Basically what you need to do is kick the sdo_num_res value up, and add a predicate as something like "where dealer_make='PORSCHE'" to the query.
    Also, why have a separate address table? You should have all of the data in the same table to get the maximum benefit from Oracle and Oracle spatial.
    select id, geo_address.firmname,
    geo_address.addrline, geo_address.lastline,
    phone, fax, a.location.sdo_point.x,
    a.location.sdo_point.y
    from all_dealers a
    where mdsys.locator_within_distance (a.location, mdsys.sdo_geometry(2001, NULL,
    mdsys.sdo_point_type(x,y,NULL),NULL,NULL),
    'sdo_num_res=X LAYER_GTYPE=POINT') =
    'TRUE'
    and dealer_make = 'PORSCHE';
    Note that I put sdo_num_res=X - the X is dependent on what you think the percentage of dealers is that deals in PORSCHE automobiles - if 2 % of dealers are PORSCHE dealers and you want to see 2 in the final answer, then sdo_num_res should probably be something over 100. Note this won't guarantee you will always see two porsche dealres, but it does make it likely.
    As I said earlier, in 9i this gets easier (and faster).
    hope this helps,
    dan

  • Access Points report half duplex in CDP Neighbors

    Hi
    We are currently converting our AP's to light AP's - using a 5508 controller. I just noticed that when I check an AP, under Access Point Details, CDP Neighbors, it correctly reports the switch it's connected to, with the right port. But under "Duplex" it says Half Duplex?
    It seems to do this for all AP's. I have checked both an 1121, 1131 and 1141. When I check the connected port on the switch it says Full Duplex.
    Is this a display issue or something I should examine further?
    Regards,
    Kaj

    Leo is correct. There is a bug that causes this. It will also eventually cause the controller to lock up. On a 2106 this happens much more often due to the lower amount of memory and processor power. TAC suggests that you hard code the switch to 100 meg full but I have seen that his has no real effect.

  • Converting multiple points to line

    Hi All
    I have table consist of point data.. how to convert multiple points to line data.. if anyknows pls tell me ..
    Thak you

    user13340372,
    . . . .Are you trying to draw a line between 2 points or draw a line connecting N points?
    How to Create a Line From 2 Points_
    . . . .You could use the SDO_Geometry constructor. For example, if you have a table POINTS defined as (ID NUMBER, FromPt SDO_GEOMETRY, ToPt SDO_GEOMETRY), then you could:
    SELECT 
        SDO_GEOMETRY(
        'LINESTRING ('||
        -- concatenate coordinates from FromPt
        REPLACE(REPLACE(p.FromPt.Get_WKT(), 'POINT (', NULL), ')', NULL)||','||
        -- concatenate coordinates from ToPt
        REPLACE(REPLACE(p.ToPt.Get_WKT(), 'POINT (', NULL), ')', NULL)||')'
        ---  SRID
        , 4326)
    FROM
        POINTS p;              
    How to Create a Line From N Points_
    . . . .In a "connect-the-dots" puzzle, you draw lines from one numbered point to the next numbered point. There, the numbers define how points are related. If you dont have that information, then you need to decide how you want your points connected. Here are a few options - your requirements should indicate which (if any) is suitable:
    . . . .(a) Draw Arbitrary Linestring Through Points: user10278189 already posted that PL/SQL solution (above).
    . . . .(b) Connect Nearest Neigbors: set CURRENT_POINT to a point (e.g., bottom-left). Then identify its nearest-neighbor (hereinafter, "NextPoint") using SDO_NN. Flag NextPoint as "visited" and set CURRENT_POINT to NextPoint. Repeat until all points in the point-set are flagged as "visited." The result ( which depends on the starting point ) is a linestring connecting all points (a "line" is only between 2 points; a linestring is between 2 or more points). This requires PL/SQL.
    . . . .(c) Draw Along Shortest Distances: Create a table containing: FromPt_ID, toPt_ID and distances between each pair of points. (If you do this via a cross product, remove rows where FromPt_ID = ToPt_ID.) Begin connecting the points with the minimum distance from the last "visited" point (as before, flag the points that have been used as "visited"). The result of this operation is the shortest linestring connecting your point-set. This requires PL/SQL.
    . . . .(d) Outline Set of Points: You could also use the SDO_GEOM.Sdo_ConvexHull function to create polygon that encloses your point set, and then use SDO_UTIL.PolygonToLine to turn that area-geometry into a line-geometry. This can probably be done in a single statement.
    . . . .(e) Others (TSP, spanning tree, etc).
    Regards,
    Noel

Maybe you are looking for