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
/
singular.py
2783 lines (2246 loc) · 88.7 KB
/
singular.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 Singular
AUTHORS:
- David Joyner and William Stein (2005): first version
- Martin Albrecht (2006-03-05): code so singular.[tab] and x =
singular(...), x.[tab] includes all singular commands.
- Martin Albrecht (2006-03-06): This patch adds the equality symbol to
singular. Also fix a problem in which " " as prompt means comparison
will break all further communication with Singular.
- Martin Albrecht (2006-03-13): added current_ring() and
current_ring_name()
- William Stein (2006-04-10): Fixed problems with ideal constructor
- Martin Albrecht (2006-05-18): added sage_poly.
- Simon King (2010-11-23): Reduce the overhead caused by waiting for
the Singular prompt by doing garbage collection differently.
- Simon King (2011-06-06): Make conversion from Singular to Sage more flexible.
- Simon King (2015): Extend pickling capabilities.
Introduction
------------
This interface is extremely flexible, since it's exactly like
typing into the Singular interpreter, and anything that works there
should work here.
The Singular interface will only work if Singular is installed on
your computer; this should be the case, since Singular is included
with Sage. The interface offers three pieces of functionality:
#. ``singular_console()`` - A function that dumps you
into an interactive command-line Singular session.
#. ``singular(expr, type='def')`` - Creation of a
Singular object. This provides a Pythonic interface to Singular.
For example, if ``f=singular(10)``, then
``f.factorize()`` returns the factorization of
`10` computed using Singular.
#. ``singular.eval(expr)`` - Evaluation of arbitrary
Singular expressions, with the result returned as a string.
Of course, there are polynomial rings and ideals in Sage as well
(often based on a C-library interface to Singular). One can convert
an object in the Singular interpreter interface to Sage by the
method ``sage()``.
Tutorial
--------
EXAMPLES: First we illustrate multivariate polynomial
factorization::
sage: R1 = singular.ring(0, '(x,y)', 'dp')
sage: R1
polynomial ring, over a field, global ordering
// coefficients: QQ
// number of vars : 2
// block 1 : ordering dp
// : names x y
// block 2 : ordering C
sage: f = singular('9x16 - 18x13y2 - 9x12y3 + 9x10y4 - 18x11y2 + 36x8y4 + 18x7y5 - 18x5y6 + 9x6y4 - 18x3y6 - 9x2y7 + 9y8')
sage: f
9*x^16-18*x^13*y^2-9*x^12*y^3+9*x^10*y^4-18*x^11*y^2+36*x^8*y^4+18*x^7*y^5-18*x^5*y^6+9*x^6*y^4-18*x^3*y^6-9*x^2*y^7+9*y^8
sage: f.parent()
Singular
::
sage: F = f.factorize(); F
[1]:
_[1]=9
_[2]=x^6-2*x^3*y^2-x^2*y^3+y^4
_[3]=-x^5+y^2
[2]:
1,1,2
::
sage: F[1]
9,
x^6-2*x^3*y^2-x^2*y^3+y^4,
-x^5+y^2
sage: F[1][2]
x^6-2*x^3*y^2-x^2*y^3+y^4
We can convert `f` and each exponent back to Sage objects
as well.
::
sage: g = f.sage(); g
9*x^16 - 18*x^13*y^2 - 9*x^12*y^3 + 9*x^10*y^4 - 18*x^11*y^2 + 36*x^8*y^4 + 18*x^7*y^5 - 18*x^5*y^6 + 9*x^6*y^4 - 18*x^3*y^6 - 9*x^2*y^7 + 9*y^8
sage: F[1][2].sage()
x^6 - 2*x^3*y^2 - x^2*y^3 + y^4
sage: g.parent()
Multivariate Polynomial Ring in x, y over Rational Field
This example illustrates polynomial GCD's::
sage: R2 = singular.ring(0, '(x,y,z)', 'lp')
sage: a = singular.new('3x2*(x+y)')
sage: b = singular.new('9x*(y2-x2)')
sage: g = a.gcd(b)
sage: g
x^2+x*y
This example illustrates computation of a Groebner basis::
sage: R3 = singular.ring(0, '(a,b,c,d)', 'lp')
sage: I = singular.ideal(['a + b + c + d', 'a*b + a*d + b*c + c*d', 'a*b*c + a*b*d + a*c*d + b*c*d', 'a*b*c*d - 1'])
sage: I2 = I.groebner()
sage: I2
c^2*d^6-c^2*d^2-d^4+1,
c^3*d^2+c^2*d^3-c-d,
b*d^4-b+d^5-d,
b*c-b*d^5+c^2*d^4+c*d-d^6-d^2,
b^2+2*b*d+d^2,
a+b+c+d
The following example is the same as the one in the Singular - Gap
interface documentation::
sage: R = singular.ring(0, '(x0,x1,x2)', 'lp')
sage: I1 = singular.ideal(['x0*x1*x2 -x0^2*x2', 'x0^2*x1*x2-x0*x1^2*x2-x0*x1*x2^2', 'x0*x1-x0*x2-x1*x2'])
sage: I2 = I1.groebner()
sage: I2
x1^2*x2^2,
x0*x2^3-x1^2*x2^2+x1*x2^3,
x0*x1-x0*x2-x1*x2,
x0^2*x2-x0*x2^2-x1*x2^2
sage: I2.sage()
Ideal (x1^2*x2^2, x0*x2^3 - x1^2*x2^2 + x1*x2^3, x0*x1 - x0*x2 - x1*x2, x0^2*x2 - x0*x2^2 - x1*x2^2) of Multivariate Polynomial Ring in x0, x1, x2 over Rational Field
This example illustrates moving a polynomial from one ring to
another. It also illustrates calling a method of an object with an
argument.
::
sage: R = singular.ring(0, '(x,y,z)', 'dp')
sage: f = singular('x3+y3+(x-y)*x2y2+z2')
sage: f
x^3*y^2-x^2*y^3+x^3+y^3+z^2
sage: R1 = singular.ring(0, '(x,y,z)', 'ds')
sage: f = R.fetch(f)
sage: f
z^2+x^3+y^3+x^3*y^2-x^2*y^3
We can calculate the Milnor number of `f`::
sage: _=singular.LIB('sing.lib') # assign to _ to suppress printing
sage: f.milnor()
4
The Jacobian applied twice yields the Hessian matrix of
`f`, with which we can compute.
::
sage: H = f.jacob().jacob()
sage: H
6*x+6*x*y^2-2*y^3,6*x^2*y-6*x*y^2, 0,
6*x^2*y-6*x*y^2, 6*y+2*x^3-6*x^2*y,0,
0, 0, 2
sage: H.sage()
[6*x + 6*x*y^2 - 2*y^3 6*x^2*y - 6*x*y^2 0]
[ 6*x^2*y - 6*x*y^2 6*y + 2*x^3 - 6*x^2*y 0]
[ 0 0 2]
sage: H.det() # This is a polynomial in Singular
72*x*y+24*x^4-72*x^3*y+72*x*y^3-24*y^4-48*x^4*y^2+64*x^3*y^3-48*x^2*y^4
sage: H.det().sage() # This is the corresponding polynomial in Sage
72*x*y + 24*x^4 - 72*x^3*y + 72*x*y^3 - 24*y^4 - 48*x^4*y^2 + 64*x^3*y^3 - 48*x^2*y^4
The 1x1 and 2x2 minors::
sage: H.minor(1)
2,
6*y+2*x^3-6*x^2*y,
6*x^2*y-6*x*y^2,
6*x^2*y-6*x*y^2,
6*x+6*x*y^2-2*y^3
sage: H.minor(2)
12*y+4*x^3-12*x^2*y,
12*x^2*y-12*x*y^2,
12*x^2*y-12*x*y^2,
12*x+12*x*y^2-4*y^3,
-36*x*y-12*x^4+36*x^3*y-36*x*y^3+12*y^4+24*x^4*y^2-32*x^3*y^3+24*x^2*y^4
::
sage: _=singular.eval('option(redSB)')
sage: H.minor(1).groebner()
1
Computing the Genus
-------------------
We compute the projective genus of ideals that define curves over
`\QQ`. It is *very important* to load the
``normal.lib`` library before calling the
``genus`` command, or you'll get an error message.
EXAMPLES::
sage: singular.lib('normal.lib')
sage: R = singular.ring(0,'(x,y)','dp')
sage: i2 = singular.ideal('y9 - x2*(x-1)^9 + x')
sage: i2.genus()
40
Note that the genus can be much smaller than the degree::
sage: i = singular.ideal('y9 - x2*(x-1)^9')
sage: i.genus()
0
An Important Concept
--------------------
AUTHORS:
- Neal Harris
The following illustrates an important concept: how Sage interacts
with the data being used and returned by Singular. Let's compute a
Groebner basis for some ideal, using Singular through Sage.
::
sage: singular.lib('poly.lib')
sage: singular.ring(32003, '(a,b,c,d,e,f)', 'lp')
polynomial ring, over a field, global ordering
// coefficients: ZZ/32003
// number of vars : 6
// block 1 : ordering lp
// : names a b c d e f
// block 2 : ordering C
sage: I = singular.ideal('cyclic(6)')
sage: g = singular('groebner(I)')
Traceback (most recent call last):
...
TypeError: Singular error:
...
We restart everything and try again, but correctly.
::
sage: singular.quit()
sage: singular.lib('poly.lib'); R = singular.ring(32003, '(a,b,c,d,e,f)', 'lp')
sage: I = singular.ideal('cyclic(6)')
sage: I.groebner()
f^48-2554*f^42-15674*f^36+12326*f^30-12326*f^18+15674*f^12+2554*f^6-1,
...
It's important to understand why the first attempt at computing a
basis failed. The line where we gave singular the input
'groebner(I)' was useless because Singular has no idea what 'I' is!
Although 'I' is an object that we computed with calls to Singular
functions, it actually lives in Sage. As a consequence, the name
'I' means nothing to Singular. When we called
``I.groebner()``, Sage was able to call the groebner
function on'I' in Singular, since 'I' actually means something to
Sage.
Long Input
----------
The Singular interface reads in even very long input (using files)
in a robust manner, as long as you are creating a new object.
::
sage: t = '"%s"'%10^15000 # 15 thousand character string (note that normal Singular input must be at most 10000)
sage: a = singular.eval(t)
sage: a = singular(t)
TESTS:
We test an automatic coercion::
sage: a = 3*singular('2'); a
6
sage: type(a)
<class 'sage.interfaces.singular.SingularElement'>
sage: a = singular('2')*3; a
6
sage: type(a)
<class 'sage.interfaces.singular.SingularElement'>
Create a ring over GF(9) to check that ``gftables`` has been installed,
see :trac:`11645`::
sage: singular.eval("ring testgf9 = (9,x),(a,b,c,d,e,f),(M((1,2,3,0)),wp(2,3),lp);")
''
"""
# ****************************************************************************
# Copyright (C) 2005 David Joyner and William Stein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import print_function, absolute_import
import io
import os
import re
import sys
import pexpect
from time import sleep
from decorator import decorater
from .expect import Expect, ExpectElement, FunctionElement, ExpectFunction
from sage.interfaces.tab_completion import ExtraTabCompletion
from sage.structure.sequence import Sequence_generic
from sage.structure.element import RingElement
import sage.rings.integer
from sage.env import SINGULARPATH
from sage.misc.verbose import get_verbose
from sage.docs.instancedoc import instancedoc
class SingularError(RuntimeError):
"""
Raised if Singular printed an error message
"""
pass
class Singular(ExtraTabCompletion, Expect):
r"""
Interface to the Singular interpreter.
EXAMPLES: A Groebner basis example.
::
sage: R = singular.ring(0, '(x0,x1,x2)', 'lp')
sage: I = singular.ideal([ 'x0*x1*x2 -x0^2*x2', 'x0^2*x1*x2-x0*x1^2*x2-x0*x1*x2^2', 'x0*x1-x0*x2-x1*x2'])
sage: I.groebner()
x1^2*x2^2,
x0*x2^3-x1^2*x2^2+x1*x2^3,
x0*x1-x0*x2-x1*x2,
x0^2*x2-x0*x2^2-x1*x2^2
AUTHORS:
- David Joyner and William Stein
"""
def __init__(self, maxread=None, script_subdirectory=None,
logfile=None, server=None,server_tmpdir=None,
seed=None):
"""
EXAMPLES::
sage: singular == loads(dumps(singular))
True
"""
prompt = '> '
Expect.__init__(self,
terminal_echo=False,
name = 'singular',
prompt = prompt,
# no tty, fine grained cputime()
# and do not display CTRL-C prompt
command = "Singular -t --ticks-per-sec 1000 --cntrlc=a",
server = server,
server_tmpdir = server_tmpdir,
script_subdirectory = script_subdirectory,
restart_on_ctrlc = True,
verbose_start = False,
logfile = logfile,
eval_using_file_cutoff=100 if os.uname()[0]=="SunOS" else 1000)
self.__libs = []
self._prompt_wait = prompt
self.__to_clear = [] # list of variable names that need to be cleared.
self._seed = seed
def set_seed(self,seed=None):
"""
Set the seed for singular interpreter.
The seed should be an integer at least 1
and not more than 30 bits.
See
http://www.singular.uni-kl.de/Manual/html/sing_19.htm#SEC26
and
http://www.singular.uni-kl.de/Manual/html/sing_283.htm#SEC323
EXAMPLES::
sage: s = Singular()
sage: s.set_seed(1)
1
sage: [s.random(1,10) for i in range(5)]
[8, 10, 4, 9, 1]
"""
if seed is None:
seed = self.rand_seed()
self.eval('system("--random",%d)' % seed)
self._seed = seed
return seed
def _start(self, alt_message=None):
"""
EXAMPLES::
sage: s = Singular()
sage: s.is_running()
False
sage: s._start()
sage: s.is_running()
True
sage: s.quit()
"""
self.__libs = []
Expect._start(self, alt_message)
# Load some standard libraries.
self.lib('general') # assumed loaded by misc/constants.py
# these options are required by the new coefficient rings
# supported by Singular 3-1-0.
self.option("redTail")
self.option("redThrough")
self.option("intStrategy")
self._saved_options = self.option('get')
# set random seed
self.set_seed(self._seed)
def __reduce__(self):
"""
EXAMPLES::
sage: singular.__reduce__()
(<function reduce_load_Singular at 0x...>, ())
"""
return reduce_load_Singular, ()
def _equality_symbol(self):
"""
EXAMPLES::
sage: singular._equality_symbol()
'=='
"""
return '=='
def _true_symbol(self):
"""
EXAMPLES::
sage: singular._true_symbol()
'1'
"""
return '1'
def _false_symbol(self):
"""
EXAMPLES::
sage: singular._false_symbol()
'0'
"""
return '0'
def _quit_string(self):
"""
EXAMPLES::
sage: singular._quit_string()
'quit'
"""
return 'quit'
def _send_interrupt(self):
"""
Send an interrupt to Singular. If needed, additional
semi-colons are sent until we get back at the prompt.
TESTS:
The following works without restarting Singular::
sage: a = singular(1)
sage: _ = singular._expect.sendline('1+') # unfinished input
sage: try:
....: alarm(0.5)
....: singular._expect_expr('>') # interrupt this
....: except KeyboardInterrupt:
....: pass
Control-C pressed. Interrupting Singular. Please wait a few seconds...
We can still access a::
sage: 2*a
2
"""
# Work around for Singular bug
# http://www.singular.uni-kl.de:8002/trac/ticket/727
sleep(0.1)
E = self._expect
E.sendline(chr(3))
for i in range(5):
try:
E.expect_upto(self._prompt, timeout=1.0)
return
except Exception:
pass
E.sendline(";")
def _read_in_file_command(self, filename):
r"""
EXAMPLES::
sage: singular._read_in_file_command('test')
'< "...";'
sage: filename = tmp_filename()
sage: f = open(filename, 'w')
sage: _ = f.write('int x = 2;\n')
sage: f.close()
sage: singular.read(filename)
sage: singular.get('x')
'2'
"""
return '< "%s";'%filename
def eval(self, x, allow_semicolon=True, strip=True, **kwds):
r"""
Send the code x to the Singular interpreter and return the output
as a string.
INPUT:
- ``x`` - string (of code)
- ``allow_semicolon`` - default: False; if False then
raise a TypeError if the input line contains a semicolon.
- ``strip`` - ignored
EXAMPLES::
sage: singular.eval('2 > 1')
'1'
sage: singular.eval('2 + 2')
'4'
if the verbosity level is `> 1` comments are also printed
and not only returned.
::
sage: r = singular.ring(0,'(x,y,z)','dp')
sage: i = singular.ideal(['x^2','y^2','z^2'])
sage: s = i.std()
sage: singular.eval('hilb(%s)'%(s.name()))
'// 1 t^0\n// -3 t^2\n// 3 t^4\n// -1 t^6\n\n// 1 t^0\n//
3 t^1\n// 3 t^2\n// 1 t^3\n// dimension (affine) = 0\n//
degree (affine) = 8'
::
sage: from sage.misc.verbose import set_verbose
sage: set_verbose(1)
sage: o = singular.eval('hilb(%s)'%(s.name()))
// 1 t^0
// -3 t^2
// 3 t^4
// -1 t^6
// 1 t^0
// 3 t^1
// 3 t^2
// 1 t^3
// dimension (affine) = 0
// degree (affine) = 8
This is mainly useful if this method is called implicitly. Because
then intermediate results, debugging outputs and printed statements
are printed
::
sage: o = s.hilb()
// 1 t^0
// -3 t^2
// 3 t^4
// -1 t^6
// 1 t^0
// 3 t^1
// 3 t^2
// 1 t^3
// dimension (affine) = 0
// degree (affine) = 8
// ** right side is not a datum, assignment ignored
...
rather than ignored
::
sage: set_verbose(0)
sage: o = s.hilb()
"""
# Simon King:
# In previous versions, the interface was first synchronised and then
# unused variables were killed. This created a considerable overhead.
# By trac ticket #10296, killing unused variables is now done inside
# singular.set(). Moreover, it is not done by calling a separate _eval_line.
# In that way, the time spent by waiting for the singular prompt is reduced.
# Before #10296, it was possible that garbage collection occurred inside
# of _eval_line. But collection of the garbage would launch another call
# to _eval_line. The result would have been a dead lock, that could only
# be avoided by synchronisation. Since garbage collection is now done
# without an additional call to _eval_line, synchronisation is not
# needed anymore, saving even more waiting time for the prompt.
# Uncomment the print statements below for low-level debugging of
# code that involves the singular interfaces. Everything goes
# through here.
x = str(x).rstrip().rstrip(';')
x = x.replace("> ",">\t") #don't send a prompt (added by Martin Albrecht)
if not allow_semicolon and x.find(";") != -1:
raise TypeError("singular input must not contain any semicolons:\n%s"%x)
if len(x) == 0 or x[len(x) - 1] != ';':
x += ';'
s = Expect.eval(self, x, **kwds)
# "Segment fault" is not a typo:
# Singular actually does use that string
if s.find("error occurred") != -1 or s.find("Segment fault") != -1:
raise SingularError('Singular error:\n%s'%s)
if get_verbose() > 0:
for line in s.splitlines():
if line.startswith("//"):
print(line)
return s
else:
return s
def set(self, type, name, value):
"""
Set the variable with given name to the given value.
REMARK:
If a variable in the Singular interface was previously marked for
deletion, the actual deletion is done here, before the new variable
is created in Singular.
EXAMPLES::
sage: singular.set('int', 'x', '2')
sage: singular.get('x')
'2'
We test that an unused variable is only actually deleted if this method
is called::
sage: a = singular(3)
sage: n = a.name()
sage: del a
sage: singular.eval(n)
'3'
sage: singular.set('int', 'y', '5')
sage: singular.eval('defined(%s)'%n)
'0'
"""
cmd = ''.join('if(defined(%s)){kill %s;};'%(v,v) for v in self.__to_clear)
cmd += '%s %s=%s;'%(type, name, value)
self.__to_clear = []
self.eval(cmd)
def get(self, var):
"""
Get string representation of variable named var.
EXAMPLES::
sage: singular.set('int', 'x', '2')
sage: singular.get('x')
'2'
"""
return self.eval('print(%s);'%var)
def clear(self, var):
"""
Clear the variable named ``var``.
EXAMPLES::
sage: singular.set('int', 'x', '2')
sage: singular.get('x')
'2'
sage: singular.clear('x')
"Clearing the variable" means to allow to free the memory
that it uses in the Singular sub-process. However, the
actual deletion of the variable is only committed when
the next element in the Singular interface is created::
sage: singular.get('x')
'2'
sage: a = singular(3)
sage: singular.get('x')
'`x`'
"""
# We add the variable to the list of vars to clear when we do an eval.
# We queue up all the clears and do them at once to avoid synchronizing
# the interface at the same time we do garbage collection, which can
# lead to subtle problems. This was Willem Jan's ideas, implemented
# by William Stein.
self.__to_clear.append(var)
def _create(self, value, type='def'):
"""
Creates a new variable in the Singular session and returns the name
of that variable.
EXAMPLES::
sage: singular._create('2', type='int')
'sage...'
sage: singular.get(_)
'2'
"""
name = self._next_var_name()
self.set(type, name, value)
return name
def __call__(self, x, type='def'):
"""
Create a singular object X with given type determined by the string
x. This returns var, where var is built using the Singular
statement type var = ... x ... Note that the actual name of var
could be anything, and can be recovered using X.name().
The object X returned can be used like any Sage object, and wraps
an object in self. The standard arithmetic operators work. Moreover
if foo is a function then X.foo(y,z,...) calls foo(X, y, z, ...)
and returns the corresponding object.
EXAMPLES::
sage: R = singular.ring(0, '(x0,x1,x2)', 'lp')
sage: I = singular.ideal([ 'x0*x1*x2 -x0^2*x2', 'x0^2*x1*x2-x0*x1^2*x2-x0*x1*x2^2', 'x0*x1-x0*x2-x1*x2'])
sage: I
-x0^2*x2+x0*x1*x2,
x0^2*x1*x2-x0*x1^2*x2-x0*x1*x2^2,
x0*x1-x0*x2-x1*x2
sage: type(I)
<class 'sage.interfaces.singular.SingularElement'>
sage: I.parent()
Singular
"""
if isinstance(x, SingularElement) and x.parent() is self:
return x
elif isinstance(x, ExpectElement):
return self(x.sage())
elif not isinstance(x, ExpectElement) and hasattr(x, '_singular_'):
return x._singular_(self)
# some convenient conversions
if type in ("module","list") and isinstance(x,(list,tuple,Sequence_generic)):
x = str(x)[1:-1]
return SingularElement(self, type, x, False)
def _coerce_map_from_(self, S):
"""
Return ``True`` if ``S`` admits a coercion map into the
Singular interface.
EXAMPLES::
sage: singular._coerce_map_from_(ZZ)
True
sage: singular.coerce_map_from(ZZ)
Call morphism:
From: Integer Ring
To: Singular
sage: singular.coerce_map_from(float)
"""
# we want to implement this without coercing, since singular has state.
if hasattr(S, 'an_element'):
if hasattr(S.an_element(), '_singular_'):
return True
elif S is int:
return True
return None
def cputime(self, t=None):
r"""
Returns the amount of CPU time that the Singular session has used.
If ``t`` is not None, then it returns the difference
between the current CPU time and ``t``.
EXAMPLES::
sage: t = singular.cputime()
sage: R = singular.ring(0, '(x0,x1,x2)', 'lp')
sage: I = singular.ideal([ 'x0*x1*x2 -x0^2*x2', 'x0^2*x1*x2-x0*x1^2*x2-x0*x1*x2^2', 'x0*x1-x0*x2-x1*x2'])
sage: gb = I.groebner()
sage: singular.cputime(t) #random
0.02
"""
if t:
return float(self.eval('timer-(%d)'%(int(1000*t))))/1000.0
else:
return float(self.eval('timer'))/1000.0
###################################################################
# Singular libraries
###################################################################
def lib(self, lib, reload=False):
"""
Load the Singular library named lib.
Note that if the library was already loaded during this session it
is not reloaded unless the optional reload argument is True (the
default is False).
EXAMPLES::
sage: singular.lib('sing.lib')
sage: singular.lib('sing.lib', reload=True)
"""
if lib[-4:] != ".lib":
lib += ".lib"
if not reload and lib in self.__libs:
return
self.eval('LIB "%s"'%lib)
self.__libs.append(lib)
LIB = lib
load = lib
###################################################################
# constructors
###################################################################
def ideal(self, *gens):
"""
Return the ideal generated by gens.
INPUT:
- ``gens`` - list or tuple of Singular objects (or
objects that can be made into Singular objects via evaluation)
OUTPUT: the Singular ideal generated by the given list of gens
EXAMPLES: A Groebner basis example done in a different way.
::
sage: _ = singular.eval("ring R=0,(x0,x1,x2),lp")
sage: i1 = singular.ideal([ 'x0*x1*x2 -x0^2*x2', 'x0^2*x1*x2-x0*x1^2*x2-x0*x1*x2^2', 'x0*x1-x0*x2-x1*x2'])
sage: i1
-x0^2*x2+x0*x1*x2,
x0^2*x1*x2-x0*x1^2*x2-x0*x1*x2^2,
x0*x1-x0*x2-x1*x2
::
sage: i2 = singular.ideal('groebner(%s);'%i1.name())
sage: i2
x1^2*x2^2,
x0*x2^3-x1^2*x2^2+x1*x2^3,
x0*x1-x0*x2-x1*x2,
x0^2*x2-x0*x2^2-x1*x2^2
"""
if isinstance(gens, str):
gens = self(gens)
if isinstance(gens, SingularElement):
return self(gens.name(), 'ideal')
if not isinstance(gens, (list, tuple)):
raise TypeError("gens (=%s) must be a list, tuple, string, or Singular element"%gens)
if len(gens) == 1 and isinstance(gens[0], (list, tuple)):
gens = gens[0]
gens2 = []
for g in gens:
if not isinstance(g, SingularElement):
gens2.append(self.new(g))
else:
gens2.append(g)
return self(",".join([g.name() for g in gens2]), 'ideal')
def list(self, x):
r"""
Creates a list in Singular from a Sage list ``x``.
EXAMPLES::
sage: singular.list([1,2])
[1]:
1
[2]:
2
sage: singular.list([1,2,[3,4]])
[1]:
1
[2]:
2
[3]:
[1]:
3
[2]:
4
sage: R.<x,y> = QQ[]
sage: singular.list([1,2,[x,ideal(x,y)]])
[1]:
1
[2]:
2
[3]:
[1]:
x
[2]:
_[1]=x
_[2]=y
Strings have to be escaped before passing them to this method::
sage: singular.list([1,2,'"hi"'])
[1]:
1
[2]:
2
[3]:
hi
TESTS:
Check that a list already converted to Singular can be
embedded into a list to be converted::
sage: singular.list([1, 2, singular.list([3, 4])])
[1]:
1
[2]:
2
[3]:
[1]:
3
[2]:
4
"""
# We have to be careful about object destruction.
# If we convert an object to a Singular element, the only
# thing that goes into the list definition statement is the
# Singular variable name, so we need to keep the element
# around long enough to ensure that the variable still exists
# when we create the list. We ensure this by putting created
# elements on a list, which gets destroyed when this function
# returns, by which time the list has been created.
singular_elements = []
def strify(x):
if isinstance(x, (list, tuple, Sequence_generic)):
return 'list(' + ','.join([strify(i) for i in x]) + ')'
elif isinstance(x, SingularElement):