Skip to content

Commit

Permalink
more cython-lint suggested fixes in cython/core
Browse files Browse the repository at this point in the history
  • Loading branch information
fchapoton committed Aug 12, 2023
1 parent 223badf commit 520ed04
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 93 deletions.
6 changes: 4 additions & 2 deletions cython/core/abelian_group.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,9 @@ cdef class PresentationMatrix():
"""
A sparse representation of the presentation matrix of an abelian group.
"""
cdef rows, cols, _row_support, _col_support, _entries, _units, dead_columns
cdef int rows, cols
cdef dict _row_support, _col_support, _entries
cdef set _units, dead_columns

def __init__(self, rows, cols):
self.rows = rows
Expand Down Expand Up @@ -229,7 +231,7 @@ cdef class PresentationMatrix():
Continue until no units remain. When a generator is removed,
remember its column index.
"""
cdef temp, m, i, j, k, l
cdef int temp, m, i, j, k, l
while len(self._units) > 0:
for i, j in self._units:
break
Expand Down
28 changes: 14 additions & 14 deletions cython/core/basic.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ except ImportError:
from .matrix import matrix, vector, SimpleMatrix
from . import number

## SnapPy components
# SnapPy components
import spherogram
from .manifolds import __path__ as manifold_paths
from . import database
Expand Down Expand Up @@ -322,7 +322,7 @@ def set_rand_seed(seed):
# Ptolemy utility functions
# convert and free an identification of variables structure
cdef convert_and_free_identification_of_variables(
Identification_of_variables c_vars):
Identification_of_variables c_vars):
var_list = []

if c_vars.variables:
Expand All @@ -337,13 +337,13 @@ cdef convert_and_free_identification_of_variables(

# convert and free an integer matrix from C
cdef convert_and_free_integer_matrix(
Integer_matrix_with_explanations c_matrix):
Integer_matrix_with_explanations c_matrix):
if not c_matrix.entries:
return []

python_matrix = [
[ c_matrix.entries[i][j] for j in range(c_matrix.num_cols)]
for i in range(c_matrix.num_rows)]
python_matrix = [[c_matrix.entries[i][j]
for j in range(c_matrix.num_cols)]
for i in range(c_matrix.num_rows)]

explain_row = []

Expand Down Expand Up @@ -452,7 +452,7 @@ cdef Real2gen_direct(Real R):
divisible by 32.
"""
IF HIGH_PRECISION: # Real = qd_real
IF HIGH_PRECISION: # Real = qd_real
cdef double* qd = <double*>&R
cdef int i
# The value of a qd_real is the sum of the values of its four doubles.
Expand All @@ -476,7 +476,7 @@ ctypedef object (*func_real_to_obj)(Real)
# Convert Real to gen in an appropriate manner for this environment
cdef func_real_to_obj Real2gen

if hasattr(pari, '_real_coerced_to_bits_prec'): # Cypari
if hasattr(pari, '_real_coerced_to_bits_prec'): # Cypari
Real2gen = Real2gen_direct
else:
Real2gen = Real2gen_string
Expand Down Expand Up @@ -557,31 +557,31 @@ cdef double Real2double(Real R):

cdef Complex gen2Complex(g):
cdef Complex result
IF HIGH_PRECISION: # Real = qd_real; 212 bits of precision
IF HIGH_PRECISION: # Real = qd_real; 212 bits of precision
cdef py_string
cdef char* c_string
cdef Real real_part, imag_part
old_precision = pari.set_real_precision(64)

py_string = to_byte_str(str(g.real()).replace(' E','E')) # save a reference
py_string = to_byte_str(str(g.real()).replace(' E','E')) # save a reference
c_string = py_string
real_part = <Real>c_string
py_string = to_byte_str(str(g.imag()).replace(' E','E')) # save a reference
py_string = to_byte_str(str(g.imag()).replace(' E','E')) # save a reference
c_string = py_string
imag_part = <Real>c_string
result.real, result.imag = real_part, imag_part

pari.set_real_precision(old_precision)
ELSE: # Real = double
ELSE: # Real = double
result.real, result.imag = g.real(), g.imag()
return result

#IF HIGH_PRECISION:
# IF HIGH_PRECISION:
cdef Real2Number(Real R):
return Number(Real2gen(R))
cdef Complex2Number(Complex C):
return Number(Complex2gen(C))
#ELSE:
# ELSE:
# cdef Real2Number(Real R):
# return Number(R)
# cdef Complex2Number(Complex C):
Expand Down
65 changes: 33 additions & 32 deletions cython/core/dirichlet.pyx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# Dirichlet Domains

cdef (WEPolyhedron*, int) get_generators_from_bytes(
data_bytes, double vertex_epsilon,
displacement, centroid_at_origin,
maximize_injectivity_radius,
include_words)except*:
cdef (WEPolyhedron*, int) get_generators_from_bytes(data_bytes,
double vertex_epsilon,
displacement,
centroid_at_origin,
maximize_injectivity_radius,
include_words) except *:

cdef int num_gens

