Exemplo n.º 1
0
        /// <summary>
        /// Overload constructor that takes the transfer function as input and initiate The start variables in Matlab
        /// </summary>
        /// <param name="num">Numorator cooefficients of the transfer function polynomial</param>
        /// <param name="den">Denominator cooefficients of the transfer function polynomial</param>
        public SimTF(Double[] num, Double[] den)
        {
            MWinstance = new MLApp.MLApp();

            // Puts the num en den in the Matlab enviroment
            MWinstance.PutWorkspaceData("num", "base", num);
            MWinstance.PutWorkspaceData("den", "base", den);

            //Create the transfer function
            MWinstance.Execute(STR_SysTfnumDen);
        }
Exemplo n.º 2
0
 // Access the Matlab Workspace to Send/Remove/Get Data
 /// <summary>
 /// Send the array of doubles to Matlab.
 /// </summary>
 /// <param name="varName"> The Unique variable name.</param>
 /// <param name="dblInput"> Passed Array of Data.</param>
 /// <exception cref="System.RunTime.InteropServices.COMException"> Thrown when matlab is closed and no connection.</exception>
 public static void sendDataToMatlab(string varName, double[] dblInput)
 {
     try
     {
         matlab.PutWorkspaceData(varName, "base", dblInput); // varname, workspace, values
     }
     catch (System.Runtime.InteropServices.COMException ex)
     {
         matlab = null;
     }
 }
Exemplo n.º 3
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";
        }
Exemplo n.º 4
0
 public static void PlotarVetor(double[] vetor)
 {
     MLApp.MLApp matlab = new MLApp.MLApp();
     matlab.Visible = 0;
     //matlab.PutWorkspaceData("a", "base", matriz);
     matlab.PutWorkspaceData("a", "base", vetor);
     matlab.Execute("plot(a);");
 }
        private void Show3DModel()
        {
            Model3D obj_3d = new Model3D();

            if (listData.Count + 1 != obj_3d.iDataLen)
            {
                return;
            }

            double[] data = new double[obj_3d.iDataLen];
            for (int i = 0; i < obj_3d.iDataLen - 1; i++)
            {
                data[i] = listData[i];
            }
            data[obj_3d.iDataLen - 1] = data[0];

            double[] dX = obj_3d.GetX(data);
            double[] dY = obj_3d.GetY(data);
            double[] dZ = obj_3d.GetZ(iMeasureTimes);

            matlab.PutWorkspaceData("X", "base", dX);
            matlab.PutWorkspaceData("Y", "base", dY);
            matlab.PutWorkspaceData("Z", "base", dZ);

            String sret = matlab.Execute("plot3(X, Y, Z, 'LineWidth', 2);");

            matlab.Execute("xlabel('X'), ylabel('Y'), zlabel('Z');");
            matlab.Execute("grid on;");
            matlab.Execute("view(45, 45);");
            matlab.Execute("hold on;");

            iMeasureTimes += iStepSize;

            List <double[]> listXYZ = new List <double[]>();

            listXYZ.Add(dX);
            listXYZ.Add(dY);
            listXYZ.Add(dZ);

            queueData.Enqueue(listXYZ);

            if (queueData.Count == 2)
            {
                ShowClose3DSurf();
            }
        }
        /// <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);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Sets the Transfer Function in Matlab
        /// </summary>
        public void setTFtoMatlabEnviroment()
        {
            // Puts the num en den in the Matlab enviroment
            MWinstance.PutWorkspaceData("num", "base", num);
            MWinstance.PutWorkspaceData("den", "base", den);

            //Create the transfer function
            MWinstance.Execute(STR_SysTfnumDen);
        }
        public void runScript(MLApp.MLApp matlab, string range)
        {
            double start = Convert.ToDouble(start_freq);

            Console.WriteLine("Start freq = " + start);
            double stop = Convert.ToDouble(stop_freq);

            Console.WriteLine("Stop freq = " + stop);
            double bw = Convert.ToDouble(span);

            Console.WriteLine("Bandwidth = " + bw);


            Workbook.workbook.Save();
            string path       = pathname.Text;
            string excel_file = pathname.Text + filename.Text + ".xlsx";

            // Change to the directory where the MATLAB function is located
            matlab.Execute(@path);
            matlab.PutWorkspaceData("data_file", "base", excel_file);
            matlab.PutWorkspaceData("start", "base", start);
            matlab.PutWorkspaceData("stop", "base", stop);
            matlab.PutWorkspaceData("span", "base", bw);
            matlab.PutWorkspaceData("range", "base", range);

            //Run the SVD curve fitting method
            Console.WriteLine(matlab.Execute("[Q_L,Q_UL,f_center,s21] = original_expression_SVD(data_file,start,stop,span,range)"));
            Thread.Sleep(3000);


            //Obtain the returned values from the workspace
            Q_L      = getQ(matlab)[0];
            Q_UL     = getQ(matlab)[1];
            f_center = getQ(matlab)[2];
            s21      = getQ(matlab)[3];
        }
