Exemplo n.º 1
0
        private byte[][] GenerateInitialAllocation()
        {
            this.variables = this.InitializeMatrix();

            Tuple <double, int>[] machinesAndScores = new Tuple <double, int> [this.Rows];
            for (int i = 0; i < this.Rows; i++)
            {
                double score = this.ComputeMachineScore(i);
                machinesAndScores[i] = new Tuple <double, int>(score, i);
            }

            Tuple <double, int>[] ordered = machinesAndScores.OrderByDescending(c => c.Item1).ToArray();

            for (int j = 0; j < this.Columns; j++)
            {
                foreach (Tuple <double, int> machineAndScore in ordered.Take(this.desiredContainerInstanceCounts[j]))
                {
                    this.variables[machineAndScore.Item2][j] = 1;
                }

                for (int i = 0; i < this.Rows; i++)
                {
                    double score = this.ComputeMachineScore(i);
                    machinesAndScores[i] = new Tuple <double, int>(score, i);
                }

                ordered = machinesAndScores.OrderByDescending(c => c.Item1).ToArray();
            }

            return(this.variables);
        }
Exemplo n.º 2
0
        private IEnumerable <int> CalcularDistancias(Ponto ponto, int nItens)
        {
            var distancias = new Tuple <int, double> [this.Count - 1];

            int[] ordenadas = new int[this.Count];

            int endBusca = _mapa[ponto];

            // Inicializa o vetor de distâncias
            for (int idx = 0; idx < this.Count; idx++)
            {
                Tuple <int, double> dPonto = null;

                dPonto = idx == endBusca
                    ? new Tuple <int, double>(endBusca, 0)
                    : new Tuple <int, double>(idx, Ponto.Distancia(_caderno[idx].Local, ponto));

                if (idx == endBusca)
                {
                    continue;
                }

                distancias[idx] = dPonto;
            }

            // inclui, ordenadamente, no vetor de distâncias
            return(distancias
                   .OrderByDescending(t => t.Item2)
                   .Take(nItens)
                   .Select(t => t.Item1));
        }
Exemplo n.º 3
0
        public static Task <Tuple <int[], int, int[], int, int> > BeamSerach(int[] board, int beamWeight, int limitWeight = 500000)
        {
            return(Task.Run(() =>
            {
                var results = new Tuple <int[], int, int[], int, int> [30];//board, score, route, startRow, startColumn;
                Parallel.For(0, 6 * 5, idx =>
                {
                    var route = new int[50];
                    int tmpScore = 0;

                    fixed(int *b = board, r = route)
                    {
                        try
                        {
                            tmpScore = DoubleLimitedSearch(b, beamWeight, limitWeight, idx / 6, idx % 6, r);
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine(idx);
                            results[idx] = Tuple.Create(new int[50], 0, new int[50], idx / 6, idx % 6);
                            return;
                        }
                        //tmpScore = BeamSearch(b, 1, 42, 400, idx / 6, idx % 6, r);
                    }

                    results[idx] = Tuple.Create(board, tmpScore, route, idx / 6, idx % 6);
                });
                return results.OrderByDescending(x => x.Item2).First();
            }));
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            var s = new Tuple <int, int, int> [3];

            for (var i = 0; i < 3; i++)
            {
                var _ = Console.ReadLine().Split();
                var h = int.Parse(_[0]);
                var w = int.Parse(_[1]);
                s[i] = Tuple.Create(i, h, w);
            }

            var o = s.OrderByDescending(x => x.Item2).ThenBy(x => x.Item3).ToArray();

            foreach (var t in o)
            {
                if (t.Item1 == 0)
                {
                    Console.WriteLine("A");
                }
                else if (t.Item1 == 1)
                {
                    Console.WriteLine("B");
                }
                else
                {
                    Console.WriteLine("C");
                }
            }
        }
        public void OrderByDescendingWithPropertyReturnsProperlyOrderedResult()
        {
            var items = new Tuple <string, int>[]
            {
                new Tuple <string, int>("2", 2),
                new Tuple <string, int>("3", 3),
                new Tuple <string, int>("1", 1)
            };

            var sortedItems = items.OrderByDescending((t) => t.Item1);

            Assert.True(items.AsQueryable <Tuple <string, int> >().OrderByDescending("Item1").SequenceEqual(sortedItems));
        }
