예제 #1
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="_startMatrix">Symmetric distance matrix</param>
        /// <param name="_labels">Dictionary with labels of the distance matrix</param>
        public NeighborJoining(decimal[,] _startMatrix, Dictionary <int, string> _labels)
        {
            //Check for symmetrical distances
            if (_startMatrix.GetLength(0) != _startMatrix.GetLength(1))
            {
                throw new Exception("Matrix needs to be symmetric!");
            }

            //Check for existing labels
            //Check for unique labels
            List <string> lstLabels = new List <string>();

            for (int count = 0; count < _labels.Count; count++)
            {
                string strLabel;
                if (_labels.TryGetValue(count, out strLabel))
                {
                    // Check for unique
                    if (lstLabels.Contains(strLabel))
                    {
                        throw new Exception($"Label {strLabel} is not unique!");
                    }
                    else
                    {
                        lstLabels.Add(strLabel);
                    }
                }
                else
                {
                    throw new Exception($"Label for index {count} is missing!");
                }
            }

            //Set properties
            StartMatrix = _startMatrix;
            StartLabels = _labels;

            NodesAndEdges = new List <Tuple <string, decimal, string> >();

            // Set node levels to 0
            Dictionary <int, int> initNodeLevels = new Dictionary <int, int>();

            foreach (int nodeIndex in StartLabels.Keys)
            {
                initNodeLevels.Add(nodeIndex, level);
            }

            //Create leaf nodes for every label
            Nodes = new List <BifiTree>();

            foreach (string node in StartLabels.Values)
            {
                Nodes.Add(new BifiTree(node));
            }

            //Init neighbor joining with start matrix
            NeighborJoiningController(StartMatrix, StartLabels, initNodeLevels);
        }
예제 #2
0
 /// <summary>
 /// 向量对角化
 /// </summary>
 /// <param name="vec">向量</param>
 /// <returns>返回对角化矩阵</returns>
 public static decimal[,] VecDiag(this decimal[,] vec)
 {
     decimal[,] diagMatrix = new decimal[vec.GetLength(0), vec.GetLength(0)];
     for (int i = 0, len = vec.GetLength(0); i < len; i++)
     {
         diagMatrix[i, i] = vec[i, 0];
     }
     return(diagMatrix);
 }
예제 #3
0
        public void TestUpgma()
        {
            //decimal[,] distanceMatrix1 =
            //{
            //    { 0, 0, 0, 0, 0 },
            //    { 0, 0, 1, 1, 1 },
            //    { 0, 1, 0, 2, 2 },
            //    { 0, 1, 2, 0, 3 },
            //    { 0, 1, 2, 3, 0 },
            //};

            //var result = UpgmaClustering.Upgma(distanceMatrix1);

            decimal[,] distanceMatrix2 =
            {
                {  0, 19, 27,  8, 33, 18, 13 },
                { 19,  0, 31, 18, 36,  1, 13 },
                { 27, 31,  0, 26, 41, 32, 29 },
                {  8, 18, 26,  0, 31, 17, 14 },
                { 33, 36, 41, 31,  0, 35, 28 },
                { 18,  1, 32, 17, 35,  0, 12 },
                { 13, 13, 29, 14, 28, 12,  0 }
            };

            var names = new List <string>();

            for (var i = 0; i < distanceMatrix2.GetLength(0); i++)
            {
                names.Add("" + i);
            }


            List <string> vectorNames     = new List <string>();
            var           maxVectorLength = distanceMatrix2.GetLength(0) > distanceMatrix2.GetLength(1) ? distanceMatrix2.GetLength(0) : distanceMatrix2.GetLength(1);

            for (var i = 0; i < maxVectorLength; i++)
            {
                vectorNames.Add(SpreadsheetFileHandler.AlphabetLetterRollOver(i) + i);
            }

            List <List <UpgmaNode> > nodeList;
            List <List <string> >    treeList;

            var minimumOutputTreeLeafs = 1;

            List <string> finalTreeLeafOrderList;

            UpgmaClustering.Upgma(distanceMatrix2, vectorNames, minimumOutputTreeLeafs, out nodeList, out treeList, out finalTreeLeafOrderList);

            CheckUpgmaDistanceConsistency(nodeList[nodeList.Count - 1]);

            List <string> treeLeafOrderList;
            var           tree = Newick.NewickTreeFormat(nodeList[nodeList.Count - 1].ToList <GenericNode>(), names, out treeLeafOrderList, minimumOutputTreeLeafs);

            Console.WriteLine(tree);
        }