Expand All @@ -25,7 +26,7 @@ cdef (WEPolyhedron*, int) get_generators_from_bytes(
for i in range(num_gens):
for j in range(4):
for k in range(4):
num_string = nums.pop(0) # save a reference
num_string = nums.pop(0) # save a reference
generators[i][j][k] = <Real_struct>Real_from_string(
<char*>num_string)
elif len(nums) == 8*num_gens:
Expand All @@ -36,10 +37,10 @@ cdef (WEPolyhedron*, int) get_generators_from_bytes(
temp_gens[i].parity = orientation_preserving
for j in range(2):
for k in range(2):
num_string = nums.pop(0) # save a reference
num_string = nums.pop(0) # save a reference
temp_gens[i].matrix[j][k].real = Real_from_string(
<char*>num_string)
num_string = nums.pop(0) # save a reference
num_string = nums.pop(0) # save a reference
temp_gens[i].matrix[j][k].imag = Real_from_string(
<char*>num_string)
Moebius_array_to_O31_array(temp_gens, generators, num_gens)
Expand All @@ -63,12 +64,12 @@ cdef (WEPolyhedron*, int) get_generators_from_bytes(
free(generators)
return dirichlet_domain, num_gens

cdef WEPolyhedron* dirichlet_from_O31_matrix_list(
matrices,
double vertex_epsilon,
displacement, centroid_at_origin,
maximize_injectivity_radius,
include_words)except*:
cdef WEPolyhedron* dirichlet_from_O31_matrix_list(matrices,
double vertex_epsilon,
displacement,
centroid_at_origin,
maximize_injectivity_radius,
include_words) except *:

cdef WEPolyhedron* c_dirichlet_domain
cdef O31Matrix* generators
Expand All @@ -81,7 +82,7 @@ cdef WEPolyhedron* dirichlet_from_O31_matrix_list(
generators[i][j][k] = <Real_struct>Object2Real(A[j,k])
if not O31_determinants_OK(generators, num_gens, det_error_epsilon):
raise ValueError('The data given do not have the '
'right determinants.')
'right determinants.')
cdef double c_displacement[3]
for n from 0 <= n < 3:
c_displacement[n] = <double>displacement[n]
Expand All @@ -105,7 +106,7 @@ cdef class CDirichletDomain():
def __cinit__(self,
Manifold manifold=None,
vertex_epsilon=default_vertex_epsilon,
displacement=[0.0, 0.0, 0.0],
displacement=None,
centroid_at_origin=True,
maximize_injectivity_radius=True,
include_words = False,
Expand All @@ -114,6 +115,8 @@ cdef class CDirichletDomain():
O31_generators=None,
str manifold_name='unnamed'):
cdef double c_displacement[3]
if displacement is None:
displacement = [0.0, 0.0, 0.0]
self.c_dirichlet_domain = NULL
if generator_file != '':
with open(generator_file, mode='rb') as input_file:
Expand Down Expand Up @@ -231,10 +234,10 @@ cdef class CDirichletDomain():
return self._number_(radius)

def length_spectrum_dicts(self, cutoff_length=1.0,
full_rigor=True,
multiplicities=True,
user_radius=0.0,
grouped=True):
full_rigor=True,
multiplicities=True,
user_radius=0.0,
grouped=True):
"""
Return a list of info objects describing the short
geodesics up to the specified cutoff length. The keys are
Expand Down Expand Up @@ -280,7 +283,7 @@ cdef class CDirichletDomain():
for n from 0 <= n < num_lengths:
length = Complex2Number(geodesics[n].length)
its_matrix = matrix([[self._number_(Real2Number(<Real>geodesics[n].matrix[i][j]))
for j in range(4)] for i in range(4)] )
for j in range(4)] for i in range(4)] )
d = {
"length" : self._number_(length),
"parity" : MatrixParity[geodesics[n].parity],
Expand Down Expand Up @@ -338,8 +341,8 @@ cdef class CDirichletDomain():
{'position': ( self._number_(Real2Number(<Real>vertex.x[1])),
self._number_(Real2Number(<Real>vertex.x[2])),
self._number_(Real2Number(<Real>vertex.x[3])) ),
'ideal': bool(vertex.ideal),
'vertex_class' : vertex.v_class.index
'ideal': bool(vertex.ideal),
'vertex_class' : vertex.v_class.index
})
vertex = vertex.next
return vertices
Expand Down Expand Up @@ -480,18 +483,17 @@ cdef class CDirichletDomain():
"""

cdef WEEdge *edge = &self.c_dirichlet_domain.edge_list_begin
edges = []
cdef list edges = []

vertex_to_index = self._vertex_to_index_dict()

edge = edge.next
while edge != &self.c_dirichlet_domain.edge_list_end:

edges.append(
{ 'tail_vertex_index' : vertex_to_index[<size_t>(edge.v[0])],
'tip_vertex_index' : vertex_to_index[<size_t>(edge.v[1])],
'edge_class' : edge.e_class.index
})
{'tail_vertex_index': vertex_to_index[<size_t>(edge.v[0])],
'tip_vertex_index': vertex_to_index[<size_t>(edge.v[1])],
'edge_class': edge.e_class.index})

edge = edge.next

Expand All @@ -500,10 +502,9 @@ cdef class CDirichletDomain():
def view(self):
if PolyhedronViewer:
return ViewerWindow(PolyhedronViewer, facedicts=self.face_list(),
title='Dirichlet Domain of %s' % self.manifold_name)
else:
raise RuntimeError('The PolyhedronViewer class '
'was not imported.')
title=f'Dirichlet Domain of {self.manifold_name}')
raise RuntimeError('The PolyhedronViewer class '
'was not imported.')