Exemplo n.º 6
0
        //return Tuple<double, double, double> for each box start m/z, end m/z, m/z length
        public static Tuple <double, double, double>[] GenerateDynamicBoxes_TD(List <IsoEnvelop> isoEnvelops)
        {
            var thred = isoEnvelops.OrderByDescending(p => p.IntensityRatio).First().IntensityRatio / 20;
            var mzs   = isoEnvelops.Where(p => p.IntensityRatio > thred).Select(p => p.ExperimentIsoEnvelop.First().Mz).OrderBy(p => p).ToList();

            Tuple <double, double, double>[] ranges = new Tuple <double, double, double> [mzs.Count];

            for (int i = 1; i < mzs.Count; i++)
            {
                ranges[i - 1] = new Tuple <double, double, double>(mzs[i - 1], mzs[i], mzs[i] - mzs[i - 1]);
            }
            ranges[mzs.Count - 1] = new Tuple <double, double, double>(mzs.Last(), 2000, 2000 - mzs.Last());

            return(ranges.OrderByDescending(p => p.Item3).Where(p => p.Item3 > 15).Take(12).OrderBy(p => p.Item1).ToArray());
        }
Exemplo n.º 7
0
    static void Main()
    {
        // Create array of tuples.
        Tuple <int, int>[] tuples = new Tuple <int, int> [3];
        tuples[0] = new Tuple <int, int>(3, 6);
        tuples[1] = new Tuple <int, int>(6, 4);
        tuples[2] = new Tuple <int, int>(0, 60);

        // Order by descending on Item1.
        var result = tuples.OrderByDescending(a => a.Item1);

        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }
        /**
         * Sorts characters in descending order by word count
         *
         * @param wcounts a map of character -> word count
         * @return sorted vector of {character, word count} pairs
         */
        public static List <Tuple <int, string> > SortCharactersByWordcount(Dictionary <string, int> wordcount)
        {
            List <Tuple <int, string> > sortedByValueList = new List <Tuple <int, string> >();

            // Implement sorting by word count here
            Tuple <int, string>[] tupleArray = new Tuple <int, string> [wordcount.Count];
            int i = 0;

            OrderedDictionary orderedWordCount = new OrderedDictionary();

            foreach (KeyValuePair <string, int> pair in wordcount)
            {
                orderedWordCount.Add(pair.Key, pair.Value);
            }


            ICollection keyCollection = orderedWordCount.Keys;

            String[] myKeys = new String[orderedWordCount.Count];
            keyCollection.CopyTo(myKeys, 0);

            ICollection valueCollection = orderedWordCount.Values;

            int[] myValues = new int[orderedWordCount.Count];
            valueCollection.CopyTo(myValues, 0);

            for (int k = 0; k < orderedWordCount.Count; k++)
            {
                if (k < tupleArray.Length)
                {
                    tupleArray[k] = new Tuple <int, string>(myValues[k], myKeys[k]);
                }
                else
                {
                    Console.WriteLine("Error: 'k' index is out of bounds.\n");
                }
            }

            var result = tupleArray.OrderByDescending(a => a.Item1);

            foreach (var item in result)
            {
                sortedByValueList.Add(item);
            }

            return(sortedByValueList);
        }
Exemplo n.º 9
0
        void Solve()
        {
            io.i(out N, out M);
            io.ini(out a, out b, out y, M);
            io.i(out Q);
            io.ini(out v, out w, Q);

            var uf       = new UnionFind(N);
            var aby      = new Tuple <int, int, int> [M];
            var vwi      = new Tuple <int, int, int> [Q];
            var abyQueue = new Queue <Tuple <int, int, int> >();
            var vwiQueue = new Queue <Tuple <int, int, int> >();

            M.REP(i => aby[i] = Tuple.Create(a[i], b[i], y[i]));
            Q.REP(i => vwi[i] = Tuple.Create(v[i], w[i], i));

            foreach (var v in aby.OrderByDescending(t => t.Item3).ToArray())
            {
                abyQueue.Enqueue(v);
            }
            foreach (var v in vwi.OrderByDescending(t => t.Item2).ToArray())
            {
                vwiQueue.Enqueue(v);
            }

            var ans = new int[Q];

            while (vwiQueue.Any())
            {
                var cur  = vwiQueue.Dequeue();
                var city = cur.Item1;
                var year = cur.Item2;
                var idx  = cur.Item3;
                while (abyQueue.Any() && abyQueue.First().Item3 > year)
                {
                    var cur2 = abyQueue.Dequeue();
                    var a    = cur2.Item1;
                    var b    = cur2.Item2;
                    uf.Unite(a, b);
                }
                ans[idx] = uf.Size(city);
            }

            io.o(ans);
        }
