122122# ****************************************************************************
123123from collections .abc import Hashable
124124from copyreg import constructor as copyreg_constructor
125- import os
126- import shlex
127- from subprocess import Popen , PIPE
128- from warnings import warn
129125from functools import reduce
130126from io import IOBase , StringIO
127+ from subprocess import Popen , PIPE
128+ from warnings import warn
129+ import os
130+ import shlex
131131
132- from sage .misc .lazy_import import lazy_import
133- lazy_import ('sage.combinat.posets.posets' , 'FinitePoset' )
134132from sage .arith .misc import GCD as gcd
133+ from sage .features import PythonModule
134+ from sage .features .palp import PalpExecutable
135135from sage .features .databases import DatabaseReflexivePolytopes
136136from sage .geometry .cone import _ambient_space_point , integral_length
137- lazy_import ('sage.geometry.hasse_diagram' , 'lattice_from_incidences' )
138137from sage .geometry .point_collection import (PointCollection ,
139138 read_palp_point_collection )
140139from sage .geometry .toric_lattice import ToricLattice , ToricLattice_generic
141- lazy_import ('sage.groups.perm_gps.permgroup_named' , 'SymmetricGroup' )
142-
143- from sage .features import PythonModule
144- from sage .features .palp import PalpExecutable
145- lazy_import ('ppl' , ['C_Polyhedron' , 'Generator_System' , 'Linear_Expression' ],
146- feature = PythonModule ("ppl" , spkg = 'pplpy' , type = 'standard' ))
147- lazy_import ('ppl' , 'point' , as_ = 'PPL_point' ,
148- feature = PythonModule ("ppl" , spkg = 'pplpy' , type = 'standard' ))
149-
140+ from sage .geometry .convex_set import ConvexSet_compact
150141from sage .matrix .constructor import matrix
151- from sage .structure .element import Matrix
152142from sage .misc .cachefunc import cached_method
153143from sage .misc .flatten import flatten
144+ from sage .misc .lazy_import import lazy_import
154145from sage .misc .temporary_file import tmp_filename
155146from sage .modules .free_module_element import vector
156- lazy_import ('sage.numerical.mip' , 'MixedIntegerLinearProgram' )
157- lazy_import ("sage.plot.plot3d.index_face_set" , "IndexFaceSet" )
158- lazy_import ("sage.plot.plot3d.all" , ["line3d" , "point3d" ])
159- lazy_import ("sage.plot.plot3d.shapes2" , "text3d" )
160147from sage .rings .integer import Integer
161148from sage .rings .integer_ring import ZZ
162149from sage .rings .rational_field import QQ
163150from sage .sets .set import Set_generic
164- from sage .structure .sequence import Sequence
165- from sage .structure .sage_object import SageObject
151+ from sage .structure .element import Matrix
166152from sage .structure .richcmp import richcmp_method , richcmp
167- from sage .geometry .convex_set import ConvexSet_compact
153+ from sage .structure .sage_object import SageObject
154+ from sage .structure .sequence import Sequence
168155import sage .geometry .abc
169156
170157
158+ lazy_import ("sage.combinat.posets.posets" , 'FinitePoset' )
159+ lazy_import ("sage.geometry.hasse_diagram" , 'lattice_from_incidences' )
160+ lazy_import ("sage.groups.perm_gps.permgroup_named" , 'SymmetricGroup' )
161+ lazy_import ("sage.numerical.mip" , 'MixedIntegerLinearProgram' )
162+ lazy_import ("sage.plot.plot3d.all" , ["line3d" , "point3d" ])
163+ lazy_import ("sage.plot.plot3d.index_face_set" , "IndexFaceSet" )
164+ lazy_import ("sage.plot.plot3d.shapes2" , "text3d" )
165+ lazy_import ('ppl' , ['C_Polyhedron' , 'Generator_System' , 'Linear_Expression' ],
166+ feature = PythonModule ("ppl" , spkg = 'pplpy' , type = 'standard' ))
167+ lazy_import ('ppl' , 'point' , as_ = 'PPL_point' ,
168+ feature = PythonModule ("ppl" , spkg = 'pplpy' , type = 'standard' ))
169+
170+
171171class SetOfAllLatticePolytopesClass (Set_generic ):
172- def _repr_ (self ):
172+ def _repr_ (self ) -> str :
173173 r"""
174174 Return a string representation.
175175
@@ -316,10 +316,9 @@ def LatticePolytope(data, compute_vertices=True, n=0, lattice=None):
316316 (lattice is None or lattice is data .module ())):
317317 return LatticePolytopeClass (data , compute_vertices )
318318 if isinstance (data , str ):
319- f = open (data )
320- skip_palp_matrix (f , n )
321- data = read_palp_point_collection (data )
322- f .close ()
319+ with open (data ) as f :
320+ skip_palp_matrix (f , n )
321+ data = read_palp_point_collection (data )
323322 if isinstance (data , (IOBase , StringIO )):
324323 data = read_palp_point_collection (data )
325324 if not isinstance (data , PointCollection ) and not isinstance (data , (list , tuple )):
@@ -402,12 +401,13 @@ def ReflexivePolytope(dim, n):
402401 if n > 15 :
403402 raise ValueError ("there are only 16 reflexive polygons!" )
404403 return ReflexivePolytopes (2 )[n ]
405- elif dim == 3 :
404+
405+ if dim == 3 :
406406 if n > 4318 :
407407 raise ValueError ("there are only 4319 reflexive 3-polytopes!" )
408408 return ReflexivePolytopes (3 )[n ]
409- else :
410- raise NotImplementedError ("only 2- and 3-dimensional reflexive polytopes are available!" )
409+
410+ raise NotImplementedError ("only 2- and 3-dimensional reflexive polytopes are available!" )
411411
412412
413413# Sequences of reflexive polytopes
@@ -536,7 +536,7 @@ class LatticePolytopeClass(ConvexSet_compact, Hashable, sage.geometry.abc.Lattic
536536
537537 def __init__ (self , points = None , compute_vertices = None ,
538538 ambient = None , ambient_vertex_indices = None ,
539- ambient_facet_indices = None ):
539+ ambient_facet_indices = None ) -> None :
540540 r"""
541541 Construct a lattice polytope.
542542
@@ -591,7 +591,7 @@ def _sage_input_(self, sib, coerced):
591591 raise NotImplementedError
592592 return sib .name ('LatticePolytope' )(sib (self ._vertices ), compute_vertices = False )
593593
594- def __contains__ (self , point ):
594+ def __contains__ (self , point ) -> bool :
595595 r"""
596596 Check if ``point`` is contained in ``self``.
597597
@@ -610,7 +610,7 @@ def __contains__(self, point):
610610 """
611611 return self ._contains (point )
612612
613- def __richcmp__ (self , other , op ):
613+ def __richcmp__ (self , other , op ) -> bool :
614614 r"""
615615 Compare ``self`` with ``other``.
616616
@@ -676,7 +676,7 @@ def __richcmp__(self, other, op):
676676 return richcmp (self ._vertices , other ._vertices , op )
677677
678678 @cached_method
679- def __hash__ (self ):
679+ def __hash__ (self ) -> int :
680680 r"""
681681 Return the hash of ``self``.
682682
@@ -725,7 +725,7 @@ def __setstate__(self, state):
725725 """
726726 self .__dict__ .update (state )
727727
728- def _compute_embedding (self ):
728+ def _compute_embedding (self ) -> None :
729729 r"""
730730 Compute embedding data for this polytope.
731731
@@ -845,7 +845,7 @@ def _compute_hodge_numbers(self):
845845 """
846846 raise NotImplementedError ("use nef_partitions(hodge_numbers=True)!" )
847847
848- def _contains (self , point , region = 'whole polytope' ):
848+ def _contains (self , point , region = 'whole polytope' ) -> bool :
849849 r"""
850850 Check if ``point`` is contained in ``self``.
851851
@@ -941,7 +941,7 @@ def _embed(self, data):
941941 return M (self ._embedding_matrix * vector (QQ , data ) +
942942 self ._shift_vector )
943943
944- def _latex_ (self ):
944+ def _latex_ (self ) -> str :
945945 r"""
946946 Return the latex representation of ``self``.
947947
@@ -966,7 +966,7 @@ def _latex_(self):
966966 result += "_{%d}" % self .index ()
967967 return result
968968
969- def _palp (self , command , reduce_dimension = False ):
969+ def _palp (self , command , reduce_dimension = False ) -> str :
970970 r"""
971971 Run ``command`` on vertices of this polytope.
972972
@@ -3570,7 +3570,7 @@ def plot3d(self,
35703570 vlabels = list (range (len (vertices )))
35713571 for i , v in enumerate (vertices ):
35723572 pplot += text3d (vlabels [i ], bc + index_shift * (v - bc ), rgbcolor = vindex_color )
3573- if show_points and len ( points ) :
3573+ if show_points and points :
35743574 pplot += point3d (points , size = point_size , rgbcolor = point_color )
35753575 if show_pindices :
35763576 for i , p in enumerate (points ):
@@ -3724,12 +3724,12 @@ def points(self, *args, **kwds):
37243724 self ._points = points = self ._vertices
37253725 if self .dim () == 1 :
37263726 v = points [1 ] - points [0 ]
3727- l = gcd (v )
3728- if l > 1 :
3729- v = M (v .base_extend (QQ ) / l )
3727+ l_gcd = gcd (v )
3728+ if l_gcd > 1 :
3729+ v = M (v .base_extend (QQ ) / l_gcd )
37303730 points = list (points )
37313731 current = points [0 ]
3732- for i in range (l - 1 ):
3732+ for i in range (l_gcd - 1 ):
37333733 current += v
37343734 current .set_immutable ()
37353735 points .append (current )
@@ -4000,16 +4000,16 @@ def traverse_boundary(self):
40004000 if self .dim () != 2 :
40014001 raise ValueError ("Boundary can be traversed only for 2-polytopes!" )
40024002 zero_faces = set (self .faces (0 ))
4003- l = [self .faces (0 )[0 ]]
4004- prev , next = sorted (zero_faces .intersection (l [0 ].adjacent ()))
4005- l = [prev , l [0 ], next ]
4006- while len (l ) < self .nvertices ():
4007- prev , next = zero_faces .intersection (l [- 1 ].adjacent ())
4008- if next == l [- 2 ]:
4003+ li = [self .faces (0 )[0 ]]
4004+ prev , next = sorted (zero_faces .intersection (li [0 ].adjacent ()))
4005+ li = [prev , li [0 ], next ]
4006+ while len (li ) < self .nvertices ():
4007+ prev , next = zero_faces .intersection (li [- 1 ].adjacent ())
4008+ if next == li [- 2 ]:
40094009 next = prev
4010- l .append (next )
4010+ li .append (next )
40114011 vertex_to_index = {v : i for i , v in enumerate (self .vertices ())}
4012- return [vertex_to_index [v .vertex (0 )] for v in l ]
4012+ return [vertex_to_index [v .vertex (0 )] for v in li ]
40134013
40144014 def vertex (self , i ):
40154015 r"""
@@ -5235,11 +5235,10 @@ def _read_poly_x_incidences(data, dim):
52355235 f[d][i]: sum_j Incidence(i'th dim-d-face, j-th facet) x 2^j
52365236 f[0]: 0011 0101 1010 1100
52375237 f[1]: 0001 0010 0100 1000
5238- sage: f = open(result_name)
5239- sage: l = f.readline()
5240- sage: lattice_polytope._read_poly_x_incidences(f, 2)
5238+ sage: with open(result_name) as f:
5239+ ....: l = f.readline()
5240+ ....: lattice_polytope._read_poly_x_incidences(f, 2)
52415241 [[[3], [0], [2], [1]], [[0, 3], [2, 3], [0, 1], [1, 2]]]
5242- sage: f.close()
52435242 sage: os.remove(result_name)
52445243 """
52455244 data .readline ()
@@ -5265,9 +5264,9 @@ def all_cached_data(polytopes):
52655264 Compute all cached data for all given ``polytopes`` and
52665265 their polars.
52675266
5268- This functions does it MUCH faster than member functions of
5267+ This function does it MUCH faster than member functions of
52695268 ``LatticePolytope`` during the first run. So it is recommended to
5270- use this functions if you work with big sets of data. None of the
5269+ use this function if you work with big sets of data. None of the
52715270 polytopes in the given sequence should be constructed as the polar
52725271 polytope to another one.
52735272
@@ -5334,14 +5333,13 @@ def all_nef_partitions(polytopes, keep_symmetric=False):
53345333 if keep_symmetric :
53355334 keys += " -s"
53365335 result_name = _palp ("nef.x -f " + keys , polytopes )
5337- result = open (result_name )
5338- for p in polytopes :
5339- if not p .is_reflexive ():
5340- raise ValueError ("nef-partitions can be computed for reflexive "
5341- "polytopes only" )
5342- p ._read_nef_partitions (result )
5343- p ._nef_partitions_s = keep_symmetric
5344- result .close ()
5336+ with open (result_name ) as result :
5337+ for p in polytopes :
5338+ if not p .is_reflexive ():
5339+ raise ValueError ("nef-partitions can be computed for reflexive "
5340+ "polytopes only" )
5341+ p ._read_nef_partitions (result )
5342+ p ._nef_partitions_s = keep_symmetric
53455343 os .remove (result_name )
53465344
53475345
@@ -5422,10 +5420,9 @@ def all_polars(polytopes):
54225420 3-d reflexive polytope in 3-d lattice N
54235421 """
54245422 result_name = _palp ("poly.x -fe" , polytopes )
5425- result = open (result_name )
5426- for p in polytopes :
5427- p ._read_equations (result )
5428- result .close ()
5423+ with open (result_name ) as result :
5424+ for p in polytopes :
5425+ p ._read_equations (result )
54295426 os .remove (result_name )
54305427
54315428
0 commit comments