예제 #1
0
        public void GrayScaleImageTest(ImageData imageData)
        {
            byte[] a = Convert.FromBase64String(imageData.Base64);
            //MemoryStream memoryStream = new MemoryStream(a);
            //Image image = System.Drawing.Image.FromStream(memoryStream);
            Analyse        z = new Analyse();
            MWNumericArray mWNumericArray = a;
            MWArray        I     = z.analyseImage(mWNumericArray, imageData.CoordinateXY[0], imageData.CoordinateXY[1]);
            MWNumericArray I_num = I.ToArray();

            Byte[] I_bytes = (Byte[])I_num.ToVector(MWArrayComponent.Real);

            int w = I.Dimensions[0];
            int h = I.Dimensions[1];

            Bitmap       bmp = new Bitmap(w, h, PixelFormat.Format8bppIndexed);
            ColorPalette cp  = bmp.Palette;

            for (Int32 i = 0; i < 256; ++i)
            {
                cp.Entries[i] = Color.FromArgb(255, i, i, i);
            }

            bmp.Palette = cp;

            BitmapData data = bmp.LockBits((new Rectangle(0, 0, bmp.Width, bmp.Height)), ImageLockMode.WriteOnly, bmp.PixelFormat);

            Marshal.Copy(I_bytes, 0, data.Scan0, I_bytes.Length);
            bmp.UnlockBits(data);
            bmp.Save("image.png", ImageFormat.Png);
        }
예제 #2
0
        draw drawtest = new draw();//创建类 draw 的实例


        private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog d = new OpenFileDialog();

            d.Filter = "(*.mat)|*.mat|所有文件(*.*)|*.*"; if (d.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = File.OpenRead(d.FileName); StreamReader sr = new StreamReader(fs); string s;
                string     filename = d.FileName;
                d1 = pcl.loaddata(filename);
                // MessageBox.Show(filename);
                MWArray[] agrsIn = new MWArray[] { d1 };  
                pcl.pces(4, ref agrsOut, agrsIn);

                MWNumericArray x1 = agrsOut[0] as MWNumericArray;
                MWNumericArray x2 = agrsOut[1] as MWNumericArray;
                MWNumericArray x3 = agrsOut[2] as MWNumericArray;
                MWNumericArray x4 = agrsOut[3] as MWNumericArray;
                rbegin        = (double[, ])x1.ToArray();
                pend          = (double[, ])x2.ToArray();
                rpk           = (double[, ])x3.ToArray();
                f1            = (double[, ])d1.ToArray();
                qt_mean       = x4.ToScalarDouble();
                textBox4.Text = qt_mean.ToString();
                for (int i = 0; i < 12000; i++)
                {
                    data[i].X = (int)i;//强制类型转换,将double转为int,可能会丢失数据
                    data[i].Y = (int)((1000 - f1[0, i *5]) * 250 / 4500 + 100);
                }
                this.timer1.Enabled  = true; //可以使用
                this.timer1.Interval = 100;  //定时时间为100毫秒
                this.timer1.Tick    += new System.EventHandler(this.timer1_Tick);

                this.timer1.Start();//启动定时器
            }
        }
예제 #3
0
파일: Tools.cs 프로젝트: tum-i4/Aletheia
        /// <summary>
        /// creates 2D array from Matlab MW array
        /// </summary>
        /// <param name="mwArray">Matlab MW array</param>
        /// <returns></returns>
        public static double[,] buildTwoDimensionalDoubleArrayFromMWArray(MWArray mwArray)
        {
            Array tmpArray = mwArray.ToArray();

            int rank = tmpArray.Rank;

            int[] dimension = new int[rank];


            for (int i = 0; i < rank; i++)
            {
                dimension[i] = tmpArray.GetLength(i);
            }

            double[,] doubleArray = new double[dimension[0], dimension[1]];

            for (int i = 0; i < dimension[0]; i++)
            {
                for (int j = 0; j < dimension[1]; j++)
                {
                    doubleArray[i, j] = (double)tmpArray.GetValue(i, j);
                }
            }

            return(doubleArray);
        }
예제 #4
0
파일: Tools.cs 프로젝트: tum-i4/Aletheia
        /// <summary>
        /// converts MatLab MW array to C# compatible jagged array
        /// </summary>
        /// <param name="mwArray">Matlab MW array</param>
        /// <returns></returns>
        public static double[][] buildJaggedDoubleArrayFromMWArray(MWArray mwArray)
        {
            Array tmpArray = mwArray.ToArray();

            int rank = tmpArray.Rank;

            int[] dimension = new int[rank];

            for (int i = 0; i < rank; i++)
            {
                dimension[i] = tmpArray.GetLength(i);
            }

            double[][] doubleArray = new double[dimension[0]][];

            for (int i = 0; i < dimension[0]; i++)
            {
                double[] tmpArrayLine = new double[dimension[1]];
                for (int j = 0; j < dimension[1]; j++)
                {
                    tmpArrayLine[j] = (double)tmpArray.GetValue(i, j);
                }
                doubleArray[i] = tmpArrayLine;
            }

            return(doubleArray);
        }
예제 #5
0
        public ActionResult GetEmployer(string[] sendforcalc)
        {
            var pop = 5;
            var gem = 10;
            var Pa  = 0.2;

            CalcTsp.Class1 calcTsp = new CalcTsp.Class1();
            double[]       list    = new double[20 * 3];
            int            i       = 0;

            foreach (var item in sendforcalc)
            {
                string[] arr = item.Split(' ');
                list[i]     = i / 3;
                list[i + 1] = double.Parse(arr[0]);
                list[i + 2] = double.Parse(arr[1]);
                i           = i + 3;
            }
            MWNumericArray array     = new MWNumericArray(20, 3, list);
            MWArray        resultObj = calcTsp.CalcTsp(array, pop, Pa, gem);
            Array          a         = resultObj.ToArray();
            var            numa      = a.GetValue(0, 0);
            var            aaaaa     = numa.ToString();
            int            num       = int.Parse(aaaaa);

            return(Json(num, JsonRequestBehavior.AllowGet));
        }
예제 #6
0
        public void CalDistrubtionProcess_Prev(double[] dwx, double[] dwvelo, string folderPath, string fileName)
        {
            MWNumericArray wx = new MWNumericArray(dwx);

            Array.Clear(dwx, 0, dwx.Length);
            MWNumericArray wvelo = new MWNumericArray(dwvelo);

            Array.Clear(dwvelo, 0, dwvelo.Length);

            MWArray resultMW    = anc.sub_calculate_distrubtion_with_one_output(wx, wvelo);
            Array   resultArray = resultMW.ToArray();
            int     count       = resultArray.Length / 3;

            double[] d1 = new double[count];
            double[] d2 = new double[count];
            double[] d3 = new double[count];

            double[,] resultArray_A = (double[, ])resultArray;

            for (int i = 0; i < count; i++)
            {
                d1[i] = resultArray_A[i, 0];
                d2[i] = resultArray_A[i, 1];
                d3[i] = resultArray_A[i, 2];
            }

            CreateExcel(d1, d2, d3, folderPath, fileName);
        }
예제 #7
0
        //private string FromChars(char[,] chars)
        //{
        //    string str = "";
        //    char c;
        //    for (int i = 0; i < chars.GetLength(0); i++)
        //    {
        //        for (int j = 0; j < chars.GetLength(1); j++)
        //        {
        //            c = chars[i, j];
        //            if (chars[i, j] == '"')
        //                str += "\"";
        //             else
        //                 str += chars[i, j];
        //        }
        //    }
        //    return str;
        //}


        public char[] Encrypt(string plaintext)
        {
            MWArray ciphertext = (MWArray)this.aesMatObj.AESEncrypt((MWArray)plaintext, CipherKey, SboxDec, Rcon, MatMixCol);

            char[,] ctchars = (char[, ])ciphertext.ToArray();
            char[] chars = MatricesFactory.To1D(ctchars);

            return(chars);
        }
예제 #8
0
        public char[] Decrypt(char[] ciphertext)
        {
            double[] ciphervector = BitManipulator.CharToDouble(ciphertext);
            //MWArray[] mw = this.aesMatObj.AESDecrypt(2, (MWNumericArray)(MatricesFactory.To2D(ciphervector)), CipherKey, SboxDec, SboxInv, Rcon, MatMixColInv);
            //MWNumericArray mn = (MWNumericArray)mw[1];
            MWArray plaintext = (MWArray)this.aesMatObj.AESDecrypt((MWNumericArray)(MatricesFactory.To2D(ciphervector)), CipherKey, SboxDec, SboxInv, Rcon, MatMixColInv);

            char[,] plaintextchars = (char[, ])plaintext.ToArray();

            return(MatricesFactory.To1D(plaintextchars));
        }
