Пример #1
0
        public static Double[,] Pow(this Double[,] a, Double[,] b)
        {
            if (a.Fits(b))
            {
                var rows   = a.GetRows();
                var cols   = a.GetColumns();
                var result = new Double[rows, cols];

                for (var i = 0; i < rows; i++)
                {
                    for (var j = 0; j < cols; j++)
                    {
                        result[i, j] = Math.Pow(a[i, j], b[i, j]);
                    }
                }

                return(result);
            }

            return(null);
        }
Пример #2
0
 }//end ApplyCovarianceFunction
 private Double GetKrigedGageCorrelations(Double[,] I, Double[,] D, List<double> correlations)
 {
     double[,] weights = null;
     double val = 0;
     try
     {
         weights = GetVarianceWeights(I, D);
         //weights have an n+1 due to the added LagrangeParameter
         if (weights.GetLength(0) - 1 != correlations.Count) throw new Exception("weights-1 != indexGages count");
         
         for (int i = 0; i < correlations.Count; i++)
         {
             val = val + weights[i, 0] * correlations[i];
         }//next i
         return val;
     }
     catch (Exception)
     {
         return  double.NaN;
     }//end try
 }//end getKrigedGageValue
Пример #3
0
        public static Double[,] And(this Double[,] a, Double[,] b)
        {
            if (a.Fits(b))
            {
                var rows   = a.GetRows();
                var cols   = a.GetColumns();
                var result = new Double[rows, cols];

                for (var i = 0; i < rows; i++)
                {
                    for (var j = 0; j < cols; j++)
                    {
                        result[i, j] = (a[i, j].ToBoolean() && b[i, j].ToBoolean()).ToNumber();
                    }
                }

                return(result);
            }

            return(null);
        }
Пример #4
0
        public static Double[,] IsGreaterOrEqual(this Double[,] a, Double[,] b)
        {
            if (a.Fits(b))
            {
                var rows   = a.GetRows();
                var cols   = a.GetColumns();
                var result = new Double[rows, cols];

                for (var i = 0; i < rows; i++)
                {
                    for (var j = 0; j < cols; j++)
                    {
                        result[i, j] = (a[i, j] >= b[i, j]).ToNumber();
                    }
                }

                return(result);
            }

            return(null);
        }
Пример #5
0
        //把数据从UI读取到中间文件
        private void readUItoArray()
        {
            //清空字典
            plate_info = new Dictionary <string, string>();
            //重新初始化中间数组
            tpl = new Info[8, 12];
            od  = new double[8, 12];
            //string[,] odStr = new string[8, 12];//使用字符数组更好?


            //读取文件到中间数组
            //合法性检测
            if (this.textName.Text.Trim() == null)
            {
                MessageBox.Show("请输入项目名称!", "系统提示");
                return;
            }
            if (this.txtUnit.Text.Trim() == null)
            {
                MessageBox.Show("请输入单位名称!", "系统提示");
                return;
            }


            //基本信息-》中间数据
            plate_info["SaveTime"] = DateTime.Now.ToString();//保存文件时的时间
            plate_info["Name"]     = this.textName.Text.Trim();
            plate_info["Lot"]      = this.textLot.Text.Trim();
            plate_info["LabDate"]  = this.dateTimePicker1.Text.Trim();
            plate_info["Unit"]     = this.txtUnit.Text.Trim();
            plate_info["Notice"]   = "不要随意更改文件内容,否则再次读取时将发生错误。";
            plate_info["Curve"]    = this.getRadioIndex().ToString();//拟合的模型编号

            //tpl-》中间数据
            DataReadWrite drw = new DataReadWrite();

            //从UI读取到中间数组
            tpl = drw.readFromUI(this.dataGridView0, true);
            od  = drw.readFromUI(this.dataGridView1);
        }
Пример #6
0
        /// <summary>
        ///   Returns the solution matrix if the matrix is square or the least squares solution otherwise.
        /// </summary>
        ///
        /// <param name="matrix">The matrix for the linear problem.</param>
        /// <param name="rightSide">The right side <c>b</c>.</param>
        /// <param name="leastSquares">True to produce a solution even if the
        ///   <paramref name="matrix"/> is singular; false otherwise. Default is false.</param>
        ///
        /// <remarks>
        ///   Please note that this does not check if the matrix is non-singular
        ///   before attempting to solve. If a least squares solution is desired
        ///   in case the matrix is singular, pass true to the <paramref name="leastSquares"/>
        ///   parameter when calling this function.
        /// </remarks>
        ///
        /// <example>
        /// <code>
        /// // Create a matrix. Please note that this matrix
        /// // is singular (i.e. not invertible), so only a
        /// // least squares solution would be feasible here.
        ///
        /// Double[,] matrix =
        /// {
        ///     { 1, 2, 3 },
        ///     { 4, 5, 6 },
        ///     { 7, 8, 9 },
        /// };
        ///
        /// // Define a right side matrix b:
        /// Double[,] rightSide = { {1}, {2}, {3} };
        ///
        /// // Solve the linear system Ax = b by finding x:
        /// Double[,] x = Matrix.Solve(matrix, rightSide, leastSquares: true);
        ///
        /// // The answer should be { {-1/18}, {2/18}, {5/18} }.
        /// </code>
        /// </example>
        ///
        public static Double[,] Solve(this Double[,] matrix, Double[,] rightSide, bool leastSquares = false)
        {
            int rows = matrix.GetLength(0);
            int cols = matrix.GetLength(1);

            if (rows != rightSide.GetLength(0))
            {
                throw new DimensionMismatchException("rightSide",
                                                     "The number of rows in the right hand side matrix must be "
                                                     + "equal to the number of rows in the problem matrix.");
            }

            if (leastSquares)
            {
                return(new SingularValueDecomposition(matrix,
                                                      computeLeftSingularVectors: true,
                                                      computeRightSingularVectors: true,
                                                      autoTranspose: true).Solve(rightSide));
            }
            if (rows == cols)
            {
                // Solve by LU Decomposition if matrix is square.
                return(new LuDecomposition(matrix).Solve(rightSide));
            }
            else
            {
                if (cols < rows)
                {
                    // Solve by QR Decomposition if not.
                    return(new QrDecomposition(matrix).Solve(rightSide));
                }
                else
                {
                    return(new SingularValueDecomposition(matrix,
                                                          computeLeftSingularVectors: true,
                                                          computeRightSingularVectors: true,
                                                          autoTranspose: true).Solve(rightSide));
                }
            }
        }
        public static string perceptiveHash(Double[,] dm)
        {
            string    temp = "";
            int       sum = 0, tempNum = 0;
            const int Avg = 8;
            int       ddd;

            foreach (Double d in dm)
            {
                if (d <= 0)
                {
                    ddd = 0;
                }
                else
                {
                    ddd = 1;
                }
                sum += ddd * (int)Math.Pow(2, tempNum);
                tempNum++;
                if (tempNum == Avg)
                {
                    tempNum = 0;
                    if (sum != 0)
                    {
                        temp += (char)sum;
                    }
                    sum = 0;
                }
            }
            if (tempNum > 1)
            {
                tempNum = 0;
                if (sum != 0)
                {
                    temp += (char)sum;
                }
                sum = 0;
            }
            return(temp);
        }
Пример #8
0
        /// <summary>
        /// Creates a new Givens decomposition.
        /// </summary>
        /// <param name="matrix">The matrix to decompose.</param>
        public GivensDecomposition(Double[,] matrix)
            : base(matrix)
        {
            var Q = Helpers.One(_rows);
            var R = (Double[, ])matrix.Clone();

            // Main loop.
            for (var j = 0; j < _columns - 1; j++)
            {
                for (var i = _rows - 1; i > j; i--)
                {
                    var a = R[i - 1, j];
                    var b = R[i, j];
                    var G = Helpers.One(_rows);

                    var beta = Math.Sqrt(a * a + b * b);
                    var s    = -b / beta;
                    var c    = a / beta;

                    G[i - 1, i - 1] = c;
                    G[i - 1, i]     = -s;
                    G[i, i - 1]     = s;
                    G[i, i]         = c;

                    R = Helpers.Multiply(G, R);
                    Q = Helpers.Multiply(Q, Helpers.Transpose(G));
                }
            }

            for (var j = 0; j < _columns; j++)
            {
                if (R[j, j] == 0.0)
                {
                    HasFullRank = false;
                }
            }

            r = R;
            q = Q;
        }
        public Double[] MethodI(Double[,] C, Double[] d, int n, double epsilon)
        {
            Double[] X0 = new Double[n];
            double   delta;

            Double[] E = new Double[n];
            Double[] X = new Double[n];

            for (int i = 0; i < n; i++)
            {
                X0[i] = d[i];
            }
            do
            {
                for (int i = 0; i < n; i++)
                {
                    X[i] = 0;
                    for (int j = 0; j < n; j++)
                    {
                        X[i] += C[i, j] * X0[j];
                    }
                    X[i] += d[i];
                    E[i]  = Math.Abs(X[i] - X0[i]);
                }
                delta = E[0];
                for (int i = 1; i < n; i++)
                {
                    if (delta < E[i])
                    {
                        delta = E[i];
                    }
                }

                for (int i = 0; i < n; i++)
                {
                    X0[i] = X[i];
                }
            } while (delta > epsilon);
            return(X);
        }
        public static void EnYakınKomşuBaldanTatlıdır(Double[,] graph, List <int> path)
        {
            Dictionary <int, Double> shortestOnes = new Dictionary <int, Double>();

            for (int i = 0; i < numberOfNodes; i++)
            {
                shortestOnes.Add(i, 100000);
            }

            int p = 0;

            do
            {
                int position = path.Last();
                int i        = position;

                for (int j = 0; j < numberOfNodes; j++)
                {
                    if (graph[i, j] != 0 && shortestOnes[i] > graph[i, j] && !path.Contains(j))
                    {
                        shortestOnes[i] = graph[i, j];
                        position        = j;
                        //graph[i, j] = 0;
                    }
                    //else
                    //{
                    //    graph[i, j] = 0;
                    //}
                }

                path.Add(position);
                cost += shortestOnes[i];
                //for (int k = 0; k < numberOfNodes; k++)
                //    graph[k, i] = 0;
                p++;
            }while (path.Last() != 0 && p < numberOfNodes - 1);

            cost += graph[path.Last(), 0];
            path.Add(0);
        }