예제 #4
0
        /// <summary>Constructs a QR decomposition.</summary>    
        /// <param name="value">The matrix A to be decomposed.</param>
        /// <param name="transpose">True if the decomposition should be performed on
        /// the transpose of A rather than A itself, false otherwise. Default is false.</param>
        public QrDecompositionD(decimal[,] value, bool transpose)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Matrix cannot be null.");
            }

            if ((!transpose && value.GetLength(0) < value.GetLength(1)) ||
                 (transpose && value.GetLength(1) < value.GetLength(0)))
            {
                throw new ArgumentException("Matrix has more columns than rows.", "value");
            }

            this.qr = transpose ? value.Transpose() : (decimal[,])value.Clone();

            int rows = qr.GetLength(0);
            int cols = qr.GetLength(1);
            this.Rdiag = new decimal[cols];

            for (int k = 0; k < cols; k++)
            {
                // Compute 2-norm of k-th column without under/overflow.
                decimal nrm = 0;
                for (int i = k; i < rows; i++)
                    nrm = Tools.Hypotenuse(nrm, qr[i, k]);

                if (nrm != 0)
                {
                    // Form k-th Householder vector.
                    if (qr[k, k] < 0)
                        nrm = -nrm;

                    for (int i = k; i < rows; i++)
                        qr[i, k] /= nrm;

                    qr[k, k] += 1;

                    // Apply transformation to remaining columns.
                    for (int j = k + 1; j < cols; j++)
                    {
                        decimal s = 0;

                        for (int i = k; i < rows; i++)
                            s += qr[i, k] * qr[i, j];

                        s = -s / qr[k, k];

                        for (int i = k; i < rows; i++)
                            qr[i, j] += s * qr[i, k];
                    }
                }

                this.Rdiag[k] = -nrm;
            }
        }
예제 #5
0
        /// <summary>
        ///   Solves a set of equation systems of type <c>A * X = B</c>.
        /// </summary>
        /// <param name="value">Right hand side matrix with as many rows as <c>A</c> and any number of columns.</param>
        /// <returns>Matrix <c>X</c> so that <c>L * U * X = B</c>.</returns>
        ///
        public decimal[,] Solve(decimal[,] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (value.GetLength(0) != rows)
            {
                throw new DimensionMismatchException("value", "The matrix should have the same number of rows as the decomposition.");
            }

            if (!Nonsingular)
            {
                throw new InvalidOperationException("Matrix is singular.");
            }


            // Copy right hand side with pivoting
            int count = value.GetLength(1);

            decimal[,] X = value.Submatrix(pivotVector, null);


            // Solve L*Y = B(piv,:)
            for (int k = 0; k < cols; k++)
            {
                for (int i = k + 1; i < cols; i++)
                {
                    for (int j = 0; j < count; j++)
                    {
                        X[i, j] -= X[k, j] * lu[i, k];
                    }
                }
            }

            // Solve U*X = Y;
            for (int k = cols - 1; k >= 0; k--)
            {
                for (int j = 0; j < count; j++)
                {
                    X[k, j] /= lu[k, k];
                }

                for (int i = 0; i < k; i++)
                {
                    for (int j = 0; j < count; j++)
                    {
                        X[i, j] -= X[k, j] * lu[i, k];
                    }
                }
            }

            return(X);
        }
예제 #6
0
 static void Output(decimal[,] matrix)
 {
     for (int i = 0; i < matrix.GetLength(0); i++)
     {
         for (int j = 0; j < matrix.GetLength(1); j++)
         {
             Console.Write(matrix[i, j] + " ");
         }
         Console.WriteLine();
     }
 }