예제 #9
0
        public void CalDistrubtionProcess(double[] dwx, double[] dwvelo, string folderPath, string fileName, double rmsMean, string fileName_tii)
        {
            MWNumericArray wx = new MWNumericArray(dwx);

            Array.Clear(dwx, 0, dwx.Length);
            MWNumericArray wvelo = new MWNumericArray(dwvelo);

            Array.Clear(dwvelo, 0, dwvelo.Length);

            //MWArray resultMW = anc.sub_calculate_distrubtion_with_one_output(wx, wvelo);
            MWArray resultMW    = anc.sub_calculate_rms_distrubtion(wx, wvelo);
            Array   resultArray = resultMW.ToArray();

            int count = resultArray.Length / 3;

            double[] d1 = new double[count];
            double[] d2 = new double[count];
            double[] d3 = new double[count];

            double[,] resultArray_A = (double[, ])resultArray;

            for (int i = 0; i < count; i++)
            {
                d1[i] = resultArray_A[i, 0];
                d2[i] = resultArray_A[i, 1];
                d3[i] = resultArray_A[i, 2];
            }

            MWArray resultMW_tii    = anc.sub_calculate_tii_distrubtion(wx, wvelo, rmsMean);
            Array   resultArray_tii = resultMW_tii.ToArray();

            int count_tii = resultArray_tii.Length / 3;

            double[] d1_tii = new double[count_tii];
            double[] d2_tii = new double[count_tii];
            double[] d3_tii = new double[count_tii];

            double[,] resultArray_A_tii = (double[, ])resultArray_tii;

            for (int i = 0; i < count_tii; i++)
            {
                d1_tii[i] = resultArray_A_tii[i, 0];
                d2_tii[i] = resultArray_A_tii[i, 1];
                d3_tii[i] = resultArray_A_tii[i, 2];
            }

            CreateExcel(d1, d2, d3, folderPath, fileName);

            CreateExcel(d1_tii, d2_tii, d3_tii, folderPath, fileName_tii);
        }