def manifold(self):
"""
Expand Down
14 changes: 10 additions & 4 deletions cython/core/fundamental_group.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ Alphabet = '$abcdefghijklmnopqrstuvwxyzZYXWVUTSRQPONMLKJIHGFEDCBA'

# Helper functions for manipulating fg. words


def inverse_list_word(word):
return [ -x for x in word[::-1] ]


def reduce_list_word(word):
"""
Cancels inverse generators.
Expand All @@ -20,6 +22,7 @@ def reduce_list_word(word):
result.append(letter)
return result


cdef c_word_as_int_list(int *word):
cdef int n = 0
word_list = []
Expand Down Expand Up @@ -125,7 +128,6 @@ cdef class CFundamentalGroup():
','.join(self.generators()),
'\n '.join(self.relators()))


def num_generators(self):
"""
Return the number of generators for the presentation.
Expand Down Expand Up @@ -197,7 +199,7 @@ cdef class CFundamentalGroup():

while len(moves) > 0:
a = moves.pop(0)
if a >= len(words): # new generator added
if a >= len(words): # new generator added
n = moves.index(a) # end symbol location
# word is the expression of the new generator in terms
# of the old ones
Expand All @@ -210,9 +212,9 @@ cdef class CFundamentalGroup():
if a == b: # generator removed
words[a] = words[-1]
words = words[:-1]
elif a == -b: # invert generator
elif a == -b: # invert generator
words[a] = inverse_list_word(words[a])
else: #handle slide
else: # handle slide
A, B = words[abs(a)], words[abs(b)]
if a*b < 0:
B = inverse_list_word(B)
Expand Down Expand Up @@ -473,9 +475,11 @@ class FundamentalGroup(CFundamentalGroup):
longitude(n) --> word representing the longitude on cusp #n
"""


if _within_sage:
FundamentalGroup.__bases__ += (sage.structure.sage_object.SageObject,)


# Holonomy Groups
cdef class CHolonomyGroup(CFundamentalGroup):
def _matrices(self, word):
Expand Down Expand Up @@ -527,6 +531,7 @@ cdef class CHolonomyGroup(CFundamentalGroup):
"""
return self._matrices(word)[2]


class HolonomyGroup(CHolonomyGroup):
"""
A FundamentalGroup represents a presentation of the fundamental
Expand Down Expand Up @@ -585,5 +590,6 @@ class HolonomyGroup(CHolonomyGroup):
def _number_(n):
return number.number_to_native_number(n)


if _within_sage:
HolonomyGroup.__bases__ += (sage.structure.sage_object.SageObject,)
8 changes: 4 additions & 4 deletions cython/core/manifold.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -412,10 +412,10 @@ cdef class Manifold(Triangulation):
return filled

def fundamental_group(self,
simplify_presentation = True,
fillings_may_affect_generators = True,
minimize_number_of_generators = True,
try_hard_to_shorten_relators = True):
simplify_presentation = True,
fillings_may_affect_generators = True,
minimize_number_of_generators = True,
try_hard_to_shorten_relators = True):
"""
Return a HolonomyGroup representing the fundamental group of
the manifold, together with its holonomy representation. If
Expand Down
12 changes: 7 additions & 5 deletions cython/core/pickle.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,8 @@ cdef c_Triangulation* unpickle_triangulation(bytes pickle) except *:
free(cusps)
return tri

cdef int unpickle_tetrahedron_data(
c_TetrahedronData *data, bytes pickle, int start, int flag) except *:
cdef int unpickle_tetrahedron_data(c_TetrahedronData *data, bytes pickle,
int start, int flag) except *:
cdef int i, j, v, f
cdef int n = start
cdef unsigned char perm
Expand Down Expand Up @@ -324,9 +324,11 @@ cdef c_Triangulation* listlike_to_triangulation(listlike,
if num_tets == 0:
raise ValueError('No tetrahedra data provided')

first = listlike[0]
if (len(first) != 2 or len(first[0]) != 4 or
not [len(x) for x in first[1]] == [4, 4, 4, 4]):
try:
first0, first1 = listlike[0]
except ValueError:
raise ValueError('Tetrahedra data appears invalid')
if len(first0) != 4 or [len(x) for x in first1] != [4, 4, 4, 4]:
raise ValueError('Tetrahedra data appears invalid')

py_name = b'from_data'
Expand Down
Loading

0 comments on commit 520ed04

Please sign in to comment.