예제 #7
0
 /// <summary>
 /// prints a matrix to console output
 /// </summary>
 /// <param name="matrix">matrix to be printed</param>
 /// <param name="round">number of decimal points to round answers, default 2</param>
 public static void PrintMatrix(decimal[,] matrix, int round = 2)
 {
     for (int i = 0; i < matrix.GetLength(0); i++)
     {
         for (int j = 0; j < matrix.GetLength(1); j++)
         {
             Console.Write(decimal.Round(matrix[i, j], round) + "\t");
         }
         Console.WriteLine();
     }
 }
예제 #8
0
        public static decimal[,] Get(decimal[,] resultArray, int cellsPerUnitSquare, GameComponents.RNG rng, decimal persistence = 1m)
        {
            int width        = resultArray.GetLength(0);
            int height       = resultArray.GetLength(1);
            int vectorWidth  = (width / cellsPerUnitSquare) + 2;            // make sure we have at least enough vectors for all 4 corners
            int vectorHeight = (height / cellsPerUnitSquare) + 2;

            Point[,] vectors = new Point[vectorWidth, vectorHeight];
            for (int vx = 0; vx < vectorWidth; ++vx)
            {
                for (int vy = 0; vy < vectorHeight; ++vy)
                {
                    int px = rng.GetNext(201) - 100;                     // store vectors as hundredths, positive or negative
                    int py = rng.GetNext(201) - 100;
                    vectors[vx, vy] = new Point(px, py);
                }
            }
            decimal distBetweenMidpoints = 1m / (decimal)cellsPerUnitSquare;

            for (int x = 0; x < width; ++x)
            {
                for (int y = 0; y < height; ++y)
                {
                    // first find gradient vectors:
                    int sourceX = x / cellsPerUnitSquare;
                    int sourceY = y / cellsPerUnitSquare;
                    // also find where this x,y is within the containing square:
                    int     xInCell       = x % cellsPerUnitSquare;
                    int     yInCell       = y % cellsPerUnitSquare;
                    decimal xVector0      = (distBetweenMidpoints * 0.5m) + xInCell * distBetweenMidpoints;
                    decimal yVector0      = (distBetweenMidpoints * 0.5m) + yInCell * distBetweenMidpoints;
                    decimal xVector1      = 1m - xVector0;
                    decimal yVector1      = 1m - yVector0;
                    decimal xGradientx0y0 = vectors[sourceX, sourceY].X / 100m;
                    decimal xGradientx1y0 = vectors[sourceX + 1, sourceY].X / 100m;
                    decimal xGradientx0y1 = vectors[sourceX, sourceY + 1].X / 100m;
                    decimal xGradientx1y1 = vectors[sourceX + 1, sourceY + 1].X / 100m;
                    decimal yGradientx0y0 = vectors[sourceX, sourceY].Y / 100m;
                    decimal yGradientx1y0 = vectors[sourceX + 1, sourceY].Y / 100m;
                    decimal yGradientx0y1 = vectors[sourceX, sourceY + 1].Y / 100m;
                    decimal yGradientx1y1 = vectors[sourceX + 1, sourceY + 1].Y / 100m;
                    decimal x0y0Dot       = xGradientx0y0 * xVector0 + yGradientx0y0 * yVector0;
                    decimal x1y0Dot       = xGradientx1y0 * xVector1 + yGradientx1y0 * yVector0;
                    decimal x0y1Dot       = xGradientx0y1 * xVector0 + yGradientx0y1 * yVector1;
                    decimal x1y1Dot       = xGradientx1y1 * xVector1 + yGradientx1y1 * yVector1;
                    decimal lerpX0        = Lerp(x0y0Dot, x1y0Dot, xVector0);
                    decimal lerpX1        = Lerp(x0y1Dot, x1y1Dot, xVector0);
                    decimal lerpFinal     = Lerp(lerpX0, lerpX1, yVector0);
                    resultArray[x, y] += lerpFinal * 256m * persistence;
                }
            }

            return(resultArray);
        }
예제 #9
0
 public static void PrintMatrix(decimal[,] matrix)
 {
     for (int i = 0; i < matrix.GetLength(0); i++)
     {
         for (int j = 0; j < matrix.GetLength(1); j++)
         {
             Console.Write(" " + matrix[i, j] + " ");
         }
         Console.WriteLine();
     }
 }
