예제 #1
0
        public void mySimulateFunction()
        {
            matlab.Execute(testInputX);
            matlab.Execute(testInputY);
            matlab.Execute(testInputP);

            loadMatlabFile("MySimulations.m");
            double xRes     = (double)matlab.GetVariable("xRes", "base");
            double yRes     = (double)matlab.GetVariable("yRes", "base");
            double pRes     = (double)matlab.GetVariable("pRes", "base");
            double myResult = (double)matlab.GetVariable("myResult", "base");
            int    res      = 0;

            int r = (int)myResult;

            if (Math.Abs(r - myResult) < Math.Abs(r + 1 - myResult))
            {
                res = r;
            }
            else
            {
                res = r + 1;
            }

            double errorPerc = (double)100 * errorCount / (double)runsCount;

            XResultLabel.Content      = (string)FindResource("XResults") + xRes;
            YResultLabel.Content      = (string)FindResource("YResults") + yRes;
            PResultLabel.Content      = (string)FindResource("PResults") + pRes;
            CResultLabel.Content      = (string)FindResource("CResults") + myResult;
            ErrorPercentLabel.Content = (string)FindResource("ErrorPercent") + errorPerc + " %";
            MyResultLabel.Content     = (string)FindResource("Result") + res;

            nowResult = res;
        }
