Interface to polymake

class sage.interfaces.polymake.Polymake(script_subdirectory=None, logfile=None, server=None, server_tmpdir=None, seed=None, command=None)

Bases: sage.interfaces.tab_completion.ExtraTabCompletion, sage.interfaces.expect.Expect

Interface to the polymake interpreter.

In order to use this interface, you need to either install the optional polymake package for Sage, or install polymake system-wide on your computer.

Type polymake.[tab] for a list of most functions available from your polymake install. Type polymake.Function? for polymake’s help about a given Function Type polymake(...) to create a new Magma object, and polymake.eval(...) to run a string using polymake and get the result back as a string.

EXAMPLES:

sage: p = polymake.rand_sphere(4, 20, seed=5)       # optional - polymake
sage: p                                             # optional - polymake
Random spherical polytope of dimension 4; seed=5...
sage: set_verbose(3)
sage: p.H_VECTOR                                    # optional - polymake
used package ppl
  The Parma Polyhedra Library (PPL): A C++ library for convex polyhedra
  and other numerical abstractions.
  http://www.cs.unipr.it/ppl/
1 16 47 16 1
sage: set_verbose(0)
sage: p.F_VECTOR                                    # optional - polymake
20 101 162 81
sage: print(p.F_VECTOR._sage_doc_())                # optional - polymake # random
property_types/Algebraic Types/Vector:
 A type for vectors with entries of type Element.

 You can perform algebraic operations such as addition or scalar multiplication.

 You can create a new Vector by entering its elements, e.g.:
    $v = new Vector<Int>(1,2,3);
 or
    $v = new Vector<Int>([1,2,3]);
_eval_line(line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=True, **kwds)

Evaluate a command.

INPUT:

  • line, a command (string) to be evaluated
  • allow_use_file (optional bool, default True), whether or not to use a file if the line is very long.
  • wait_for_prompt (optional, default True), whether or not to wait before polymake returns a prompt. If it is a string, it is considered as alternative prompt to be waited for.
  • restart_if_needed (optional bool, default True), whether or not to restart polymake in case something goes wrong
  • further optional arguments (e.g., timeout) that will be passed to pexpect.pty_spawn.spawn.expect(). Note that they are ignored if the line is too long and thus is evaluated via a file. So, if a timeout is defined, it should be accompanied by allow_use_file=False.

Different reaction types of polymake, including warnings, comments, errors, request for user interaction, and yielding a continuation prompt, are taken into account.

Usually, this method is indirectly called via eval().

EXAMPLES:

sage: p = polymake.cube(3)              # optional - polymake  # indirect doctest

Here we see that remarks printed by polymake are displayed if the verbosity is positive:

sage: set_verbose(1)
sage: p.N_LATTICE_POINTS                # optional - polymake
used package latte
  LattE (Lattice point Enumeration) is a computer software dedicated to the
  problems of counting lattice points and integration inside convex polytopes.
  Copyright by Matthias Koeppe, Jesus A. De Loera and others.
  http://www.math.ucdavis.edu/~latte/
27
sage: set_verbose(0)

If polymake raises an error, the polymake interface raises a PolymakeError:

sage: polymake.eval('FOOBAR(3);')       # optional - polymake
Traceback (most recent call last):
...
PolymakeError: Undefined subroutine &Polymake::User::FOOBAR called...

If a command is incomplete, then polymake returns a continuation prompt. In that case, we raise an error:

sage: polymake.eval('print 3')          # optional - polymake
Traceback (most recent call last):
...
SyntaxError: Incomplete polymake command 'print 3'
sage: polymake.eval('print 3;')         # optional - polymake
'3'

However, if the command contains line breaks but eventually is complete, no error is raised:

sage: print(polymake.eval('$tmp="abc";\nprint $tmp;'))  # optional - polymake
abc

When requesting help, polymake sometimes expect the user to choose from a list. In that situation, we abort with a warning, and show the list from which the user can chose; we could demonstrate this using the help() method, but here we use an explicit code evaluation:

sage: print(polymake.eval('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/Cone/properties/Triangulation and volume/TRIANGULATION
2: objects/Polytope/properties/Triangulation and volume/TRIANGULATION
3: objects/Visualization/Visual::PointConfiguration/methods/TRIANGULATION
4: objects/Visualization/Visual::Polytope/methods/TRIANGULATION
5: objects/PointConfiguration/properties/Triangulation and volume/TRIANGULATION

By default, we just wait until polymake returns a result. However, it is possible to explicitly set a timeout. The following usually does work in an interactive session and often in doc tests, too. However, sometimes it hangs, and therefore we remove it from the tests, for now:

sage: c = polymake.cube(15)             # optional - polymake
sage: polymake.eval('print {}->F_VECTOR;'.format(c.name()), timeout=1) # optional - polymake # not tested
Traceback (most recent call last):
...
RuntimeError: Polymake fails to respond timely

We verify that after the timeout, polymake is still able to give answers:

sage: c                                 # optional - polymake
cube of dimension 15
sage: c.N_VERTICES                      # optional - polymake
32768

Note, however, that the recovery after a timeout is not perfect. It may happen that in some situation the interface collapses and thus polymake would automatically be restarted, thereby losing all data that have been computed before.

application(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
1

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.

clear(var)

Clear the variable named var.

NOTE:

This is implicitly done when deleting an element in the interface.

console()

Raise an error, pointing to interact() and polymake_console().

EXAMPLES:

sage: polymake.console()
Traceback (most recent call last):
...
NotImplementedError: Please use polymake_console() function or the .interact() method
function_call(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...
get(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
help(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 PolymakeError results:

sage: polymake.help('Triangulation')      # optional - polymake
Traceback (most recent call last):
...
PolymakeError: unknown help topic 'Triangulation'
new_object(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
1
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>'
set(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
version()

Version of the polymake installation.

EXAMPLES:

sage: polymake.version()               # optional - polymake
'3...'
class sage.interfaces.polymake.PolymakeElement(parent, value, is_name=False, name=None)

Bases: sage.interfaces.tab_completion.ExtraTabCompletion, sage.interfaces.expect.ExpectElement

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
-3319173990813887/4503599627370496
bool()

Return whether this polymake element is equal to True.

EXAMPLES:

sage: from sage.interfaces.polymake import polymake
sage: polymake(0).bool()                # optional polymake
False
sage: polymake(1).bool()                # optional polymake
True
full_typename()

The name of the specialised type of this element.

EXAMPLES:

sage: c = polymake.cube(4)          # optional - polymake
sage: c.full_typename()             # optional - polymake
'Polytope<Rational>'
sage: c.VERTICES.full_typename()    # optional - polymake
'Matrix<Rational, NonSymmetric>'
get_member(attrname)

Get a member/property of this element.

NOTE:

Normally, it should be possible to just access the property in the usual Python syntax for attribute access. However, if that fails, one can request the member explicitly.

EXAMPLES:

sage: p = polymake.rand_sphere(4, 20, seed=5)    # optional - polymake

Normally, a property would be accessed as follows:

sage: p.F_VECTOR                                # optional - polymake
20 101 162 81

However, explicit access is possible as well:

sage: p.get_member('F_VECTOR')                  # optional - polymake
20 101 162 81

In some cases, the explicit access works better:

sage: p.type                                    # optional - polymake
Member function 'type' of Polymake::polytope::Polytope__Rational object
sage: p.get_member('type')                      # optional - polymake
Polytope<Rational>[SAGE...]
sage: p.get_member('type').get_member('name')   # optional - polymake
Polytope

Note that in the last example calling the erroneously constructed member function type still works:

sage: p.type()                                  # optional - polymake
Polytope<Rational>[SAGE...]
get_member_function(attrname)

Request a member function of this element.

NOTE:

It is not checked whether a member function with the given name exists.

EXAMPLES:

sage: c = polymake.cube(2)                                  # optional - polymake
sage: c.contains                                            # optional - polymake
Member function 'contains' of Polymake::polytope::Polytope__Rational object
sage: V = polymake.new_object('Vector', [1,0,0])            # optional - polymake
sage: V                                                     # optional - polymake
1 0 0
sage: c.contains(V)                                         # optional - polymake
1

Whether a member function of the given name actually exists for that object will only be clear when calling it:

sage: c.get_member_function('foo')                          # optional - polymake
Member function 'foo' of Polymake::polytope::Polytope__Rational object
sage: c.get_member_function('foo')()                        # optional - polymake
Traceback (most recent call last):
...
TypeError: Can't locate object method "foo" via package "Polymake::polytope::Polytope__Rational" at input line 1.
known_properties()

List the names of properties that have been computed so far on this element.

NOTE:

This is in many cases equivalent to use polymake’s list_properties, which returns a blank separated string representation of the list of properties. However, on some elements, list_properties would simply result in an error.

EXAMPLES:

sage: c = polymake.cube(4)                      # optional - polymake
sage: c.known_properties()                      # optional - polymake
['AFFINE_HULL',
 'BOUNDED',
 'CONE_AMBIENT_DIM',
 'CONE_DIM',
...
 'VERTICES_IN_FACETS']
sage: c.list_properties()                       # optional - polymake
CONE_AMBIENT_DIM, CONE_DIM, FACETS, AFFINE_HULL, VERTICES_IN_FACETS,
BOUNDED...

A computation can change the list of known properties:

sage: c.F_VECTOR                                # optional - polymake
16 32 24 8
sage: c.known_properties()                      # optional - polymake
['AFFINE_HULL',
 'BOUNDED',
 'COMBINATORIAL_DIM',
 'CONE_AMBIENT_DIM',
 'CONE_DIM',
 'DUAL_H_VECTOR',
 'FACETS',
 'FAR_FACE',
 'FEASIBLE',
 'FULL_DIM',
 'F_VECTOR',
 'GRAPH',
 'LINEALITY_DIM',
 'LINEALITY_SPACE',
 'N_FACETS',
 'N_VERTICES',
 'POINTED',
 'SIMPLE',
 'SIMPLICIAL',
 'VERTICES',
 'VERTICES_IN_FACETS']
qualified_typename()

The qualified name of the type of this element.

EXAMPLES:

sage: c = polymake.cube(4)              # optional - polymake
sage: c.qualified_typename()            # optional - polymake
'polytope::Polytope<Rational>'
sage: c.VERTICES.qualified_typename()   # optional - polymake
'common::Matrix<Rational, NonSymmetric>'
typename()

The name of the underlying base type of this element in polymake.

EXAMPLES:

sage: c = polymake.cube(4)          # optional - polymake
sage: c.typename()                  # optional - polymake
'Polytope'
sage: c.VERTICES.typename()         # optional - polymake
'Matrix'
typeof()

Returns the type of a polymake “big” object, and its underlying Perl type.

NOTE:

This is mainly for internal use.

EXAMPLES:

sage: p = polymake.rand_sphere(3, 13, seed=12)               # optional - polymake
sage: p.typeof()                                            # optional - polymake
('Polymake::polytope::Polytope__Rational', 'ARRAY')
sage: p.VERTICES.typeof()                                   # optional - polymake
('Polymake::common::Matrix_A_Rational_I_NonSymmetric_Z', 'ARRAY')
sage: p.get_schedule("F_VECTOR").typeof()                   # optional - polymake
('Polymake::Core::Scheduler::RuleChain', 'ARRAY')

On “small” objects, it just returns empty strings:

sage: p.N_VERTICES.typeof()                                 # optional - polymake
('', '')
sage: p.list_properties().typeof()                          # optional - polymake
('', '')
exception sage.interfaces.polymake.PolymakeError

Bases: exceptions.RuntimeError

Raised if polymake yields an error message.

class sage.interfaces.polymake.PolymakeFunctionElement(obj, name, memberfunction=False)

Bases: sage.interfaces.expect.FunctionElement

A callable (function or member function) bound to a polymake element.

EXAMPLES:

sage: c = polymake.cube(2)                          # optional - polymake
sage: V = polymake.new_object('Vector', [1,0,0])    # optional - polymake
sage: V                                             # optional - polymake
1 0 0
sage: c.contains                                    # optional - polymake
Member function 'contains' of Polymake::polytope::Polytope__Rational object
sage: c.contains(V)                                 # optional - polymake
1
sage.interfaces.polymake.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 >
sage.interfaces.polymake.reduce_load_Polymake()

Returns the polymake interface object defined in sage.interfaces.polymake.

EXAMPLES:

sage: from sage.interfaces.polymake import reduce_load_Polymake
sage: reduce_load_Polymake()
Polymake