예제 #10
0
        public decimal[,] Resta(decimal[,] m)
        {
            if (matriz.GetLength(0) != m.GetLength(0) || matriz.GetLength(1) != m.GetLength(1))
            {
                throw new Exception("Las matrices son impoisibles de restar");
            }

            Matrix matriz1 = new Matrix(m);

            return(Suma(matriz1.EscalarMult(-1)));
        }
 private static void PrintArr(decimal[,] array)
 {
     for (int i = 0; i < array.GetLength(0); i++)
     {
         for (int j = 0; j < array.GetLength(1); j++)
         {
             Console.Write(string.Format("{0}", array[i, j]).PadRight(5));
         }
         Console.WriteLine();
     }
 }
예제 #12
0
 public static void DisplayDeterminant(decimal[,] Matrix)
 {
     for (int i = 0; i < Matrix.GetLength(0); i++)
     {
         for (int j = 0; j < Matrix.GetLength(1); j++)
         {
             Console.Write(" " + Matrix[i, j]);
         }
         Console.WriteLine();
     }
 }
 public static void Print_Matrix(decimal[,] array)
 {
     for (int i = 0; i < array.GetLength(0); ++i)
     {
         for (int j = 0; j < array.GetLength(1); ++j)
         {
             Console.Write(array[i, j] + " ");
         }
         Console.WriteLine();
     }
 }
예제 #14
0
 private static void PrintMatrix(decimal[,] matrix)
 {
     for (int row = 0; row < matrix.GetLength(0); row++)
     {
         for (int col = 0; col < matrix.GetLength(1); col++)
         {
             Console.Write(matrix[row, col] + " ");
         }
         Console.WriteLine();
     }
 }
        public static double[] DoTheAnalysis(double sigma, double bottomThresholdCanny, double upperThresholdCanny,
                                             int waveletLength, double bottomThresholdHaar, double upperThresholdHaar, int widthOfBrightnessDiffer, double snr = -1)
        {
            decimal[,] origImage            = MakeOriginImArr(widthOfBrightnessDiffer);
            decimal[,] origImageCopyForHaar = MakeOriginImArr(widthOfBrightnessDiffer);

            double[,] perfectEdgeImage = MakePerfectEdgeImArr();

            Bitmap bmpToSaveForTest = new Bitmap(origImage.GetLength(1), origImage.GetLength(0));

            for (int i = 0; i < origImage.GetLength(0); i++)
            {
                for (int j = 0; j < origImage.GetLength(1); j++)
                {
                    bmpToSaveForTest.SetPixel(j, i, Color.FromArgb((int)Math.Ceiling(origImage[i, j]), (int)Math.Ceiling(origImage[i, j]), (int)Math.Ceiling(origImage[i, j])));
                }
            }

            if (snr > -1)
            {
                origImage            = AddGausNoise(origImage, snr);// зашумляем изображение
                origImageCopyForHaar = AddGausNoise(origImageCopyForHaar, snr);
            }

            CannyForm = new CannyForm(sigma, bottomThresholdCanny, upperThresholdCanny, bmp: null, imageArray: origImage); //создаем окно для вывода результатов метода Канни, передавая путь к выбранному файлу

            double[,] cannyResult = new double[CannyForm.cannyResult.Height, CannyForm.cannyResult.Width];
            for (int i = 0; i < cannyResult.GetLength(0); i++)
            {
                for (int j = 0; j < cannyResult.GetLength(1); j++)
                {
                    cannyResult[i, j] = CannyForm.cannyResult.GetPixel(j, i).R;
                }
            }
            HaarForm = new HaarForm(waveletLength, bottomThresholdHaar, upperThresholdHaar, bmp: null, imageArray: origImageCopyForHaar); //создаем окно для вывода результатов метода Хаара, передавая путь к выбранному файлу

            double[,] haarResult = new double[HaarForm.resultBmp.Height, HaarForm.resultBmp.Width];
            for (int i = 0; i < haarResult.GetLength(0); i++)
            {
                for (int j = 0; j < haarResult.GetLength(1); j++)
                {
                    haarResult[i, j] = HaarForm.resultBmp.GetPixel(j, i).R;
                }
            }

            double cannyPrettCrit = CountPrettCriteriaWithoutBorderPixels(perfectEdgeImage, cannyResult, waveletLength);
            double haarPrettCrit  = CountPrettCriteriaWithoutBorderPixels(perfectEdgeImage, haarResult, waveletLength);

            double[] prettCrit = new double[2];
            prettCrit[0] = cannyPrettCrit;
            prettCrit[1] = haarPrettCrit;

            return(prettCrit);
        }