예제 #10
0
        public void FromMatlabArray(MWArray data)
        {
            var k = data.ToArray();

            for (int i = 0; i < k.GetLength(0); i++)
            {
                for (int j = 0; j < k.GetLength(1); j++)
                {
                    object a = k.GetValue(i, j);
                    byte   b = (byte)a;
                    Pixel  p = new Pixel((int)b, (int)b, (int)b, 255);
                    SetPixel(j, i, p);
                }
            }
        }
        /// <summary>
        /// 自动对齐
        /// </summary>
        /// <param name="ww">输入参考波形1的数据</param>
        ///WW(1,:):左高低
        ///WW(2,:):右高低
        ///WW(3,:):左轨向
        ///WW(4,:):右轨向
        ///WW(5,:):轨距------(总共5列数据)
        /// <param name="ww1">参考波形2的数据</param>
        /// <returns>移动的点数</returns>
        /// 备注:波形1不动,波形2减去点数
        ///       波形2不动,波形1加上点数
        public int AutoTranslation(float[][] ww, float[][] ww1)
        {
            int retVal = 0;

            int            rowLen_ww = ww.GetLength(0);
            int            colLen_ww = ww[0].Length;
            MWNumericArray d_ww      = new MWNumericArray(MWArrayComplexity.Real, rowLen_ww, colLen_ww);

            //matlab中矩阵的下标是从1开始的,而C#是从0开始的
            for (int i = 0; i < rowLen_ww; i++)
            {
                for (int j = 0; j < colLen_ww; j++)
                {
                    d_ww[i + 1, j + 1] = ww[i][j];
                }
            }

            int            rowLen_ww1 = ww1.GetLength(0);
            int            colLen_ww1 = ww1[0].Length;
            MWNumericArray d_ww1      = new MWNumericArray(MWArrayComplexity.Real, rowLen_ww1, colLen_ww1);

            //matlab中矩阵的下标是从1开始的,而C#是从0开始的
            for (int i = 0; i < rowLen_ww1; i++)
            {
                for (int j = 0; j < colLen_ww1; j++)
                {
                    d_ww1[i + 1, j + 1] = ww1[i][j];
                }
            }

            try
            {
                //调用算法
                MWArray resultArray = ppmc.sub_preprocessing_alignment_data(d_ww, d_ww1);
                //MWArray resultArray = null;
                double[,] tmpArray = (double[, ])(resultArray.ToArray());

                retVal = (int)tmpArray[0, 0];
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            return(retVal);
        }
예제 #12
0
        public Image Apply(Image img)
        {
            MWArray arr = m_assets.ConnectedComponent(img.ToSingleMatlabArray());
            var     d   = arr.ToArray();

            Elements = new CCElement[d.GetLength(0)];
            for (int i = 0; i < d.GetLength(0); i++)
            {
                var ooo = d.GetValue(i, 0);
                Elements[i].Center_X = (double)ooo;

                ooo = d.GetValue(i, 1);
                Elements[i].Center_Y = (double)ooo;

                ooo = d.GetValue(i, 2);
                Elements[i].Area = (double)ooo;
            }
            return(img);
        }
예제 #13
0
파일: Tools.cs 프로젝트: tum-i4/Aletheia
        /// <summary>
        /// convert Matlab MW array to one dimentional integer array
        /// </summary>
        /// <param name="mwArray">Matlab MW array</param>
        /// <returns></returns>
        public static int[] buildOneDimensionalIntArray(MWArray mwArray)
        {
            Array tmpArray = mwArray.ToArray();

            int rank = tmpArray.Rank;

            int[] dimension = new int[rank];

            for (int i = 0; i < rank; i++)
            {
                dimension[i] = tmpArray.GetLength(i);
            }

            int[] intArray = new int[dimension[0]];

            for (int i = 0; i < dimension[0]; i++)
            {
                intArray[i] = Convert.ToInt32((double)tmpArray.GetValue(i, 0));
            }

            return(intArray);
        }
예제 #14
0
        // Generate the feature vector of the given image.
        public double[] GenerateFeature(short[,] pixelData)
        {
            // Initialize the parameters of feature (data).
            MWStructArray fea_first = new MWStructArray(1, 1, new string[] { "pixels", "maxsize" });

            fea_first.SetField("pixels", new MWNumericArray(pixelData));
            fea_first.SetField("maxsize", 75);

            // Initialize the parameters of dictionary.
            MWStructArray dic_first = new MWStructArray(1, 1, new string[] { "dicsize", "patchsize", "samplenum", "dic" });

            dic_first.SetField("dicsize", 200);
            dic_first.SetField("patchsize", 16);
            dic_first.SetField("samplenum", 100);
            MWArray array = new MWNumericArray(this.dict_dimension[0], this.dict_dimension[1], MatrixUtil.FlattenMatrix(this.dic, this.dict_dimension[0], this.dict_dimension[1]));

            dic_first.SetField("dic", array);

            // Orthogonal matching pursuit encoder
            Stopwatch ompTimer = Stopwatch.StartNew();

            MWArray rgbdfea = ompNormal.extract_feature_normal(fea_first, dic_first);

            ompTimer.Stop();

            Array feature = rgbdfea.ToArray();

            Console.WriteLine("Feature Extraction Time: {0} ms", ompTimer.ElapsedMilliseconds);

            double[] feature_vector = new double[feature.Length];
            for (int i = 0; i < feature.Length; i++)
            {
                feature_vector[i] = System.Convert.ToDouble(feature.GetValue(i, 0));
            }

            return(feature_vector);
        }
예제 #15
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        /// <summary>
        /// ���������� �����ϰ� �⺻ ���ļ������� ���
        /// </summary>
        private void CalcFrequency()
        {
            //double Resolution;
            int MaxPoint = 0;

            // Sampled
            Resolution = (double)Frequency.GetData(4) - (double)Frequency.GetData(3);

            InitFre = (int)Math.Round(300/Resolution);
            MaxFre = (int)Math.Round(6400/Resolution);

            double[] FrequencySampled = new double[(int)(MaxFre-InitFre)];
            double[] MAbsorptionSampled = new double[(int)(MaxFre-InitFre)];
            MRealSurfaceImpedanceSampled = new double[(int)(MaxFre-InitFre)];
            MlmagSurfaceImpedanceSampled = new double[(int)(MaxFre-InitFre)];

            double[] FrequencyFitted = new double[32];
            //			double[] MAbsorptionFitted = new double[32];
            //			double[] MSurfaceImpedanceFitted = new double[32];

            FrequencySampled[0] = 0;
            MAbsorptionSampled[0] = 0;

            for (int i=1;i<(MaxFre-InitFre);i++)
            {
                FrequencySampled[i] = Frequency.GetData(InitFre + i-1);
                MAbsorptionSampled[i] = MAbsorption.GetData(InitFre + i-1);
            }

            for (int i=1;i<33;i++)
            {
                FrequencyFitted[i-1] = i*200;
            }

            //MeritCalcClass.polyfitting(FrequencyFitted, FrequencySampled, MAbsorptionSampled, 13);  //INSUNG
            m_Out = MeritCalcClass.PolyFitting((MWNumericArray)MAbsorptionSampled, (MWNumericArray)FrequencyFitted, (MWNumericArray)FrequencySampled, 13);
            //m_Out = MeritCalcClass.PolyFitting(

            m_DataFitted = (double[,])m_Out.ToArray();

            //			MAbsorptionFitted = ((Array)MeritCalcClass.DataFitted).;

            long[] temp = new long[2];
            temp[0] = 1;
            temp[1] = 1;

            for (int i=1;i<33;i++)
            {
                TempFrequency[i-1] = FrequencyFitted[i-1];
                temp[1] = i;
                TempMAbsorption[i - 1] = (double)m_DataFitted.GetValue(0, temp[1]);
            }

            if (MRealSurfaceImpedance.GetCount()>0)
            {
                MRealSurfaceImpedanceSampled[0] = 0;
                for (int i=1;i<(MaxFre-InitFre);i++)
                {
                    MRealSurfaceImpedanceSampled[i] = MRealSurfaceImpedance.GetData(InitFre + i-1);
                }

                //MeritCalcClass.polyfitting(FrequencyFitted, FrequencySampled, MRealSurfaceImpedanceSampled, 13); //INSUNG
                m_Out = MeritCalcClass.PolyFitting((MWNumericArray)MRealSurfaceImpedanceSampled, (MWNumericArray)FrequencyFitted, (MWNumericArray)FrequencySampled, 13);
                m_DataFitted = (double[,])m_Out.ToArray();

                //				MSurfaceImpedanceFitted = (double[])MeritCalcClass.DataFitted;

                for (int i=1;i<33;i++)
                {
                    temp[1] = i;
                    TempMRealSurfaceImpedance[i - 1] = (double)m_DataFitted.GetValue(0, temp[1]);
                }
            }

            if (MImagSurfaceImpedance.GetCount()>0)
            {
                MlmagSurfaceImpedanceSampled[0] = 0;
                for (int i=1;i<(MaxFre-InitFre);i++)
                {
                    MlmagSurfaceImpedanceSampled[i] = MImagSurfaceImpedance.GetData(InitFre + i-1);
                }

                //MeritCalcClass.polyfitting(FrequencyFitted, FrequencySampled, MlmagSurfaceImpedanceSampled, 13);  //INSUNG
                MeritCalcClass.PolyFitting((MWNumericArray)MlmagSurfaceImpedanceSampled, (MWNumericArray)FrequencyFitted, (MWNumericArray)FrequencySampled, 13);
                m_DataFitted = (double[,])m_Out.ToArray();
                //				MSurfaceImpedanceFitted = (double[])MeritCalcClass.DataFitted;

                for (int i=1;i<33;i++)
                {
                    temp[1] = i;
                    TempMImagSurfaceImpedance[i - 1] = (double)m_DataFitted.GetValue(0, temp[1]);
                }
            }

            MaxPoint = GetMaxPoint(TempMAbsorption) + 1;

            SetFreq(1, MaxPoint, 32);
        }
예제 #16
0
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                string methodName = args[0];//方法名称
                Class1 C          = null;

                #region 水文曲线
                if (methodName == MethodName.SWCure)
                {
                    try
                    {
                        C = new Class1();
                        //删除文件
                        string filePath = Path.Combine(Application.StartupPath, ConfigNames.SvCure);
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                        double[,] CC = (double[, ])C.miaodian().ToArray();
                        Console.WriteLine("Cv:" + CC[0, 0]);
                        Console.WriteLine("Cs:" + CC[0, 1]);
                        Console.WriteLine("X:" + CC[0, 2]);
                        Console.WriteLine("Nihe:" + CC[0, 3]);
                        XmlHelper.Serialize <CvCure>(new CvCure()
                        {
                            Cv   = CC[0, 0],
                            Cs   = CC[0, 1],
                            X    = CC[0, 2],
                            Nihe = CC[0, 3].ToString()
                        }, filePath);
                        Console.ReadKey();  //不直接关闭
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (C != null)
                        {
                            C.Dispose();
                        }
                    }
                }
                #endregion

                #region 拟合曲线

                else if (methodName == MethodName.NiHeCure)
                {
                    try
                    {
                        double         X   = Convert.ToDouble(args[1]);
                        MWNumericArray XX  = new MWNumericArray(X);
                        double         Cv  = Convert.ToDouble(args[2]);
                        MWNumericArray Cvv = new MWNumericArray(Cv);
                        double         Cs  = Convert.ToDouble(args[3]);
                        MWNumericArray Css = new MWNumericArray(Cs);
                        C = new Class1();
                        double[,] Nihe = (double[, ])C.peixian(Cvv, Css, XX).ToArray();
                        Console.WriteLine("Nihe:" + Nihe[0, 0]);
                        XmlHelper.Serialize <string>(Nihe[0, 0].ToString(), Path.Combine(Application.StartupPath, ConfigNames.TempName));
                        C.Dispose();
                        Console.ReadKey();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (C != null)
                        {
                            C.Dispose();
                        }
                    }
                }

                #endregion

                #region 曲线反查

                else if (methodName == MethodName.ResearchCure)
                {
                    double         X   = Convert.ToDouble(args[1]);
                    MWNumericArray XX  = new MWNumericArray(X);
                    double         Cv  = Convert.ToDouble(args[2]);
                    MWNumericArray Cvv = new MWNumericArray(Cv);
                    double         Cs  = Convert.ToDouble(args[3]);
                    MWNumericArray Css = new MWNumericArray(Cs);
                    //反查类型 c1-根据概率查值,c2-根据值查询概率,c3-查询时间段内所有内定概率
                    string type = args[4].Split('-')[0];
                    if (type == "c1")
                    {
                        double         k   = Convert.ToDouble(args[4].Split('-')[1]);
                        MWNumericArray kik = new MWNumericArray(k);
                        C = new Class1();
                        double[,] Xcha = (double[, ])C.chaxun1(Cvv, Css, XX, kik).ToArray();
                        Console.WriteLine(Xcha[0, 0]);
                    }
                    else if (type == "c2")
                    {
                        double         k   = Convert.ToDouble(args[4].Split('-')[1]);
                        MWNumericArray kik = new MWNumericArray(k);
                        C = new Class1();
                        double[,] Xcha = (double[, ])C.chaxun2(Cvv, Css, XX, kik).ToArray();
                        Console.WriteLine(Xcha[0, 0]);
                    }
                    // c3-站号-时间段
                    else if (type == "c3")
                    {
                        string state = args[4].Split('-')[1];
                        string time  = args[4].Split('-')[2];
                        //将时间段转换为小时
                        double during  = 0;
                        bool   success = CollectionCons.DicStrToHour.TryGetValue(time, out during);
                        if (success == false)
                        {
                            Console.WriteLine("参数错误");
                            return;
                        }
                        double value       = 0;
                        string commandText = string.Empty;
                        C = new Class1();
                        foreach (double item in CollectionCons.StaticsPercents)
                        {
                            try
                            {
                                MWNumericArray kik = new MWNumericArray(item);
                                double[,] Xcha = (double[, ])C.chaxun1(Cvv, Css, XX, kik).ToArray();
                                value          = Xcha[0, 0];
                                //先查询数据是否存在,存在更新,不存在新增
                                commandText = string.Format("SELECT * FROM [DB_RainMonitor].[dbo].[RAINFALL_PERCENT] where [PERCENT]={0} and During={1} and MONITORNUM='{2}'", item, during, state);
                                object obj = SqlHelper.ExecuteScalar(SqlHelper.GetConnSting(), System.Data.CommandType.Text, commandText);
                                if (obj == null)
                                {
                                    commandText = string.Format("insert into RAINFALL_PERCENT values(NEWID(),'{0}',{1},{2},{3},{4},{5},{6},{7},'{8}',{9})", state, "null", "null", "null", X, Cv, Cs, item, during, value);
                                }
                                else
                                {
                                    commandText = string.Format("update RAINFALL_PERCENT set [VALUE] = {0} where [PERCENT]={1} and During={2} and MONITORNUM='{3}'", value, item, during, state);
                                }
                                SqlHelper.ExecuteNonQuery(SqlHelper.GetConnSting(), System.Data.CommandType.Text, commandText);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("入库失败-" + ex.Message);
                                return;
                            }
                        }
                        Console.WriteLine("入库成功!");
                    }
                }

                #endregion

                #region 暴雨衰减

                else if (methodName == MethodName.RainStormSub)
                {
                    //参数值 1-小于一小时的时间段,2-小于一小时的值,3-大于一小时的时间段,4-大于一小时的值

                    List <double> list1   = new List <double>();
                    string[]      minHour = args[2].Split(',');
                    Array.ForEach(minHour, t =>
                    {
                        list1.Add(Convert.ToDouble(t));
                    });
                    MWNumericArray MatY1 = new MWNumericArray(list1.ToArray());
                    List <double>  list2 = new List <double>();
                    minHour = args[1].Split(',');
                    Array.ForEach(minHour, t =>
                    {
                        list2.Add(Convert.ToDouble(t));
                    });
                    MWNumericArray MatX1 = new MWNumericArray(list2.ToArray());
                    List <double>  list3 = new List <double>();
                    minHour = args[4].Split(',');
                    Array.ForEach(minHour, t =>
                    {
                        list3.Add(Convert.ToDouble(t));
                    });
                    MWNumericArray MatY2 = new MWNumericArray(list3.ToArray());
                    List <double>  list4 = new List <double>();
                    minHour = args[3].Split(',');
                    Array.ForEach(minHour, t =>
                    {
                        list4.Add(Convert.ToDouble(t));
                    });
                    MWNumericArray MatX2 = new MWNumericArray(list4.ToArray());
                    try
                    {
                        C = new Class1();
                        SubCure sub = new SubCure();
                        //删除文件
                        string filePath = Path.Combine(Application.StartupPath, ConfigNames.SubCure);
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                        MWArray polyData3 = C.polyfit_line(MatX1, MatY1);
                        MWArray polyData1 = C.polyfit_line(MatX1, MatY1);
                        MWArray polyData2 = C.polyfit_line(MatX2, MatY2);
                        double[,] DataBox1 = (double[, ])polyData1.ToArray();
                        double[,] DataBox2 = (double[, ])polyData2.ToArray();
                        double d = (Math.Abs(DataBox2[0, 0]) / Math.Abs(DataBox1[0, 0]) - 1) * 0.3;
                        sub.d = d;
                        double k1 = Math.Log10(10 + d);
                        double k2 = Math.Log10(0.1 + d);
                        double nd = Math.Abs((DataBox1[0, 0] + DataBox2[0, 0]) / (k1 - k2));
                        double Sd = (Math.Pow((10 + d), nd) / Math.Pow(10, Math.Abs(DataBox2[0, 0]))) * Math.Pow(10, DataBox2[0, 1]);
                        sub.nd = nd;
                        sub.Sd = Sd;
                        sub.n1 = DataBox1[0, 0];
                        sub.j1 = DataBox1[0, 1];
                        sub.n2 = DataBox2[0, 0];
                        sub.j2 = DataBox2[0, 1];
                        XmlHelper.Serialize <SubCure>(sub, filePath);
                        Console.ReadKey();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (C != null)
                        {
                            C.Dispose();
                        }
                    }
                }

                #endregion

                #region d=0

                else if (methodName == MethodName.RainStormSub0)
                {
                    //参数值 1-小于一小时的时间段,2-小于一小时的值,3-大于一小时的时间段,4-大于一小时的值

                    List <double> list1   = new List <double>();
                    string[]      minHour = args[2].Split(',');
                    Array.ForEach(minHour, t =>
                    {
                        list1.Add(Convert.ToDouble(t));
                    });
                    MWNumericArray MatY1 = new MWNumericArray(list1.ToArray());
                    List <double>  list2 = new List <double>();
                    minHour = args[1].Split(',');
                    Array.ForEach(minHour, t =>
                    {
                        list2.Add(Convert.ToDouble(t));
                    });
                    MWNumericArray MatX1 = new MWNumericArray(list2.ToArray());
                    try
                    {
                        C = new Class1();
                        //删除文件
                        string filePath = Path.Combine(Application.StartupPath, ConfigNames.SubCure0);
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                        MWArray polyData3 = C.polyfit_line(MatX1, MatY1);
                        MWArray polyData1 = C.polyfit_line(MatX1, MatY1);
                        double[,] DataBox1 = (double[, ])polyData1.ToArray();
                        SubCure sub = new SubCure();
                        double  nd  = Math.Abs(2 * (DataBox1[0, 0]) / (Math.Log(10) - Math.Log(0.1)));
                        double  Sd  = (Math.Pow(10, nd) / Math.Pow(10, Math.Abs(DataBox1[0, 0]))) * Math.Pow(10, DataBox1[0, 1]);
                        sub.nd = nd;
                        sub.Sd = Sd;
                        sub.n1 = DataBox1[0, 0];
                        sub.j1 = DataBox1[0, 1];
                        XmlHelper.Serialize <SubCure>(sub, filePath);
                        Console.ReadKey();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (C != null)
                        {
                            C.Dispose();
                        }
                    }
                }

                #endregion

                #region 洪峰流量

                else if (methodName == MethodName.FloodPeak)
                {
                    //p1,Qm,eps1,sd,R,d,nd,r1,F,L1,L2,I1,I2,A1,A2,tc,eps2,项目路径

                    MWNumericArray p1_0 = new MWNumericArray(Convert.ToDouble(args[1]));
                    //MWArray p1_0 = MWArray(p);
                    MWNumericArray Qm_0 = new MWNumericArray(Convert.ToDouble(args[2]));
                    //MWArray Qm_0 = MWArray(Q);
                    MWNumericArray eps = new MWNumericArray(Convert.ToDouble(args[3]));
                    //MWArray eps = MWArray(ee);
                    MWNumericArray sd = new MWNumericArray(Convert.ToDouble(args[4]));
                    //MWArray sd = MWArray(s);
                    MWNumericArray R = new MWNumericArray(Convert.ToDouble(args[5]));
                    //MWArray R = MWArray(RR);
                    MWNumericArray d = new MWNumericArray(Convert.ToDouble(args[6]));
                    //MWArray d = MWArray(dd);
                    MWNumericArray nd = new MWNumericArray(Convert.ToDouble(args[7]));
                    //MWArray nd = MWArray(ndd);
                    MWNumericArray r1 = new MWNumericArray(Convert.ToDouble(args[8]));
                    //MWArray r1 = MWArray(rr1);
                    MWNumericArray F = new MWNumericArray(Convert.ToDouble(args[9]));
                    //MWArray F = MWArray(FF);
                    MWNumericArray L1 = new MWNumericArray(Convert.ToDouble(args[10]));
                    //MWArray L1 = MWArray(LL1);
                    MWNumericArray L2 = new MWNumericArray(Convert.ToDouble(args[11]));
                    //MWArray L2 = MWArray(LL2);
                    MWNumericArray I1 = new MWNumericArray(Convert.ToDouble(args[12]));
                    //MWArray I1 = MWArray(II1);
                    MWNumericArray I2 = new MWNumericArray(Convert.ToDouble(args[13]));
                    //MWArray I2 = MWArray(II2);
                    MWNumericArray A1 = new MWNumericArray(Convert.ToDouble(args[14]));
                    //MWArray A1 = MWArray(AA1);
                    MWNumericArray A2 = new MWNumericArray(Convert.ToDouble(args[15]));
                    //MWArray A2 = MWArray(AA2);
                    MWNumericArray tc   = new MWNumericArray(Convert.ToDouble(args[16]));
                    MWNumericArray eps1 = new MWNumericArray(Convert.ToDouble(args[17]));
                    try
                    {
                        C = new Class1();
                        MainResult result = new MainResult();
                        //删除文件
                        if (File.Exists(args[18]))
                        {
                            File.Delete(args[18]);
                        }
                        MWArray A = C.fun_main(p1_0, Qm_0, eps, sd, R, d, nd, r1, F, L1, L2, I1, I2, A1, A2);
                        double[,] AA = (double[, ])A.ToArray();
                        result.Qm    = AA[0, 0];
                        result.p1    = AA[0, 1];
                        result.tQ    = AA[0, 2];
                        result.d1    = AA[0, 3];

                        MWArray B = C.func_getTc(sd, R, d, nd, r1, AA[0, 0], AA[0, 1], AA[0, 2], F, tc, eps1);
                        double[,] BB = (double[, ])B.ToArray();
                        result.t     = BB[0, 0];
                        result.a1tc  = BB[0, 1];
                        result.d2    = BB[0, 5];
                        XmlHelper.Serialize <MainResult>(result, args[18]);
                        Console.ReadKey();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (C != null)
                        {
                            C.Dispose();
                        }
                    }
                }

                #endregion

                #region 导出Sd-Qm查询表

                else if (methodName == MethodName.SdQmTable)
                {
                    // 项目路径-保存表路径
                    string projectForlder = args[1];
                    string xmlPath        = Path.Combine(projectForlder, ConfigNames.RainStormSub);
                    //暴雨衰减赋值
                    BYSJResult bysj = null;
                    if (File.Exists(xmlPath))
                    {
                        bysj = XmlHelper.Deserialize <BYSJResult>(xmlPath);
                    }
                    //暴雨损失赋值
                    BYSSResult byss = null;
                    xmlPath = Path.Combine(projectForlder, ConfigNames.RainStormLoss);
                    if (File.Exists(xmlPath))
                    {
                        byss = XmlHelper.Deserialize <BYSSResult>(xmlPath);
                    }
                    //沟道汇流赋值
                    HCHLResult hchl = null;
                    xmlPath = Path.Combine(projectForlder, ConfigNames.RiverConfluence);
                    if (File.Exists(xmlPath))
                    {
                        hchl = XmlHelper.Deserialize <HCHLResult>(xmlPath);
                    }
                    //坡面汇流赋值
                    xmlPath = Path.Combine(projectForlder, ConfigNames.SlopeConfluence);
                    PMHLResult pmhl = null;
                    if (File.Exists(xmlPath))
                    {
                        pmhl = XmlHelper.Deserialize <PMHLResult>(xmlPath);
                    }
                    //默认参数
                    xmlPath = Path.Combine(projectForlder, ConfigNames.DefaultArgModel);
                    DefaultArgModel defaultArg = null;
                    if (File.Exists(xmlPath))
                    {
                        defaultArg = XmlHelper.Deserialize <DefaultArgModel>(xmlPath);
                    }
                    if (bysj == null || byss == null || hchl == null || pmhl == null || defaultArg == null)
                    {
                        Console.WriteLine("参数不全!");
                        return;
                    }
                    double         p1    = Convert.ToDouble(defaultArg.p1);
                    double         Qm_v  = Convert.ToDouble(defaultArg.Qm);
                    double         eps_0 = Convert.ToDouble(defaultArg.esp1);
                    MWNumericArray p1_0  = new MWNumericArray(p1);
                    MWNumericArray Qm_0  = new MWNumericArray(Qm_v);;
                    MWNumericArray eps   = new MWNumericArray(eps_0);
                    MWNumericArray R     = new MWNumericArray(byss.R);
                    MWNumericArray d     = new MWNumericArray(bysj.d);
                    MWNumericArray nd    = new MWNumericArray(bysj.nd);
                    MWNumericArray r1    = new MWNumericArray(byss.r1);
                    MWNumericArray F     = new MWNumericArray(byss.F);
                    MWNumericArray L1    = new MWNumericArray(hchl.L1);
                    MWNumericArray L2    = new MWNumericArray(pmhl.L2);
                    MWNumericArray I1    = new MWNumericArray(hchl.l1);
                    MWNumericArray I2    = new MWNumericArray(pmhl.l2);
                    MWNumericArray A1    = new MWNumericArray(hchl.A1);
                    MWNumericArray A2    = new MWNumericArray(pmhl.A2);

                    DataTable  aTable = new DataTable();
                    DataColumn Sd     = new DataColumn("Sd", typeof(double));
                    DataColumn Qm     = new DataColumn("Qm", typeof(double));
                    aTable.Columns.Add(Sd);
                    aTable.Columns.Add(Qm);
                    try
                    {
                        C = new Class1();
                        double sd_0 = 10;
                        for (int i = 0; i < 1001; i++)
                        {
                            MWNumericArray sd = new MWNumericArray(sd_0);
                            MWArray        A  = C.fun_main(p1_0, Qm_0, eps, sd, R, d, nd, r1, F, L1, L2, I1, I2, A1, A2);
                            double[,] AA = (double[, ])A.ToArray();
                            DataRow row = aTable.NewRow();
                            row["Sd"] = sd_0;
                            row["Qm"] = AA[0, 0];
                            aTable.Rows.Add(row);
                            sd_0 = sd_0 + 0.1;
                        }
                        XmlHelper.SaveDataToExcelFile(aTable, args[2]);
                        Console.WriteLine("导出完成!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("导出异常:" + ex.Message);
                    }
                    finally
                    {
                        if (C != null)
                        {
                            C.Dispose();
                        }
                    }
                }

                #endregion
            }
        }
예제 #17
0
        public async Task <RateResult> PredictMovieRate(User predictedUser, int movieIndex)
        {
            MWArray[] models = createModel.CreateModel(2);

            var userModel = models[0];
            var itemModel = models[1];

            List <Rate> rates = await GetRates();

            // - predictedUser.Rates.Count
            int[,] rateArray = new int[rates.Count, 4];

            var userCount = await movieContext.Users.CountAsync();

            int[,] itemRates = new int[userCount, 1];

            //Convert rates to input data set
            int count = 0;

            for (int i = 0; i < rates.Count; i++)
            {
                var currentRate = rates[i];

                ////discard user's rate
                //if (currentRate.UserId == predictedUser.Id)
                //    continue;

                if (currentRate.MovieId == movieIndex)
                {
                    itemRates[currentRate.UserId - 1, 0] = currentRate.MovieRate;
                }

                rateArray[count, 0] = currentRate.UserId;
                rateArray[count, 1] = currentRate.MovieId;
                rateArray[count, 2] = currentRate.MovieRate;
                count++;
            }

            for (int i = 0; i < itemRates.Length; i++)
            {
                if (itemRates[i, 0] == 0)
                {
                    itemRates[i, 0] = -1;
                }
            }

            //Create user-item dataset for calculating knn
            MWArray newValues = calculateKNN.PrepareDataSet((MWNumericArray)rateArray);

            double[,] newRates = (double[, ])newValues.ToArray();

            //create a given user's rate matrices for comparing values
            var movieCount = newRates.GetLength(1);

            double[,] userRates = new double[1, movieCount];
            var predictedUserRates = predictedUser.Rates;

            for (int i = 0; i < movieCount; i++)
            {
                userRates[0, i] = -1;
            }

            predictedUserRates.ForEach(rate => userRates[0, rate.MovieId - 1] = rate.MovieRate);

            // trainSet, movieRates , userToGuessIndex, N
            MWArray[] itemResult = predictionHelper.ItemBased(2, newValues, (MWNumericArray)itemRates, predictedUser.Id, 60);

            var itemPrediction = (double[, ])itemResult[1].ToArray();

            var roundedItem = -1;
            var itemVal     = itemPrediction[0, 0];

            if (!Double.IsNaN(itemVal))
            {
                roundedItem = Convert.ToInt32(itemVal);
            }

            //RESULT
            //mw[0] = distanceValues
            //mw[1] = bestSimilartityValues
            //mw[2] = guess for selected movie
            MWArray[] mW = predictionHelper.KNNCalculation(3, userModel, (MWNumericArray)userRates, movieIndex, 50);

            var userPrediction = (double[, ])mW[2].ToArray();

            var value       = userPrediction[0, 0];
            int roundedUser = -1;

            if (!Double.IsNaN(value))
            {
                roundedUser = Convert.ToInt32(value);
            }
            return(new RateResult {
                ItemResult = roundedItem, UserResult = roundedUser
            });
        }
예제 #18
0
        static void Main()
        {
            Func <double, double> Result = ((double result) => { return(Math.Pow(Math.E, -result)); });

            Console.WriteLine("...bayes_estimation2 Start!!!...");

            Class_p     pre1 = new Class_p();
            MWArray     max_m1 = (MWNumericArray)pre1.pre_process();
            f_method    fsolve_r1 = new f_method();
            f_method1   fmincon_r = new f_method1();
            Classi      integratef = new Classi();
            Classi1     integratef1 = new Classi1();
            MWCharArray str2 = "theta";
            MWCharArray str2f = "n";
            string      str1tt = "(theta^" + 0.ToString() + "/factorial(" + 0.ToString() + ")*exp(1)^(-theta))", str1t;

            Console.WriteLine("please assign the number of points you want deal with:");
            int i, j, data_range = int.Parse(Console.ReadLine());

            for (i = 0; i <= data_range; i++)
            {
                str1tt = str1tt + "*" + "(theta^" + i.ToString() + "/factorial(" + i.ToString() + ")*exp(1)^(-theta))";
            }

            string str1ttf = "(theta^n/factorial(n)*exp(1)^(-theta))" + "*" + str1tt;

            double[,] max_m2 = (double[, ])max_m1.ToArray();
            var max_m3 = DenseMatrix.OfArray(max_m2);

            int s1 = max_m2.GetLength(0), s2 = max_m2.GetLength(1);

            var result_p  = new DenseMatrix((int)Math.Ceiling((double)(s1 / data_range)), s2);
            var result_p1 = new DenseVector(s2);

            double[] std_r;

            long stop_Value = 0, start_Value = 0, freq = 0;

            QueryPerformanceFrequency(ref freq);      //获取CPU频率
            QueryPerformanceCounter(ref start_Value); //获取初始前值

            var count1f = new DenseMatrix((int)Math.Ceiling((double)(s1 / data_range)), s2);

            double[] count1t = new double[s2];
            MathNet.Numerics.LinearAlgebra.Matrix <double> tmp_m1;

            MWArray[] argsOut   = new MWArray[3];
            MWArray[] argsOut1  = new MWArray[2];
            MWArray[] argsIn    = new MWArray[6];
            MWArray[] argsIn1   = new MWArray[5];
            MWArray[] argsIn1f  = new MWArray[4];
            MWArray[] argsOutf1 = new MWArray[1];
            MWArray[] argsIn1f1 = new MWArray[7];
            MWArray[] argsOutf2 = new MWArray[1];
            int       exitflag  = 0;
            int       allmins   = 0;

            for (i = 0; i < s2; i++)
            {
                //s2 / data_range???
                for (j = 0; j < (int)Math.Ceiling((double)(s1 / data_range)); j++)
                {
                    int count1 = 0;
                    if ((j + 1) * data_range - 1 > max_m3.RowCount)
                    {
                        tmp_m1 = max_m3.SubMatrix(j * data_range, data_range - ((j + 1) * data_range - max_m3.ColumnCount), i, 1);
                    }
                    else
                    {
                        tmp_m1 = max_m3.SubMatrix(j * data_range, data_range, i, 1);
                    }
                    for (int ii = 0; ii < tmp_m1.RowCount; ii++)
                    {
                        for (int jj = 0; jj < tmp_m1.ColumnCount; jj++)
                        {
                            if (Math.Abs(tmp_m1[ii, jj]) > 0.9 * max_m3.SubMatrix(0, max_m3.RowCount, i, 1).Enumerate().Max())
                            {
                                count1++;
                            }
                        }
                    }
                    count1f[j, i] = count1;
                    count1t[i]    = count1t[i] + count1;
                }
                count1t[i] = count1t[i] / Math.Ceiling((double)(s1 / data_range));
            }

            for (i = 0; i < s2; i++)
            {
                //s2 / data_range???
                for (j = 0; j < (int)Math.Ceiling((double)(s1 / data_range)); j++)
                {
                    str1t = "theta^" + count1f[j, i].ToString() + "/factorial(" + ((int)Math.Round(count1f[j, i])).ToString() + ")*exp(1)^(-theta)-" + (count1f[j, i] / data_range).ToString();
                    MWCharArray str1 = new MWCharArray(str1t);
                    argsIn[0]  = str1;
                    argsIn[1]  = str2;
                    argsIn[2]  = 1;
                    argsIn[5]  = 100;
                    argsOut[0] = result_p[j, i];
                    argsOut[1] = exitflag;
                    argsOut[2] = allmins;
                    if (count1f[j, i] <= count1t[i])
                    {
                        argsIn[3] = 0;
                        argsIn[4] = count1t[i];
                        fsolve_r1.fsolve_r1(3, ref argsOut, argsIn);
                        result_p[j, i] = ((MWNumericArray)argsOut[0]).ToScalarDouble();
                    }
                    else
                    {
                        argsIn[3] = count1t[i];
                        argsIn[4] = data_range;
                        fsolve_r1.fsolve_r1(3, ref argsOut, argsIn);
                        result_p[j, i] = ((MWNumericArray)argsOut[0]).ToScalarDouble();
                    }
                }
            }
            std_r = (double[])Std_t1(result_p);

            for (i = 0; i < s2; i++)
            {
                string str3 = "((1/(sqrt(2*pi)*" + std_r[i].ToString() + "))*exp(((theta-" + count1t[i].ToString() + ")^2)/" + "(-2*" + std_r[i].ToString() + "^2)))";
                str1tt      = str1tt + "*" + str3;
                argsIn1f[0] = str1tt;
                argsIn1f[1] = str2;
                argsIn1f[2] = 0;
                argsIn1f[3] = data_range;
                integratef.integrate(1, ref argsOutf1, argsIn1f);
                result_p1[i] = ((MWNumericArray)argsOutf1[0]).ToScalarDouble();
                str1tt       = str1tt + "/" + result_p1[i].ToString();
                str1tt       = str1tt + "*" + str1ttf + "*" + str2f;;
                argsIn1f1[0] = str1tt;
                argsIn1f1[1] = str2;
                argsIn1f1[2] = str2f;
                argsIn1f1[3] = 0;
                argsIn1f1[4] = data_range;
                argsIn1f1[5] = 0;
                argsIn1f1[6] = data_range;
                integratef1.integrate1(1, ref argsOutf2, argsIn1f1);
                result_p1[i] = ((MWNumericArray)argsOutf2[0]).ToScalarDouble();
            }

            //for (i = 0; i < s2; i++)
            //{
            //    MWCharArray str1tt1;
            //    //s2 / data_range???
            //    for (j = 0; j < (int)Math.Ceiling((double)(s1 / data_range)); j++)
            //    {
            //        string str3 = "((1/(sqrt(2*pi)*" + std_r[i].ToString() + "))*exp(((theta-" + count1t[i].ToString() + ")^2)/" + "(-2*" + std_r[i].ToString() + "^2)))";
            //        str1tt = str1tt + "*" + str3;
            //        str1tt1 = new MWCharArray(str1tt);
            //        argsIn1[0] = str1tt1;
            //        argsIn1[1] = str2;
            //        argsIn1[2] = result_p[j, i];
            //        argsIn1[3] = 0;
            //        argsIn1[4] = data_range;
            //        argsOut1[0] = result_p[j, i];
            //        argsOut1[1] = exitflag;
            //        fmincon_r.fmincon_r(2, ref argsOut1, argsIn1);
            //        result_p[j, i] = Result(((MWNumericArray)argsOut1[0]).ToScalarDouble());
            //    }
            //}
            MatlabWriter.Write("result_p1.mat", result_p, "result_p1");
            QueryPerformanceCounter(ref stop_Value);//获取终止变量值
            var times2 = (stop_Value - start_Value) / (double)freq * 1000;

            Console.WriteLine("RunTime " + times2 / 1000 + "s");
        }
 public void FromMatlabArray(MWArray data)
 {
     var k = data.ToArray();
     for (int i = 0; i < k.GetLength(0); i++)
     {
         for (int j = 0; j < k.GetLength(1); j++)
         {
             object a = k.GetValue(i,j);
             byte b = (byte) a;
             Pixel p = new Pixel((int)b,(int)b,(int)b,255);
             SetPixel(j,i,p);
         }
     }
 }
예제 #20
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        public double[] CalOptValuesIndexFind(double Thickness, double BulkDensity, double tFResist, double[,] SFactorMat, double[,] PorosityMat, double tc1, double tc2, int[] FreRegion, int ParaIndenti,int LoopNum)
        {
            int RowSizeOfPara=0;
            int ColumSizeOfPara=0;
            int SizeOfPEFre=FreRegion[1]-FreRegion[0];

            double fre;
            double[] ValueIndex=new double[3];
            int[] CalOptValues=new int[2];

            if (ParaIndenti==2)
            {
                RowSizeOfPara=SFactorMat.GetLength(0);;
                ColumSizeOfPara=SFactorMat.GetLength(1);
            }

            else if (ParaIndenti==3)
            {
                RowSizeOfPara=PorosityMat.GetLength(0);;
                ColumSizeOfPara=PorosityMat.GetLength(1);
            }
            else if (ParaIndenti==4)
            {
                RowSizeOfPara=SFactorMat.GetLength(0);;
                ColumSizeOfPara=SFactorMat.GetLength(1);
            }

            double[,,] MAbsorptionMat=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,,] PDAbsorption=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,,] CharFreError=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,] CharFreErrorSum=new double[RowSizeOfPara,ColumSizeOfPara];
            double[,] APDAbsorption=new double[RowSizeOfPara,ColumSizeOfPara];

            ttempMAbsorption=TempMAbsorption;
            APDAbsorption.Initialize();

            for (int ff=0;ff<SizeOfPEFre;ff++)
            {
                fre=(ff+FreRegion[0])*200;
                //MeritCalcClass.apfibrous5para(Thickness, tFResist, SFactorMat, PorosityMat, tc1, tc2,fre);  //INSUNG
                m_Out = MeritCalcClass.APFibrous5para(B, tc1, tc2, m_Density1, Densityo, tFResist, fre, (MWNumericArray)PorosityMat, HeatRatio, ItaAir, Thickness, Npr, P0, (MWNumericArray)SFactorMat, Z0); //INSUNG
                APDAbsorption = (double[,])m_Out.ToArray();
                for (int i=0;i<RowSizeOfPara;i++)
                {
                    for (int j=0; j<ColumSizeOfPara;j++)
                    {
                        MAbsorptionMat[i,j,ff]=ttempMAbsorption[ff+FreRegion[0]];
                        PDAbsorption[i,j,ff]=APDAbsorption[i+1,j+1];
                        CharFreError[i,j,ff]=Math.Abs(MAbsorptionMat[i,j,ff]-PDAbsorption[i,j,ff]);
                    }
                }
            }

            for (int i=0;i<RowSizeOfPara;i++)
            {
                for(int j=0;j<ColumSizeOfPara;j++)
                {
                    for(int ff=0;ff<(SizeOfPEFre-1);ff++)
                    {
                        CharFreErrorSum[i,j] += CharFreError[i,j,ff];
                    }
                }
            }

            if (ParaIndenti==2)
            {
                ValueIndex=FindMin(CharFreErrorSum, RowSizeOfPara, ColumSizeOfPara);
            }
            else if (ParaIndenti==3)
            {
                ValueIndex=FindMin(CharFreErrorSum, RowSizeOfPara, ColumSizeOfPara);
            }
            else if (ParaIndenti==4)
            {
                ValueIndex=FindMin(CharFreErrorSum, RowSizeOfPara, ColumSizeOfPara);
            }

            return ValueIndex;
        }
예제 #21
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        public double[] CalOptValuesIndexFind(double Thickness, double BulkDensity, double tFResist, double tSFactor, double Porosity, double[,] c1Mat, double[,] c2Mat, int[] FreRegion, int ParaIndenti,int LoopNum)
        {
            int RowSizeOfPara= 0;
            int ColumSizeOfPara= 0;
            int SizeOfPEFre=32;
               //     double TempMaxError=0.0;

            double fre;
            double[] ValueIndex=new double[3];
            int[] CalOptValues=new int[2];

            if (ParaIndenti==5)
            {
                RowSizeOfPara=c1Mat.GetLength(0);;
                ColumSizeOfPara=c1Mat.GetLength(1);
            }
            else if (ParaIndenti==6)
            {
                RowSizeOfPara=c2Mat.GetLength(0);;
                ColumSizeOfPara=c2Mat.GetLength(1);
            }
            else if (ParaIndenti==7)
            {
                RowSizeOfPara=c1Mat.GetLength(0);;
                ColumSizeOfPara=c1Mat.GetLength(1);
            }

            double[,,] MAbsorptionMat=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,,] PDAbsorption=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,,] CharFreError=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,] CharFreErrorSum=new double[RowSizeOfPara,ColumSizeOfPara];
            double[,] APDAbsorption=new double[RowSizeOfPara,ColumSizeOfPara];
            double[,] MaxError=new double[RowSizeOfPara,ColumSizeOfPara];
            ttempMAbsorption=TempMAbsorption;

            for (int ff=0;ff<SizeOfPEFre;ff++)
            {
                fre=(ff+1)*200;

                //MeritCalcClass.apfibrous5para(Thickness, tFResist, tSFactor, tPorosity, c1Mat, c2Mat,fre);  //INSUNG
                m_Out = MeritCalcClass.APFibrous5para(B, (MWNumericArray)c1Mat, (MWNumericArray)c2Mat, m_Density1, Densityo, tFResist, fre, tPorosity, HeatRatio, ItaAir, Thickness, Npr, P0, tSFactor, Z0); //INSUNG
                APDAbsorption = (double[,])m_Out.ToArray();

                for (int i=0;i<RowSizeOfPara;i++)
                {
                    for (int j=0;j<ColumSizeOfPara;j++)
                    {
                        MAbsorptionMat[i,j,ff]=ttempMAbsorption[ff];
                        PDAbsorption[i,j,ff]=APDAbsorption[i+1,j+1];
                        CharFreError[i,j,ff]=Math.Abs(MAbsorptionMat[i,j,ff]-PDAbsorption[i,j,ff]);
                    }
                }
            }

            for (int i=0;i<RowSizeOfPara;i++)
            {
                for(int j=0;j<ColumSizeOfPara;j++)
                {
                    for(int ff=0;ff<SizeOfPEFre;ff++)
                    {
                        CharFreErrorSum[i,j] += CharFreError[i,j,ff];
                    }
                }
            }
            //			for (int i=0;i<RowSizeOfPara;i++)
            //			{
            //				TempMaxError=0;
            //				for(int j=0;j<ColumSizeOfPara;j++)
            //				{
            //					TempMaxError=0;
            //					for(int ff=0;ff<(SizeOfPEFre-1);ff++)
            //					{
            //						if (TempMaxError < CharFreError[i,j,ff])
            //						{
            //							TempMaxError=CharFreError[i,j,ff];
            //							MaxError[i,j]=TempMaxError;
            //						}
            //						CharFreErrorSum[i,j]+= CharFreError[i,j,ff];
            //					}
            //				}
            //			}

            if (ParaIndenti==5)
            {
                ValueIndex=FindMin(CharFreErrorSum, RowSizeOfPara, ColumSizeOfPara);
            }
            else if (ParaIndenti==6)
            {
                ValueIndex=FindMin(CharFreErrorSum, RowSizeOfPara, ColumSizeOfPara);
            }
            else if (ParaIndenti==7)
            {
                double FirstError=10000;
                double tempc1=0;
                double tempc2=0;
                //double Optc1=tc1;
                //double Optc2=tc2;

                for (int i=0;i<RowSizeOfPara;i++)
                {
                    for (int j=0;j<ColumSizeOfPara;j++)
                    {
                        tempc1= c1Mat[i,j];
                        tempc2= c2Mat[i,j];
                        //if ( (MinMaxtError >= MaxError[i,j]) && (tempc1 >= tempc2) )
                        if ( (FirstError >= CharFreErrorSum[i,j]) && (tempc1 >= tempc2) )
                        {
                            ValueIndex[0]=i;
                            ValueIndex[1]=j;
                            //ValueIndex[2]=CharFreErrorSum[i,j];
                            //MinMaxError=MaxError[i,j];
                            FirstError= CharFreErrorSum[i,j];
                        }
                    }
                }
            }

            return ValueIndex;
        }
예제 #22
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        public double[] CalOptValuesIndexFind(double Thickness, double BulkDensity, double[,] FResistMat, double tSFactor, double tPorosity, double tc1, double tc2, int[] FreRegion, int ParaIndenti,int LoopNum)
        {
            int RowSizeOfPara=0;
            int ColumSizeOfPara=0;
            int SizeOfPEFre=FreRegion[1]-FreRegion[0];
            double TempMaxError=0.0;
            double fre;
            double[] ValueIndex=new double[3];
            int[] CalOptValues=new int[2];

            RowSizeOfPara=FResistMat.GetLength(0);
            ColumSizeOfPara=FResistMat.GetLength(1);

            double[,,] MAbsorptionMat=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,,] PDAbsorption=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,,] CharFreError=new double[RowSizeOfPara,ColumSizeOfPara,SizeOfPEFre];
            double[,] CharFreErrorSum=new double[RowSizeOfPara,ColumSizeOfPara];
            double[,] APDAbsorption=new double[RowSizeOfPara,ColumSizeOfPara];
            double[,] MaxError=new double[RowSizeOfPara,ColumSizeOfPara];

            ttempMAbsorption=TempMAbsorption;

            for (int ff=0;ff<SizeOfPEFre;ff++)
            {
                fre=(ff+1)*200;
                //MeritCalcClass.apfibrous5para(Thickness, FResistMat, tSFactor, tPorosity, tc1, tc2,fre);   //INSUNG
                m_Out = MeritCalcClass.APFibrous5para(B, tc1, tc2, m_Density1, Densityo, (MWNumericArray)FResistMat, fre, tPorosity, HeatRatio, ItaAir, Thickness, Npr, P0, tSFactor, Z0); //INSUNG
                APDAbsorption = (double[,])m_Out.ToArray();

                for (int i=0;i<RowSizeOfPara;i++)
                {
                    for (int j=0; j<ColumSizeOfPara;j++)
                    {
                        MAbsorptionMat[i,j,ff]=ttempMAbsorption[ff];
                        PDAbsorption[i,j,ff]=APDAbsorption[i+1,j+1];
                        CharFreError[i,j,ff]=Math.Abs(MAbsorptionMat[i,j,ff]-PDAbsorption[i,j,ff]);
                    }
                }
            }

            for (int i=0;i<RowSizeOfPara;i++)
            {
                TempMaxError=0;
                for(int j=0;j<ColumSizeOfPara;j++)
                {
                    TempMaxError=0;
                    for(int ff=0;ff<(SizeOfPEFre-1);ff++)
                    {
                        if (TempMaxError < CharFreError[i,j,ff])
                        {
                           TempMaxError=CharFreError[i,j,ff];
                           MaxError[i,j]=TempMaxError;
                        }
                        //CharFreErrorSum[i,j]+= CharFreError[i,j,ff];
                    }
                }
            }

            ValueIndex=FindMin(MaxError, RowSizeOfPara, ColumSizeOfPara);
            //ValueIndex=FindMin(CharFreErrorSum, RowSizeOfPara, ColumSizeOfPara);

            return ValueIndex;
        }
