/// <summary> /// removes a list of multiple objects from the point cloud by a distance /// </summary> /// <param name="pInputPoints">the list of removable point clouds</param> /// <param name="pRemoveDistance">the nearest neighbour search distance</param> /// <returns>the amount of points removed</returns> public int removePointcloudsFromPointCloud(List <PointCloud> pInputPoints, float pRemoveDistance) { Object parWork = new Object(); HashSet <Point> removeList = new HashSet <Point>(); //go through list // parallel Parallel.ForEach(pInputPoints, pcl => { Parallel.ForEach(pcl.pointcloud_hs, p => { NearestNeighbour <Point> nn = pointcloud_kd.NearestNeighbors(new double[] { p.point.X, p.point.Y, p.point.Z }, 10000, pRemoveDistance); while (nn.MoveNext()) { lock (parWork) removeList.Add(nn.Current); } }); }); //remove points from pointcloud int removecount = 0; foreach (Point p in removeList) { if (this.pointcloud_hs.Remove(p)) { removecount++; } } resetLazyLoadingObjectsAfterUpdate(); return(removecount); }
private void KDSearch() { KDTree <int> kd = new KDTree <int>(3); // clear neighbours and init tree int i = 0; foreach (BoidController bc in boids) { bc.neighbours.Clear(); kd.AddPoint(new double[3] { bc.transform.position.x, bc.transform.position.y, bc.transform.position.z }, i); i++; } // search foreach (BoidController bc in boids) { NearestNeighbour <int> neighbours = kd.NearestNeighbors(new double[3] { bc.transform.position.x, bc.transform.position.y, bc.transform.position.z }, n, r_c2); while (neighbours.MoveNext()) { int id = neighbours.Current; if (id != bc.id) { bc.neighbours.Add(boids[id]); } } } }
/// <summary> /// downsamples the pointcloud by using a downsample factor. Reduces amount of points in downsample factor distance to 1 /// </summary> /// <param name="pDownsampleFactor">the downsample factor, a distance in m</param> public void downsamplePointcloud(float pDownsampleFactor) { //new target cloud HashSet <Point> newHS = new HashSet <Point>(); //check all initial points foreach (Point p in pointcloud_hs) { //if not processed, add to new cloud, check neighbours and set them as processed; processed points dont get added to new pointcloud if (!p.processed) { newHS.Add(p); p.processed = true; //check for nearest neighbours, set them processed, so they dont get added to list NearestNeighbour <Point> nn = pointcloud_kd.NearestNeighbors(new double[] { p.point.X, p.point.Y, p.point.Z }, 10000, pDownsampleFactor); while (nn.MoveNext()) { if (!nn.Current.processed) { nn.Current.processed = true; } } } } //goes through the point list and set every point as unprocessed Parallel.ForEach(newHS, point => point.processed = false); //set downsampled cloud as new this.pointcloud_hs = newHS; //resets the objects so they represent the current data this.resetLazyLoadingObjectsAfterUpdate(); }
public void Run() { var files = GetAllFiles(workSpace); var areas = GetAreas(files); var total = this.reader.GetGifts(workSpace + @"\Total\gifts.csv"); this.validator.Validate(total, areas); Parallel.ForEach(areas, area => { var gifts = area.Gifts; var tours = new List <Tour>(); while (gifts.Count() > 0) { var tour = new NearestNeighbour().GetTour(gifts, maxWeight); tours.Add(tour); gifts = gifts.Except(tour.Gifts).ToList(); Console.WriteLine("Tours: {0}, Remaining gifts: {1}", tours.Count(), gifts.Count()); } area.AddTour(tours); Console.WriteLine("Finished for area: "); //foreach (var tour in tours) //{ // //Plotter.Plot(tour.Gifts); // Plotter.PlotInfo(tour.Gifts); //} }); Write(areas); //Console.WriteLine("Total tour count: {0}", areas.SelectMany(t => t).Count()); Console.ReadLine(); }
public static bool Add(KDRectangle Rectangle) { if (tree.Size == 0) { tree.AddPoint(new double[] { Rectangle.LeftTop.X, Rectangle.RightBottom.X, Rectangle.LeftTop.Y, Rectangle.RightBottom.Y }, Rectangle); return(true); } else { NearestNeighbour <KDRectangle> pIter = tree.NearestNeighbors(new double[] { Rectangle.LeftTop.X, Rectangle.RightBottom.X, Rectangle.LeftTop.Y, Rectangle.RightBottom.Y }, 10); while (pIter.MoveNext()) { KDRectangle overlaper = pIter.Current; if (doOverlap(Rectangle.LeftTop, Rectangle.RightBottom, overlaper.LeftTop, overlaper.RightBottom)) { Console.WriteLine(Rectangle.Name); Rectangle.Filled = true; return(false); } } tree.AddPoint(new double[] { Rectangle.LeftTop.X, Rectangle.RightBottom.X, Rectangle.LeftTop.Y, Rectangle.RightBottom.Y }, Rectangle); return(true); } }
public void GetTour_GiftListEmpty_ReturnEmptyList() { var nearestNeighbour = new NearestNeighbour(); var tour = nearestNeighbour.GetTour(new List <Gift>(), 0); Assert.AreEqual(0, tour.Gifts.Count()); }
public void TestNearestNeighbour() { neighbour = new NearestNeighbour(); neighbour.graph = graph; foreach (var v in neighbour.NearestNeighbourOptimization()) { System.Diagnostics.Debug.Write(v.index + " "); } System.Diagnostics.Debug.WriteLine($"\nDistance: { neighbour.minDistance}\n"); }
public void GetTour_OnlyOneGiftAndTooHeavy_ReturnEmptyList() { var maxWeight = 10; var gifts = new List <Gift> { new Gift(1, 11, 0, 0) }; var nearestNeighbour = new NearestNeighbour(); var tour = nearestNeighbour.GetTour(gifts, maxWeight); Assert.AreEqual(0, tour.Gifts.Count()); }
public void GetTour_OnlyOneGiftAndWeightIsOk_ReturnListWithGift() { var maxWeight = 10; var gifts = new List <Gift> { new Gift(1, 9, 0, 0) }; var nearestNeighbour = new NearestNeighbour(); var tour = nearestNeighbour.GetTour(gifts, maxWeight).Gifts; Assert.AreEqual(tour.First(), gifts.First()); }
void Update() { if (Input.GetMouseButton(0)) { ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (groundPlane.Raycast(ray, out rayDistance)) { pos = ray.GetPoint(rayDistance); pIter = Collection.NearestNeighbors(new double[] { pos.x, pos.z }, MaxCount, Range); while (pIter.MoveNext()) { pIter.Current.Transform.localScale = Vector3.zero; } } } }
private static void AssignmentOnedotEight(Dictionary <int, Dictionary <int, double> > ratings, int targetUser, Similarity similarityType, double threshold, int maxNeighhbours, int maxResults, int?minimumRatings) { Console.WriteLine("\n\n## Assignment 1.8"); Console.WriteLine("------------------------------------------"); Console.WriteLine("Rating predictions for user " + targetUser + " with a minimum of " + minimumRatings + " items rated"); var neighbours = new NearestNeighbour().FindNearestNeighbour(ratings, targetUser, threshold, maxNeighhbours, similarityType); var predictions = new PredictRating().PredictTopRatings(ratings, neighbours, targetUser, 0.35, 25, 8, minimumRatings, similarityType); foreach (var prediction in predictions) { Console.WriteLine("\tUser " + targetUser + " will rate item " + prediction.Key + " with a rating of " + prediction.Value); } }
public void GetTour_FiveGiftsWithTotalWeightOverMaxWeight_ReturnListInCorrectOrderWithContainingOnlySubsetOfGifts() { var maxWeight = 40; var gifts = new List <Gift> { new Gift(1, 20, 3, 0), new Gift(2, 20, 2, 0), new Gift(3, 20, 60, 0), new Gift(4, 20, 1, 0), new Gift(5, 20, 80, 0) }; var nearestNeighbour = new NearestNeighbour(); var tour = nearestNeighbour.GetTour(gifts, maxWeight).Gifts; Assert.AreEqual(2, tour.Count()); Assert.AreEqual(tour[0], gifts[4]); Assert.AreEqual(tour[1], gifts[2]); }
public void GetTour_FiveGiftsWithTotalWeightUnderMaxWeight_ReturnListInCorrectOrderWithContainingAllGifts() { var maxWeight = 1000; var gifts = new List <Gift> { new Gift(1, 20, 0, 0), new Gift(2, 20, 30, 0), new Gift(3, 20, 70, 0), new Gift(4, 20, 10, 0), new Gift(5, 20, 5, 0) }; var nearestNeighbour = new NearestNeighbour(); var tour = nearestNeighbour.GetTour(gifts, maxWeight).Gifts; Assert.AreEqual(tour[0], gifts[2]); Assert.AreEqual(tour[1], gifts[1]); Assert.AreEqual(tour[2], gifts[3]); Assert.AreEqual(tour[3], gifts[4]); Assert.AreEqual(tour[4], gifts[0]); }
/** * Similar to Merge vertices, expect that this method only collapses vertices within * a specified distance of one another (typically epsilon). Returns true if any action * was taken, false otherwise. Outputs indices that have been welded in the @welds var. */ public static bool WeldVertices(this pb_Object pb, int[] indices, float delta, out int[] welds) { List <int> universal = pb.sharedIndices.GetUniversalIndices(indices).ToList(); Vector3[] v = pb.vertices; HashSet <int> used = new HashSet <int>(); KDTree <int> tree = new KDTree <int>(3, 48); // dimensions (xyz), node size for (int i = 0; i < universal.Count; i++) { Vector3 vert = v[pb.sharedIndices[universal[i]][0]]; tree.AddPoint(new double[] { vert.x, vert.y, vert.z }, universal[i]); } List <List <int> > groups = new List <List <int> >(); double[] point = new double[3] { 0, 0, 0 }; int[][] si = pb.sharedIndices.ToArray(); for (int i = 0; i < universal.Count; i++) { if (used.Contains(universal[i])) { continue; } int tri = si[universal[i]][0]; point[0] = v[tri].x; point[1] = v[tri].y; point[2] = v[tri].z; NearestNeighbour <int> neighborIterator = tree.NearestNeighbors(point, 64, delta); List <int> neighbors = new List <int>(); while (neighborIterator.MoveNext()) { if (used.Contains(neighborIterator.Current)) { continue; } used.Add(neighborIterator.Current); neighbors.Add(neighborIterator.Current); } used.Add(universal[i]); groups.Add(neighbors); } pb_IntArray[] rebuilt = new pb_IntArray[groups.Count]; // + remainingCount ]; welds = new int[groups.Count]; for (int i = 0; i < groups.Count; i++) { rebuilt[i] = new pb_IntArray(groups[i].SelectMany(x => pb.sharedIndices[x].array).ToArray()); welds[i] = rebuilt[i][0]; } foreach (pb_IntArray arr in rebuilt) { Vector3 avg = pb_Math.Average(pbUtil.ValuesWithIndices(v, arr.array)); foreach (int i in arr.array) { v[i] = avg; } } pb.SetVertices(v); // profiler.EndSample(); pb_IntArray[] remaining = pb.sharedIndices.Where((val, index) => !used.Contains(index)).ToArray(); rebuilt = pbUtil.Concat(rebuilt, remaining); pb.SetSharedIndices(rebuilt); return(true); }
public FixedPaletteQuantization(Color[] fixedPalette) { this.nearestNeighbour = new ExhaustivePaletteSearch(); this.Palette = fixedPalette; }
private void btnCorrelation_Click(object sender, EventArgs e) { SimpleCorrelation correlation = new SimpleCorrelation(); Bitmap bmp0 = new Bitmap(Bitmap.FromFile("0.bmp")); Bitmap bmp1 = new Bitmap(Bitmap.FromFile("1.bmp")); Bitmap bmp2 = new Bitmap(Bitmap.FromFile("2.bmp")); Bitmap bmp3 = new Bitmap(Bitmap.FromFile("3.bmp")); Bitmap bmp4 = new Bitmap(Bitmap.FromFile("4.bmp")); Bitmap bmp5 = new Bitmap(Bitmap.FromFile("5.bmp")); Bitmap bmp6 = new Bitmap(Bitmap.FromFile("6.bmp")); Bitmap bmp7 = new Bitmap(Bitmap.FromFile("7.bmp")); Bitmap bmp8 = new Bitmap(Bitmap.FromFile("8.bmp")); Bitmap bmp9 = new Bitmap(Bitmap.FromFile("9.bmp")); List<PatternClass> teachingVector = new List<PatternClass>(); for (int i = 0; i < 5; i++) { teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp0, i),0)), 0)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp1, i),1)), 1)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp2, i),2)), 2)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp3, i),3)), 3)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp4, i),4)), 4)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp5, i),5)), 5)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp6, i),6)), 6)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp7, i),7)), 7)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp8, i),8)), 8)); teachingVector.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures(CropImage(bmp9, i),9)), 9)); } List<PatternClass> sampleObjects = new List<PatternClass>(); sampleObjects.Add(new PatternClass(new FeatureVector(ImageFeatureExtractor.ExtractFeatures((Bitmap)pictureBox1.Image, 10)), 0)); NearestAverage averageAlg = new NearestAverage(new EuclideanDistance()); int classyfiAvg = averageAlg.Classify(teachingVector, sampleObjects[0].FeatureVector.Values); NearestNeighbour neighbourAlb = new NearestNeighbour(3, new EuclideanDistance()); int classyfiNeighbour = neighbourAlb.Classify(teachingVector, sampleObjects[0].FeatureVector.Values); pictureBox1.Image = null; pictureBox1.Invalidate(); MessageBox.Show(classyfiNeighbour.ToString()); }
private static void Main(string[] args) { Options options = null; Parser.Default.ParseArguments <Options>(args) .WithParsed(res => options = res) .WithNotParsed(err => Environment.Exit(1)); var stopWatch = Stopwatch.StartNew(); if (!File.Exists(options.FileName)) { Console.WriteLine($"File {options.FileName} doesn't exist."); return; } Console.Write($"Start parsing file: {options.FileName} "); City city; try { using (var reader = new StreamReader(options.FileName)) { city = (City) new XmlSerializer(typeof(City)).Deserialize(reader); } } catch (Exception e) { Console.WriteLine( $"Unable to parse osm file: {e.Message}. See about downloading here: https://github.com/bruce-willis/City-Roads/blob/develop/docs/download.md"); return; } Console.WriteLine($"Elapsed time: {stopWatch.Elapsed}"); TimeHelper.MeasureTime(() => SvgHelper.GenerateSvg(city, options), "generationg svg file"); if (options.GenerateNodesList) { TimeHelper.MeasureTime(() => CsvHelper.WriteNodesInfo(options.OutputDirectory), "creating csv with nodes' information"); } if (options.GenerateAdjacencyList) { TimeHelper.MeasureTime(() => CsvHelper.WriteAdjacencyList(options.OutputDirectory), "creating csv with adjacency list"); } if (options.GenerateAdjacencyMatrix) { TimeHelper.MeasureTime(() => CsvHelper.WriteAdjacencyMatrix(options.OutputDirectory), "creating csv with adjacency matrix"); } DistanceHelper.AddNodes(city); if (options.FindShortestPathes) { DistanceHelper.CompareAlgorithms(options.OutputDirectory); } if (options.SolveSalesmanProblem) { Directory.CreateDirectory(Path.Combine(options.OutputDirectory, "Salesman")); TimeHelper.MeasureTime(() => CommonSalesman.Distances.GetType(), "calculating distances and pathes between destinations"); TimeHelper.MeasureTime(() => NearestNeighbour.Calculate(options.OutputDirectory), "solving travelling salesman problem using nearest neighbour"); TimeHelper.MeasureTime(() => NearestNeighbour.Calculate(options.OutputDirectory, withRandom: true), "solving travelling salesman problem using nearest neighbour and random"); //int i = 0; //double d1, d2; //do //{ // d1 = NearestNeighbour.Calculate(city, options.OutputDirectory); // d2 = NearestNeighbour.CalculateWithRandom(city, options.OutputDirectory); // Console.WriteLine(i++); //} while (d1 <= d2); //Console.WriteLine(d1); //Console.WriteLine(d2); TimeHelper.MeasureTime(() => SimulatedAnnealing.Calculate(10, 0.00001, options.OutputDirectory), "solving tsp using simulated annealing"); } Console.WriteLine($"\nJob done! Now it's time for tea. Total time elapsed: {stopWatch.Elapsed}"); Console.WriteLine(new Random().Next(0, 2) == 1 ? "Лучший в СПбГУ - Факультет ПМ-ПУ" : "Ответ на главный вопрос жизни, вселенной и всего такого - 42"); }
protected override void PreQuantization(EmguImage image) { this.listColor = new List<Color>(); this.nearestNeighbour = null; this.image = image; }
protected override Pixel QuantizatePixel(int x, int y) { // Get the color and add to the list Color color = image[y, x]; int colorIndex; if (listColor.Count < this.MaxColors) { if (!listColor.Contains(color)) listColor.Add(color); colorIndex = listColor.IndexOf(color); } else { // Create the labpalette if so if (nearestNeighbour == null) { LabColor[] labPalette = ColorConversion.ToLabPalette<Color>(listColor.ToArray()); nearestNeighbour = new ExhaustivePaletteSearch(); nearestNeighbour.Initialize(labPalette); } LabColor labNoTrans = ColorConversion.ToLabPalette<Color>(new Color[] { color })[0]; colorIndex = nearestNeighbour.Search(labNoTrans); } return new Pixel((uint)colorIndex, (uint)color.Alpha, true); }
static void Main(string[] args) { String dataFilePath = args[0]; String weightsFilePath = args[1]; String outputFilePath = args[2]; int metric = Int32.Parse(args[3]); int numThreads = Int32.Parse(args[4]); Stopwatch w = new Stopwatch(); w.Start(); List <double[]> samples = CSVIO.Load <double>(dataFilePath); List <double[]> weights = CSVIO.Load <double>(weightsFilePath); w.Stop(); long loadingMS = w.ElapsedMilliseconds; w.Reset(); w.Start(); DistanceFunctions distFunc = distFunc = new SquareEuclideanDistanceFunction(); if (metric == 2) { distFunc = new Cosine(); } if (metric == 3) { distFunc = new Pearson(); } Console.WriteLine("Using distance function with brute force: {0} and numthreads: {1}", metric, numThreads); NNAlgorithm nnMethod = null; // if euclidean then can use fast kdtree if (metric == 1) { nnMethod = new KDTreeNN(weights, distFunc); } else { nnMethod = new BruteForceNN(weights, distFunc); } List <int[]> nearestNeighbours = NearestNeighbour.GetNearestNeighbours(samples, nnMethod, numThreads); w.Stop(); long vqMS = w.ElapsedMilliseconds; w.Reset(); w.Start(); CSVIO.Save <int>(outputFilePath, nearestNeighbours); w.Stop(); long savingMS = w.ElapsedMilliseconds; Console.WriteLine("Loading Time: {0} NN Time: {1} Saving Time: {2}", loadingMS, vqMS, savingMS); }
private static void AssignmentOnedotTwo(Dictionary <int, Dictionary <int, double> > ratings, int user, double threshold, int max, Similarity similarityType) { Console.WriteLine("\n\n## Assignment 1.2"); Console.WriteLine("------------------------------------------"); var nearestNeighbours = new Dictionary <int, double>(); if (similarityType == Similarity.EuclidianAndPearsonAndCosine) { var similarities = new Similarity[3]; similarities[0] = Similarity.Euclidian; similarities[1] = Similarity.Pearson; similarities[2] = Similarity.Cosine; foreach (var sim in similarities) { nearestNeighbours = new NearestNeighbour().FindNearestNeighbour(ratings, user, threshold, max, sim); var loop = new Dictionary <int, double>(); switch (sim) { case Similarity.Euclidian: loop = nearestNeighbours.OrderBy(o => o.Value).Take(max) .ToDictionary(k => k.Key, v => v.Value); Console.WriteLine("Nearest neighbours using Euclidian are:"); break; case Similarity.Pearson: loop = nearestNeighbours.OrderByDescending(o => o.Value).Take(max) .ToDictionary(k => k.Key, v => v.Value); Console.WriteLine("\nNearest neighbours using Pearson are:"); break; case Similarity.Cosine: loop = nearestNeighbours.OrderByDescending(o => o.Value).Take(max) .ToDictionary(k => k.Key, v => v.Value); Console.WriteLine("\nNearest neighbours using Cosine are:"); break; default: break; } foreach (KeyValuePair <int, double> item in loop) { Console.WriteLine("\tUser " + item.Key + " with a distance of " + item.Value); } } } else { nearestNeighbours = new NearestNeighbour().FindNearestNeighbour(ratings, user, threshold, max, similarityType); Console.WriteLine("Nearest neighbours are:"); foreach (KeyValuePair <int, double> item in nearestNeighbours) { Console.WriteLine("\tUser " + item.Key + " with a distance of " + item.Value); } } }
/// <summary> /// calculates an euclidean cluster extraction from the point cloud based on a euclidean distance. returns a list of point clouds /// </summary> /// <param name="pInputCloud">the combined point cloud</param> /// <param name="pConfig">the config object for the algorithms</param> /// <returns>a list of point clouds</returns> public static List <PointCloud> calculateEuclideanClusterExtraction(PointCloud pInputCloud, float pEuclideanExtractionRadius, CancellationToken pToken) { //update status Log.LogManager.updateAlgorithmStatus("Euclidean Cluster Extraction"); Log.LogManager.writeLogDebug("[EuclideanClusterExtraction] Extraction Radius: " + pEuclideanExtractionRadius); //creates the end list to be returned List <PointCloud> clusters = new List <PointCloud>(); foreach (Point p in pInputCloud.pointcloud_hs) { pToken.ThrowIfCancellationRequested(); //checks if point has been processed already, if yes, skip if (p.processed) { continue; } //create new queue Queue <Point> Q = new Queue <Point>(); //add point to queue Q.Enqueue(p); //result values HashSet <Point> resultCloud = new HashSet <Point>(); PointCloud resultCluster = new PointCloud(resultCloud); //while queue has points, check for neighbours and add them to queue as well, do as long there are neighbours while (Q.Count > 0) { pToken.ThrowIfCancellationRequested(); //remove point from queue and add to current cluster, point has been processed by doing that Point p2 = Q.Dequeue(); if (p2.processed) { continue; } resultCloud.Add(p2); p2.processed = true; //check all neighbour points, add them to queue if they havnt been processed yet double[] tp = { p2.point.X, p2.point.Y, p2.point.Z }; NearestNeighbour <Point> nb = lookForNeighbours(pInputCloud.pointcloud_kd, tp, pEuclideanExtractionRadius); while (nb.MoveNext()) { if (!nb.Current.processed) { Q.Enqueue(nb.Current); } } } clusters.Add(resultCluster); } //set all points as unprocessed, so they can be used for other algorithms Parallel.ForEach(clusters, pointcloud => Parallel.ForEach(pointcloud.pointcloud_hs, point => point.processed = false)); //updates the status Log.LogManager.updateAlgorithmStatus("Done"); //return return(clusters); }