Exemplo n.º 10
0
        public static Tuple <int[], int, int[], int, int> BeamSerach(int[] board)
        {
            var results = new Tuple <int[], int, int[], int, int> [30];//board, score, route, startRow, startColumn;

            Parallel.For(0, 6 * 5, idx =>
            {
                var route    = new int[50];
                int tmpScore = 0;

                fixed(int *b = board, r = route)
                {
                    tmpScore = BeamSearch(b, 1, 42, 400, idx / 6, idx % 6, r);
                }

                results[idx] = Tuple.Create(route, tmpScore, route, idx / 6, idx % 6);
            });
            return(results.OrderByDescending(x => x.Item2).First());
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            //入力
            int N = int.Parse(Console.ReadLine());

            //各値の和とインデックス情報を持つ配列 Tuple<sum,index>
            Tuple <int, int>[] res = new Tuple <int, int> [N];
            //A,B
            int[] A = new int[N];
            int[] B = new int[N];

            //sumの計算をする
            for (int i = 0; i < N; i++)
            {
                int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();
                A[i]   = input[0];
                B[i]   = input[1];
                res[i] = Tuple.Create(i, A[i] + B[i]);
            }

            //和の値で降順でソートする
            var res2 = res.OrderByDescending(x => x.Item2);

            //ソートされたデータからインデックスの情報を取り出して、
            //高橋くんのときは奇数番目のA[i]をたす。青木くんのときは偶数番目のB[i]を引く
            long count = 0;
            int  index = 0;

            foreach (var i in res2)
            {
                if (index % 2 == 0)
                {
                    count += A[i.Item1];
                }
                else
                {
                    count -= B[i.Item1];
                }
                index++;
            }

            Console.WriteLine(count);
        }