Пример #11
0
        /// <summary>
        /// Guassian the specified matrix, upperMatrix and lowerMatrix.
        /// </summary>
        /// <returns>The guassian.</returns>
        /// <param name="matrix">Matrix.</param>
        /// <param name="upperMatrix">Upper matrix.</param>
        /// <param name="lowerMatrix">Lower matrix.</param>
        private static void Guassian(Double[,] matrix, ref Double[,] upperMatrix, ref Double[,] lowerMatrix)
        {
            Console.WriteLine(@"Matrix: ");
            DisplayMatrix(matrix);
            int degrees = matrix.Rank;
            int rows    = matrix.GetLength(0);
            int cols    = matrix.GetLength(1);

            Double[] firstRow  = new Double[cols];
            Double[] secondRow = new Double[cols];

            for (int i = 0; i < rows - 1; i++)
            {
                for (int j = i; j < rows - 1; j++)
                {
                    for (int k = 0; k < cols; k++)
                    {
                        firstRow[k] = matrix[i, k];

                        if (j + 1 < rows)
                        {
                            secondRow[k]          = matrix[j + 1, k];
                            lowerMatrix[j + 1, i] = Multiplier(firstRow, secondRow, i);
                        }
                    }
                    if (i + 1 < rows)
                    {
                        Console.WriteLine(@"Multiplier:  {0} ", Multiplier(firstRow, secondRow, i));
                        Console.WriteLine();
                        Console.WriteLine(@"LowerMatrix: ");
                        DisplayMatrix(lowerMatrix);
                        Console.WriteLine();
                        ReplaceMatrix(ref upperMatrix, Elimination(firstRow, secondRow, Multiplier(firstRow, secondRow, i)), j + 1);
                        Console.WriteLine(@"UpperMatrix: ");
                        DisplayMatrix(upperMatrix);
                        Console.WriteLine();
                    }
                }
            }
        }
Пример #12
0
        public static Object Reduce(this Double[,] matrix, Function f, Object start)
        {
            var args    = new Object[5];
            var result  = start;
            var rows    = matrix.GetRows();
            var columns = matrix.GetColumns();

            for (int i = 0, k = 0; i < rows; i++)
            {
                for (var j = 0; j < columns; j++, k++)
                {
                    args[0] = result;
                    args[1] = matrix[i, j];
                    args[2] = (Double)k;
                    args[3] = (Double)i;
                    args[4] = (Double)j;
                    result  = f(args);
                }
            }

            return(result);
        }
Пример #13
0
        }     //end getVarianceWeights
        private Double[,] BuildCovarianceMatrix(Double[,] matrix, Double rangeParameterA, Double partialSillSigma)
        {
            double[,] covarianceMatrix = new double[matrix.GetLength(0), matrix.GetLength(1)];
            try
            {
                for (int r = 0; r < matrix.GetLength(0); r++)
                {
                    for (int c = 0; c < matrix.GetLength(1); c++)
                    {
                        covarianceMatrix[r, c] = ApplyCovarianceFunction(matrix[r, c], rangeParameterA, partialSillSigma);
                    } //nex c
                }     //next r

                SetLagrangeParameter(ref covarianceMatrix);

                return(covarianceMatrix);
            }
            catch (Exception e)
            {
                throw;
            }
        }//end BuildCovarianceMatrix
Пример #14
0
        static void Main(string[] args)
        {
            Console.Title = "Tercer Desafio Practico";
            String[] datosadmin = Init.Inicio();
            int      bloq       = State.Bloqueo(datosadmin);

            datosadmin[2] = bloq.ToString();
            Escribir.Write(datosadmin, "admindata", "datadmin.dll");
            if (bloq < 1)
            {
                Console.WriteLine("Usuario bloqueado, presione cualquier tecla para salir.");
            }
            else
            {
                String[,] datosempl = Empleados.Wordemploy();
                Double[,] salarios  = Sueldos.Calculos(datosempl);
                String[] mayormenor = Sueldos.Mymn300(salarios, datosempl);
                Salida.Escriturafinal(datosempl, salarios, mayormenor);
            }
            Console.WriteLine("Gracias por utilizar nuestros servicios, presione cualquier tecla para salir.");
            Console.ReadKey();
        }
Пример #15
0
        }     //end getKrigedGageValue

        private Double[,] GetVarianceWeights(Double[,] I, Double[,] D)
        {
            //the set of wieghts that provide unbiased estimates with a minimum estimation variance is calculated by
            //multiplying the inverted covariance matrix(I or C^-1) by the ungaged covarinace matrix (D matrix)
            //Isaaks, E. H., and R. M. Srivastava (1989), An Introduction to Applied
            //		Geostatistics, 1st ed., Oxford Univ. Press, New York. pg295
            int    matrixLength = 0;
            Double wSum         = 0;

            Double[,] w = null;
            try
            {
                if (I.GetLength(0) != D.GetLength(0) ||
                    I.GetLength(1) != D.GetLength(0))
                {
                    throw new Exception("rows != columns");
                }

                matrixLength = I.GetLength(0);

                w = new Double[matrixLength, 1];
                for (int i = 0; i < matrixLength; i++)
                {
                    wSum = 0;
                    for (int j = 0; j < matrixLength; j++)
                    {
                        // matrix DOT product
                        wSum = wSum + I[i, j] * D[j, 0];
                    } //next r
                    w[i, 0] = wSum;
                }     //next i

                return(w);
            }
            catch (Exception e)
            {
                throw;
            } //end try
        }     //end getVarianceWeights
Пример #16
0
        private Boolean ConstruMInv()  //construimos una matriz identidad con las dimesiones de la matriz original
        {
            int i, j;

            try {
                mInv = new double[fc, cc];
                for (i = 0; i < this.fc; i++)
                {
                    for (j = 0; j < this.cc; j++)
                    {
                        this.mInv[i, j] = 0;
                        if (i == j)
                        {
                            this.mInv[i, j] = 1;
                        }
                    }
                }
                return(true);
            } catch {
                return(false);
            }
        }
        public static Double[,] Inverse(Double[,] matrix)
        {
            var rows   = matrix.GetLength(0);
            var cols   = matrix.GetLength(1);
            var target = Helpers.One(cols);

            if (cols < 24)
            {
                var lu = new LUDecomposition(matrix);
                return(lu.Solve(target));
            }
            else if (Helpers.IsSymmetric(matrix))
            {
                var cho = new CholeskyDecomposition(matrix);
                return(cho.Solve(target));
            }
            else
            {
                var qr = QRDecomposition.Create(matrix);
                return(qr.Solve(target));
            }
        }
Пример #18
0
        private Double[,] RowPivot(Double[,] matrix, int k)
        {
            //int row = 0;

            for (int i = k + 1; i < matrix.GetLength(0); i++)
            {
                if (matrix[i, i] != 0)
                {
                    Double[] x = new Double[matrix.GetLength(1)];

                    for (int j = 0; j < matrix.GetLength(1); j++)
                    {
                        x[j]         = matrix[k, j];
                        matrix[k, j] = matrix[i, j];
                        matrix[i, j] = x[j];
                    }
                    break;
                }
            }

            return(matrix);
        }