예제 #23
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        public double CalcFiborousGraphData()
        {
            double Merit=0;
            double freq;

            double c1 = Math.Sqrt(8*SFactor*ItaAir/(Porosity*FResist))/ViscousCL;
            double c2 = Math.Sqrt(8*SFactor*ItaAir/(Porosity*FResist))/ThermalCL;

            //			H = (Math.Pow(FResist*ViscousCL*Porosity,2))/(4*(Math.Pow(SFactor,2))*ItaAir*Densityo);
            //			HP = 16*ItaAir/((Math.Pow(Npr*ThermalCL,2))*Densityo);

            CAbsorption.Clear();
            CRealSurfaceImpedance.Clear();
            CImagSurfaceImpedance.Clear();

            CAbsorption.AddData(0);
            CRealSurfaceImpedance.AddData(0);
            CImagSurfaceImpedance.AddData(0);

            for (int ff=1;ff<=MaxFre;ff++)
            {
                freq=Frequency.GetData(ff);
                //MeritCalcClass.meritcalc(freq, (double)MAbsorption.GetData(ff),BulkDensity, FResist, SFactor, Porosity, c1, c2, Thickness);//INSUNG
                m_Out = MeritCalcClass.MeritCalc(BulkDensity,B,c1,c2,Densityo,FResist,freq,Porosity,HeatRatio,ItaAir,Thickness,(double)MAbsorption.GetData(ff),Npr,P0,SFactor,Z0);//INSUNG
                m_Merit = (double)m_Out.ToArray().GetValue(0, 0);
                m_Absorption = (double)m_Out.ToArray().GetValue(0, 1);
                m_RealSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 2);
                m_ImagSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 3);
                m_Density1 = BulkDensity;//INSUNG

                CAbsorption.AddData((double)m_Absorption);
                CRealSurfaceImpedance.AddData((double)m_RealSurfaceImpedance);
                CImagSurfaceImpedance.AddData((double)m_ImagSurfaceImpedance);
                Merit=Merit+(double)m_Merit;
            }

            return Merit;
        }
예제 #24
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        public double CalcElasticGraphData()
        {
            double Merit=0;

            double freq;

            //double c1 = Math.Sqrt(8*SFactor*ItaAir/(Porosity*FResist))/ViscousCL;
            //double c2 = Math.Sqrt(8*SFactor*ItaAir/(Porosity*FResist))/ThermalCL;

            CAbsorption.Clear();
            CRealSurfaceImpedance.Clear();
            CImagSurfaceImpedance.Clear();

            CAbsorption.AddData(0);
            CRealSurfaceImpedance.AddData(0);
            CImagSurfaceImpedance.AddData(0);

            for (int ff=1;ff<=MaxFre;ff++)
            {
                freq=Frequency.GetData(ff);
                //MeritCalcClass.elasticmeritcalc(freq, (double)MAbsorption.GetData(ff),FResist, SFactor, Porosity, c1, c2, Ymodulus, LossFactor, PoissonR, Thickness);  //INSUNG
                m_Out = MeritCalcClass.ElasticMeritCalc(C,c1,c2,m_Density1,m_DensityA,Densityo,Ymodulus,FResist,freq,Porosity,HeatRatio,Thickness,LossFactor,(double)MAbsorption.GetData(ff),Npr,PoissonR,SFactor);  //INSUNG
                m_Merit = (double)m_Out.ToArray().GetValue(0, 0);
                m_Absorption = (double)m_Out.ToArray().GetValue(0, 1);
                m_RealSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 2);
                m_ImagSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 3);

                CAbsorption.AddData((double)m_Absorption);
                CRealSurfaceImpedance.AddData((double)m_RealSurfaceImpedance);
                CImagSurfaceImpedance.AddData((double)m_ImagSurfaceImpedance);

                Merit=Merit+(double)m_Merit;

            }

            return Merit;
        }
예제 #25
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        public double[] MeritCalc(double Freq1,double Freq2,double tFResist,double tSFactor,double tPorosity,double tc1,double tc2)
        {
            double Merit=0;
            double MaxError=0;
            double freq;
            double tempError;
            double[] Errors=new double[2];

            for (int ff=(int)Freq1;ff<=(int)Freq2;ff++)
            {
                freq=TempFrequency[ff-1];
                //MeritCalcClass.meritcalc(freq, (double)TempMAbsorption[ff-1],BulkDensity, tFResist, tSFactor, tPorosity, tc1, tc2, Thickness);//INSUNG
                m_Out = MeritCalcClass.MeritCalc(BulkDensity,B,tc1,tc2,Densityo,tFResist,freq,tPorosity,HeatRatio,ItaAir,Thickness,(double)TempMAbsorption[ff-1],Npr,P0,tSFactor,Z0);//INSUNG
                m_Merit = (double)m_Out.ToArray().GetValue(0, 0);
                m_Absorption = (double)m_Out.ToArray().GetValue(0, 1);
                m_RealSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 2);
                m_ImagSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 3);

                m_Density1 = BulkDensity;//INSUNG
                Merit=Merit+(double)(m_Merit);
                tempError=(double)(m_Merit);
                if(MaxError>tempError)
                {
                    MaxError=tempError;
                }

                //System.Windows.Forms.Application.DoEvents();
            }
            Errors=new double[2] {MaxError,Merit};

            return Errors;
        }
예제 #26
0
파일: MPEData.cs 프로젝트: InsungChoi/dddd
        public double[,] SolidCalc()
        {
            double[,]  OptSolidPara=new double[1,3];
            double Slope1;
            double Slope2;
            double Slope3;
            double Slope4;
            double ResonanceFrequency=0;
            double freq;
            double Merit=0;
            double tLossFactor=0;
            double OptLossFactor=0;

            int ResonFreIndex=0;

            for (int i=2;i<MaxFre-InitFre-2;i++)
            {
                Slope1=(MRealSurfaceImpedanceSampled[i-1]*415-MRealSurfaceImpedanceSampled[i-2]*415)/Resolution;
                Slope2=(MRealSurfaceImpedanceSampled[i]*415-MRealSurfaceImpedanceSampled[i-1]*415)/Resolution;

                Slope3=(MRealSurfaceImpedanceSampled[i+1]*415-MRealSurfaceImpedanceSampled[i]*415)/Resolution;
                Slope4=(MRealSurfaceImpedanceSampled[i+2]*415-MRealSurfaceImpedanceSampled[i+1]*415)/Resolution;

                if ( (Slope1/(Math.Abs(Slope1)) < 0) && (Slope2/(Math.Abs(Slope2)) < 0) && (Slope3/(Math.Abs(Slope3)) > 0) && (Slope4/(Math.Abs(Slope4)) > 0))
                {
                    ResonanceFrequency=(double)i*Resolution+300;
                    break;
                }

            }
            ResonFreIndex=(int)Math.Round(ResonanceFrequency/Resolution);

            //MeritCalcClass.peelasticsolid(Thickness, BulkDensity, ResonanceFrequency);
            m_Out = MeritCalcClass.PEElasticSolid(BulkDensity, Thickness, ResonanceFrequency); //INSUNG
            OptSolidPara = (double[,])m_Out.ToArray();

            Ymodulus=(double)OptSolidPara[1,1];
            PoissonR=(double)OptSolidPara[1,3];

            double Merittemp=100000;
            for (int i=1;i<99;i++)
            {

                tLossFactor=i*0.01;
                freq=ResonFreIndex*Resolution;

                //MeritCalcClass.elasticmeritcalc(freq, (double)MAbsorption.GetData(ResonFreIndex),FResist, SFactor, Porosity, c1, c2, Ymodulus, tLossFactor, PoissonR, Thickness);  //INSUNG
                m_Out = MeritCalcClass.ElasticMeritCalc(C,c1,c2,m_Density1,m_DensityA,Densityo,Ymodulus,FResist,freq,Porosity,HeatRatio,Thickness,tLossFactor,(double)MAbsorption.GetData(ResonFreIndex),Npr,PoissonR,SFactor);  //INSUNG
                m_Merit = (double)m_Out.ToArray().GetValue(0, 0);
                m_Absorption = (double)m_Out.ToArray().GetValue(0, 1);
                m_RealSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 2);
                m_ImagSurfaceImpedance = (double)m_Out.ToArray().GetValue(0, 3);

                Merit=(double)m_Merit;

                if(Merit<Merittemp)
                {
                    OptLossFactor=tLossFactor;
                    Merittemp=Merit;
                }
            }
            OptSolidPara[1,2]=OptLossFactor;

            return OptSolidPara;
        }