Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/interfaces/scilab.py
4056 views
1
r"""
2
Interface to Scilab
3
4
Scilab is a scientific software package for numerical computations
5
providing a powerful open computing environment for engineering and
6
scientific applications. Scilab includes hundreds of mathematical
7
functions with the possibility to add interactively programs from
8
various languages (C, C++, Fortran...). It has sophisticated data
9
structures (including lists, polynomials, rational functions, linear
10
systems...), an interpreter and a high level programming language.
11
12
The commands in this section only work if you have the "scilab"
13
interpreter installed and available in your PATH. It's not necessary
14
to install any special Sage packages.
15
16
EXAMPLES::
17
18
sage: scilab.eval('2+2') # optional - scilab
19
'ans =\n \n 4.'
20
sage: scilab('2+2') # optional - scilab
21
4.
22
sage: a = scilab(10) # optional - scilab
23
sage: a**10 # optional - scilab
24
1.000D+10
25
26
Tutorial based the MATLAB interface tutorial:
27
28
EXAMPLES::
29
30
sage: scilab('4+10') # optional - scilab
31
14.
32
sage: scilab('date') # optional - scilab; random output
33
15-Feb-2010
34
sage: scilab('5*10 + 6') # optional - scilab
35
56.
36
sage: scilab('(6+6)/3') # optional - scilab
37
4.
38
sage: scilab('9')^2 # optional - scilab
39
81.
40
sage: a = scilab(10); b = scilab(20); c = scilab(30) # optional - scilab
41
sage: avg = (a+b+c)/3 # optional - scilab
42
sage: avg # optional - scilab
43
20.
44
sage: parent(avg) # optional - scilab
45
Scilab
46
47
sage: my_scalar = scilab('3.1415') # optional - scilab
48
sage: my_scalar # optional - scilab
49
3.1415
50
sage: my_vector1 = scilab('[1,5,7]') # optional - scilab
51
sage: my_vector1 # optional - scilab
52
1. 5. 7.
53
sage: my_vector2 = scilab('[1;5;7]') # optional - scilab
54
sage: my_vector2 # optional - scilab
55
1.
56
5.
57
7.
58
sage: my_vector1 * my_vector2 # optional - scilab
59
75.
60
61
sage: row_vector1 = scilab('[1 2 3]') # optional - scilab
62
sage: row_vector2 = scilab('[3 2 1]') # optional - scilab
63
sage: matrix_from_row_vec = scilab('[%s; %s]'%(row_vector1.name(), row_vector2.name())) # optional - scilab
64
sage: matrix_from_row_vec # optional - scilab
65
1. 2. 3.
66
3. 2. 1.
67
68
sage: column_vector1 = scilab('[1;3]') # optional - scilab
69
sage: column_vector2 = scilab('[2;8]') # optional - scilab
70
sage: matrix_from_col_vec = scilab('[%s %s]'%(column_vector1.name(), column_vector2.name())) # optional - scilab
71
sage: matrix_from_col_vec # optional - scilab
72
1. 2.
73
3. 8.
74
75
sage: my_matrix = scilab('[8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1]') # optional - scilab
76
sage: my_matrix # optional - scilab
77
8. 12. 19.
78
7. 3. 2.
79
12. 4. 23.
80
8. 1. 1.
81
82
sage: combined_matrix = scilab('[%s, %s]'%(my_matrix.name(), my_matrix.name())) # optional - scilab
83
sage: combined_matrix # optional - scilab
84
8. 12. 19. 8. 12. 19.
85
7. 3. 2. 7. 3. 2.
86
12. 4. 23. 12. 4. 23.
87
8. 1. 1. 8. 1. 1.
88
89
sage: tm = scilab('0.5:2:10') # optional - scilab
90
sage: tm # optional - scilab
91
0.5 2.5 4.5 6.5 8.5
92
93
sage: my_vector1 = scilab('[1,5,7]') # optional - scilab
94
sage: my_vector1(1) # optional - scilab
95
1.
96
sage: my_vector1(2) # optional - scilab
97
5.
98
sage: my_vector1(3) # optional - scilab
99
7.
100
101
Matrix indexing works as follows::
102
103
sage: my_matrix = scilab('[8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1]') # optional - scilab
104
sage: my_matrix(3,2) # optional - scilab
105
4.
106
107
One can also use square brackets::
108
109
sage: my_matrix[3,2] # optional - scilab
110
4.
111
112
113
Setting using parenthesis cannot work (because of how the Python
114
language works). Use square brackets or the set function::
115
116
sage: my_matrix = scilab('[8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1]') # optional - scilab
117
sage: my_matrix.set(2,3, 1999) # optional - scilab
118
sage: my_matrix # optional - scilab
119
8. 12. 19.
120
7. 3. 1999.
121
12. 4. 23.
122
8. 1. 1.
123
sage: my_matrix[2,3] = -126 # optional - scilab
124
sage: my_matrix # optional - scilab
125
8. 12. 19.
126
7. 3. - 126.
127
12. 4. 23.
128
8. 1. 1.
129
130
TESTS::
131
132
sage: M = scilab(x) # optional - scilab
133
Traceback (most recent call last):
134
...
135
TypeError: _interface_init_() takes exactly one argument (0 given)
136
sage: M = scilab(matrix(3,range(9))); M # optional - scilab
137
0. 1. 2.
138
3. 4. 5.
139
6. 7. 8.
140
sage: M(10) # optional - scilab
141
Traceback (most recent call last):
142
...
143
TypeError: Error executing code in Scilab
144
...
145
Invalid index.
146
sage: M[10] # optional - scilab
147
Traceback (most recent call last):
148
...
149
TypeError: Error executing code in Scilab
150
...
151
Invalid index.
152
sage: M(4,2) # optional - scilab
153
Traceback (most recent call last):
154
...
155
TypeError: Error executing code in Scilab
156
...
157
Invalid index.
158
sage: M[2,4] # optional - scilab
159
Traceback (most recent call last):
160
...
161
TypeError: Error executing code in Scilab
162
...
163
Invalid index.
164
sage: M(9) = x # optional - scilab
165
Traceback (most recent call last):
166
...
167
SyntaxError: can't assign to function call (..., line 1)
168
169
AUTHORS:
170
171
-- Ronan Paixao (2008-11-26), based on the MATLAB tutorial by
172
William Stein (2006-10-11)
173
"""
174
##############################################################################
175
# Copyright (C) 2006 William Stein <[email protected]>
176
# Copyright (C) 2008 Ronan Paixao <[email protected]>
177
#
178
# Distributed under the terms of the GNU General Public License (GPL).
179
#
180
# This code is distributed in the hope that it will be useful,
181
# but WITHOUT ANY WARRANTY; without even the implied warranty of
182
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
183
# General Public License for more details.
184
#
185
# The full text of the GPL is available at:
186
#
187
# http://www.gnu.org/licenses/
188
##############################################################################
189
190
import os
191
192
from expect import Expect, ExpectElement
193
194
195
class Scilab(Expect):
196
"""
197
Interface to the Scilab interpreter.
198
199
EXAMPLES:
200
sage: a = scilab('[ 1, 1, 2; 3, 5, 8; 13, 21, 33 ]') # optional - scilab
201
sage: b = scilab('[ 1; 3; 13]') # optional - scilab
202
sage: c = a * b # optional - scilab
203
sage: print c # optional - scilab
204
30.
205
122.
206
505.
207
"""
208
def __init__(self, maxread=100, script_subdirectory="",
209
logfile=None, server=None,server_tmpdir=None):
210
"""
211
Initializes the Scilab class.
212
213
EXAMPLES:
214
sage: from sage.interfaces.scilab import Scilab
215
sage: sci_obj = Scilab(script_subdirectory='user') # optional - scilab
216
sage: del sci_obj # optional - scilab
217
"""
218
Expect.__init__(self,
219
name = 'scilab',
220
prompt = '-->',
221
command = "scilab -nogui",
222
maxread = maxread,
223
server = server,
224
server_tmpdir = server_tmpdir,
225
script_subdirectory = script_subdirectory,
226
restart_on_ctrlc = False,
227
verbose_start = False,
228
logfile = logfile,
229
eval_using_file_cutoff=100)
230
231
def _quit_string(self):
232
"""
233
Returns the string used to quit the pexpect interface.
234
235
EXAMPLES:
236
sage: scilab._quit_string() # optional - scilab
237
'quit;'
238
"""
239
return 'quit;'
240
241
def _install_hints(self):
242
"""
243
Hints for installing Scilab.
244
245
EXAMPLES:
246
sage: print scilab._install_hints() # optional - scilab
247
You must ...
248
"""
249
return """
250
You must obtain the Scilab program in order to use Scilab
251
from Sage. You can read all about Scilab at
252
http://www.scilab.org/
253
The executable must be accessible system-wide.
254
"""
255
256
def _start(self):
257
"""
258
Starts Scilab and sets some options.
259
260
EXAMPLES:
261
sage: scilab._start() # optional - scilab
262
"""
263
Expect._start(self)
264
self.eval("mode(0)")
265
266
def eval(self, command, *args, **kwds):
267
"""
268
Evaluates commands.
269
270
EXAMPLES:
271
sage: scilab.eval("5") # optional - scilab
272
'ans =\n \n 5.'
273
sage: scilab.eval("d=44") # optional - scilab
274
'd =\n \n 44.'
275
"""
276
s = Expect.eval(self, command, **kwds).replace("\x1b[?1l\x1b>","").strip()
277
return s
278
279
def whos(self, name=None, typ=None):
280
"""
281
Returns information about current objects.
282
Arguments:
283
nam: first characters of selected names
284
typ: name of selected Scilab variable type
285
286
EXAMPLES:
287
sage: scilab.whos("core") # optional - scilab
288
'Name Type Size Bytes...'
289
sage: scilab.whos(typ='function') # optional - scilab
290
'Name Type Size Bytes...'
291
"""
292
parameters = ""
293
if name:
294
parameters += " -name %s" % (str(name))
295
if typ:
296
parameters += " -type %s" % (str(typ))
297
return self.eval('whos' + parameters)
298
299
def set(self, var, value):
300
"""
301
Set the variable var to the given value.
302
303
EXAMPLES:
304
sage: scilab.set('a', 123) # optional - scilab
305
sage: scilab.get('a') # optional - scilab
306
'\n \n 123.'
307
"""
308
cmd = '%s=%s;'%(var,value)
309
out = self.eval(cmd)
310
if out.find("error") != -1:
311
raise TypeError, "Error executing code in Scilab\nCODE:\n\t%s\nScilab ERROR:\n\t%s"%(cmd, out)
312
313
def get(self, var):
314
"""
315
Get the value of the variable var.
316
317
EXAMPLES:
318
sage: scilab.eval('b=124;') # optional - scilab
319
''
320
sage: scilab.get('b') # optional - scilab
321
'\n \n 124.'
322
"""
323
s = self.eval('%s'%var)
324
i = s.find('=')
325
return s[i+1:]
326
327
def console(self):
328
"""
329
Starts Scilab console.
330
331
EXAMPLES:
332
sage: scilab.console() # optional - scilab and not tested
333
334
"""
335
scilab_console()
336
337
def version(self):
338
"""
339
Returns the version of the Scilab software used.
340
341
EXAMPLES:
342
sage: scilab.version() # optional - scilab
343
'scilab-...'
344
"""
345
return scilab_version()
346
347
def sage2scilab_matrix_string(self, A):
348
"""
349
Return a Scilab matrix from a Sage matrix.
350
351
INPUT:
352
A Sage matrix with entries in the rationals or reals.
353
354
OUTPUT:
355
A string that evaluates to an Scilab matrix.
356
357
EXAMPLES:
358
sage: M33 = MatrixSpace(QQ,3,3) # optional - scilab
359
sage: A = M33([1,2,3,4,5,6,7,8,0]) # optional - scilab
360
sage: scilab.sage2scilab_matrix_string(A) # optional - scilab
361
'[1, 2, 3; 4, 5, 6; 7, 8, 0]'
362
363
"""
364
return str(A.rows()).replace('), (', '; ').replace('(', '').replace(')','')
365
366
def _object_class(self):
367
"""
368
Returns the class of the object.
369
370
EXAMPLES:
371
sage: scilab._object_class() # optional - scilab
372
<class 'sage.interfaces.scilab.ScilabElement'>
373
sage: type(scilab(2)) # optional - scilab
374
<class 'sage.interfaces.scilab.ScilabElement'>
375
"""
376
return ScilabElement
377
378
379
class ScilabElement(ExpectElement):
380
def __getitem__(self, n):
381
"""
382
Use parenthesis for Scilab matrices instead.
383
384
EXAMPLES:
385
sage: M = scilab('[1,2,3;4,5,6;7,8,9]') # optional - scilab
386
sage: M[1] # optional - scilab
387
1.
388
sage: M[7] # optional - scilab
389
3.
390
sage: M[3,2] # optional - scilab
391
8.
392
"""
393
if isinstance(n, tuple):
394
index = str(n)[1:-1]
395
else:
396
index = str(n)
397
return self.parent()('%s(%s)' % (self._name, index))
398
399
def __setitem__(self, n, value):
400
"""
401
Sets an element of a matrix.
402
403
EXAMPLES:
404
sage: M = scilab('[1,2,3;4,5,6;7,8,9]') # optional - scilab
405
sage: M[6] = 0 # optional - scilab
406
sage: M # optional - scilab
407
1. 2. 3.
408
4. 5. 6.
409
7. 0. 9.
410
sage: M[3,2] = 10 # optional - scilab
411
sage: M # optional - scilab
412
1. 2. 3.
413
4. 5. 6.
414
7. 10. 9.
415
"""
416
if isinstance(n, tuple):
417
index = str(n)[1:-1]
418
else:
419
index = str(n)
420
self.parent().eval('%s(%s) = %s' % (self._name, index, value))
421
422
def _matrix_(self, R):
423
r"""
424
Return \sage matrix from this scilab element.
425
426
EXAMPLES:
427
sage: A = scilab('[1,2;3,4]') # optional - scilab
428
sage: matrix(ZZ, A) # optional - scilab
429
[1 2]
430
[3 4]
431
sage: A = scilab('[1,2;3,4.5]') # optional - scilab
432
sage: matrix(RR, A) # optional - scilab
433
[1.00000000000000 2.00000000000000]
434
[3.00000000000000 4.50000000000000]
435
"""
436
from sage.matrix.all import MatrixSpace
437
from sage.rings.all import ZZ
438
s = str(self).strip()
439
v = s.split('\n ')
440
nrows = len(v)
441
if nrows == 0:
442
return MatrixSpace(R,0,0)(0)
443
ncols = len(v[0].split())
444
M = MatrixSpace(R, nrows, ncols)
445
v = sum([[x.rstrip('.') for x in w.split()] for w in v], [])
446
return M(v)
447
448
def set(self, i, j, x):
449
"""
450
Set the variable var to the given value.
451
452
EXAMPLES:
453
sage: scilab.set('c', 125) # optional - scilab
454
sage: scilab.get('c') # optional - scilab
455
'\n \n 125.'
456
"""
457
P = self._check_valid()
458
z = P(x)
459
P.eval('%s(%s,%s) = %s'%(self.name(), i, j, z.name()))
460
461
# An instance
462
scilab = Scilab(script_subdirectory='user')
463
464
465
466
import os
467
def scilab_console():
468
"""
469
This requires that the optional Scilab program be installed and in
470
your PATH, but no optional Sage packages need to be installed.
471
472
EXAMPLES:
473
sage: from sage.interfaces.scilab import scilab_console # optional - scilab
474
sage: scilab_console() # optional - scilab and not tested
475
___________________________________________
476
scilab-5.0.3
477
478
Consortium Scilab (DIGITEO)
479
Copyright (c) 1989-2008 (INRIA)
480
Copyright (c) 1989-2007 (ENPC)
481
___________________________________________
482
483
484
Startup execution:
485
loading initial environment
486
487
-->2+3
488
ans =
489
490
5.
491
492
-->quit
493
494
Typing quit exits the Scilab console and returns you to Sage.
495
Scilab, like Sage, remembers its history from one session to
496
another.
497
"""
498
os.system('scilab -nogui')
499
500
501
def scilab_version():
502
"""
503
Return the version of Scilab installed.
504
505
EXAMPLES:
506
sage: from sage.interfaces.scilab import scilab_version # optional - scilab
507
sage: scilab_version() # optional - scilab
508
'scilab-...'
509
"""
510
return str(scilab('getversion()')).strip()
511
512
513