This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
fricas.py
2132 lines (1699 loc) · 80.3 KB
/
fricas.py
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Interface to FriCAS
.. TODO::
- some conversions in ``sage.functions`` are still missing and
all should be checked and tested
FriCAS is a free GPL-compatible (modified BSD license) general
purpose computer algebra system based on Axiom. The FriCAS
website can be found at http://fricas.sourceforge.net/.
AUTHORS:
- Mike Hansen (2009-02): Split off the FriCAS interface from
the Axiom interface.
- Martin Rubey, Bill Page (2016-08): Completely separate from Axiom,
implement more complete translation from FriCAS to SageMath types.
EXAMPLES::
sage: fricas('3 * 5') # optional - fricas
15
sage: a = fricas(3) * fricas(5); a # optional - fricas
15
The type of a is :class:`FriCASElement`, i.e., an element of the
FriCAS interpreter::
sage: type(a) # optional - fricas
<class 'sage.interfaces.fricas.FriCASElement'>
sage: a.parent() # optional - fricas
FriCAS
The underlying FriCAS type of a is also available, via the type
method::
sage: a.typeOf() # optional - fricas
PositiveInteger
FriCAS objects are normally displayed using "ASCII art"::
sage: fricas(2/3) # optional - fricas
2
-
3
sage: fricas('x^2 + 3/7') # optional - fricas
2 3
x + -
7
Functions defined in FriCAS are available as methods of the :class:`fricas<FriCAS>` object::
sage: F = fricas.factor('x^5 - y^5'); F # optional - fricas
4 3 2 2 3 4
- (y - x)(y + x y + x y + x y + x )
sage: type(F) # optional - fricas
<class 'sage.interfaces.fricas.FriCASElement'>
sage: F.typeOf() # optional - fricas
Factored(Polynomial(Integer))
We can also create a FriCAS polynomial and apply the function
``factor`` from FriCAS. The notation ``f.factor()`` is consistent
with how the rest of SageMath works::
sage: f = fricas('x^5 - y^5') # optional - fricas
sage: f^2 # optional - fricas
10 5 5 10
y - 2 x y + x
sage: f.factor() # optional - fricas
4 3 2 2 3 4
- (y - x)(y + x y + x y + x y + x )
For many FriCAS types, translation to an appropriate SageMath type is
available::
sage: f.factor().sage() # optional - fricas
(y - x) * (y^4 + y^3*x + y^2*x^2 + y*x^3 + x^4)
Control-C interruption works well with the FriCAS interface. For
example, try the following sum but with a much bigger range, and hit
control-C::
sage: f = fricas('(x^5 - y^5)^10000') # not tested - fricas
Interrupting FriCAS...
...
KeyboardInterrupt: Ctrl-c pressed while running FriCAS
Let us demonstrate some features of FriCAS. FriCAS can guess a
differential equation for the generating function for integer
partitions::
sage: fricas("guessADE([partition n for n in 0..40], homogeneous==4)") # optional - fricas
[
[
n
[x ]f(x):
2 3 (iv) 2 2 , 3 ,,,
x f(x) f (x) + (20 x f(x) f (x) + 5 x f(x) )f (x)
<BLANKLINE>
+
2 2 ,, 2
- 39 x f(x) f (x)
<BLANKLINE>
+
2 , 2 2 , 3 ,, 2 , 4
(12 x f(x)f (x) - 15 x f(x) f (x) + 4 f(x) )f (x) + 6 x f (x)
<BLANKLINE>
+
, 3 2 , 2
10 x f(x)f (x) - 16 f(x) f (x)
<BLANKLINE>
=
0
,
2 3 4
f(x) = 1 + x + 2 x + 3 x + O(x )]
]
FriCAS can solve linear ordinary differential equations::
sage: fricas.set("y", "operator y") # optional - fricas
sage: fricas.set("deq", "x^3*D(y x, x, 3) + x^2*D(y x, x, 2) - 2*x*D(y x, x) + 2*y x - 2*x^4") # optional - fricas
sage: fricas.set("sol", "solve(deq, y, x)"); fricas("sol") # optional - fricas
5 3 2
x - 10 x + 20 x + 4
[particular = ----------------------,
15 x
3 2 3 3 2
2 x - 3 x + 1 x - 1 x - 3 x - 1
basis = [---------------, ------, -------------]]
x x x
sage: fricas("sol.particular").sage() # optional - fricas
1/15*(x^5 - 10*x^3 + 20*x^2 + 4)/x
sage: fricas("sol.basis").sage() # optional - fricas
[(2*x^3 - 3*x^2 + 1)/x, (x^3 - 1)/x, (x^3 - 3*x^2 - 1)/x]
sage: fricas.eval(")clear values y deq sol") # optional - fricas
''
FriCAS can expand expressions into series::
sage: x = var('x'); ex = sqrt(cos(x)); a = fricas(ex).series(x=0); a # optional - fricas
1 2 1 4 19 6 559 8 29161 10 11
1 - - x - -- x - ---- x - ------ x - --------- x + O(x )
4 96 5760 645120 116121600
sage: a.coefficients()[38].sage() # optional - fricas
-29472026335337227150423659490832640468979/274214482066329363682430667508979749984665600000000
sage: ex = sqrt(atan(x)); a = fricas(ex).series(x=0); a # optional - fricas
1 5 9
- - -
2 1 2 31 2 6
x - - x + --- x + O(x )
6 360
sage: a.coefficient(9/2).sage() # optional - fricas
31/360
sage: x = fricas("x::TaylorSeries Fraction Integer") # optional - fricas
sage: y = fricas("y::TaylorSeries Fraction Integer") # optional - fricas
sage: 2*(1+2*x+sqrt(1-4*x)-2*x*y).recip() # optional - fricas
2 3 2 2 3 4 4 5
1 + (x y + x ) + 2 x + (x y + 2 x y + 6 x ) + (4 x y + 18 x )
+
3 3 4 2 5 6 5 2 6 7
(x y + 3 x y + 13 x y + 57 x ) + (6 x y + 40 x y + 186 x )
+
4 4 5 3 6 2 7 8
(x y + 4 x y + 21 x y + 130 x y + 622 x )
+
6 3 7 2 8 9
(8 x y + 66 x y + 432 x y + 2120 x )
+
5 5 6 4 7 3 8 2 9 10
(x y + 5 x y + 30 x y + 220 x y + 1466 x y + 7338 x ) + O(11)
FriCAS does some limits right::
sage: x = var('x'); ex = x^2*exp(-x)*Ei(x) - x; fricas(ex).limit(x=oo) # optional - fricas
1
"""
###########################################################################
# Copyright (C) 2008 Mike Hansen <mhansen@gmail.com>
# 2007 Bill Page
# 2006 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# The full text of the GPL is available at:
#
# https://www.gnu.org/licenses/
###########################################################################
import re
import os
from sage.interfaces.tab_completion import ExtraTabCompletion
from sage.interfaces.expect import Expect, ExpectElement, FunctionElement, ExpectFunction
from sage.misc.misc import SAGE_TMP_INTERFACE
from sage.env import DOT_SAGE, LOCAL_IDENTIFIER
from sage.docs.instancedoc import instancedoc
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.misc.lazy_import import lazy_import
lazy_import('sage.libs.pynac.pynac', ['symbol_table'])
lazy_import('sage.calculus.var', ['var', 'function'])
FRICAS_SINGLE_LINE_START = 3 # where output starts when it fits next to the line number
FRICAS_MULTI_LINE_START = 2 # and when it doesn't
FRICAS_LINE_LENGTH = 80 # length of a line, should match the line length in sage
# the following messages have, unfortunately, no markup.
FRICAS_WHAT_OPERATIONS_STRING = r"Operations whose names satisfy the above pattern\(s\):"
FRICAS_ERROR_IN_LIBRARY_CODE = ">> Error detected within library code:"
# only the last command should be necessary to make the interface
# work, the other are optimizations. Beware that lisp distinguishes
# between ' and ".
FRICAS_INIT_CODE = (
")set functions compile on",
")set message autoload off",
")set message type off",
")set output length " + str(FRICAS_LINE_LENGTH),
")lisp (setf |$ioHook|"
" (lambda (x &optional args)"
" (when (member x '(|startAlgebraOutput| |endOfAlgebraOutput|"
" |startKeyedMsg| |endOfKeyedMsg|))"
" (prin1 x)"
" (princ #\\Newline))))")
# code (one-liners!) executed after having set up the prompt
FRICAS_HELPER_CODE = (
'sageprint(x:InputForm):String == ' +
'(atom? x => (' +
'float? x => return float(x)::String;' +
'integer? x => return integer(x)::String;' +
'string? x => return concat(["_"", string(x)::String, "_""])$String;' +
'symbol? x => return string(symbol(x)));' +
'S: List String := [sageprint y for y in destruct x];' +
'R: String := new(1 + reduce(_+, [1 + #(s)$String for s in S], 0),' +
'space()$Character);' +
'copyInto!(R, "(", 1);' +
'i := 2;' +
'for s in S repeat'
'(copyInto!(R, s, i); i := i + 1 + #(s)$String);' +
'copyInto!(R, ")", i-1);' +
'return R)',)
FRICAS_LINENUMBER_OFF_CODE = ")lisp (setf |$IOindex| NIL)"
FRICAS_FIRST_PROMPT = r"\(1\) -> "
FRICAS_LINENUMBER_OFF_PROMPT = r"\(NIL\) -> "
class FriCAS(ExtraTabCompletion, Expect):
"""
Interface to a FriCAS interpreter.
"""
def __init__(self, name='fricas', command='fricas -nosman',
script_subdirectory=None, logfile=None,
server=None, server_tmpdir=None):
"""
Create an instance of the FriCAS interpreter.
TESTS::
sage: fricas == loads(dumps(fricas)) # optional - fricas
True
Check that :trac:`25174` is fixed::
sage: fricas(I) # optional - fricas
%i
sage: integrate(sin(x)*exp(I*x), x, -pi, 0, algorithm="fricas") # optional - fricas
1/2*I*pi
sage: fricas(I*sin(x)).sage() # optional - fricas
I*sin(x)
sage: fricas(I*x).sage() # optional - fricas
I*x
"""
eval_using_file_cutoff = 4096 - 5 # magic number from Expect._eval_line (there might be a bug)
assert max(len(c) for c in FRICAS_INIT_CODE) < eval_using_file_cutoff
self.__eval_using_file_cutoff = eval_using_file_cutoff
self._COMMANDS_CACHE = '%s/%s_commandlist_cache.sobj' % (DOT_SAGE, name)
# we run the init code in _start to avoid spurious output
Expect.__init__(self,
name=name,
prompt=FRICAS_FIRST_PROMPT,
command=command,
script_subdirectory=script_subdirectory,
server=server,
server_tmpdir=server_tmpdir,
restart_on_ctrlc=False,
verbose_start=False,
init_code=[],
logfile=logfile,
eval_using_file_cutoff=eval_using_file_cutoff)
def _start(self):
"""
Start the FriCAS interpreter and switch off the linenumbers.
EXAMPLES::
sage: a = FriCAS() # optional - fricas
sage: a.is_running() # optional - fricas
False
sage: a._start() # optional - fricas
sage: a.is_running() # optional - fricas
True
sage: a.quit() # optional - fricas
"""
# setting the prompt properly is necessary for restarting FriCAS
self._prompt = FRICAS_FIRST_PROMPT
Expect._start(self)
for line in FRICAS_INIT_CODE:
self.eval(line, reformat=False)
# switching off the line numbers also modified the prompt
self._prompt = FRICAS_LINENUMBER_OFF_PROMPT
self.eval(FRICAS_LINENUMBER_OFF_CODE, reformat=False)
for line in FRICAS_HELPER_CODE:
self.eval(line, reformat=False)
def _install_hints(self):
"""
Hints for installing FriCAS on your computer.
EXAMPLES::
sage: print(fricas._install_hints())
In order...
"""
return r"""
In order to use the FriCAS interface you need to have FriCAS installed.
You can either run 'sage -i fricas' to install FriCAS as an optional
package within SageMath, or install FriCAS separately, see
http://fricas.sourceforge.net.
"""
def _quit_string(self):
"""
Return the string used to quit FriCAS.
EXAMPLES::
sage: fricas._quit_string() # optional - fricas
')quit'
sage: a = FriCAS() # optional - fricas
sage: a.is_running() # optional - fricas
False
sage: a._start() # optional - fricas
sage: a.is_running() # optional - fricas
True
sage: a.quit() # optional - fricas
sage: a.is_running() # optional - fricas
False
TESTS::
sage: import psutil # optional - fricas
sage: p = fricas.pid(); pr = psutil.Process(p); pr # optional - fricas
<psutil.Process(pid=..., name='FRICASsys') at ...>
sage: pr.children() # optional - fricas
[]
"""
return ')quit'
def _commands(self):
"""
Return a list of commands available. This is done by parsing the
result of the first section of the output of ')what things'.
EXAMPLES::
sage: cmds = fricas._commands() # optional - fricas
sage: len(cmds) > 100 # optional - fricas
True
sage: '<' in cmds # optional - fricas
True
sage: 'factor' in cmds # optional - fricas
True
"""
output = self.eval(")what operations", reformat=False)
m = re.search(FRICAS_WHAT_OPERATIONS_STRING + r"\n(.*)\n\|startKeyedMsg\|",
output, flags=re.DOTALL)
l = m.groups()[0].split()
return l
def _tab_completion(self, verbose=True, use_disk_cache=True):
"""
Return a list of all the commands defined in Fricas and optionally
(per default) store them to disk.
EXAMPLES::
sage: c = fricas._tab_completion(use_disk_cache=False, verbose=False) # optional - fricas
sage: len(c) > 100 # optional - fricas
True
sage: 'factor' in c # optional - fricas
True
sage: '**' in c # optional - fricas
False
sage: 'upperCase?' in c # optional - fricas
False
sage: 'upperCase_q' in c # optional - fricas
True
sage: 'upperCase_e' in c # optional - fricas
True
"""
try:
return self.__tab_completion
except AttributeError:
import sage.misc.persist
if use_disk_cache:
try:
self.__tab_completion = sage.misc.persist.load(self._COMMANDS_CACHE)
return self.__tab_completion
except IOError:
pass
if verbose:
print("\nBuilding %s command completion list (this takes" % self)
print("a few seconds only the first time you do it).")
print("To force rebuild later, delete %s." % self._COMMANDS_CACHE)
v = self._commands()
# process the commands to strip out things which are not
# valid Python identifiers
valid = re.compile('[^a-zA-Z0-9_]+')
names = [x for x in v if valid.search(x) is None]
# replace trailing ? with _q and trailing ! with _e
names += [x[:-1] + "_q" for x in v if x.endswith("?")]
names += [x[:-1] + "_e" for x in v if x.endswith("!")]
self.__tab_completion = names
if len(v) > 200:
# Fricas is actually installed.
sage.misc.persist.save(v, self._COMMANDS_CACHE)
return names
def _read_in_file_command(self, filename):
"""
Return the FriCAS command to read the file ``filename``.
INPUT:
- ``filename``, a string ending in '.input'.
OUTPUT:
- a string with the command for reading filename without output.
TESTS:
Evaluate a rather long line::
sage: len(fricas([i for i in range(600)])) # optional - fricas, indirect doctest
600
"""
if not filename.endswith('.input'):
raise ValueError("the filename must end with .input")
return ')read %s )quiet' % filename
def _local_tmpfile(self):
"""
Return a local tmpfile ending with ".input" used to buffer long
command lines sent to FriCAS.
"""
try:
return self.__local_tmpfile
except AttributeError:
self.__local_tmpfile = os.path.join(SAGE_TMP_INTERFACE, 'tmp' + str(self.pid()) + '.input')
return self.__local_tmpfile
def _remote_tmpfile(self):
"""
Return a remote tmpfile ending with ".input" used to buffer long
command lines sent to FriCAS.
"""
try:
return self.__remote_tmpfile
except AttributeError:
self.__remote_tmpfile = self._remote_tmpdir() + "/interface_%s:%s.input" % (LOCAL_IDENTIFIER, self.pid())
return self.__remote_tmpfile
# what I expect from FriCAS:
# 1.) in set(self, var, value)
#
# no markers:
# there could be some "debugging" output, as in fricas("guessADE([1,1,1,1], debug==true)")
#
# startKeyedMsg: an error happened
#
# 2.) in get(self, var)
#
# |startAlgebraOutput\|...|endOfAlgebraOutput\|
#
# 3.) I also need a routine to send a system command and get its output.
def _check_errors(self, line, output):
"""
Check whether output contains an error and, if so, raise it.
INPUT:
- ``line``, a string that was sent to FriCAS.
- ``output``, a string returned by FriCAS
OUTPUT:
None
TESTS::
sage: fricas.set("x", "[i fo83r i in 0..17]") # optional - fricas, indirect doctest
Traceback (most recent call last):
...
RuntimeError: An error occurred when FriCAS evaluated '[i fo83r i in 0..17]':
Line 1: x:=[i fo83r i in 0..17];
...A..........B
Error A: Missing mate.
Error B: syntax error at top level
Error B: Possibly missing a ]
3 error(s) parsing
sage: fricas.set("x", "something stupid") # optional - fricas, indirect doctest
Traceback (most recent call last):
...
RuntimeError: An error occurred when FriCAS evaluated 'something stupid':
There are no library operations named something
Use HyperDoc Browse or issue
)what op something
to learn if there is any operation containing " something " in its
name.
<BLANKLINE>
Cannot find a definition or applicable library operation named
something with argument type(s)
Variable(stupid)
<BLANKLINE>
Perhaps you should use "@" to indicate the required return type, or
"$" to specify which version of the function you need.
"""
# otherwise there might be a message
m = re.search(r"\|startKeyedMsg\|\n(.*)\n\|endOfKeyedMsg\|",
output, flags=re.DOTALL)
if m:
replacements = [('|startKeyedMsg|\n', ''),
('|endOfKeyedMsg|', '')]
for old, new in replacements:
output = output.replace(old, new)
raise RuntimeError("An error occurred when FriCAS evaluated '%s':\n%s" % (line, output))
# or even an error
if FRICAS_ERROR_IN_LIBRARY_CODE in output:
raise RuntimeError("An error occurred when FriCAS evaluated '%s':\n%s" % (line, output))
def set(self, var, value):
"""
Set a variable to a value in FriCAS.
INPUT:
- ``var``, ``value``: strings, the first representing a valid
FriCAS variable identifier, the second a FriCAS expression.
OUTPUT: None
EXAMPLES::
sage: fricas.set('xx', '2') # optional - fricas
sage: fricas.get('xx') # optional - fricas
'2'
"""
cmd = '%s%s%s;' % (var, self._assign_symbol(), value)
output = self.eval(cmd, reformat=False)
self._check_errors(value, output)
def get(self, var):
r"""
Get the string representation of the value (more precisely, the
OutputForm) of a variable or expression in FriCAS.
If FriCAS cannot evaluate `var` an error is raised.
EXAMPLES::
sage: fricas.set('xx', '2') # optional - fricas
sage: fricas.get('xx') # optional - fricas
'2'
sage: a = fricas('(1 + sqrt(2))^5') # optional - fricas
sage: fricas.get(a.name()) # optional - fricas
' +-+\n29 \\|2 + 41'
sage: fricas.get('(1 + sqrt(2))^5') # optional - fricas
' +-+\n29 \\|2 + 41'
sage: fricas.new('(1 + sqrt(2))^5') # optional - fricas
+-+
29 \|2 + 41
"""
output = self.eval(str(var), reformat=False)
# if there is AlgebraOutput we ask no more
m = re.search(r"\|startAlgebraOutput\|\n(.*)\n\|endOfAlgebraOutput\|",
output, flags=re.DOTALL)
if m:
lines = m.groups()[0].split("\n")
if max(len(line) for line in lines) < FRICAS_LINE_LENGTH:
return "\n".join(line[FRICAS_SINGLE_LINE_START:] for line in lines)
else:
return "\n".join(line[FRICAS_MULTI_LINE_START:] for line in lines)
self._check_errors(var, output)
def get_string(self, var):
"""
Return the value of a FriCAS string as a string, without checking
that it is a string.
TESTS:
We test that strings are returned properly::
sage: r = fricas.get_string('concat([concat(string(i)," ") for i in 0..299])') # optional - fricas
sage: r == " ".join([str(i) for i in range(300)]) + ' ' # optional - fricas
True
sage: fricas.get_string('concat([string(1) for i in 1..5])') == "1"*5 # optional - fricas
True
sage: fricas.get_string('concat([string(1) for i in 1..10000])') == "1"*10000 # optional - fricas
True
A problem with leading space::
sage: s = "unparse((-1234567890123456789012345678901234567890123456789012345678901234567890*n::EXPR INT)::INFORM)"
sage: fricas.get_string(s) # optional - fricas
'(-1234567890123456789012345678901234567890123456789012345678901234567890)*n'
Check that :trac:`25628` is fixed::
sage: var("a b"); f = 1/(1+a*cos(x)) # optional - fricas
(a, b)
sage: lF = integrate(f, x, algorithm="fricas") # optional - fricas
sage: (diff(lF[0], x) - f).simplify_trig() # optional - fricas
0
sage: (diff(lF[1], x) - f).simplify_trig() # optional - fricas
0
sage: f = 1/(b*x^2+a); lF = integrate(f, x, algorithm="fricas"); lF # optional - fricas
[1/2*log((2*a*b*x + (b*x^2 - a)*sqrt(-a*b))/(b*x^2 + a))/sqrt(-a*b),
arctan(sqrt(a*b)*x/a)/sqrt(a*b)]
sage: (diff(lF[0], x) - f).simplify_trig() # optional - fricas
0
sage: (diff(lF[1], x) - f).simplify_trig() # optional - fricas
0
"""
# strip removes leading and trailing whitespace, after that
# we can assume that the first and the last character are
# double quotes
return self.get(str(var)).replace("\n", "").strip()[1:-1]
def get_integer(self, var):
"""
Return the value of a FriCAS integer as an integer, without
checking that it is an integer.
TESTS::
sage: fricas.get_integer('factorial 1111') == factorial(1111) # optional - fricas
True
"""
return int(self.get_unparsed_InputForm(str(var)))
def get_boolean(self, var):
"""
Return the value of a FriCAS boolean as a boolean, without checking
that it is a boolean.
TESTS::
sage: fricas.get_boolean('(1=1)::Boolean') == True # optional - fricas
True
sage: fricas.get_boolean('(1=2)::Boolean') == False # optional - fricas
True
"""
return self.get(str(var)).replace("\n", "") == "true"
def get_unparsed_InputForm(self, var):
"""
Return the unparsed ``InputForm`` as a string.
.. TODO::
- catch errors, especially when InputForm is not available:
- for example when integration returns ``"failed"``
- ``UnivariatePolynomial``
- should we provide workarounds, too?
TESTS::
sage: fricas.get_unparsed_InputForm('1..3') # optional - fricas
'(1..3)$Segment(PositiveInteger())'
"""
return self.get_string('unparse((%s)::InputForm)' % str(var))
def get_InputForm(self, var):
"""
Return the ``InputForm`` as a string.
TESTS::
sage: fricas.get_InputForm('1..3') # optional - fricas
'(($elt (Segment (PositiveInteger)) SEGMENT) 1 3)'
"""
return self.get_string('sageprint((%s)::InputForm)' % str(var))
def _assign_symbol(self):
"""
Return the symbol used for setting a variable in FriCAS.
EXAMPLES::
sage: fricas.set("x", "1"); # optional - fricas, indirect doctest
sage: fricas.get("x") # optional - fricas
'1'
sage: fricas.eval(")cl val x") # optional - fricas
''
"""
return ":="
def _equality_symbol(self):
"""
Return the equality testing logical symbol in FriCAS.
EXAMPLES::
sage: a = fricas(x==6); a # optional - fricas, indirect doctest
x = 6
A warning::
sage: fricas.set("x", 2); # optional - fricas
sage: a = fricas(x==6); a # optional - fricas
2 = 6
sage: fricas.eval(")cl val x") # optional - fricas
''
"""
return "="
def _true_symbol(self):
"""
Return the string used for ``True`` in FriCAS.
EXAMPLES::
sage: str(fricas("(1=1)@Boolean")) == fricas._true_symbol() # optional - fricas
True
"""
return "true"
def _false_symbol(self):
"""
Return the string used for ``False`` in FriCAS.
EXAMPLES::
sage: str(fricas("(1~=1)@Boolean")) == fricas._false_symbol() # optional - fricas
True
"""
return "false"
def _inequality_symbol(self):
"""
Return the string used for False in FriCAS.
EXAMPLES::
sage: fricas(x!=0) # optional - fricas, indirect doctest
true
"""
return '~='
def _repr_(self):
"""
EXAMPLES::
sage: fricas # indirect doctest
FriCAS
"""
return "FriCAS"
def __reduce__(self):
"""
EXAMPLES::
sage: fricas.__reduce__() # optional - fricas
(<function reduce_load_fricas at 0x...>, ())
sage: f, args = _ # optional - fricas
sage: f(*args) # optional - fricas
FriCAS
"""
return reduce_load_fricas, tuple([])
def eval(self, code, strip=True, synchronize=False, locals=None, allow_use_file=True,
split_lines="nofile", reformat=True, **kwds):
"""
Evaluate ``code`` using FriCAS.
Except ``reformat``, all arguments are passed to
:meth:`sage.interfaces.expect.Expect.eval`.
INPUT:
- ``reformat`` -- bool; remove the output markers when True.
This can also be used to pass system commands to FriCAS.
EXAMPLES::
sage: fricas.set("x", "1783"); fricas("x") # optional - fricas
1783
sage: fricas.eval(")cl val x"); # optional - fricas
''
sage: fricas("x") # optional - fricas
x
"""
output = Expect.eval(self, code, strip=strip,
synchronize=synchronize, locals=locals,
allow_use_file=allow_use_file, split_lines=split_lines,
**kwds)
# we remove carriage returns (\r) to make parsing easier
# they are sent depending on how fricas was invoked:
# on linux, "fricas -nox -noclef" sends "\r\n" and "fricas -nosman" sends "\n"
output = output.replace('\r', '')
if reformat:
replacements = [('|startAlgebraOutput|\n', ''),
('|endOfAlgebraOutput|', ''),
('|startKeyedMsg|\n', ''),
('|endOfKeyedMsg|', '')]
for old, new in replacements:
output = output.replace(old, new)
return output
def _function_class(self):
"""
Return the FriCASExpectFunction class.
EXAMPLES::
sage: fricas._function_class() # optional - fricas
<class 'sage.interfaces.fricas.FriCASExpectFunction'>
sage: type(fricas.gcd) # optional - fricas
<class 'sage.interfaces.fricas.FriCASExpectFunction'>
"""
return FriCASExpectFunction
def _object_class(self):
"""
EXAMPLES::
sage: fricas._object_class() # optional - fricas
<class 'sage.interfaces.fricas.FriCASElement'>
sage: type(fricas(2)) # optional - fricas
<class 'sage.interfaces.fricas.FriCASElement'>
"""
return FriCASElement
def _function_element_class(self):
"""
Return the FriCAS function element class.
EXAMPLES::
sage: fricas._function_element_class() # optional - fricas
<class 'sage.interfaces.fricas.FriCASFunctionElement'>
sage: type(fricas(2).gcd) # optional - fricas
<class 'sage.interfaces.fricas.FriCASFunctionElement'>
"""
return FriCASFunctionElement
def console(self):
"""
Spawn a new FriCAS command-line session.
EXAMPLES::
sage: fricas.console() # not tested
FriCAS (AXIOM fork) Computer Algebra System
Version: FriCAS 1.0.5
Timestamp: Thursday February 19, 2009 at 06:57:33
-----------------------------------------------------------------------------
Issue )copyright to view copyright notices.
Issue )summary for a summary of useful system commands.
Issue )quit to leave AXIOM and return to shell.
-----------------------------------------------------------------------------
"""
fricas_console()
@instancedoc
class FriCASElement(ExpectElement):
"""
Instances of this class represent objects in FriCAS.
Using the method :meth:`sage` we can translate some of them to
SageMath objects:
.. automethod:: _sage_
"""
def __len__(self):
"""
Return the length of a list.
EXAMPLES::
sage: v = fricas('[x^i for i in 0..5]') # optional - fricas
sage: len(v) # optional - fricas
6
TESTS:
Streams are not handled yet::
sage: oh = fricas('[i for i in 1..]') # optional - fricas
sage: len(oh) # optional - fricas
Traceback (most recent call last):
...
TypeError: ...
"""
P = self._check_valid()
l = P('#(%s)' % self._name)
return l.sage()
def __iter__(self):
"""
Return an iterator over ``self``.
EXAMPLES::
sage: L = fricas([4,5,6]) # optional - fricas
sage: list(L) # optional - fricas
[4, 5, 6]
TESTS:
Streams are not handled yet::
sage: oh = fricas('[i for i in 1..]') # optional - fricas
sage: next(iter(oh)) # known bug
"""
for i in range(len(self)):
yield self[i]
def __getitem__(self, n):
"""
We implement the sage conventions here, translating to 0-based iterables.
We do not check validity, since many objects in FriCAS are
iterable, in particular Streams
TESTS::
sage: fricas("[1,2,3]")[0] # optional - fricas
1
Negative indices do work::
sage: fricas("[1,2,3]")[-1] # optional - fricas
3
sage: fricas("[1,2,3]")[-2] # optional - fricas
2
Invalid indices raise exceptions::
sage: fricas("[1,2,3]")[3] # optional - fricas
Traceback (most recent call last):
...
TypeError: An error occurred when FriCAS evaluated 'elt(...,...)':
<BLANKLINE>