예제 #16
0
        public static void ImprimirMatriz(decimal[,] matriz)
        {
            for (int i = 0; i < matriz.GetLength(0); i++)
            {
                for (int j = 0; j < matriz.GetLength(1); j++)
                {
                    Console.Write(matriz[i, j] + "\t");
                }

                Console.WriteLine();
            }
        }
예제 #17
0
 Point[,] getPoints(double[] x, decimal[,] y) // WORKING
 {
     Point[,] p = new Point[y.GetLength(0), y.GetLength(1)];
     for (int i = 0; i < y.GetLength(0); ++i) // dla kazdej funkcji
     {
         for (int j = 0; j < x.Length; ++j)   // dla kazdego x
         {
             p[i, j] = conv(x[j], y[i, j]);
         }
     }
     return(p);
 }
예제 #18
0
 /// <summary>
 /// 对矩阵的激活函数
 /// </summary>
 /// <param name="martix"></param>
 /// <returns></returns>
 public decimal[,] Active(decimal[,] martix)
 {
     decimal[,] ret = new decimal[martix.GetLength(0), martix.GetLength(1)];
     for (int i = 0, len_i = martix.GetLength(0); i < len_i; i++)
     {
         for (int j = 0, len_j = martix.GetLength(1); j < len_j; j++)
         {
             ret[i, j] = Active(martix[i, j]);
         }
     }
     return(ret);
 }
예제 #19
0
 /// <summary>
 /// 矩阵向量化
 /// </summary>
 /// <param name="matrix">传入需要向量化的矩阵</param>
 /// <returns>返回向量</returns>
 public static decimal[,] MatrixVec(this decimal[,] matrix)
 {
     decimal[,] ret = new decimal[matrix.GetLength(0) * matrix.GetLength(1), 1];
     for (int i = 0, len_i = matrix.GetLength(1); i < len_i; i++)
     {
         for (int j = 0, len_j = matrix.GetLength(0); j < len_j; j++)
         {
             ret[i * len_j + j, 0] = matrix[j, i];
         }
     }
     return(ret);
 }
예제 #20
0
 /// <summary>
 /// 矩阵减矩阵
 /// </summary>
 /// <param name="Matrix1"></param>
 /// <param name="Matrix2"></param>
 /// <returns></returns>
 public static decimal[,] MatrixReduceMatrix(this decimal[,] Matrix1, decimal[,] Matrix2)
 {
     decimal[,] Ret = new decimal[Matrix1.GetLength(0), Matrix1.GetLength(1)];
     for (int i = 0, len_i = Matrix1.GetLength(0); i < len_i; i++)
     {
         for (int j = 0, len_j = Matrix1.GetLength(1); j < len_j; j++)
         {
             Ret[i, j] = Matrix1[i, j] - Matrix2[i, j];
         }
     }
     return(Ret);
 }
예제 #21
0
        /// <summary>
        /// Constructs a new matrix with height and width of <paramref name="size"/>.
        /// </summary>
        /// <param name="size">Size of matrix.</param>
        /// <param name="values">Values to use to initialize the matrix. These values are not used
        /// directly, but are rather copied. Addressed as [row, column].</param>
        protected TransformationMatrixBase(int size, decimal[,] values)
        {
            Size = size;

            if (values.GetLength(0) != size || values.GetLength(1) != size)
            {
                throw new ArgumentException("Matrix initialization values are not of the correct size!", "values");
            }

            M = new decimal[size, size];
            Array.Copy(values, M, values.Length);
        }
