Example #1
1
        /// <summary>Get a rainfall forecast for the specified station number.</summary>
        /// <param name="stationNumber">The SILO station number.</param>
        /// <returns>Stream of data.</returns>
        public Stream Get(int stationNumber, DateTime nowDate, bool rainOnly)
        {
            // Get SILO data and write to a temporary file.
            DateTime startDate = new DateTime(1981, 1, 1);
            MemoryStream dataStream = WeatherFile.ExtractMetStreamFromSILO(stationNumber, startDate, DateTime.Now);
            string siloFileName = GetTemporaryFileName();
            string forecastFileName = null;

            try
            {
                File.WriteAllBytes(siloFileName, dataStream.ToArray());

                ChangeToWorkingDirectory();

                // Run the MatLab script over the temporary SILO file.
                POAMAforecast.Class1 forecast = new POAMAforecast.Class1();

                MWArray metFile = new MWCharArray(siloFileName);
                MWArray rainfallOnly = new MWNumericArray((double)1);
                if (!rainOnly)
                    rainfallOnly = new MWNumericArray((double)0);
                MWArray writeFiles = new MWNumericArray((double)1.0);
                MWArray startDay = new MWNumericArray(Convert.ToDouble(nowDate.Day));
                MWArray startMonth = new MWNumericArray(Convert.ToDouble(nowDate.Month));
                MWArray startYear = new MWNumericArray(Convert.ToDouble(nowDate.Year));
                forecast.calsite(metFile, rainfallOnly, writeFiles, startDay, startMonth, startYear);

                forecastFileName = siloFileName.Replace(".sim", "") + "_" + nowDate.Year + ".sim";

                // Get rid of temporary file.
                File.Delete(siloFileName);

                if (WebOperationContext.Current != null && WebOperationContext.Current.OutgoingRequest != null)
                    WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
                if (File.Exists(forecastFileName))
                {
                    // Read in the forecast data.
                    byte[] bytes = File.ReadAllBytes(forecastFileName);
                    return new MemoryStream(bytes);
                }
                else
                    return null;
            }
            finally
            {
                if (File.Exists(siloFileName))
                    File.Delete(siloFileName);
                if (forecastFileName != null && File.Exists(forecastFileName))
                    File.Delete(forecastFileName);
            }
        }
Example #2
1
 private MWNumericArray transpose(MWNumericArray array)
 {
     double[] tmp = (double[])array.ToVector(MWArrayComponent.Real);
     return new MWNumericArray(tmp.Length, 1, tmp);
 }
        public void TrainModel(string featureFilePath, string completeFeatureFilePath, List<double[]> featureVector)
        {
            int dataLength = featureVector[0].Length;
            double[] featureData = MatrixUtil.FlattenMatrix(featureVector);
            MWCharArray rgbdFile = new MWCharArray(featureFilePath);
            MWNumericArray newFeature = new MWNumericArray(dataLength, featureVector.Count, featureData);
            rgbdfea.rgbdfea rgbdfea = new rgbdfea.rgbdfea();
            rgbdfea.appendFeature(rgbdFile, newFeature);

            TrainModel(completeFeatureFilePath);
        }
        public double[,] MakeSquare_vectorInput(double[] dimArray)
        {
            var input  = new MWNumericArray(dimArray);
            var result = this.Matlab.makesquare_in_vector(input);

            return(Utility.MWArrayToMatrix(result));
        }
Example #5
0
 public override MWNumericArray Process(MWNumericArray m)
 {
     MWArray[] r = Tools.FilterHandler.atscale(3, m);
     this._m = r[1] as MWNumericArray;
     this._s = r[2] as MWNumericArray;
     return(r[0] as MWNumericArray);
 }
        public static MWNumericArray GetCipherKey(string key)
        {
            MWNumericArray ret = null;

            if (Regex.IsMatch(key, @"^[a-zA-Z]+$"))
            {
                ret = (MWNumericArray)Program.aesMatObj.loadmatfile((MWArray)key);;
            }
            else
            {
                double[,] doubles = new double[4, 4];
                string[] cells = key.Split(' ');
                int      count = -1;
                for (int i = 0; i < 4; i++)
                {
                    for (int j = 0; j < 4; j++)
                    {
                        doubles[i, j] = double.Parse(cells[++count]);
                    }
                }

                ret = (MWNumericArray)doubles;
            }
            return(ret);
        }
Example #7
0
        public Image RunFilter(Image src)
        {
            filterDataContext db = new filterDataContext();
            //Bilateral Bilateral = new Bilateral();
            double[] sigma = new double[] { 3, 0.1 };
            double w = 5;
            MWNumericArray mw_sigma = new MWNumericArray(sigma);
            //MWArray Result = Bilateral.bfilter2(image, w, mw_sigma);
            //MWArray image = new MWNumericArray(src.Array.Array);
            /*
            int H = src.Height;
            int W = src.Width;

            int sq = W * H;
            */
            MWArray[] Result = bilateral(2, src.image, w, mw_sigma);
            //MWArray[] Result = bfilter2(2, src.image, w, mw_sigma);
            MWNumericArray descriptor = null;
            descriptor = (MWNumericArray)Result[0];
            double[,] result = null;
            result = (double[,])descriptor.ToArray(MWArrayComponent.Real);
            Image res = new Image(result);
            MWNumericArray e_descriptor = null;
            e_descriptor = (MWNumericArray)Result[1];
            WorkTime = (double)e_descriptor.ToScalarDouble();
            db.add_b_res(src.Height, src.Height / src.Width, WorkTime, w, sigma[0], sigma[1]);
            Result = null;
            e_descriptor = null;
            result = null;
            mw_sigma = null;
            GC.Collect();
            return res;
        }
Example #8
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));
        }
Example #9
0
        public static void Kands(MWNumericArray x, double pp, out double[] groupA, out double[] groupB)
        {
            var rlst = ToolHandler.Kands(2, x, pp);

            groupA = (double[])((MWNumericArray)rlst[0]).ToVector(MWArrayComponent.Real);
            groupB = (double[])((MWNumericArray)rlst[1]).ToVector(MWArrayComponent.Real);
        }
Example #10
0
        private void PhaseRetrivalIteration(DataTable Dt, string SavePath)
        {
            if (Dt.NumUse() < 4)
            {
                Output("Please select at least four images, "
                       + "including a focal image, a reference image and at least two median images.");
                return;
            }

            if (Dt.NumType("Focal") != 1)
            {
                Output("Please select one and only one focal image.");
                return;
            }

            if (Dt.NumType("Reference") != 1)
            {
                Output("Please select one and only one reference image.");
                return;
            }

            string        FocalName  = null;
            int           FocalDist  = 0;
            List <String> MedianName = new List <string>();
            List <int>    MedianDist = new List <int>();
            string        ExportName = null;

            foreach (DataRow Dr in Dt.Rows)
            {
                if (Dr["Type"].ToString() == "Focal")
                {
                    FocalName = Dr.GetName();
                    FocalDist = int.Parse(Dr["Distance"].ToString());
                }

                if (Dr["Type"].ToString() == "Median")
                {
                    MedianName.Add(Dr.GetName());
                    MedianDist.Add(int.Parse(Dr["Distance"].ToString()));
                    ExportName = "RetrievedPhase";
                }

                if (Dr["Type"].ToString() == "Reference")
                {
                    continue;
                }
            }

            MWCharArray    MWMedianName = new MWCharArray(MedianName.ToArray());
            MWNumericArray MWMedianDist = new MWNumericArray(1, MedianDist.Count, MedianDist.ToArray());

            StreamWriter CancelWriter = new StreamWriter(SavePath + "\\Cancel.log");

            CancelWriter.BaseStream.SetLength(0);
            CancelWriter.WriteLine("Continue");
            CancelWriter.Dispose();

            Mf.RetrieveReferencePhase(SavePath, ExportName, MWParameter, 10000, FocalName, FocalDist, MWMedianName, MWMedianDist);
            Token.ThrowIfCancellationRequested();
        }
Example #11
0
        public override MWNumericArray Process(MWNumericArray m)
        {
            //throw new NotImplementedException();
            var d = Tools.FilterHandler.detrend(m) as MWNumericArray;

            return(d);
        }
Example #12
0
        public bool Comp_Add(Component item)
        {
            if (item == null)
            {
                throw new System.ArgumentNullException("can't add a null Spectrum");
            }
            if (this.Comp_Contains(item))
            {
                return(false);
            }
            this._components.Add(item);

            if (this._specs.Count > 0)
            {
                double[] d = new double[this._specs.Count];
                for (int i = 0; i < this._specs.Count; i++)
                {
                    d[i] = double.NaN;
                }
                if (this._y == null)
                {
                    this._y = new MWNumericArray(this._specs.Count, 1, d);
                }
                else
                {
                    this._y = Data.Tools.InsertColumn(this._y, d, this._y.Dimensions[0] + 1);
                }
            }
            return(true);
        }
Example #13
0
        /// <summary>
        /// 过渡性质有NaN的光谱数据
        /// </summary>
        public void FilterNaN()
        {
            if (this._y == null)
            {
                return;
            }
            var idx = new List <int>();

            for (int i = 1; i <= this._y.Dimensions[0]; i++)
            {
                bool tag = true;
                for (int j = 1; j <= this._y.Dimensions[1]; j++)
                {
                    if (double.IsNaN(this._y[i, j].ToScalarDouble()))
                    {
                        tag = false;
                        break;
                    }
                }
                if (tag)
                {
                    idx.Add(i - 1);
                }
            }
            if (idx.Count < this._specs.Count)
            {
                var lib = this.SubLib(idx.ToArray());
                this._x     = lib.X;
                this._y     = lib.Y;
                this._specs = lib.Specs;
            }
        }
Example #14
0
        public SpecBase(string path = null)
        {
            if (String.IsNullOrWhiteSpace(path))
            {
                return;
            }
            var db = Serialize.Read <SpecBase>(path);

            if (db == null)
            {
                return;
            }
            this._axis        = db._axis;
            this._components  = db._components;
            this._date        = db._date;
            this._description = db._description;
            this._editor      = db._editor;
            this._fullPath    = path;
            this._specs       = db._specs;
            this._title       = db._title;
            this._x           = db._x;
            this._y           = db._y;


            //  db.Dispose();
            db = null;
        }
Example #15
0
 public Spectrum this[int i]
 {
     get
     {
         var item = this._specs[i];
         item = this.getAxisData(item, i);
         return(item);
     }
     set
     {
         if (value == null)
         {
             return;
         }
         this._x = Data.Tools.SetColumn(this._x, value.Data.Y, i + 1);
         if (this._y != null && value.Components != null && value.Components.Count > 0)
         {
             var dlst = (double[])Data.Tools.SelectRow(this._y, i + 1).ToVector(MWArrayComponent.Real);
             for (int r = 0; r < this._components.Count; r++)
             {
                 var c = value.Components.Where(d => d.Name == this._components[r].Name).FirstOrDefault();
                 if (c != null)
                 {
                     dlst[r] = c.ActualValue;
                 }
             }
             this._y = Data.Tools.SetRow(this._y, dlst, i + 1);
         }
         value.Components = null;
         value.Data       = null;
         this._specs[i]   = value;
     }
 }
        public static MWNumericArray Bitmap2MWArray(Bitmap bmp)
        {
            MWNumericArray matrix = null;

            byte[, ,] rgbImage = new byte[3, bmp.Height, bmp.Width];
            for (int i = 0; i < bmp.Width; i++)
            {
                for (int j = 0; j < bmp.Height; j++)
                {
                    if (bmp.GetPixel(i, j).R != 0)
                    {
                    }
                    rgbImage[0, j, i] = bmp.GetPixel(i, j).R;
                    rgbImage[1, j, i] = bmp.GetPixel(i, j).G;
                    rgbImage[2, j, i] = bmp.GetPixel(i, j).B;
                }
            }

            try
            {
                matrix = new MWNumericArray();
                matrix = rgbImage;
            }
            catch (Exception ex)
            {
                string s = ex.InnerException.Message;
            }

            return(matrix);
        }
Example #17
0
        public static double[] InsertColumn(double[] a, double[] b, int idx)
        {
            var a1 = new MWNumericArray(1, a.Length, a);
            var b1 = new MWNumericArray(1, b.Length, b);

            return((double[])InsertColumn(a1, b1, idx).ToVector(MWArrayComponent.Real));
        }
Example #18
0
        private void button3_Click(object sender, EventArgs e)
        {
            MWNumericArray theta = new MWNumericArray(1, sample_counts, sample_position);
            MWNumericArray U_1   = new MWNumericArray(1, sample_counts, u1);
            MWNumericArray U_2   = new MWNumericArray(1, sample_counts, u2);

            Plot_User plot = new Plot_User();

            plot.Plot_Circle(U_1, U_2);

            MWArray[] result_1 = new Fit_Parameter.Class1().Fit_1(4, theta, U_1);
            MWArray[] result_2 = new Fit_Parameter.Class1().Fit_2(4, theta, U_2);
            //   up = (MWNumericArray)new Sensor.Sensor().envelope(theta, U_1);
            Array  a        = result_1.ToArray();
            Array  b        = result_2.ToArray();
            double envelope = (double.Parse(a.GetValue(2).ToString()) + double.Parse(b.GetValue(2).ToString())) / 2;
            double alpha    = (double.Parse(a.GetValue(3).ToString()) + double.Parse(b.GetValue(3).ToString())) / 2;

            textBox13.Text = a.GetValue(0).ToString(); //A_1
            textBox9.Text  = a.GetValue(1).ToString(); //d_1
            textBox14.Text = b.GetValue(0).ToString(); //A_2
            textBox10.Text = b.GetValue(1).ToString(); //d_2
            textBox18.Text = envelope.ToString();      //a_0
            textBox23.Text = alpha.ToString();         //alpha

            theta.Dispose();
            U_1.Dispose();
            U_2.Dispose();
        }
Example #19
0
        public SparseMatrix(MWNumericArray matlabArray)
        {
            double[,] data = (double[,])matlabArray.ToArray(MWArrayComponent.Real);
            int n = data.GetLength(0);

            values = new Dictionary<long, double>();
            rowElements = new HashSet<int>[n];
            columnElements = new HashSet<int>[n];

            size = n;

            for (int i = 0; i < n; ++i)
            {
                rowElements[i] = new HashSet<int>();
                columnElements[i] = new HashSet<int>();
            }

            for (int row = 0; row < n; ++row)
            {
                for (int col = 0; col < n; ++col)
                {
                    if (data[row, col] != 0) this[row, col] = (double)data[row, col];
                }
            }
        }
Example #20
0
        public static double[] corecurve(double[] x, double[] y)
        {
            var mx = new MWNumericArray(1, x.Length, x);
            var my = new MWNumericArray(1, y.Length, y);

            return((double[])((MWNumericArray)ToolHandler.corecurve(mx, my)).ToVector(MWArrayComponent.Real));
        }
Example #21
0
        public void Train(SpecBase lib, bool needFilter = true)
        {
            //过滤掉性质有NaN的数据
            lib.FilterNaN();
            int[] idxs = lib.Specs.Select((d, idx) => new { s = d, idx = idx }).Where(d => d.s.Usage != UsageTypeEnum.Ignore).Select(d => d.idx).ToArray();
            this._lib = Serialize.DeepClone <SpecBase>(lib.SubLib(idxs));
            if (needFilter && this._filters != null)
            {
                this._lib.SetX(Preprocesser.Process(this._filters, this._lib), true);
            }

            //PCA分解
            var handler = Tools.ModelHandler;

            if (this._maxRank < 1)
            {
                this._maxRank = 10;
            }
            this._maxRank = Math.Min(this._maxRank, this._lib.X.Dimensions[1]);
            var r = handler.IdentifyTrain(3, this._lib.X, this._maxRank);

            this._p       = (MWNumericArray)r[0];
            this._w       = (MWNumericArray)r[1];
            this._t       = (MWNumericArray)r[2];
            this._trained = true;
        }
Example #22
0
        private void getCV_btn_Click(object sender, EventArgs e)
        {
            /*if (mbSession == null)
             * {
             *  System.Windows.Forms.MessageBox.Show("当前没有连接到设备","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);
             * }
             * else
             * {
             *  ShowVCData form = new ShowVCData();
             *  form.SetmbSession(mbSession);
             *  form.setKind(true);
             *  form.Show();
             *
             * }*/

            double[] s = new double[500000];
            for (int i = 0; i < 500000; i++)
            {
                s[i] = new Random().NextDouble();
            }

            Class1         class1 = new Class1();
            MWNumericArray aaa    = (MWNumericArray)s;
            MWNumericArray res    = (MWNumericArray)class1.FFT(aaa);

            Console.WriteLine("OKKIKKKK");
        }
Example #23
0
        public override MWNumericArray Process(MWNumericArray m)
        {
            //throw new NotImplementedException();
            var d = Tools.FilterHandler.deriate2(m, this._winSize) as MWNumericArray;

            return(d);
        }
Example #24
0
        private void button1_Click(object sender, EventArgs e)
        {
            string Atext, convCoretext;

            convCoretext = textBox3.Text;
            Atext        = textBox4.Text;
            double Anum, convCorenum;

            Anum        = Convert.ToDouble(Atext);
            convCorenum = Convert.ToDouble(convCoretext);

            DehazeFunctionV2.Class1 v2c1 = new DehazeFunctionV2.Class1();
            MWArray[] resultlist         = new MWArray[2];
            resultlist = v2c1.DehazeFunctionV2(2, pathname, Anum, convCorenum);
            MWNumericArray Atmospherelight = (MWNumericArray)resultlist[0];
            MWNumericArray SSIM            = (MWNumericArray)resultlist[1];

            textBox2.Text = SSIM.ToString();

            string pathname2;

            pathname2 = "D:\\op\\cache\\temp.jpg";  //获得文件的绝对路径
                                                    //this.pictureBox2.Load(pathname2);//load貌似过时了?
                                                    // this.pictureBox2.Image = Image.FromFile(pathname2);
                                                    //    pictureBox2.Image.Dispose();
            FileStream pFileStream = new FileStream(pathname2, FileMode.Open, FileAccess.Read);

            outputImg.Image = Image.FromStream(pFileStream);
            pFileStream.Close();
            pFileStream.Dispose();
        }
