1r"""
2The cochain algebra :math:`A_{PL}(K)`.
3Let :math:`K` be a simplicial set, and let :math:`A_{PL} = \{(A_{PL})_n\}_{n \geq 0}` be the simplicial cochain
4algebra defined at :ref:`simplicialapl`
5
6.. math::
7
8 A_{PL}(K) = \bigoplus_{p \geq 0}A_{PL}^p(K)
9
10is the cochain algebra defined as follows:
11
12* The homogenous part :math:`A_{PL}^p(K)` is the set of simplicial set morphisms from :math:`K` to :math:`A_{PL}^p`.
13 That is, an element :math:`\Phi \in A_{PL}^p(K)` is a mapping that assigns to each :math:`n`-simplex :math:`\sigma \in K_n`,
14 an element :math:`\Phi(\sigma) \in (A_{PL}^p)_n`, satisfying
15
16 .. math::
17
18 \begin{array}{c}
19 \Phi({\partial_i(\sigma)})=\partial_i(\Phi(\sigma)) \\
20 \Phi({s_j(\sigma)})=s_j(\Phi(\sigma))
21 \end{array}
22
23* Addition, scalar multiplication, product and the differential are induced by the corresponding operations
24 in the algebras :math:`(A_{PL})_n`.
25
26The structure of the cochain algebra :math:`A_{PL}(K)`, at some general dimension :math:`n` and degree :math:`p`,
27can be visualized in figure :ref:`fig:simplicial_aplK`. The horizontal direction corresponds to the simplicial
28structure for a given dimension :math:`n` (subscript), and the vertical direction corresponds to the graded structure
29of the algebra (representing the degree :math:`p` with superscript). As the simplicial cochain algebra :math:`(A_{PL})_n` is at
30the ground of this structure, all the elements of :math:`A^p_{PL}(K)_n` will vanish when :math:`p>n`. This is because it is not
31possible to assign non-zero polynomial forms of degree greater than the dimension of the simplices.
32
33.. image:: /_static/aplktkzcd.svg
34 :align: center
35 :class: only-light
36 :alt: The structure of the cochain algebra :math:`A_{PL}(K)`.
37
38.. image:: /_static/aplktkzcdneg.svg
39 :align: center
40 :class: only-dark
41 :alt: The structure of the cochain algebra :math:`A_{PL}(K)`.
42
43.. raw:: latex
44
45 \begin{figure}[H]
46 \centering
47 \begin{tikzcd}
48 & \vdots \arrow[d, "d^{p-2}_A"] & \vdots \arrow[d, "d^{p-2}_A"] & \vdots \arrow[d, "d^{p-2}_A"]& \\
49 \cdots & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] A^{p-1}_{PL}(K)_{n-1} \arrow[d, "d^{p-1}_A"] & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] A^{p-1}_{PL}(K)_{n} \arrow[d, "d^{p-1}_A"] & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] A^{p-1}_{PL}(K)_{n+1} \arrow[d, "d^{p-1}_A"] & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] \cdots \\
50 \cdots & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] A^{p}_{PL}(K)_{n-1} \arrow[d, "d^{p}_A"] & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] A^{p}_{PL}(K)_{n} \arrow[d, "d^{p}_A"] & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] A^{p}_{PL}(K)_{n+1} \arrow[d, "d^{p}_A"] & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] \cdots \\
51 \cdots & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] A^{p+1}_{PL}(K)_{n-1} \arrow[d, "d^{p+1}_A"] & A^{p+1}_{PL}(K)_{n} \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] \arrow[d, "d^{p+1}_A"] & A^{p+1}_{PL}(K)_{n+1} \arrow[d, "d^{p+1}_A"] \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] & \arrow[l, "\vdots" above, shift left=2] \arrow[l, shift right=3,"\partial_i" above] \cdots \\
52 & \vdots & \vdots & \vdots &
53 \end{tikzcd}
54 \caption{The structure of the cochain algebra $A_{PL}(K)$.}
55 \label{simplicial_aplK}
56 \end{figure}
57
58"""
59
60from sage.structure.unique_representation import UniqueRepresentation, CachedRepresentation
61from sage.misc.cachefunc import cached_method, cached_function
62from sage.structure.sage_object import SageObject
63from sage.categories.morphism import Morphism
64from sage.all import *
65from sage.structure.parent import Parent
66from sage.structure.element import Element
67from sage.rings.rational_field import QQ
68from sage.matrix.constructor import vector, matrix, zero_matrix, identity_matrix
69from collections import defaultdict
70from itertools import combinations
71from sage.arith.misc import multinomial
72from sage.combinat.set_partition_ordered import OrderedSetPartitions
73from sage.structure.richcmp import rich_to_bool, op_EQ, op_NE, op_LT, op_LE, op_GT, op_GE
74from sage.algebras.commutative_dga import sorting_keys
75import copy
76from copy import deepcopy
77from .hodge import Hodge
78from .SimplicialAPL import SimplicialAPL
79from . import utils
80from .utils import sgn_face, sgn_perm
81
82
[docs]
83class APLK(Parent, UniqueRepresentation, CachedRepresentation):
84
85 def __init__(self, K, base_ring=QQ, precompute_degree=None):
86 if ((not hasattr(K, 'n_cells')) or (not hasattr(K, 'face')) or (not hasattr(K, 'dimension'))):
87 raise TypeError(
88 'K must be a simplicial complex with n_cells(), face(), and dimension() methods')
89 self.K = K
90 self._base_ring = base_ring
91 self._dimension = K.dimension()
92 self._gens = {}
93 self._coboundaries = {}
94 self._cocycles = {}
95 self._cohomology_raw = {}
96 self._cohomology = {}
97 self._cohomology_mmodels = {}
98 self._cohomology_raw_mmodels = {}
99 self._minimalmodels = {}
100 self._numerical_invariants = {}
101 self._ch_vector = ()
102
103 self._apl_algebras = SimplicialAPL(self._dimension)
104
105 Parent.__init__(self, base=QQ)
106 f = MorphismFromQQToAPLK(self)
107 self.register_coercion(f)
108 self._gens = {'hodge': {}, 'whitney': {}}
109 for d in range((K.dimension() + 1)):
110 self._gens['hodge'][d] = {
111 'harmonics': {}, 'exacts': {}, 'coexacts': {}}
112 self._gens['whitney'][d] = {
113 'harmonics': {}, 'exacts': {}, 'coexacts': {}}
114 self._hodge = Hodge(K)
115 self._hodge_matrix_decompositions = {}
116 if precompute_degree:
117 print('Precomputing hodge decomposition up to degree',
118 precomp_hodge_deg, flush=True)
119 self._hodge_matrix_decompositions = self.hodge_matrix_decompositions(
120 precomp_hodge_deg)
121
122 def _check_compatibility(self, components):
123 K = self.K
124 SApl = self._apl_algebras
125 face_map = self._face_homomorphism()
126 for dim in range(1, (self._dimension + 1)):
127 cells = self.K._n_cells_sorted(dim)
128 A = SApl.n_th_object(dim)
129 for (sigma_idx, sigma) in enumerate(cells):
130 f_sigma = components.get(sigma, A.zero())
131 if f_sigma.is_zero():
132 continue
133 for i in range((dim + 1)):
134 tau = K.face(sigma, i)
135 #tau_dim = (dim - 1)
136 f_tau_expected = face_map(f_sigma, i)
137 f_tau_actual = components.get(tau, SApl.n_th_object(dim-1).zero())
138 if (not (f_tau_expected - f_tau_actual).reduce(0).is_zero()):
139 raise ValueError(
140 f'Face map compatibility failed for face {i} of {sigma}:\n Expected: {f_tau_expected.reduce(0)}\n Actual: {f_tau_actual.reduce(0)}')
141
142 def _cochain_to_vector(self, dim, cochain):
143 cells = self.K._n_cells_sorted(dim)
144 v = vector(QQ, len(cells), [cochain.get(sigma, 0) for sigma in cells])
145 return v
146
147 def _coface_coeff_endomorphism(self, faces, dim_from, dim_to):
148 S = self._apl_algebras
149 dom = S.n_th_object(dim_from).base_ring()
150 cod = S.n_th_object(dim_to).base_ring()
151 if (dim_from > dim_to):
152 face_matrix = identity_matrix(cod, len(dom.gens()), sparse=True)
153 face_matrix = face_matrix.delete_rows(faces).T
154 else:
155 face_matrix = identity_matrix(cod, len(cod.gens()), sparse=True)
156 face_matrix = face_matrix.delete_rows(faces)
157 codgens = vector(cod, cod.gens())
158 image = list((face_matrix * codgens))
159 return dom.hom(image, cod)
160
161 def _degree_factorization(self, deg):
162 return [(i, (deg - i)) for i in range(deg) if ((i <= (deg - i)) and (i > 0))]
163
164 @cached_method(do_pickle=True)
165 def _face_data(self, dim_from, dim_to):
166 return utils._face_data(self.K, dim_from, dim_to, self._base_ring)
167
168 def _face_homomorphism(self):
169 if (dim == 0):
170 raise ValueError(
171 'Cannot compute face homomorphism for 0-simplices')
172 return self._apl_algebras.face
173
174 @cached_method(do_pickle=True)
175 def _face_matrix(self, K, face, dim):
176 return utils._face_matrix(K, dim, base_ring)
177
178 def _gens_names_coexacts(self, d):
179 return list(self.coexact_basis(d).keys())
180
181 def _gens_names_exacts(self, d):
182 return list(self.exact_basis(d).keys())
183
184 def _gens_names_harmonics(self, d):
185 return list(self.harmonic_basis(d).keys())
186
187 @cached_method(do_pickle=True)
188 def _get_basis(self, d, whitney_basis=True, subtype='harmonics', check=False):
189 if whitney_basis:
190 gensType = 'whitney'
191 else:
192 gensType = 'hodge'
193
194 if (subtype == 'harmonics'):
195 basis_func = self.harmonic_basis
196 hodge_basis_func = self._hodge.harmonic_basis
197 gLabel = 'h{}_{}'
198 elif (subtype == 'exacts'):
199 basis_func = self.exact_basis
200 hodge_basis_func = self._hodge.exact_basis
201 gLabel = 'e{}_{}'
202 elif (subtype == 'coexacts'):
203 basis_func = self.coexact_basis
204 hodge_basis_func = self._hodge.coexact_basis
205 gLabel = 'c{}_{}'
206 if self._gens[gensType][d][subtype]:
207 return self._gens[gensType][d][subtype]
208 if (not whitney_basis):
209 basis = hodge_basis_func(d)
210 gens = {gLabel.format(d, i): h for (i, h) in enumerate(basis) if h}
211 else:
212 basis = basis_func(d, False, check)
213 gens = {gname: self.whitney_form_from_vector(d, cochain, check) for (
214 gname, cochain) in basis.items() if cochain}
215 self._gens[gensType][d][subtype] = gens
216 return gens
217
218 def _get_cohomology_dimensions(self):
219 dim = self._dimension
220 co = self.K.cohomology(base_ring=QQ)
221 return vector(QQ, [co[d].rank() for d in range((dim + 1))])
222
223 def _get_coordinates(self, w):
224 deg = w.degree()
225 hodgeMats = self.hodge_decomposition(deg)
226 (h, e, c) = w.hodge_cochain_decomposition()
227 H = hodgeMats['H']
228 if (not (H.nrows() == 0)):
229 hCoords = H.T.solve_right(h)
230 else:
231 hCoords = zero_vector(QQ, H.ncols())
232 X = hodgeMats['X']
233 if (not (X.nrows() == 0)):
234 xCoords = X.T.solve_right(e)
235 else:
236 xCoords = zero_vector(QQ, X.ncols())
237 Y = hodgeMats['Y']
238 if (not (Y.nrows() == 0)):
239 yCoords = Y.T.solve_right(c)
240 else:
241 yCoords = zero_vector(QQ, Y.ncols())
242 return {'harmonic_coords': hCoords, 'exact_coords': xCoords, 'coexact_coords': yCoords}
243
244 @cached_method(do_pickle=True)
245 def _hodge_matrix_decomposition(self, d, check=False, verbose=True):
246 [H, X, Y] = self._hodge.hodge_decomposition(d)
247 self._hodge_matrix_decompositions[d] = {'H': H, 'X': X, 'Y': Y}
248 return self._hodge_matrix_decompositions[d]
249
250 def _inject_subset_vars(self, func_basis, d=[], reload=True, verbose=True, check=False):
251 def check_list_degs(degrees):
252 if (not degrees):
253 return range(1, (self._dimension + 1))
254 elif (isinstance(degrees, tuple) or isinstance(degrees, list)):
255 degs = degrees
256 else:
257 degs = [degrees]
258 for d in degs:
259 deg = int(d)
260 if (deg < 0):
261 raise ValueError('max_degree must be a positive integer')
262 if (deg not in ZZ):
263 raise ValueError('max_degree must be a positive integer')
264 if (deg > self._dimension):
265 raise ValueError(
266 'max_degree must be lower or equal to the dimiension of self')
267 return degs
268 degrees = check_list_degs(d)
269 gens = {}
270 for deg in degrees:
271 gens.update(func_basis(deg, check))
272 return self._inject_variables(gens, verbose)
273
274 def _inject_variables(self, gens, reload=True, verbose=True):
275 from sage.repl.user_globals import set_global, get_globals
276 for name in gens.keys():
277 if ((not (name in get_globals().keys())) or reload):
278 set_global(name, gens[name])
279 if verbose:
280 print('Defining {}'.format(', '.join(gens.keys())), flush=True)
281 return None
282
283 @cached_method(do_pickle=True)
284 def _nonzero_product_faces(self, dim1, dim2):
285 dim = (dim1 + dim2)
286 cp = cartesian_product([list(combinations(
287 range((dim + 1)), dim2)), list(combinations(range((dim + 1)), dim1))])
288 return [c for c in cp if (not set(c[0]).intersection(set(c[1])))]
289
290 def _pack_data(self):
291 data = {}
292 data['K'] = self.K
293 self.gens(whitney_basis=True, verbose=True)
294 self.gens(whitney_basis=False, verbose=True)
295 data['gens'] = self._gens
296 for n in range((self._dimension + 1)):
297 self.coboundaries(n)
298 self.cocycles(n)
299 self.cohomology_raw(n)
300 self.cohomology(n)
301 self.hodge_matrix_decompositions(n)
302 data['coboundaries'] = self._coboundaries
303 data['cocycles'] = self._cocycles
304 data['cohomology_raw'] = self._cohomology_raw
305 data['cohomology'] = self._cohomology
306 data['ch_vector'] = self._get_cohomology_dimensions()
307 data['apl_algebras '] = self._apl_algebras
308 data['hodge'] = self.hodge()
309 data['hodge_matrix_decompositions'] = self._hodge_matrix_decompositions
310 data['cohomology_mmodels'] = self._cohomology_mmodels
311 data['minimalmodels'] = self._minimalmodels
312 data['numerical_invariants'] = self._numerical_invariants
313 return data
314
315 def _repr_(self):
316 return f'Algebra of Whitney Forms on {self.K}'
317
318 def _vector_to_cochain(self, dim, v):
319 cells = self.K._n_cells_sorted(dim)
320 return {sigma: v[i] for (i, sigma) in enumerate(v)}
321
[docs]
322 def base_ring(self):
323 return self._base_ring
324
[docs]
325 def basis(self, d):
326 basis = []
327 basis += list(self.harmonic_basis(d).values())
328 basis += list(self.exact_basis(d).values())
329 basis += list(self.coexact_basis(d).values())
330 return basis
331
[docs]
332 def basis_ts(self, deg_y, deg_t):
333 K = self.K
334 b0 = self.basis(0)
335 b2 = self.basis(deg_y)
336 deg0_coefs = [prod(c) for c in cartesian_product((deg_t * [b0]))]
337 b02 = [prod(c) for c in cartesian_product([deg0_coefs, b2])]
338 rows = [g.terms_repr((deg_t + 1)) for g in b02]
339 m = matrix(QQ, len(rows), rows, sparse=True)
340 basis = m.row_space().basis()
341 gens = [sum([(c * g) for (c, g) in zip(b, b02)]) for b in basis]
342 return [g for g in gens if g]
343
[docs]
344 def ch_vector(self):
345 if (not (len(self._ch_vector) == 0)):
346 return self._ch_vector
347 else:
348 self._ch_vector = self._get_cohomology_dimensions()
349 return self._ch_vector
350
[docs]
351 def coboundaries(self, n):
352 if (n in self._coboundaries.keys()):
353 return self._coboundaries[n]
354 elif (n > self._dimension):
355 return span(QQ, zero_vector(QQ, 0))
356 basis = [v for v in self._hodge.coexact_basis(n) if v]
357 F = self.base_ring()
358 V = span(F, basis).span_of_basis(basis)
359 self._coboundaries[n] = V
360 return V
361
362 # def m(self, cochains=[],dims=[]):
363 # dim = sum(dims)
364 # face_matrices = [self._face_data(dims[d], dim) for d in dims]
365 # ncells = len(self.K.n_cells(dim))
366 # w = vector(QQ, ncells)
367 # #product_faces = self._nonzero_product_faces(dim1, dim2)
368 # pathlengths = [dim-d for d in dims]
369 # product_faces = [[tuple(f) for f in path[1:]] for path
370 # in OrderedSetPartitions(range(dim+1), [1]+ pathlengths)]
371 # #coef = ((factorial(dim1) * factorial(dim2)) / factorial((dim + 1)))
372 # coef = prod([factorial(d) for d in dims])/factorial(dim+1)
373 # for fpaths in product_faces:
374 # faces_orig_order = tuple(flatten(fpaths))
375 # sgn_prod = sgn_perm(faces_orig_order)
376 # propags = [face_matrices[i][fpaths[i]].T*c for (i, c) in enumerate(cochains)]
377 # v = propags[0]
378 # for i in range(1,len(propags)):
379 # v2 = propags[i]
380 # v = v.pairwise_product(v2)
381 # w += (sgn_prod * v)
382 # return (coef * w)
383
[docs]
384 def cochain_wedge_product(self, c1, dim1, c2, dim2):
385 dim = (dim1 + dim2)
386 face_data1 = self._face_data(dim1, dim)
387 face_data2 = self._face_data(dim2, dim)
388 w = vector(QQ, len(self.K.n_cells(dim)))
389 product_faces = self._nonzero_product_faces(dim1, dim2)
390 coef = ((factorial(dim1) * factorial(dim2)) / factorial((dim + 1)))
391 #coef = 1/multinomial(dim1,dim2)
392 for (f1, f2) in product_faces:
393 faces_orig_order = (list(f1) + list(f2))
394 sgn_prod = sgn_perm(faces_orig_order)
395 f_matrix1 = face_data1[f1].T
396 v1 = (f_matrix1 * c1)
397 f_matrix2 = face_data2[f2].T
398 v2 = (f_matrix2 * c2)
399 v = v1.pairwise_product(v2)
400 w += (sgn_prod * v)
401 return (coef * w)
402
[docs]
403 def cocycles(self, n):
404 if (n in self._cocycles.keys()):
405 return self._cocycles[n]
406 elif (n > self._dimension):
407 return span(QQ, zero_vector(QQ, 0))
408 H_basis = self._hodge.harmonic_basis(n)
409 X_basis = self._hodge.exact_basis(n)
410 basis = [v for v in (H_basis + X_basis) if v]
411 F = self.base_ring()
412 V = span(F, basis).span_of_basis(basis)
413 self._cocycles[n] = V
414 return V
415
416 @cached_method(do_pickle=True)
417 def coexact_basis(self, d, whitney_basis=True, check=False):
418 gensSubtype = 'coexacts'
419 return self._get_basis(d, whitney_basis, gensSubtype, check)
420
[docs]
421 def cohomology(self, n):
422 if (n in self._cohomology.keys()):
423 return self._cohomology[n]
424 elif (n > self._dimension):
425 return span(QQ, zero_vector(QQ, 0))
426 H_basis = self.harmonic_basis(n)
427 H_basis_brackets = [CohomologyClass(
428 value, self) for (name, value) in H_basis.items()]
429 self._cohomology[n] = CombinatorialFreeModule(self.base_ring(
430 ), H_basis_brackets, sorting_key=sorting_keys, monomial_reverse=True)
431 return self._cohomology[n]
432
433 @cached_method(do_pickle=True)
434 def cohomology_algebra(self, max_degree=-1, verbose=False):
435 """
436 Compute a CDGA with trivial differential, that is isomorphic to the cohomology of
437 ``self`` up to ``max_degree`` (default: dimension of the space)
438
439 INPUT:
440
441 - ``max_degree`` -- integer (default: `dimension of the space`); degree to which the result is required to
442 be isomorphic to ``self``'s cohomology
443
444 .. tab:: Sage
445
446 EXAMPLES::
447
448 sage: S2 = simplicial_sets.Sphere(2)
449 sage: K = S2.product(S2)
450 sage: K.cohomology()
451 {0: 0, 1: 0, 2: Z x Z, 3: 0, 4: Z}
452 sage: W = APLK(K)
453 sage: H = W.cohomology_algebra()
454 sage: H
455 Commutative Differential Graded Algebra with generators ('x0', 'x1', 'x2') in degrees (2, 2, 4) with relations [x0^2 + 2*x2, x0*x1 - x2, x1^2] over Rational Field with differential:
456 x0 --> 0
457 x1 --> 0
458 x2 --> 0
459 sage: hgens = K.cohomology_ring(base_ring=QQ).gens()
460 sage: hgens
461 (h^{0,0}, h^{2,0}, h^{2,1}, h^{4,0})
462 sage: x0 = hgens[1]
463 sage: x1 = hgens[2]
464 sage: x2 = hgens[3]
465 sage: x0**2+2*x2
466 0
467 sage: x0*x1-x2
468 0
469 sage: x1**2
470 0
471
472 .. tab:: Raw code
473
474 EXAMPLES::
475
476 S2 = simplicial_sets.Sphere(2)
477 K = S2.product(S2)
478 print("Simplicial cohomology")
479 print(K.cohomology())
480 W = APLK(K)
481 H = W.cohomology_algebra()
482 print(H)
483 hgens = K.cohomology_ring(base_ring=QQ).gens()
484 print("testing relations of the generators")
485 x0 = hgens[1]
486 x1 = hgens[2]
487 x2 = hgens[3]
488 print(f"x0**2+2*x2 ==> {x0**2+2*x2}")
489 print(f"x0*x1-x2 ==> {x0*x1-x2}")
490 print(f"x1**2 ==> {x1**2}")
491 """
492
493 H = self.K.cohomology_ring(base_ring=self.base_ring())
494
495 if max_degree == -1:
496 max_deg = self.K.dimension()
497
498 elif max_degree >= 0 and max_degree <= self.K.dimension():
499 max_deg = max_degree
500 else:
501 raise ValueError(f"The parameter max_degree must be an integer in range (0, {max_deg})")
502
503 cohomgens = {d:list(H.basis(d)) for d in range(1, max_deg+1)}
504
505 if not cohomgens:
506 raise ValueError("cohomology ring has no generators")
507
508 h_vector = [len(H.basis(d)) for d in range(max_deg+1)]
509
510 chgens = []
511 degrees = []
512 for d in cohomgens:
513 for g in cohomgens[d]:
514 degrees.append(d)
515 chgens.append(g)
516
517 A = GradedCommutativeAlgebra(self.base_ring(),
518 [f'x{i}' for i in range(len(chgens))],
519 degrees)
520 rels = []
521 for d in range(1, max_deg + 1):
522 i = sum(h_vector[:d])
523 j = i + h_vector[d]
524 B1 = A.basis(d)
525 V2 = self.cohomology_raw(d)
526 images = []
527 for g in B1:
528 ig = g._im_gens_(H, chgens)
529 if ig.is_zero():
530 images.append(V2.zero())
531 else:
532 images.append(V2.from_vector(ig.to_vector()[i:j]))
533 V1 = self.base_ring()**len(B1)
534 h = V1.hom(images, codomain=V2)
535 ker = h.kernel()
536 for g in ker.basis():
537 newrel = sum(g[i] * B1[i] for i in range(len(B1)))
538 rels.append(newrel)
539 if verbose:
540 print("Building CDGA ==> Computing the quotient by relations...", flush=True)
541 return A.quotient(A.ideal(rels)).cdg_algebra({})
542
[docs]
543 def cohomology_raw(self, n):
544 if (n in self._cohomology_raw.keys()):
545 return self._cohomology_raw[n]
546 elif (n > self._dimension):
547 return span(QQ, zero_vector(QQ, 0))
548 basis = self._hodge.harmonic_basis(n)
549 F = self.base_ring()
550 V = span(F, basis).span_of_basis(basis)
551 self._cohomology_raw[n] = V
552 return V
553
[docs]
554 def constant(self, c):
555 components = {}
556 for dim in range((self._dimension + 1)):
557 A = self._apl_algebras.n_th_object(dim)
558 for sigma in self.K._n_cells_sorted(dim):
559 components[sigma] = A(c)
560 return self.element_class()(self, components, check=False)
561
[docs]
562 def dimension(self):
563 return self._dimension
564
[docs]
565 def element_class(self):
566 return APLKElement
567
568 @cached_method(do_pickle=True)
569 def exact_basis(self, d, whitney_basis=True, check=False):
570 gensSubtype = 'exacts'
571 return self._get_basis(d, whitney_basis, gensSubtype, check)
572
[docs]
573 def gens(self, whitney_basis=True, verbose=True):
574 if whitney_basis:
575 gensType = 'whitney'
576 else:
577 gensType = 'hodge'
578 for d in range((self.dimension() + 1)):
579 if verbose:
580 print('Getting generators of degree ', d, '...', flush=True)
581 if (not self._gens[gensType][d]['harmonics']):
582 self._gens[gensType][d]['harmonics'] = self.harmonic_basis(
583 d, whitney_basis)
584 if (not self._gens[gensType][d]['exacts']):
585 self._gens[gensType][d]['exacts'] = self.exact_basis(
586 d, whitney_basis)
587 if (not self._gens[gensType][d]['coexacts']):
588 self._gens[gensType][d]['coexacts'] = self.coexact_basis(
589 d, whitney_basis)
590 return self._gens[gensType]
591
[docs]
592 def gens_names(self, deg=[]):
593 if (not deg):
594 deg_list = range((self._dimension + 1))
595 elif ((deg in ZZ) and (deg >= 0)):
596 deg_list = [deg]
597 names = []
598 for d in deg_list:
599 names += self._gens_names_harmonics(d)
600 names += self._gens_names_exacts(d)
601 names += self._gens_names_coexacts(d)
602 return names
603
604 @cached_method(do_pickle=True)
605 def harmonic_basis(self, d, whitney_basis=True, check=False):
606 gensSubtype = 'harmonics'
607 return self._get_basis(d, whitney_basis, gensSubtype, check)
608
[docs]
609 def hodge(self):
610 return self._hodge
611
612 @cached_method(do_pickle=True)
613 def hodge_decomposition(self, d, check=False):
614 return self._hodge_matrix_decompositions.get(d, self._hodge_matrix_decomposition(d, check))
615
616 @cached_method(do_pickle=True)
617 def hodge_matrix_decompositions(self, deg=0, check=False, verbose=True):
618 max_deg = int(deg)
619 if (max_deg < 0):
620 raise ValueError('max_degree must be a positive integer')
621 if (max_deg not in ZZ):
622 raise ValueError('max_degree must be a positive integer')
623 if (max_deg > self._dimension):
624 raise ValueError(
625 'max_degree must be lower or equal to the dimiension of self')
626 if (max_deg == 0):
627 max_deg = self._dimension
628 for d in range((max_deg + 1)):
629 if verbose:
630 print('Getting hodge matrix decomposition at degree ',
631 d, '...', flush=True)
632 if (not (d in self._hodge_matrix_decompositions.keys())):
633 self._hodge_matrix_decomposition(d, check)
634 return self._hodge_matrix_decompositions
635
[docs]
636 def inject_coexact_vars(self, d=[], reload=True, verbose=True, check=False):
637 return self._inject_subset_vars(self.coexact_basis, d, reload, verbose, check)
638
[docs]
639 def inject_exact_vars(self, d=[], reload=True, verbose=True, check=False):
640 return self._inject_subset_vars(self.exact_basis, d, reload, verbose, check)
641
[docs]
642 def inject_harmonic_vars(self, d=[], reload=True, verbose=True, check=False):
643 return self._inject_subset_vars(self.harmonic_basis, d, reload, verbose, check)
644
[docs]
645 def inject_variables(self, reload=True, verbose=True):
646 gens = {}
647 for (d, components) in self.gens(verbose=verbose).items():
648 for (gtype, values) in components.items():
649 gens.update(values)
650 return self._inject_variables(gens, reload, verbose)
651
714
[docs]
715 def load_data(self, data):
716 self.K = data['K']
717 self._gens = data['gens']
718 self._coboundaries = data['coboundaries']
719 self._cocycles = data['cocycles']
720 self._cohomology_raw = data['cohomology_raw']
721 self._cohomology = data['cohomology']
722 self._ch_vector = data['ch_vector']
723 self._apl_algebras = data['apl_algebras ']
724 self._hodge = data['hodge']
725 self._hodge_matrix_decompositions = data['hodge_matrix_decompositions']
726 self._cohomology_mmodels = data['cohomology_mmodels']
727 self._minimalmodels = data['minimalmodels']
728 self._numerical_invariants = data['numerical_invariants']
729 return None
730
[docs]
731 def numerical_invariants(self, max_degree=3, max_iterations=3):
732 r"""
733 Return the numerical invariants of the algebra, up to degree ``d``. The
734 numerical invariants reflect the number of generators added at each step
735 of the construction of the minimal model.
736
737 The numerical invariants are the dimensions of the subsequent Hirsch
738 extensions used at each degree to compute the minimal model.
739
740 INPUT:
741
742 - ``max_degree`` -- integer (default: `3`); the degree up to which the
743 numerical invariants are computed
744
745 - ``max_iterations`` -- integer (default: `3`); the maximum number of iterations
746 used to compute the minimal model, if it is not already cached
747
748 EXAMPLES::
749
750 sage: A.<e1, e2, e3> = GradedCommutativeAlgebra(QQ)
751 sage: B = A.cdg_algebra({e3 : e1*e2})
752 sage: B.minimal_model(4)
753 Commutative Differential Graded Algebra morphism:
754 From: Commutative Differential Graded Algebra with
755 generators ('x1_0', 'x1_1', 'y1_0') in degrees (1, 1, 1)
756 over Rational Field with differential:
757 x1_0 --> 0
758 x1_1 --> 0
759 y1_0 --> x1_0*x1_1
760 To: Commutative Differential Graded Algebra with
761 generators ('e1', 'e2', 'e3') in degrees (1, 1, 1)
762 over Rational Field with differential:
763 e1 --> 0
764 e2 --> 0
765 e3 --> e1*e2
766 Defn: (x1_0, x1_1, y1_0) --> (e1, e2, e3)
767 sage: B.numerical_invariants(2)
768 {1: [2, 1, 0], 2: [0, 0]}
769
770 ALGORITHM:
771
772 The numerical invariants are stored as the minimal model is constructed.
773
774 .. WARNING::
775
776 The method is not granted to finish (it can't, since the minimal
777 model could be infinitely generated in some degrees).
778 The parameter ``max_iterations`` controls how many iterations of
779 the method are attempted at each degree. In case they are not
780 enough, an exception is raised. If you think that the result will
781 be finitely generated, you can try to run it again with a higher
782 value for ``max_iterations``.
783
784 REFERENCES:
785
786 For a precise definition and properties, see :cite:`manero_effective_2020`.
787
788 """
789 self.minimal_model(max_degree, max_iterations)
790 return {i: self._numerical_invariants[i]
791 for i in range(1, max_degree + 1)}
792
[docs]
793 def minimal_model(self, i=3, max_iterations=3, partial_result=False, verbose=True, parallelComp=False):
794 r"""
795
796 .. tab:: sage
797
798 EXAMPLES::
799
800 sage: load("Sullivan_MM/tests/zariski.py")
801 sage: [S6_1, S6_2] = pair6()
802 sage: A1 = APLK(S6_1)
803 sage: M1 = A1.minimal_model(i=2, max_iterations=2,parallelComp=False,verbose=True,partial_result=True)
804 Starting the computation at degree 1
805 Checking injectivity at degree 2 ==> iteration 1 (out of 2)
806 (1/3) Trying to get a Whitney form primitive...
807 (1/3) Trying to get a Whitney form primitive...
808 (1/3) Trying to get a Whitney form primitive...
809 Extending the model...
810 ....creating GCA...
811 ....building HOM B --> A...
812 ....updating differential...
813 ....Building new Minimal Model...
814 Checking injectivity at degree 2 ==> iteration 2 (out of 2)
815 sage: B1 = M1.domain()
816 sage: B1
817 Commutative Differential Graded Algebra with generators ('x1_0', 'x1_1', 'x1_2', 'x1_3', 'x1_4', 'y1_0',
818 'y1_1', 'y1_2', 'y1_3', 'y1_4', 'y1_5') in degrees (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) over Rational
819 Field with differential:
820 x1_0 --> 0
821 x1_1 --> 0
822 x1_2 --> 0
823 x1_3 --> 0
824 x1_4 --> 0
825 y1_0 --> x1_1*x1_2
826 y1_1 --> x1_1*x1_3
827 y1_2 --> x1_2*x1_3
828 y1_3 --> x1_1*x1_4
829 y1_4 --> x1_2*x1_4
830 y1_5 --> x1_3*x1_4
831 sage: B1.cohomology(2)
832 Free module generated by {[x1_0*x1_1], [x1_0*x1_2], [x1_0*x1_3], [x1_0*x1_4], [x1_1*y1_0], [x1_2*y1_0],
833 [x1_3*y1_0 - x1_1*y1_2], [x1_4*y1_0 - x1_1*y1_4], [x1_1*y1_1], [x1_2*y1_1 + x1_1*y1_2], [x1_3*y1_1],
834 [x1_4*y1_1 - x1_1*y1_5], [x1_2*y1_2], [x1_3*y1_2], [x1_4*y1_2 - x1_2*y1_5], [x1_1*y1_3],
835 [x1_2*y1_3 + x1_1*y1_4], [x1_3*y1_3 + x1_1*y1_5], [x1_4*y1_3], [x1_2*y1_4], [x1_3*y1_4 + x1_2*y1_5],
836 [x1_4*y1_4], [x1_3*y1_5], [x1_4*y1_5]} over Rational Field
837 sage: x13 = M1._imgens['x1_3']
838 sage: y15 = M1._imgens['y1_5']
839 sage: p = x13*y15
840 sage: p
841 [1/12]*e2_28
842 sage: p.dif()
843 0
844 sage: dp = x13*y15
845 sage: p = dp.solve_primitive()
846 sage: p.dif() == dp
847 True
848 sage: p.check()
849 True
850
851 sage: S2 = simplicial_sets.Sphere(2)
852 sage: S4 = simplicial_sets.Sphere(4)
853 sage: CP2 = simplicial_sets.ComplexProjectiveSpace(2)
854 sage: WS = APLK(S2.wedge(S4))
855 sage: WC = APLK(CP2)
856 sage: MS = WS.minimal_model(i=4,max_iterations=3,verbose=True)
857 Starting the computation at degree 2
858 Checking injectivity at degree 3 ==> iteration 1 (out of 3)
859 Checking surjectivity at degree 3...
860 Checking injectivity at degree 4 ==> iteration 1 (out of 3)
861 Extending the model...
862 ....creating GCA...
863 ....building HOM B --> A...
864 ....updating differential...
865 ....Building new Minimal Model...
866 Checking injectivity at degree 4 ==> iteration 2 (out of 3)
867 Checking surjectivity at degree 4...
868 Extending the model...
869 ....creating GCA...
870 ....building HOM B --> A...
871 ....updating differential...
872 ....Building new Minimal Model...
873 Checking injectivity at degree 5 ==> iteration 1 (out of 3)
874 sage: MC = WC.minimal_model(i=4,max_iterations=3,verbose=True)
875 Starting the computation at degree 2
876 Checking injectivity at degree 3 ==> iteration 1 (out of 3)
877 Checking surjectivity at degree 3...
878 Checking injectivity at degree 4 ==> iteration 1 (out of 3)
879 Checking surjectivity at degree 4...
880 Checking injectivity at degree 5 ==> iteration 1 (out of 3)
881 sage: MS.domain()
882 Commutative Differential Graded Algebra with generators ('x2_0', 'y3_0', 'x4_0') in degrees (2, 3, 4) over Rational Field with differential:
883 x2_0 --> 0
884 y3_0 --> x2_0^2
885 x4_0 --> 0
886 sage: MC.domain()
887 Commutative Differential Graded Algebra with generators ('x2_0',) in degrees (2,) with relations [0] over Rational Field with differential:
888 x2_0 --> 0
889 sage: S2.wedge(S4).cohomology()
890 {0: 0, 1: 0, 2: Z, 3: 0, 4: Z}
891 sage: CP2.cohomology()
892 {0: 0, 1: 0, 2: Z, 3: 0, 4: Z}
893 sage: MS.cohomology(2)
894 Free module generated by {[x2_0]} over Rational Field
895 sage: MS.cohomology(3)
896 Free module generated by {} over Rational Field
897 sage: MS.cohomology(4)
898 Free module generated by {[x4_0]} over Rational Field
899 sage: MC.cohomology(2)
900 Free module generated by {[x2_0]} over Rational Field
901 sage: MC.cohomology(3)
902 Free module generated by {} over Rational Field
903 sage: MC.cohomology(4)
904 Free module generated by {[x2_0^2]} over Rational Field
905
906
907 .. tab:: Raw code
908
909 EXAMPLES::
910
911 load("Sullivan_MM/tests/zariski.py")
912 [S6_1, S6_2] = pair6()
913 A1 = APLK(S6_1)
914 M1 = A1.minimal_model(i=2, max_iterations=2,parallelComp=False,verbose=True,partial_result=True)
915 B1 = M1.domain()
916 B1.cohomology(2)
917 x13 = M1._imgens['x1_3']
918 y15 = M1._imgens['y1_5']
919 dp = x13*y15
920 p = dp.solve_primitive()
921 p.dif() == dp
922 p.check()
923
924 S2 = simplicial_sets.Sphere(2)
925 S4 = simplicial_sets.Sphere(4)
926 CP2 = simplicial_sets.ComplexProjectiveSpace(2)
927 WS = APLK(S2.wedge(S4))
928 WC = APLK(CP2)
929 MS = WS.minimal_model(i=4,max_iterations=3,verbose=True)
930 MC = WC.minimal_model(i=4,max_iterations=3,verbose=True)
931 MS.domain()
932 MC.domain()
933 S2.wedge(S4).cohomology()
934 CP2.cohomology()
935 MS.cohomology(2)
936 MS.cohomology(3)
937 MS.cohomology(4)
938 MC.cohomology(2)
939 MC.cohomology(3)
940 MC.cohomology(4)
941
942 """
943 max_degree = int(i)
944 if (max_degree < 1):
945 raise ValueError('the degree must be a positive integer')
946 if ((max_iterations not in ZZ) or (max_iterations < 1)):
947 raise ValueError('max_iterations must be a positive integer')
948 if (max_degree in self._minimalmodels):
949 return self._minimalmodels[max_degree]
950 from copy import copy
951
952 def extend(M, ndegrees, ndifs, nimags, nnames, verbose=False):
953 B = M.domain()
954 if verbose:
955 print(f'Extending the model...', flush=True)
956 old_names = [str(g) for g in B.gens()]
957 new_names = (old_names + list(nnames))
958 new_degrees = ([g.degree() for g in B.gens()] + list(ndegrees))
959 if verbose:
960 print(f'....creating GCA...', flush=True)
961 A = GradedCommutativeAlgebra(
962 B.base_ring(), names=new_names, degrees=new_degrees)
963 if verbose:
964 print(f'....building HOM B --> A...', flush=True)
965 h = B.hom(A.gens()[:B.ngens()], check=False)
966 d = B.differential()
967 if verbose:
968 print(f'....updating differential...', flush=True)
969 diff = {h(g): h(d(g)) for g in B.gens()}
970 cndifs = list(copy(ndifs))
971 for g in A.gens()[B.ngens():]:
972 diff[g] = h(cndifs.pop(0))
973 newCDGA = A.cdg_algebra(diff)
974 new_imgens = tuple(([M._imgens[name]
975 for name in old_names] + list(nimags)))
976 if verbose:
977 print(f'....Building new Minimal Model...', flush=True)
978 return MinimalModel(domain=newCDGA, codomain=self, names=tuple(new_names),
979 gens=new_imgens)
980
981 def extendx(M, degree, verbose=False, parallelComp=False):
982 if verbose:
983 print(f'Checking surjectivity at degree {degree}...', flush=True)
984 CM = M.cohomology_raw(degree)
985 CW = self.cohomology_raw(degree)
986 #ncells = len(self.K.n_cells(degree))
987 imagesphico = []
988 if parallelComp:
989 if verbose:
990 print(f' Parallel Computation of the cohomology images...', flush=True)
991 Mcohobasis = M.cohomology(degree).basis().keys()
992 zipped_data = [(M, g) for g in Mcohobasis]
993 imagesphico = [g[1] for g in imagesPhiCoho(zipped_data)]
994 else:
995 ncoords = CW.dimension()
996 for g in M.cohomology(degree).basis().keys():
997 w = M.phi(g.representative()).reduce(0)
998 h = w.coordinates()['harmonic_coords']
999 if ((h == 0) and (len(h) < ncoords)):
1000 h = zero_vector(QQ, ncoords)
1001 imagesphico += [h]
1002
1003 # phico: CM --> CW
1004 phico = matrix(QQ, CM.dimension(), list(imagesphico), sparse=True).T
1005
1006
1007 # if verbose:
1008 # print('phico', flush=True)
1009 # print(matrix(QQ, CM.dimension(), list(imagesphico), sparse=True), flush=True)
1010 # print('##############################################', flush=True)
1011 # print('phico.column_space().complement()', flush=True)
1012 # print(phico, flush=True)
1013 # print('##############################################', flush=True)
1014 # print('CW', flush=True)
1015 # print(CW, flush=True)
1016 if (phico.rank() == 0):
1017 QI = CW
1018 else:
1019 QI = phico.column_space().complement()
1020 # else:
1021 # CW_basismat = CW.basis_matrix().sparse_matrix()
1022 # QI = (phico * CW_basismat).row_space()
1023 self._numerical_invariants[degree] = [QI.dimension()]
1024 if (QI.dimension() > 0):
1025 nnames = [f'x{degree}_{j}' for j in range(QI.dimension())]
1026 nbasis = []
1027 for v in QI.basis():
1028 vl = v #CW.lift(QI.lift(v))
1029 #g = self.whitney_form_from_vector(degree, vl)
1030 g = self.whitney_form_from_vector(degree, v)
1031 nbasis.append(g)
1032 nimags = nbasis
1033 ndegrees = [degree for _ in nbasis]
1034 ndifs = [self.zero() for _ in nimags]
1035 Mext = extend(M, tuple(ndegrees), tuple(ndifs), tuple(nimags), tuple(nnames), verbose)
1036 Mext._numerical_invariants = self._numerical_invariants
1037 return Mext
1038 M._numerical_invariants = self._numerical_invariants
1039 return M
1040
1041 @parallel(ncpus=Integer(10))
1042 def imagesPhiCoho(M, pol):
1043 #print(f' getting image phi cohomology of the polynomial {pol}', flush=True)
1044 p_rep = pol.representative()
1045 w = M.phi(p_rep).reduce(0)
1046 if w.dif().is_zero():
1047 h = w.coordinates()['harmonic_coords']
1048 ncoords = M.codomain().cohomology_raw(p_rep.degree()).dimension()
1049 if ((h == 0) and (len(h) < ncoords)):
1050 h = zero_vector(QQ, ncoords)
1051 return h
1052
1053 @parallel(ncpus=Integer(10))
1054 def find_preimages(M, pol):
1055 if verbose:
1056 print(f'finding preimage of the polynomial {pol}', flush=True)
1057 w = M.phi(pol)
1058 if verbose:
1059 print(f'finding preimage of the element of {pol}', flush=True)
1060 if w.is_zero():
1061 return self.zero()
1062 else:
1063 return w.solve_primitive(verbose=verbose)
1064 # v = w.integral()
1065 # if v.is_zero():
1066 # return self.zero()
1067 # else:
1068 # primitive = w.get_preimage_exact_component()
1069 # if (primitive.differential().reduce(0) == w.reduce(0)):
1070 # return primitive
1071 # else:
1072 # return w.solve_primitive(verbose=verbose)
1073
1074 def extendy(M, degree, verbose=False, parallelComp=False):
1075 nnamesy = 0
1076 for iteration in range(max_iterations):
1077 if verbose:
1078 print(
1079 f'Checking injectivity at degree {degree} ==> iteration {(iteration + 1)} (out of {max_iterations})', flush=True)
1080 CM = M.cohomology_raw(degree)
1081 CW = self.cohomology_raw(degree)
1082 imagesphico = []
1083 if parallelComp:
1084 if verbose:
1085 print(
1086 f' Parallel Computation of the cohomology images...', flush=True)
1087 Mcohobasis = M.cohomology(degree).basis().keys()
1088 zipped_data = [(M, g) for g in Mcohobasis]
1089 imagesphico = [g[1] for g in imagesPhiCoho(zipped_data)]
1090 if verbose:
1091 print(
1092 f'elements imagesphico ==> {[g for g in imagesphico]}', flush=True)
1093 print(f'', flush=True)
1094 else:
1095 ncoords = CW.dimension()
1096 for g in M.cohomology(degree).basis().keys():
1097 w = M.phi(g.representative()).reduce(0)
1098 if w.dif().is_zero():
1099 h = w.coordinates()['harmonic_coords']
1100 if ((h == 0) and (len(h) < ncoords)):
1101 h = zero_vector(QQ, ncoords)
1102 imagesphico += [h]
1103 # if verbose:
1104 # print(
1105 # f'elements imagesphico ==> {[g for g in imagesphico]}', flush=True)
1106 # print(f'', flush=True)
1107
1108 # phico := matrix representation of the induced morphism phi on cohomology.
1109 # The ith-column represents the coordinate vector of the generator g \in H(M) at H(C(K)).
1110 phico = matrix(QQ, CM.dimension(), list(imagesphico), sparse=True).T
1111 # phicokermat := kernel matrix of the induced morphism phi
1112 phicokermat = phico.right_kernel_matrix().sparse_matrix()
1113 ker_dim = phicokermat.nrows()
1114 self._numerical_invariants[(degree - 1)].append(ker_dim)
1115 M._numerical_invariants = self._numerical_invariants
1116 if (ker_dim == 0):
1117 return M
1118 if (iteration == (max_iterations - 1)):
1119 return (M,)
1120 ndifs = (phicokermat * CM.basis_matrix()).rows()
1121 basisdegree = M.basis(degree)
1122 """
1123 print(f"len(basisdegree) ==> {len(basisdegree)}", flush=True)
1124 print(f"ndifs ==> {ndifs}", flush=True)
1125 print(f"phicokermat ==> {phicokermat}", flush=True)
1126 print(f"CM.basis_matrix().dimensions ==> {CM.basis_matrix().dimensions()}", flush=True)
1127 print(f"phicokermat.dimensions ==> {phicokermat.dimensions()}", flush=True)
1128 """
1129 ndifs = [sum(((basisdegree[j] * CM.lift(g)[j])
1130 for j in range(len(basisdegree)))) for g in ndifs]
1131 #ncells = len(self.K.n_cells((degree - 1)))
1132 nimags = []
1133 if parallelComp:
1134 raise NotImplementedError
1135 if verbose:
1136 print(f' Parallel Computation of the Whitney preimages...', flush=True)
1137 #nimags = [w[1] for w in find_preimages(((M, g) for g in ndifs))]
1138 else:
1139 for g in ndifs:
1140 w = M.phi(g)
1141 if w.is_zero():
1142 nimags.append(self.zero())
1143 else:
1144 #print(f" finding preimage ==> {w.dif().reduce(0)}",flush=True)
1145 primitive = w.solve_primitive(verbose=verbose)
1146 nimags.append(primitive)
1147 # v = w.integral()
1148 # if v.is_zero():
1149 # nimags.append(self.zero())
1150 # else:
1151 # #primitive = w.get_preimage_exact_component()
1152 # if (primitive.differential().reduce(0) == w.reduce(0)):
1153 # nimags.append(primitive)
1154 # else:
1155 # nimags.append(w.solve_primitive(verbose=verbose))
1156 ndegrees = [(degree - 1) for g in nimags]
1157 nnames = ['y{}_{}'.format((degree - 1), (j + nnamesy))
1158 for j in range(len(nimags))]
1159 nnamesy += len(nimags)
1160 # if verbose:
1161 # print()
1162 # print("Extend ndifs", flush=True)
1163 # print(ndifs)
1164 # print()
1165 M = extend(M, tuple(ndegrees), tuple(ndifs),
1166 tuple(nimags), tuple(nnames), verbose)
1167 M._numerical_invariants = self._numerical_invariants
1168 return M
1169
1170 if (not self._minimalmodels):
1171 degnzero = 1
1172 while (self.cohomology(degnzero).dimension() == 0):
1173 self._numerical_invariants[degnzero] = [0]
1174 degnzero += 1
1175 if (degnzero > max_degree):
1176 raise ValueError('cohomology is trivial up to max_degree')
1177 if verbose:
1178 print(
1179 f'Starting the computation at degree {degnzero}', flush=True)
1180 gens = [g.representative() for (i, g) in enumerate(
1181 self.cohomology(degnzero).basis().keys())]
1182 self._numerical_invariants[degnzero] = [len(gens)]
1183 names = ['x{}_{}'.format(degnzero, j) for j in range(len(gens))]
1184 A = GradedCommutativeAlgebra(self.base_ring(), names, degrees=[
1185 degnzero for _ in names])
1186 B = A.cdg_algebra(A.differential({}))
1187 M = MinimalModel(domain=B, codomain=self,
1188 names=tuple(names), gens=tuple(gens))
1189 Mext = extendy(M, (degnzero + 1), verbose, parallelComp)
1190 if isinstance(Mext, tuple):
1191 if (not partial_result):
1192 raise ValueError(
1193 'could not cover all relations in max iterations in degree {}'.format((degnzero + 1)))
1194 return Mext[0]
1195 M = Mext
1196 self._minimalmodels[degnzero] = M
1197 else:
1198 degnzero = max(self._minimalmodels)
1199 M = self._minimalmodels[degnzero]
1200
1201 for degree in range((degnzero + 1), (max_degree + 1)):
1202 if (not (degree in self._numerical_invariants.keys())):
1203 self._numerical_invariants[degree] = []
1204 Mext = extendx(M, degree, verbose, parallelComp)
1205 M = extendy(Mext, (degree + 1), verbose, parallelComp)
1206 if isinstance(M, tuple):
1207 if partial_result:
1208 return M[0]
1209 else:
1210 raise ValueError(
1211 'could not cover all relations in max iterations in degree {}'.format((degree + 1)))
1212 self._minimalmodels[degree] = M
1213 return M
1214
[docs]
1215 def one(self):
1216 components = {}
1217 for dim in range((self._dimension + 1)):
1218 A = self._apl_algebras.n_th_object(dim)
1219 for sigma in self.K._n_cells_sorted(dim):
1220 components[sigma] = A.one()
1221 return self.element_class()(self, components, check=False)
1222
[docs]
1223 def reset_data(self):
1224 self._gens = {}
1225 self._apl_algebras = {}
1226 self._hodge = {}
1227 self._hodge_matrix_decompositions = {}
1228 self._minimalmodels = {}
1229 self._numerical_invariants = {}
1230 self._coboundaries = {}
1231 self._cocycles = {}
1232 self._cohomology_raw = {}
1233 self._cohomology = {}
1234 self._ch_vector = self._get_cohomology_dimensions()
1235 self._apl_algebras = SimplicialAPL(self._dimension)
1236 self._gens = {'hodge': {}, 'whitney': {}}
1237 for d in range((self.K.dimension() + 1)):
1238 self._gens['hodge'][d] = {
1239 'harmonics': {}, 'exacts': {}, 'coexacts': {}}
1240 self._gens['whitney'][d] = {
1241 'harmonics': {}, 'exacts': {}, 'coexacts': {}}
1242 self._hodge = Hodge(self.K)
1243 self._hodge_matrix_decompositions = {}
1244 return None
1245
[docs]
1246 def save(self, filename='WData_temp'):
1247 data = self._pack_data()
1248 save(dumps([self, data]), filename)
1249 return None
1250
1264
1286
[docs]
1287 def aplk_genset(self, dim, degt = 1, check=False):
1288
1289 S = self._apl_algebras
1290 A = S.n_th_object(dim)
1291 R = A.base_ring()
1292 rgens = R.monomials_of_degree(degt)
1293 hodge = self.hodge()
1294 harmonic_basis = hodge.harmonic_basis(dim)
1295 exact_basis = hodge.exact_basis(dim)
1296 coexact_basis = hodge.coexact_basis(dim)
1297 cells = self.K._n_cells_sorted(dim)
1298 wf = A.whitney_form()
1299 genset = []
1300 for basis in [harmonic_basis, exact_basis, coexact_basis]:
1301 for v in basis:
1302 for t in rgens:
1303 components = self.zero()._components
1304 for (i, c) in enumerate(v):
1305 components[cells[i]] += A((c* A(t) * wf))
1306 for dim_to in range((dim + 1), (self._dimension + 1)):
1307 cofaces = self.K._n_cells_sorted(dim_to)
1308 face_data = self._face_data(dim, dim_to)
1309 ncells = len(cofaces)
1310 Ato = S.n_th_object(dim_to)
1311 for face in face_data.keys():
1312 face_matrix = face_data[face].T
1313 w = (face_matrix * v)
1314 #sgn = sgn_face(face)
1315 for (j, c) in enumerate(w):
1316 components[cofaces[j]] += (
1317 Ato((c * S.affine_map(faces=face, dim=dim_to, coef=Ato(t), normalized=True))))
1318 gen = self.element_class()(self, components, check)
1319 genset += [gen]
1320 return genset
1321
[docs]
1322 def zero(self):
1323 components = {}
1324 for dim in range((self._dimension + 1)):
1325 A = self._apl_algebras.n_th_object(dim)
1326 for sigma in self.K._n_cells_sorted(dim):
1327 components[sigma] = A.zero()
1328 return self.element_class()(self, components, check=False)
1329
1330
[docs]
1331class APLKElement(Element):
1332
1333 def __getitem__(self, sigma):
1334 return self._components[sigma]
1335
1336 def __init__(self, parent, components, check=False):
1337 self._components = components
1338 self._base_ring = parent.base_ring()
1339 Element.__init__(self, parent)
1340 if check:
1341 print(
1342 '(WhitneyForm Element Constructor) Checking compatibility...', flush=True)
1343 parent._check_compatibility(components)
1344 self._vector = None
1345 self._hodge_decomp = ()
1346 self._hodge_whitney_decomp = ()
1347 self._coords = {}
1348 self._repr_str = None
1349
1350 def __neg__(self):
1351 return ((- 1) * self)
1352
1353 def __pow__(self, n):
1354 components = {}
1355 for sigma in self._components:
1356 components[sigma] = prod((n * [self._components[sigma]]))
1357 return self.parent().element_class()(self.parent(), components, check=False)
1358
1359 def _add_(self, other):
1360 components = {}
1361 for sigma in self._components:
1362 components[sigma] = (self._components[sigma] +
1363 other._components[sigma])
1364 return self.parent().element_class()(self.parent(), components, check=False)
1365
1366 def _div_(self, other):
1367 if (not other.is_constant()):
1368 raise ValueError(f'the element {other} is not constant')
1369 components = {}
1370 other_red = other.reduce(0)
1371 for sigma in self._components:
1372 components[sigma] = (
1373 self._components[sigma] / QQ(other_red._components[sigma].leading_coefficient()))
1374 return self.parent().element_class()(self.parent(), components, check=False)
1375
1376 def _mul_(self, other):
1377 components = {}
1378 for sigma in self._components:
1379 components[sigma] = (self._components[sigma]
1380 * other._components[sigma])
1381 return self.parent().element_class()(self.parent(), components, check=False)
1382
1383 def _repr_(self):
1384 if self._repr_str:
1385 return self._repr_str
1386 W = self.parent()
1387 d = self.degree()
1388
1389 if self.is_zero():
1390 self._repr_str = '0'
1391 return self._repr_str
1392
1393 elif self.integral()==0:
1394 self._repr_str = '[non-zero ker_oint]'
1395 return self._repr_str
1396
1397 def terms_str(coords, names):
1398 terms = []
1399 for (c, g) in zip(coords, names):
1400 if c:
1401 if (c != 1):
1402 coeff = (('(' + str(c)) + ')*')
1403 else:
1404 coeff = ''
1405 terms += [(coeff + g)]
1406 return terms
1407
1408 def str_component(coords, names):
1409 prefix = ''
1410 suffix = ''
1411 if (len(coords.nonzero_positions()) > 1):
1412 prefix = '['
1413 suffix = ']'
1414 return ((prefix + ' + '.join(terms_str(coords, names))) + suffix)
1415 coords = self.coordinates()
1416 h_coords = coords['harmonic_coords']
1417 e_coords = coords['exact_coords']
1418 c_coords = coords['coexact_coords']
1419 harmonic_component = ''
1420 exact_component = ''
1421 coexact_component = ''
1422 if (h_coords != 0):
1423 h_names = W._gens_names_harmonics(d)
1424 h_gcd = gcd(h_coords)
1425 if (h_gcd == 1):
1426 h_gcd_str = ''
1427 else:
1428 h_coords = (h_coords / h_gcd)
1429 h_gcd_str = (('[' + str(h_gcd)) + ']*')
1430 harmonic_component = str_component(h_coords, h_names)
1431 if (h_gcd != 1):
1432 harmonic_component = (h_gcd_str + harmonic_component)
1433 if (e_coords != 0):
1434 e_names = W._gens_names_exacts(d)
1435 e_gcd = gcd(e_coords)
1436 if (e_gcd == 1):
1437 e_gcd_str = ''
1438 else:
1439 e_coords = (e_coords / e_gcd)
1440 e_gcd_str = (('[' + str(e_gcd)) + ']*')
1441 exact_component = str_component(e_coords, e_names)
1442 prefix = ''
1443 if h_coords:
1444 prefix = ' + '
1445 if (e_gcd != 1):
1446 exact_component = ((prefix + e_gcd_str) + exact_component)
1447 if (c_coords != 0):
1448 c_names = W._gens_names_coexacts(d)
1449 c_gcd = gcd(c_coords)
1450 if (c_gcd == 1):
1451 c_gcd_str = ''
1452 else:
1453 c_coords = (c_coords / c_gcd)
1454 c_gcd_str = (('[' + str(c_gcd)) + ']*')
1455 coexact_component = str_component(c_coords, c_names)
1456 prefix = ''
1457 if (h_coords or e_coords):
1458 prefix = ' + '
1459 if (c_gcd != 1):
1460 coexact_component = ((prefix + c_gcd_str) + coexact_component)
1461 self._repr_str = ((harmonic_component + exact_component) + coexact_component)
1462 return self._repr_str
1463
1464 def _richcmp_(self, other, op):
1465 if (op == op_EQ):
1466 if (self._components.keys() != other._components.keys()):
1467 return False
1468 for sigma in self._components:
1469 if (self._components[sigma].reduce(0) != other._components[sigma].reduce(0)):
1470 return False
1471 return True
1472 elif (op == op_NE):
1473 return (not self._richcmp_(other, op_EQ))
1474 else:
1475 raise NotImplementedError(
1476 'operation not implemented for this element class')
1477
1478 def _sub_(self, other):
1479 components = {}
1480 for sigma in self._components:
1481 components[sigma] = (self._components[sigma] -
1482 other._components[sigma])
1483 return self.parent().element_class()(self.parent(), components, check=False)
1484
[docs]
1485 def base_ring(self):
1486 return self._base_ring
1487
[docs]
1488 def check(self):
1489 red_el = self.reduce(0)
1490 for homog in red_el.homogeneous_components().values():
1491 self.parent()._check_compatibility(homog._components)
1492 return True
1493
[docs]
1494 def coefficient(self):
1495 if (self.degree() == 0):
1496 return self
1497 W = self.parent()
1498 S = W._apl_algebras
1499 K = W.K
1500 dim = self.degree()
1501 components = W.zero()._components
1502 A = W._apl_algebras.n_th_object(dim)
1503 ncells = set(K.n_cells(dim))
1504 nkeys = set(self._components.keys())
1505 for sigma in ncells.intersection(nkeys):
1506 p = self._components[sigma].reduce(0)
1507 if (not p.is_zero()):
1508 coeff = p.leading_coefficient()
1509 components[sigma] = A(coeff)
1510 for d in reversed(range(dim)):
1511 A = W._apl_algebras.n_th_object(d)
1512 upperDims = (dim - d)
1513 faces = list(combinations(range((dim + 1)), upperDims))
1514 for face in faces:
1515 coface_morph = W._coface_coeff_endomorphism(face, dim, d)
1516 for sigma in K.n_cells(dim):
1517 f_sigma = sigma
1518 for f in reversed(face):
1519 f_sigma = K.face(f_sigma, f)
1520 components[f_sigma] = A(coface_morph(components[sigma]))
1521 for d in range((dim + 1), K.dimension()):
1522 A = W._apl_algebras.n_th_object(d)
1523 upperDims = (d - dim)
1524 faces = list(combinations(range((d + 1)), upperDims))
1525 for face in faces:
1526 coface_morph = W._coface_coeff_endomorphism(face, dim, d)
1527 for sigma in K.n_cells(d):
1528 f_sigma = sigma
1529 for f in face:
1530 f_sigma = K.face(f_sigma, f)
1531 components[sigma] = (
1532 ((- 1) ** sgn_face(face)) * A(coface_morph(components[f_sigma])))
1533 return self.parent().element_class()(self.parent(), components, check=False)
1534
[docs]
1535 def coordinates(self):
1536 if self._coords:
1537 return self._coords
1538 else:
1539 self._coords = self.parent()._get_coordinates(self)
1540 return self._coords
1541
[docs]
1542 def degree(self):
1543 degrees = set()
1544 W = self.parent()
1545 for (sigma, f) in self._components.items():
1546 A = W._apl_algebras.n_th_object(sigma.dimension())
1547 if (not f.is_zero()):
1548 deg = A(f).degree()
1549 if (deg in range((A.n + 1))):
1550 degrees.add(deg)
1551 if (len(degrees) == 1):
1552 return degrees.pop()
1553 else:
1554 return (- 1)
1555
[docs]
1556 def dif(self, check=False):
1557 r"""
1558 Alias for :meth:`differential`
1559 """
1560 return self.differential(check)
1561
[docs]
1562 def differential(self, check=False):
1563 components = {}
1564 for sigma in self._components:
1565 components[sigma] = self._components[sigma].differential().reduce(0)
1566 return self.parent().element_class()(self.parent(), components, check)
1567
[docs]
1568 def dup(self, check=False):
1569 r"""
1570 Alias for :meth:`dupont_contraction`
1571 """
1572 return self.dupont_contraction(check)
1573
[docs]
1574 def dupont_contraction(self, check=False):
1575 r"""
1576 The Dupont\'s contraction of polynomial differential forms defined
1577 on a generic simplicial set `S` (see :cite:`dupont1976simplicial`).
1578 This method implements the Dupont\'s contraction
1579
1580 .. math::
1581
1582 s_n: A^{*}_{PL}(S_n) \rightarrow A^{*-1}_{PL}(S_n)
1583
1584 as it is described in :cite:`cheng2008transferring` (see also :cite:`dupont1976simplicial`).
1585
1586 Let :math:`\mathbb{K}` be a field of characteristic :math:`0` and let :math:`S = \{S_n\}_{n \geq 0}` be a
1587 simplicial set. Also, let :math:`A_{PL}(S)` be the algebra of polynomial differential forms defined on :math:`S`,
1588 and :math:`C^*(S)`, the simplicial cochain complex associated to :math:`S`.
1589
1590 Let :math:`I = \{i_0,\dots,i_p\}`, with :math:`0 \leq i_0 < \cdots < i_p \leq n,` and define
1591
1592 .. math::
1593
1594 J := [n] \smallsetminus I = \{j_0,\dots,j_q\}
1595
1596 such that :math:`0 \leq j_0 < \cdots < j_q \leq n` and :math:`p+q=n`.
1597
1598 Let :math:`\sigma_p \in S_p` and :math:`\sigma_n \in S_n` be two simplices of `S` such that,
1599 :math:`\partial_J(\sigma_n) = \sigma_p` where
1600
1601 .. math::
1602
1603 \partial_J = \partial_{j_0} \circ \cdots \circ \partial_{j_q}.
1604
1605 Let :math:`\beta \in C^p(S)`. The Whitney map (see :cite:`Whitney1957GeometricIT, WhitneyFormsLOHI`)
1606
1607 .. math::
1608
1609 \mathcal{W}^p = \{\mathcal{W}^p_n: C^p(S_p) \rightarrow A^p_{PL}(S_n)\}
1610
1611 is defined as:
1612
1613 .. math::
1614
1615 \mathcal{W}^p_n(\beta)(\sigma_n)|_{\sigma_p} = \beta(\sigma_p) \cdot n! \cdot \sum_{k=0}^{p} (-1)^j t_{i_k}
1616 y_{i_0} \wedge \cdots \wedge \hat{y}_{i_k} \wedge \cdots \wedge y_{i_p}
1617
1618 where the symbol :math:`\; \hat{} \;` means the term is omitted. The elements in the image of
1619 :math:`\mathcal{W}` are called the `elementary differential forms` or just `Whitney forms`.
1620 The motivation behind this notation is that the subset `I` comes from the inclusion
1621
1622 .. math::
1623
1624 i: \Delta^p \hookrightarrow{} \Delta^n
1625
1626 that, by the :math:`A_{PL}` functor translates to the inclusion of algebras:
1627
1628 .. math::
1629
1630 \begin{array}{cccc}
1631 A_{PL}(i): &(A_{PL})_p & \hookrightarrow{} & (A_{PL})_n \\
1632 & (t_0,\dots, t_p) &\rightarrow& (t_{i_0},\dots, t_{i_p})
1633 \end{array}
1634
1635
1636
1637 Finally, consider the de Rham map (see :cite:`Whitney1957GeometricIT, dupont1976simplicial, felix_rational_2001`):
1638
1639 .. math::
1640
1641 \int_n: A^n_{PL}(S) \rightarrow C^n(S)
1642
1643 Dupont constructed an explicit simplicial contraction of the commutative differential graded algebra
1644 of polynomial differential forms :math:`A_{PL}(S)` to :math:`C^*(S)` compatible with the intrinsic
1645 affine structure of the polynomial differential forms (affine relations) and also with
1646 the wedge product of forms (up to homotopy).
1647
1648 This method implements step by step the description of the contraction given
1649 by Cheng et al. (see :cite:`cheng2008transferring`), with minor notation adaptations for the sake
1650 of maintain coherence with the rest of the code. The description given by Cheng et al. is as follows:
1651
1652 For each vertex :math:`e_i` of the :math:`n`-simplex :math:`\Delta^n`, define the dilation map
1653
1654 .. math::
1655
1656 \phi_i : [0,1] \times \Delta^n \to \Delta^n
1657
1658 by the formula
1659
1660 .. math::
1661
1662 \phi_i(u,t_0, \dots, t_n) = ((1-u)t_0,\dots,(1-u)t_i+u,\dots,(1-u)t_n) .
1663
1664 Let
1665
1666 .. math::
1667
1668 (\pi_i){}_*:A^*_{PL}([0,1]\times\Delta^n) \rightarrow A^{*-1}_{PL}(\Delta^n)
1669
1670 be integration over the first factor.
1671
1672 Now, let :math:`\omega \in (A_{PL})_n` and define the operator
1673
1674 .. math::
1675
1676 h_n^i : A^*_{PL}(\Delta^n) \rightarrow A^{*-1}_{PL}(\Delta^n)
1677
1678 by the formula
1679
1680 .. math::
1681
1682 h_n^i\omega = (\pi_i)_* \phi_i^* \omega.
1683
1684 where :math:`\phi_i^* \omega` is the pullback of :math:`\omega` respect to :math:`\phi_i`.
1685
1686 Let
1687
1688 .. math::
1689
1690 \epsilon_n^i: A^*_{PL}(\Delta^n) \rightarrow \mathbb{K}
1691
1692 be evaluation at the vertex :math:`e_i`. The Poincar\'e Lemma states that
1693
1694 .. math::
1695
1696 \mathbb{1}_{A} - \epsilon_n^i = d \circ h_n^i + h_n^i \circ d .
1697
1698
1699 Now, let :math:`J^k:=\{\{i_0,\dots, i_{k-1}\} \; | \; 0 \leq i_0 < \cdots < i_{k-1} \leq n\}`,
1700 be the set of all subsets of :math:`\{0,\dots,n\}` with cardinality `k`.
1701
1702 **Theorem** (Dupont :cite:`dupont1976simplicial`):
1703
1704 The operator
1705
1706 .. math::
1707
1708 s_n(\omega) = \sum_{k=0}^{n-1} \sum_{I \in J^k} \mathcal{W}^I_n(1) \wedge (h^{i_k} \circ
1709 \cdots \circ h^{i_0})(\omega)
1710
1711 defines a simplicial contraction from :math:`A^*_{PL}(S)` to :math:`C^*(S)`:
1712
1713 .. math::
1714
1715 \mathcal{W}_n \circ \int_n - \mathbb{1}_{A} = d \circ s_n+s_n \circ d .
1716
1717 **Theorem** (Getzler :cite:`Getzler_2009`):
1718
1719 The side conditions
1720
1721 - :math:`\int_n \circ s_n = 0`
1722
1723 - :math:`s_n \circ s_n = 0`
1724
1725 hold.
1726
1727 .. SEEALSO::
1728
1729 :meth:`.AplN.Element.integral`
1730
1731 :meth:`.AplN.whitney_form`
1732
1733 :meth:`.AplN.Element.dupont_operator`
1734
1735 :meth:`.SimplicialAPL.whitney_map`
1736
1737 :meth:`.integral`
1738
1739
1740 .. REFERENCES::
1741
1742 - :cite:`Whitney1957GeometricIT`
1743
1744 - :cite:`dupont1976simplicial`
1745
1746 - :cite:`cheng2008transferring`
1747
1748 - :cite:`WhitneyFormsLOHI`
1749
1750 - :cite:`felix_rational_2001`
1751
1752
1753
1754 INPUT:
1755
1756 - ``p`` -- an element of ``self``.
1757
1758 - ``i`` -- integer; the vertex index to apply the operator
1759
1760 OUTPUT: an element of ``self``;
1761
1762 EXAMPLES::
1763
1764 sage: K = simplicial_complexes.Sphere(2)
1765 sage: W = WhitneyFormAlgebraComplex(K)
1766 sage: W.inject_variables()
1767 Getting generators of degree 0 ...
1768 Getting generators of degree 1 ...
1769 Getting generators of degree 2 ...
1770 Defining t0, t1, t2, t3, e1_0, e1_1, e1_2, c1_0, c1_1, c1_2, h2_0, e2_0, e2_1, e2_2
1771 sage: p = t0**2+t3**5
1772 sage: dp = p.differential()
1773 sage: wi = sum(dp.reduce(0).hodge_whitney_decomposition())
1774 sage: dp-wi == dp.dupont_contraction().differential()
1775 True
1776
1777 """
1778
1779 def contraction(p):
1780 A = p.parent()
1781 S = self.parent()._apl_algebras
1782 n = A.n
1783 result = A.zero()
1784 for k in range(n):
1785 simplices = list(combinations(range((n + 1)), (k + 1)))
1786 for sigma in simplices:
1787 facepath = tuple(sorted((set(range((n + 1))) - set(sigma))))
1788 #print(f"k ==> {k}, sigma ==> {sigma} and facepath==> {facepath} at dim {n}", flush=True)
1789 if not len(facepath) == n-k:
1790 raise RuntimeError("internal error using combinations "
1791 "at dupont_contraction method (AplK)")
1792 wf = S.whitney_map(facepath, n)
1793 dup = p
1794 for i in sigma:
1795 dup = dup.dupont_operator(i)
1796 result += (wf * dup)
1797 return result.reduce(0)
1798
1799 components = {}
1800 for (sigma, pol) in self._components.items():
1801 components[sigma] = contraction(self._components[sigma])
1802 return self.parent().element_class()(self.parent(), components, check)
1803
[docs]
1804 def get_preimage_exact_component(self):
1805 W = self.parent()
1806 deg = self.degree()
1807 lengthCoords = len(W.coexact_basis((deg - 1)))
1808 exact_basis = W.exact_basis(deg)
1809 exact_coords = self.coordinates()['exact_coords']
1810 if (exact_coords == 0):
1811 return W.zero()
1812 else:
1813 hodge = W.hodge()
1814 v = (hodge.exact_matrix(deg).T * exact_coords)
1815 preimage_cochain = hodge.preimage(v, deg)
1816 w = W.whitney_form_from_vector((deg - 1), preimage_cochain)
1817 return w
1818
[docs]
1819 def hodge_cochain_decomposition(self):
1820 if self._hodge_decomp:
1821 return self._hodge_decomp
1822 if self.is_zero():
1823 z = self.integral()
1824 return tuple(3*[z])
1825 hodge = self.parent().hodge()
1826 cochain = self.integral()
1827 deg = self.degree()
1828 self._hodge_decomp = hodge.hodge_cochain_decomposition(cochain, deg)
1829 return self._hodge_decomp
1830
[docs]
1831 def hodge_whitney_decomposition(self):
1832 if self._hodge_whitney_decomp:
1833 return self._hodge_whitney_decomp
1834 W = self.parent()
1835 hodge = W.hodge()
1836 (h, e, c) = self.hodge_cochain_decomposition()
1837 self._hodge_whitney_decomp = tuple(
1838 [W.whitney_form_from_vector(self.degree(), x) for x in (h, e, c)])
1839 return self._hodge_whitney_decomp
1840
[docs]
1841 def hodge_whitney_remainders(self):
1842 if (not (self.integral() == 0)):
1843 (wh, we, wc) = self.hodge_whitney_decomposition()
1844 harmonic_remainder = ((self - we) - wc)
1845 exact_remainder = ((self - wh) - wc)
1846 coexact_remainder = ((self - wh) - we)
1847 return (harmonic_remainder, exact_remainder, coexact_remainder)
1848 else:
1849 print('The element is a representative of the zero cochain....', flush=True)
1850 return ((), (), ())
1851
[docs]
1852 def homogeneous_components(self):
1853 degs = self.homogeneous_degrees()
1854 if (len(degs) == 1):
1855 return {degs[0]: self}
1856 reducedSelf = self.reduce(0)
1857 components = {}
1858 for d in degs:
1859 element = self.parent().zero()
1860 dcomp = self.parent().zero()._components
1861 for (sigma, f) in reducedSelf._components.items():
1862 element._components[sigma] = f.homogeneous_component(d)
1863 if (not element.is_zero()):
1864 components[d] = element
1865 return components
1866
[docs]
1867 def homogeneous_degrees(self):
1868 degs = []
1869 for (sigma, f) in self._components.items():
1870 homComps = f.homogeneous_components()
1871 if isinstance(homComps, dict):
1872 degs += list(homComps.keys())
1873 elif (not self.is_zero()):
1874 degs += [self.degree()]
1875 else:
1876 degs += [0]
1877 return list(set(degs))
1878
[docs]
1879 def is_closed(self):
1880 if (self.differential().reduce(0) == 0):
1881 return True
1882 return False
1883
[docs]
1884 def is_coexact(self):
1885 (rem_H, rem_E, rem_C) = self.hodge_whitney_remainders()
1886 if ((isinstance(rem_H, APLKElement) and rem_H.is_zero()) or (rem_H == 0)):
1887 if ((isinstance(rem_E, APLKElement) and rem_E.is_zero()) or (rem_E == 0)):
1888 if (not rem_C.is_zero()):
1889 return True
1890 return False
1891
[docs]
1892 def is_cohomologous_to(self, other):
1893 if other.is_zero():
1894 return self.is_exact()
1895 if ((not isinstance(other, self.parent().element_class())) or (self.parent() is not other.parent())):
1896 raise ValueError(f'the element {other} does not lie in this CDGA')
1897 difference = (self - other)
1898 if difference.is_homogeneous():
1899 return (difference.is_exact() or difference.is_zero())
1900 return (self.is_exact() and other.is_exact())
1901
[docs]
1902 def is_constant(self):
1903 if (self.degree() != 0):
1904 return False
1905 components = {}
1906 w = self.reduce(0)
1907 for sigma in w._components:
1908 if (not (w._components[sigma].leading_coefficient().degree() == 0)):
1909 return False
1910 return True
1911
[docs]
1912 def is_exact(self):
1913 (rem_H, rem_E, rem_C) = self.hodge_whitney_remainders()
1914 if ((isinstance(rem_H, APLKElement) and rem_H.is_zero()) or (rem_H == 0)):
1915 if ((isinstance(rem_C, APLKElement) and rem_C.is_zero()) or (rem_C == 0)):
1916 if (not rem_E.is_zero()):
1917 return True
1918 return False
1919
[docs]
1920 def is_harmonic(self):
1921 (rem_H, rem_E, rem_C) = self.hodge_whitney_remainders()
1922 if ((isinstance(rem_E, APLKElement) and rem_E.is_zero()) or (rem_E == 0)):
1923 if ((isinstance(rem_C, APLKElement) and rem_C.is_zero()) or (rem_C == 0)):
1924 if (not rem_H.is_zero()):
1925 return True
1926 return False
1927
[docs]
1928 def is_homogeneous(self):
1929 if self.is_zero():
1930 return True
1931 homogeneous = True
1932 for (sigma, f) in self._components.items():
1933 if (not f.is_zero()):
1934 homogeneous = (homogeneous and f.is_homogeneous())
1935 if (not homogeneous):
1936 return False
1937 return True
1938
[docs]
1939 def is_zero(self):
1940 return (self.reduce(0) == self.parent().zero())
1941
[docs]
1942 def leading_coefficient(self):
1943 coeffs = self.leading_coefficients()
1944 if (not coeffs):
1945 return (0, 0)
1946 degrees = [c[1] for c in coeffs]
1947 idx = degrees.index(max(degrees))
1948 return coeffs[idx]
1949
[docs]
1950 def leading_coefficients(self):
1951 if self.is_zero():
1952 return []
1953 W = self.parent()
1954 K = W.K
1955 cells = K.n_cells(self.degree())
1956 components = self._components
1957 coeffs = []
1958 for sigma in cells:
1959 if ((sigma in components) and components[sigma]):
1960 coeffs += [self._components[sigma].leading_coefficient()]
1961 degrees = [e.degree() for e in coeffs]
1962 return list(set(zip(coeffs, degrees)))
1963
[docs]
1964 def reduce(self, i=0):
1965 components = {}
1966 for sigma in self._components:
1967 components[sigma] = self._components[sigma].reduce(i)
1968 return self.parent().element_class()(self.parent(), components, check=False)
1969
[docs]
1970 def solve_primitive(self, verbose=False):
1971 if self.differential():
1972 raise ValueError('The element is not closed.')
1973 W = self.parent()
1974 K = W.K
1975 S = W._apl_algebras
1976 result = W.zero()
1977 for (deg, homo) in self.homogeneous_components().items():
1978 wi = homo.get_preimage_exact_component().reduce(0)
1979 if verbose:
1980 print('(1/3) Trying to get a Whitney form primitive...', flush=True)
1981 if (wi.differential().reduce(0) == homo.reduce(0)):
1982 result += wi
1983 else:
1984 if verbose:
1985 print(
1986 ' (2/3) Trying to get a primitive with the Dupont contraction ==> (ds+sd) == (wi-p)...', flush=True)
1987 s = homo.dupont_contraction().reduce(0)
1988 if ((wi - s).differential().reduce(0) == homo.reduce(0)):
1989 result += wi - s
1990 else:
1991 if verbose:
1992 print('(3/3) Trying the brute-force approach...', flush=True)
1993 print("", flush=True)
1994 print(f"(wi-s).dif() ==> {(wi-s).differential().reduce(0)}", flush=True)
1995 print("", flush=True)
1996 b0 = W.basis(0)
1997 b2 = W.basis((homo.degree() - 1))
1998 deg_t = homo.reduce(0).leading_coefficient()[1]
1999 deg0_coefs = [prod(c)
2000 for c in cartesian_product((deg_t * [b0]))]
2001 b02 = [prod(c) for c in cartesian_product(
2002 [deg0_coefs, b2]) if prod(c).differential()]
2003 db02 = [g.differential().reduce(0) for g in b02]
2004 rows = [g.terms_repr(deg_t) for g in db02]
2005 m = matrix(QQ, len(db02), rows, sparse=True)
2006 vdp = homo.reduce(0).terms_repr(deg_t)
2007 coords = m.T.solve_right(vdp)
2008 primitive = sum([prod(c) for c in zip(coords, b02)])
2009 assert (primitive.differential().reduce(
2010 0) == homo.reduce(0))
2011 result += primitive
2012 return result
2013
[docs]
2014 def str(self):
2015 return {sigma: f for (sigma, f) in self._components.items() if (not f.is_zero())}
2016
[docs]
2017 def terms_repr(self, deg_t=[]):
2018 K = self.parent().K
2019 list_repr = []
2020 if (not deg_t):
2021 deg_t = self.leading_coefficient()[1]
2022 deg_y = self.degree()
2023 for f in K.facets():
2024 pol = self._components[f]
2025 if pol:
2026 v = pol._to_extended_graded_module(
2027 deg_y=deg_y, deg_t=deg_t).to_vector()
2028 else:
2029 n = len(pol.parent().extended_basis(
2030 deg_y=deg_y, deg_t=deg_t, cum=True))
2031 v = vector(QQ, (n * [0]))
2032 list_repr.append(list(v))
2033 return vector(QQ, flatten(list_repr), sparse=True)
2034
[docs]
2035 def to_AplK(self, reduce=None):
2036 aplK_dict = {}
2037 for dim in range((self.parent().dimension() + 1)):
2038 for sigma in self.parent().K._n_cells_sorted(dim):
2039 f_sigma = self._components[sigma]
2040 if ((not (reduce == None)) and (reduce in ZZ) and (reduce in range((f_sigma.parent().n + 1)))):
2041 f_sigma = f_sigma.reduce(reduce)
2042 if f_sigma.is_zero():
2043 continue
2044 aplK_dict[sigma] = f_sigma
2045 return aplK_dict
2046
[docs]
2047 def to_cochain(self):
2048 cochain = {}
2049 for dim in range((self.parent().dimension() + 1)):
2050 for sigma in self.parent().K._n_cells_sorted(dim):
2051 f_sigma = self._components[sigma]
2052 if f_sigma.is_zero():
2053 continue
2054 if (f_sigma.degree() == dim):
2055 try:
2056 val = f_sigma.integral()
2057 if (val != 0):
2058 cochain[sigma] = val
2059 except (AttributeError, ValueError):
2060 if (not f_sigma.is_zero()):
2061 cochain[sigma] = f_sigma.leading_coefficient()
2062 return cochain
2063
[docs]
2064 def integral(self):
2065 r"""
2066 Returns the integral of ``self``.
2067
2068 George De Rham :cite:`de1931analysis` in the 1930\'s proved that integration provides a natural direct
2069 quasi-isomorphism of cochain complexes that connects the algebra of differential forms
2070 (in this context :math:`(A_{PL}(K)`) with the cochain complex :math:`C^*(K)`:
2071
2072 .. math::
2073
2074 \oint : A_{PL}(K) \rightarrow C^*(K)
2075
2076 as follows. Let :math:`\int_{n}` be the linear map:
2077
2078 .. math::
2079
2080 \int_{n}: (A_{PL})_{n}^{n} \rightarrow \mathbb{Q}
2081
2082 by setting
2083
2084 .. math::
2085 :nowrap:
2086
2087 \begin{split}
2088 \int_{n}t_1^{k_1}\dots t_n^{k_n}dt_1 \wedge \dots \wedge dt_n &= \int_{0}^{1} dt_1\int_{0}^{1-t_1} dt_2 \dots\\
2089 &\dots \int_{0}^{1-\sum\limits_{1}^{n-1}t_i}t_1^{k_1}\dots t_n^{k_n}dt_n = \\
2090 &= \frac{k_1!k_2! \dots k_n!}{(k_1+ \dots +k_n+n)!}.
2091 \end{split}
2092
2093 This map represents the integration :math:`\int_{\Delta^n}\omega` of an `n`-form
2094 :math:`\omega \in (A_{PL})^n_n` over the standard `n`-simplex :math:`\Delta^n`.
2095 Using this map, we can integrate elements of :math:`A_{PL}(K)` as follows: consider a homogeneous
2096 element :math:`\Phi^n_n \in A^n_{PL}(K_n)`. Its integral is the element of :math:`C^n(K)` determined
2097 by the integration map:
2098
2099 .. math::
2100
2101 \left(\oint(\Phi^n_n)\right)(\sigma) = \int_{n}\Phi^n_n(\sigma),
2102
2103 for every :math:`\sigma \in K_n`. For homogeneous elements :math:`\Phi^n_m\in A^n_{PL}(K_m)`
2104 with :math:`n\neq m`, the integral is set to zero (:math:`\left(\oint(\Phi^n_m)\right)(\sigma)=0`).
2105 Then, the map is extended to all :math:`A_{PL}(K)` by linearity.
2106
2107 OUTPUT: a vector represented the cochain element.
2108
2109 EXAMPLES::
2110
2111 sage: from Sullivan_MM import *
2112 sage: S2 = simplicial_complexes.Sphere(2)
2113 sage: K = S2.wedge(S2)
2114 sage: K.set_immutable()
2115 sage: W = WhitneyFormAlgebraComplex(K)
2116 sage: W.inject_variables()
2117 Getting generators of degree 0 ...
2118 Getting generators of degree 1 ...
2119 Getting generators of degree 2 ...
2120 Defining t0, t1, t2, t3, t4, t5, t6, e1_0, e1_1, e1_2, e1_3, e1_4, e1_5, c1_0, c1_1, c1_2, c1_3, c1_4,
2121 c1_5, h2_0, h2_1, e2_0, e2_1, e2_2, e2_3, e2_4, e2_5
2122 sage: e2_1.integral()
2123 (0, 1, 0, 0, 0, 0, -1, 0)
2124 sage: W.whitney_form_from_vector(v=e2_1.integral(),dim=2) == e2_1
2125 True
2126 """
2127 if self._vector:
2128 return self._vector
2129 W = self.parent()
2130 assert (self.is_homogeneous() or self.is_zero())
2131 deg = self.degree()
2132 cells = W.K._n_cells_sorted(deg)
2133 if (deg == 0):
2134 base_ring = QQ
2135 values = zero_vector(base_ring, len(cells))
2136 for (i, sigma) in enumerate(cells):
2137 p = self._components[sigma].reduce(0)
2138 if p:
2139 values[i] = p.leading_coefficient()
2140 self._vector = vector(base_ring, len(cells), values, sparse=True)
2141 else:
2142 values = []
2143 for sigma in cells:
2144 c = 0
2145 if (sigma in self._components.keys()):
2146 p = self._components[sigma].reduce(0)
2147 c = p.integral()
2148 values.append(c)
2149 self._vector = vector(QQ, len(cells), values, sparse=True)
2150 return self._vector
2151
2152
[docs]
2153class MorphismFromQQToAPLK(Morphism):
2154 def __init__(self, codomain):
2155 self.constant = codomain.constant
2156 Morphism.__init__(self, QQ, codomain)
2157
2158 def _call_(self, x):
2159 return self.constant(x)
2160
2161
[docs]
2162class CohomologyClass(SageObject, CachedRepresentation):
2163 """
2164 A class for representing cohomology classes.
2165
2166 This just has ``_repr_`` and ``_latex_`` methods which put
2167 brackets around the object's name.
2168
2169 EXAMPLES::
2170
2171 sage: from sage.algebras.commutative_dga import CohomologyClass
2172 sage: CohomologyClass(3)
2173 [3]
2174 sage: A.<x,y,z,t> = GradedCommutativeAlgebra(QQ, degrees=(2,2,3,3))
2175 sage: CohomologyClass(x^2 + 2*y*z, A)
2176 [2*y*z + x^2]
2177
2178 TESTS:
2179
2180 In order for the cache to not confuse objects with the same representation,
2181 we can pass the parent of the representative as a parameter::
2182
2183 sage: A.<e1,e2,e3,e4,e5,e6> = GradedCommutativeAlgebra(QQ)
2184 sage: B1 = A.cdg_algebra({e5:e1*e2,e6:e3*e4})
2185 sage: B2 = A.cdg_algebra({e5:e1*e2,e6:e1*e2+e3*e4})
2186 sage: B1.minimal_model()
2187 Commutative Differential Graded Algebra morphism:
2188 From: Commutative Differential Graded Algebra with generators ('x1_0', 'x1_1', 'x1_2', 'x1_3', 'y1_0', 'y1_1') in degrees (1, 1, 1, 1, 1, 1) over Rational Field with differential:
2189 x1_0 --> 0
2190 x1_1 --> 0
2191 x1_2 --> 0
2192 x1_3 --> 0
2193 y1_0 --> x1_0*x1_1
2194 y1_1 --> x1_2*x1_3
2195 To: Commutative Differential Graded Algebra with generators ('e1', 'e2', 'e3', 'e4', 'e5', 'e6') in degrees (1, 1, 1, 1, 1, 1) over Rational Field with differential:
2196 e1 --> 0
2197 e2 --> 0
2198 e3 --> 0
2199 e4 --> 0
2200 e5 --> e1*e2
2201 e6 --> e3*e4
2202 Defn: (x1_0, x1_1, x1_2, x1_3, y1_0, y1_1) --> (e1, e2, e3, e4, e5, e6)
2203 sage: B2.minimal_model()
2204 Commutative Differential Graded Algebra morphism:
2205 From: Commutative Differential Graded Algebra with generators ('x1_0', 'x1_1', 'x1_2', 'x1_3', 'y1_0', 'y1_1') in degrees (1, 1, 1, 1, 1, 1) over Rational Field with differential:
2206 x1_0 --> 0
2207 x1_1 --> 0
2208 x1_2 --> 0
2209 x1_3 --> 0
2210 y1_0 --> x1_0*x1_1
2211 y1_1 --> x1_2*x1_3
2212 To: Commutative Differential Graded Algebra with generators ('e1', 'e2', 'e3', 'e4', 'e5', 'e6') in degrees (1, 1, 1, 1, 1, 1) over Rational Field with differential:
2213 e1 --> 0
2214 e2 --> 0
2215 e3 --> 0
2216 e4 --> 0
2217 e5 --> e1*e2
2218 e6 --> e1*e2 + e3*e4
2219 Defn: (x1_0, x1_1, x1_2, x1_3, y1_0, y1_1) --> (e1, e2, e3, e4, e5, -e5 + e6)
2220 """
2221 def __init__(self, rep, cdga=None):
2222 """
2223 EXAMPLES::
2224
2225 sage: from sage.algebras.commutative_dga import CohomologyClass
2226 sage: CohomologyClass(x - 2) # needs sage.symbolic
2227 [x - 2]
2228 """
2229 self._name = str(rep)
2230 self._rep = rep
2231 self._cdga = cdga
2232
2233 def __hash__(self):
2234 r"""
2235 TESTS::
2236
2237 sage: from sage.algebras.commutative_dga import CohomologyClass
2238 sage: hash(CohomologyClass(sin)) == hash(sin) # needs sage.symbolic
2239 True
2240 """
2241 return hash(self._name)
2242
2243 def _repr_(self):
2244 """
2245 EXAMPLES::
2246
2247 sage: from sage.algebras.commutative_dga import CohomologyClass
2248 sage: CohomologyClass(sin) # needs sage.symbolic
2249 [sin]
2250 """
2251 return '[{}]'.format(self._name)
2252
2253 def _latex_(self):
2254 r"""
2255 EXAMPLES::
2256
2257 sage: from sage.algebras.commutative_dga import CohomologyClass
2258 sage: latex(CohomologyClass(sin)) # needs sage.symbolic
2259 \left[ \sin \right]
2260 sage: latex(CohomologyClass(x^2)) # needs sage.symbolic
2261 \left[ x^{2} \right]
2262 """
2263 from sage.misc.latex import latex
2264 return '\\left[ {} \\right]'.format(latex(self._name))
2265
[docs]
2266 def representative(self):
2267 """
2268 Return the representative of ``self``.
2269
2270 EXAMPLES::
2271
2272 sage: from sage.algebras.commutative_dga import CohomologyClass
2273 sage: x = CohomologyClass(sin) # needs sage.symbolic
2274 sage: x.representative() == sin # needs sage.symbolic
2275 True
2276 """
2277 return self._rep
2278
2279
[docs]
2280class MinimalModel(SageObject, UniqueRepresentation, CachedRepresentation):
2281
2282 def __init__(self, domain, codomain, names, gens, numerical_invariants=None, base_ring=QQ):
2283
2284 self._base_ring = base_ring
2285 self._cdga = domain
2286 self._aplk_algebra = codomain
2287 self._imgens = {name: gen for (name, gen) in zip(names, gens)}
2288 self._hodge_decomps = {}
2289 self._cohomology = {}
2290 self._cohomology_raw = {}
2291 self._harmonic_basis = {}
2292 self._coexact_basis = {}
2293
2294 if numerical_invariants:
2295 self._numerical_invariants = loads(numerical_invariants)
2296 else:
2297 self._numerical_invariants = {}
2298
[docs]
2299 def numerical_invariants(self):
2300 return self._numerical_invariants
2301
2302 # def _coexact_basis_raw(self, deg):
2303 # if (not (deg in self._hodge_decomps.keys())):
2304 # self._hodge_decomps[deg] = self.hodge_subspaces_decomposition_raw(
2305 # deg)
2306 # return self.hodge_basis_decomposition_raw[deg]['coexacts']
2307
2308 # def _exact_basis_raw(self, deg):
2309 # if (not (deg in self._hodge_decomps.keys())):
2310 # self._hodge_decomps[deg] = self.hodge_subspaces_decomposition_raw(
2311 # deg)
2312 # return self.hodge_basis_decomposition_raw[deg]['exacts']
2313
2314 def _gens_from_subspace(self, n, VS):
2315 A = self.domain()
2316 B = A.basis(n)
2317 basis_raw = (VS.lift(VS.basis()[i]) for i in range(VS.dimension()))
2318 basis = []
2319 for coeffs in basis_raw:
2320 element = sum([(c * b) for (c, b) in zip(list(coeffs), B)])
2321 if (not element.is_zero()):
2322 basis += [element]
2323 return basis
2324
2325 def _get_free_module(self, n, VS):
2326 A = self.domain()
2327 M_basis = self._gens_from_subspace(n, VS)
2328 M_basis_brackets = [CohomologyClass(b, A) for b in M_basis]
2329 return CombinatorialFreeModule(A.base_ring(), M_basis_brackets, sorting_key=sorting_keys, monomial_reverse=True)
2330
2331 def _harmonic_basis_raw(self, deg):
2332 if (not (deg in self._hodge_decomps.keys())):
2333 self._hodge_decomps[deg] = self.hodge_subspaces_decomposition_raw(deg)
2334 return self.hodge_basis_decomposition_raw[deg]['harmonics']
2335
2336 def _repr_(self):
2337 return f'Minimal Model of the {self._aplk_algebra}'
2338
2339 # def add_coexacts(self, deg, gens):
2340 # if (not (deg in self._coexact_basis.keys())):
2341 # self._coexact_basis[deg] = gens
2342 # else:
2343 # self._coexact_basis[deg].append(gens)
2344 #
2345 # def add_harmonics(self, deg, gens):
2346 # if (not (deg in self._harmonic_basis.keys())):
2347 # self._harmonic_basis[deg] = gens
2348 # else:
2349 # self._harmonic_basis[deg].update(gens)
2350 # self.hodge_subspaces_decomposition_raw(deg, update=True)
2351 # return None
2352
[docs]
2353 def basis(self, n):
2354 return self._cdga.basis(n)
2355
[docs]
2356 def coboundaries(self, n):
2357 Y = self.coboundaries_raw(n)
2358 return self._get_free_module(n, Y)
2359
[docs]
2360 def coboundaries_raw(self, n):
2361 A = self.domain()
2362 F = A.base_ring()
2363 if (n == 0):
2364 return VectorSpace(F, 0, sparse=True)
2365 if (n == 1):
2366 V0 = VectorSpace(F, len(A.basis(1)), sparse=True)
2367 return V0.subspace([])
2368 D = self.differential(n)
2369 return D.image()
2370
[docs]
2371 def cocycles(self, n):
2372 X = self.cocycles_raw(n)
2373 return self._get_free_module(n, X)
2374
[docs]
2375 def cocycles_raw(self, n):
2376 A = self.domain()
2377 F = A.base_ring()
2378 if (n == 0):
2379 return VectorSpace(F, 1, sparse=True)
2380 D = self.differential(n)
2381 return D.right_kernel()
2382
[docs]
2383 def codomain(self):
2384 return self._aplk_algebra
2385
[docs]
2386 def coexact_gens(self, deg):
2387 Y = self.hodge_subspaces_decomposition_raw(deg)['coexacts']
2388 return self._gens_from_subspace(deg, Y)
2389
[docs]
2390 def cohomology(self, n):
2391 H = self.cohomology_raw(n)
2392 return self._get_free_module(n, H)
2393
[docs]
2394 def cohomology_raw(self, n):
2395 return self.domain().cohomology_raw(n)
2396 return self.hodge_subspaces_decomposition_raw(n)['harmonics']
2397
[docs]
2398 def differential(self, deg):
2399 return self._cdga.differential().differential_matrix(deg).sparse_matrix().T
2400
[docs]
2401 def domain(self):
2402 return self._cdga
2403
[docs]
2404 def exact_gens(self, deg):
2405 X = self.hodge_subspaces_decomposition_raw(deg)['exacts']
2406 return self._gens_from_subspace(deg, X)
2407
[docs]
2408 def harmonic_gens(self, deg):
2409 H = self.cohomology_raw(deg)
2410 return self._gens_from_subspace(deg, H)
2411
[docs]
2412 def hodge_basis_decomposition_raw(self, deg):
2413 if (not (deg in self._hodge_decomps.keys())):
2414 self._hodge_decomps[deg] = self.hodge_subspaces_decomposition_raw(deg)
2415 return {k: S.basis() for (k, S) in self._hodge_decomps[deg].items()}
2416
[docs]
2417 def hodge_subspaces_decomposition_raw(self, deg, update=True):
2418 if ((deg in self._hodge_decomps.keys()) and (not update)):
2419 return self._hodge_decomps[deg]
2420 dif_prev = self.differential((deg - 1))
2421 dif_curr = self.differential(deg)
2422 ngens = len(self.basis(deg))
2423 cobo_mat_prev = self.coboundaries_raw((deg - 1)).basis_matrix()
2424 if (deg == 0):
2425 X = zero_matrix(QQ, ngens).row_space()
2426 elif ((cobo_mat_prev.ncols() == 0) and (dif_prev.T.ncols() == 0)):
2427 X = zero_matrix(QQ, ngens).row_space()
2428 else:
2429 X = (cobo_mat_prev * dif_prev.T).row_space()
2430 Y = (dif_curr.T * dif_curr).row_space()
2431 if ((Y.dimension() == 0) and (not (Y.degree() == ngens))):
2432 Y = zero_matrix(QQ, ngens).row_space()
2433 H = (X + Y).complement().basis_matrix().sparse_matrix().row_space()
2434 self._hodge_decomps[deg] = {'harmonics': H, 'exacts': X, 'coexacts': Y}
2435 return self._hodge_decomps[deg]
2436
2437
[docs]
2438 def im_gens(self):
2439 r"""
2440 Return the images of the generators of the domain.
2441
2442 OUTPUT:
2443
2444 - ``dict`` -- a copy of the dictionary indexed by the generators of the
2445 minimal model, and its values are the corresponding images by the morphism :math:'\vaphi'
2446
2447 .. tab:: Sage
2448
2449 EXAMPLES::
2450 sage: S2 = simplicial_sets.Sphere(2)
2451 sage: W = APLK(S2)
2452 sage: M = W.minimal_model(i=6)
2453 sage: M.im_gens()
2454 {'x2_0': h2_0, 'y3_0': 0}
2455 """
2456 return self._imgens.copy()
2457
[docs]
2458 def laplacian(self, dim):
2459 r"""
2460 Returns the discrete laplacian of dimension ``dim``.
2461
2462 INPUT:
2463
2464 - ``dim`` -- the dimension of the cochain module.
2465
2466 OUTPUT: a tuple of sparse matrices `(L, Ldown, Lup)` corresponding with the laplacian, the
2467 down laplacian and the up laplacian matrices.
2468
2469 .. tab:: Sage
2470
2471 EXAMPLES::
2472
2473
2474 """
2475
2476 d_curr = self.differential(dim)
2477 d_prev = self.differential((dim - 1))
2478 L_down = (d_prev * d_prev.T)
2479 L_up = (d_curr.T * d_curr)
2480 L = (L_down + L_up)
2481 self._laplacians[dim] = (L, L_down, L_up)
2482 return (L, L_down, L_up)
2483
2484
[docs]
2485 def phi(self, pol):
2486 B = self._cdga
2487 if (not (pol.parent() == B)):
2488 raise ValueError(f'The element {pol} does not belong to {B}')
2489 W = self._aplk_algebra
2490 m_gens = B.gens()
2491 w_gens = {g: self._imgens[str(g)] for g in m_gens}
2492 w_element = W.zero()
2493 for (exp, coef) in pol.dict().items():
2494 term = (coef * W.one())
2495 for i in range(len(exp)):
2496 e = exp[i]
2497 if e:
2498 gen = w_gens[m_gens[i]]
2499 term *= (gen ** e)
2500 w_element += term
2501 return w_element
2502
2503if (__name__ == '__main__'):
2504 print('Module loaded', flush=True)
2505 print()