Пример #19
0
        //返回od数据
        public double[,] readFromUI(DataGridView dgv)
        {
            //string[,] odStr=new string[8,12];
            od = new double[8, 12];

            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 12; j++)
                {
                    if ((dgv.Rows[i].Cells[j].Value != null) && (dgv.Rows[i].Cells[j].Value.ToString() != ""))
                    {
                        //获取单元格内容字符串
                        od[i, j] = double.Parse(dgv.Rows[i].Cells[j].Value.ToString());
                    }
                    else 
                    {
                        od[i, j] = -10000; 
                    }
                }
            }
            return od;
        }
Пример #20
0
        static Double Det(Double[,] A, Int32 n)
        {
            if (n == 0)
            {
                return(0);
            }
            if (n == 1)
            {
                return(A[0, 0]);
            }
            if (n == 2)
            {
                return(A[0, 0] * A[1, 1] - A[0, 1] * A[1, 0]);
            }
            Double AA = 0;

            for (int i = 0; i < n; i++)
            {
                AA = AA + A[0, i] * System.Math.Pow(-1, i) * Det(AStar(A, n, 0, i), n - 1);
            }
            return(AA);
        }
Пример #21
0
            /*量化解碼*/
            public void D_quantized(int[,] tem_y, int[,] tem_u, int[,] tem_v, Double[,] ten_y, Double[,] ten_u, Double[,] ten_v)
            {
                //Dz_y zigzag解碼後的y
                //Dz_u zigzag解碼後的u
                //Dz_v zigzag解碼後的v
                int[,] uv_table = { { 16, 11, 10, 16,  24,  40,  51,  61 },
                                    { 12, 12, 14, 19,  26,  58,  60,  55 },
                                    { 14, 13, 16, 24,  40,  57,  69,  56 },
                                    { 14, 17, 22, 29,  51,  87,  80,  62 },
                                    { 18, 22, 37, 56,  68, 109, 103,  77 },
                                    { 24, 35, 55, 64,  81, 104, 113,  92 },
                                    { 49, 64, 78, 87, 103, 121, 120, 101 },
                                    { 72, 92, 95, 98, 112, 100, 103,  99 } };

                int[,] y_table = { { 17, 18, 24, 47, 99, 99, 99, 99 },
                                   { 18, 21, 26, 66, 99, 99, 99, 99 },
                                   { 24, 26, 56, 99, 99, 99, 99, 99 },
                                   { 47, 66, 99, 99, 99, 99, 99, 99 },
                                   { 99, 99, 99, 99, 99, 99, 99, 99 },
                                   { 99, 99, 99, 99, 99, 99, 99, 99 },
                                   { 99, 99, 99, 99, 99, 99, 99, 99 },
                                   { 99, 99, 99, 99, 99, 99, 99, 99 } };

                for (int m = 0; m < new_h; m += dim)
                {
                    for (int n = 0; n < new_w; n += dim)
                    {
                        for (int i = 0; i < dim; i++)
                        {
                            for (int j = 0; j < dim; j++)
                            {
                                ten_y[i + m, j + n] = tem_y[i + m, j + n] * y_table[i, j];
                                ten_u[i + m, j + n] = tem_u[i + m, j + n] * uv_table[i, j];
                                ten_v[i + m, j + n] = tem_v[i + m, j + n] * uv_table[i, j];
                            }
                        }
                    }
                }
            }
Пример #22
0
        string AlreadyMatchingTemplate(Double[,] rs)
        {
            try
            {
                SqlConnection cn = new SqlConnection(st.ConStr);
                cn.Open();
                SqlDataReader rd    = new SqlCommand("SELECT * FROM employees", cn).ExecuteReader();
                var           rlist = new SortedDictionary <string, double>();
                while (rd.Read())
                {
                    byte[] data = (byte[])rd["iristemp"];
                    Double[,] dbv = (Double[, ])st.ByteArrayToObject(data);

                    /*if (ByteArrayCompare(data, rs))
                     *  return rd["eid"] + " : " + rd["imgkey"];*/
                    rlist.Add(rd["eid"] + "-" + rd["ename"], st.TemplateEquals(dbv, rs));
                }
                cn.Close();


                IEnumerable <KeyValuePair <string, double> > vals = rlist.OrderByDescending(k => k.Value);

                if (vals.Count() > 0)
                {
                    var val = vals.ElementAt(0);
                    if (val.Value > 60.0)
                    {
                        return(val.Key);
                    }
                }
                return(null);
            }
            catch (Exception ex)
            {
                st.WMsgBox(ex.ToString());
                return(null);
            }
        }
        private void algoritmoGauss(Double[,] matriz)
        {
            int tamMatriz = matriz.GetUpperBound(1);
            int pivote    = 0;

            for (int i = 0; i <= tamMatriz - 1; i++)
            {
                if (matriz[i, i] == 0)
                {
                    //Deberia lanzar un error
                    //rchTeOperaciones.Text += "Error: " + "no es posible resolver ecuacion";
                }
                else
                {
                    if (matriz[i, i] != 1)
                    {
                        Double divisorPiv = matriz[i, i];
                        for (int col = 0; col <= tamMatriz; col++)
                        {
                            matriz[i, col] = matriz[i, col] / divisorPiv;
                        }
                    }

                    for (int ren = 0; ren < tamMatriz; ren++)
                    {
                        if (ren != pivote)
                        {
                            Double val0 = -Convert.ToDouble(matriz[ren, i]);
                            for (int col = 0; col <= tamMatriz; col++)
                            {
                                matriz[ren, col] = matriz[i, col] * val0 + matriz[ren, col];
                            }
                        }
                    }
                }
                pivote++;
            }
        }
Пример #24
0
            /*以下為色彩轉換副程式*/
            public void rgb_to_yuv(int[,,] rgbData, Double[,] arr_y, Double[,] arr_u, Double[,] arr_v)
            {
                //設定像點資料
                for (int y = 0; y < Height; y++)
                {
                    for (int x = 0; x < Width; x++)
                    {
                        arr_y[y, x] = 0.299 * rgbData[y, x, 0] + 0.587 * rgbData[y, x, 1] + 0.114 * rgbData[y, x, 2];     //亮度轉換
                        arr_u[y, x] = 0.5 * rgbData[y, x, 2] - 0.169 * rgbData[y, x, 0] - 0.331 * rgbData[y, x, 1] + 128; //藍色色度差轉換
                        arr_v[y, x] = 0.5 * rgbData[y, x, 0] - 0.419 * rgbData[y, x, 1] - 0.081 * rgbData[y, x, 2] + 128; //紅色色度差轉換

                        if (arr_y[y, x] < 0)
                        {
                            arr_y[y, x] = 0;
                        }
                        if (arr_y[y, x] > 255)
                        {
                            arr_y[y, x] = 255;
                        }
                        if (arr_u[y, x] < 0)
                        {
                            arr_u[y, x] = 0;
                        }
                        if (arr_u[y, x] > 255)
                        {
                            arr_u[y, x] = 255;
                        }
                        if (arr_v[y, x] < 0)
                        {
                            arr_v[y, x] = 0;
                        }
                        if (arr_v[y, x] > 255)
                        {
                            arr_v[y, x] = 255;
                        }
                    }
                }
            }
Пример #25
0
 /*以下為取樣*/
 public void sampling(Double[,] arr_u, Double[,] arr_v)
 {
     new_h = Height - Height % dim;
     new_w = Width - Width % dim;
     for (int i = 0; i < Height; i++)
     {
         for (int j = 0; j < Width; j++)
         {
             if (j % 2 == 0)
             {
                 if (i % 2 == 0)
                 {
                     if (i + 1 < Height)
                     {
                         arr_v[i + 1, j] = arr_v[i, j];
                     }
                     if (i + 1 < Height && j + 1 < Width)
                     {
                         arr_v[i + 1, j + 1] = arr_v[i, j];
                     }
                     if (j + 1 < Width)
                     {
                         arr_v[i, j + 1] = arr_v[i, j];
                     }
                 }
                 else
                 {
                     arr_u[i - 1, j] = arr_u[i, j];
                     if (j + 1 < Width)
                     {
                         arr_u[i - 1, j + 1] = arr_u[i, j];
                         arr_u[i, j + 1]     = arr_u[i, j];
                     }
                 }
             }
         }
     }
 }
Пример #26
0
        public static Double[] GetAllDetail(Double[,] input, Int32 currentLevel)
        {
            Int32 Len = input.GetLength(0) >> currentLevel;

            Double[] output   = new Double[input.GetLength(0) * input.GetLength(0) - (Len * Len)];
            Int32    OutIndex = 0;

            for (int lev = currentLevel; lev > 0; lev--)
            {
                Int32 Bound = input.GetLength(0) >> lev - 1;
                Len = input.GetLength(0) >> lev;
                for (int i = 0; i < Len; i++)
                {
                    for (int j = Len; j < Bound; j++)
                    {
                        output[OutIndex] = input[i, j];
                        OutIndex++;
                    }
                }
                for (int i = Len; i < Bound; i++)
                {
                    for (int j = 0; j < Len; j++)
                    {
                        output[OutIndex] = input[i, j];
                        OutIndex++;
                    }
                }
                for (int i = Len; i < Bound; i++)
                {
                    for (int j = Len; j < Bound; j++)
                    {
                        output[OutIndex] = input[i, j];
                        OutIndex++;
                    }
                }
            }
            return(output);
        }