Exemplo n.º 12
0
        private static void LQDeferred_Exec()
        {
            Tuple <int, int>[] tuples = new Tuple <int, int> [4];
            tuples[0] = new Tuple <int, int>(3, 6);
            tuples[1] = new Tuple <int, int>(6, 4);
            tuples[2] = new Tuple <int, int>(0, 60);

            // Order by descending on Item1
            var result = tuples.OrderByDescending(a => a.Item1);

            //* we can add here, because of deferrred execution
            tuples[3] = new Tuple <int, int>(4, 65);
            Console.WriteLine("Example of deferred Excution");
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
Exemplo n.º 13
0
        public static int FullPacksackSelectionEx(int[] weights, int[] values, int packsackCapacity)
        {
            int m = weights.Length;

            float[] quality = new float[m];
            for (int i = 0; i < m; i++)
            {
                quality[i] = (float)values[i] / weights[i];
            }

            Tuple <int, int>[] wv = new Tuple <int, int> [m];
            for (int i = 0; i < m; i++)
            {
                wv[i] = new Tuple <int, int>(weights[i], values[i]);
            }

            wv = wv.OrderByDescending(x => (float)x.Item2 / x.Item1).ToArray();

            int times = 0;
            int value, weight, maxValues = 0;

            for (int i = 0; i < m; i++)
            {
                times = packsackCapacity / wv[i].Item1;

                if (times < 1)
                {
                    continue;
                }

                value             = times * wv[i].Item2;
                weight            = times * wv[i].Item1;
                maxValues        += value;
                packsackCapacity -= weight;

                if (packsackCapacity == 0)
                {
                    break;
                }
            }

            return(maxValues);
        }
Exemplo n.º 14
0
        private void HandleProcesses(SpecWriter writer, ConfigWriter configWriter, List <Process> processes)
        {
            Tuple <ProcessStats, Process>[] stats = new Tuple <ProcessStats, Process> [processes.Count];

            for (int i = 0; i < processes.Count; i++)
            {
                stats[i] = new Tuple <ProcessStats, Process>(GetProcessStats(processes[i]), processes[i]);
            }

            var sortedStats = stats.OrderByDescending(s => s.Item1.ExecutionTimeMs);

            // Mark the longest process in the spec so it may be used for scaling in the transformer if applicable
            bool isLongest = true;

            foreach (var item in sortedStats)
            {
                WriteMimicInvocation(item.Item2, writer, configWriter, isLongest);
                isLongest = false;
            }
        }
Exemplo n.º 15
0
    private Tuple<Point, List<Point>>[] unique(Tuple<Point, List<Point>>[] killPoints)
    {
        var uniqueEffects = new List<Tuple<Point, List<Point>>>();
        foreach (var killPoint in killPoints.OrderByDescending(t=>t.Item2.Count))
        {
            var isCoveredByExistingPoint =
                uniqueEffects.Any(existingKillPoint =>
                    killPoint.Item2.All(p=> existingKillPoint.Item2.Contains(p))
                );

            if (!isCoveredByExistingPoint)
            {
                //Console.Error.WriteLine("    + Adding test of {0}", killPoint.Item1);
                uniqueEffects.Add(killPoint);
            }
            else
            {
                //Console.Error.WriteLine("    - Skipping test of {0}", killPoint.Item1);
            }
        }
        return uniqueEffects.ToArray();
    }
Exemplo n.º 16
0
        public static Tuple<int[], int, int[], int, int> BeamSerach(int[] board)
        {
            var results = new Tuple<int[], int, int[], int, int>[30];//board, score, route, startRow, startColumn;
            Parallel.For(0, 6 * 5, idx =>
            {
                var route = new int[50];
                int tmpScore = 0;

                fixed (int* b = board, r = route)
                {
                    tmpScore = BeamSearch(b, 1, 42, 400, idx / 6, idx % 6, r);
                }

                results[idx] = Tuple.Create(route, tmpScore, route, idx / 6, idx % 6);
            });
            return results.OrderByDescending(x => x.Item2).First();
        }
Exemplo n.º 17
0
        private static void Main()
        {
            var img = new Bitmap(Image.FromFile(".\\Fingerprints\\102_5.tif"));
            var imgBytes = new int[img.Size.Width, img.Size.Height];
            for (var x = 0; x < img.Size.Width; x++)
                for (var y = 0; y < img.Size.Height; y++)
                {
                    var color = img.GetPixel(x, y);
                    imgBytes[x, y] = (int)(.299 * color.R + .587 * color.G + .114 * color.B);
                }

            var orfield = OrientationFieldGenerator.GenerateOrientationField(imgBytes);
            //VSCOMEdetector(orfield);
            int nFilters = 7;
            int nBands = 3;
            int bandRadius = 24;
            int holeRadius = 14;
            int nSectors = 9;


           
            var filterbank = new List<List<Tuple<int, int, double>>>();

            int[,] filtersInt = new int[32,nFilters*32];

            for (int i = 0; i < nFilters; i++)
            {
                filterbank.Add(CreateGaborFilter((1.0/10), Math.PI/nFilters*i));
            }

            // this code was used to test the similarity of the fingerprints
            //var min = filterbank.SelectMany(x=>x).Select(x=>x.Item3).Min();
            //var max = filterbank.SelectMany(x=>x).Select(x=>x.Item3).Max();

            //for (int i = 0; i < nFilters; i++)
            //{
            //    var filter = filterbank[i];
            //    foreach (var tuple in filter)
            //    {
            //        filtersInt[tuple.Item1, tuple.Item2 + i*32] = (int) ((tuple.Item3 - min)/(max - min)*255);
            //    }
            //}

            //Common.SaveAndShowImage(filtersInt);

            int size = nBands * nSectors*nFilters;

            int num = 60000;

            List<double>[] dbase = new List<double>[num];
            var rand = new Random();
            for (int w = 0; w < num; w++)
            {
                var lst = new List<double>();
                for(int s=0;s<size;s++)
                {
                    lst.Add(rand.NextDouble() * 128.0f);
                }
                dbase[w] = lst;
            }

            using (FileStream fs = new FileStream("C:\\temp\\fusrodah_cpu_results.csv", FileMode.Create))
            {
                using (StreamWriter streamWriter = new StreamWriter(fs))
                {
                    streamWriter.WriteLine("Find;Create;Match;Top");
                    for (int n = 0; n < 20; n++)
                    {
                        int radius = nBands*bandRadius + holeRadius + 16; //mask size

                        var sw = new Stopwatch();
                        sw.Start();
                        PerformNewDetectionAlgorithmTestfire(imgBytes);
                        streamWriter.Write(sw.ElapsedMilliseconds + ";");
                        sw.Stop();


                        sw.Restart();
                        var normalizedImage =
                            NormalizeImage(imgBytes, nBands, holeRadius, bandRadius,
                                           265, 292);
                        //Common.SaveAndShowImage(normalizedImage);
                        var filteredImages = new List<int[,]>();
                        for (int i = 0; i < nFilters; i++) filteredImages.Add(null);
                        Parallel.ForEach(filterbank, new ParallelOptions() {MaxDegreeOfParallelism = 4},
                                         filter =>
                                             {

                                                 var filtered = FilterWithGaborFilter(normalizedImage,
                                                                                      filter, nBands, holeRadius,
                                                                                      bandRadius,
                                                                                      265, 292);
                                                 //Common.SaveAndShowImage(filtered);
                                                 filteredImages[filterbank.IndexOf(filter)] = filtered;
                                             }

                            );
                        var fingercode = new List<double>();
                        for (int i = 0; i < nFilters*nBands*nSectors; i++)
                        {
                            fingercode.Add(0);
                        }
                        Parallel.ForEach(filteredImages,
                                         new ParallelOptions {MaxDegreeOfParallelism = 4},
                                         filteredImgBytes =>
                                             {
                                                 var fingercodePart = FormFingerCode(filteredImgBytes, nSectors, nBands,
                                                                                     holeRadius,
                                                                                     bandRadius);
                                                 int startIndex = filteredImages.IndexOf(filteredImgBytes)*
                                                                  nBands*nSectors;
                                                 foreach (var d in fingercodePart)
                                                 {
                                                     fingercode[startIndex++] = d;
                                                 }
                                             });
                        sw.Stop();
                        streamWriter.Write(sw.ElapsedMilliseconds + ";");
                        //Common.SaveFingerCode(fingercode, nBands, nSectors, nFilters, bandRadius, holeRadius);
                        sw.Restart();
                        Tuple<int, double>[] result = new Tuple<int, double>[num];

                        Parallel.ForEach(new[] {0, 1, 2, 3}, new ParallelOptions() {MaxDegreeOfParallelism = 4},
                                         (offset) =>
                                             {
                                                 for (int i = 0; i < num/4; i++)
                                                 {
                                                     var index = i*4 + offset;
                                                     result[index] = Tuple.Create(index,
                                                                                  CalculateDistance(fingercode,
                                                                                                    dbase[index]));
                                                 }
                                             });
                        sw.Stop();
                        streamWriter.Write(sw.ElapsedMilliseconds + ";");
                        sw.Restart();
                        result = result.OrderByDescending(x => x.Item2).ToArray();
                        sw.Stop();
                        streamWriter.WriteLine(sw.ElapsedMilliseconds);
                    }
                }
            }
        }
Exemplo n.º 18
0
        static void Main()
        {
            int T = int.Parse(Console.ReadLine());

            for (int t = 1; t <= T; t++)
            {
                int N      = int.Parse(Console.ReadLine());
                var levels = new Tuple <int, int> [N];
                for (int i = 0; i < N; i++)
                {
                    var line = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
                    levels[i] = new Tuple <int, int>(line[0], line[1]);
                }
                var sortedLevels  = levels.OrderByDescending(l => l.Item2).ThenBy(l => l.Item1).ToList();
                var oneStarLevels = new List <Tuple <int, int> >();
                int stars         = 0;
                int used          = 0;
                while (sortedLevels.Count > 0 || oneStarLevels.Count > 0)
                {
                    var nextLevel = oneStarLevels.Where(l => l.Item2 <= stars);
                    if (nextLevel.Any())
                    {
                        var level = nextLevel.First();
                        //Console.WriteLine("Level 2 from 1 on {0},{1} -> {2} stars", level.Item1, level.Item2, stars);
                        oneStarLevels.Remove(level);
                        stars++;
                        used++;
                        continue;
                    }
                    nextLevel = sortedLevels.Where(l => l.Item2 <= stars);
                    if (nextLevel.Any())
                    {
                        var level = nextLevel.Last();
                        //Console.WriteLine("Level 2 from 0 on {0},{1} -> {2} stars", level.Item1, level.Item2, stars);
                        sortedLevels.Remove(level);
                        stars += 2;
                        used++;
                        continue;
                    }
                    nextLevel = sortedLevels.Where(l => l.Item1 <= stars);
                    if (nextLevel.Any())
                    {
                        var level = nextLevel.First();
                        //Console.WriteLine("Level 1 from 0 on {0},{1} -> {2} stars", level.Item1, level.Item2, stars);
                        oneStarLevels.Add(level);
                        sortedLevels.Remove(level);
                        stars++;
                        used++;
                        continue;
                    }
                    else
                    {
                        used = -1;
                        break;
                    }
                }
                if (used < 0)
                {
                    Console.WriteLine("Case #{0}: Too Bad", t);
                }
                else
                {
                    Console.WriteLine("Case #{0}: {1}", t, used);
                }
            }
        }
Exemplo n.º 19
0
        private static void Main()
        {
            var img      = new Bitmap(Image.FromFile(".\\Fingerprints\\102_5.tif"));
            var imgBytes = new int[img.Size.Width, img.Size.Height];

            for (var x = 0; x < img.Size.Width; x++)
            {
                for (var y = 0; y < img.Size.Height; y++)
                {
                    var color = img.GetPixel(x, y);
                    imgBytes[x, y] = (int)(.299 * color.R + .587 * color.G + .114 * color.B);
                }
            }

            var orfield = OrientationFieldGenerator.GenerateOrientationField(imgBytes);
            //VSCOMEdetector(orfield);
            int nFilters   = 7;
            int nBands     = 3;
            int bandRadius = 24;
            int holeRadius = 14;
            int nSectors   = 9;



            var filterbank = new List <List <Tuple <int, int, double> > >();

            int[,] filtersInt = new int[32, nFilters *32];

            for (int i = 0; i < nFilters; i++)
            {
                filterbank.Add(CreateGaborFilter((1.0 / 10), Math.PI / nFilters * i));
            }

            // this code was used to test the similarity of the fingerprints
            //var min = filterbank.SelectMany(x=>x).Select(x=>x.Item3).Min();
            //var max = filterbank.SelectMany(x=>x).Select(x=>x.Item3).Max();

            //for (int i = 0; i < nFilters; i++)
            //{
            //    var filter = filterbank[i];
            //    foreach (var tuple in filter)
            //    {
            //        filtersInt[tuple.Item1, tuple.Item2 + i*32] = (int) ((tuple.Item3 - min)/(max - min)*255);
            //    }
            //}

            //Common.SaveAndShowImage(filtersInt);

            int size = nBands * nSectors * nFilters;

            int num = 60000;

            List <double>[] dbase = new List <double> [num];
            var             rand  = new Random();

            for (int w = 0; w < num; w++)
            {
                var lst = new List <double>();
                for (int s = 0; s < size; s++)
                {
                    lst.Add(rand.NextDouble() * 128.0f);
                }
                dbase[w] = lst;
            }

            using (FileStream fs = new FileStream("C:\\temp\\fusrodah_cpu_results.csv", FileMode.Create))
            {
                using (StreamWriter streamWriter = new StreamWriter(fs))
                {
                    streamWriter.WriteLine("Find;Create;Match;Top");
                    for (int n = 0; n < 20; n++)
                    {
                        int radius = nBands * bandRadius + holeRadius + 16; //mask size

                        var sw = new Stopwatch();
                        sw.Start();
                        PerformNewDetectionAlgorithmTestfire(imgBytes);
                        streamWriter.Write(sw.ElapsedMilliseconds + ";");
                        sw.Stop();


                        sw.Restart();
                        var normalizedImage =
                            NormalizeImage(imgBytes, nBands, holeRadius, bandRadius,
                                           265, 292);
                        //Common.SaveAndShowImage(normalizedImage);
                        var filteredImages = new List <int[, ]>();
                        for (int i = 0; i < nFilters; i++)
                        {
                            filteredImages.Add(null);
                        }
                        Parallel.ForEach(filterbank, new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = 4
                        },
                                         filter =>
                        {
                            var filtered = FilterWithGaborFilter(normalizedImage,
                                                                 filter, nBands, holeRadius,
                                                                 bandRadius,
                                                                 265, 292);
                            //Common.SaveAndShowImage(filtered);
                            filteredImages[filterbank.IndexOf(filter)] = filtered;
                        }

                                         );
                        var fingercode = new List <double>();
                        for (int i = 0; i < nFilters * nBands * nSectors; i++)
                        {
                            fingercode.Add(0);
                        }
                        Parallel.ForEach(filteredImages,
                                         new ParallelOptions {
                            MaxDegreeOfParallelism = 4
                        },
                                         filteredImgBytes =>
                        {
                            var fingercodePart = FormFingerCode(filteredImgBytes, nSectors, nBands,
                                                                holeRadius,
                                                                bandRadius);
                            int startIndex = filteredImages.IndexOf(filteredImgBytes) *
                                             nBands * nSectors;
                            foreach (var d in fingercodePart)
                            {
                                fingercode[startIndex++] = d;
                            }
                        });
                        sw.Stop();
                        streamWriter.Write(sw.ElapsedMilliseconds + ";");
                        //Common.SaveFingerCode(fingercode, nBands, nSectors, nFilters, bandRadius, holeRadius);
                        sw.Restart();
                        Tuple <int, double>[] result = new Tuple <int, double> [num];

                        Parallel.ForEach(new[] { 0, 1, 2, 3 }, new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = 4
                        },
                                         (offset) =>
                        {
                            for (int i = 0; i < num / 4; i++)
                            {
                                var index     = i * 4 + offset;
                                result[index] = Tuple.Create(index,
                                                             CalculateDistance(fingercode,
                                                                               dbase[index]));
                            }
                        });
                        sw.Stop();
                        streamWriter.Write(sw.ElapsedMilliseconds + ";");
                        sw.Restart();
                        result = result.OrderByDescending(x => x.Item2).ToArray();
                        sw.Stop();
                        streamWriter.WriteLine(sw.ElapsedMilliseconds);
                    }
                }
            }
        }
