-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupport_functions.py
1234 lines (920 loc) · 106 KB
/
support_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy
import scipy.sparse as sp
from collections import Counter
from itertools import combinations, product
from copy import deepcopy
from random import shuffle
from multiprocessing import Pool
from Coalgebra import Coalgebra
__author__ = 'mfansler'
def expand_tuple_list(tp):
def expand_tuple_helper(acc, tp_comp):
if type(tp_comp) is list or type(tp_comp) is set:
return [x + (y,) for x in acc for y in tp_comp]
return [x + (tp_comp,) for x in acc]
if type(tp) is not tuple:
raise TypeError("parameter must be a tuple")
return reduce(expand_tuple_helper, tp, [tuple()])
def expand_map_all(xs):
return {k: [tp for v in vs for tp in expand_tuple_list(v)] for k, vs in xs.iteritems() if vs}
def deep_freeze(x):
type_x = type(x)
if type_x is list or type_x is set:
return frozenset([deep_freeze(el) for el in x])
if type_x is tuple:
return tuple(map(deep_freeze, x))
return x
def deep_thaw(x):
type_x = type(x)
if type_x is list or type_x is set or type_x is frozenset:
return [deep_thaw(el) for el in x]
if type_x is tuple:
return tuple(map(deep_thaw, x))
return x
def unnest(ls):
if type(ls) is list:
if len(ls) == 1:
return unnest(ls[0])
return ls
return [ls]
def tensor(*groups):
maxes = [max(g.keys()) for g in groups]
tensor_groups = {i: set() for i in range(sum(maxes) + 1)}
for combin in product(*[range(m+1) for m in maxes]):
tensor_groups[sum(combin)].update(
product(*[group[combin[i]] for i, group in enumerate(groups)]))
return tensor_groups
def factorize(tps, C):
results = tps
last_size = -1
def is_cycle(chain):
return not any(list_mod(derivative(chain, C)))
def chains_equal(a, b):
if type(a) is list and type(b) is list:
return not any(list_mod(a + b))
if type(a) == type(b):
return a == b
return False
def tuple_diff_indices(tp1, tp2):
return [i for i, (l, r) in enumerate(zip(tp1, tp2)) if not chains_equal(l, r)]
def combine_component(a, b):
if type(a) is list:
if type(b) is list:
return sorted(a + b)
return sorted(a + [b])
if type(b) is list:
return sorted([a] + b)
return sorted([a, b])
def merge_adjacent_tuples(acc, tp):
for i in range(len(acc)):
idxs = tuple_diff_indices(acc[i], tp)
if len(idxs) == 1 and is_cycle(list(acc[i][idxs[0]]) + list(tp[idxs[0]])):
tp_list = list(acc[i])
tp_list[idxs[0]] = combine_component(acc[i][idxs[0]], tp[idxs[0]])
acc[i] = tuple(tp_list)
return acc
return acc + [tp]
while len(results) - last_size:
last_size = len(results)
results = reduce(merge_adjacent_tuples, results, [])
return results
def factorize_cycles(tps, C):
if not tps:
return tps
is_not_tuples = type(tps[0]) is not tuple
if is_not_tuples:
# wrap cells in 1-tuples so identical code can be used
tps = [(x,) for x in tps]
results = tps
# iterate through each tuple component
for idx in range(len(tps[0])):
# partition based on all other indices
partition = {}
for tp in results:
key = deep_freeze(tp[:idx] + tp[idx+1:])
if key in partition:
partition[key].append(tp)
else:
partition[key] = [tp]
results = []
# iterate over the partitions, treating each as a queue
for queue in partition.values():
remaining = []
for (d_tp, tp) in [(derivative(tp[idx], C), tp) for tp in queue]:
if d_tp:
remaining.append((d_tp, tp))
else:
# any unbounded elements can be placed directly in results
results.append(tp[:idx] + ([tp[idx]],) + tp[idx + 1:])
cycle_len = 2
queue = []
while len(remaining) >= cycle_len:
while remaining:
cur = remaining.pop(0)
cycle = None
for combs in combinations(range(len(remaining)), cycle_len -1):
# combine the derivatives
d_chain = cur[0] + [dx for i in combs for dx in remaining[i][0]]
# check if a simple chain is formed
if all([v == 2 for v in Counter(d_chain).values()]):
# get the different elements as a list
cycle_cmps = [cur[1][idx]] + [tp[1][idx] for j, tp in enumerate(remaining) if j in combs]
# merge them into a single cycle chain
cycle = cur[1][:idx] + (cycle_cmps, ) + cur[1][idx + 1:]
# append to results
results.append(cycle)
# remove what was merged from the list of remaining
remaining = [tp for j, tp in enumerate(remaining) if j not in combs]
# break out of the for loop
break
if cycle is None:
queue.append(cur)
# increase cycle length
cycle_len += 1
# swap
remaining, queue = queue, []
# if any remainders, add them to the results
results += [tp[:idx] + ([tp[idx]],) + tp[idx + 1:] for (_, tp) in remaining]
if is_not_tuples:
# unwrap from tuple if they weren't tuples originally
results = [x[0] for x in results]
return results
def group_boundary_chains(chains, C):
num_cols = len(chains)
num_rows = 0
entries = []
row_legend = {}
# iterate over chains, creating a vector representation of their boundaries
for chain in chains:
entry = []
d_chain = [t for dx in derivative(chain, C) for t in expand_tuple_list(dx)]
d_chain = list_mod(d_chain)
for dx in d_chain:
frozen_dx = deep_freeze(dx)
if frozen_dx not in row_legend:
row_legend[frozen_dx] = num_rows
num_rows += 1
entry.append(row_legend[frozen_dx])
entries.append(sorted(list_mod(entry)))
# create matrix
bd_mat = sp.lil_matrix((num_cols, num_rows), dtype=numpy.int8)
bd_mat.rows = entries
bd_mat.data = [[1]*len(row) for row in bd_mat.rows]
bd_mat = bd_mat.transpose()
# row reduce
rref_mat, rank = row_reduce_mod2(bd_mat, augment=0)
# use reduced matrix to group chains into boundary cycles
ungrouped = range(num_cols)
groups = []
while ungrouped:
group = []
# pop columns off from right to left
j = ungrouped.pop()
group.append(chains[j])
cur_col = rref_mat.getcol(j)
for nz in cur_col.nonzero()[0]:
if nz != j:
left_col = rref_mat.getrow(nz).nonzero()[1][0]
ungrouped.remove(left_col)
group.append(chains[left_col])
groups.append(group)
return groups
def add_maps_mod_2(a, b):
res = chain_map_mod(a)
for k, vals in deepcopy(b).iteritems():
if k not in res:
res[k] = vals
else:
for v in vals:
if v in res[k]:
res[k] = [u for u in res[k] if u != v]
else:
res[k].append(v)
return res
def row_swap(A, r1, r2):
A.rows[r1], A.rows[r2] = A.rows[r2], A.rows[r1]
A.data[r1], A.data[r2] = A.data[r2], A.data[r1]
def mat_mod2(A):
A.data[:] = numpy.fmod(A.data, 2)
return A
def add_rows(A, r1, r2):
r1_plus_r2 = []
pos_r1 = 0
pos_r2 = 0
try:
while True:
if A.rows[r1][pos_r1] < A.rows[r2][pos_r2]:
r1_plus_r2.append(A.rows[r1][pos_r1])
pos_r1 += 1
elif A.rows[r1][pos_r1] > A.rows[r2][pos_r2]:
r1_plus_r2.append(A.rows[r2][pos_r2])
pos_r2 += 1
else:
pos_r1 += 1
pos_r2 += 1
except IndexError:
if pos_r1 == len(A.rows[r1]):
r1_plus_r2.extend(A.rows[r2][pos_r2:])
elif pos_r2 == len(A.rows[r2]):
r1_plus_r2.extend(A.rows[r1][pos_r1:])
A.rows[r2] = r1_plus_r2
#A.rows[r2] = sorted(list_mod(A.rows[r1] + A.rows[r2]))
A.data[r2] = [1]*len(A.rows[r2])
def parallel_row_sum((j, r1, r2)):
r1_plus_r2 = []
pos_r1 = 0
pos_r2 = 0
try:
while True:
if r1[pos_r1] < r2[pos_r2]:
r1_plus_r2.append(r1[pos_r1])
pos_r1 += 1
elif r1[pos_r1] > r2[pos_r2]:
r1_plus_r2.append(r2[pos_r2])
pos_r2 += 1
else:
pos_r1 += 1
pos_r2 += 1
except IndexError:
if pos_r1 == len(r1):
r1_plus_r2.extend(r2[pos_r2:])
elif pos_r2 == len(r2):
r1_plus_r2.extend(r1[pos_r1:])
return j, r1_plus_r2, [1]*len(r1_plus_r2)
def row_reduce_mod2(A, augment=0):
if A.ndim != 2:
raise Exception("require two dimensional matrix input, found ", A.ndim)
# convert to lil matrix for efficient reduction
A = A.tolil()
# make sure everything is mod 2
A.data = [[x % 2 for x in xs] for xs in A.data]
# rank = the num of independent columns found so far
rank = 0
# this is used repeatedly, so makes sense to generate it only once
row_range = range(A.shape[0])
# multithreading worker pool for computing row sums
p = Pool(8)
for i in range(A.shape[1] - augment):
# identify all rows with nonzero entries in i-th column
# only those rows below the nonzero rows of the independent cols are independent
nzs = [(j, len(A.rows[j])) for j in row_range if i in A.rows[j]]
upper_nzs = [nz[0] for nz in nzs if nz[0] < rank]
lower_nzs = [nz for nz in nzs if nz[0] >= rank]
# progess information
print "\rcolumn: {}/{}; num_lower_nonzero: {}; reducible: {}".format(i, A.shape[1], len(lower_nzs), i - rank),
if len(lower_nzs) > 0:
# the sparsest will be used
sparsest = min(lower_nzs, key=lambda nz: nz[1])
row_swap(A, rank, sparsest[0])
sum_jobs = []
for nz in [nz_pair[0] for nz_pair in lower_nzs if nz_pair != sparsest]:
if nz != rank:
# if not from the rank position, then it hasn't moved
sum_jobs.append((nz, A.rows[rank], A.rows[nz]))
elif sparsest[0] != nz:
# if it was in the rank row, and it was moved
# the main this is, we don't want to add the rank row to itself
sum_jobs.append((sparsest[0], A.rows[rank], A.rows[sparsest[0]]))
if rank > 0:
for nz in upper_nzs:
sum_jobs.append((nz, A.rows[rank], A.rows[nz]))
# doesn't matter what order they are done in
for j, row_j, data_j in p.imap_unordered(parallel_row_sum, sum_jobs, chunksize=100):
A.rows[j] = row_j
A.data[j] = data_j
rank += 1
# clean up the pool
p.close()
p.terminate()
return A, rank
def ref_mod2(A, augment=0, eliminate=True):
if A.ndim != 2:
raise Exception("require two dimensional matrix input, found ", A.ndim)
# convert to lil matrix for efficient reduction
A = A.tolil()
# make sure everything is mod 2
A.data = [[x % 2 for x in xs] for xs in A.data]
# rank = the num of independent columns found so far
rank = 0
# this is used repeatedly, so makes sense to generate it only once
row_range = range(A.shape[0])
# multithreading worker pool for computing row sums
p = Pool(8)
for i in range(A.shape[1] - augment):
# only consider lower nonzeros, and only have to check first element in each row
lower_nzs = [(j, len(A.rows[j])) for j in row_range[rank:] if A.rows[j] and A.rows[j][0] == i]
# print some info on progress
print "\rcolumn: {}/{}; num_lower_nonzero: {}; reducible: {}".format(i + 1, A.shape[1], len(lower_nzs), i - rank),
if len(lower_nzs) > 0:
# select the sparsest row to serve as representative
# in order to minimize accumulation of nonzeros in matrix
sparsest = min(lower_nzs, key=lambda nz: nz[1])
row_swap(A, rank, sparsest[0])
# work queue
sum_jobs = []
for nz in [nz_pair[0] for nz_pair in lower_nzs if nz_pair != sparsest]:
if nz != rank:
# if not from the rank position, then it hasn't moved
sum_jobs.append((nz, A.rows[rank], A.rows[nz]))
elif sparsest[0] != nz:
# if it was in the rank row, and it was moved
# the main this is, we don't want to add the rank row to itself
sum_jobs.append((sparsest[0], A.rows[rank], A.rows[sparsest[0]]))
# carry out sums
for j, row_j, data_j in p.imap_unordered(parallel_row_sum, sum_jobs, chunksize=100):
A.rows[j] = row_j
A.data[j] = data_j
rank += 1
elif eliminate:
for j in range(rank):
if i in A.rows[j]:
A.rows[j].remove(i)
A.data[j].pop()
print "finished, now cleaning up"
# clean up the pool
p.close()
p.terminate()
return A, rank
def backsubstitute_mod2(ref_mat):
# assumes that last column is the y column
print "\nBack-substitution"
# solution for (ref_mat[:,:-1]) * (x) = (ref_mat[:,-1])
x = []
# all nzs remaining
nzs = ref_mat.getcol(-1).nonzero()[0]
nzs = nzs.tolist()
while len(nzs) > 0:
print "\rlen(y) = {}; len(x) = {}".format(len(nzs), len(x)),
row_idx = nzs[-1]
col_idx = ref_mat.getrow(row_idx).nonzero()[1][0]
x.append(col_idx)
if col_idx == ref_mat.shape[1] - 1:
nzs.pop()
continue
for i in ref_mat.getcol(col_idx).nonzero()[0]:
if i in nzs:
nzs.remove(i)
else:
nzs.append(i)
nzs.sort()
print
return x
def dot_mod2(A, x):
# NOTE: assumes lil matrix
y = []
nzs = x.nonzero()[0]
nzs = set(nzs)
for i, r in enumerate(A.rows):
if len(nzs.intersection(set(r))) % 2:
y.append(i)
# returns a list of all nonzero entries in product
return y
def select_basis(A):
cols = []
rank = 0
A = A.tocsc()
row_red_op = sp.eye(A.shape[0])
row_red_op = row_red_op.tolil()
for i in range(A.shape[1]):
#c = mat_mod2(row_red_op.dot(A.getcol(i)))
#nzs = c.nonzero()[0]
nzs = dot_mod2(row_red_op, A.getcol(i))
upper_nzs = [j for j in nzs if j < rank]
lower_nzs = [j for j in nzs if j >= rank]
# print some info on progress
print "\rcolumn: {}/{}; num_lower_nonzero: {}; reducible: {}".format(i, A.shape[1], len(lower_nzs), i - rank),
if len(lower_nzs) > 0:
cols.append(i)
if rank != lower_nzs[0]:
row_swap(row_red_op, rank, lower_nzs[0])
lower_nzs.pop(0)
for j in lower_nzs:
add_rows(row_red_op, rank, j)
for j in upper_nzs:
add_rows(row_red_op, rank, j)
rank += 1
return cols, row_red_op, rank
def list_mod(ls, modulus=2):
return [s for s, num in Counter(ls).iteritems() if num % modulus]
def chain_map_mod(xs, modulus=2):
return {k: list_mod(ls, modulus=modulus) for k, ls in xs.iteritems()}
def facet_to_cells(facet, C):
"""
Function to obtain a list of cells that a given cell is facet of.
:param facet: cell from cell complex
:param C: Coalgebra with cell complex that facet is in
:return: a list of all cells in the complex for which the given cell is a facet
"""
return {face for face, facets in C.differential.iteritems() if facet in facets and facets[facet] % 2}
def derivative(x, C):
if type(x) is list:
return [dy for y in x for dy in derivative(y, C)]
if type(x) is tuple:
return [tuple(x[:i]) + (derivative(x[i], C), ) + tuple(x[i + 1:]) for i in range(len(x))]
if type(x) is dict:
dx = {k: [] for k in x.keys()}
# first handle raising cell-selecting map
for k, vs in x.iteritems():
for cell in facet_to_cells(k, C):
if cell in dx:
dx[cell] += vs
else:
dx[cell] = vs
dx[k] += derivative(vs, C)
return dx
if x in C.differential:
return [k for k, v in C.differential[x].iteritems() if v % 2]
return []
# generates all 0-n combinations of elements in the list xs
def all_combinations(xs):
for i in range(len(xs) + 1):
for c in combinations(xs, i):
yield c
# generates the function f: C -> H
# @param C Coalgebra to map from
# @param g map from H (== H*(C)) to class representatives in C
#
# returns function f(x)
def generate_f_integral(C, g):
# create a map from cells to index
basis = {el: i for (i, el) in enumerate([el for grp in C.groups.values() for el in grp])}
inv_basis = {v: k for k, v in basis.iteritems()}
# store num cells
n = len(basis)
# prepare n x n incidence matrix
# includes multiple dimensions, but it's sparse, so no efficiency lost
inc_mat = sp.lil_matrix((n, n), dtype=numpy.int8)
# enter incidences
for el, bd in C.differential.iteritems():
inc_mat.rows[basis[el]] = [basis[c] for c, i in bd.iteritems() if i % 2]
inc_mat.data = [[1]*len(row) for row in inc_mat.rows]
# switch to cols
inc_mat = inc_mat.transpose()
# append identity
inc_mat = sp.hstack([inc_mat, sp.identity(n, dtype=numpy.int8)])
# row reduce
rref_mat, rank = row_reduce_mod2(inc_mat, augment=n)
# extract just the (partial) inverse
inv_mat = rref_mat.tocsc()[:, n:].tocsr()
ker_basis = []
for i in range(rank):
first = rref_mat[i, :].nonzero()[1][0]
ker_basis.append(inv_basis[first])
# clean up
del inc_mat, rref_mat
# method to check if chain (typically a cycle) is in Im[boundary]
# zombies are components that don't get killed by boundary
def has_zombies(x):
# convert to vector in established basis
x_vec = [0]*n
for el in x:
x_vec[basis[el]] = 1
# converts vector to Im[boundary] basis
zombies = inv_mat.dot(numpy.array(x_vec))[rank:]
# linear combination of bounding cells
#print "boundary map: ", [b for (b, v) in zip(ker_basis, inv_mat.dot(numpy.array(x_vec))[:rank]) if v % 2]
# return true if there are components not spanned by Im[boundary]
return numpy.fmod(zombies, 2).any()
# method to be returned
# cannonical map of x in C to coset in H
def f(x):
if type(x) is not list:
x = [x]
# check if not cycle (non-vanishing boundary)
bd = list_mod([dx for cell in x if cell in C.differential for dx in C.differential[cell].iteritems()], 2)
if bd:
return []
# check if killed by known boundaries
if not has_zombies(x):
return []
# TODO: check to see if single elements are sufficient
# determine what combination of known cycles it corresponds to
for ks in all_combinations(g.keys()):
gens = [gen_comp for k in ks for gen_comp in g[k]]
if not has_zombies(list_mod(gens + x, 2)):
return list(ks)
raise Exception("Error: could not find coset!\n", x)
def integrate1(x):
if type(x) is not list:
x = [x]
# convert to vector in established basis
x_vec = [0]*n
for el in x:
x_vec[basis[el]] = 1
# converts vector to Im[boundary] basis
x_ker = inv_mat.dot(numpy.array(x_vec)) % 2
if any(x_ker[rank:]):
return None
# print "WARNING: Invalid integral!"
# print x, "contains non-vanishing component (cycle)"
# returns boundary cells that contain x as boundary
return [b for (b, v) in zip(ker_basis, x_ker[:rank]) if v % 2]
def integrate(xs):
# if a single tuple is passed, treat it as a list
if type(xs) is tuple:
xs = [xs]
# if it is a dict, assume it's a chain map
if type(xs) is dict:
return integrate_chain_map(xs)
# if not a list, assume it's an individual element, so push through integrate1
if type(xs) is not list:
return integrate1([xs])
# if it is a list, but is empty, then return empty list
if not len(xs):
return []
# it is a list, but not of tuples
# so assume that it is list of elements
if type(xs[0]) is not tuple:
return integrate1(xs)
# if it is a list of tuples, but the tuples have lists
# we'll need to expand out everything
if type(xs[0][0]) is list:
expanded_xs = [tp for x in xs for tp in expand_tuple_list(x)]
expanded_xs = list_mod(expanded_xs)
# otherwise, we need to factorize it, which improves performance
else:
expanded_xs = xs
xs = factorize_cycles(list_mod(xs), C)
xs = factorize(xs, C)
# we now have a none empty list of tuples with list components
shuffle(xs)
for x in xs:
# figure out which component in the first tuple can be integrated
for i, x_cmp in enumerate(x):
anti_x_cmp = integrate1(x_cmp)
# if this component can't be integrated, continue the loop
if anti_x_cmp is None:
continue
# otherwise construct the anti_derivative that kills it
else:
if i == 0:
anti_x = (anti_x_cmp,) + tuple(x[1:])
else:
anti_x = tuple(x[:i]) + (anti_x_cmp, ) + tuple(x[i + 1:])
anti_x = expand_tuple_list(anti_x)
# take the derivative of that anti-derivative and subtract from our list
anti_x_full_derivative = [dx_tp for dx in derivative(anti_x, C) for dx_tp in expand_tuple_list(dx) if all(dx)]
remainder = list_mod(anti_x_full_derivative + expanded_xs, 2)
# attempt to integrate that remaining portion on its own
#print len(remainder)
anti_rem = integrate(remainder) if len(remainder) < len(expanded_xs) else None
# if successful, then we have constructed a valid integral for xs
if anti_rem is not None:
# sweet
return anti_rem + anti_x
# otherwise loop back around and check for another component
# that tuple could not be integrated on its own
# loop back around and try the next one
return None
def integrate_chain_map(xs, allow_regress=True):
# assuming map comes in factored
expanded_map = chain_map_mod(expand_map_all(xs))
best_distance = sum([len(vs) for vs in expanded_map.values()])
print "\rbest_distance =", best_distance,
if best_distance == 0:
return {}
frontier = []
# generate initial frontier
for cell, tps in expanded_map.iteritems():
for tp in tps:
# first generate anti-derivatives that kill chain components
for i in range(len(tp)):
for anti_tp_cmp in facet_to_cells(tp[i], C):
anti_tp_map = {cell: [tp[:i] + (anti_tp_cmp,) + tp[i+1:]]}
der_anti_tp_map = chain_map_mod(expand_map_all(derivative(anti_tp_map, C)))
der_size = sum([len(vs) for vs in der_anti_tp_map.values()])
num_hits = sum([1 for k, vs in der_anti_tp_map.iteritems() for v in vs if k in expanded_map and v in expanded_map[k]])
distance = best_distance + der_size - 2*num_hits
if distance == 0:
return anti_tp_map
if allow_regress or distance < best_distance:
frontier.append((distance, anti_tp_map, der_anti_tp_map))
# next, generate boundary components
for d_cell in derivative(cell, C):
anti_tp_map = {d_cell: [tp]}
der_anti_tp_map = chain_map_mod(expand_map_all(derivative(anti_tp_map, C)))
der_size = sum([len(vs) for vs in der_anti_tp_map.values()])
num_hits = sum([1 for k, vs in der_anti_tp_map.iteritems() for v in vs if k in expanded_map and v in expanded_map[k]])
distance = best_distance + der_size - 2*num_hits
if distance == 0:
return anti_tp_map
if allow_regress or distance < best_distance:
frontier.append((distance, anti_tp_map, der_anti_tp_map))
frontier = sorted(frontier, key=lambda tp: tp[0])
result = None
while result is None and frontier:
cur_anti_xs = frontier.pop(0)
result = integrate_chain_map(add_maps_mod_2(expanded_map, cur_anti_xs[2]), allow_regress=False)
if result is None:
return None
return add_maps_mod_2(cur_anti_xs[1], result)
return f, integrate
def matrix_reorder_rows_by_sparsity(A):
ordering = sorted([(i, len(r), sum(r)) for i, r in enumerate(A.rows)], key=lambda (j, l, s): (l, s))
B = sp.lil_matrix(A.shape, dtype=numpy.int8)
for i in range(len(A.rows)):
B.rows[i] = A.rows[ordering[i][0]]
B.data[i] = A.data[ordering[i][0]]
return B, {b_idx: a_idx for b_idx, (a_idx, _, _) in enumerate(ordering)}
def chain_integrate(chain, C):
# expand the chain
exp_chain = [cell for raw_cell in chain for cell in expand_tuple_list(raw_cell)]
exp_chain = list_mod(exp_chain)
# if for some reason it is already zero
# there isn't really anything to integrate
if not exp_chain:
return []
# use the very first cell to determine the tuple length
dim = len(chain[0])
# create an inverse map that yields the dimension for each cell in C
cell_inv = {cell: dim for dim, cells in C.groups.iteritems() for cell in cells}
# check the different dimensions that appear in the chain
dim_indices = {tuple([cell_inv[tp_cmp] for tp_cmp in cell]) for cell in exp_chain}
# construct the possible anti-derivative dimensions that could yield
# the chain components
anti_dim_indices = {index[:i] + (index[i] + 1,) + index[i+1:] for index in dim_indices for i in range(dim)}
# get the total degree of the current cells by sampling the first
# TODO: Should we check if they are all identical??
sum_dimension = sum(next(iter(dim_indices)))
dimensions_summary = [set(z) for z in zip(*dim_indices)]
"""
There could be a simple anti-derivative using only the
components that show up in the cells present.
This is significantly faster to check, so it is definitely
worth attempting.
"""
if any([len(dims) == 2 for dims in dimensions_summary]) and \
not any([len(dims) > 2 for dims in dimensions_summary]):
graded_set_tuple = [set(z) for z in zip(*exp_chain)]
for tp_pos, cells in enumerate(graded_set_tuple):
graded_set = {dim: set() for dim in dimensions_summary[tp_pos]}
for cell in cells:
graded_set[cell_inv[cell]].add(cell)
graded_set_tuple[tp_pos] = graded_set
anti_derivative_space = set()
for index in anti_dim_indices:
if all([index_cmp in graded_set_tuple[i] for i, index_cmp in enumerate(index)]):
anti_derivs = tuple(
[graded_set_tuple[i][index_cmp] for i, index_cmp in enumerate(index)])
anti_derivative_space.update(expand_tuple_list(anti_derivs))
anti_derivative_space = list(anti_derivative_space)
num_cols = len(anti_derivative_space) + 1
num_rows = 0
entries = []
row_legend = {}
# iterate over possible components in anti-derivative space,
# creating a vector representation of their derivatives
for chain in anti_derivative_space:
entry = []
d_chain = [t for dx in derivative(chain, C) for t in expand_tuple_list(dx)]
d_chain = list_mod(d_chain)
for dx in d_chain:
frozen_dx = deep_freeze(dx)
if frozen_dx not in row_legend:
row_legend[frozen_dx] = num_rows
num_rows += 1
entry.append(row_legend[frozen_dx])
entries.append(sorted(list_mod(entry)))
# append the group to the entries
entries.append(sorted([row_legend[deep_freeze(chain)] for chain in exp_chain]))
# create matrix
bd_mat = sp.lil_matrix((num_cols, num_rows), dtype=numpy.int8)
bd_mat.rows = entries
bd_mat.data = [[1]*len(row) for row in bd_mat.rows]
bd_mat = bd_mat.transpose()
# row reduce
ref_mat, rank = ref_mod2(bd_mat, augment=1, eliminate=False)
anti_derivative = backsubstitute_mod2(ref_mat)
if (num_cols - 1) in anti_derivative:
print "\nRow reduction did not find linearly dependent result!"
while (num_cols - 1) in anti_derivative:
anti_derivative.remove(num_cols - 1) # can still get partial solution
anti_derivative = [anti_derivative_space[col] for col in anti_derivative]
full_derivative = [dx_tp for dx in derivative(anti_derivative, C) for dx_tp in expand_tuple_list(dx) if all(dx)]
full_derivative = list_mod(full_derivative)
if not list_mod(full_derivative + exp_chain):
return anti_derivative
else:
print "\nSimple anti-derivative not found for group: ", chain
print "closest anti-derivative: ", factorize(factorize_cycles(anti_derivative, C), C)
print "calculated derivative:", factorize(factorize_cycles(full_derivative, C), C)
"""
Compute the full anti-derivative space and express the group
using these components
"""
# generate all possible anti-derivative cells
anti_derivative_space = set()
for index in anti_dim_indices:
anti_derivative_space.update(expand_tuple_list(tuple([C.groups[i] for i in index])))
# need to fix the order so that they can be recovered
anti_derivative_space = list(anti_derivative_space)
num_cols = len(anti_derivative_space) + 1
num_rows = 0
entries = []
row_legend = {}
# iterate over possible cells in anti-derivative space,
# creating a vector representation of their derivatives
for cell in anti_derivative_space:
entry = []
d_cell = [t for dx in derivative(cell, C) for t in expand_tuple_list(dx)]
d_cell = list_mod(d_cell)
# create an entry for each derivative cell
for dx in d_cell:
frozen_dx = deep_freeze(dx)
# update the row_legend if this cell is new
if frozen_dx not in row_legend:
row_legend[frozen_dx] = num_rows
num_rows += 1
# add the corresponding row number to the "column"
entry.append(row_legend[frozen_dx])
# once done mod, sort, then add to the rest of the entries
entries.append(sorted(entry))
# include a temp dummy row
entries.append(list(range(num_rows)))
# create matrix
bd_mat = sp.lil_matrix((num_cols, num_rows), dtype=numpy.int8)
bd_mat.rows = entries
bd_mat.data = [[1]*len(row) for row in bd_mat.rows]
# reordering by sparsity helps to get density accumulation down
bd_mat, reordered_map = matrix_reorder_rows_by_sparsity(bd_mat)
# replace the dummy row
bd_mat.rows[-1] = sorted([row_legend[deep_freeze(chain)] for chain in exp_chain])
bd_mat.data[-1] = [1]*len(bd_mat.rows[-1])
# transpose the matrix
bd_mat = bd_mat.transpose()