Пример #27
0
        public Double[,] IterForm(Double[,] A, Double[] b, int n)
        {
            C1 = new Double[n, n];
            C2 = new Double[n];
            //получение итерационной формы системы
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (i == j)
                    {
                        C1[i, j] = 0;
                    }
                    else
                    {
                        C1[i, j] = -A[i, j] / A[i, i];
                    }
                }
                C2[i] = b[i] / A[i, i];
            }

            return(C1);
        }
Пример #28
0
 public static object[,] _PFE(object[,] products,
                              object[,] valueDate,
                              object[,] forwardValueDates,
                              object[,] requiredPecentiles,
                              object[,] model,
                              object[,] nSims)
 {
     try
     {
         Product[]          _products           = XU.GetObject1D <Product>(products, "products");
         Date               _valueDate          = XU.GetDate0D(valueDate, "valueDate");
         Date[]             _forwardValueDates  = XU.GetDate1D(forwardValueDates, "forwardValueDates");
         Double[]           _requiredPecentiles = XU.GetDouble1D(requiredPecentiles, "requiredPecentiles");
         NumeraireSimulator _model = XU.GetObject0D <NumeraireSimulator>(model, "model");
         Int32              _nSims = XU.GetInt320D(nSims, "nSims");
         Double[,] _result = XLValuation.PFE(_products, _valueDate, _forwardValueDates, _requiredPecentiles, _model, _nSims);
         return(XU.ConvertToObjects(_result));
     }
     catch (Exception e)
     {
         return(XU.Error2D(e));
     }
 }
