-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
polymake.py
2742 lines (2254 loc) · 109 KB
/
polymake.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 polymake
polymake (https://polymake.org) is a mature open source package for
research in polyhedral geometry and related fields, developed since 1997
by Ewgenij Gawrilow and Michael Joswig and various contributors.
polymake has been described in [GJ1997]_, [GJ2006]_, [JMP2009]_, [GJRW2010]_,
[GHJ2016]_, and [AGHJLPR2017]_.
"""
# ****************************************************************************
# Copyright (C) 2017 Simon King <simon.king@uni-jena.de>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# The full text of the GPL is available at:
#
# https://www.gnu.org/licenses/
# ****************************************************************************
import os
import re
import sys
import time
from .expect import Expect
from .interface import (Interface, InterfaceElement, InterfaceFunctionElement)
from sage.cpython.string import bytes_to_str, str_to_bytes
from sage.misc.verbose import get_verbose
from sage.misc.cachefunc import cached_method
from sage.interfaces.tab_completion import ExtraTabCompletion
from sage.structure.richcmp import rich_to_bool
import pexpect
from random import randrange
from time import sleep
import warnings
_name_pattern = re.compile('SAGE[0-9]+')
_available_polymake_answers = {
0: "returns prompt",
1: "returns continuation prompt",
2: "requests interactive input",
3: "kills computation",
4: "raises error",
5: "issues warning",
6: "shows additional information",
7: "lost connection",
8: "fails to respond timely"
}
class PolymakeError(RuntimeError):
"""
Raised if polymake yields an error message.
TESTS::
sage: polymake.eval('print foo;') # optional polymake
Traceback (most recent call last):
...
PolymakeError: Unquoted string "foo" may clash with future reserved word...
"""
pass
def polymake_console(command=''):
"""
Spawn a new polymake command-line session.
EXAMPLES::
sage: from sage.interfaces.polymake import polymake_console
sage: polymake_console() # not tested
Welcome to polymake version ...
...
Ewgenij Gawrilow, Michael Joswig (TU Berlin)
http://www.polymake.org
This is free software licensed under GPL; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Press F1 or enter 'help;' for basic instructions.
Application polytope currently uses following third-party software packages:
4ti2, bliss, cdd, latte, libnormaliz, lrs, permlib, ppl, sketch, sympol, threejs, tikz, topcom, tosimplex
For more details: show_credits;
polytope >
"""
from sage.repl.rich_output.display_manager import get_display_manager
if not get_display_manager().is_in_terminal():
raise RuntimeError('Can use the console only in the terminal. Try %%polymake magics instead.')
os.system(command or os.getenv('SAGE_POLYMAKE_COMMAND') or 'polymake')
class PolymakeAbstract(ExtraTabCompletion, Interface):
r"""
Abstract interface to the polymake interpreter.
This class should not be instantiated directly,
but through its subclasses Polymake (Pexpect interface)
or PolymakeJuPyMake (JuPyMake interface).
EXAMPLES::
sage: from sage.interfaces.polymake import PolymakeAbstract, polymake_expect, polymake_jupymake
We test the verbosity management with very early doctests
because messages will not be repeated.
Testing the deprecated pexpect-based interface::
sage: type(polymake_expect)
<...sage.interfaces.polymake.PolymakeExpect...
sage: isinstance(polymake_expect, PolymakeAbstract)
True
sage: p = polymake_expect.rand_sphere(4, 20, seed=5) # optional - polymake_expect
doctest...: DeprecationWarning: the pexpect-based interface to
polymake is deprecated.
Install package jupymake so that Sage can use the more robust
jupymake-based interface to polymake
See https://trac.sagemath.org/27745 for details.
sage: p # optional - polymake_expect
Random spherical polytope of dimension 4; seed=5...
sage: set_verbose(3)
sage: p.H_VECTOR # optional - polymake_expect
used package ppl
The Parma Polyhedra Library ...
1 16 40 16 1
sage: set_verbose(0)
sage: p.F_VECTOR # optional - polymake_expect
20 94 148 74
Testing the JuPyMake interface::
sage: isinstance(polymake_jupymake, PolymakeAbstract)
True
sage: p = polymake_jupymake.rand_sphere(4, 20, seed=5) # optional - jupymake
sage: p # optional - jupymake
Random spherical polytope of dimension 4; seed=5...
sage: set_verbose(3)
sage: p.H_VECTOR # optional - jupymake
polymake: used package ppl
The Parma Polyhedra Library ...
1 16 40 16 1
sage: set_verbose(0)
sage: p.F_VECTOR # optional - jupymake
20 94 148 74
"""
def __init__(self, seed=None):
"""
TESTS::
sage: from sage.interfaces.polymake import PolymakeAbstract
sage: PolymakeAbstract()
Polymake
"""
Interface.__init__(self, "polymake")
self._seed = seed
self.__tab_completion = {}
@cached_method
def version(self):
"""
Version of the polymake installation.
EXAMPLES::
sage: polymake.version() # optional - polymake # random
'4...'
TESTS::
sage: from sage.interfaces.polymake import Polymake
sage: Polymake(command='foobar').version()
Traceback (most recent call last):
...
RuntimeError: runtime error with deprecated pexpect-based interface to polymake; please install jupymake
"""
return self.get('$Polymake::Version')
# Pickling etc
def __reduce__(self):
"""
EXAMPLES::
sage: loads(dumps(polymake)) is polymake
True
"""
return reduce_load_Polymake, tuple([])
def _object_class(self):
"""
Return the class by which elements in this interface are implemented.
TESTS::
sage: C = polymake('cube(3)') # indirect doctest # optional - polymake
sage: C # optional - polymake
cube of dimension 3
sage: type(C) # optional - polymake
<class 'sage.interfaces.polymake.PolymakeElement'>
"""
return PolymakeElement
def _function_element_class(self):
"""
Return the class by which member functions of this interface are implemented.
TESTS:
We use ellipses in the tests, to make it more robust against future
changes in polymake::
sage: p = polymake.rand_sphere(4, 20, seed=5) # optional - polymake
sage: p.get_schedule # optional - polymake # indirect doctest
Member function 'get_schedule' of Polymake::polytope::Polytope__Rational object
sage: p.get_schedule('"F_VECTOR"') # optional - polymake # random
CONE_DIM : RAYS | INPUT_RAYS
precondition : BOUNDED ( POINTED : )
POINTED :
N_INPUT_RAYS : INPUT_RAYS
precondition : N_RAYS | N_INPUT_RAYS ( ppl.convex_hull.primal: FACETS, LINEAR_SPAN : RAYS | INPUT_RAYS )
sensitivity check for FacetPerm
ppl.convex_hull.primal: FACETS, LINEAR_SPAN : RAYS | INPUT_RAYS
INPUT_RAYS_IN_FACETS : INPUT_RAYS, FACETS
sensitivity check for VertexPerm
RAYS_IN_FACETS, RAYS, LINEALITY_SPACE : INPUT_RAYS_IN_FACETS, INPUT_RAYS
GRAPH.ADJACENCY : RAYS_IN_FACETS
DUAL_GRAPH.ADJACENCY : RAYS_IN_FACETS
N_EDGES : ADJACENCY ( applied to GRAPH )
N_EDGES : ADJACENCY ( applied to DUAL_GRAPH )
precondition : POINTED ( LINEALITY_DIM, LINEALITY_SPACE : )
LINEALITY_DIM, LINEALITY_SPACE :
COMBINATORIAL_DIM : CONE_DIM, LINEALITY_DIM
N_RAYS : RAYS
N_FACETS : FACETS
precondition : COMBINATORIAL_DIM ( F_VECTOR : N_FACETS, N_RAYS, GRAPH.N_EDGES, DUAL_GRAPH.N_EDGES, COMBINATORIAL_DIM )
F_VECTOR : N_FACETS, N_RAYS, GRAPH.N_EDGES, DUAL_GRAPH.N_EDGES, COMBINATORIAL_DIM
"""
return PolymakeFunctionElement
def function_call(self, function, args=None, kwds=None):
"""
EXAMPLES::
sage: polymake.rand_sphere(4, 30, seed=15) # optional - polymake # indirect doctest
Random spherical polytope of dimension 4; seed=15...
"""
args, kwds = self._convert_args_kwds(args, kwds)
self._check_valid_function_name(function)
s = self._function_call_string(function,
[s.name() for s in args],
['{}=>{}'.format(key, value.name()) for key, value in kwds.items()])
return self(s)
def _function_call_string(self, function, args, kwds):
"""
Returns the string used to make function calls.
EXAMPLES::
sage: polymake._function_call_string('cube', ['2','7','3'], ['group=>1']) # optional - polymake
'cube(2,7,3, group=>1);'
sage: c = polymake('cube(2,7,3, group=>1)') # optional - polymake
sage: c.VERTICES # optional - polymake
1 3 3
1 7 3
1 3 7
1 7 7
sage: c.GROUP # optional - polymake
full combinatorial group
"""
if kwds:
if args:
call_str = "{}({}, {});".format(function, ",".join(list(args)), ",".join(list(kwds)))
return call_str
return "{}({});".format(function, ",".join(list(kwds)))
return "{}({});".format(function, ",".join(list(args)))
def _coerce_impl(self, x, use_special=True):
"""
Implementation of coercion.
TESTS:
Test that dictionaries are converted to hashes::
sage: h = polymake({'"a"': 1, '"b"': 2}) # optional - polymake
sage: h # optional - polymake
HASH(0x...)
sage: h['"a"'] # optional - polymake
1
"""
if isinstance(x, dict):
# Convert dictionaries to hashes.
# This is an adaptation of the list/tuple code from Interface._coerce_impl
A = []
z = dict()
cls = self._object_class()
def convert(y):
if isinstance(y, cls):
return y
else:
return self(y)
for k, v in x.items():
k = convert(k)
v = convert(v)
z[k] = v
A.append("{}=>{}".format(k.name(), v.name()))
r = self.new("{" + ",".join(A) + "}")
r.__sage_dict = z # do this to avoid having the entries of the list be garbage collected
return r
from sage.rings.all import Integer, Rational, RDF
from sage.rings.number_field.number_field import is_QuadraticField
def to_str(x):
if isinstance(x, list):
s = '['
for y in x:
s += to_str(y) + ', '
s += ']'
return s
if isinstance(x, (Integer, Rational, int)):
return '{}'.format(x)
parent = None
try:
parent = x.parent()
except AttributeError:
pass
if is_QuadraticField(parent):
return x._polymake_init_()
try:
if x.parent().is_exact():
# No other exact rings are supported.
raise NotImplementedError
except AttributeError:
pass
try:
x = RDF(x)
return '{}'.format(x)
except:
pass
raise NotImplementedError
# Iteratively calling polymake for conversion takes a long time.
# However, it takes iterated arrays of integers, rationals and floats directly.
try:
return self.new(to_str(x))
except NotImplementedError:
pass
return super(PolymakeAbstract, self)._coerce_impl(x, use_special=use_special)
def console(self):
"""
Raise an error, pointing to :meth:`~sage.interfaces.interface.Interface.interact` and :func:`polymake_console`.
EXAMPLES::
sage: polymake.console()
Traceback (most recent call last):
...
NotImplementedError: Please use polymake_console() function or the .interact() method
"""
raise NotImplementedError("Please use polymake_console() function or the .interact() method")
# Methods concerning interface communication
def _install_hints(self):
"""
TESTS::
sage: print(polymake._install_hints())
Please install the optional polymake package for sage
or install polymake system-wide
(use the shell command 'sage --info polymake' for more information)
"""
return "Please install the optional polymake package for sage" + os.linesep + "or install polymake system-wide" + os.linesep + "(use the shell command 'sage --info polymake' for more information)"
def _start(self):
"""
Start the polymake interface in the application "polytope".
.. NOTE::
There should be no need to call this explicitly.
TESTS::
sage: polymake._start() # optional - polymake
Since 'normal_fan' is not defined in the polymake application 'polytope',
we now get
::
sage: 'normal_fan' in dir(polymake) # optional - polymake
False
"""
self.application("polytope")
self.eval('use Scalar::Util qw(reftype);')
self.eval('use Scalar::Util qw(blessed);')
def _assign_symbol(self):
"""
TESTS::
sage: polymake._assign_symbol()
'='
"""
return "="
def _equality_symbol(self):
"""
TESTS::
sage: polymake._equality_symbol()
'=='
"""
return "=="
def _read_in_file_command(self, filename):
"""
TESTS::
sage: polymake._read_in_file_command('foobar')
'eval read_file "foobar";\n'
Force use of file::
sage: L = polymake([42] * 400) # optional - polymake
sage: len(L) # optional - polymake
400
Just below standard file cutoff of 1024::
sage: L = polymake([42] * 84) # optional - polymake
sage: len(L) # optional - polymake
84
"""
return 'eval read_file "{}";\n'.format(filename)
def _next_var_name(self):
r"""
Returns the next unused variable name.
TESTS::
sage: print(polymake._next_var_name())
SAGE...
"""
if len(self._available_vars):
return self._available_vars.pop(0)
try:
self.__seq += 1
except AttributeError:
self.__seq = 0
return r'SAGE{}'.format(self.__seq)
def clear(self, var):
r"""
Clear the variable named ``var``.
.. NOTE::
This is implicitly done when deleting an element in the interface.
TESTS::
sage: c = polymake.cube(15) # optional - polymake
sage: polymake._available_vars = [] # optional - polymake
sage: old = c._name # optional - polymake
sage: del c # optional - polymake # indirect doctest
sage: len(polymake._available_vars) # optional - polymake
1
sage: polymake._next_var_name() in old # optional - polymake
True
"""
self._available_vars.append(_name_pattern.search(var).group())
def _create(self, value, name=None):
"""
Assign a value to a name in the polymake interface.
INPUT:
- ``value`` -- string; Polymake command (or value) whose result
is to be assigned to a variable
- ``name`` -- (optional) string; if given, the new variable has this
name; otherwise, the name is automatically generated
RETURN:
The command by which the assigned value can now be retrieved.
.. NOTE::
In order to overcome problems with the perl programming language,
we store *all* data as arrays. If the given value is an array
of length different from one, then the new variable contains that
array. Otherwise, the new variable is an array of length one whose
only entry is the given value, which has to be a scalar (which
also includes Perl references). In other words, perl hashes
are not suitable.
EXAMPLES::
sage: polymake._create("('foo', 'bar')", name="my_array") # optional - polymake
'@my_array'
sage: print(polymake.eval('print join(", ", @my_array);')) # optional - polymake
foo, bar
sage: polymake._create('"foobar"', name="my_string") # optional - polymake
'$my_string[0]'
sage: print(polymake.eval('print $my_string[0];')) # optional - polymake
foobar
"""
name = self._next_var_name() if name is None else name
self.set(name, value)
# If value is a list, then @name is now equal to that list.
# Otherwise, value is obtained by $name[0]. So, we modify
# the name returned by _create so that it can be used to
# access the wrapped value.
if self.eval('print scalar @{};'.format(name)).strip() == '1':
return '$'+name+'[0]'
return '@'+name
def set(self, var, value):
"""
Set the variable var to the given value.
Eventually, ``var`` is a reference to ``value``.
.. WARNING::
This method, although it doesn't start with an underscore, is
an internal method and not part of the interface. So, please do
not try to call it explicitly. Instead, use the polymake interface
as shown in the examples.
REMARK:
Polymake's user language is Perl. In Perl, if one wants to assign
the return value of a function to a variable, the syntax to do so
depends on the type of the return value. While this is fine in
compiled code, it seems quite awkward in user interaction.
To make this polymake pexpect interface a bit more user friendly,
we treat *all* variables as arrays. A scalar value (most typically
a reference) is thus interpreted as the only item in an array of
length one. It is, of course, possible to use the interface without
knowing these details.
EXAMPLES::
sage: c = polymake('cube(3)') # optional - polymake # indirect doctest
sage: d = polymake.cube(3) # optional - polymake
Equality is, for "big" objects such as polytopes, comparison by
identity::
sage: c == d # optional - polymake
False
However, the list of vertices is equal::
sage: c.VERTICES == d.VERTICES # optional - polymake
True
TESTS:
The following shows how polymake variables are wrapped in our interface.
It should, however, **never** be needed to do the following
*explicitly*::
sage: polymake.set('myvar', 'cube(3)') # optional - polymake
sage: polymake.get('$myvar[0]') # optional - polymake
'Polymake::polytope::Polytope__Rational=ARRAY(...)'
The following tests against :trac:`22658`::
sage: P = polymake.new_object("Polytope", FACETS=[[12, -2, -3, -5, -8, -13, -21, -34, -55], # optional - polymake
....: [0, 1, 0, 0, 0, 0, 0, 0, 0],
....: [0, 0, 0, 0, 0, 0, 0, 0, 1],
....: [0, 0, 0, 0, 0, 0, 0, 1, 0],
....: [0, 0, 0, 0, 0, 0, 1, 0, 0],
....: [0, 0, 0, 0, 0, 1, 0, 0, 0],
....: [0, 0, 0, 0, 1, 0, 0, 0, 0],
....: [0, 0, 0, 1, 0, 0, 0, 0, 0],
....: [0, 0, 1, 0, 0, 0, 0, 0, 0]])
sage: P.VERTICES # optional - polymake
1 6 0 0 0 0 0 0 0
1 0 4 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
1 0 0 12/5 0 0 0 0 0
1 0 0 0 0 0 0 0 12/55
1 0 0 0 0 0 0 6/17 0
1 0 0 0 0 0 4/7 0 0
1 0 0 0 0 12/13 0 0 0
1 0 0 0 3/2 0 0 0 0
sage: P.F_VECTOR # optional - polymake
9 36 84 126 126 84 36 9
"""
if isinstance(value, str):
value = value.strip().rstrip(';').strip()
cmd = "@{}{}({});".format(var, self._assign_symbol(), value)
self.eval(cmd)
def get(self, cmd):
"""
Return the string representation of an object in the polymake interface.
EXAMPLES::
sage: polymake.get('cube(3)') # optional - polymake
'Polymake::polytope::Polytope__Rational=ARRAY(...)'
Note that the above string representation is what polymake provides.
In our interface, we use what polymake calls a "description"::
sage: polymake('cube(3)') # optional - polymake
cube of dimension 3
"""
return self.eval("print {};".format(cmd)).strip()
def help(self, topic, pager=True):
"""
Displays polymake's help on a given topic, as a string.
INPUT:
- ``topic``, a string
- ``pager``, optional bool, default ``True``: When True, display help, otherwise return as a string.
EXAMPLES::
sage: print(polymake.help('Polytope', pager=False)) # optional - polymake # random
objects/Polytope:
Not necessarily bounded or unbounded polyhedron.
Nonetheless, the name "Polytope" is used for two reasons:
Firstly, combinatorially we always deal with polytopes; see the description of VERTICES_IN_FACETS for details.
The second reason is historical.
We use homogeneous coordinates, which is why Polytope is derived from Cone.
Note that a pointed polyhedron is projectively equivalent to a polytope.
Scalar is the numeric data type used for the coordinates.
In some cases, polymake expects user interaction to choose from
different available help topics. In these cases, a warning is given,
and the available help topics are displayed resp. printed, without
user interaction::
sage: polymake.help('TRIANGULATION') # optional - polymake # random
doctest:warning
...
UserWarning: Polymake expects user interaction. We abort and return the options that Polymake provides.
There are 5 help topics matching 'TRIANGULATION':
1: objects/Visualization/Visual::Polytope/methods/TRIANGULATION
2: objects/Visualization/Visual::PointConfiguration/methods/TRIANGULATION
3: objects/Cone/properties/Triangulation and volume/TRIANGULATION
4: objects/PointConfiguration/properties/Triangulation and volume/TRIANGULATION
5: objects/Polytope/properties/Triangulation and volume/TRIANGULATION
If an unknown help topic is requested, a :class:`PolymakeError`
results::
sage: polymake.help('Triangulation') # optional - polymake
Traceback (most recent call last):
...
PolymakeError: unknown help topic 'Triangulation'
"""
H = self.eval('help("{}");\n'.format(topic))
if not H:
raise PolymakeError("unknown help topic '{}'".format(topic))
if pager:
from IPython.core.page import page
page(H, start=0)
else:
return H
def _tab_completion(self):
r"""
Return a list of polymake function names.
..NOTE::
- The list of functions depends on the current application. The
result is cached, of course separately for each application.
- It is generally not the case that all the returned function
names can actually successfully be called.
TESTS::
sage: polymake.application('fan') # optional - polymake
sage: 'normal_fan' in dir(polymake) # optional - polymake # indirect doctest
True
sage: polymake.application('polytope') # optional - polymake
Since ``'normal_fan'`` is not defined in the polymake application
``'polytope'``, we now get::
sage: 'normal_fan' in dir(polymake) # optional - polymake
False
Global functions from ``'core'`` are available::
sage: 'show_credits' in dir(polymake) # optional - polymake
True
Global functions from ``'common'`` are available::
sage: 'lex_ordered' in dir(polymake) # optional - polymake
True
"""
if not self.is_running():
self._start()
try:
return self.__tab_completion[self._application]
except KeyError:
pass
s = self.eval("apropos '';").split('\n')
out = []
for name in s:
if (name.startswith("/common/functions/")
or name.startswith("/core/functions")
or name.startswith("/" + self._application + "/functions/")):
out.append(name.split("/")[-1])
self.__tab_completion[self._application] = sorted(out)
return self.__tab_completion[self._application]
# Polymake specific methods
def application(self, app):
"""
Change to a given polymake application.
INPUT:
- ``app``, a string, one of "common", "fulton", "group", "matroid", "topaz",
"fan", "graph", "ideal", "polytope", "tropical"
EXAMPLES:
We expose a computation that uses both the 'polytope' and the 'fan'
application of polymake. Let us start by defining a polytope `q` in
terms of inequalities. Polymake knows to compute the f- and h-vector
and finds that the polytope is very ample::
sage: q = polymake.new_object("Polytope", INEQUALITIES=[[5,-4,0,1],[-3,0,-4,1],[-2,1,0,0],[-4,4,4,-1],[0,0,1,0],[8,0,0,-1],[1,0,-1,0],[3,-1,0,0]]) # optional - polymake
sage: q.H_VECTOR # optional - polymake
1 5 5 1
sage: q.F_VECTOR # optional - polymake
8 14 8
sage: q.VERY_AMPLE # optional - polymake
true
In the application 'fan', polymake can now compute the normal fan
of `q` and its (primitive) rays::
sage: polymake.application('fan') # optional - polymake
sage: g = q.normal_fan() # optional - polymake
sage: g.RAYS # optional - polymake
-1 0 1/4
0 -1 1/4
1 0 0
1 1 -1/4
0 1 0
0 0 -1
0 -1 0
-1 0 0
sage: g.RAYS.primitive() # optional - polymake
-4 0 1
0 -4 1
1 0 0
4 4 -1
0 1 0
0 0 -1
0 -1 0
-1 0 0
Note that the list of functions available by tab completion depends
on the application.
TESTS:
Since 'trop_witness' is not defined in the polymake application 'polytope'
but only in 'tropical', the following shows the effect of changing
the application. ::
sage: polymake.application('polytope') # optional - polymake
sage: 'trop_witness' in dir(polymake) # optional - polymake
False
sage: polymake.application('tropical') # optional - polymake
sage: 'trop_witness' in dir(polymake) # optional - polymake
True
sage: polymake.application('polytope') # optional - polymake
sage: 'trop_witness' in dir(polymake) # optional - polymake
False
For completeness, we show what happens when asking for an application
that doesn't exist::
sage: polymake.application('killerapp') # optional - polymake
Traceback (most recent call last):
...
ValueError: Unknown polymake application 'killerapp'
Of course, a different error results when we send an explicit
command in polymake to change to an unknown application::
sage: polymake.eval('application "killerapp";') # optional - polymake
Traceback (most recent call last):
...
PolymakeError: Unknown application killerapp
"""
if app not in ["common", "fulton", "group", "matroid", "topaz", "fan", "graph", "ideal", "polytope", "tropical"]:
raise ValueError("Unknown polymake application '{}'".format(app))
self._application = app
self.eval('application "{}";'.format(app))
def new_object(self, name, *args, **kwds):
"""
Return a new instance of a given polymake type, with given positional or named arguments.
INPUT:
- ``name`` of a polymake class (potentially templated), as string.
- further positional or named arguments, to be passed to the constructor.
EXAMPLES::
sage: q = polymake.new_object("Polytope<Rational>", INEQUALITIES=[[4,-4,0,1],[-4,0,-4,1],[-2,1,0,0],[-4,4,4,-1],[0,0,1,0],[8,0,0,-1]]) # optional - polymake
sage: q.N_VERTICES # optional - polymake
4
sage: q.BOUNDED # optional - polymake
true
sage: q.VERTICES # optional - polymake
1 2 0 4
1 3 0 8
1 2 1 8
1 3 1 8
sage: q.full_typename() # optional - polymake
'Polytope<Rational>'
"""
try:
f = self.__new[name]
except AttributeError:
self.__new = {}
f = self.__new[name] = self._function_class()(self, "new {}".format(name))
except KeyError:
f = self.__new[name] = self._function_class()(self, "new {}".format(name))
return f(*args, **kwds)
########################################
## Elements
class PolymakeElement(ExtraTabCompletion, InterfaceElement):
"""
Elements in the polymake interface.
EXAMPLES:
We support all "big" polymake types, Perl arrays of length
different from one, and Perl scalars::
sage: p = polymake.rand_sphere(4, 20, seed=5) # optional - polymake
sage: p.typename() # optional - polymake
'Polytope'
sage: p # optional - polymake
Random spherical polytope of dimension 4; seed=5...
Now, one can work with that element in Python syntax, for example::
sage: p.VERTICES[2][2] # optional - polymake
1450479926727001/2251799813685248
"""
def _repr_(self):
"""
String representation of polymake elements.
EXAMPLES:
In the case of a "big" object, if polymake provides a description
of the object that is not longer than single line, it is used for
printing::
sage: p = polymake.rand_sphere(3, 12, seed=15) # optional - polymake
sage: p # optional - polymake
Random spherical polytope of dimension 3; seed=15...
sage: c = polymake.cube(4) # optional - polymake
sage: c # optional - polymake
cube of dimension 4
We use the print representation of scalars to display scalars::
sage: p.N_VERTICES # optional - polymake
12
The items of a Perl arrays are shown separated by commas::
sage: p.get_member('list_properties') # optional - polymake # random
POINTS, CONE_AMBIENT_DIM, BOUNDED, FEASIBLE, N_POINTS, POINTED,
CONE_DIM, FULL_DIM, LINEALITY_DIM, LINEALITY_SPACE,
COMBINATORIAL_DIM, AFFINE_HULL, VERTICES, N_VERTICES
We chose to print rule chains explicitly, so that the user doesn't
need to know how to list the rules using polymake commands::
sage: r = p.get_schedule('"H_VECTOR"') # optional - polymake
sage: r # optional - polymake # random
precondition : N_RAYS | N_INPUT_RAYS ( ppl.convex_hull.primal: FACETS, LINEAR_SPAN : RAYS | INPUT_RAYS )
sensitivity check for FacetPerm
ppl.convex_hull.primal: FACETS, LINEAR_SPAN : RAYS | INPUT_RAYS
RAYS_IN_FACETS : RAYS, FACETS
SIMPLICIAL : COMBINATORIAL_DIM, RAYS_IN_FACETS
N_FACETS : FACETS
precondition : COMBINATORIAL_DIM ( F_VECTOR : N_FACETS, N_RAYS, COMBINATORIAL_DIM )
F_VECTOR : N_FACETS, N_RAYS, COMBINATORIAL_DIM
precondition : SIMPLICIAL ( H_VECTOR : F_VECTOR )
H_VECTOR : F_VECTOR
sage: r.typeof() # optional - polymake
('Polymake::Core::Scheduler::RuleChain', 'ARRAY')
Similarly, polymake matrices and vectors are explicitly listed::
sage: c.VERTICES.typename() # optional - polymake
'Matrix'
sage: c.VERTICES[0].typename() # optional - polymake
'Vector'
sage: c.VERTICES # optional - polymake # random
1 -1 -1 -1 -1
1 1 -1 -1 -1
1 -1 1 -1 -1
1 1 1 -1 -1
1 -1 -1 1 -1
1 1 -1 1 -1
1 -1 1 1 -1
1 1 1 1 -1
1 -1 -1 -1 1
1 1 -1 -1 1
1 -1 1 -1 1
1 1 1 -1 1
1 -1 -1 1 1
1 1 -1 1 1
1 -1 1 1 1
1 1 1 1 1
sage: c.VERTICES[0] # optional - polymake
1 -1 -1 -1 -1
For other types, we simply use the print representation offered
by polymake::
sage: p.TWO_FACE_SIZES.typename() # optional - polymake
'Map'
sage: p.TWO_FACE_SIZES # optional - polymake
{(3 20)}
"""
T1, T2 = self.typeof()
P = self._check_valid()
name = self._name
if T1:
Temp = self.typename()
if Temp: