Click here to Skip to main content
15,880,796 members
Articles / Programming Languages / C#

OctaveSharp - Running GNU Octave with C#

Rate me:
Please Sign up or sign in to vote.
4.97/5 (15 votes)
10 Apr 2012CPOL2 min read 88.2K   2.1K   35   29
OctaveSharp wrapper for using Octave in C# applications

Introduction  

“GNU Octave is a high-level interpreted language, primarily intended for numerical computations. It provides capabilities for the numerical solution of linear and nonlinear problems, and for performing other numerical experiments. It also provides extensive graphics capabilities for data visualization and manipulation. Octave is normally used through its interactive command line interface, but it can also be used to write non-interactive programs. The Octave language is quite similar to Matlab so that most programs are easily portable.

Octave is distributed under the terms of the GNU General Public License. “

Image 1

(Text and image above belong to http://www.gnu.org/software/octave/)

Recently I had to use some Octave scripts within a C# project I’m currently working on. After searching for a solution I had to implement my own Octave wrapper.

Image 2

The basic idea is to start a process and redirect the standard input, output and error streams in order to execute random commands with the Octave interpreter. One common problem is that after successfully running a command, the interpreter blocks the output stream and there is no way to know when Octave finished its job. A solution to this problem is as follows: given the fact that the last line in the execution of the process is always available you can create a random string and make Octave echo this string every time you run another command; when parsing the output, an indication that the previous command is surly executed is when you encounter your echoed string.

Implementation

When starting the octave process a new random echo string is generated:

C#
private string StartOctave(string PathToOctaveBinaries, bool CreateWindow) {
      this.OctaveEchoString = Guid.NewGuid().ToString();
      OctaveProcess = new Process();
      .
      .
      .
      OctaveProcess.OutputDataReceived +=
           new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
      OctaveProcess.BeginOutputReadLine();
      OctaveEntryText = ExecuteCommand(null);
 }  

When executing a random command the current thread blocks until a ManualResetEvent is triggered:

C#
public string ExecuteCommand(string command) {
    if (OctaveProcess.HasExited)
        OctaveProcess.Start();
    SharedBuilder.Clear();
    if (command != null) {
        OctaveProcess.StandardInput.WriteLine(command);
    }
    //echo the random GUID string
    OctaveProcess.StandardInput.WriteLine("\""+ OctaveEchoString + "\"");
    OctaveDoneEvent.Reset();
    OctaveDoneEvent.WaitOne();
    return SharedBuilder.ToString();
}

And the asynchronous output data received puts all data in a StringBuilder until it comes across the echoed string.

C#
void OctaveProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) {
           if (e.Data == null) {
               SharedBuilder.Clear();
               SharedBuilder.Append("Octave has exited with the following error message: \r\n" + OctaveProcess.StandardError.ReadToEnd());
               OctaveDoneEvent.Set();
               return;
           }
           if (e.Data.Trim() == "ans = " + OctaveEchoString)
               OctaveDoneEvent.Set();
           else
               SharedBuilder.Append(e.Data + "\r\n");
       }

Using the code

Just create a new Octave class instance using one of the two constructors and pass on the full path to your octave installation.

After doing so, you can access the Octave command interpreter using the “ExecuteCommand” method. Reading results is done in the form of scalars(GetScalar), vectors(GetVector) and matrices(GetMatrix).

A simple script that calculates the transpose of a matrix is given below:

C#
octave = new Octave(@"D:\Download\Soft\Octave3.6.0_gcc4.6.2\bin", false);
octave.ExecuteCommand("a=[1,2;3,4];");
octave.ExecuteCommand("result=a';");
double[][] m = octave.GetMatrix("result");

Hope this helps and if you use any of this work make sure to add a reference: Boros Tiberiu, OctaveSharp - running GNU Octave with C#, CodeProject, 2012

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Research Institute For Artificial Intelligence, Ro
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionManipulating Graph Windows Pin
Member 148724342-Jan-23 3:29
Member 148724342-Jan-23 3:29 
SuggestionNumber Formats Pin
Member 128575018-Jun-17 1:54
Member 128575018-Jun-17 1:54 
QuestionActual version for Octave 4.2.0 Pin
Member 1297366131-Jan-17 23:06
Member 1297366131-Jan-17 23:06 
QuestionOctave 4.0.0 compatibility Pin
format C: /U8-Sep-15 10:44
format C: /U8-Sep-15 10:44 
GeneralThanks! Pin
Paul Schlachter1-Aug-15 4:11
Paul Schlachter1-Aug-15 4:11 
QuestionImage processing package functions call Pin
Member 1043647927-Jan-15 2:43
Member 1043647927-Jan-15 2:43 
QuestionProblem with ProcessStart Arguments Pin
masamafaxen6-Jan-15 23:32
masamafaxen6-Jan-15 23:32 
QuestionFor complex value? Pin
Member 103291491-Dec-14 20:20
Member 103291491-Dec-14 20:20 
QuestionCode isn't working Pin
Member 110564963-Sep-14 10:01
Member 110564963-Sep-14 10:01 
QuestionUsing built-in libraries Pin
Member 1090395025-Jul-14 11:55
Member 1090395025-Jul-14 11:55 
QuestionFunctions work with cd Pin
Member 1090395030-Jun-14 0:12
Member 1090395030-Jun-14 0:12 
Hi!

As you may already know, ExecuteCommand with "cd" works fine to point out a suitable directory containing the m-files.
My question regarding the inline definition is therefore not as urgent, but I would love a cooperation on this - I believe this is a very interesting project with the Data Science area growing rapidly and all!

Joakim Gåfvels
QuestionFunctions Pin
Member 1090395029-Jun-14 23:37
Member 1090395029-Jun-14 23:37 
AnswerRe: Functions Pin
Member 1095056216-Jul-14 2:45
Member 1095056216-Jul-14 2:45 
GeneralRe: Functions Pin
Member 1090395023-Jul-14 4:57
Member 1090395023-Jul-14 4:57 
SuggestionAbout the exit on error... Pin
Brisingr Aerowing7-Aug-13 8:04
professionalBrisingr Aerowing7-Aug-13 8:04 
GeneralRe: About the exit on error... Pin
MrButtle6-Oct-13 5:17
MrButtle6-Oct-13 5:17 
GeneralRe: About the exit on error... Pin
Brisingr Aerowing6-Oct-13 15:59
professionalBrisingr Aerowing6-Oct-13 15:59 
QuestionTutorial of implementation Pin
bukowski317-Jun-13 4:07
bukowski317-Jun-13 4:07 
QuestionOctaveSharp for ASP.NET Pin
Gerd Schluckebier1-Nov-12 1:26
Gerd Schluckebier1-Nov-12 1:26 
AnswerRe: OctaveSharp for ASP.NET Pin
Tiberiu Boros6-Nov-12 11:00
Tiberiu Boros6-Nov-12 11:00 
QuestionOctaveSharp Pin
CVision4-Sep-12 4:03
CVision4-Sep-12 4:03 
AnswerRe: OctaveSharp Pin
Tiberiu Boros4-Sep-12 8:12
Tiberiu Boros4-Sep-12 8:12 
QuestionGetVector errors Pin
Member 76977543-Apr-12 22:13
Member 76977543-Apr-12 22:13 
AnswerRe: GetVector errors Pin
Tiberiu Boros10-Apr-12 9:51
Tiberiu Boros10-Apr-12 9:51 
QuestionPlot 3D Pin
Member 874500820-Mar-12 1:32
Member 874500820-Mar-12 1:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.