Пример #29
0
        public static Boolean IsSymmetric(Double[,] matrix)
        {
            var rows = matrix.GetLength(0);
            var cols = matrix.GetLength(1);

            if (rows == cols)
            {
                for (var i = 0; i < rows; i++)
                {
                    for (var j = 0; j < i; j++)
                    {
                        if (matrix[i, j] != matrix[j, i])
                        {
                            return(false);
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
Пример #30
0
        public static void MultiplyMatricesTasks(Double[,] matrA, Double[,] matrB,
                                                 Double[,] result, Int32 n)
        {
            // Масив задач
            Task[] tasks = new Task[ProcessorCount - 1];
            // Кількість ітерацій на потік
            Int32 iterationsPerTask = n / ProcessorCount;
            Int32 i, currentStartNumber;

            for (i = 0, currentStartNumber = 0; i < ProcessorCount - 1; i++, currentStartNumber += iterationsPerTask)
            {
                Int32 number = currentStartNumber;
                // Створюємо та одразу запускаємо нову задачу
                tasks[i] = Task.Run(() =>
                                    MultiplyWithBounds(matrA, matrB, result, n, number, number + iterationsPerTask - 1));
            }

            // Для головного потоку
            MultiplyWithBounds(matrA, matrB, result, n, currentStartNumber, currentStartNumber + iterationsPerTask - 1);

            // Чекаємо, коли усі задачі завершаться
            Task.WhenAll(tasks).Wait();
        }
Пример #31
0
 /// <summary>
 /// Konstruktor.
 /// </summary>
 /// <param name="costMatrix">Macierz kosztu przejścia.</param>
 public TSPFitness(Double[,] costMatrix)
 {
     this.costMatrix = (Double[,])costMatrix.Clone();
 }
        /// <summary>
        ///   Construct an eigenvalue decomposition.</summary>
        /// <param name="value">
        ///   The matrix to be decomposed.</param>
        /// <param name="assumeSymmetric">
        ///   Defines if the matrix should be assumed as being symmetric
        ///   regardless if it is or not. Default is <see langword="false"/>.</param>
        /// <param name="inPlace">
        ///   Pass <see langword="true"/> to perform the decomposition in place. The matrix
        ///   <paramref name="value"/> will be destroyed in the process, resulting in less
        ///   memory comsumption.</param>
        public EigenvalueDecomposition(Double[,] value, bool assumeSymmetric, bool inPlace)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Matrix cannot be null.");
            }

            if (value.GetLength(0) != value.GetLength(1))
            {
                throw new ArgumentException("Matrix is not a square matrix.", "value");
            }

            n = value.GetLength(1);
            V = new Double[n, n];
            d = new Double[n];
            e = new Double[n];


            this.symmetric = assumeSymmetric;

            if (this.symmetric)
            {
                V = inPlace ? value : (Double[,])value.Clone();

                // Tridiagonalize.
                this.tred2();

                // Diagonalize.
                this.tql2();
            }
            else
            {
                H = inPlace ? value : (Double[,])value.Clone();

                ort = new Double[n];

                // Reduce to Hessenberg form.
                this.orthes();

                // Reduce Hessenberg to real Schur form.
                this.hqr2();
            }
        }
        public void SetAccel(Double[,] accelValues)
        {

            AccelValues = accelValues;

        }
 private CoordinateDataBuffer()
 {
     _ellipseCoordinates = new Point();
     PointerCoordinates = new Point[2];
     AccelValues = new Double[2, 3];
 }
Пример #35
0
        /// <summary>
        /// Instructs the algorithm to prepare it's data.
        /// </summary>
        public void PrepareToStart()
        {
            Random random = new Random();

            /* Build up those matrixes */
            m_Matrix1 = new Double[m_Matrix1X, m_Matrix1Y];
            m_Matrix2 = new Double[m_Matrix2X, m_Matrix2Y];
            m_ResultMatrix = new Double[m_Matrix2X, m_Matrix1Y];

            /* Populate matrix 1 */
            for (Int32 x = 0; x < m_Matrix1X; x++)
            {
                for (Int32 y = 0; y < m_Matrix1Y; y++ )
                    m_Matrix1[x, y] = Math.Round(random.NextDouble() * 100, 2);
            }

            /* Populate Matrix 2*/
            for (Int32 x = 0; x < m_Matrix2X; x++)
            {
                for (Int32 y = 0; y < m_Matrix2Y; y++)
                    m_Matrix2[x, y] = Math.Round(random.NextDouble() * 100, 2);
            }
        }
Пример #36
0
 internal void unpopulate()
 {
     digitalData = null;
     analogPulse = null;
 }
Пример #37
0
        //Fuzzy C-Means process thread\\
        private void fuzzycmeansprocessThread()
        {
            timer2.Start();
            BackgroundWorker b = new BackgroundWorker();
            int period = 0;
            int periodTrackbarValue = periodTrackBar.Value;
            metroPanel1.Visible = false;
            metroPanel2.Visible = false;
            metroPanel3.Visible = true;
            this.Text = "Process";
            fuzzyrfmTimerLabel.Visible = false;
            viewFuzzyBtn.Visible = false;
            viewResultBtn.Visible = false;
            winChartViewer1.Image = null;
            b.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                query = "SELECT TOP 1 * FROM [CSS].[dbo].[transaction] order by purchaseDate DESC";
                sqlConnection();
                sqlCon.Open();
                command = new SqlCommand();
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                sa = new SqlDataAdapter(command);
                dt = new DataTable();
                sa.Fill(dt);
                dateCutOff = Convert.ToDateTime(dt.Rows[0][3]);

                query = "SELECT * FROM [CSS].[dbo].[transaction] order by [CID]";
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                sa = new SqlDataAdapter(command);
                dt = new DataTable();
                sa.Fill(dt);

                //Customer table emptied\\
                delQuery = "delete [CSS].[DBO].customer";
                command = new SqlCommand(delQuery, sqlCon);
                command.CommandText = delQuery;
                sa = new SqlDataAdapter(command);
                command.Connection = sqlCon;
                command.ExecuteNonQuery();

                custName = new String[1];
                custID = new String[1];
                DateTime date = Convert.ToDateTime(dt.Rows[0][3]);
                Double mntry = Convert.ToInt64(dt.Rows[0][2]);
                X = new Double[dt.Rows.Count, 3];
                int frq = 1;
                int idx = 0;
                DataRow dr;
                dr = dt.Rows[0];

                //Customer data preprocessing\\
                for (int i = 0; i < periodTrackbarValue; i++)
                {
                    period += DateTime.DaysInMonth(dateCutOff.Year, dateCutOff.Month - i);
                }
                for (int i = 0; i < dt.Rows.Count - 1; i++)
                {
                    if (Convert.ToInt32((dateCutOff - Convert.ToDateTime(dr.Table.Rows[i][3])).TotalDays) <= period)
                    {
                        custName[idx] = dr.Table.Rows[i][1].ToString();
                        custID[idx] = dr.Table.Rows[i][4].ToString();
                        if (custID[idx] == dt.Rows[i + 1][4].ToString())
                        {
                            if (Convert.ToInt32((dateCutOff - Convert.ToDateTime(dt.Rows[i + 1][3])).TotalDays) <= period)
                            {
                                if (Convert.ToDateTime(dt.Rows[i + 1][3]) > Convert.ToDateTime(dr.Table.Rows[i][3]))
                                {
                                    date = Convert.ToDateTime(dt.Rows[i + 1][3]);
                                }
                                frq += 1;
                                mntry += Convert.ToInt64(dt.Rows[i + 1][2]);
                            }
                        }
                        else if (custID[idx] != dt.Rows[i + 1][4].ToString())
                        {
                            X[idx, 0] = Convert.ToInt32((dateCutOff - date).TotalDays);
                            X[idx, 1] = frq;
                            X[idx, 2] = mntry;
                            idx += 1;
                            Array.Resize(ref custName, idx + 1);
                            Array.Resize(ref custID, idx + 1);
                            frq = 1;
                            mntry = Convert.ToInt64(dt.Rows[i + 1][2]);
                            date = Convert.ToDateTime(dt.Rows[i + 1][3]);
                        }
                    }
                }
                num = Enumerable.Range(0, X.GetLength(0)).Count(i => X[i, 0] != 0);
                //Customer calculated data insertion to customer table in SQL\\
                for (int i = 0; i < num; i++)
                {
                    String customerQuery = "INSERT customer (CID, customerName, Frequency, totalPurchase, lastPurchase, clusterIndex) VALUES ('" + custID[i] + "', '" + custName[i].Replace("'", " ") + "', '" + X[i, 1] + "', '" + X[i, 2] + "', '" + dateCutOff.AddDays(-X[i, 0]) + "', '" + 0 + "')";
                    command.CommandText = customerQuery;
                    command.CommandType = CommandType.Text;
                    command.Connection = sqlCon;
                    command = new SqlCommand(customerQuery, sqlCon);
                    command.ExecuteNonQuery();
                }
                fuzzyCMeans();
            };

            b.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                this.TopMost = true;
                this.BringToFront();
                this.Focus();
                sqlCon.Open();
                timer2.Stop();
                clusterProgressBar.Visible = false;
                clusterProgressBar.Enabled = false;
                rfmprocessBtn.Visible = true;
                rfmprocessBtn.Focus();
                this.TopMost = false;
                viewFuzzyBtn.Visible = true;
                fuzzycmeansTimerLabel.Location = new Point(163, 9);
                query = "SELECT TOP 1 * FROM [CSS].[dbo].[historyIndex] order by historyID DESC";
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                sa = new SqlDataAdapter(command);
                dt = new DataTable();
                sa.Fill(dt);
                query = "UPDATE [CSS].[dbo].historyIndex set fuzzyProcessTime ='" + timeSpan + "', MPCScore='" + MPCScore + "', fuzzyRFMTime=null where historyID ='" + dt.Rows[0][0].ToString() + "'";
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Connection = sqlCon;
                command.ExecuteNonQuery();
                sqlCon.Close();
            };
            clusterProgressBar.Enabled = true;
            b.RunWorkerAsync();
        }
Пример #38
0
 public Mat4(Double[,] data)
 {
     _data = data;
 }
        private Double[,] v; // right singular vectors

        #endregion Fields

        #region Constructors

        /// <summary>Constructs a new singular value decomposition.</summary>
        /// <param name="value">
        ///   The matrix to be decomposed.</param>
        public SingularValueDecomposition(Double[,] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Matrix cannot be null.");
            }

            //m should not less than n
            Double[,] a;
            m = value.GetLength(0); // rows
            n = value.GetLength(1); // cols

            if (m < n)
            {
                throw new System.Exception("rows should not less than cols in value matrix");
            }

            // Proceed anyway
            a = (Double[,])value.Clone();

            int nu = System.Math.Min(m, n);
            int ni = System.Math.Min(m + 1, n);
            s = new Double[ni];
            u = new Double[m, nu];
            v = new Double[n, n];
            Double[] e = new Double[n];
            Double[] work = new Double[m];

            // Will store ordered sequence of indices after sorting.
            si = new int[ni]; for (int i = 0; i < ni; i++) si[i] = i;

            // Reduce A to bidiagonal form, storing the diagonal elements in s and the super-diagonal elements in e.
            int nct = System.Math.Min(m - 1, n);
            int nrt = System.Math.Max(0, System.Math.Min(n - 2, m));
            for (int k = 0; k < System.Math.Max(nct, nrt); k++)
            {
                if (k < nct)
                {
                    // Compute the transformation for the k-th column and place the k-th diagonal in s[k].
                    // Compute 2-norm of k-th column without under/overflow.
                    s[k] = 0;
                    for (int i = k; i < m; i++)
                    {
                        s[k] = Hypotenuse(s[k], a[i, k]);
                    }

                    if (s[k] != 0)
                    {
                        if (a[k, k] < 0)
                            s[k] = -s[k];

                        for (int i = k; i < m; i++)
                            a[i, k] /= s[k];

                        a[k, k] += 1;
                    }

                    s[k] = -s[k];
                }

                for (int j = k + 1; j < n; j++)
                {
                    if ((k < nct) & (s[k] != 0))
                    {
                        // Apply the transformation.
                        Double t = 0;
                        for (int i = k; i < m; i++)
                        {
                            t += a[i, k] * a[i, j];
                        }

                        t = -t / a[k, k];

                        for (int i = k; i < m; i++)
                        {
                            a[i, j] += t * a[i, k];
                        }
                    }

                    // Place the k-th row of A into e for the subsequent calculation of the row transformation.
                    e[j] = a[k, j];
                }

                if (k < nct)
                {
                    // Place the transformation in U for subsequent back
                    // multiplication.
                    for (int i = k; i < m; i++)
                        u[i, k] = a[i, k];
                }

                if (k < nrt)
                {
                    // Compute the k-th row transformation and place the k-th super-diagonal in e[k].
                    // Compute 2-norm without under/overflow.
                    e[k] = 0;
                    for (int i = k + 1; i < n; i++)
                        e[k] = Hypotenuse(e[k], e[i]);

                    if (e[k] != 0)
                    {
                        if (e[k + 1] < 0)
                            e[k] = -e[k];

                        for (int i = k + 1; i < n; i++)
                            e[i] /= e[k];

                        e[k + 1] += 1;
                    }

                    e[k] = -e[k];
                    if ((k + 1 < m) & (e[k] != 0))
                    {
                        // Apply the transformation.
                        for (int i = k + 1; i < m; i++)
                            work[i] = 0;

                        int k1 = k + 1;
                        for (int i = k1; i < m; i++)
                        {
                            for (int j = k1; j < n; j++)
                            {
                                work[i] += e[j] * a[i, j];
                            }
                        }

                        for (int j = k1; j < n; j++)
                        {
                            Double t = -e[j] / e[k1];
                            for (int i = k1; i < m; i++)
                            {
                                a[i, j] += t * work[i];
                            }
                        }
                    }

                    // Place the transformation in V for subsequent back multiplication.
                    for (int i = k + 1; i < n; i++)
                        v[i, k] = e[i];
                }
            }

            // Set up the final bidiagonal matrix or order p.
            int p = System.Math.Min(n, m + 1);
            if (nct < n) s[nct] = a[nct, nct];
            if (m < p) s[p - 1] = 0;
            if (nrt + 1 < p) e[nrt] = a[nrt, p - 1];
            e[p - 1] = 0;

            //generate U.
            for (int j = nct; j < nu; j++)
            {
                for (int i = 0; i < m; i++)
                    u[i, j] = 0;
                u[j, j] = 1;
            }

            for (int k = nct - 1; k >= 0; k--)
            {
                if (s[k] != 0)
                {
                    for (int j = k + 1; j < nu; j++)
                    {
                        Double t = 0;
                        for (int i = k; i < m; i++)
                        {
                            t += u[i, k] * u[i, j];
                        }

                        t = -t / u[k, k];

                        for (int i = k; i < m; i++)
                        {
                            u[i, j] += t * u[i, k];
                        }
                    }

                    for (int i = k; i < m; i++)
                    {
                        u[i, k] = -1.0 * u[i, k];
                    }

                    u[k, k] = 1 + u[k, k];
                    for (int i = 0; i < k - 1; i++)
                        u[i, k] = 0;
                }
                else
                {
                    for (int i = 0; i < m; i++)
                        u[i, k] = 0;
                    u[k, k] = 1;
                }
            }

            //generate V.
            for (int k = n - 1; k >= 0; k--)
            {
                if ((k < nrt) & (e[k] != 0))
                {
                    // TODO: The following is a pseudo correction to make SVD
                    //  work on matrices with n > m (less rows than columns).

                    // For the proper correction, compute the decomposition of the
                    //  transpose of A and swap the left and right eigenvectors

                    // Original line:
                    //   for (int j = k + 1; j < nu; j++)
                    // Pseudo correction:
                    //   for (int j = k + 1; j < n; j++)

                    for (int j = k + 1; j < n; j++) // pseudo-correction
                    {
                        Double t = 0;
                        for (int i = k + 1; i < n; i++)
                        {
                            t += v[i, k] * v[i, j];
                        }

                        t = -t / v[k + 1, k];

                        for (int i = k + 1; i < n; i++)
                        {
                            v[i, j] += t * v[i, k];
                        }
                    }
                }

                for (int i = 0; i < n; i++)
                {
                    v[i, k] = 0;
                }
                v[k, k] = 1;
            }

            // Main iteration loop for the singular values.
            int pp = p - 1;
            int iter = 0;
            while (p > 0)
            {
                int k, kase;

                // Here is where a test for too many iterations would go.

                // This section of the program inspects for
                // negligible elements in the s and e arrays.  On
                // completion the variables kase and k are set as follows.

                // kase = 1     if s(p) and e[k-1] are negligible and k<p
                // kase = 2     if s(k) is negligible and k<p
                // kase = 3     if e[k-1] is negligible, k<p, and
                //              s(k), ..., s(p) are not negligible (qr step).
                // kase = 4     if e(p-1) is negligible (convergence).

                for (k = p - 2; k >= -1; k--)
                {
                    if (k == -1)
                        break;

                    if (System.Math.Abs(e[k]) <=
                       tiny + eps * (System.Math.Abs(s[k]) + System.Math.Abs(s[k + 1])))
                    {
                        e[k] = 0;
                        break;
                    }
                }

                if (k == p - 2)
                {
                    kase = 4;
                }
                else
                {
                    int ks;
                    for (ks = p - 1; ks >= k; ks--)
                    {
                        if (ks == k)
                            break;

                        Double t = (ks != p ? System.Math.Abs(e[ks]) : 0) +
                                   (ks != k + 1 ? System.Math.Abs(e[ks - 1]) : 0);
                        if (System.Math.Abs(s[ks]) <= tiny + eps * t)
                        {
                            s[ks] = 0;
                            break;
                        }
                    }

                    if (ks == k)
                        kase = 3;
                    else if (ks == p - 1)
                        kase = 1;
                    else
                    {
                        kase = 2;
                        k = ks;
                    }
                }

                k++;

                // Perform the task indicated by kase.
                switch (kase)
                {
                    // Deflate negligible s(p).
                    case 1:
                        {
                            Double f = e[p - 2];
                            e[p - 2] = 0;
                            for (int j = p - 2; j >= k; j--)
                            {
                                Double t = Hypotenuse(s[j], f);
                                Double cs = s[j] / t;
                                Double sn = f / t;
                                s[j] = t;
                                if (j != k)
                                {
                                    f = -sn * e[j - 1];
                                    e[j - 1] = cs * e[j - 1];
                                }

                                for (int i = 0; i < n; i++)
                                {
                                    t = cs * v[i, j] + sn * v[i, p - 1];
                                    v[i, p - 1] = -sn * v[i, j] + cs * v[i, p - 1];
                                    v[i, j] = t;
                                }
                            }
                        }
                        break;

                    // Split at negligible s(k).
                    case 2:
                        {
                            Double f = e[k - 1];
                            e[k - 1] = 0;
                            for (int j = k; j < p; j++)
                            {
                                Double t = Hypotenuse(s[j], f);
                                Double cs = s[j] / t;
                                Double sn = f / t;
                                s[j] = t;
                                f = -sn * e[j];
                                e[j] = cs * e[j];

                                for (int i = 0; i < m; i++)
                                {
                                    t = cs * u[i, j] + sn * u[i, k - 1];
                                    u[i, k - 1] = -sn * u[i, j] + cs * u[i, k - 1];
                                    u[i, j] = t;
                                }
                            }
                        }
                        break;

                    // Perform one qr step.
                    case 3:
                        {
                            // Calculate the shift.
                            Double scale = System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Abs(s[p - 1]), System.Math.Abs(s[p - 2])), System.Math.Abs(e[p - 2])), System.Math.Abs(s[k])), System.Math.Abs(e[k]));
                            Double sp = s[p - 1] / scale;
                            Double spm1 = s[p - 2] / scale;
                            Double epm1 = e[p - 2] / scale;
                            Double sk = s[k] / scale;
                            Double ek = e[k] / scale;
                            Double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;
                            Double c = (sp * epm1) * (sp * epm1);
                            double shift = 0;

                            if ((b != 0) | (c != 0))
                            {
                                if (b < 0)
                                    shift = -System.Math.Sqrt(b * b + c);
                                else
                                    shift = System.Math.Sqrt(b * b + c);

                                shift = c / (b + shift);
                            }

                            Double f = (sk + sp) * (sk - sp) + (Double)shift;
                            Double g = sk * ek;

                            // Chase zeros.
                            for (int j = k; j < p - 1; j++)
                            {
                                Double t = Hypotenuse(f, g);
                                Double cs = f / t;
                                Double sn = g / t;
                                if (j != k) e[j - 1] = t;
                                f = cs * s[j] + sn * e[j];
                                e[j] = cs * e[j] - sn * s[j];
                                g = sn * s[j + 1];
                                s[j + 1] = cs * s[j + 1];

                                for (int i = 0; i < n; i++)
                                {
                                    /*t = cs * v[i, j] + sn * v[i, j + 1];
                                    v[i, j + 1] = -sn * v[i, j] + cs * v[i, j + 1];
                                    v[i, j] = t;*/

                                    Double vij = v[i, j]; // *vj;
                                    Double vij1 = v[i, j + 1]; // *vj1;

                                    t = cs * vij + sn * vij1;
                                    v[i, j + 1] = -sn * vij + cs * vij1;
                                    v[i, j] = t;
                                }

                                t = Hypotenuse(f, g);
                                cs = f / t;
                                sn = g / t;
                                s[j] = t;
                                f = cs * e[j] + sn * s[j + 1];
                                s[j + 1] = -sn * e[j] + cs * s[j + 1];
                                g = sn * e[j + 1];
                                e[j + 1] = cs * e[j + 1];

                                if (j < m - 1)
                                {
                                    for (int i = 0; i < m; i++)
                                    {
                                        /* t = cs * u[i, j] + sn * u[i, j + 1];
                                         u[i, j + 1] = -sn * u[i, j] + cs * u[i, j + 1];
                                         u[i, j] = t;*/

                                        Double uij = u[i, j]; // *uj;
                                        Double uij1 = u[i, j + 1]; // *uj1;

                                        t = cs * uij + sn * uij1;

                                        u[i, j + 1] = -sn * uij + cs * uij1;
                                        u[i, j] = t;
                                    }
                                }

                            }

                            e[p - 2] = f;
                            iter = iter + 1;
                        }
                        break;

                    // Convergence.
                    case 4:
                        {
                            // Make the singular values positive.
                            if (s[k] <= 0)
                            {
                                s[k] = (s[k] < 0 ? -s[k] : 0);

                                for (int i = 0; i <= pp; i++)
                                    v[i, k] = -v[i, k];

                            }

                            // Order the singular values.
                            while (k < pp)
                            {
                                if (s[k] >= s[k + 1])
                                    break;

                                Double t = s[k];
                                s[k] = s[k + 1];
                                s[k + 1] = t;

                                int ti = si[k];
                                si[k] = si[k + 1];
                                si[k + 1] = ti;

                                if (k < n - 1)
                                {
                                    for (int i = 0; i < n; i++)
                                    {
                                        t = v[i, k + 1];
                                        v[i, k + 1] = v[i, k];
                                        v[i, k] = t;
                                    }
                                }

                                if (k < m - 1)
                                {
                                    for (int i = 0; i < m; i++)
                                    {
                                        t = u[i, k + 1];
                                        u[i, k + 1] = u[i, k];
                                        u[i, k] = t;
                                    }
                                }

                                k++;
                            }

                            iter = 0;
                            p--;
                        }
                        break;
                }
            }
        }
Пример #40
0
 /// <summary>
 /// Tworzy okno dialogowe dla wczytania danych z pliku.
 /// </summary>
 private void loadDataButton_Click(object sender, EventArgs e)
 {
     OpenFileDialog openFileDialog = new OpenFileDialog();
     openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
     DialogResult result = openFileDialog.ShowDialog();
     if (result == DialogResult.OK) // Test result.
     {
         try
         {
             costMatrix = LoadFile(openFileDialog.FileName);
             InsertData(costMatrix);
         }
         catch (Exception ex)
         {
             MessageBox.Show("Nie można wczytać pliku z danymi: " + ex.Message);
         }
     }
 }
Пример #41
0
 //从前一个窗体获得数据
 private void getData()
 {
     //获取第一窗体输入的数字
     //int num = ((Form1)this.Owner).num;
     plate_info = ((Form1)this.Owner).plate_info;
     tpl = ((Form1)this.Owner).tpl;
     od = ((Form1)this.Owner).od;
 }
Пример #42
0
        public MainForm()
        {
            InitializeComponent();

            selecitonModifierComboBox.DisplayMember = "Key";
            selecitonModifierComboBox.ValueMember = "Value";
            selecitonModifierComboBox.DataSource = new BindingSource(ModifierCombinationDict, null);

            selectionAlgorithmComboBox.DisplayMember = "Key";
            selectionAlgorithmComboBox.ValueMember = "Value";
            selectionAlgorithmComboBox.DataSource = new BindingSource(SelectionStrategiesDict, null);
            selectionAlgorithmComboBox.SelectedIndex = 1;

            {
                crossoverStategies = new List<Object>();
                var type = typeof(PermutationChromosome.ICrossOverStrategy);
                var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                    .SelectMany(s => s.GetTypes())
                    .Where(p => type.IsAssignableFrom(p) && !type.IsEquivalentTo(p));

                foreach (var t in types)
                {
                    PermutationChromosome.ICrossOverStrategy crossoverStrategy
                        = (PermutationChromosome.ICrossOverStrategy)t.GetConstructor(Type.EmptyTypes).Invoke(null);
                    crossoverStategies.Add(crossoverStrategy);
                }
                this.crossoverAlgorithmComboBox.DataSource = crossoverStategies;
            }
            {
                mutationStategies = new List<Object>();
                var type = typeof(PermutationChromosome.IMutationStrategy);
                var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                    .SelectMany(s => s.GetTypes())
                    .Where(p => type.IsAssignableFrom(p) && !type.IsEquivalentTo(p));

                foreach (var t in types)
                {
                    PermutationChromosome.IMutationStrategy mutationStrategy
                        = (PermutationChromosome.IMutationStrategy)t.GetConstructor(Type.EmptyTypes).Invoke(null);
                    mutationStategies.Add(mutationStrategy);
                }
                this.mutationAlgorithmComboBox.DataSource = mutationStategies;
            }

            this.Text = "Algorytmów genetycznych na przykładzie problemu komiwojażera";

            Double INF = Double.PositiveInfinity;

            // Miasta - odleglości miedzy miastami.
            costMatrix = new Double[,]
            {
                { INF,    304.0,  486.0,  584.0,  341.0},   //Gdansk
                { 304.0,  INF,    280.0,  403.0,  304.0},    //poznan
                { 486.0,  280.0,  INF,    304.0,  341.0},  //wrocla
                { 584.0,  403.0,  304.0,  INF,    299},      //krakow
                { 341.0,  304,    341.0,  299,    INF},        //warszawa
            };

            InsertData(costMatrix);

            /*
             * Utwórz background workera dla asynchronicznego przetwarzania.
             */
            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
            worker.WorkerReportsProgress = true;
            worker.DoWork += new DoWorkEventHandler((Object sender, DoWorkEventArgs args) =>
                {
                    worker.ReportProgress(1);
                    while (population.NextGeneration() && !worker.CancellationPending)
                    {
                        if (population.Generation % 1000 == 0)
                        {
                            worker.ReportProgress((Int32)population.Generation);
                        }
                    }
                    worker.ReportProgress((Int32)population.Generation);
                });
            worker.ProgressChanged += new ProgressChangedEventHandler((Object sender, ProgressChangedEventArgs args) =>
                {
                    progressLabel.Text = "Iteracja: " + args.ProgressPercentage;

                    if (showAllCheckbox.Checked && stopCondition.Leader != null)
                    {
                        textBox1.AppendText("Najlepsze dopasowanie: " + (1.0 / stopCondition.Leader.Evaluate()) + Environment.NewLine);
                        textBox1.AppendText(stopCondition.Leader.ToString() + Environment.NewLine);
                    }
                });
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((Object sender, RunWorkerCompletedEventArgs args) =>
                {
                    textBox1.AppendText("Najlepsze dopasowanie: " + (1.0 / stopCondition.Leader.Evaluate()) + Environment.NewLine);
                    textBox1.AppendText(stopCondition.Leader.ToString() + Environment.NewLine);
                    startProcessingButton.Text = "Start";
                    TimeStop = DateTime.Now;
                    TimeSpan roznica = TimeStop - TimeStart;
                    textBox1.AppendText("Czas pracy: " + roznica.TotalMilliseconds + "ms" + Environment.NewLine);
                    textBox1.AppendText("====================" + Environment.NewLine);
                });
        }