Exemplo n.º 20
0
 public static string sanitizeVars(this string inputCode)
 {
     replacementVars = memory.getVariableNames().Select((m, i) => new Tuple<string, string>(m, createHash(i))).ToArray();
     replacementVars = replacementVars.OrderByDescending(n => n.Item1.Length).ToArray();
     for (int i = 0; i < replacementVars.Length; i++)
     {
         inputCode = inputCode.Replace(replacementVars[i].Item1, "(" + replacementVars[i].Item2 + ")");
     }
     Array.Reverse(replacementVars);
     return inputCode;
 }
Exemplo n.º 21
0
        /// <summary>
        /// This is meant to be a generic prune method.  It returns the top weights, and normalizes them so the sum of the smaller
        /// set is the same as the sum of the larger set
        /// </summary>
        private static Tuple<int, double>[] Prune(double[] weights, int count)
        {
            // Convert the weights into a list with the original index
            Tuple<int, double>[] weightsIndexed = new Tuple<int, double>[weights.Length];
            for (int cntr = 0; cntr < weights.Length; cntr++)
            {
                weightsIndexed[cntr] = new Tuple<int, double>(cntr, weights[cntr]);
            }

            if (count > weights.Length)
            {
                // This method shouldn't have been called, there is nothing to do
                return weightsIndexed;
            }

            Tuple<int, double>[] topWeights = weightsIndexed.OrderByDescending(o => Math.Abs(o.Item2)).Take(count).ToArray();

            double sumWeights = weights.Sum(o => Math.Abs(o));
            double sumTop = topWeights.Sum(o => Math.Abs(o.Item2));

            double ratio = sumWeights / sumTop;
            if (double.IsNaN(ratio))
            {
                ratio = 1d;		// probably divide by zero
            }

            // Normalize the top weights
            return topWeights.Select(o => new Tuple<int, double>(o.Item1, o.Item2 * ratio)).ToArray();
        }
Exemplo n.º 22
0
        private static Tuple<Point3D, Point3D, double>[] Prune_Pre(Tuple<Point3D, Point3D, double>[] existing, int count)
        {
            // Sort it so the smaller links have a higher chance of being removed
            var retVal = existing.
                OrderByDescending(o => Math.Abs(o.Item3)).      // the weights could be negative, so sort on distance from zero
                ToList();

            Random rand = StaticRandom.GetRandomForThread();

            while (retVal.Count > count)
            {
                // Choose a random item to remove - favor the end of the list (where the smallest links are)
                double percent = rand.NextPow(10);
                int index = UtilityCore.GetIndexIntoList(percent, retVal.Count);

                retVal.RemoveAt(index);
            }

            return retVal.ToArray();
        }