Exemplo n.º 9
0
 public static void SendMatrix(Matrix <double> mat, string matlabname, string workspacename = WORKSPACENAME)
 {
     ML.PutWorkspaceData(matlabname, workspacename, mat.Data);
 }
        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());
            }
        }
 public void SetVariable(string varName, object value)
 {
     _mlapp.PutWorkspaceData(varName, "base", value);
 }
Exemplo n.º 12
0
        private void hideInImage(byte[,] red1, byte[,] green1, byte[,] blue1)
        {
            byte[,] red = red1;
            int randh = 0, randw = 0;

            byte[,] green = green1;
            byte[,] blue  = blue1;
            #region hide data in image
            int height = red.GetLength(0), width = red.GetLength(1);

            /*Since data will be added from  5th pixel. 1st three pixels used to store
             * the position of lastpixel in which data is stored
             * and 4th pixel storing whether the last pixel has used all it's capacity or not
             */
            long encryption = 0, hidetime;
            int  j = 4;
            try
            {
                string filinter = "C:\\temp\\example\\Data\\hello.txt";

                timer.Start();
                f(textfile, filinter);
                timer.Stop();
                encryption  = timer.ElapsedMilliseconds;
                label7.Text = (encryption.ToString());

                byte[] fileData = StreamFile(filinter);
                textfile = filinter;
                int len = fileData.Length;
                int i;
                int requiredBitsRed, requiredBitsGreen, requiredBitsBlue;
                var encryptbmp = new Bitmap(width, height);

                if ((len * 8 > capacity) || (width < 5))
                {
                    throw new ImageToSmall("Image is too small to use");
                }
                else
                {
                    timer.Start();
                    int  currentByte = 0;
                    bool isDone      = false;
                    int  less;
                    byte byte_to_replace, a, b;
                    int  offset = 0;
                    int  pixel_row = 0, pixel_column = 0, pixel_color = 0, num_of_bits_stored = 5;
                    for (i = 0; i < height; i++)
                    {
                        for (; j < width; j++)
                        {
                            a = 0; b = 0;


                            requiredBitsRed   = requiredBit(red[i, j]);
                            requiredBitsGreen = requiredBit(green[i, j]);
                            requiredBitsBlue  = requiredBit(blue[i, j]);

                            #region replace red pixel
                            byte_to_replace = 0;
                            if (requiredBitsRed <= 8 - offset)
                            {
                                byte_to_replace = get_byte(offset, fileData[currentByte], requiredBitsRed);
                                offset         += requiredBitsRed;
                                if (offset == 8)
                                {
                                    offset = 0;
                                    ++currentByte;
                                }
                                if (currentByte == len)
                                {
                                    pixel_row          = i;
                                    pixel_column       = j;
                                    pixel_color        = 1;
                                    num_of_bits_stored = requiredBitsRed;
                                    isDone             = true;
                                }
                            }
                            else if (requiredBitsRed > 8 - offset)
                            {
                                less         = 8 - offset;
                                a            = get_byte(offset, fileData[currentByte], less);
                                currentByte += 1;
                                if (currentByte == len)
                                {
                                    pixel_row          = i;
                                    pixel_column       = j;
                                    pixel_color        = 1;
                                    num_of_bits_stored = less;
                                    b      = 0;
                                    isDone = true;
                                }
                                else
                                {
                                    offset  = 0;
                                    b       = get_byte(offset, fileData[currentByte], requiredBitsRed - less);
                                    offset += requiredBitsRed - less;
                                }
                                byte_to_replace = (byte)((a << requiredBitsRed - less) | b);
                            }


                            red[i, j] = (byte)(maskByte(red[i, j], requiredBitsRed) | byte_to_replace);
                            if (isDone)
                            {
                                break;
                            }
                            #endregion

                            #region replace blue pixel
                            byte_to_replace = 0;
                            if (requiredBitsBlue <= 8 - offset)
                            {
                                byte_to_replace = get_byte(offset, fileData[currentByte], requiredBitsBlue);
                                offset         += requiredBitsBlue;
                                if (offset == 8)
                                {
                                    offset = 0;
                                    ++currentByte;
                                }
                                if (currentByte == len)
                                {
                                    pixel_row          = i;
                                    pixel_column       = j;
                                    pixel_color        = 2;
                                    num_of_bits_stored = requiredBitsBlue;
                                    isDone             = true;
                                }
                            }
                            else if (requiredBitsBlue > 8 - offset)
                            {
                                less         = 8 - offset;
                                a            = get_byte(offset, fileData[currentByte], less);
                                currentByte += 1;
                                if (currentByte == len)
                                {
                                    pixel_row          = i;
                                    pixel_column       = j;
                                    pixel_color        = 2;
                                    num_of_bits_stored = less;
                                    b      = 0;
                                    isDone = true;
                                }
                                else
                                {
                                    offset  = 0;
                                    b       = get_byte(offset, fileData[currentByte], requiredBitsBlue - less);
                                    offset += requiredBitsBlue - less;
                                }
                                byte_to_replace = (byte)((a << requiredBitsBlue - less) | b);
                            }


                            blue[i, j] = (byte)(maskByte(blue[i, j], requiredBitsBlue) | byte_to_replace);
                            if (isDone)
                            {
                                break;
                            }
                            #endregion

                            #region replace green pixel
                            byte_to_replace = 0;
                            if (requiredBitsGreen <= 8 - offset)
                            {
                                byte_to_replace = get_byte(offset, fileData[currentByte], requiredBitsGreen);
                                offset         += requiredBitsGreen;
                                if (offset == 8)
                                {
                                    offset = 0;
                                    ++currentByte;
                                }
                                if (currentByte == len)
                                {
                                    pixel_row          = i;
                                    pixel_column       = j;
                                    pixel_color        = 3;
                                    num_of_bits_stored = requiredBitsGreen;
                                    isDone             = true;
                                }
                            }
                            else if (requiredBitsGreen > 8 - offset)
                            {
                                less         = 8 - offset;
                                a            = get_byte(offset, fileData[currentByte], less);
                                currentByte += 1;
                                if (currentByte == len)
                                {
                                    pixel_row          = i;
                                    pixel_column       = j;
                                    pixel_color        = 3;
                                    num_of_bits_stored = less;
                                    b      = 0;
                                    isDone = true;
                                }
                                else
                                {
                                    offset  = 0;
                                    b       = get_byte(offset, fileData[currentByte], requiredBitsGreen - less);
                                    offset += requiredBitsGreen - less;
                                }
                                byte_to_replace = (byte)((a << requiredBitsGreen - less) | b);
                            }


                            green[i, j] = (byte)(maskByte(green[i, j], requiredBitsGreen) | byte_to_replace);
                            if (isDone)
                            {
                                break;
                            }
                            #endregion
                        }
                        if (isDone)
                        {
                            break;
                        }
                        j = 0;
                    }
                    byte[] numb = new byte[4], Color = new byte[4], Row = new byte[4], Col = new byte[4];
                    if (isDone)
                    {
                        Row   = BitConverter.GetBytes(pixel_row);
                        Col   = BitConverter.GetBytes(pixel_column);
                        Color = BitConverter.GetBytes(pixel_color);
                        numb  = BitConverter.GetBytes(num_of_bits_stored);
                    }
                    for (i = 0; i < 4; i++)
                    {
                        red[0, i]  = Row[i];
                        blue[0, i] = Col[i];
                    }
                    green[0, 0] = Color[0];
                    green[0, 1] = Color[1];
                    green[0, 2] = numb[0];
                    green[0, 3] = numb[1];
                    randw       = (pixel_column + 1) % (width - 1);
                    randh       = (j == 0) ? pixel_row + 1 : pixel_row;
                }
            }
            catch (Exception ex)
            {
                label4.Text = ex.Message;
            }

            if (randh != height)
            {
                j = randw;
                byte   randRed, randGreen, randBlue;
                Random rnd = new Random();
                for (i = randh; i < height; i++)
                {
                    for (; j < width; j++)
                    {
                        int requiredBitsRed, requiredBitsGreen, requiredBitsBlue;
                        requiredBitsRed   = requiredBit(red[i, j]);
                        requiredBitsGreen = requiredBit(green[i, j]);
                        requiredBitsBlue  = requiredBit(blue[i, j]);
                        randRed           = (byte)rnd.Next((int)Math.Pow(2, requiredBitsRed));
                        randBlue          = (byte)rnd.Next((int)Math.Pow(2, requiredBitsBlue));
                        randGreen         = (byte)rnd.Next((int)Math.Pow(2, requiredBitsGreen));
                        red[i, j]         = (byte)(maskByte(red[i, j], requiredBitsRed) | maskByte(randRed, requiredBitsRed));
                        blue[i, j]        = (byte)(maskByte(blue[i, j], requiredBitsBlue) | maskByte(randBlue, requiredBitsBlue));
                        green[i, j]       = (byte)(maskByte(green[i, j], requiredBitsGreen) | maskByte(randGreen, requiredBitsGreen));
                    }
                    j = 0;
                }
            }
            #endregion
            timer.Stop();
            hidetime    = timer.ElapsedMilliseconds;
            label8.Text = hidetime.ToString();
            label6.Text = (encryption + hidetime).ToString();
            MLApp.MLApp matlab = new MLApp.MLApp();
            matlab.PutWorkspaceData("red", "base", red);
            matlab.PutWorkspaceData("green", "base", green);
            matlab.PutWorkspaceData("blue", "base", blue);
            matlab.Execute("im = cat(3,red,blue,green)");
            Console.WriteLine(matlab.Execute("imwrite(im,'C:\\temp\\example\\Data\\after2222.png')"));
            label3.Text = label3.Text + "completed";
            var form = new Form2("C:\\temp\\example\\Data\\after2222.png");
            form.Show();
        }