Пример #43
0
        public void fuzzyCMeans()
        {
            P = new Double[maxIter];
            P[0] = 0;
            cltr = Decimal.ToInt32(clusterSizeNUD.Value);
            ctr = 1;
            V = new Double[cltr, 3];

            command = new SqlCommand();
            query = "SELECT * FROM customer order by CID";
            sqlConnection();
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            command.Connection = sqlCon;
            sa = new SqlDataAdapter(command);
            dt = new DataTable();
            sa.Fill(dt);
            custCltr = new int[dt.Rows.Count];
            r = new Double[cltr, 2];
            f = new Double[cltr, 2];
            m = new Double[cltr, 2];
            segmentD = new Dictionary<String, String>{{"Superstar","1"},{"Golden","2"},{"Typical","3"},{"Occasional","4"},
                {"Everyday","5"},{"Dormant","6"}};

            rfmd = new Dictionary<String, String>{
                {"000","Dormant Customer 18"},{"010","Dormant Customer 12"},{"020","Dormant Customer 6"},{"030","Dormant Customer 3"},
                {"001","Dormant Customer 17"},{"011","Dormant Customer 11"},{"021","Dormant Customer 5"},{"031","Dormant Customer 2"},
                {"002","Dormant Customer 16"},{"012","Dormant Customer 10"},{"022","Dormant Customer 4"},{"032","Dormant Customer 1"},
                {"003","Occasional Customer 14"},{"013","Occasional Customer 13"},{"023","Golden Customer 8"},{"033","Golden Customer 7"},
                {"004","Occasional Customer 12"},{"014","Occasional Customer 11"},{"024","Superstar 8"},{"034","Superstar 7"},
                {"100","Dormant Customer 15"},{"110","Dormant Customer 9"},{"120","Everyday Shopper 18"},{"130","Everyday Shopper 17"},
                {"101","Dormant Customer 14"},{"111","Dormant Customer 8"},{"121","Everyday Shopper 16"},{"131","Everyday Shopper 15"},
                {"102","Dormant Customer 13"},{"112","Dormant Customer 7"},{"122","Everyday Shopper 14"},{"132","Everyday Shopper 13"},
                {"103","Occasional Customer 10"},{"113","Occasional Customer 9"},{"123","Golden Customer 6"},{"133","Golden Customer 5"},
                {"104","Occasional Customer 8"},{"114","Occasional Customer 7"},{"124","Superstar 6"},{"134","Superstar 5"},
                {"200","Typical Customer 14"},{"210","Typical Customer 13"},{"220","Everyday Shopper 12"},{"230","Everyday Shopper 11"},
                {"201","Typical Customer 12"},{"211","Typical Customer 11"},{"221","Everyday Shopper 10"},{"231","Everyday Shopper 9"},
                {"202","Occasional Customer 6"},{"212","Occasional Customer 5"},{"222","Everyday Shopper 8"},{"232","Everyday Shopper 7"},
                {"203","Occasional Customer 4"},{"213","Occasional Customer 3"},{"223","Golden Customer 4"},{"233","Golden Customer 3"},
                {"204","Occasional Customer 2"},{"214","Occasional Customer 1"},{"224","Superstar 4"},{"234","Superstar 3"},
                {"300","Typical Customer 10"},{"310","Typical Customer 9"},{"320","Everyday Shopper 6"},{"330","Everyday Shopper 5"},
                {"301","Typical Customer 8"},{"311","Typical Customer 7"},{"321","Everyday Shopper 4"},{"331","Everyday Shopper 3"},
                {"302","Typical Customer 6"},{"312","Typical Customer 5"},{"322","Everyday Shopper 2"},{"332","Everyday Shopper 1"},
                {"303","Typical Customer 4"},{"313","Typical Customer 3"},{"323","Golden Customer 2"},{"333","Golden Customer 1"},
                {"304","Typical Customer 2"},{"314","Typical Customer 1"},{"324","Superstar 2"},{"334","Superstar 1"},};

            //RFM criteria value input to array\\
            rfmc = new int[3, 8];
            rfmc[0, 0] = Convert.ToInt32(recQLTlow.Text);
            rfmc[0, 1] = Convert.ToInt32(recRCNThigh.Text);
            rfmc[0, 2] = Convert.ToInt32(recLTlow.Text);
            rfmc[0, 3] = Convert.ToInt32(recQLThigh.Text);
            rfmc[0, 4] = Convert.ToInt32(recLTA.Text);
            rfmc[0, 5] = Convert.ToInt32(recLThigh.Text);

            rfmc[1, 0] = Convert.ToInt32(freRlow.Text);
            rfmc[1, 1] = Convert.ToInt32(freVRhigh.Text);
            rfmc[1, 2] = Convert.ToInt32(freOlow.Text);
            rfmc[1, 3] = Convert.ToInt32(freRhigh.Text);
            rfmc[1, 4] = Convert.ToInt32(freVO.Text);
            rfmc[1, 5] = Convert.ToInt32(freOhigh.Text);

            rfmc[2, 0] = Convert.ToInt32(monLlow.Text + "000000");
            rfmc[2, 1] = Convert.ToInt32(monVLhigh.Text + "000000");
            rfmc[2, 2] = Convert.ToInt32(monMlow.Text + "000000");
            rfmc[2, 3] = Convert.ToInt32(monLhigh.Text + "000000");
            rfmc[2, 4] = Convert.ToInt32(monHlow.Text + "000000");
            rfmc[2, 5] = Convert.ToInt32(monMhigh.Text + "000000");
            rfmc[2, 6] = Convert.ToInt32(monVH.Text + "000000");
            rfmc[2, 7] = Convert.ToInt32(monHhigh.Text + "000000");

            //Random number generation\\
            u = new Double[dt.Rows.Count, cltr];
            for (int k = 0; k < cltr; k++)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    u[i, k] = rnd.NextDouble();
                }
            }

            //Fuzzy C-Means Method\\
            do
            {
                //Cluster Centroid Function\\
                for (int k = 0; k < cltr; k++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            temp1 += Math.Pow(u[i, k], w);
                            temp2 += Math.Pow(u[i, k], w) * X[i, j];
                        }
                        V[k, j] = temp2 / temp1;
                        temp1 = 0;
                        temp2 = 0;
                    }
                }

                //Objective Function\\
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int k = 0; k < cltr; k++)
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            temp3 += Math.Pow(X[i, j] - V[k, j], w);
                        }
                        temp4 += temp3 * Math.Pow(u[i, k], 2);
                        temp3 = 0;
                    }
                }
                P[ctr] += temp4;
                temp4 = 0;

                //Membership Degree Function\\
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    temp10 = 0;
                    for (int k = 0; k < cltr; k++)
                    {
                        for (int k2 = 0; k2 < cltr; k2++)
                        {
                            for (int j = 0; j < 3; j++)
                            {
                                temp5 += Math.Pow(X[i, j] - V[k, j], w);
                                temp6 += Math.Pow(X[i, j] - V[k2, j], w);
                            }
                            temp7 = Math.Pow(temp5, -1);
                            temp8 = Math.Pow(temp6, -1);
                            temp9 += temp8;
                            temp5 = 0;
                            temp6 = 0;
                        }
                        u[i, k] = temp7 / temp9;
                        if (temp10 < u[i, k])
                        {
                            temp10 = u[i, k];
                            custCltr[i] = k;
                        }
                        temp7 = 0;
                        temp8 = 0;
                        temp9 = 0;
                    }
                }
                if (ctr == 3)
                {
                    createChart(winChartViewer1, 1);
                }
                if (ctr % 50 == 0)
                {
                    createChart(winChartViewer1, 1);
                }
                ctr++;
            } while (ctr < maxIter && Math.Abs((P[ctr - 1] - P[ctr - 2])) > tc);
            createChart(winChartViewer1, 1);
            MPC(PC());
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                temp1 = 0;
                for (int k = 0; k < cltr; k++)
                {
                    if (temp1 < u[i, k])
                    {
                        temp1 = u[i, k];
                        custCltr[i] = k;
                    }
                }
            }
        }