예제 #2
0
        // 辅助函数:从当前的 matlab 引擎中根据所传入的字符串获取其 double 的值
        public static double getDoubleFromMatlab(string varName)
        {
            var    tempOut       = matlab.GetVariable(varName, "base");
            double tempOutDouble = Convert.ToDouble(tempOut);

            return(tempOutDouble);
        }
        public Pair <int> CreateComplexHybridModel(float[] Et, float[] Zt)
        {
            try
            {
                int bestA = 0;
                int bestB = 0;

                load("MyGA_1.m");
                int          n            = (int)matlab.GetVariable("n", "base");
                bool         endCondition = true;
                StreamWriter gaLogger     = new StreamWriter("Complex_Hybrid_Logger.txt");
                StreamWriter sw           = new StreamWriter("Complex_Result_Model_Output.txt");
                do
                {
                    Dispatcher.Invoke(new Action(() => IterationLabel.Content = getMyVariable("m")));

                    string command = "\n y=[";
                    for (int i = 1; i <= n; i++)
                    {
                        float aa = 0, bb = 0;
                        aa = float.Parse(getMyVariable("p(" + i + ",1)"));
                        bb = float.Parse(getMyVariable("p(" + i + ",2)"));
                        int    a     = (int)Math.Round(aa);
                        int    b     = (int)Math.Round(bb);
                        double error = SVMComplexModel(a, b, Et, Zt);
                        gaLogger.WriteLine("{0} {1} ->  {2}", a, b, error);
                        gaLogger.Flush();
                        command += error + ",";
                    }
                    gaLogger.WriteLine("\n\n\n");
                    command = command.Remove(command.Length - 1) + "]; \n";
                    string matlabCode = justLoadAndGetContent("MyGA2.m") + command + justLoadAndGetContent("MyGA_3.m");
                    string result     = matlab.Execute(matlabCode);

                    bestA = (int)Math.Round(float.Parse(getMyVariable("NowA")));
                    bestB = (int)Math.Round(float.Parse(getMyVariable("NowB")));

                    sw.WriteLine(result);
                    Dispatcher.Invoke(new Action(() => IterationLabel.Content = getMyVariable("m")));
                    matlab.Execute(
                        "EndCondition = m<" + maxGAIteretionInHybrid + " && abs(maxvalue(m)-maxvalue(m-(m0-1)))>0.001*maxvalue(m) && (abs(maxvalue(m))>1e-10 && abs(maxvalue(m-(m0-1)))>1e-10) && m<" + maxGAIteretionInHybrid + " && abs(maxvalue(m)-meanvalue(m))>1e-5 || m<20");
                    endCondition = (bool)matlab.GetVariable("EndCondition", "base");
                } while (endCondition);
                gaLogger.Flush();
                gaLogger.Close();
                sw.Flush();
                sw.Close();
                Dispatcher.Invoke(new Action(() => ActivityProgressBar.IsIndeterminate = false));
                MessageBox.Show("Finaly Our Complex Hybrid Model Created Successfully .", "Done", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                return(new Pair <int>(bestA, bestB));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "ERROR1", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return(null);
        }
예제 #4
0
        public void StartArima(double[] data)
        {
            train = new double[data.Length - NUMBER_OF_TEST_CASES];
            test  = new double[NUMBER_OF_TEST_CASES];
            for (int i = 0; i < train.Length; i++)
            {
                train[i] = data[i];
            }
            for (int i = train.Length, j = 0; i < data.Length; i++, j++)
            {
                test[j] = data[i];
            }

            logger = new StreamWriter("ArimaGALog.txt");

            load("MyGA1.m");
            int          n            = (int)matlab.GetVariable("n", "base");
            bool         endCondition = true;
            StreamWriter sw           = new StreamWriter("ArimaGA_Output.txt");

            do
            {
                string command = "\n y=[";
                for (int i = 1; i <= n; i++)
                {
                    double pp    = double.Parse(getMyVariable("p(" + i + ",1)"));
                    double dd    = double.Parse(getMyVariable("p(" + i + ",2)"));
                    double qq    = double.Parse(getMyVariable("p(" + i + ",3)"));
                    int    p     = (int)Math.Round(pp);
                    int    d     = (int)Math.Round(dd);
                    int    q     = (int)Math.Round(qq);
                    double error = arimaModelFunction(p, d, q, CompareComboBox.SelectedIndex);
                    logger.WriteLine("{0} {1} {2} ->  {3}", p, d, q, error);
                    command += error + ",";
                }
                logger.WriteLine("\n\n\n");
                command = command.Remove(command.Length - 1) + "]; \n";
                string matlabCode = justLoadAndGetContent("MyGA2.m") + command + justLoadAndGetContent("MyGA3.m");
                string result     = matlab.Execute(matlabCode);
                sw.WriteLine(result);
                matlab.Execute(
                    "EndCondition = m<1000 && abs(maxvalue(m)-maxvalue(m-(m0-1)))>0.001*maxvalue(m) && (abs(maxvalue(m))>1e-10 && abs(maxvalue(m-(m0-1)))>1e-10) && m<10000 && abs(maxvalue(m)-meanvalue(m))>1e-5 || m<20");
                endCondition = (bool)matlab.GetVariable("EndCondition", "base");
            } while (endCondition);

            bestP = (int)Math.Round(float.Parse(getMyVariable("NowP")));
            bestD = (int)Math.Round(float.Parse(getMyVariable("NowD")));
            bestQ = (int)Math.Round(float.Parse(getMyVariable("NowQ")));
            double mse          = -1 * arimaModelFunction(bestP, bestD, bestQ, 0);
            double errorPercent = -1 * arimaModelFunction(bestP, bestD, bestQ, 1);

            sw.WriteLine("\n\n\n Best P & D & Q are => with this MSE & Error%\n\n {0} {1} {2} => {3} {4}", bestP,
                         bestD, bestQ, mse, errorPercent);
            sw.Flush();
            sw.Close();
            MessageBox.Show("Done", "GA with Arima", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        public void StartArima(double[] data)
        {
            try
            {
                trainArima = new double[data.Length - NUMBER_OF_HYBRID_TEST];
                testArima  = new double[NUMBER_OF_HYBRID_TEST];
                for (int i = 0; i < trainArima.Length; i++)
                {
                    trainArima[i] = data[i];
                }
                for (int i = trainArima.Length, j = 0; i < data.Length; i++, j++)
                {
                    testArima[j] = data[i];
                }

                load("MyGA1.m");
                int          n            = (int)matlab.GetVariable("n", "base");
                bool         endCondition = true;
                StreamWriter sw           = new StreamWriter("Hybrid_ArimaSVM_Output.txt");
                do
                {
                    string command = "\n y=[";
                    for (int i = 1; i <= n; i++)
                    {
                        double pp    = double.Parse(getMyVariable("p(" + i + ",1)"));
                        double dd    = double.Parse(getMyVariable("p(" + i + ",2)"));
                        double qq    = double.Parse(getMyVariable("p(" + i + ",3)"));
                        int    p     = (int)Math.Round(pp);
                        int    d     = (int)Math.Round(dd);
                        int    q     = (int)Math.Round(qq);
                        double error = arimaModelFunction(p, d, q);
                        command += error + ",";
                    }
                    command = command.Remove(command.Length - 1) + "]; \n";
                    string matlabCode = justLoadAndGetContent("MyGA2.m") + command + justLoadAndGetContent("MyGA3.m");
                    string result     = matlab.Execute(matlabCode);
                    sw.WriteLine(result);
                    matlab.Execute(
                        "EndCondition = m<1000 && abs(maxvalue(m)-maxvalue(m-(m0-1)))>0.001*maxvalue(m) && (abs(maxvalue(m))>1e-10 && abs(maxvalue(m-(m0-1)))>1e-10) && m<10000 && abs(maxvalue(m)-meanvalue(m))>1e-5 || m<20");
                    endCondition = (bool)matlab.GetVariable("EndCondition", "base");
                } while (endCondition);
                sw.Flush();
                sw.Close();
                MessageBox.Show("Model Created Successfully", "Best SVM with Grid & Best Arima With GA", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "ERROR1", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
예제 #6
0
        public MainModelView(Canvas canvas, Window master)
        {
            if (Properties.Settings.Default.ModelPath.Length == 0)
            {
                Properties.Settings.Default.ModelPath = Directory.GetCurrentDirectory();
            }
            if (Properties.Settings.Default.AppPath.Length == 0)
            {
                Properties.Settings.Default.AppPath = Directory.GetCurrentDirectory();
            }

            this._master             = master;
            this.TrashCommand        = new Command(this.TrashAction, this.TrashActionCan);
            this.BackCommand         = new Command(this.BackAction, this.BackActionCan);
            this.ProcessCommand      = new Command(this.ProcessAction, this.ProcessActionCan);
            this.TrueCommand         = new Command(this.TrueAction, this.TrueActionCan);
            this.FalseCommand        = new Command(this.FalseAction, this.FalseActionCan);
            this.OpenMatriceCommand  = new Command(this.OpenMatriceAction);
            this.ResetDataCommand    = new Command(this.ResetDataAction);
            this.OpenSettingsCommand = new Command(this.OpenSettingsAction);

            this.matrix            = new Stack <Point>();
            this.canvas            = canvas;
            this.FunctionPredictor = Properties.Settings.Default.NameModel;
            this.Data       = Data.Open(this.FunctionPredictor);
            this.state      = false;
            this.StateValid = true;

            this.worker = new BackgroundWorker()
            {
                WorkerSupportsCancellation = true
            };
            this.worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            this.worker.DoWork             += (sender, e) =>
            {
                try
                {
                    bool[,] image = new bool[28, 28];
                    foreach (Point point in this.matrix)
                    {
                        image[(int)point.Y * 2, (int)point.X * 2]         = true;
                        image[(int)point.Y * 2 + 1, (int)point.X * 2]     = true;
                        image[(int)point.Y * 2, (int)point.X * 2 + 1]     = true;
                        image[(int)point.Y * 2 + 1, (int)point.X * 2 + 1] = true;
                    }

                    MLApp.MLApp matlab = new MLApp.MLApp();
                    matlab.Execute("cd " + Properties.Settings.Default.ModelPath);
                    matlab.PutWorkspaceData("X", "base", image);
                    matlab.Execute(@"label = " + this.FunctionPredictor + "(X)");
                    var label = matlab.GetVariable("label", "base");
                    e.Result = label;
                }
                catch (Exception err)
                {
                    e.Result = err.Message;
                }
            };
            this.InProcess = "Hidden";
        }
예제 #7
0
        ///// <summary>
        ///// Simulates the transfer function in matlab and outputs the results a a Double array
        ///// </summary>
        ///// <param name="Uvector">The Input vector, these input should have the same size as the Time Vector at regualar intervals</param>
        ///// <param name="Tvector">The Output vector, this vector should have a regualor non repeating sequence of real numbers t0:dt:t1</param>
        //public double[] Simulate(Double[] Uvector, Double[] Tvector)
        //{

        //    // Put the variables in de matlab workspace
        //    MWinstance.PutWorkspaceData("Uvector", "base", Uvector);
        //    MWinstance.PutWorkspaceData("Tvector", "base", Tvector);

        //    // Execute the Transfer Function
        //    Result = MWinstance.Execute(STR_SresLsimsysUvectorTvector);

        //    // Get the Yvector from the Matalb instance
        //    Double[,] Yarray = MWinstance.GetVariable("Yarray", "base");

        //
        //    // Gets a 1-dimensional Yvector from the 2-dimenisional Yarray
        //    Double[] Yvector = new Double[Yarray.Length];
        //    int i = 0;

        //    foreach (var row in Yarray)
        //    {
        //        Yvector[i++] = row;
        //    }

        //    return Yvector;
        //}

        /// <param name="Uvector">Overload constructor that takes the transfer function as input and initiate The start variables in Matlab</param>
        /// <param name="Tvector">The Output vector, this vector should have a regualor non repeating sequence of real numbers t0:dt:t1 Beacause of Labview shitty timing this will be normalised by the dt variable</param>
        /// <param name="dt">Used to normalise the Tvector</param>
        public double[] Simulate(Double[] Uvector, Double[] Tvector, Double dt)
        {
            //Makes the Tvector vector workable in Matlab
            Double[] tvec = new Double[Tvector.Length];

            for (int i = 0; i < Tvector.Length; i++)
            {
                tvec[i] = Math.Round(Math.Round(Tvector[0], 0) + i * dt, 3);
            }

            // Sort the U vector using the T vector as key
            Double[,] UT_Matrix = new Double[Tvector.Length, 2];

            // Put the variables in de matlab workspace
            MWinstance.PutWorkspaceData("Uvector", "base", Uvector);
            MWinstance.PutWorkspaceData("Tvector", "base", tvec);

            // Execute the Transfer Function
            Result = MWinstance.Execute(STR_SresLsimsysUvectorTvector);

            // Get the Yvector from the Matalb instance
            Double[,] Yarray = MWinstance.GetVariable("Yarray", "base");


            // Gets a 1-dimensional Yvector from the 2-dimenisional Yarray
            Double[] Yvector = new Double[Yarray.Length];

            for (int i = 0; i < Yarray.Length; i++)
            {
                Yvector[i] = Yarray[i, 0];
            }

            return(Yvector);
        }
예제 #8
0
 /// <summary>
 /// Checks the Matlab workspace for the variable name, so no data is Overwritten.
 /// </summary>
 /// <param name="name"> The variable name being checked for.</param>
 /// <returns></returns>
 public static bool isVariableInWorkspace(string name)
 {
     try
     {
         return(!(matlab.GetVariable(name, "base") == null));
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
예제 #9
0
 public MATLABWrapper(string _mcodepath, string _groupID)
 {
     groupID = _groupID;
     mcodepath = new DirectoryInfo(_mcodepath);
     if (!mcodepath.Exists)
     {
         throw new Exception("The mcode folder can not be found.");
     }
     var activationContext = Type.GetTypeFromProgID("matlab.application.single");
     matlab = (MLApp.MLApp)Activator.CreateInstance(activationContext);
     matlab.Visible = 0;
     String output;
     output= matlab.Execute("cd " + mcodepath.FullName);
     output=matlab.Execute("pwd");
     var currentDirCheck = matlab.GetVariable("ans", "base");
     DirectoryInfo currentDirCheckDi = new DirectoryInfo(currentDirCheck);
     if (currentDirCheckDi.FullName != mcodepath.FullName)
     {
         throw new Exception("Changing MATLAB working directory to mcode directory failed. Working directory stuck at " + currentDirCheck);
     }
 }
        /// <summary>
        /// Simulate a transfer function in the S-domain
        /// </summary>
        /// <param name="num">Numerator of the transfer function. Array of doubles. Polynomial ordered from nth... 2nd... 1th... Constant</param>
        /// <param name="den">Denominator of the transfer function. Array of doubles. Polynomial ordered from nth... 2nd... 1th... Constant</param>
        /// <param name="PreviousValue">Value from the previous itteration. Use the shift register to obtain this value</param>
        /// <param name="CurrentValue">Value from the current itteration</param>
        public double Simulate(Double[] num, Double[] den, Double PreviousValue, Double CurrentValue)
        {
            // Put the variables in de matlab workspace
            MWinstance.PutWorkspaceData("PreviousValue", "base", PreviousValue);
            MWinstance.PutWorkspaceData("CurrentValue", "base", CurrentValue);
            MWinstance.PutWorkspaceData("num", "base", num);
            MWinstance.PutWorkspaceData("den", "base", den);

            /*
             * Matlab script for SimulateTF
             * Writen by Jelle Spijker
             *
             * function  CurrentOutput = SimulateTF( num, den, PreviousValue, CurrentValue )
             * %UNTITLED Summary of this function goes here
             * %   Detailed explanation goes here
             * TransferFunction = tf(num, den);
             * TimeVector = 0:1;
             * if PreviousValue ~= CurrentValue
             *     InputVector = ones(1,2) * PreviousValue;
             *     InputVector(2) = CurrentValue;
             * else
             *     InputVector = ones(1,2) * PreviousValue;
             * end
             * OutputVector = lsim(TransferFunction, InputVector, TimeVector);
             * CurrentOutput = OutputVector(end);
             * end
             *
             */

            result = MWinstance.Execute("Sres = SimulateTF(num, den, PreviousValue, CurrentValue)");

            // Get the result from the Matalb instance
            var test = MWinstance.GetVariable("Sres", "base");

            //Casts the result in a double
            resultD = (Double)test;

            return(resultD);
        }
예제 #11
0
        /// <summary>
        /// This method calls the matlab code, hands over the data to matlab and stores the results. Afterwards the
        /// clusters and the centerlines/medians are plotted and the rectangles for the stackpanel showing, how many of
        /// the clustered streamlines are contained in the respective cluster.
        /// </summary>
        /// <param name="clusterObject">The object for the clustering (vectorfield, travel)</param>
        private void cluster(IClusterObject clusterObject)
        {
            clearClusterCanvas();

            lineCanvas.Children.Clear();
            barPanel.Children.Clear();

            executeMatlab(clusterObject);

            double[,] centerLines      = matlab.GetVariable("reconCenterLines", "base");
            double[,] percentCluster2D = matlab.GetVariable("percentCluster", "base");
            double[] percentCluster = Util.Make1Dimensional(percentCluster2D);

            drawClusters(percentCluster, clusterObject);

            drawCenterLines(centerLines, percentCluster, clusterObject);

            addRects(Util.getRects(numClusters, percentCluster, barPanel.ActualWidth, barPanel.ActualHeight));
        }
예제 #12
0
        /// <summary>
        /// Handles the body frame data arriving from the sensor
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            bool dataReceived = false;

            using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
            {
                if (bodyFrame != null)
                {
                    if (this.bodies == null)
                    {
                        this.bodies = new Body[bodyFrame.BodyCount];
                    }

                    // The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
                    // As long as those body objects are not disposed and not set to null in the array,
                    // those body objects will be re-used.
                    bodyFrame.GetAndRefreshBodyData(this.bodies);
                    dataReceived = true;
                }
            }

            if (dataReceived)
            {
                using (DrawingContext dc = this.drawingGroup.Open())
                {
                    // Draw a transparent background to set the render size
                    dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));

                    //  public TimeSpan RelativeTime;
                    //Debug.WriteLine(head.Position.X);


                    Body body = null;
                    if (this.bodyTracked) //HERE WE TRACK THE CLOSEST BODY TO THE CAMERA
                    {
                        if (this.bodies[this.bodyIndex].IsTracked)
                        {
                            body = this.bodies[this.bodyIndex];
                        }
                        else
                        {
                            bodyTracked = false;
                        }
                    }
                    if (!bodyTracked)
                    {
                        for (int i = 0; i < this.bodies.Length; ++i)
                        {
                            if (this.bodies[i].IsTracked)
                            {
                                this.bodyIndex   = i;
                                this.bodyTracked = true;
                                break;
                            }
                        }
                    }

                    if (body != null && this.bodyTracked && body.IsTracked)
                    {
                        // body represents your single tracked skeleton



                        int penIndex = 0;


                        Pen drawPen = this.bodyColors[penIndex++];

                        //GRAB THE JOINTS YOU WANT TO SAVE
                        Joint leftHand      = body.Joints[JointType.HandLeft];
                        Joint rightHand     = body.Joints[JointType.HandRight];
                        Joint head          = body.Joints[JointType.Head];
                        Joint leftshoulder  = body.Joints[JointType.ShoulderLeft];
                        Joint rightshoulder = body.Joints[JointType.ShoulderRight];
                        Joint neck          = body.Joints[JointType.Neck];

                        //  Debug.WriteLine(Globals.counter);



                        //MATLAB FUNCTION --16/01
                        MLApp.MLApp matlab = new MLApp.MLApp();
                        matlab.Visible = 0;


                        if (Globals.rec == false)
                        {
                            Globals.counter = 0;
                        }

                        //HERE OUR COUNTER VALUE AND THE RECORD BUTTON TRIGGERS THE WRITTING OF DATA
                        if (Globals.counter % 1 == 0 && Globals.rec == true)
                        {
                            //used to gather more data-----NOT USED ANY MORE

                            /* using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Spyros\Desktop\Right.txt", true))
                             * {
                             *    //file.Write(Globals.counter);
                             *    //file.Write(";");
                             *
                             *    //HEAD-NECK vector
                             *
                             *    file.Write(head.Position.X - neck.Position.X);
                             *    file.Write(",");
                             *    file.Write(head.Position.Y - neck.Position.Y);
                             *    file.Write(",");
                             *    file.Write(head.Position.Z - neck.Position.Z);
                             *    file.Write(",");
                             *
                             *    //Left shoulder-left hand vector
                             *    file.Write(leftshoulder.Position.X - leftHand.Position.X);
                             *    file.Write(",");
                             *    file.Write(leftshoulder.Position.Y - leftHand.Position.Y);
                             *    file.Write(",");
                             *    file.Write(leftshoulder.Position.Z - leftHand.Position.Z);
                             *    file.Write(",");
                             *
                             *    //right shoulder-right hand vector
                             *    file.Write(rightshoulder.Position.X - rightHand.Position.X);
                             *    file.Write(",");
                             *    file.Write(rightshoulder.Position.Y - rightHand.Position.Y);
                             *    file.Write(",");
                             *    file.Write(rightshoulder.Position.Z - rightHand.Position.Z);
                             *    file.WriteLine("");
                             *
                             *
                             *
                             * }*/



                            //RECENTLY ADDED CODE 16/01



                            //predict movement here

                            //USED FOR ARMS
                            if (Globals.hands == true)
                            {    //predict result through matlab
                                string output = matlab.Execute("y=predmovement_2([" + (leftshoulder.Position.Y - leftHand.Position.Y) + "," + (rightshoulder.Position.X - rightHand.Position.X) + "," + (rightshoulder.Position.Y - rightHand.Position.Y) + "])");
                            }
                            //USED FOR HEAD
                            if (Globals.head == true)
                            {    //predict result through matlab
                                string output = matlab.Execute("y=predmovement([" + (head.Position.X - neck.Position.X) + "," + (head.Position.Y - neck.Position.Y) + "," + (head.Position.Z - neck.Position.Z) + "])");
                            }

                            double a = matlab.GetVariable("y", "base");         //we get the variable that we want
                            if (a == 0)
                            {
                                //file2.WriteLine("LEFT OBJECT;");
                                string wht3 = matlab.Execute("msg.Data = '0';");
                            }
                            else if (a == 1)
                            {
                                string wh4 = matlab.Execute("msg.Data = '-1';");
                            }
                            else if (a == -1)
                            {
                                //file2.WriteLine("RIGHT OBJECT;");
                                string wh111 = matlab.Execute("msg.Data = '1';");
                            }
                            //Debug.WriteLine(a);



                            //Debug.WriteLine("New data added");
                            //SENT DATA ACROSS NETWORK
                            string wht5 = matlab.Execute("send(chatpub,msg);");
                        }

                        if (body.IsTracked)
                        {
                            this.DrawClippedEdges(body, dc);

                            IReadOnlyDictionary <JointType, Joint> joints = body.Joints;

                            // convert the joint points to depth (display) space
                            Dictionary <JointType, Point> jointPoints = new Dictionary <JointType, Point>();

                            foreach (JointType jointType in joints.Keys)
                            {
                                // sometimes the depth(Z) of an inferred joint may show as negative
                                // clamp down to 0.1f to prevent coordinatemapper from returning (-Infinity, -Infinity)

                                CameraSpacePoint position = joints[jointType].Position;
                                if (position.Z < 0)
                                {
                                    position.Z = InferredZPositionClamp;
                                }

                                DepthSpacePoint depthSpacePoint = this.coordinateMapper.MapCameraPointToDepthSpace(position);
                                jointPoints[jointType] = new Point(depthSpacePoint.X, depthSpacePoint.Y);
                            }

                            this.DrawBody(joints, jointPoints, dc, drawPen);

                            this.DrawHand(body.HandLeftState, jointPoints[JointType.HandLeft], dc);
                            this.DrawHand(body.HandRightState, jointPoints[JointType.HandRight], dc);
                        }
                        // prevent drawing outside of our render area
                        this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
                    }
                    Globals.counter++;
                }
            }
        }
        public override IOperation Apply()
        {
            lock (locker) {
                var initializationScript = MatlabInitializationScriptParameter.ActualValue;
                if (!string.IsNullOrEmpty(initializationScript.Value) && !initializationScript.Exists())
                {
                    throw new FileNotFoundException(string.Format("The initialization script \"{0}\" cannot be found.", initializationScript.Value));
                }

                var evaluationScript = MatlabEvaluationScriptParameter.ActualValue;
                if (string.IsNullOrEmpty(evaluationScript.Value))
                {
                    throw new FileNotFoundException("The evaluation script in the problem is not set.");
                }
                if (!evaluationScript.Exists())
                {
                    throw new FileNotFoundException(string.Format("The evaluation script \"{0}\" cannot be found.", evaluationScript.Value));
                }

                string result;
                if (matLabConnector == null)
                {
                    Type matlabtype = Type.GetTypeFromProgID("matlab.application.single");
                    matLabConnector         = (MLApp.MLApp)Activator.CreateInstance(matlabtype);
                    matLabConnector.Visible = 0;

                    if (!string.IsNullOrEmpty(initializationScript.Value))
                    {
                        var directoryName = Path.GetDirectoryName(initializationScript.Value);
                        if (string.IsNullOrEmpty(directoryName))
                        {
                            directoryName = Environment.CurrentDirectory;
                        }
                        result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName));
                        if (!string.IsNullOrEmpty(result))
                        {
                            throw new InvalidOperationException(result);
                        }

                        result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(initializationScript.Value));
                        if (!string.IsNullOrEmpty(result))
                        {
                            throw new InvalidOperationException(result);
                        }
                    }
                }

                if (!changedDirectory)
                {
                    var directoryName = Path.GetDirectoryName(evaluationScript.Value);
                    if (string.IsNullOrEmpty(directoryName))
                    {
                        directoryName = Environment.CurrentDirectory;
                    }
                    result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName));
                    if (!string.IsNullOrEmpty(result))
                    {
                        throw new InvalidOperationException(result);
                    }
                    changedDirectory = true;
                }

                var parameterVector = ParameterVectorParameter.ActualValue;
                var parameterNames  = ParameterNamesParameter.ActualValue;

                for (int i = 0; i < ProblemSizeParameter.ActualValue.Value; i++)
                {
                    matLabConnector.PutWorkspaceData(parameterNames[i], "base", parameterVector[i]);
                }

                result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(evaluationScript.Value));
                if (!string.IsNullOrEmpty(result))
                {
                    throw new InvalidOperationException(result);
                }

                string qualityVariableName = QualityVariableParameter.ActualValue.Value;
                var    quality             = matLabConnector.GetVariable(qualityVariableName, "base");

                if (double.IsNaN(quality))
                {
                    quality = double.MaxValue;
                }
                if (double.IsInfinity(quality))
                {
                    quality = double.MaxValue;
                }

                QualityParameter.ActualValue = new DoubleValue(quality);
                return(base.Apply());
            }
        }
