-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOctave.cs
More file actions
554 lines (448 loc) · 17.1 KB
/
Octave.cs
File metadata and controls
554 lines (448 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
using System.Threading;
using System.IO;
using OctaveWrapper.Exceptions;
namespace OctaveWrapper
{
public class Octave
{
public const string OctaveTimeout = "Octave timeout";
private const string OctaveAns = "ans =";
public event OctaveRestartedEventHandler OctaveRestarted;
public delegate void OctaveRestartedEventHandler(object sender, EventArgs e);
private Process OctaveProcess;
private string OctaveEchoString;
private string PathToOctaveBinary;
private bool CreateWindow;
public Octave(string PathToOctaveBinary, bool CreateWindow, int timeout)
{
this.PathToOctaveBinary = PathToOctaveBinary;
StartOctave(PathToOctaveBinary, CreateWindow, timeout);
}
private void StartOctave(string PathToOctaveBinary, bool CreateWindow, int timeout)
{
this.CreateWindow = CreateWindow;
this.OctaveEchoString = Guid.NewGuid().ToString();
OctaveProcess = new Process();
// set process start info
ProcessStartInfo pi = new ProcessStartInfo();
pi.FileName = PathToOctaveBinary;
pi.RedirectStandardInput = true;
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = !CreateWindow;
pi.Verb = "open";
pi.WorkingDirectory = ".";
OctaveProcess.StartInfo = pi;
try
{
OctaveProcess.Start();
}
catch (SystemException)
{
throw new OctaveException(new IOException("binary not found"), null);
}
OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
OctaveProcess.ErrorDataReceived += new DataReceivedEventHandler(OctaveProcess_OutputErrorReceived);
OctaveProcess.BeginOutputReadLine();
OctaveProcess.BeginErrorReadLine();
string nullString = null;
OctaveEntryText = ExecuteCommand(ref nullString, timeout);
}
public void StopOctave()
{
if (!OctaveProcess.HasExited)
{
OctaveProcess.OutputDataReceived -= new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
OctaveProcess.ErrorDataReceived -= new DataReceivedEventHandler(OctaveProcess_OutputErrorReceived);
OctaveProcess.Close();
}
}
public bool HasExited()
{
return OctaveProcess.HasExited;
}
public bool GetBoolean(string varName, int timeout)
{
double res = GetScalar(varName, timeout);
if(res <= 0)
{
return false;
}
else
{
return true;
}
}
public double GetScalar(string varName, int timeout)
{
string res = ExecuteCommand(ref varName, timeout);
string val = res.Substring(res.LastIndexOf("=") + 1).Trim().Replace(".", ",");
return double.Parse(val);
}
public void GetColumnVector(string varName, int timeout, out double[] returnVector)
{
string res = ExecuteCommand(ref varName, timeout);
string[] lines = res.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
List<double> data = new List<double>(new double[lines.Length]);
if (data.Count > 0)
{
// the first element in "lines" is the variable name
for (int m = 0; m < lines.Length; m++)
{
string[] dataS = lines[m].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
for (int k = 0; k < dataS.Length; k++)
{
data[m] = double.Parse(dataS[k].ToString().Replace(".", ","));
}
}
}
returnVector = data.ToArray();
}
public void GetMatrix(string varName, int timeout, out double[][] returnMatrix)
{
string matrixParameter = varName + "(1,:)";
string res = ExecuteCommand(ref matrixParameter, timeout); // get columns
string[] lines = res.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
returnMatrix = new double[lines.Length][];
for (int i = 0; i < returnMatrix.Length; i++)
{
GetColumnVector(varName + "(:, " + (i + 1) + ")", timeout, out returnMatrix[i]);
}
}
StringBuilder SharedBuilder = new StringBuilder();
ManualResetEvent OctaveDoneEvent = new ManualResetEvent(false);
public string OctaveEntryText { get; internal set; }
public void WorkThread(object o)
{
string command = (string)o;
SharedBuilder.Clear();
OctaveDoneEvent.Reset();
if (command != null)
{
OctaveProcess.StandardInput.WriteLine(command);
}
OctaveProcess.StandardInput.WriteLine("\"" + OctaveEchoString + "\"");
OctaveDoneEvent.WaitOne();
}
public string ExecuteCommand(ref string command, int timeout)
{
if (OctaveProcess.HasExited)
{
StartOctave(this.PathToOctaveBinary, this.CreateWindow, timeout);
if (OctaveRestarted != null)
OctaveRestarted(this, EventArgs.Empty);
}
exitError = false;
Thread thread = new Thread(new ParameterizedThreadStart(WorkThread));
thread.Priority = ThreadPriority.Highest;
thread.SetApartmentState(ApartmentState.MTA);
thread.Start(command);
#if DEBUG
System.DateTime beforeTime = DateTime.Now;
#endif
if(timeout >= 0)
{
if (!thread.Join(timeout))
{
thread.Abort();
throw new OctaveException(OctaveTimeout);
}
}
else
{
thread.Join();
}
if (exitError)
{
throw new OctaveException(SharedBuilder.ToString());
}
#if DEBUG
System.Diagnostics.Debug.Write("Octave duration: " + DateTime.Now.Subtract(beforeTime).TotalSeconds + " s");
#endif
return SharedBuilder.ToString();
}
public string ExecuteCommandWithErrorCheck(ref string command, int timeout)
{
string temp = ExecuteCommand(ref command, timeout);
if (temp.Contains("error"))
return temp;
else
return null;
}
public Tuple<string, int> ExecuteCommands(string[] commands, int timeout)
{
if (commands == null || commands.Length == 0)
return new Tuple<string, int>("No commands available", -1);
string temp;
for (int i = 0; i < commands.Length; i++)
{
temp = ExecuteCommandWithErrorCheck(ref commands[i], timeout);
if (String.IsNullOrEmpty(temp))
return new Tuple<string, int>(temp, i);
}
return null;
}
public string ExecuteFile(ref string command, string filePath, int timeout)
{
if (OctaveProcess.HasExited)
{
StartOctave(this.PathToOctaveBinary, this.CreateWindow, timeout);
if (OctaveRestarted != null)
OctaveRestarted(this, EventArgs.Empty);
}
exitError = false;
Thread thread = new Thread(new ParameterizedThreadStart(WorkThread));
thread.Priority = ThreadPriority.Highest;
thread.SetApartmentState(ApartmentState.MTA);
string newCommand = "load(" + filePath.Replace("\\", "\\\\") + "); " + command;
thread.Start(newCommand);
if (timeout >= 0)
{
if (!thread.Join(timeout))
{
thread.Abort();
throw new OctaveException(OctaveTimeout);
}
}
else
{
thread.Join();
}
if (exitError)
{
throw new OctaveException(SharedBuilder.ToString());
}
return SharedBuilder.ToString();
}
bool exitError = false;
void OctaveProcess_OutputErrorReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
return;
} else
{
SharedBuilder.Append(e.Data + "\r\n");
OctaveDoneEvent.Set();
}
}
void OctaveProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
return;
}
if (e.Data.Trim() == OctaveAns + " " + OctaveEchoString)
OctaveDoneEvent.Set();
else
{
if (e.Data == OctaveAns)
return;
else if (e.Data.Contains(OctaveAns))
{
SharedBuilder.Append(e.Data.Replace(OctaveAns, ""));
return;
}
else if (String.IsNullOrWhiteSpace(e.Data))
{
return;
}
SharedBuilder.Append(e.Data + "\r\n");
}
}
public string SetBoolean(string varName, bool boolean, int timeout)
{
string parameter = varName + " = " + boolean + ";";
return ExecuteCommand(ref parameter, timeout);
}
public string SetScalar(string varName, double scalar, int timeout)
{
string parameter = varName + " = " + scalar.ToString().Replace(",", ".") + ";";
return ExecuteCommand(ref parameter, timeout);
}
public string SetScalar(string varName, string scalar, int timeout)
{
string parameter = varName + " = " + scalar.Replace(",", ".") + ";";
return ExecuteCommand(ref parameter, timeout);
}
public string SetColumnVector(string varName, ref double[] vector, int timeout)
{
string data = "";
CreateVector(ref vector, true, out data);
string parameter = varName + " = " + data + ";";
data = null;
return ExecuteCommand(ref parameter, timeout);
}
public string SetColumnVector(string varName, ref string[] vector, int timeout)
{
string data;
CreateVector(ref vector, true, out data);
string parameter = varName + " = " + data + ";";
data = null;
return ExecuteCommand(ref parameter, timeout);
}
public string SetRowVector(string varName, ref double[] vector, int timeout)
{
string data;
CreateVector(ref vector, false, out data);
string parameter = varName + " = " + data + ";";
data = null;
return ExecuteCommand(ref parameter, timeout);
}
public string SetRowVector(string varName, ref string[] vector, int timeout)
{
string data;
CreateVector(ref vector, false, out data);
string parameter = varName + " = " + data + ";";
data = null;
return ExecuteCommand(ref parameter, timeout);
}
public string SetMatrix(string varName, ref double[][] matrix, int timeout)
{
StringBuilder command = new StringBuilder();
command.Append(varName + " = [");
string lineSign = ";";
string columnSign = ",";
for (int i = 0; i < matrix.Length; i++)
{
for (int n = 0; n < matrix[i].Length; n++)
{
command.Append(matrix[i][n].ToString().Replace(",", "."));
if (n != (matrix[i].Length - 1))
{
command.Append(columnSign);
}
}
if (i != (matrix.Length - 1))
{
command.Append(lineSign);
}
}
command.Append("];");
string stringCommand = command.ToString();
return ExecuteCommand(ref stringCommand, timeout);
}
public string SetMatrix(string varName, ref string[][] matrix, int timeout)
{
StringBuilder command = new StringBuilder();
command.Append(varName + " = [");
string lineSign = ";";
string columnSign = ",";
for (int i = 0; i < matrix.Length; i++)
{
for (int n = 0; n < matrix[i].Length; n++)
{
command.Append(matrix[i][n].Replace(",", "."));
if (n != (matrix[i].Length - 1))
{
command.Append(columnSign);
}
}
if (i != (matrix.Length - 1))
{
command.Append(lineSign);
}
}
command.Append("];");
string stringCommand = command.ToString();
return ExecuteCommand(ref stringCommand, timeout);
}
public string SetString(string varName, string stringValue, int timeout)
{
string parameter = varName + " = \"" + stringValue + "\";";
return ExecuteCommand(ref parameter, timeout);
}
public void ClearAllVariables(int timeout)
{
string parameter = "clear";
ExecuteCommand(ref parameter, timeout);
}
private void CreateVector(ref double[] vector, bool isColumnVector, out string data)
{
string sign;
if (isColumnVector)
sign = ";";
else
sign = ",";
StringBuilder command = new StringBuilder();
command.Append("[");
for (int i = 0; i < vector.Length; i++)
{
command.Append(vector[i].ToString().Replace(",", "."));
if (i != (vector.Length - 1))
{
command.Append(sign);
}
}
command.Append("]");
data = command.ToString();
}
private void CreateVector(ref string[] vector, bool isColumnVector, out string data)
{
string sign;
if (isColumnVector)
sign = ";";
else
sign = ",";
StringBuilder command = new StringBuilder();
command.Append("[");
for (int i = 0; i < vector.Length; i++)
{
if (vector[i] != null)
{
command.Append(vector[i].Replace(",", "."));
if (i != (vector.Length - 1))
{
command.Append(sign);
}
}
}
command.Append("]");
data = command.ToString();
}
//https://www.gnu.org/software/octave/doc/interpreter/Predicates-for-Numeric-Objects.html#XREFisscalar
//https://www.gnu.org/software/octave/doc/interpreter/Object-Sizes.html#Object-Sizes
[Flags]
public enum ResultTypes
{
None = 0x01,
Scalar = 0x02,
Vector = 0x04,
Matrix = 0x08
}
public ResultTypes GetResultType(string variableName, int timeout)
{
string resultVariable = "own_matlab_octave_result_variable";
string parameter = resultVariable + " = " + "isscalar(" + variableName + ")";
ExecuteCommand(ref parameter, timeout);
if(GetBoolean(resultVariable, timeout))
{
return ResultTypes.Scalar;
}
parameter = resultVariable + " = " + "ismatrix(" + variableName + ")";
ExecuteCommand(ref parameter, timeout);
if(GetBoolean(resultVariable, timeout))
{
parameter = resultVariable + " = " + "columns(" + variableName + ")";
ExecuteCommand(ref parameter, timeout);
int columns = (int) GetScalar(resultVariable, timeout);
if(columns == 1)
{
return ResultTypes.Vector;
}
else if(columns > 1)
{
return ResultTypes.Matrix;
}
}
return ResultTypes.None;
}
}
}