예제 #22
0
 decimal[,] Transpuesta(decimal[,] m)
 {
     decimal[,] result = new decimal[m.GetLength(0), m.GetLength(1)];
     for (int i = 0; i < result.GetLength(0); i++)
     {
         for (int j = 0; j < result.GetLength(1); j++)
         {
             result[i, j] = m[j, i];
         }
     }
     return(result);
 }
예제 #23
0
        /*public static void OutputUpgmaLog(string outputFilename, List<UpgmaNode> nodeList, List<decimal[,]> distanceMatrixCache, List<List<List<int>>> distanceMatrixMapCache)
         * {
         *  var sb = new StringBuilder();
         *
         *  for (int index = 0; index < nodeList.Count; index++)
         *  {
         *      var node = nodeList[index];
         *
         *      var nodeId = string.Join("_", node.VectorIndexes);
         *      var childNodeId = node.ChildNode != null ? string.Join("_", node.ChildNode.VectorIndexes) : "null";
         *      var parentNodeIdA = node.ParentNodeA != null ? string.Join("_", node.ParentNodeA.VectorIndexes) : "null";
         *      var parentNodeIdB = node.ParentNodeB != null ? string.Join("_", node.ParentNodeB.VectorIndexes) : "null";
         *
         *      sb.AppendLine("Node #" + index + ": " + nodeId);
         *      sb.AppendLine("Is leaf node: " + node.IsLeafNode());
         *      sb.AppendLine("Is root node: " + node.IsRootNode());
         *      sb.AppendLine("Is branch node: " + node.IsBranchNode());
         *      sb.AppendLine("Is unclustered node: " + node.IsNodeUnclustered());
         *      sb.AppendLine("Loop iteration: " + node.DistanceMatrixIterationNumber);
         *      sb.AppendLine("Child node: " + childNodeId + ". Distance: " + node.DistanceChildNode);
         *      sb.AppendLine("Parent node 1: " + parentNodeIdA + ". Distance: " + node.DistanceParentNodeA);
         *      sb.AppendLine("Parent node 2: " + parentNodeIdB + ". Distance: " + node.DistanceParentNodeB);
         *      sb.AppendLine();
         *  }
         *
         *  for (int index = 0; index < distanceMatrixCache.Count; index++)
         *  {
         *      var distanceMatrix = distanceMatrixCache[index];
         *
         *      var distanceMatrixMap = distanceMatrixMapCache[index];
         *
         *      sb.AppendLine("Distance Matrix Iteration #" + index + ". " + distanceMatrix.GetLength(0) + " x " + distanceMatrix.GetLength(1) + " matrix:");
         *
         *
         *      sb.AppendLine();
         *
         *      for (var matrixIndex = 0; matrixIndex < distanceMatrixMap.Count; matrixIndex++)
         *      {
         *          var matrixIndexIdList = distanceMatrixMap[matrixIndex];
         *
         *          sb.AppendLine("Matrix index #" + matrixIndex + ": " + string.Join(", ", matrixIndexIdList));
         *      }
         *
         *      sb.AppendLine();
         *
         *      var width = distanceMatrix.Cast<decimal>().Select(a => a.ToString().Length).Max() + 1;
         *
         *      if (distanceMatrix.GetLength(0).ToString().Length + 1 > width) width = distanceMatrix.GetLength(0).ToString().Length + 1;
         *      if (distanceMatrix.GetLength(1).ToString().Length + 1 > width) width = distanceMatrix.GetLength(1).ToString().Length + 1;
         *
         *      sb.Append("".PadLeft(width));
         *      for (var x = 0; x < distanceMatrix.GetLength(0); x++)
         *      {
         *          sb.Append(x.ToString().PadLeft(width));
         *      }
         *
         *      sb.AppendLine();
         *
         *      for (var y = 0; y < distanceMatrix.GetLength(1); y++)
         *      {
         *          sb.Append(y.ToString().PadLeft(width));
         *
         *          for (var x = 0; x < distanceMatrix.GetLength(0); x++)
         *          {
         *              string s = distanceMatrix[x, y].ToString().PadLeft(width);
         *              sb.Append(s);
         *          }
         *
         *          sb.AppendLine();
         *      }
         *
         *      sb.AppendLine();
         *  }
         *
         *  File.WriteAllText(outputFilename, sb.ToString());
         * }*/

        /*public static void CacheUpgmaMatrixes(decimal[,] distanceMatrix, List<decimal[,]> distanceMatrixCache, List<List<int>> distanceMatrixMap, List<List<List<int>>> distanceMatrixMapCache)
         * {
         *  // Copy distance matrix
         *  var distanceMatrixCacheCopy = new decimal[distanceMatrix.GetLength(0), distanceMatrix.GetLength(1)];
         *  Array.Copy(distanceMatrix, distanceMatrixCacheCopy, distanceMatrix.Length);
         *
         *  // Cache distance matrix
         *  distanceMatrixCache.Add(distanceMatrixCacheCopy);
         *
         *
         *  // Copy matrix map
         *  var distanceMatrixMapCacheCopy = new List<List<int>>();
         *  for (var i = 0; i < distanceMatrixMap.Count; i++)
         *  {
         *      distanceMatrixMapCacheCopy.Add(new List<int>());
         *      distanceMatrixMapCacheCopy[i].AddRange(distanceMatrixMap[i].Select(a => a).ToList());
         *  }
         *
         *  // Cache matrix map
         *  distanceMatrixMapCache.Add(distanceMatrixMapCacheCopy);
         * }*/

        public static void Upgma(decimal[,] distanceMatrix, List <string> vectorNames, int minimumOutputTreeLeafs,
                                 out List <List <UpgmaNode> > nodeListList, out List <List <string> > treeListList,
                                 out List <string> finalTreeLeafOrderList, bool newickTreeEveryIteration = false,
                                 ProgressActionSet progressActionSet = null)
        {
            if (distanceMatrix == null || distanceMatrix.GetLength(0) == 0 || distanceMatrix.GetLength(1) == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(distanceMatrix), "distance matrix is null or empty");
            }

            Upgma(ConvertTypes.Decimal2DArrayToDecimalListList(distanceMatrix), vectorNames, minimumOutputTreeLeafs, out nodeListList, out treeListList, out finalTreeLeafOrderList, newickTreeEveryIteration, progressActionSet);
        }