Пример #44
0
 /// <summary>
 ///     Prepares the data before training.
 /// </summary>
 public virtual void PrepareData()
 {
     _SequenceCount = ((_WorkingDataset[0].GetLength(0) - _PortionOfDatasetReserved) - _WindowWidth) - _DistanceToForcastHorrison;
     Int32 inputCount = _InputNodes.Count;
     Int32 outputCount = _OutputNodes.Count;
     _InputSequences = new Double[_SequenceCount, _WindowWidth, inputCount];
     _ExpectedOutputs = new Double[_SequenceCount, outputCount];
     for (Int32 i = 0; i < _SequenceCount; i++)
     {
         for (Int32 j = 0; j < _WindowWidth; j++)
         {
             for (Int32 k = 0; k < inputCount; k++) _InputSequences[i, j, k] = _WorkingDataset[k][i + j];
             for (Int32 l = 0; l < outputCount; l++) _ExpectedOutputs[i, l] = _WorkingDataset[l][i + j + _DistanceToForcastHorrison];
         }
     }
 }
Пример #45
0
        //把数据从UI读取到中间文件
        private void readUItoArray()
        {
            //清空字典
            plate_info = new Dictionary<string, string>();
            //重新初始化中间数组
            tpl = new Info[8, 12];
            od = new double[8, 12];
            //string[,] odStr = new string[8, 12];//使用字符数组更好?

            //读取文件到中间数组
            //合法性检测
            if (this.textName.Text.Trim() == null)
            {
                MessageBox.Show("请输入项目名称!", "系统提示");
                return;
            }
            if (this.txtUnit.Text.Trim() == null)
            {
                MessageBox.Show("请输入单位名称!", "系统提示");
                return;
            }

            //基本信息-》中间数据
            plate_info["SaveTime"] = DateTime.Now.ToString();//保存文件时的时间
            plate_info["Name"] = this.textName.Text.Trim();
            plate_info["Lot"] = this.textLot.Text.Trim();
            plate_info["LabDate"] = this.dateTimePicker1.Text.Trim();
            plate_info["Unit"] = this.txtUnit.Text.Trim();
            plate_info["Notice"] = "不要随意更改文件内容,否则再次读取时将发生错误。";
            plate_info["Curve"] = this.getRadioIndex().ToString();//拟合的模型编号

            //tpl-》中间数据
            DataReadWrite drw = new DataReadWrite();
            //从UI读取到中间数组
            tpl = drw.readFromUI(this.dataGridView0, true);
            od = drw.readFromUI(this.dataGridView1);
        }
        /// <summary>
        ///   Construct an eigenvalue decomposition.</summary>
        ///
        /// <param name="value">
        ///   The matrix to be decomposed.</param>
        /// <param name="assumeSymmetric">
        ///   Defines if the matrix should be assumed as being symmetric
        ///   regardless if it is or not. Default is <see langword="false"/>.</param>
        /// <param name="inPlace">
        ///   Pass <see langword="true"/> to perform the decomposition in place. The matrix
        ///   <paramref name="value"/> will be destroyed in the process, resulting in less
        ///   memory comsumption.</param>
        /// <param name="sort">
        ///   Pass <see langword="true"/> to sort the eigenvalues and eigenvectors at the end
        ///   of the decomposition.</param>
        ///
        public EigenvalueDecomposition(Double[,] value, bool assumeSymmetric,
            bool inPlace = false, bool sort = false)
        {
            if (value == null)
                throw new ArgumentNullException("value", "Matrix cannot be null.");

            if (value.GetLength(0) != value.GetLength(1))
                throw new ArgumentException("Matrix is not a square matrix.", "value");

            n = value.GetLength(1);
            V = new Double[n, n];
            d = new Double[n];
            e = new Double[n];


            this.symmetric = assumeSymmetric;

            if (this.symmetric)
            {
                V = inPlace ? value : (Double[,])value.Clone();

                // Tridiagonalize.
                this.tred2();

                // Diagonalize.
                this.tql2();
            }
            else
            {
                H = inPlace ? value : (Double[,])value.Clone();

                ort = new Double[n];

                // Reduce to Hessenberg form.
                this.orthes();

                // Reduce Hessenberg to real Schur form.
                this.hqr2();
            }

            if (sort)
            {
                // Sort eigenvalues and vectors in descending order
                var idx = Vector.Range(n);
                Array.Sort(idx, (i, j) => 
                {
                    if (Math.Abs(d[i]) == Math.Abs(d[j]))
                        return -Math.Abs(e[i]).CompareTo(Math.Abs(e[j]));
                    return -Math.Abs(d[i]).CompareTo(Math.Abs(d[j]));
                });

                this.d = this.d.Get(idx);
                this.e = this.e.Get(idx);
                this.V = this.V.Get(null, idx);
            }
        }