예제 #14
0
        private static void ComputeUplinkFlowEnery_Updataenergy(Sensor sender)
        {
            //每次更新表之前先清空原表
            sender.MiniFlowTable.Clear();

            //非初始化路由表的更新,距离和角度矩阵不发生改变,因而对应的特征向量不变,所以仅需改变能量矩阵,故可较少与自主化服务器的交互,节省时长
            //每次更新信息时,AHP第一层矩阵都会发生变化,矩阵元素是自身剩余能量的函数
            if (sender.HopsToSink > 1)
            {
                //从邻居表中筛选出部分节点加入路由表中
                foreach (NeighborsTableEntry neiEntry in sender.NeighborsTable)
                {
                    //筛选一:仅当夹角为锐角且距离sink跳数更近的邻居节点才加入MiniFlowTable,初始UpLinkAction = Forward
                    if (neiEntry.angle < 90 && neiEntry.NeiNode.HopsToSink <= sender.HopsToSink)
                    {
                        MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                        MiniEntry.NeighborEntry = neiEntry;
                        sender.MiniFlowTable.Add(MiniEntry);
                    }
                }
                //路由表个数
                int number_of_MiniFlowTable = sender.MiniFlowTable.Count;

                //能量矩阵,取值[0,100],表示剩余能量百分比,Energy_max=100,表示剩余能量取值最大值,用作Energy矩阵元素归一化分母
                double[] Energy     = new double[number_of_MiniFlowTable];
                double   Energy_max = 100;

                //全零矩阵,用作上传数据至自动化Matlab中时充当虚部矩阵
                double[] pr = new double[number_of_MiniFlowTable];

                //构建相关矩阵
                for (int i = 0; i < number_of_MiniFlowTable; i++)
                {
                    Energy[i] = sender.MiniFlowTable.ToArray()[i].ResidualEnergyPercentage;
                }

                //原始矩阵数据归一化
                for (int i = 0; i < number_of_MiniFlowTable; i++)
                {
                    //值越大越好
                    Energy[i] = Energy[i] / Energy_max;
                }



                //定义最终需要上传的能量矩阵
                double[] Energy_Up_To_Matlab = new double[number_of_MiniFlowTable];



                //构建最终需要上传的属性矩阵
                for (int i = 0; i < number_of_MiniFlowTable; i++)
                {
                    //值越大越好,比重与数值成正比
                    Energy_Up_To_Matlab[i] = Standardization_Energy(Energy[i]);
                }

                //与Matlab建立连接

                // MLApp.MLApp matlab = new MLApp.MLApp();
                MLApp.MLApp matlab = sender.matlab;
                matlab.Execute(@"cd C:\Users\Kang\Documents\MATLAB\Fuzzy");
                //上传Energy_Up_To_Matlab矩阵到自动化服务器工作区,
                matlab.PutFullMatrix("Energy_Up_To_Matlab", "base", Energy_Up_To_Matlab, pr);
                //上传Distance_Up_To_Matlab矩阵自动化服务器工作区


                //在自动化服务器中执行此命令
                matlab.Execute("AHP_Energy_output=AHP_Fuzzy_Energy(Energy_Up_To_Matlab)");



                //定义对应的二维数组,表示Forward Set中节点相对应各属性的AHP矩阵

                //关于能量的AHP矩阵,AHP_Energy[i][j]表示第i个节点相对与第j个节点的能量比重
                Array AHP_Energy = new double[number_of_MiniFlowTable, number_of_MiniFlowTable];



                //接收自动化Matlab中矩阵时充当虚部矩阵,此参数为函数所必须,不可省略
                Array AHP_out_pr = new double[number_of_MiniFlowTable, number_of_MiniFlowTable];

                //接收Matlab自动化服务器中处理过的矩阵,其中的值的含义与AHP矩阵中值含义相同

                //接收Energy矩阵,实部存放在AHP_Energy中,虚部存放在ref AHP_out_pr中
                matlab.GetFullMatrix("AHP_Energy_output", "base", ref AHP_Energy, ref AHP_out_pr);



                //获取矩阵的最大特征值和特征向量
                //最大特征值
                double AHP_Energy_Eigenvalue;

                //对应的特征向量
                Array AHP_Energy_Eigenvector = new double[number_of_MiniFlowTable];

                //接收来自Matlab自动化服务器的特征向量的虚部,此矩阵为全零矩阵
                Array AHP_Eigenvector_pr = new double[number_of_MiniFlowTable];

                //通过Matlab求AHP_Energy矩阵的最大特征值和对应的特征向量
                matlab.PutFullMatrix("Matrix", "base", AHP_Energy, AHP_out_pr);
                matlab.Execute("[Eigenvalue,Eigenvector] = Get_Max_Eigenvalue_Eigenvector(Matrix)");
                AHP_Energy_Eigenvalue = matlab.GetVariable("Eigenvalue", "base");
                matlab.GetFullMatrix("Eigenvector", "base", ref AHP_Energy_Eigenvector, ref AHP_Eigenvector_pr);

                //归一化
                Array AHP_Energy_Eigenvector_Normalization = Normalization(AHP_Energy_Eigenvector);


                //构建AHP矩阵

                double[,] array =
                {
                    {       1,       1, 3 },
                    {       1,       1, 2 },
                    { 1.0 / 3, 1.0 / 2, 1 }
                };
                //第一层AHP矩阵
                Array AHP_Level1 = new double[3, 3];
                AHP_Level1 = array;

                Array  AHP_Level1_pr_in      = new double[3, 3];
                Array  AHP_Level1_pr_out     = new double[3];
                double AHP_Level1_Eigenvalue = 0;

                //第一层特征向量,依次表示能量,距离,角度的权重
                Array AHP_Level1_Eigenvector = new double[3];


                //通过Matlab求AHP_Level1矩阵的最大特征值和对应的特征向量
                matlab.PutFullMatrix("Matrix", "base", AHP_Level1, AHP_Level1_pr_in);
                matlab.Execute("[Eigenvalue,Eigenvector] = Get_Max_Eigenvalue_Eigenvector(Matrix)");
                AHP_Level1_Eigenvalue = matlab.GetVariable("Eigenvalue", "base");
                matlab.GetFullMatrix("Eigenvector", "base", ref AHP_Level1_Eigenvector, ref AHP_Level1_pr_out);

                //第一层特征向量归一化
                Array AHP_Level1_Eigenvector_Normalization = Normalization(AHP_Level1_Eigenvector);


                //求Priority == 属性在总目标上的权重 * 节点在该属性上的权重   然后求和
                for (int i = 0; i < sender.MiniFlowTable.Count; i++)
                {
                    double Priority_Energy   = (double)AHP_Level1_Eigenvector_Normalization.GetValue(0) * (double)AHP_Energy_Eigenvector_Normalization.GetValue(i);
                    double Priority_Distance = (double)AHP_Level1_Eigenvector_Normalization.GetValue(1) * (double)sender.AHP_Distance_Eigenvector_Normalization.GetValue(i);
                    double Priority_Angle    = (double)AHP_Level1_Eigenvector_Normalization.GetValue(2) * (double)sender.AHP_Angle_Eigenvector_Normalization.GetValue(i);
                    sender.MiniFlowTable.ToArray()[i].UpLinkPriority = Priority_Energy + Priority_Distance + Priority_Angle;
                    //具体得分比重,用于显示观察,鼠标移动到节点上可观测具体数值
                    sender.MiniFlowTable.ToArray()[i].UpLinkPriority_Energy   = Priority_Energy;
                    sender.MiniFlowTable.ToArray()[i].UpLinkPriority_Distance = Priority_Distance;
                    sender.MiniFlowTable.ToArray()[i].UpLinkPriority_Angle    = Priority_Angle;
                }

                //排序
                sender.MiniFlowTable.Sort(new MiniFlowTableSorterUpLinkPriority());


                //候选集大小阈值,邻居节点总数开平方,然后向上取整
                int Ftheashoeld = Convert.ToInt16(Math.Ceiling(Math.Sqrt(sender.NeighborsTable.Count)));
                sender.forwardnumber = 0;
                foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                {
                    if (sender.forwardnumber < Ftheashoeld)
                    {
                        MiniEntry.UpLinkAction = FlowAction.Forward;
                        sender.forwardnumber++;
                    }
                    else
                    {
                        MiniEntry.UpLinkAction = FlowAction.Drop;
                    }
                }

                //环检测
                foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                {
                    if (MiniEntry.UpLinkAction == FlowAction.Forward)
                    {
                        foreach (MiniFlowTableEntry mini in MiniEntry.NeighborEntry.NeiNode.MiniFlowTable)
                        {
                            //发现环
                            if (mini.ID == sender.ID && mini.UpLinkAction == FlowAction.Forward)
                            {
                                //破环
                                //破环原则:保留周边路由节点平均能量较低者的路由表项
                                if (sender.MiniFlowTable_Energy_average >= MiniEntry.NeighborEntry.NeiNode.MiniFlowTable_Energy_average)
                                {
                                    MiniEntry.UpLinkAction = FlowAction.Drop;
                                    sender.forwardnumber--;
                                }
                                else
                                {
                                    mini.UpLinkAction = FlowAction.Drop;
                                    MiniEntry.NeighborEntry.NeiNode.forwardnumber--;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                //转发表中只有sink节点
                foreach (NeighborsTableEntry neiEntry in sender.NeighborsTable)
                {
                    if (neiEntry.ID == 0)
                    {
                        MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                        MiniEntry.NeighborEntry  = neiEntry;
                        MiniEntry.UpLinkPriority = 1;
                        sender.MiniFlowTable.Add(MiniEntry);
                    }
                }
            }
        }
예제 #15
0
        public string Upload(int Id, string filename, string Data, int fs)
        {
            //TODO: Pass the file to the Feature Extractor

            #region Filter File
            string path = Server.MapPath("~/Models/MatlabFilters");
            System.IO.File.WriteAllText(path + "\\" + filename, Data);
            MLApp.MLApp matlab = new MLApp.MLApp();
            matlab.Execute("cd('" + path + "')");
            matlab.Execute("a=load('" + filename + "')");
            matlab.Execute("c=baselinefilter(a," + fs + ")");
            var    o        = (double[, ])matlab.GetVariable("c", "base");
            string filedata = "";

            for (int i = 0; i < o.GetLength(0); i++)
            {
                for (int j = 0; j <= o.GetLength(1); j++)
                {
                    filedata += o[i, j] + " ";
                }
                filedata.Trim(' ');

                filedata += "\n";
            }
            #endregion

            #region Pass File to Feature Extractor
            ECG ecgFeatureExtractor = new ECG();
            InputVector = ecgFeatureExtractor.ExtractFeatures(filedata, filename, fs); // fs = 370
            string filename2 = "feat.txt";
            File.WriteAllText(path + "\\" + filename2, InputVector);
            #endregion

            //File.WriteAllText(path + "\\" + filename,InputVector);

            #region Create New Record
            CardiologistV2.DAL.DatabaseContext db = new CardiologistV2.DAL.DatabaseContext();
            var p = db.Patients.Find(Id);
            var r = new CardiologistV2.Models.Record();
            r.PatientID = Id;
            r.Recdate   = DateTime.Now;
            r.Data      = filedata;

            //r.Featuress.Add(new Features() {
            //Value=InputVector,
            //})
            ;// = InputVector;
            #endregion

            //Calling Matlab...
            #region simulate network
            matlab.Execute("b = load('" + filename2 + "')");
            matlab.Execute("n = load('matlab.mat')");
            matlab.Execute("s = sim(n.net ,b)");
            var obj = (double[, ])matlab.GetVariable("s", "base");
            #endregion

            #region Make Logical Decision
            int MaxIndex = -1;
            int numpulses = obj.GetLength(1);
            int numpvc = 0; int numlbbb = 0; int numrbbb = 0; int numnormal = 0;
            var vector = new List <double>();
            for (int j = 0; j < numpulses; j++)
            {
                for (int i = 0; i < obj.GetLength(0); i++)
                {
                    vector.Add(obj[i, j]);
                }
                MaxIndex = vector.IndexOf(vector.Max());
                switch (MaxIndex)
                {
                case 0:     //pvc
                    numpvc++;
                    break;

                case 1:     //lbbb
                    numlbbb++;
                    break;

                case 2:     //rbbb
                    numrbbb++;
                    break;

                case 3:     //normal
                    numnormal++;
                    break;

                default:
                    break;
                }
            }

            string result = "Pvc = " + ((double)numpvc * 100.00) / numpulses + "%" + "Lbbb = "
                            + ((double)numlbbb * 100.00) / numpulses + "% " + "Rbbb = "
                            + ((double)numrbbb * 100.00) / numpulses + "% " + "Normal = "
                            + ((double)numnormal * 100.00) / numpulses + "%";
            #endregion

            #region Save in Database
            r.Result = result;
            p.Records.Add(r);
            db.SaveChanges();
            #endregion
            //TODO: Say everything's Alright
            return("200|" + result);
        }
예제 #16
0
        public ActionResult Create(Record record, HttpPostedFileBase txtfile)
        {
            if (ModelState.IsValid)
            {
                string filename = ""; string path = ""; string Data = "";
                if (txtfile != null && txtfile.ContentLength > 0)
                {
                    filename = System.Guid.NewGuid() + "_" + txtfile.FileName;
                    path     = Server.MapPath("~/Signals/" + filename);
                    txtfile.SaveAs(path);
                    //   record.Data = filename;
                    Data        = System.IO.File.ReadAllText(path);
                    record.Data = Data;
                }
                #region Filter File
                string path1 = Server.MapPath("~/Matlab");
                System.IO.File.WriteAllText(path1 + "\\" + filename, Data);
                MLApp.MLApp matlab = new MLApp.MLApp();
                matlab.Execute("cd('" + path1 + "')");
                matlab.Execute("a=load('" + filename + "')");
                matlab.Execute("c=baselinefilter(a," + 370 + ")");
                var    o        = (double[, ])matlab.GetVariable("c", "base");
                string filedata = "";

                for (int i = 0; i < o.GetLength(0); i++)
                {
                    for (int j = 0; j < o.GetLength(1); j++)
                    {
                        filedata += o[i, j] + " ";
                    }
                    filedata.Trim(' ');

                    filedata += "\n";
                }
                #endregion //DONE!

                #region Pass File to Feature Extractor
                ECG    ecgFeatureExtractor = new ECG();
                string InputVector         = ecgFeatureExtractor.ExtractFeatures(filedata, filename, 370); // fs = 370
                string filename2           = "feat.txt";
                System.IO.File.WriteAllText(path1 + "\\" + filename2, InputVector);
                #endregion


                #region simulate network
                matlab.Execute("b = load ('" + filename2 + "')");
                matlab.Execute("n = load('matlab.mat')");
                matlab.Execute("s = sim(n.net ,b)");
                var obj = (double[, ])matlab.GetVariable("s", "base");
                #endregion

                /* #region Make Logical Decision
                 * int MaxIndex = -1;
                 * int numpulses = obj.GetLength(1);
                 * int numpvc = 0; int numlbbb = 0; int numrbbb = 0; int numnormal = 0;
                 * var vector = new List<double>();
                 * for (int j = 0; j < numpulses; j++)
                 * {
                 *  // for (int i = 0; i < obj.GetLength(0); i++)
                 *   for (int i = 0; i < 4; i++)
                 *   {
                 *       vector.Add(obj[i, j]);
                 *   }
                 *   MaxIndex = vector.IndexOf(vector.Max());
                 *   switch (MaxIndex)
                 *   {
                 *       case 0: //pvc
                 *           numpvc++;
                 *           break;
                 *       case 1: //lbbb
                 *           numlbbb++;
                 *           break;
                 *       case 2: //rbbb
                 *           numrbbb++;
                 *           break;
                 *       case 3: //normal
                 *           numnormal++;
                 *           break;
                 *       default:
                 *           break;
                 *   }
                 * }
                 * string result = "Pvc = " + ((double)(numpvc * 100) / numpulses )+ "%" + "Lbbb = "
                 + ((double)(numlbbb * 100) / numpulses )+ "% " + "Rbbb = "
                 + ((double)(numrbbb * 100) / numpulses )+ "% " + "Normal = "
                 + ((double)(numnormal * 100) / numpulses )+ "%";
                 +
                 + //string result = "Pvc = " + numpvc + "lbbb = " + numlbbb + "rbbb =" + numrbbb + "normal = " + numnormal;
                 #endregion
                 */
                #region other result
                int non = 0;
                int nol = 0;
                int nor = 0;
                int nop = 0;
                for (int i = 0; i < obj.GetLength(1); i++)
                {
                    double maxx = -1;
                    for (int j = 0; j < 4; j++)
                    {
                        if (obj[0, i] >= maxx)
                        {
                            maxx = obj[0, i];
                        }
                        if (obj[1, i] >= maxx)
                        {
                            maxx = obj[1, i];
                        }
                        if (obj[2, i] >= maxx)
                        {
                            maxx = obj[2, i];
                        }
                        if (obj[3, i] >= maxx)
                        {
                            maxx = obj[3, i];
                        }
                        if (obj[0, i] == maxx)
                        {
                            nop++;
                        }
                        if (obj[1, i] == maxx)
                        {
                            nol++;
                        }
                        if (obj[2, i] == maxx)
                        {
                            nor++;
                        }
                        if (obj[3, i] == maxx)
                        {
                            non++;
                        }
                    }
                }
                string resultt = "Pvc = " + nop + "lbbb = " + nol + "rbbb =" + nor + "normal = " + non;

                /*   string resultt = "Pvc = " + (double)((nop * 100) / obj.GetLength(0)) + "%" + "Lbbb = "
                 + (double)((nol * 100) / obj.GetLength(0)) + "% " + "Rbbb = "
                 + (double)((nor * 100) / obj.GetLength(0))+ "% " + "Normal = "
                 + (double)((non * 100) / obj.GetLength(0)) + "%";*/
                #endregion
                record.Result = resultt;
                //int PatientID = WebSecurity.GetUserId(User.Identity.Name);
                //Patient patient = db.Patients.Find(record.PatientID);
                int pid = 0;
                foreach (Patient pa in db.Patients)
                {
                    if (pa.Name == User.Identity.Name)
                    {
                        pid = pa.PatientID;
                    }
                }

                record.PatientID = pid;
                db.Records.Add(record);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.PatientID = new SelectList(db.Patients, "PatientID", "Name", record.PatientID);
            return(View(record));
        }
예제 #17
0
        void matlab(string code)
        {
            string[] lines, var_temp;
            List<string> variables=new List<string>();
            List<string> var_result = new List<string>();
            int var_count=0;

            lines = code.Split('\r');

            MLApp.MLApp matlab = new MLApp.MLApp();

            for (int a = 0; a < lines.Count(); a++)
            {
                if(lines[a].StartsWith("\n"))
                    lines[a]=lines[a].Remove(0,1);

                string i = matlab.Execute(lines[a]);
                //TODO osetrit ak nie je spravny matlabovsky prikaz

                if (lines[a].Contains('='))                         //ak obsahuje = prekpokladame ze pred = je premenna ktoru posleme spet
                {
                    var_temp = lines[a].Split('=')[0].Split(", ".ToCharArray());
                    for (int b = 0; b < var_temp.Count(); b++)
                    {
                        if (var_temp[b].StartsWith("["))                //odstranime [] ak nahodou obsahuje
                        {
                            var_temp[b]=var_temp[b].Remove(0, 1);
                        }
                        if (var_temp[b].EndsWith("]"))                //odstranime [] ak nahodou obsahuje
                        {
                            var_temp[b]=var_temp[b].Remove(var_temp[b].Length - 1, 1);
                        }
                        if (!variables.Contains(var_temp[b]) && var_temp[b]!="")
                        {
                            variables.Add(var_temp[b]);
                            var_count++;
                        }
                    }
                }
                //matlab.Execute(lines[a]);
            }
            foreach (string variable in variables)
            {
                try
                {
                    var_result.Add(Convert.ToString(matlab.GetVariable(variable, "base")));
                }
                catch(Exception e)
                {
                    var_result.Add(variable + ": ??? Undefined function or variable");
                }
            }

            for (int a = 0; a < variables.Count; a++)
            {
                result += variables[a] + " = " + var_result[a] + "\r\n";
            }
        }
예제 #18
0
        public static void ComputeUplinkFlowEnery(Sensor sender)
        {
            if (Settings.Default.RoutingAlgorithm == "LORA")
            {
                double n = Convert.ToDouble(sender.NeighborsTable.Count) + 1;

                double LControl = Settings.Default.ExpoLCnt * Math.Sqrt(n);
                double HControl = Settings.Default.ExpoHCnt * Math.Sqrt(n);
                double EControl = Settings.Default.ExpoECnt * Math.Sqrt(n);
                double RControl = Settings.Default.ExpoRCnt * Math.Sqrt(n);


                double HSum = 0; // sum of h value.
                double RSum = 0;
                foreach (NeighborsTableEntry can in sender.NeighborsTable)
                {
                    HSum += can.H;
                    RSum += can.R;
                }

                // normalized values.
                foreach (NeighborsTableEntry neiEntry in sender.NeighborsTable)
                {
                    if (neiEntry.NeiNode.ResidualEnergyPercentage >= 0) // the node is a live.
                    {
                        MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                        MiniEntry.NeighborEntry    = neiEntry;
                        MiniEntry.NeighborEntry.HN = 1.0 / (Math.Pow((Convert.ToDouble(MiniEntry.NeighborEntry.H) + 1.0), HControl));
                        MiniEntry.NeighborEntry.RN = 1 - (Math.Pow(MiniEntry.NeighborEntry.R, RControl) / RSum);
                        MiniEntry.NeighborEntry.LN = Math.Pow(MiniEntry.NeighborEntry.L / 100, LControl);

                        MiniEntry.NeighborEntry.E  = Operations.DistanceBetweenTwoPoints(PublicParamerters.SinkNode.CenterLocation, MiniEntry.NeighborEntry.CenterLocation);
                        MiniEntry.NeighborEntry.EN = (MiniEntry.NeighborEntry.E / (Operations.DistanceBetweenTwoPoints(PublicParamerters.SinkNode.CenterLocation, sender.CenterLocation) + sender.ComunicationRangeRadius));

                        sender.MiniFlowTable.Add(MiniEntry);
                    }
                }

                // pro sum
                double HpSum = 0; // sum of h value.
                double LpSum = 0;
                double RpSum = 0;
                double EpSum = 0;
                foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                {
                    HpSum += (1 - Math.Exp(MiniEntry.NeighborEntry.HN));
                    RpSum += Math.Exp(MiniEntry.NeighborEntry.RN);
                    LpSum += (1 - Math.Exp(-MiniEntry.NeighborEntry.LN));
                    EpSum += (Math.Pow((1 - Math.Sqrt(MiniEntry.NeighborEntry.EN)), EControl));
                }

                double sumAll = 0;
                foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                {
                    MiniEntry.NeighborEntry.HP = (1 - Math.Exp(MiniEntry.NeighborEntry.HN)) / HpSum;
                    MiniEntry.NeighborEntry.RP = Math.Exp(MiniEntry.NeighborEntry.RN) / RpSum;
                    MiniEntry.NeighborEntry.LP = (1 - Math.Exp(-MiniEntry.NeighborEntry.LN)) / LpSum;
                    MiniEntry.NeighborEntry.EP = (Math.Pow((1 - Math.Sqrt(MiniEntry.NeighborEntry.EN)), EControl)) / EpSum;

                    MiniEntry.UpLinkPriority = (MiniEntry.NeighborEntry.EP + MiniEntry.NeighborEntry.HP + MiniEntry.NeighborEntry.RP + MiniEntry.NeighborEntry.LP) / 4;
                    sumAll += MiniEntry.UpLinkPriority;
                }

                // normalized:
                foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                {
                    MiniEntry.UpLinkPriority = (MiniEntry.UpLinkPriority / sumAll);
                }
                // sort:
                sender.MiniFlowTable.Sort(new MiniFlowTableSorterUpLinkPriority());

                // action:
                double average         = 1 / Convert.ToDouble(sender.MiniFlowTable.Count);
                int    Ftheashoeld     = Convert.ToInt16(Math.Ceiling(Math.Sqrt(Math.Sqrt(n)))); // theshold.
                int    forwardersCount = 0;
                foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                {
                    if (MiniEntry.UpLinkPriority >= average && forwardersCount <= Ftheashoeld)
                    {
                        MiniEntry.UpLinkAction = FlowAction.Forward;
                        forwardersCount++;
                    }
                    else
                    {
                        MiniEntry.UpLinkAction = FlowAction.Drop;
                    }
                }
            }

            if (Settings.Default.RoutingAlgorithm == "AHP_Fuzzy")
            {
                /*
                 * ------------------------------------
                 |MiniFlowTable|NeighborEntry|NeiNode |
                 * ------------------------------------
                 */


                //构建MiniFlowTable

                //与sink不相邻的节点
                if (sender.HopsToSink > 1)

                {
                    //从邻居表中筛选出部分节点加入路由表中
                    foreach (NeighborsTableEntry neiEntry in sender.NeighborsTable)
                    {
                        //筛选一:仅当夹角为锐角且距离sink跳数更近的邻居节点才加入MiniFlowTable,初始UpLinkAction = Forward
                        if (neiEntry.angle < 90 && neiEntry.NeiNode.HopsToSink <= sender.HopsToSink)
                        {
                            MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                            MiniEntry.NeighborEntry = neiEntry;
                            sender.MiniFlowTable.Add(MiniEntry);
                        }
                    }
                    //路由表个数
                    int number_of_MiniFlowTable = sender.MiniFlowTable.Count;

                    //能量矩阵,取值[0,100],表示剩余能量百分比,Energy_max=100,表示剩余能量取值最大值,用作Energy矩阵元素归一化分母
                    double[] Energy     = new double[number_of_MiniFlowTable];
                    double   Energy_max = 100;

                    //sender与forwarders之间的距离矩阵,取值[0,PublicParamerters.CommunicationRangeRadius]
                    //其中Distance_max=PublicParamerters.CommunicationRangeRadius,表距离取值最大值,用作Distance矩阵元素归一化分母
                    double[] Distance     = new double[number_of_MiniFlowTable];
                    double   Distance_max = PublicParamerters.CommunicationRangeRadius;

                    //角度矩阵,取值[0,90],因为路由表经过筛选一,Angle_max=90,表示角度取值最大值,用作Angle矩阵元素归一化分母
                    double[] Angle     = new double[number_of_MiniFlowTable];
                    double   Angle_max = 90;

                    //全零矩阵,用作上传数据至自动化Matlab中时充当虚部矩阵
                    double[] pr = new double[number_of_MiniFlowTable];



                    //构建相关矩阵
                    for (int i = 0; i < number_of_MiniFlowTable; i++)
                    {
                        Energy[i]   = sender.MiniFlowTable.ToArray()[i].ResidualEnergyPercentage;
                        Distance[i] = sender.MiniFlowTable.ToArray()[i].Distance_Sender_To_Receiver;
                        Angle[i]    = sender.MiniFlowTable.ToArray()[i].Angle;
                    }

                    //原始矩阵数据归一化
                    for (int i = 0; i < number_of_MiniFlowTable; i++)
                    {
                        //值越大越好
                        Energy[i] = Energy[i] / Energy_max;

                        //值越小越好
                        Distance[i] = Distance[i] / Distance_max;

                        //值越小越好
                        Angle[i] = Angle[i] / Angle_max;
                    }

                    //定义最终需要上传的属性矩阵

                    //定义最终需要上传的能量矩阵
                    double[] Energy_Up_To_Matlab = new double[number_of_MiniFlowTable];

                    //定义最终需要上传的距离矩阵
                    double[] Distance_Up_To_Matlab = new double[number_of_MiniFlowTable];

                    //定义最终需要上传的角度矩阵
                    double[] Angle_Up_To_Matlab = new double[number_of_MiniFlowTable];

                    //构建最终需要上传的属性矩阵
                    for (int i = 0; i < number_of_MiniFlowTable; i++)
                    {
                        //值越大越好,比重与数值成正比
                        Energy_Up_To_Matlab[i] = Standardization_Energy(Energy[i]);
                        // Energy_Up_To_Matlab[i] = Energy[i];

                        //值越小越好,比重与数值成反比
                        Distance_Up_To_Matlab[i] = Standardization_Distance(Distance[i]);
                        //Distance_Up_To_Matlab[i] = 1 - Distance[i];
                        //值越小越好,比重与数值成反比
                        Angle_Up_To_Matlab[i] = Standardization_Angle(Angle[i]);
                        //Angle_Up_To_Matlab[i] = 1 - Angle[i];
                    }

                    //利用Matlab构建对应矩阵


                    //首先将Matlab注册为自动化服务器
                    //从 C# 客户端程序中,将对您的项目的引用添加到 MATLAB COM 对象。例如,在 Microsoft® Visual Studio® 中,打开您的项目。在项目菜单中,选择添加引用。在“添加引用”对话框中,选择 COM 选项卡。选择 MATLAB 应用程序
                    //此例为调用函数示例

                    /*
                     *
                     *
                     *
                     * 在文件夹 c:\temp\example 中创建 MATLAB 函数 myfunc。
                     * function [x,y] = myfunc(a,b,c)
                     * x = a + b;
                     * y = sprintf('Hello %s',c);
                     *
                     *
                     *
                     *
                     *
                     * //// Create the MATLAB instance
                     * MLApp.MLApp matlab = new MLApp.MLApp();
                     *
                     * // Change to the directory where the function is located
                     * matlab.Execute(@"cd c:\temp\example");
                     *
                     * // Define the output
                     * object result = null;
                     *
                     * // Call the MATLAB function myfunc
                     * matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world");
                     *
                     * //Display result
                     * object[] res = result as object[];
                     *
                     * Console.WriteLine(res[0]);
                     * Console.WriteLine(res[1]);
                     * Console.ReadLine();
                     */


                    //与Matlab建立连接

                    // MLApp.MLApp matlab = new MLApp.MLApp();
                    MLApp.MLApp matlab = sender.matlab;
                    matlab.Execute(@"cd C:\Users\Kang\Documents\MATLAB\Fuzzy");
                    //上传Energy_Up_To_Matlab矩阵到自动化服务器工作区,
                    matlab.PutFullMatrix("Energy_Up_To_Matlab", "base", Energy_Up_To_Matlab, pr);
                    //上传Distance_Up_To_Matlab矩阵自动化服务器工作区
                    matlab.PutFullMatrix("Distance_Up_To_Matlab", "base", Distance_Up_To_Matlab, pr);
                    //上传Angle_Up_To_Matlab矩阵自动化服务器工作区
                    matlab.PutFullMatrix("Angle_Up_To_Matlab", "base", Angle_Up_To_Matlab, pr);

                    //在自动化服务器中执行此命令
                    matlab.Execute("[AHP_Energy_output,AHP_Distance_output,AHP_Angle_output]=AHP_Fuzzy(Energy_Up_To_Matlab,Distance_Up_To_Matlab,Angle_Up_To_Matlab)");



                    //定义对应的二维数组,表示Forward Set中节点相对应各属性的AHP矩阵

                    //关于能量的AHP矩阵,AHP_Energy[i][j]表示第i个节点相对与第j个节点的能量比重
                    Array AHP_Energy = new double[number_of_MiniFlowTable, number_of_MiniFlowTable];

                    //关于距离的AHP矩阵,AHP_Distance[i][j]表示第i个节点相对与第j个节点的距离比重
                    Array AHP_Distance = new double[number_of_MiniFlowTable, number_of_MiniFlowTable];

                    //关于角度的AHP矩阵,AHP_Angle[i][j]表示第i个节点相对与第j个节点的角度比重
                    Array AHP_Angle = new double[number_of_MiniFlowTable, number_of_MiniFlowTable];

                    //接收自动化Matlab中矩阵时充当虚部矩阵,此参数为函数所必须,不可省略
                    Array AHP_out_pr = new double[number_of_MiniFlowTable, number_of_MiniFlowTable];

                    //接收Matlab自动化服务器中处理过的矩阵,其中的值的含义与AHP矩阵中值含义相同

                    //接收Energy矩阵,实部存放在AHP_Energy中,虚部存放在ref AHP_out_pr中
                    matlab.GetFullMatrix("AHP_Energy_output", "base", ref AHP_Energy, ref AHP_out_pr);

                    //接收Distance矩阵,存放在AHP_Distance中
                    matlab.GetFullMatrix("AHP_Distance_output", "base", ref AHP_Distance, ref AHP_out_pr);

                    //接收Angle矩阵,存放在AHP_Angle中
                    matlab.GetFullMatrix("AHP_Angle_output", "base", ref AHP_Angle, ref AHP_out_pr);



                    //获取矩阵的最大特征值和特征向量
                    //最大特征值
                    double AHP_Energy_Eigenvalue;
                    double AHP_Distance_Eigenvalue;
                    double AHP_Angle_Eigenvalue;
                    //对应的特征向量
                    Array AHP_Energy_Eigenvector   = new double[number_of_MiniFlowTable];
                    Array AHP_Distance_Eigenvector = new double[number_of_MiniFlowTable];
                    Array AHP_Angle_Eigenvector    = new double[number_of_MiniFlowTable];

                    //接收来自Matlab自动化服务器的特征向量的虚部,此矩阵为全零矩阵
                    Array AHP_Eigenvector_pr = new double[number_of_MiniFlowTable];

                    //通过Matlab求AHP_Energy矩阵的最大特征值和对应的特征向量
                    matlab.PutFullMatrix("Matrix", "base", AHP_Energy, AHP_out_pr);
                    matlab.Execute("[Eigenvalue,Eigenvector] = Get_Max_Eigenvalue_Eigenvector(Matrix)");
                    AHP_Energy_Eigenvalue = matlab.GetVariable("Eigenvalue", "base");
                    matlab.GetFullMatrix("Eigenvector", "base", ref AHP_Energy_Eigenvector, ref AHP_Eigenvector_pr);


                    //通过Matlab求AHP_Distance矩阵的最大特征值和对应的特征向量
                    matlab.PutFullMatrix("Matrix", "base", AHP_Distance, AHP_out_pr);
                    matlab.Execute("[Eigenvalue,Eigenvector] = Get_Max_Eigenvalue_Eigenvector(Matrix)");
                    AHP_Distance_Eigenvalue = matlab.GetVariable("Eigenvalue", "base");
                    matlab.GetFullMatrix("Eigenvector", "base", ref AHP_Distance_Eigenvector, ref AHP_Eigenvector_pr);


                    //通过Matlab求AHP_Angle矩阵的最大特征值和对应的特征向量
                    matlab.PutFullMatrix("Matrix", "base", AHP_Angle, AHP_out_pr);
                    matlab.Execute("[Eigenvalue,Eigenvector] = Get_Max_Eigenvalue_Eigenvector(Matrix)");
                    AHP_Angle_Eigenvalue = matlab.GetVariable("Eigenvalue", "base");
                    matlab.GetFullMatrix("Eigenvector", "base", ref AHP_Angle_Eigenvector, ref AHP_Eigenvector_pr);

                    //归一化
                    Array AHP_Energy_Eigenvector_Normalization   = Normalization(AHP_Energy_Eigenvector);
                    Array AHP_Distance_Eigenvector_Normalization = Normalization(AHP_Distance_Eigenvector);
                    Array AHP_Angle_Eigenvector_Normalization    = Normalization(AHP_Angle_Eigenvector);


                    //保留距离和角度归一化向量
                    sender.AHP_Angle_Eigenvector_Normalization    = AHP_Angle_Eigenvector_Normalization;
                    sender.AHP_Distance_Eigenvector_Normalization = AHP_Distance_Eigenvector_Normalization;



                    //构建AHP矩阵

                    double[,] array =
                    {
                        {       1,       1, 3 },
                        {       1,       1, 2 },
                        { 1.0 / 3, 1.0 / 2, 1 }
                    };
                    //第一层AHP矩阵
                    Array AHP_Level1 = new double[3, 3];
                    AHP_Level1 = array;

                    Array  AHP_Level1_pr_in      = new double[3, 3];
                    Array  AHP_Level1_pr_out     = new double[3];
                    double AHP_Level1_Eigenvalue = 0;

                    //第一层特征向量,依次表示能量,距离,角度的权重
                    Array AHP_Level1_Eigenvector = new double[3];


                    //通过Matlab求AHP_Level1矩阵的最大特征值和对应的特征向量
                    matlab.PutFullMatrix("Matrix", "base", AHP_Level1, AHP_Level1_pr_in);
                    matlab.Execute("[Eigenvalue,Eigenvector] = Get_Max_Eigenvalue_Eigenvector(Matrix)");
                    AHP_Level1_Eigenvalue = matlab.GetVariable("Eigenvalue", "base");
                    matlab.GetFullMatrix("Eigenvector", "base", ref AHP_Level1_Eigenvector, ref AHP_Level1_pr_out);

                    //第一层特征向量归一化
                    Array AHP_Level1_Eigenvector_Normalization = Normalization(AHP_Level1_Eigenvector);



                    //求Priority == 属性在总目标上的权重 * 节点在该属性上的权重   然后求和
                    for (int i = 0; i < sender.MiniFlowTable.Count; i++)
                    {
                        double Priority_Energy   = (double)AHP_Level1_Eigenvector_Normalization.GetValue(0) * (double)AHP_Energy_Eigenvector_Normalization.GetValue(i);
                        double Priority_Distance = (double)AHP_Level1_Eigenvector_Normalization.GetValue(1) * (double)AHP_Distance_Eigenvector_Normalization.GetValue(i);
                        double Priority_Angle    = (double)AHP_Level1_Eigenvector_Normalization.GetValue(2) * (double)AHP_Angle_Eigenvector_Normalization.GetValue(i);
                        sender.MiniFlowTable.ToArray()[i].UpLinkPriority = Priority_Energy + Priority_Distance + Priority_Angle;
                        //具体得分比重,用于显示观察,鼠标移动到节点上可观测具体数值
                        sender.MiniFlowTable.ToArray()[i].UpLinkPriority_Energy   = Priority_Energy;
                        sender.MiniFlowTable.ToArray()[i].UpLinkPriority_Distance = Priority_Distance;
                        sender.MiniFlowTable.ToArray()[i].UpLinkPriority_Angle    = Priority_Angle;
                    }

                    //排序
                    sender.MiniFlowTable.Sort(new MiniFlowTableSorterUpLinkPriority());


                    //候选集大小阈值,邻居节点总数开平方,然后向上取整
                    int Ftheashoeld = Convert.ToInt16(Math.Ceiling(Math.Sqrt(sender.NeighborsTable.Count)));
                    sender.forwardnumber = 0;
                    foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                    {
                        if (sender.forwardnumber < Ftheashoeld)
                        {
                            MiniEntry.UpLinkAction = FlowAction.Forward;
                            sender.forwardnumber++;
                        }
                        else
                        {
                            MiniEntry.UpLinkAction = FlowAction.Drop;
                        }
                    }

                    //环检测
                    foreach (MiniFlowTableEntry MiniEntry in sender.MiniFlowTable)
                    {
                        if (MiniEntry.UpLinkAction == FlowAction.Forward)
                        {
                            foreach (MiniFlowTableEntry mini in MiniEntry.NeighborEntry.NeiNode.MiniFlowTable)
                            {
                                //发现环
                                if (mini.ID == sender.ID && mini.UpLinkAction == FlowAction.Forward)
                                {
                                    //破环
                                    if (sender.forwardnumber >= MiniEntry.NeighborEntry.NeiNode.forwardnumber)
                                    {
                                        MiniEntry.UpLinkAction = FlowAction.Drop;
                                        sender.forwardnumber--;
                                    }
                                    else
                                    {
                                        mini.UpLinkAction = FlowAction.Drop;
                                        MiniEntry.NeighborEntry.NeiNode.forwardnumber--;
                                    }
                                }
                            }
                        }
                    }
                }

                //与sink相邻的节点
                else
                {
                    //转发表中只有sink节点
                    foreach (NeighborsTableEntry neiEntry in sender.NeighborsTable)
                    {
                        if (neiEntry.ID == 0)
                        {
                            MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                            MiniEntry.NeighborEntry  = neiEntry;
                            MiniEntry.UpLinkPriority = 1;
                            sender.MiniFlowTable.Add(MiniEntry);
                        }
                    }
                }
            }

            if (Settings.Default.RoutingAlgorithm == "ORR")
            {
                //sink的邻居节点
                if (sender.HopsToSink == 1)
                {
                    //转发表中仅包括sink节点
                    foreach (NeighborsTableEntry neiEntry in sender.NeighborsTable)
                    {
                        if (neiEntry.ID == 0)
                        {
                            MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                            MiniEntry.NeighborEntry  = neiEntry;
                            MiniEntry.UpLinkPriority = 1;
                            sender.MiniFlowTable.Add(MiniEntry);
                        }
                    }
                }
                else
                {
                    foreach (NeighborsTableEntry nei in sender.NeighborsTable)
                    {
                        if (sender.Forwarders.Contains(nei.NeiNode))
                        {
                            MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                            MiniEntry.NeighborEntry = nei;
                            //FS表示优先级
                            MiniEntry.UpLinkPriority = nei.NeiNode.FS;
                            sender.MiniFlowTable.Add(MiniEntry);
                        }
                    }
                }
            }

            if (Settings.Default.RoutingAlgorithm == "ORW")
            {
                //sink的邻居节点
                if (sender.HopsToSink == 1)
                {
                    //转发表中仅包括sink节点
                    foreach (NeighborsTableEntry neiEntry in sender.NeighborsTable)
                    {
                        if (neiEntry.ID == 0)
                        {
                            MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                            MiniEntry.NeighborEntry  = neiEntry;
                            MiniEntry.UpLinkPriority = 1;
                            sender.MiniFlowTable.Add(MiniEntry);
                        }
                    }
                }
                else
                {
                    foreach (NeighborsTableEntry nei in sender.NeighborsTable)
                    {
                        if (sender.Forwarders.Contains(nei.NeiNode))
                        {
                            MiniFlowTableEntry MiniEntry = new MiniFlowTableEntry();
                            MiniEntry.NeighborEntry = nei;
                            //EDC表示优先级
                            MiniEntry.UpLinkPriority = nei.NeiNode.EDC;
                            sender.MiniFlowTable.Add(MiniEntry);
                        }
                    }
                }
            }
        }