예제 #24
0
 public static decimal[,] RemoveLast(decimal[,] array)
 {
     decimal[,] newArray = new decimal[array.GetLength(0) - 1, array.GetLength(1)];
     for (int i = 0; i < array.GetLength(0) - 1; i++)
     {
         for (int x = 0; x < array.GetLength(1); x++)
         {
             newArray[i, x] = array[i, x];
         }
     }
     return(newArray);
 }
예제 #25
0
 public static decimal[,] AddOneLength(decimal[,] array)
 {
     decimal[,] newArray = new decimal[array.GetLength(0) + 1, array.GetLength(1)];
     for (int i = 0; i < array.GetLength(0); i++)
     {
         for (int x = 0; x < array.GetLength(1); x++)
         {
             newArray[i, x] = array[i, x];
         }
     }
     return(newArray);
 }
예제 #26
0
        public static decimal[,] MultiplyAndAdd(this decimal[,] a, decimal b, decimal[,] c, decimal[,] result)
        {
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                {
                    result[i, j] = (decimal)((decimal)(a[i, j]) * b + (decimal)(c[i, j]));
                }
            }

            return(result);
        }
예제 #27
0
 /// <summary>
 /// 矩阵转置
 /// </summary>
 /// <param name="Matrix"></param>
 /// <returns></returns>
 public static decimal[,] Turn(this decimal[,] matrix)
 {
     decimal[,] ret = new decimal[matrix.GetLength(1), matrix.GetLength(0)];
     for (int i = 0, len_i = matrix.GetLength(1); i < len_i; i++)
     {
         for (int j = 0, len_j = matrix.GetLength(0); j < len_j; j++)
         {
             ret[i, j] = matrix[j, i];
         }
     }
     return(ret);
 }
예제 #28
0
 private decimal[,] Expand(decimal[,] array, int size1, int size2)
 {
     decimal[,] newArray = new decimal[size1, size2];
     for (int i = array.GetLength(0) - 1; i >= 0; --i)
     {
         for (int j = array.GetLength(1) - 1; j >= 0; --j)
         {
             newArray[i, j] = array[i, j];
         }
     }
     return(newArray);
 }
