private static KdTree<object> BuildKdTree(IGeometry geom, double tolerance) { var index = new KdTree<object>(tolerance); var pt = geom.Coordinates; for (int i = 0; i < pt.Length; i++) { index.Insert(pt[i]); } return index; }
public static int GetNumberPictInRangeFixTrajectory(Satellite satellite, KdTree<float, PicCollection> tree, int maxIter) { if (maxIter < 0) { return 0; } var copySatellite = satellite.Clone(); copySatellite.NextTurn(); return tree.RadialSearch(new float[] { copySatellite.Pos.Lat, copySatellite.Pos.Lon }, copySatellite.MaxRot, 150) .Where(no => no.Value.PictureCanBeTaken(copySatellite.CurrentTurn)) .Where(k => copySatellite.CanTakePicture((int)k.Point[0], (int)k.Point[1])).Count() + GetNumberPictInRangeFixTrajectory(copySatellite, tree, --maxIter); }
public static int GetNumberPictInRangeInNextTurns(Satellite satellite, KdTreeNode<float, PicCollection> n, KdTree<float, PicCollection> tree) { var possiblePict = new Coords((int)n.Point[0], (int)n.Point[1]); var copySatellite = satellite.Clone(); copySatellite.TakePicture(possiblePict); copySatellite.NextTurn(); var inRange = tree.RadialSearch(new float[] { copySatellite.Pos.Lat, copySatellite.Pos.Lon }, copySatellite.MaxRot, 150) .Where(no => no.Value.PictureCanBeTaken(copySatellite.CurrentTurn)) .Where(k => copySatellite.CanTakePicture((int)k.Point[0], (int)k.Point[1])).Count() + GetNumberPictInRangeFixTrajectory(copySatellite, tree, 500); //Console.WriteLine("Number in range for {0} {1}: {2}", possiblePict.Lat, possiblePict.Lon, inRange); return inRange; }
/// <summary> /// find all objects that matches the given predicate /// </summary> /// <param name="match">lamda expression</param> public KdTree <T> FindAll(Predicate <T> match) { var list = new KdTree <T>(_just2D); foreach (var node in this) { if (match(node)) { list.Add(node); } } return(list); }
public void ClasNearestNeighbourTest() { var points2D = new List <IPointIdFloat>() { new PointIdFloat(0, 1f, 2f), new PointIdFloat(1, 0f, 1f), new PointIdFloat(2, 3f, 3f), new PointIdFloat(3, 1.5f, 2f), new PointIdFloat(4, 5f, -1f) }; var points3D = new List <IPointIdFloat>() { new PointIdFloat(5, 1f, 2, 55f), new PointIdFloat(6, 0f, 1, 0.1f), new PointIdFloat(7, 3f, 3, 0.01f), new PointIdFloat(8, 1.5f, 2, -0.03f), new PointIdFloat(9, 5f, -1, 44f), new PointIdFloat(10, 15f, -51f, 73f), new PointIdFloat(11, 0.5f, -21f, 144f) }; //should return the only point for a singleton tree KdTree kdt = new KdTree(new List <IPointIdFloat>() { point2D }); Assert.AreEqual(point2D, kdt.NearestNeighbour(point2D)); Assert.AreEqual(point2D, kdt.NearestNeighbour(new PointIdFloat(156, 1f, 2f))); //should return the closest point (2D) kdt = new KdTree(points2D); Assert.IsTrue(points2D.All(p => kdt.NearestNeighbour(p) == p)); Assert.AreEqual(points2D[0], kdt.NearestNeighbour(new PointIdFloat(12, 1.1f, 1.9f))); Assert.AreEqual(points2D[1], kdt.NearestNeighbour(new PointIdFloat(13, -5f, -5f))); Assert.AreEqual(points2D[2], kdt.NearestNeighbour(new PointIdFloat(14, 3.01f, 2.9999f))); Assert.AreEqual(points2D[3], kdt.NearestNeighbour(new PointIdFloat(15, 1.6f, 2f))); Assert.AreEqual(points2D[4], kdt.NearestNeighbour(new PointIdFloat(16, 160f, 2f))); //should return the closest point (3D) kdt = new KdTree(points3D); Assert.IsTrue(points3D.All(p => kdt.NearestNeighbour(p) == p)); Assert.AreEqual(points3D[0], kdt.NearestNeighbour(new PointIdFloat(17, 1.1f, 1.9f, 49f))); Assert.AreEqual(points3D[1], kdt.NearestNeighbour(new PointIdFloat(18, -5f, -5f, 1f))); Assert.AreEqual(points3D[2], kdt.NearestNeighbour(new PointIdFloat(19, 3.01f, 2.9999f, -1f))); Assert.AreEqual(points3D[2], kdt.NearestNeighbour(new PointIdFloat(20, 160f, 2f, 0.1f))); Assert.AreEqual(points3D[3], kdt.NearestNeighbour(new PointIdFloat(21, 1.6f, 2f, 0f))); Assert.AreEqual(points3D[4], kdt.NearestNeighbour(new PointIdFloat(22, 160f, 2f, 40f))); }
public void TestAddDuplicateInUpdateMode() { tree = new KdTree <float, string>(2, new FloatMath(), AddDuplicateBehavior.Update); AddTestNodes(); var newValue = "I love chicken, I love liver, Meow Mix Meow Mix please deliver"; tree.Add(testNodes[0].Point, newValue); var actualValue = tree.FindValueAt(testNodes[0].Point); Assert.AreEqual(newValue, actualValue); }
public static void Main(string[] args) { OptProperties props = new OptProperties(); Parser parser = ParserFactory.BuildParser(props); parser.Parse(args); if (props.Help || props.CSVFile == null || props.OutFile == null || !(new FileInfo(props.CSVFile).Exists)) { PrintUsageAndExit(parser); } Progress.Immediate(string.Format("Setting projection dimensions to {0}", props.ProjectionDimensions)); Progress.Immediate(string.Format("Setting drawing width to {0}", props.Width)); Progress.Immediate(string.Format("Setting drawing height to {0}", props.Width)); Progress.Immediate(string.Format("Setting drawing line width to {0}", props.LineWidth)); Progress.Immediate(string.Format("Setting drawing point size to {0}", props.PointSize)); Progress.Immediate(string.Format("Setting bucket size to {0}", props.BucketSize)); Progress.Immediate(string.Format("Setting ISplitDimensionSelector to '{0}'", props.ISplitDimensionSelector)); Progress.Immediate(string.Format("Setting ISplitLocationSelector to '{0}'", props.ISplitLocationSelector)); Progress.Immediate(string.Format("Setting ITrivialSplitResolver to '{0}'", props.ITrivialSplitResolver)); IList <IVector> vecs = null; using (Progress p = new Progress(string.Format("Reading data from '{0}'", props.CSVFile))) { CSVReader r = new CSVReader(' '); vecs = r.Parse(props.CSVFile); } ISubdivisionPolicy policy = new SubdivisionPolicyConnector(props.BucketSize, props.ISplitDimensionSelectorInstance, props.ISplitLocationSelectorInstance, props.ITrivialSplitResolverInstance); KdTree <IVector> tree = null; using (Progress p = new Progress("Constructing kd-tree")) { tree = new KdTree <IVector>(vecs, policy); } using (Progress p = new Progress(string.Format("Rendering kd-tree to '{0}'", props.OutFile))) { Rendering.RenderTreeCairo render = new Rendering.RenderTreeCairo(); render.Render(tree.Root, props.ProjectionDimensions, props.OutFile, props.Width, props.Height, props.LineWidth, props.PointSize); } }
public GPSForm() { InitializeComponent(); Parser parser = new Parser(); minX = parser.XMin; minY = parser.YMin; maxX = parser.XMax; maxY = parser.YMax; mapC = Image.FromFile(Parser.IMG_MAP); mapX = mapC.Width; mapY = mapC.Height; ciudad = new Dictionary <string, City>(); kd = new KdTree(); ciudades = parser.Cities; graph = parser.Graph; nodeById = parser.NodeById; carreteras = parser.Ways; waysByNode = parser.WaysByNode; foreach (City item in parser.Cities) { string name = item.Name; int i = 2; while (ciudad.ContainsKey(name)) { name = item.Name + " (" + i++ + ")"; } ciudad.Add(name, item); comboBox1.Items.Add(name); comboBox2.Items.Add(name); } foreach (Node item in graph.Vertices()) { kd.insert(new Point2D(item)); } comboBox1.Sorted = true; comboBox2.Sorted = true; cbOpcionesBusuqueda.Items.Add(SearchTypes.Dijkstra); cbOpcionesBusuqueda.Items.Add(SearchTypes.BFS); cbOpcionesBusuqueda.Items.Add(SearchTypes.DFS); cbOpcionesBusuqueda.Items.Add(SearchTypes.AStar); cbOpcionesBusuqueda.SelectedIndex = 0; prev = DateTime.Now; }
public void KdtreeReSet() { BlenderKdtree = new KdTree <Transform>(); List <Transform> RegisterList = new List <Transform>(); for (int i = 0; i < GameObject.Find("KDTree").transform.childCount - 1; i++) { for (int j = 0; j < GameObject.Find("KDtree" + i).transform.childCount; j++) { RegisterList.Add(GameObject.Find("KDtree" + i).transform.GetChild(j)); } } BlenderKdtree.AddAll(RegisterList); }
private bool HaveNpcInRange(EntityInfo entity, CharacterRelation relation, float radius) { bool find = false; KdTree.QueryWithFunc(entity, radius, (float sqrDist, KdTreeObject obj) => { if (EntityInfo.GetRelation(entity, obj.Object) == relation) { find = true; return(false); } return(true); }); return(find); }
public void _01TestOneNode() { var triangles = new List <Triangle>() { new Triangle(new Vector3(-3, 0, 0), new Vector3(-2, 2, 0), new Vector3(-1, 0, 0)), new Triangle(new Vector3(-1, 0, 0), new Vector3(0, 2, 0), new Vector3(1, 0, 0)), new Triangle(new Vector3(1, 0, 0), new Vector3(2, 2, 0), new Vector3(3, 0, 0)), }; var tree = new KdTree(triangles); Assert.AreEqual(new Vector3(-3, 0, 0), tree.root.mesh.BoundingBox.min); Assert.AreEqual(new Vector3(3, 2, 0), tree.root.mesh.BoundingBox.max); Assert.AreEqual(tree.root.children.Count, 0); }
private static double PositionalBalance(IList <Player> players) { var tree = new KdTree <double, Player>(2, new DoubleMath(), AddDuplicateBehavior.Error); players.Execute(p => tree.Add(new double[] { p.Location.X, p.Location.Y }, p)); var orderedDistances = players. Select(p => tree.GetNearestNeighbours(new double[] { p.Location.X, p.Location.Y }, 2)). Select(ps => ps.First().Value.Location.Distance(ps.Last().Value.Location)). OrderBy(d => d). ToList(); return(Math.Exp(-Math.Sqrt(orderedDistances.Last() - orderedDistances.First()))); }
public PositionHandler(float maxSearchLength = 99) { if (Instance != null) { Instance.objectsToUpdateNearestNeighbours = null; } objectsToUpdateNearestNeighbours = new List <FindNearestNeighbour>(); kdTree = new KdTree <FindNearestNeighbour>(); kdTree.SearchLength = maxSearchLength; Instance = this; }
void Start() { generationManager = GameObject.Find("GenerationManager"); GM = generationManager.GetComponent <GenerationManager>(); pixelPopualtion = GameObject.Find("PixelPopulation"); pixelPop = pixelPopualtion.GetComponent <PixelPopulation>(); cancelledAgentList = new KdTree <Agent>(); startTime = Time.time; if (SimulationManager.Get().is2D) { InitializeAgents2DArray(populationCount); IntiPopulation = true; } if (SimulationManager.Get().is3D) { InitializeAgents3DArray(populationCount); range = SharpMatter.SharpMath.SharpMath.Range(populationList.Count); IntiPopulation = true; } Parent(); AgentName(); InitializeState(); string filePath = SimulationManager.Get().ClusterOrganizationFilePath; string fileName = "OrganizationInitialState" + ".txt"; StreamWriter writer = new StreamWriter(filePath + fileName); // StreamWriter writer = new StreamWriter(@"C:\Users\nicol\Documents\Architecture\1.AADRL\Term 4\Data\SimulationData\3D\Cluster\Init state\OrganizationInitialState.txt"); for (int i = 0; i < populationList.Count; i++) { string outPut = populationList[i].gameObject.transform.position.x.ToString() + "," + populationList[i].gameObject.transform.position.z.ToString() + "," + populationList[i].gameObject.transform.position.y.ToString(); writer.WriteLine(outPut); } writer.Close(); } // END START
public void TestContains() { KdTree <IVector> tree = new KdTree <IVector>(2, new Accelerators.Subdivision.SubdivisionPolicyConnector(1)); Assert.IsFalse(tree.Contains(Vector.Create(2.0, 1.0))); tree.Add(Vector.Create(3.0, 2.0)); Assert.IsTrue(tree.Contains(Vector.Create(3.0, 2.0))); tree.Add(Vector.Create(3.0, 2.0)); // duplicate elements Assert.IsTrue(tree.Contains(Vector.Create(3.0, 2.0))); tree.Add(Vector.Create(2.0, 1.0)); Assert.IsTrue(tree.Contains(Vector.Create(2.0, 1.0))); Assert.IsTrue(tree.Remove(Vector.Create(2.0, 1.0))); Assert.IsFalse(tree.Contains(Vector.Create(2.0, 1.0))); }
public void ClasPointsWithinDistanceWrongDimensionPointTest() { IList <IPointIdFloat> points = new List <IPointIdFloat>() { new PointIdFloat(0, 1f, 2f), new PointIdFloat(1, 0f, 1f), new PointIdFloat(2, 3f, 3f), new PointIdFloat(3, 1.5f, 2f), new PointIdFloat(4, 5f, -1f) }; KdTree kdt = new KdTree(new List <IPointIdFloat>() { new PointIdFloat(6, 1f, 2f) }); kdt.PointsWithinDistance(new PointIdFloat(7, 1f, 2f, 3f), 1); }
public void TestAdd() { KdTree <Vector> tree = new KdTree <Vector>(2, CompareFunction); tree.Add(new Vector(1.0, 1.0)); Assert.AreEqual(1, tree.Count); tree.Add(new Vector(2.0, 2.0)); Assert.AreEqual(2, tree.Count); tree.Add(new Vector(0.0, 0.0)); Assert.AreEqual(3, tree.Count); tree.Add(new Vector(2.0, 0.0)); Assert.AreEqual(4, tree.Count); tree.Add(new Vector(2.0, 4.0)); Assert.AreEqual(5, tree.Count); }
public void ClasAddWrongDimensionPointTest() { IList <IPointIdFloat> points = new List <IPointIdFloat>() { new PointIdFloat(0, 1f, 2f), new PointIdFloat(1, 0f, 1f), new PointIdFloat(2, 3f, 3f), new PointIdFloat(4, 1.5f, 2f), new PointIdFloat(3, 5f, -1f) }; KdTree kdt = new KdTree(new List <IPointIdFloat>() { new PointIdFloat(0, 1f, 2f) }); kdt.Add(new PointIdFloat(1, 1f, 2f, 3f)); }
public void ClasAddNullPointTest() { IList <IPointIdFloat> points = new List <IPointIdFloat>() { new PointIdFloat(0, 1f, 2f), new PointIdFloat(1, 0f, 1f), new PointIdFloat(2, 3f, 3f), new PointIdFloat(3, 1.5f, 2f), new PointIdFloat(4, 5f, -1f) }; KdTree kdt = new KdTree(new List <IPointIdFloat>() { new PointIdFloat(5, 1f, 2f) }); kdt.Add(null); }
// Use this for initialization void Start() { var mesh = model.sharedMesh; positions = mesh.vertices; normals = mesh.normals; var mat = model.renderer.sharedMaterial; var tex = (Texture2D)mat.mainTexture; colors = System.Array.ConvertAll(mesh.uv, (uv) => tex.GetPixelBilinear(uv.x, uv.y)); _tree = new KdTree(); _tree.build(positions, Enumerable.Range(0, mesh.vertexCount).ToArray()); _bounds = model.renderer.bounds; _bounds.Expand(2f * coloringDist); }
public ViaDfDataProvider() { using (var context = new DataContext()) { var options = new DataLoadOptions(); options.LoadWith <RoutePiece>(x => x.Route); context.LoadOptions = options; var routePieces = context.RoutePieces.ToList(); routePieceCache = routePieces.ToDictionary(x => x.ID, x => x); connectionCache = context.SearchIndexes.ToList().GroupBy(x => x.RoutePieceID).ToDictionary(x => x.Key, x => x.ToList()); routePieceKdTree = new KdTree <RoutePiece>(routePieces, x => x.Lat, x => x.Lng); } }
public void _03TestModel() { var watch = new Stopwatch(); var mesh = objWorker.Parse("C:\\Projects\\cow-engine\\assets\\cow.obj"); var triangles = (mesh as TriangleMesh).triangles; watch.Start(); var tree = new KdTree(triangles); watch.Stop(); var time = watch.Elapsed; Console.WriteLine($"{time.Milliseconds}"); Assert.Less(time.Milliseconds, 200); }
public void TestAddDuplicateInSkipMode() { tree = new KdTree <float, string>(2, new FloatMath()); Assert.AreEqual(AddDuplicateBehavior.Skip, tree.AddDuplicateBehavior); AddTestNodes(); var count = tree.Count; var added = tree.Add(testNodes[0].Point, "Some other value"); Assert.AreEqual(false, added); Assert.AreEqual(count, tree.Count); }
private void Execute(string pointCoordinates, string rectangleCoordinates, int expectedNumber) { var points = pointCoordinates .ToPoints() .ToArray(); var tree = KdTree.Construct(points); var corners = rectangleCoordinates.ToPoints().ToArray(); var visitor = new NumberOfPointsVisitor(corners[0], corners[1]); tree.Accept(visitor); Console.WriteLine(visitor.Result); Assert.AreEqual(expectedNumber, visitor.Result); }
void Start() { navMeshBuilder.SetActive(false); numberOfAgents = 100; simulationActive = false; waterTable = GameObject.Find("WaterTable").transform; trailsGO = transform.Find("Trails"); targetsGO = transform.Find("Targets"); targets = new KdTree <Transform>(); BuildTerrain(); ApplySoil(); ApplyVegetation(); }
// 用不了,不会写 C# 的泛型 public static bool RemoveFromKdTree(MonoBehaviour instance, KdTree <MonoBehaviour> trees) { bool ret = true; for (int idx = 0; idx != trees.Count; idx++) { if (trees[idx] == instance) { trees.RemoveAt(idx); ret = false; break; } } return(ret); }
public static void Main() { KdTree tree = new KdTree(); tree.Insert(new Point2D(5, 5)); tree.Insert(new Point2D(3, 2)); tree.Insert(new Point2D(2, 6)); tree.Insert(new Point2D(8, 8)); tree.Insert(new Point2D(8, 9)); tree.Insert(new Point2D(8, 9)); // no duplicates PrintContains(tree, new Point2D(5, 5)); PrintContains(tree, new Point2D(8, 9)); PrintContains(tree, new Point2D(0, 0)); }
public static void Main(string[] args) { int systemsCont = int.Parse(Console.ReadLine()); int reportsCount = int.Parse(Console.ReadLine()); int side = int.Parse(Console.ReadLine()); Rectangle space = new Rectangle(0, side, 0, side); List <Point2D> systems = new List <Point2D>(); for (int i = 0; i < systemsCont; i++) { // get solar systems string line = Console.ReadLine(); string[] tokens = line.Split(); double x = double.Parse(tokens[1]); double y = double.Parse(tokens[2]); Point2D newPoint = new Point2D(x, y); if (newPoint.IsInRectangle(space)) { systems.Add(newPoint); } } KdTree tree = new KdTree(); //tree.BuildFromList(systems); systems.ForEach(tree.Insert); systems.Clear(); for (int i = 0; i < reportsCount; i++) { // get reports string line = Console.ReadLine(); string[] tokens = line.Split(); double x = double.Parse(tokens[1]); double y = double.Parse(tokens[2]); double width = double.Parse(tokens[3]); double height = double.Parse(tokens[4]); Rectangle searchedRectangle = new Rectangle(x, x + width, y, y + height); tree.GetPoints(systems.Add, searchedRectangle, space); Console.WriteLine(systems.Count); systems.Clear(); } }
public void ClasAddTest() { IPointIdFloat p1 = new PointIdFloat(0, 1f, 2f); IPointIdFloat p2 = new PointIdFloat(1, -1f, 2f); IPointIdFloat p3 = new PointIdFloat(2, 1f, -2f); IPointIdFloat p1B = new PointIdFloat(3, 1f, 2f); IPointIdFloat p2B = new PointIdFloat(4, -1f, 2f); IPointIdFloat p2C = new PointIdFloat(5, -1f, 2f); IPointIdFloat p3B = new PointIdFloat(6, 1f, -2f); IPointIdFloat p4 = new PointIdFloat(7, 0f, 0f); KdTree kdt = new KdTree(new List <IPointIdFloat>() { p1 }); Assert.AreEqual(1, kdt.Count()); kdt.Add(p2); Assert.AreEqual(2, kdt.Count()); Assert.IsTrue(kdt.Contains(p1)); Assert.IsTrue(kdt.Contains(p2)); kdt.Add(p3); Assert.AreEqual(3, kdt.Count()); Assert.IsTrue(kdt.Contains(p1)); Assert.IsTrue(kdt.Contains(p2)); Assert.IsTrue(kdt.Contains(p3)); kdt.Add(p1B); Assert.AreEqual(4, kdt.Count()); Assert.IsTrue(kdt.Contains(p1)); Assert.IsTrue(kdt.Contains(p1B)); Assert.IsTrue(kdt.Contains(p2)); Assert.IsTrue(kdt.Contains(p3)); kdt.Add(p2B); kdt.Add(p3B); kdt.Add(p2C); Assert.AreEqual(7, kdt.Count()); Assert.IsTrue(kdt.Contains(p1)); Assert.IsTrue(kdt.Contains(p1B)); Assert.IsTrue(kdt.Contains(p2)); Assert.IsTrue(kdt.Contains(p2B)); Assert.IsTrue(kdt.Contains(p2C)); Assert.IsTrue(kdt.Contains(p3)); Assert.IsTrue(kdt.Contains(p3B)); }
public async Task NearestNeighbor_Accuracy() { List <Location> listLocations = Utils.ReadCSVFile(); KdTree <double, Location> kdTree = FillKdTree(listLocations); int orderDifferent = 0; int resultsDifferent = 0; ConcurrentDictionary <Location, List <Location> > dictNearestNeighbors = await FillOriginalApproach(listLocations, 10); foreach (Location loc in listLocations) { var v = kdTree.GetNearestNeighbours(new double[3] { loc.X, loc.Y, loc.Z }, 11); List <Location> kdResult = kdTree.GetNearestNeighbours(new double[3] { loc.X, loc.Y, loc.Z }, 11) .Where(x => x.Value != loc) .Select(x => x.Value) .ToList(); List <Location> originalResult = dictNearestNeighbors[loc]; if (kdResult.Count != 10 || originalResult.Count != 10) { Assert.Fail("Incorrect number of nearest neighbors"); } bool diffOrder = false; bool diffResults = false; for (int i = 0; i < kdResult.Count; i++) { if (kdResult[i].Id != originalResult[i].Id) { diffOrder = true; } if (!originalResult.Contains(kdResult[i])) { diffResults = true; } } if (diffResults) { resultsDifferent++; } else if (diffOrder) { orderDifferent++; } } Console.WriteLine($"Number of Locations: {listLocations.Count}\nDifferent Order: {orderDifferent}\nDifferent Results: {resultsDifferent}"); }
private void TestQuery(KdTree <object> index, Envelope queryEnv, bool includeRepeated, Coordinate[] expectedCoord) { var result = KdTree <object> .ToCoordinates(index.Query(queryEnv), includeRepeated); Array.Sort(result); Array.Sort(expectedCoord); Assert.IsTrue(result.Length == expectedCoord.Length, "Result count = {0}, expected count = {1}", result.Length, expectedCoord.Length); bool isMatch = CoordinateArrays.Equals(result, expectedCoord); Assert.IsTrue(isMatch, "Expected result coordinates not found"); }
public void TestEnumeration() { Vector[] vecs = new Vector[] { Vector.Create(-1.0, -1.0), Vector.Create(0.0, 0.0), Vector.Create(1.0, 1.0), Vector.Create(2.0, 2.0) }; KdTree <Vector> tree = new KdTree <Vector>(vecs, new Accelerators.Subdivision.SubdivisionPolicyConnector(1)); int index = 0; using (IEnumerator <Vector> e = tree.GetEnumerator()) { while (e.MoveNext()) { // iterator traverses nodes from left to right Assert.IsTrue(vecs[index].Equals(e.Current)); index += 1; } Assert.AreEqual(4, index); } }
public void Insert_MultiplePoints_TestContains() { KdTree tree = new KdTree(); tree.Insert(new Point2D(5, 5)); tree.Insert(new Point2D(3, 2)); tree.Insert(new Point2D(2, 6)); tree.Insert(new Point2D(8, 8)); tree.Insert(new Point2D(8, 9)); Assert.IsTrue(tree.Contains(new Point2D(5, 5))); Assert.IsTrue(tree.Contains(new Point2D(3, 2))); Assert.IsTrue(tree.Contains(new Point2D(2, 6))); Assert.IsTrue(tree.Contains(new Point2D(8, 8))); Assert.IsTrue(tree.Contains(new Point2D(8, 9))); }
private static void CheckIfAllStarsAreInRange(int reportsNumber, KdTree stars) { for (int m = 0; m < reportsNumber; m++) { var report = Console.ReadLine().Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); var x = int.Parse(report[1]); var y = int.Parse(report[2]); var width = int.Parse(report[3]); var height = int.Parse(report[4]); var range = new Rectangle(x, y, width, height); var starsInRange = stars.EachInOrder(s => range.IsInside(s) ? 1 : 0); Console.WriteLine(starsInRange); } }
public void Setup() { tree = new KdTree<float, string>(2, new FloatMath()); testNodes = new List<KdTreeNode<float, string>>(); testNodes.AddRange(new KdTreeNode<float, string>[] { new KdTreeNode<float, string>(new float[] { 5, 5 }, "Root"), new KdTreeNode<float, string>(new float[] { 2.5f, 2.5f }, "Root-Left"), new KdTreeNode<float, string>(new float[] { 7.5f, 7.5f }, "Root-Right"), new KdTreeNode<float, string>(new float[] { 1, 10 }, "Root-Left-Left"), new KdTreeNode<float, string>(new float[] { 10, 10 }, "Root-Right-Right") }); }
public static void Main(String[] args) { KDTree = new KdTree<float,int> (2, new FloatMath ()); idMap = new Dictionary<int, AskObject> (); maxObjectId = 0; Socket listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind (new IPEndPoint (IPAddress.Any, 1234)); listener.Listen (100); while (true) { Socket handler = listener.Accept (); ASKServer askServer = new ASKServer (handler); Thread mythread = new Thread (askServer.run); mythread.Start (); } }
public void TestSinglePoint() { var index = new KdTree<object>(.001); var node1 = index.Insert(new Coordinate(1, 1)); var node2 = index.Insert(new Coordinate(1, 1)); Assert.IsTrue(node1 == node2, "Inserting 2 identical points should create one node"); var queryEnv = new Envelope(0, 10, 0, 10); var result = index.Query(queryEnv); Assert.IsTrue(result.Count == 1); var node = Enumerable.First(result); Assert.IsTrue(node.Count == 2); Assert.IsTrue(node.IsRepeated); }
public void TestEndlessLoop() { var kd = new KdTree<string>(); kd.Insert(new Coordinate(383, 381), "A"); kd.Insert(new Coordinate(349, 168), "B"); kd.Insert(new Coordinate(473, 223), "C"); kd.Insert(new Coordinate(227, 44), "D"); kd.Insert(new Coordinate(273, 214), "E"); kd.Insert(new Coordinate(493, 87), "F"); kd.Insert(new Coordinate(502, 290), "G"); var res = kd.NearestNeighbor(new Coordinate(297, 133)); //Should be B Assert.AreEqual("B", res.Data); res = kd.NearestNeighbor(new Coordinate(272, 216)); //Should be E } Assert.AreEqual("E", res.Data); res = kd.NearestNeighbor(new Coordinate(635, 377)); //Should be G Assert.AreEqual("G", res.Data); }
/// <summary> /// Creates a Conforming Delaunay Triangulation based on the given /// unconstrained initial vertices. The initial vertex set should not contain /// any vertices which appear in the constraint set. /// </summary> /// <param name="initialVertices">a collection of <see cref="ConstraintVertex"/></param> /// <param name="tolerance">the distance tolerance below which points are considered identical</param> public ConformingDelaunayTriangulator(IEnumerable<Vertex> initialVertices, double tolerance) { _initialVertices = new List<Vertex>(initialVertices); _tolerance = tolerance; _kdt = new KdTree<Vertex>(tolerance); }
public void TearDown() { tree = null; }
private static KdTree<float, Tuple<int, PicCollection>> BuildTree(Input input) { var tree = new KdTree<float, Tuple<int, PicCollection>>(2, new FloatMath()); foreach (var picCollection in input.Collections) { for (int p = 0; p < picCollection.Locations.Count; p++) { var pict = picCollection.Locations[p]; tree.Add(new float[] {pict.Lat, pict.Lon}, Tuple.Create(p, picCollection)); } } tree.Balance(); return tree; }
public static Solution Solve(Input input) { var takenPictures = new List<Snapshot>(); var tree = new KdTree<float, PicCollection>(2, new FloatMath()); foreach (var picCollection in input.Collections) { foreach (var pict in picCollection.Locations) { tree.Add(new float[] { pict.Lat, pict.Lon }, picCollection); } } tree.Balance(); var orderedSatellelites = input.Satellites.OrderByDescending(sat => sat.MaxRot).ToList(); for (int s = 0; s < orderedSatellelites.Count; ++s) { var satellite = orderedSatellelites[s]; for (int turn = 0; turn < input.NbTurns; ++turn) { var node = tree.RadialSearch(new float[] { satellite.Pos.Lat, satellite.Pos.Lon }, satellite.MaxRot*SQRT2, 150).ToArray(); if (node.Length > 0) { var valids = node.Where(n => n.Value.PictureCanBeTaken(turn)) .Where(k => satellite.CanTakePicture((int)k.Point[0], (int)k.Point[1])) .OrderByDescending(k => Math.Pow(k.Point[0] - satellite.Pos.Lat, 2) + Math.Pow(k.Point[1] - satellite.Pos.Lon, 2)) //.OrderByDescending(k => k.Value.TakenPictures.Count) .ToList(); if (valids.Count > 0) { Console.WriteLine("Found {0} valid new positions", valids.Count); var pict = valids[0]; var pictCoord = new Coords((int)pict.Point[0], (int)pict.Point[1]); var snap = satellite.TakePicture(pictCoord); takenPictures.Add(snap); pict.Value.TakePicture(pictCoord); pict.Value.Locations.Remove(pictCoord); tree.RemoveAt(pict.Point); Console.WriteLine("Satellite {1} Found {0} pict - Turn {2}", node.Length, satellite.Id, turn); ////Console.WriteLine("Satellite Lat {0} Lon {1} Pict {2} {3} Rot {4} {5}", satellite.Pos.Lat, //satellite.Pos.Lon, pict.Point[0], pict.Point[1], satellite.CurrentRot.Lat, satellite.CurrentRot.Lon); } } satellite.NextTurn(); } } var score = input.Collections.Where(c => c.Locations.Count == 0 && c.TakenPictures.Count > 0).Sum(p => p.Value); var solution = new Solution(takenPictures, score); return solution; }
public void KdTreeTest() { var lines = File.ReadLines("../../xyz.csv", Encoding.GetEncoding("euc-kr")); Assert.IsTrue(lines.Any()); var tree = new KdTree<double,Point>(3); var points = new List<Point>(); foreach (var line in lines) { var values = line.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); var xyz = values.Skip(1).Select(Convert.ToDouble).ToArray(); var point = new Point(values[0], xyz); points.Add(point); tree.Add(xyz, point); } var ret = tree.GetNearestNeighbours(points[12].XYZ, 2); Assert.IsTrue(ret.Any()); var retNames = ret.Select(a => a.Value.Name).ToArray(); foreach (var retName in retNames) { Console.WriteLine(retName); } Assert.AreEqual("나", retNames[1]); }