Example #25
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);
        }
        public Bitmap Hog(Bitmap inputBitmap)
        {
            var inputBitmapHeight = inputBitmap.Height;
            var inputBitmapWidth  = inputBitmap.Width;

            var resultBitmap = new Bitmap(inputBitmapWidth, inputBitmapHeight);

            var rgbArrayOfInputBitmap = new byte[3, inputBitmapHeight, inputBitmapWidth];

            for (var j = 0; j < inputBitmapHeight; j++)
            {
                for (var i = 0; i < inputBitmapWidth; i++)
                {
                    rgbArrayOfInputBitmap[0, j, i] = inputBitmap.GetPixel(i, j).R;
                    rgbArrayOfInputBitmap[1, j, i] = inputBitmap.GetPixel(i, j).G;
                    rgbArrayOfInputBitmap[2, j, i] = inputBitmap.GetPixel(i, j).B;
                }
            }
            MWNumericArray imageMatrix        = rgbArrayOfInputBitmap;
            MWArray        resultBitmapMatrix = 0;

            resultBitmapMatrix = searchObjectByMatlabOperations.HOG_SVM(imageMatrix);

            for (var i = 0; i < inputBitmapHeight; i++)
            {
                for (var j = 0; j < inputBitmapWidth; j++)
                {
                    resultBitmap.SetPixel(j, i, Color.FromArgb(Convert.ToInt32(resultBitmapMatrix[i + 1, j + 1, 1].ToString()), Convert.ToInt32(resultBitmapMatrix[i + 1, j + 1, 2].ToString()), Convert.ToInt32(resultBitmapMatrix[i + 1, j + 1, 3].ToString())));
                }
            }
            return(resultBitmap);
        }
        private bool PopulateValues(ref MWNumericArray valuesArray)
        {
            string input = Console.ReadLine();

            string[] tokens       = input.Split(',');
            int      tokensLength = tokens.Length;

            if (tokensLength == 0)
            {
                return(false);
            }

            int value = 0, index = 0;

            int[] values = new int[tokensLength];

            foreach (string token in tokens)
            {
                if (int.TryParse(token, out value))
                {
                    values.SetValue(value, index++);
                }
                else
                {
                    return(false);
                }
            }

            valuesArray = new MWNumericArray(1, tokensLength, values);

            return(true);
        }
Example #28
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();//启动定时器
            }
        }
Example #29
0
    /// <summary>
    /// Generalised eigenvalues of A and B (analog to MATLAB M = eig(A,B))
    /// </summary>
    /// <param name="B">Matrix B</param>
    /// <returns>Generalised eigenvalues</returns>
    public Complex[] eige(Matrix B)
    {
        //calling Matlab API
        Eig testob = new Eig();

        //Matlab Array which gets result of Matlab function eig(A,B)
        res = testob.Eigenvalues(2, (MWNumericArray)this.matrix, (MWNumericArray)B.matrix, this.Rows());
        //arrays for real and imaginary parts
        real = (MWNumericArray)res[0];
        imag = (MWNumericArray)res[1];
        //copying parts into CSharp arrays
        double[,] resCR = (double[, ])real.ToArray(MWArrayComponent.Real);
        double[,] resCI = (double[, ])imag.ToArray(MWArrayComponent.Real);

        this.eigenvalues = new Complex[21];
        Complex[] eigenbuf = new Complex[this.rows];

        for (int i = 0; i < this.rows; i++)
        {
            eigenbuf[i] = new Complex(resCR[i, 0], resCI[i, 0]);
            eigenbuf[i] = eigenbuf[i].Pow(0.5);
        }

        Complex buf = new Complex();

        buf.quickSort(ref eigenbuf, 0, this.rows - 1);

        for (int i = 0; i < 21; i++)
        {
            this.eigenvalues[i] = eigenbuf[200 + i - 1];
        }
        return(this.eigenvalues);
    }
Example #30
0
        public Form1()
        {
            InitializeComponent();

            //create Object from your dll
            mymatrix.Class1 MyObject = new mymatrix.Class1();

            //run the method which gets the data and save in a MWArray object
            MWArray MatlabData = MyObject.mymatrix();

            //cast the data to MWNumericArray
            MWNumericArray TableValuesMat = (MWNumericArray)MatlabData;

            // now cast to a double array
            double[,] TableValues = (double[, ])TableValuesMat.ToArray();

            // now convert 2d array to a table in gridview:
            int height = TableValues.GetLength(0);
            int width  = TableValues.GetLength(1);

            this.dataGridView1.ColumnCount = width;
            for (int r = 0; r < height; r++)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(this.dataGridView1);

                for (int c = 0; c < width; c++)
                {
                    row.Cells[c].Value = TableValues[r, c];
                }

                this.dataGridView1.Rows.Add(row);
            }
        }
Example #31
0
        public static double CalcWeist(double[] x, double[] y)
        {
            Logger log = new Logger();

            log.Debug("Matlab prepare");
            Weist w = new Weist();

            MWNumericArray matlabX = new MWNumericArray(MWArrayComplexity.Real, x.Length, 1);
            MWNumericArray matlabY = new MWNumericArray(MWArrayComplexity.Real, y.Length, 1);

            MWArray[] agrsOut = new MWArray[3];
            MWArray[] agrsIn  = new MWArray[] { (MWNumericArray)matlabX, (MWNumericArray)matlabY };

            for (int i = 0; i < x.Length; i++)
            {
                matlabX[i + 1] = x[i];
                matlabY[i + 1] = y[i];
            }
            log.Debug("Matlab calculate");
            w.weist(3, ref agrsOut, agrsIn);

            double o    = double.Parse(agrsOut[0].ToString());
            double z    = double.Parse(agrsOut[1].ToString());
            string info = agrsOut[2].ToString();

            log.Debug("Matlab done");

            return(o);
        }
Example #32
0
        public double[,] doFFT(double[] sinal, double freqAm)
        {
            double[] resY = new double[sinal.Length];
            double[] resX = new double[sinal.Length];
            double[,] res = new double[sinal.Length, 2];

            MWNumericArray aux_res2  = new MWNumericArray(new double[sinal.Length]);
            MWNumericArray aux_res2X = new MWNumericArray(new double[sinal.Length]);
            MWNumericArray xdt       = new MWNumericArray(new double[sinal.Length]);
            Array          aux_res3  = null;
            Array          aux_res3X = null;
            fftMatlab2     obj       = new fftMatlab2();

            xdt = sinal;

            MWArray aux_res  = obj.IB_fft(xdt, freqAm);
            MWArray aux_resX = obj.IB_fftx(xdt, freqAm);

            aux_res2X = (MWNumericArray)aux_resX;
            aux_res2  = (MWNumericArray)aux_res;

            aux_res3X = aux_res2X.ToVector(MWArrayComponent.Real);
            aux_res3  = aux_res2.ToVector(MWArrayComponent.Real);


            resY = (double[])aux_res3;
            resX = (double[])aux_res3X;
            for (int i = 0; i < resX.Length; i++)
            {
                res[i, 0] = resY[i]; //linha 0 valores de Y
                res[i, 1] = resX[i]; //linha 1 valores de X
            }

            return(res);
        }
        // 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;
        }
        public override bool ProcessInput()
        {
            Console.WriteLine("Please input the values for x separated by commas");
            string input = Console.ReadLine();

            string[] tokens       = input.Split(',');
            int      tokensLength = tokens.Length;

            if (tokensLength == 0)
            {
                return(false);
            }

            int value = 0, index = 0;

            int[] values = new int[tokensLength];

            foreach (string token in tokens)
            {
                if (int.TryParse(token, out value))
                {
                    values.SetValue(value, index++);
                }
                else
                {
                    return(false);
                }
            }

            xValues = new MWNumericArray(1, tokensLength, values);

            return(true);
        }
        private void bgwMatlabGen_DoWork(object sender, DoWorkEventArgs e)
        {
            ArrayList lit = e.Argument as ArrayList;

            e.Result = true;

            try
            {
                MWNumericArray fc_Hz         = (double)lit[0],
                               chanUpdate_ms = (double)lit[1],
                               polarMod      = (double)lit[2],
                               mediaPara     = (double[])lit[3],
                               angSpread_deg = (double)lit[4],
                               chanMod       = (double)lit[5];
                MWCharArray traFilePath      = lit[6] as string,
                            launAnteFilePath = lit[7] as string,
                            recvAnteFilePath = lit[8] as string,
                            chanParaSavePath = lit[9] as string,
                            chanSavePath     = lit[10] as string;

                MWArray[] matlabRlt = aeroChan.AeroChanGenerate(2, fc_Hz, chanUpdate_ms, polarMod, mediaPara, angSpread_deg, chanMod, traFilePath, launAnteFilePath, recvAnteFilePath, chanParaSavePath, chanSavePath);
                if ((matlabRlt[0] as MWNumericArray).ToScalarInteger() != 0)
                {
                    e.Result  = false;
                    lastError = matlabRlt[1].ToString();
                    return;
                }
            }
            catch (Exception ex)
            {
                e.Result  = false;
                lastError = "调用Matlab失败!";
            }
        }
Example #36
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);
        }