예제 #29
0
 /// <summary>
 /// 矩阵乘标量
 /// </summary>
 /// <param name="Matrix"></param>
 /// <param name="Scalar"></param>
 /// <returns></returns>
 public static decimal[,] MatrixMultiScalar(this decimal[,] Matrix, decimal Scalar)
 {
     decimal[,] Ret = new decimal[Matrix.GetLength(0), Matrix.GetLength(1)];
     for (int i = 0, len_i = Matrix.GetLength(0); i < len_i; i++)
     {
         for (int j = 0, len_j = Matrix.GetLength(1); j < len_j; j++)
         {
             Ret[i, j] = Matrix[i, j] * Scalar;
         }
     }
     return(Ret);
 }
예제 #30
0
        public CannyForm(double sigma, double bottomThreshold, double upperThreshold, Bitmap bmp = null, decimal[,] imageArray = null)// перегружаем метод, чтобы принять на вход изображение, а не ссылку на него
        {
            InitializeComponent();
            this.bmp             = bmp;
            this.sigma           = sigma;
            this.bottomThreshold = bottomThreshold;
            this.upperThreshold  = upperThreshold;
            if (imageArray != null)
            {
                Bitmap bmp1 = new Bitmap(imageArray.GetLength(1), imageArray.GetLength(0));
                for (int i = 0; i < imageArray.GetLength(0); i++)
                {
                    for (int j = 0; j < imageArray.GetLength(1); j++)
                    {
                        bmp1.SetPixel(j, i, Color.FromArgb((int)imageArray[i, j], (int)imageArray[i, j], (int)imageArray[i, j]));
                    }
                }
                pictureBox1.Image = bmp1;

                decimal[,] imageArrayNew = CannyStandardVersion.GradUsingFirstDerOfGaus(imageArray, sigma);

                Bitmap bmp2 = new Bitmap(imageArrayNew.GetLength(1), imageArrayNew.GetLength(0));
                for (int i = 0; i < imageArrayNew.GetLength(0); i++)
                {
                    for (int j = 0; j < imageArrayNew.GetLength(1); j++)
                    {
                        bmp2.SetPixel(j, i, Color.FromArgb((int)imageArrayNew[i, j], (int)imageArrayNew[i, j], (int)imageArrayNew[i, j]));
                    }
                }
                pictureBox2.Image = bmp2;

                Bitmap bmpFromImageArrayNew = CannyStandardVersion.Non_Maximum_Suppression(bmp = null, imageArrayNew);
                pictureBox4.Image = CannyStandardVersion.Double_Threshold(bmpFromImageArrayNew, bottomThreshold, upperThreshold);
                Bitmap c = new Bitmap(bmpFromImageArrayNew);
                cannyResult       = CannyStandardVersion.Hysteresis_Thresholding(c, "Canny");
                pictureBox3.Image = cannyResult;
            }
            else
            {
                pictureBox1.Image = bmp;

                Bitmap a = new Bitmap(pictureBox1.Image);
                CannyStandardVersion.GrayScale(a);
                CannyStandardVersion.GradUsingFirstDerOfGaus(a, sigma);
                pictureBox2.Image = a;
                Bitmap b = new Bitmap(a);
                CannyStandardVersion.Non_Maximum_Suppression(b);
                pictureBox4.Image = CannyStandardVersion.Double_Threshold(b, bottomThreshold, upperThreshold);
                Bitmap c = new Bitmap(b);
                pictureBox3.Image = CannyStandardVersion.Hysteresis_Thresholding(c, "Canny");
            }
        }
예제 #31
0
        static decimal SecondaryDiagonalMinValue(decimal[,] array)
        {
            decimal minValue = decimal.MaxValue;

            for (int i = 0; i < array.GetLength(0); i++)
            {
                if (minValue > array[array.GetLength(0) - i - 1, i])
                {
                    minValue = array[array.GetLength(0) - i - 1, i];
                }
            }
            return(minValue);
        }