Example #37
0
 static void Main(string[] args)
 {
     Directory.SetCurrentDirectory(@"G:\");
     POAMAforecast.Class1 d = new POAMAforecast.Class1();
     MWArray metFile = new MWCharArray(@"Burnie.sim");
     MWArray startMonth = new MWNumericArray((double) 6.0);
     MWArray startDay = new MWNumericArray((double) 1.0);
     MWArray rainOnly = new MWNumericArray((double)1.0);
     MWArray writeFiles = new MWNumericArray((double)1.0);
     MWArray lastYearOnly = new MWNumericArray((double)1.0);
     d.calsite(metFile, startMonth, startDay, rainOnly, writeFiles, lastYearOnly);
 }
Example #38
0
 public Image addNoise(string type, Image src, double a, double b)
 {
     MWLogicalArray mw_print = new MWLogicalArray(Form1.print);
     MWArray Result = noise(type, new MWNumericArray(src.Array.Array), a, b, mw_print);
     Image res = new Image((double[,])((MWNumericArray)Result).ToArray(MWArrayComponent.Real));
     MWNumericArray tmp = new MWNumericArray(res.Array.Array);
     res.image = (MWArray)tmp;
     Result = null;
     tmp = null;
     GC.Collect();
     return res;
 }
Example #39
0
        /// <summary>
        /// 生成信号序列
        /// </summary>
        /// <param name="signal_type">信号类型</param>
        /// <param name="ray_angles">波束方向集合</param>
        /// <param name="ray_strengths">波束强度集合</param>
        /// <param name="ray_taus">波束时延集合</param>
        /// <param name="N">序列点数</param>
        /// <param name="args">args参数集合,与信号类型相关</param>
        /// <returns>信号序列</returns>
        public MWNumericArray GenerateSignal_MW(Signal_Type signal_type, double[] ray_angles, double[] ray_strengths, double[] ray_taus, int N, double[] args)
        {
            if (ray_angles.Length != ray_strengths.Length || ray_strengths.Length != ray_taus.Length)
                throw new Exception("波束角度、强度和延时数组必须具有相同长度!");

            if (ray_angles.Length == 0)
                return null;

            MWNumericArray len = new MWNumericArray(N);
            switch (signal_type)
            {
                case Signal_Type.PSEUDO_DOPPLER:
                    {
                        MWNumericArray fl = new MWNumericArray(args[0]);
                        MWNumericArray fc = new MWNumericArray(args[1]);
                        MWNumericArray fs = new MWNumericArray(args[2]);
                        MWNumericArray fswitch = new MWNumericArray(args[3]);
                        MWNumericArray R = new MWNumericArray(args[4]);
                        MWNumericArray NA = new MWNumericArray(args[5]);
                        MWNumericArray sum = (MWNumericArray)sptb.GenerateSignal_PseudoDoppler(new MWNumericArray(ray_strengths[0]),
                                                                                               fl,
                                                                                               fc,
                                                                                               fs,
                                                                                               fswitch,
                                                                                               R,
                                                                                               NA,
                                                                                               new MWNumericArray(ray_angles[0]),
                                                                                               new MWNumericArray(ray_taus[0]),
                                                                                               len);
                        for (int i = 1; i < ray_angles.Length; i++)
                        {
                            MWNumericArray sub = (MWNumericArray)sptb.GenerateSignal_PseudoDoppler(new MWNumericArray(ray_strengths[i]),
                                                                                                   fl,
                                                                                                   fc,
                                                                                                   fs,
                                                                                                   fswitch,
                                                                                                   R,
                                                                                                   NA,
                                                                                                   new MWNumericArray(ray_angles[i]),
                                                                                                   new MWNumericArray(ray_taus[i]),
                                                                                                   len);
                            sum = (MWNumericArray)sptb.Add(sum, sub);
                        }
                        return sum;
                    }
            }
            return null;
        }
Example #40
0
        public static void Analyze(System.ComponentModel.BackgroundWorker worker)
        {
            int i = 0;
            foreach (string file in Directory.GetFiles("C:\\Users\\Forpatril\\Documents\\Visual Studio 2010\\Projects\\Diploma_cs\\Images", "*.jpg"))
            {
                Image img = new Image(file);
                for (int w = 2; w < 35; w++)
                    for (int sig = 1; sig < w / 2; sig++)
                    {
                        filterclass fc = new filterclass();
                        Noise n = new Noise();
                        Image img_n = n.addNoise("gaussian", img, 0, 0.055);
                        double[] p = new double[] {w, sig, 0.2};
                        MWNumericArray parameters = new MWNumericArray(p);
                        MWLogicalArray mw_print = new MWLogicalArray(Form1.print);
                        MWArray[] Result = fc.filter2(2, img_n.image, "bilateral", parameters, mw_print);
                        MWNumericArray descriptor = null;
                        descriptor = (MWNumericArray)Result[0];
                        double[,] result = null;
                        result = (double[,])descriptor.ToArray(MWArrayComponent.Real);
                        Image ret = new Image(result);
                        MWNumericArray e_descriptor = null;
                        e_descriptor = (MWNumericArray)Result[1];
                        ret.Time = (double)e_descriptor.ToScalarDouble();

                        filterDataContext db = new filterDataContext();
                        psnrClass ps = new psnrClass();
                        double psnr = (double)((MWNumericArray)ps.psnr(ret.image, img.image)).ToScalarDouble();
                        db.add_line("bilateral", "gaussian", img.Height, img.Width, ret.Time, psnr, p[0], p[1], p[2]);


                        Result = null;
                        e_descriptor = null;
                        result = null;
                        parameters = null;
                        img_n = null;
                        n = null;
                        descriptor = null;
                        ret = null;
                        ps = null;
                        fc = null;
                        GC.Collect();
                    }
                worker.ReportProgress(i++);
                img = null;
                GC.Collect();
            }
        }
        //@param s_id subject id
        //@param ecg_in a single sample value of the subject's ECG
        public void enrollment(double[] ecg_in, int s_id)
        {
            for( int i = 0; i < ecg_in.Length; i++)
            {
                ecg[i] = ecg_in[i];
            }

            //Create a MWArray to pass value into converted matlab function
                MWNumericArray subj_id = new MWNumericArray(s_id);
                MWNumericArray ecg_raw = new MWNumericArray(1280, 1, ecg);
                MWArray temp = AClass.process(ecg_raw, M);  //process ecg data(filter and AC)

                //autocorrelated signal is added to both gallery
                MWArray gal = new MWNumericArray();
                gal = gallery;
                gallery = AClass.addtogallery(gal, temp);

                MWArray gal1 = new MWNumericArray();
                gal1 = enrollee_gallery;
                enrollee_gallery = AClass.addtogallery(gal1, temp);

                //subject id is added to the id vector
                MWArray id_temp = new MWNumericArray();
                id_temp = id;
                id = AClass.addtoid(id_temp, subj_id);

                MWArray id_temp1 = new MWNumericArray();
                id_temp1 = enrollee_id;
                enrollee_id = AClass.addtoid(id_temp1, subj_id);

                //the weight matric is calculated
                weights = AClass.dlda(gallery, id);

                //enrollee gallery is projected
                projected_gallery = AClass.projection(gallery, weights); //use enrollee gallery if want to project enrollee gallery
        }
Example #42
0
 public Image RunFilter(Image src, int id)
 {
     filterDataContext db = new filterDataContext();
     double[] p = new double[Form1.pars.par[id].Length];
     p = Form1.pars.par[id];
     MWNumericArray parameters = new MWNumericArray(p);
     MWLogicalArray mw_print = new MWLogicalArray(Form1.print);
     MWArray[] Result = filter2(2, src.image, type[id], parameters, mw_print);
     MWNumericArray descriptor = null;
     descriptor = (MWNumericArray)Result[0];
     double[,] result = null;
     result = (double[,])descriptor.ToArray(MWArrayComponent.Real);
     Image res = new Image(result);
     MWNumericArray e_descriptor = null;
     e_descriptor = (MWNumericArray)Result[1];
     res.Time = WorkTime = (double)e_descriptor.ToScalarDouble();
     //db.add_b_res(src.Height, src.Height / src.Width, WorkTime, w, sigma[0], sigma[1]);
     Result = null;
     e_descriptor = null;
     result = null;
     parameters = null;
     GC.Collect();
     return res;
 }
        public static double[,] cont_wavelet_transform(double[] input_signal, double[] scale, string wavelet)
        {
            CWT.CWT_Class c = new CWT.CWT_Class();

            int numSamples = input_signal.Length;// SPM.Count;

            MWNumericArray data = new MWNumericArray(MWArrayComplexity.Real, MWNumericType.Double, numSamples);
            MWNumericArray scale_m = new MWNumericArray(MWArrayComplexity.Real, MWNumericType.Double, scale.Length);
            MWCharArray name = new MWCharArray(wavelet);
            for (int idx = 1; idx <= scale.Length; idx++)
            {
                scale_m[idx] = scale[idx - 1];

            }

            // Initialize data 
            for (int idx = 1; idx <= numSamples; idx++)
            {
                data[idx] = input_signal[idx - 1];
            }
            MWNumericArray res = (MWNumericArray)c.PerformCWT(data, scale_m, name);
            double[,] coeffs = (double[,])(res.ToArray(MWArrayComponent.Real));
            return coeffs;
        }
Example #44
0
 private SparseMatrix GenerateInnerWeights(int size)
 {
     ESNclass esn = new ESNclass();
     MWNumericArray _size = new MWNumericArray(size);
     MWNumericArray _ratio = new MWNumericArray(0.05f);
     MWArray ret = esn.ESNInnerWeights(_size, _ratio);
     return new SparseMatrix((MWNumericArray)ret);            
 }
Example #45
0
 /// <summary>
 /// 生成指纹
 /// </summary>
 /// <param name="signal_type">信号类型</param>
 /// <param name="fingerprint_name">指纹类型</param>
 /// <param name="signals">各接收站的信号集合</param>
 /// <param name="args">args参数集合,与信号类型有关</param>
 /// <returns>指纹参数集合,与指纹类型有关</returns>
 public Fingerprint GenerateFingerprint(Signal_Type signal_type, Fingerprint_Name fingerprint_name, MWNumericArray[] signals, double[] args)
 {
     switch(fingerprint_name)
     {
         case Fingerprint_Name.S:
             {
                 Fingerprint_S.S[] ss = new Fingerprint_S.S[signals.Length];
                 for (int i = 0; i < signals.Length; i++)
                 {
                     if (signals[i] == null)
                         ss[i] = new Fingerprint_S.S();
                     else
                     {
                         MWNumericArray s = (MWNumericArray)sptb.CalcStrength(signals[i]);
                         ss[i] = new Fingerprint_S.S(s.ToScalarDouble());
                     }
                 }
                 Fingerprint_S fp = new Fingerprint_S(ss);
                 return fp;
             }
         case Fingerprint_Name.SA:
             {
                 Fingerprint_SA.SA[] sas = new Fingerprint_SA.SA[signals.Length];
                 switch(signal_type)
                 {
                     case Signal_Type.PSEUDO_DOPPLER:
                         {
                             MWNumericArray fl = new MWNumericArray(args[0]);
                             MWNumericArray fc = new MWNumericArray(args[1]);
                             MWNumericArray fs = new MWNumericArray(args[2]);
                             MWNumericArray fswitch = new MWNumericArray(args[3]);
                             MWNumericArray R = new MWNumericArray(args[4]);
                             MWNumericArray NA = new MWNumericArray(args[5]);
                             for (int i = 0; i < signals.Length; i++)
                             {
                                 if (signals[i] == null)
                                     sas[i] = new Fingerprint_SA.SA();
                                 else
                                 {
                                     MWNumericArray s = (MWNumericArray)sptb.CalcStrength(signals[i]);
                                     MWNumericArray aoa = (MWNumericArray)sptb.CalcPseudoDopplerAOA(signals[i], fl, fc, fs, fswitch, R, NA);
                                     sas[i] = new Fingerprint_SA.SA(s.ToScalarDouble(), aoa.ToScalarDouble());
                                 }
                             }
                             Fingerprint_SA fp = new Fingerprint_SA(sas);
                             return fp;
                         }
                 }
                 return null;
             }
     }
     return null;
 }
 public MWArray ToSingleMatlabArray()
 {
     MWNumericArray result = null;
     byte[,] data = new byte[Height, Width];
     for (int i = 0; i < Height; i++)
     {
         for (int j = 0; j < Width; j++)
         {
             Pixel p = GetPixel(j, i);
             data[i, j] = p.R;
         }
     }
     result = new MWNumericArray(MWArrayComplexity.Real, MWNumericType.UInt8, Height, Width);
     result = data;
     return result;
 }
Example #47
0
 /// <summary>
 /// 进行单次指纹生成仿真,包括信号生成、加噪和指纹生成
 /// </summary>
 /// <param name="signal_type">信号类型</param>
 /// <param name="noise_type">噪声类型</param>
 /// <param name="noise_params">噪声参数集合,与噪声类型有关</param>
 /// <param name="fingerprint_name">指纹类型</param>
 /// <param name="ray_angles">波束方向集合</param>
 /// <param name="ray_strengths">波束强度集合</param>
 /// <param name="ray_taus">波束时延集合</param>
 /// <param name="N">信号点数</param>
 /// <param name="args">args参数集合,与信号类型有关</param>
 /// <returns></returns>
 public Fingerprint SingleFingerprintSim(Signal_Type signal_type, Noise_Type noise_type, double[] noise_params,
                                      Fingerprint_Name fingerprint_name, List<double>[] ray_angles, List<double>[] ray_strengths,
                                      List<double>[] ray_taus, int N, double[] args)
 {
     MWNumericArray[] signals = new MWNumericArray[ray_angles.GetLength(0)];
     for(int i = 0; i < signals.Length; i++)
     {
         signals[i] = this.GenerateSignal_MW(signal_type, ray_angles[i].ToArray(), ray_strengths[i].ToArray(), ray_taus[i].ToArray(), N, args);
         signals[i] = this.AddNoise_MW(noise_type, signals[i], noise_params);
     }
     Fingerprint fp = this.GenerateFingerprint(signal_type, fingerprint_name, signals, args);
     return fp;
 }
Example #48
0
        public Vector SolveLinearEquation2(Vector y) // this * result = y
        {
            List<int> rows = new List<int>();
            List<int> cols = new List<int>();
            List<double> fvalues = new List<double>();

            foreach (long i in values.Keys)
            {
                rows.Add(Row(i)+1);
                cols.Add(Column(i)+1);
                fvalues.Add(this[i]);
            }

            MWNumericArray _rows = new MWNumericArray(rows.Count, 1, rows.ToArray());
            MWNumericArray _cols = new MWNumericArray(cols.Count, 1, cols.ToArray());
            MWNumericArray _values = new MWNumericArray(fvalues.Count, 1, fvalues.ToArray());
            MWNumericArray _y = new MWNumericArray(y.Elements.Length, 1, y.Elements);            

            solveclass solve = new solveclass();
            MWNumericArray ret = (MWNumericArray)solve.solve(_rows, _cols, _values, _y);
            double[,] fret = (double[,])ret.ToArray(MWArrayComponent.Real);
            double[] fret2 = new double[fret.GetLength(0)];
            for (int i = 0; i < fret2.Length; ++i)
            {
                fret2[i] = (double)fret[i, 0];
            }
            return new Vector(fret2);            
        }
Example #49
0
        /*
        private void button1_Click_1(object sender, EventArgs e)
        {
            brisiPrikaz();

            sistem = 1;
            melodijaPt();
            ton1(900, 5f);
            visaj(900, 1.5f);
            ton2(50, 2f,false);
            ton2(150, 2f, true);
            ton4(100, 3f,true);
            ton4(200, 3f, false);
            ton8(250, 3f, false);
            ton8(300, 3f, true);
            visaj(300, 3f);
            podaljsaj(300, 3f);
            ton16(350, 3f, true);
            ton16(400, 3f, false);
            ton32(450, 3f, true);
            ton32(500, 3f, false);
            pavza1(550);
            pavza2(600);
            pavza4(650);
            pavza8(700);
            ton1(750, 1.5f);
            visaj(750, 1.5f);
            pavza2(800);
            pavza2(850);
            ton1(900, 1.5f);
            visaj(900, 1.5f);

            sistem = 2;
            melodijaPt();
            ton1(900, 1.5f);
            visaj(900, 1.5f);
            pomCrta(200, -1f);
            pomCrta(200, 7f);
            ton1(200, 5.5f);
            ton2(200, -0.5f, false);
            ton2(50, -0.5f, false);
            ton2(150, 2f, true);
            ton4(100, 3f, true);

            ton8(250, 3f, false);
            ton8(300, 3f, true);
            visaj(300, 3f);
            ton16(350, 3f, true);
            ton16(400, 3f, false);
            pavza1(550);
            pavza2(600);
            pavza4(650);
            pavza8(700);

            sistem = 3;
            melodijaPt();
            visaj(550, 1f);
            ton32(550, 1f, true);
            ton1(900, 1.5f);
            visaj(900, 1.5f);
            ton2(50, 2f, false);
            ton2(150, 2f, true);
            ton4(100, 3f, true);
            ton4(200, 3f, false);
            ton8(250, 3f, false);
            ton8(300, 3f, true);
            visaj(300, 3f);
            ton16(350, 3f, true);
            ton16(400, 3f, false);
            pavza1(550);
            pavza2(600);
            pavza4(650);
            pavza8(700);

            sistem = 4;
            melodijaPt();
            ton1(900, 1.5f);
            visaj(900, 1.5f);
            ton2(50, 2f, false);
            ton2(150, 2f, true);
            ton4(100, 3f, true);
            ton4(200, 3f, false);
            ton8(250, 3f, false);
            ton8(300, 3f, true);
            visaj(300, 3f);
            ton16(350, 3f, true);
            ton16(400, 3f, false);

            melodijaP.Image = bmp;
        }*/
        //razpoznaj
        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                brisiPrikaz();
                Praktikium.Matlab razp = new Praktikium.Matlab();

                MWArray argin = datoteka;
                MWArray argout = new MWNumericArray();

                argout = razp.razpoznajMatlab(argin);

                //izhod
                MWNumericArray tmpArray = (MWNumericArray)argout;

                double[, ,] izhodnaMatrika = (double[, ,])tmpArray.ToArray(MWArrayComponent.Real);
                izhodnaMatrika[0, 0, 2] = izhodnaMatrika[0, 0, 2] + 1000;
                int[,] rezultat = new int[izhodnaMatrika.Length / 3, 3];
                for (int i = 0; i < izhodnaMatrika.Length / 3; i++)
                {
                    rezultat[i, 0] = Convert.ToInt32(izhodnaMatrika[i, 0, 0]);
                    rezultat[i, 1] = Convert.ToInt32(izhodnaMatrika[i, 0, 1]);
                    rezultat[i, 2] = Convert.ToInt32(izhodnaMatrika[i, 0, 2]);
                }

                String[] toni = { "A0", "Ais", "H0", "C1", "Cis1", "D1", "Dis1", "E1", "F1", "Fis1", "G1", "Gis1", "A1", "Ais1", "H1", "C2", "Cis2", "D2", "Dis2", "E2", "F2", "Fis2", "G2", "Gis2", "A2", "Ais2", "H2", "C3", "Cis3", "D3", "Dis3", "E3", "F3", "Fis3", "G3", "Gis3", "A3", "Ais3", "H3", "C4", "Cis4", "D4", "Dis4", "E4", "F4", "Fis4", "G4", "Gis4", "A4", "Ais4", "H4", "C5", "Cis5", "D5", "Dis5", "E5", "F5", "Fis5", "G5", "Gis5", "A5", "Ais5", "H5", "C6", "Cis6", "D6", "Dis6", "E6", "F6", "Fis6", "G6", "Gis6", "A6", "Ais6", "H6", "C7", "Cis7", "D7", "Dis7", "E7", "F7", "Fis7", "G7", "Gis7", "A7", "Ais7", "H7", "C8" };
                double[] frekvence = { 27.5000, 29.1352, 30.8677, 32.7032, 34.6478, 36.7081, 38.8909, 41.2034, 43.6535, 46.2493, 48.9994, 51.9131, 55.0000, 58.2705, 61.7354, 65.4064, 69.2957, 73.4162, 77.7817, 82.4069, 87.3071, 92.4986, 97.9989, 103.826, 110.000, 116.541, 123.471, 130.813, 138.591, 146.832, 155.563, 164.814, 174.614, 184.997, 195.998, 207.652, 220.000, 233.082, 246.942, 261.626, 277.183, 293.665, 311.127, 329.628, 349.228, 369.994, 391.995, 415.305, 440.000, 466.164, 493.883, 523.251, 554.365, 587.330, 622.254, 659.255, 698.456, 739.989, 783.991, 830.609, 880.000, 932.328, 987.767, 1046.50, 1108.73, 1174.66, 1244.51, 1318.51, 1396.91, 1479.98, 1567.98, 1661.22, 1760.00, 1864.66, 1975.53, 2093.00, 2217.46, 2349.32, 2489.02, 2637.02, 2793.83, 2959.96, 3135.96, 3322.44, 3520.00, 3729.31, 3951.07, 4186.01 };

                List<String> najdeniToni = new List<string>();
                List<int> dolzineTonov = new List<int>();
                int dolzinaCelotna = rezultat[0, 0];

                int najkrajsi = 1000000;
                int najdaljsi = 0;

                //polje za iskanje pavz
                int[] kjesopavze = new int[rezultat[0, 2]];
                for (int i = 0; i < kjesopavze.Length; i++)
                {
                    kjesopavze[i] = 0;
                }

                for (int i = 1; i < rezultat.Length / 3; i++)
                {

                    for (int j = rezultat[i, 1]; j < rezultat[i, 2]; j++)
                    {
                        kjesopavze[j] = 1;
                    }
                }

                List<List<double>> pavze = new List<List<double>>();

                bool zacF = false;
                int zac = 0;
                int kon = 0;
                for (int i = 0; i < kjesopavze.Length; i++)
                {
                    if (kjesopavze[i] == 0 && !zacF)
                    {
                        zac = 0;
                        kon = 0;
                        zac = i;
                        zacF = true;
                    }
                    if (kjesopavze[i] == 1 && zacF)
                    {
                        zacF = false;
                        kon = i;
                        List<double> lista = new List<double>();
                        lista.Add(zac);
                        lista.Add(kon);
                        pavze.Add(lista);
                    }
                }

                //dodam pavze - njihovo trajanje za kasnejsi rmz
                int ij = 0;
                for (int j = 1; j < rezultat.Length / 3; j++)
                {
                    if (rezultat[j, 1] > ij && j == 1)
                    {
                        najdeniToni.Add("p-");
                        dolzineTonov.Add(rezultat[j, 1]);
                        ij = rezultat[j, 1];
                    }
                    else if (rezultat[j, 1] > rezultat[j - 1, 2])
                    {
                        najdeniToni.Add("p-");
                        dolzineTonov.Add(rezultat[j, 1] - rezultat[j - 1, 2]);
                        ij = rezultat[j, 1];
                    }

                    if (rezultat[j, 1] <= ij) //smo v tonu
                    {
                        for (int k = 0; k < frekvence.Length; k++)
                        {
                            if (rezultat[j, 0] == Math.Round(frekvence[k], 0))
                            {
                                int trenutna = rezultat[j, 2] - rezultat[j, 1];
                                najdeniToni.Add(toni[k] + "-");
                                dolzineTonov.Add(trenutna);

                                if (trenutna < najkrajsi) { najkrajsi = trenutna; }
                                if (trenutna > najdaljsi) { najdaljsi = trenutna; }
                            }
                            ij = rezultat[j, 2];
                        }
                    }
                }

                //grem cez cel zapis in pisem tone in pavze

                int celinka = najkrajsi * 4;

                //algoritem za postavljanje dob tonov
                List<List<double>> vseDobe = new List<List<double>>();
                for (int i = 0; i < dolzineTonov.Count; i++)
                {
                    List<double> dobe = new List<double>();
                    int dol = dolzineTonov[i];
                    int ost = 1;
                    int trenutno = celinka;
                    int tonTempo = 1;
                    for (int t = 0; t < 6; t++)
                    {
                        if (dol > 4000)
                        {
                            if (dol >= trenutno)
                            {
                                ost = dol / trenutno;

                                for (int j = 0; j < ost; j++)
                                {
                                    dobe.Add(tonTempo);
                                }
                                dol = dol - (ost * trenutno);
                            }
                            trenutno = trenutno / 2; //celinka->polovinka
                            tonTempo++;
                        }
                    }
                    vseDobe.Add(dobe);
                }

                //algoritem za izdelavo rmz zapisa
                //
                //vseDobe vsebujejo tempo
                //najdeniToni vsebujejo imena tonov
                //G3-4;A3-4;H3-4;C4-4;D4-4;G4-16;A4-1;p-4;D4-4;F4-8;p-1;

                for (int i = 0; i < najdeniToni.Count; i++)
                {
                    for (int j = 0; j < vseDobe[i].Count; j++)
                    {
                        double doba = vseDobe[i][j];
                        if (doba == 3) { doba = 4; }
                        else if (doba == 3) { doba = 4; }
                        else if (doba == 4) { doba = 8; }
                        else if (doba == 5) { doba = 16; }
                        else if (doba == 6) { doba = 32; }

                        melodija += najdeniToni[i] + doba + ";";
                    }
                }
                narisi();
            }
            catch (Exception er)
            {
                MessageBox.Show("Napaka pri iskanju frekvenc...");
            }
        }
        private void StartCalibration()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
            ss.K = Double.Parse(this.labelk.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.Lambda_X = Double.Parse(this.labellambdax.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.Sigma_x = Double.Parse(this.labelsigma_x.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.Mu_e = Double.Parse(this.labelmu_e.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.Sigma_e = Double.Parse(this.labelsigma_e.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.Lambda_e = Double.Parse(this.labellambdae.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.P_xe = Double.Parse(this.labelpxe.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.e0 = Double.Parse(this.labele0.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.x0 = Double.Parse(this.labelx0.Text, NumberStyles.AllowDecimalPoint | NumberStyles.Float);
            ss.MaxIter = Int32.Parse(this.labelMaxIter.Text);
            try
            {
            MWNumericArray maxitera = new MWNumericArray(ss.MaxIter);
            MWNumericArray e0a = new MWNumericArray(ss.e0);
            MWNumericArray x0a = new MWNumericArray(ss.x0);
            MWNumericArray maturity = new MWNumericArray(maturities.ToArray());
            MWNumericArray futures = new MWNumericArray(pcount, lcount - 1, futureList.ToArray());
            MWNumericArray k = new MWNumericArray(ss.K);
            MWNumericArray lambdax = new MWNumericArray(ss.Lambda_X);
            MWNumericArray lambdae = new MWNumericArray(ss.Lambda_e);
            MWNumericArray sigmax = new MWNumericArray(ss.Sigma_x);
            MWNumericArray sigmae = new MWNumericArray(ss.Sigma_e);
            MWNumericArray p_xe = new MWNumericArray(ss.P_xe);
            MWNumericArray mu_e = new MWNumericArray(ss.Mu_e);
            Schwartz.Schwartz s = null;

                 s = new Schwartz.Schwartz();

            MWArray[] Results;
            try
            {
                /** Call matlab */
                Results = (MWArray[])s.SchwartzAndSmith(12,maxitera, x0a, e0a, maturity, futures, k, mu_e, sigmax, sigmae, p_xe, lambdae, lambdax);
            }
            catch
            {
                MessageBox.Show("Calibration aborted!");
                return;
            }

            /** Spot vector */
            double[,] ret = (double[,])Results[0].ToArray();
            this.generatedSpot = new double[ret.Length];
            for (int i = 0; i < ret.Length; i++)
                this.generatedSpot[i] = ret[0, i];

            ss.K = (double)((MWNumericArray)Results[1]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.Mu_e = (double)((MWNumericArray)Results[2]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.Sigma_x = (double)((MWNumericArray)Results[3]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.Sigma_e = (double)((MWNumericArray)Results[4]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.P_xe = (double)((MWNumericArray)Results[5]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.Lambda_e = (double)((MWNumericArray)Results[6]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.Lambda_X = (double)((MWNumericArray)Results[7]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.x0 = (double)((MWNumericArray)Results[8]).ToVector(MWArrayComponent.Real).GetValue(0);
            ss.e0 = (double)((MWNumericArray)Results[9]).ToVector(MWArrayComponent.Real).GetValue(0);
            likelihood = (double)((MWNumericArray)Results[10]).ToVector(MWArrayComponent.Real).GetValue(0);
            nbiter = (int)((double)((MWNumericArray)Results[11]).ToVector(MWArrayComponent.Real).GetValue(0));
            }
            catch (Exception)
            {
                MessageBox.Show("It seems your computer does not have a working copy of the Matlab Compiler Runtime\n Calibration cannot be done without, but you can still use the rest of the program.");
                this.Invoke(new CalibrationDoneCallback(CalibrationDone), this);
                return;

            }
            this.Invoke(new CalibrationDoneCallback(CalibrationDone), this);
        }
Example #51
0
        public Image(double[,] values)
        {
            Array = new ImageArray(values);
            Height = Array.Array.GetLength(0);
            Width = Array.Array.GetLength(1);
            GetBitmap();
            
            /*
            string tp = "C:\\" + GetRandomName()+".bmp";

            Bitmap.Save(tp,);
            Loader tmp = new Loader();
            image = tmp.loadimage(new MWCharArray(tp));
            tmp.Dispose();
            File.Delete(tp);
            */
            MWNumericArray tmp = new MWNumericArray(values);
            image = (MWArray)tmp;

            tmp = null;
            GC.Collect();
        }
Example #52
0
        //@2BTESTED
        /// <summary>
        ///     For an effectivly use of the matlab function, this method is designed for 1-step generating a
        ///     cloud's probablity. So when using this method, you need to format your current positions in
        ///     2 arrays and an strength array additionaly.
        /// </summary>
        /// <param name="apId">Ap id</param>
        /// <param name="x">X array</param>
        /// <param name="y">Y array</param>
        /// <param name="strength">Current signal strength</param>
        /// <returns>The probablities</returns>
        public double[] GetProbalities(string apId, double[] x, double[] y, double strength)
        {
            var mX = new MWNumericArray(x.Length, 1, x);
            var mY = new MWNumericArray(y.Length, 1, y);
            var mTrainX = new MWNumericArray(_trainX[apId].Count, 1, _trainX[apId].ToArray());
            var mTrainY = new MWNumericArray(_trainY[apId].Count, 1, _trainY[apId].ToArray());
            var mStrength = new MWNumericArray(_trainStrength[apId].Count, 1, _trainStrength[apId].ToArray());

            MWArray[] outPut = _gt.Predict(2, _paras[apId], 1, mTrainX, mTrainY, mStrength, mX, mY);
            var resM = (double[]) (((MWNumericArray) outPut[0]).ToVector(MWArrayComponent.Real));
            var resV = (double[]) (((MWNumericArray) outPut[1]).ToVector(MWArrayComponent.Real));

            var res = new List<double>();
            for (int i = 0; i < x.Length; i++)
            {
                res.Add(BasicMath.GetGaussianProbability(resM[i], resV[i], strength));
            }
            return res.ToArray(); //The results' consequence needs checkout.
        }
Example #53
0
        /// <summary>
        ///     When training points are all recorded or to a certain number,
        ///     the model training is run and the paras are renew then restored into _paras.
        ///     But we'll decide when and why we need to train the model outside this method,
        ///     and it's actually really important.
        ///     So the logic will be added soon.
        /// </summary>
        /// <param name="apId">The AP id</param>
        public void TrainModel(string apId)
        {
            try
            {
                MWNumericArray mParas = _paras[apId];
                var mTrainX = new MWNumericArray(_trainX[apId].Count, 1, _trainX[apId].ToArray());
                var mTrainY = new MWNumericArray(_trainY[apId].Count, 1, _trainY[apId].ToArray());
                var mStrength = new MWNumericArray(_trainStrength[apId].Count, 1, _trainStrength[apId].ToArray());

                MWArray[] outPut = _gt.Optimization(2, mParas, _ncg, _meanType, mTrainX, mTrainY, mStrength);
                _paras[apId] = (MWNumericArray) outPut[0];
                IsGaussianSupportOn = true;
            }
            catch (Exception)
            {
                GaussianSupportList[apId] = false;
            }
            GaussianSupportList[apId] = true;
        }
Example #54
0
 private MWNumericArray[][] wrap_func(int num, int ray_num, Transmitter.EMIT_OPTION emit_opt, Signal_Type signal_type, int sample_cnt)
 {
     MWNumericArray[][] signals = new MWNumericArray[num][];
     while (num-- > 0)
     {
         foreach (Transmitter trans in this.viz_rps.Map.Transmitters)
         {
             trans.Reset();
             trans.EmitRays(ray_num, emit_opt);   //各发射机辐射波束
             foreach (Receiver rec in this.viz_rps.Map.Receivers)
             {
                 rec.Reset();
                 if (this.viz_rps.Map.IsLOS(trans.Location, rec.Location))    //若存在LOS情况
                 {
                     LineSegment segLOS = new LineSegment(trans.Location, rec.Location);
                     Ray rayLOS = new Ray(trans, new LineSegment[] { segLOS }, segLOS.DirectionRadian, trans.CenterFrequency, trans.EmitPower * trans.Gain, trans.EmitPower * trans.Gain, true);
                     rec.AcceptRay(rayLOS, this.viz_rps.Map);
                 }
             }
             foreach (Ray ray in trans.Rays)  //更新每条ray, 若被接收,则更新接收它的接收机
             {
                 Receiver rec = null;
                 while (!ray.Update(this.viz_rps.Map, out rec)) ;
                 if (rec != null)
                     rec.AcceptRay(ray, this.viz_rps.Map);
             }
         }
         FingerprintGenerator fg = new FingerprintGenerator();
         Dictionary<Fingerprint_Name, Fingerprint> result = new Dictionary<Fingerprint_Name, Fingerprint>();
         List<double>[] ray_angles = new List<double>[this.viz_rps.Map.ReceiverCount];
         List<double>[] ray_strengths = new List<double>[this.viz_rps.Map.ReceiverCount];
         List<double>[] ray_taus = new List<double>[this.viz_rps.Map.ReceiverCount];
         int kk = 0;
         foreach (Receiver rec in this.viz_rps.Map.Receivers)
         {
             ray_angles[kk] = new List<double>();
             ray_strengths[kk] = new List<double>();
             ray_taus[kk] = new List<double>();
             foreach (Ray ray in rec.Rays)
             {
                 ray_angles[kk].Add(ray.CurrentDirection);
                 ray_strengths[kk].Add(ray.FadedPower(this.viz_rps.Map.MeterPixelRatio));
                 ray_taus[kk].Add(ray.GetLifeSpan(this.viz_rps.Map.MeterPixelRatio));
             }
             kk++;
         }
         double[] args = null;
         switch (signal_type)
         {
             case Signal_Type.PSEUDO_DOPPLER:
                 //if (this.receivers.First().Value.Antenna.AntType != AntennaType.PSEUDO_DOPPLER)
                 //    return null;
                 Antenna_PseudoDoppler ant = this.viz_rps.Map.receivers.First().Value.Antenna as Antenna_PseudoDoppler;
                 args = fg.PackArgs_PseudoDoppler(this.viz_rps.Map.receivers.First().Value.FrequencyLow, this.viz_rps.Map.receivers.First().Value.CenterFrequency,
                                                  this.viz_rps.Map.receivers.First().Value.SampleFrequency, ant.SwitchFrequency, ant.Radius, ant.AntennaNumber);
                 break;
         }
         signals[num - 1] = new MWNumericArray[ray_angles.GetLength(0)];
         for (int i = 0; i < signals.Length; i++)
         {
             signals[num - 1][i] = new FingerprintGenerator().GenerateSignal_MW(signal_type, ray_angles[i].ToArray(), ray_strengths[i].ToArray(), ray_taus[i].ToArray(), sample_cnt, args);
         }
     }
     return signals;
 }
Example #55
0
        private void AutoTest(object sender, DoWorkEventArgs e)
        {
            object[] param = (object[])e.Argument;
            int avg_cnt = (int)param[0];
            int KNN_K = (int)param[1];
            int KNNHC_K = (int)param[2];
            string db_file_name = (string)param[3];
            string data_file_name = (string)param[4];
            double start_snr = (double)param[5];
            double stop_snr = (double)param[6];
            double step_snr = (double)param[7];
            int ray_num = (int)param[8];
            Transmitter.EMIT_OPTION emit_opt = (Transmitter.EMIT_OPTION)param[9];
            Noise_Type noise_type = (Noise_Type)param[10];
            double alpha = (double)param[11];
            int sample_cnt = (int)param[12];
            Signal_Type signal_type = (Signal_Type)param[13];

            System.IO.FileStream data_fs = new FileStream(data_file_name, FileMode.Create, FileAccess.Write, FileShare.Read);

            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            FileStream fs = new FileStream(db_file_name, FileMode.Open, FileAccess.Read, FileShare.Read);
            FingerprintDataBase fdb = (FingerprintDataBase)formatter.Deserialize(fs);
            fs.Close();

            Point pt_real = new Point();
            foreach (Transmitter trans in this.viz_rps.Map.Transmitters)
                pt_real = trans.Location;

            double[] snrs = new double[(int)((stop_snr - start_snr) / step_snr) + 1];
            for(int i = 0; i < snrs.Length; i++)
                snrs[i] = start_snr + i * step_snr;

            foreach (Transmitter trans in this.viz_rps.Map.Transmitters)
            {
                trans.Reset();
                trans.EmitRays(ray_num, emit_opt);   //各发射机辐射波束
                foreach (Receiver rec in this.viz_rps.Map.Receivers)
                {
                    rec.Reset();
                    if (this.viz_rps.Map.IsLOS(trans.Location, rec.Location))    //若存在LOS情况
                    {
                        LineSegment segLOS = new LineSegment(trans.Location, rec.Location);
                        Ray rayLOS = new Ray(trans, new LineSegment[] { segLOS }, segLOS.DirectionRadian, trans.CenterFrequency, trans.EmitPower * trans.Gain, trans.EmitPower * trans.Gain, true);
                        rec.AcceptRay(rayLOS, this.viz_rps.Map);
                    }
                }
                foreach (Ray ray in trans.Rays)  //更新每条ray, 若被接收,则更新接收它的接收机
                {
                    Receiver rec = null;
                    while (!ray.Update(this.viz_rps.Map, out rec)) ;
                    if (rec != null)
                        rec.AcceptRay(ray, this.viz_rps.Map);
                }
            }
            FingerprintGenerator fg = new FingerprintGenerator();
            Dictionary<Fingerprint_Name, Fingerprint> result = new Dictionary<Fingerprint_Name, Fingerprint>();
            List<double>[] ray_angles = new List<double>[this.viz_rps.Map.ReceiverCount];
            List<double>[] ray_strengths = new List<double>[this.viz_rps.Map.ReceiverCount];
            List<double>[] ray_taus = new List<double>[this.viz_rps.Map.ReceiverCount];
            int kk = 0;
            foreach (Receiver rec in this.viz_rps.Map.Receivers)
            {
                ray_angles[kk] = new List<double>();
                ray_strengths[kk] = new List<double>();
                ray_taus[kk] = new List<double>();
                foreach (Ray ray in rec.Rays)
                {
                    ray_angles[kk].Add(ray.CurrentDirection);
                    ray_strengths[kk].Add(ray.FadedPower(this.viz_rps.Map.MeterPixelRatio));
                    ray_taus[kk].Add(ray.GetLifeSpan(this.viz_rps.Map.MeterPixelRatio));
                }
                kk++;
            }
            double[] args = null;
            switch (signal_type)
            {
                case Signal_Type.PSEUDO_DOPPLER:
                    //if (this.receivers.First().Value.Antenna.AntType != AntennaType.PSEUDO_DOPPLER)
                    //    return null;
                    Antenna_PseudoDoppler ant = this.viz_rps.Map.receivers.First().Value.Antenna as Antenna_PseudoDoppler;
                    args = fg.PackArgs_PseudoDoppler(this.viz_rps.Map.receivers.First().Value.FrequencyLow, this.viz_rps.Map.receivers.First().Value.CenterFrequency,
                                                     this.viz_rps.Map.receivers.First().Value.SampleFrequency, ant.SwitchFrequency, ant.Radius, ant.AntennaNumber);
                    break;
            }
            MWNumericArray[] signals = new MWNumericArray[ray_angles.GetLength(0)];
            for (int i = 0; i < signals.Length; i++)
            {
                signals[i] = new FingerprintGenerator().GenerateSignal_MW(signal_type, ray_angles[i].ToArray(), ray_strengths[i].ToArray(), ray_taus[i].ToArray(), sample_cnt, args);                
            }

            for (int n = 0; n < snrs.Length; n++)
            {
                double[] sum_errs = new double[6];//SA_single, SA_KNN, SA_KNNHC, S_single, S_KNN, S_KNNHC
                for(int i = 0; i < avg_cnt; i++)
                {
                    MWNumericArray[] n_signals = new MWNumericArray[signals.Length];
                    for (int l = 0; l < signals.Length; l++)
                    {
                        n_signals[l] = new FingerprintGenerator().AddNoise_MW(noise_type, signals[l], new double[] { snrs[n] });
                    }
                    Dictionary<Fingerprint_Name, Fingerprint> res = new Dictionary<Fingerprint_Name,Fingerprint>();
                    for (int j = 0; j < Enum.GetNames(new Fingerprint_Name().GetType()).Length; j++ )
                        res[(Fingerprint_Name)j] = new FingerprintGenerator().GenerateFingerprint(signal_type, (Fingerprint_Name)j, n_signals, args);
                    this.current_fingerprint = res;

                    //SA_single
                    PointF loc_SA_single = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.SA], FingerprintDataBase.Match_Strategy.Single, null);
                    sum_errs[0] += new MathUtils.MathUtility().point_dist(pt_real, loc_SA_single);

                    //SA_KNN
                    PointF loc_SA_KNN = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.SA], FingerprintDataBase.Match_Strategy.KNN, new double[] { KNN_K });
                    sum_errs[1] += new MathUtils.MathUtility().point_dist(pt_real, loc_SA_KNN);

                    //SA_KNNHC
                    PointF loc_SA_KNNHC = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.SA], FingerprintDataBase.Match_Strategy.KNN_HC, new double[] { KNNHC_K });
                    sum_errs[2] += new MathUtils.MathUtility().point_dist(pt_real, loc_SA_KNNHC);

                    //S_single
                    PointF loc_S_single = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.S], FingerprintDataBase.Match_Strategy.Single, null);
                    sum_errs[3] += new MathUtils.MathUtility().point_dist(pt_real, loc_S_single);

                    //S_KNN
                    PointF loc_S_KNN = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.S], FingerprintDataBase.Match_Strategy.KNN, new double[] { KNN_K });
                    sum_errs[4] += new MathUtils.MathUtility().point_dist(pt_real, loc_S_KNN);

                    //S_KNNHC
                    PointF loc_S_KNNHC = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.S], FingerprintDataBase.Match_Strategy.KNN_HC, new double[] { KNNHC_K });
                    sum_errs[5] += new MathUtils.MathUtility().point_dist(pt_real, loc_S_KNNHC);

                    bgAutoTest.ReportProgress((int)((n * avg_cnt + i + 1) / (double)(avg_cnt * snrs.Length) * 100));
                    System.Threading.Thread.Sleep(200);
                }

                for (int m = 0; m < sum_errs.Length; m++ )
                {
                    double err = sum_errs[m] / avg_cnt;
                    byte[] tmp = Encoding.ASCII.GetBytes(err.ToString("0.00") + "\t");
                    data_fs.Write(tmp, 0, tmp.Length);
                }
                byte[] rn = Encoding.ASCII.GetBytes("\r\n");
                data_fs.Write(rn, 0, rn.Length);
            }

            data_fs.Close();
            e.Result = true;
        }
Example #56
0
 public double[,] NetArrayFromMLArray(MWNumericArray matriz)
 {
     double[,] rdo = (double[,])matriz.ToArray(MWArrayComponent.Real);
     return rdo;
 }
        public static List<PdchModel> PdchSimulink(List<PdchModel> input)
        {
            List<PdchModel> pm = new List<PdchModel>();
            pm = input.OrderBy(e => e.PsPagingTime).ToList();
            PdchNewclass pnc = new PdchNewclass();
            int size = input.Count();
            double[,] X = new double[size, 5];
            double[,] Y = new double[size, 1];

            for (int i = 0; i < size; i++)
            {
                X[i, 0] = pm[i].BCr;
                X[i, 1] = pm[i].GDr;
                X[i, 2] = pm[i].IMr;
                X[i, 3] = pm[i].MMSr;
                X[i, 4] = pm[i].OCr;
                Y[i, 0] = pm[i].PdchUse;
            }
            MWNumericArray mtraffic = new MWNumericArray(X);
            MWNumericArray mpdchuse = new MWNumericArray(Y);

            MWArray mpdchnew = pnc.pdchsim(mtraffic, mpdchuse);
            MWNumericArray mx_y1 = (MWNumericArray)mpdchnew;
            double[,] csArray = (double[,])mx_y1.ToArray(MWArrayComponent.Real);
            for (int i = 0; i < csArray.Length; i++)
                pm[i].PdchSim = csArray[i, 0];
            return pm;
        }
        static private void UseDotNET(Array ar, Array ai, Array br,
            Array bi, ref Array cr, ref Array ci, ref Array dr, ref Array di)
        {
            /*
             * This function calls the math_by_numbers method from
             * inside a .NET assembly created with MATLAB using Builder
             * for .NET.
             */

            // Instantiate our .NET class from the MATLAB created component
            dotnetclass AClass = new dotnetclass();

            // explicity convert our input arguments into MWArrays
            // this can be done with implicit conversion
            MWNumericArray a = new MWNumericArray(1, 2, (double[])ar, (double[])ai);
            MWNumericArray b = new MWNumericArray(1, 2, (double[])br, (double[])bi);

            // call math_on_method from Assembly specifying the number
            // of return arguments expected and passing in a and b
            MWArray[] RetVal = AClass.math_on_numbers(2, a, b);

            // Unpack return values seperating the real and imaginary parts
            // using the ToArray method of MWNummericArray.  Since RetVal was
            // declared as a MWArray above, it must be explicity typecast here.  
            cr = ((MWNumericArray) RetVal[0]).ToVector(MWArrayComponent.Real);
            ci = ((MWNumericArray) RetVal[0]).ToVector(MWArrayComponent.Imaginary);
        
            dr = ((MWNumericArray) RetVal[1]).ToVector(MWArrayComponent.Real);
            di = ((MWNumericArray) RetVal[1]).ToVector(MWArrayComponent.Imaginary);

        }
Example #59
0
        //计算关键层接口
        private bool getKeyLayer(ref int[] bianHao, ref double[] pjxs)
        {
            double[,] data = getParams();
            if (data == null)
            {
                MessageBox.Show("数据录入有误,请检查。(第一层应为地表,煤层应有底板。)");
                return false;
            }

            double[] rowData = arrayTrans(data);
            MWNumericArray mwdata = new MWNumericArray(rowData.Length / 11, 11, rowData);

            try
            {
                MWArray[] result = logic.yancengzuhe(2, mwdata, FuYanXCL, CaiGao, SuiZhangXS, Mcqj);
                MWNumericArray biaoHaoList = (MWNumericArray)result[0];
                MWNumericArray pjxsList = (MWNumericArray)result[1];

                double[] outBiaoHao = (double[])biaoHaoList.ToVector(MWArrayComponent.Real);
                int length = outBiaoHao.Length;
                bianHao = new int[length];
                for (int i = 0; i < length; i++)
                {
                    bianHao[i] = (int)outBiaoHao[i];
                }

                pjxs = (double[])pjxsList.ToVector(MWArrayComponent.Real);

                return true;

            }
            catch (Exception e)
            {
                e.ToString();
                MessageBox.Show("关键层计算出现错误,请检查数据合理性");
                return false;

            }
        }
Example #60
-1
 public Image RunFilter(Image src)
 {
     filterDataContext db = new filterDataContext();
     double[] sigma = new double[] { 3.0, 3.0 };
     MWNumericArray mw_sigma = new MWNumericArray(sigma);
     MWLogicalArray mw_print = new MWLogicalArray(Form1.print);
     MWArray[] Result = filter2(2, src.image, type[2], mw_print);//spfilt(2, src.image, "median");
     MWNumericArray descriptor = null;
     descriptor = (MWNumericArray)Result[0];
     double[,] result = null;
     result = (double[,])descriptor.ToArray(MWArrayComponent.Real);
     Image res = new Image(result);
     MWNumericArray e_descriptor = null;
     e_descriptor = (MWNumericArray)Result[1];
     WorkTime = (double)e_descriptor.ToScalarDouble();
     //db.add_b_res(src.Height, src.Height / src.Width, WorkTime, w, sigma[0], sigma[1]);
     Result = null;
     e_descriptor = null;
     result = null;
     mw_sigma = null;
     GC.Collect();
     return res;
 }