-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCatMat.py
More file actions
2387 lines (2026 loc) · 92.9 KB
/
CatMat.py
File metadata and controls
2387 lines (2026 loc) · 92.9 KB
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
from sage.all import *
from sage.all import matrix, vector, identity_matrix, block_matrix, zero_vector, zero_matrix, block_diagonal_matrix
import sys
import itertools
from collections import Iterable
# This code is for computing the homology of a finite category with coefficients in a functor.
# For example, it can compute homotopy colimits in the category of cochain complexes over the integers.
# The rough steps for use: define a finite category that indexes your diagram of cochain complexes,
# and then use resolution and substitution to build a multicomplex whose total complex is your hocolim.
# TODO: support for unit-counit tensor-hom adjunction for bimodules
# TODO: bring the ring into the category to get additive categories
# TODO: preadditive categories with homs that are free abelian
# TODO: eventually, dg-categories
# TODO: main next steps: fix product categories; introduce preadditive cats
# TODO: sparse vs. dense matrices. Reimplement CatMat to be sparse, I think
# TODO: parallel computation
# TODO: indexed matrices should be a category whose objects are injective tuples
# TODO: so that we obtain unique compatible reorderings whenever required.
# TODO: (actually, two matrices should refuse to multiply if their labelings are different)
# TODO: new version should not have functions as arguments, but instead use overload
# TODO: and consequently, CatMats will be pickleable.
# Constructing a FiniteCategory using __init__
#
# object_list
# The list of objects in the category. These objects must be hashable.
#
# one_law
# This argument tells the FiniteCategory what the identity morphisms are. It must be a
# function that takes an object and returns a string that represents the identity at
# that object.
#
# hom_law
# This argument tells the FiniteCategory how to compute hom between two objects. It must be a
# function that takes a pair of objects and returns a list of morphisms from one to the other.
# The morphisms are represented as strings.
#
# composition_law
# This argument tells the FiniteCategory how to compose. It is a function of the following
# form:
# composition_law(x, f, y, g, z)
# where x, y, and z are objects, and f : x --> y and g : y --> z are morphisms represented
# as strings.
#
class FiniteCategory(object):
def __init__(self, object_list, one_law, hom_law, composition_law,
object_latex_law=None, morphism_latex_law=None,
cache=True):
self.objects = object_list
self.basic_hom = hom_law
self.basic_one = one_law
self.basic_composition = composition_law
self.one_dict = {}
self.hom_dict = {}
self.mns = {}
self.msn = {}
self.lact = {}
self.mact = {}
self.ract = {}
self.op_cat = OppositeCategory(self)
self.double_cat = ProductCategory(self.op_cat, self)
self.cache = cache
def default_object_latex_law(o):
#return '\\texttt{' + str(o) + '}'
return latex(o)
def default_morphism_latex_law(x, f, y):
return '\\scalebox{.7}{\\fbox{\\texttt{' + f + '}}}'
self.object_latex_law = object_latex_law or default_object_latex_law
self.morphism_latex_law = morphism_latex_law or default_morphism_latex_law
def identity(self, x):
if x in self.one_dict:
return self.one_dict[x]
ret = self.basic_one(x)
self.one_dict[x] = ret
return ret
def hom(self, x, y):
if (x, y) in self.hom_dict:
return self.hom_dict[(x, y)]
ret = self.basic_hom(x, y)
self.hom_dict[(x, y)] = ret
return ret
def compose(self, x, f, y, g, z):
return self.basic_composition(x, f, y, g, z)
def morphism_to_number(self, x, f, y):
if (x, f, y) in self.msn:
return self.msn[(x, f, y)]
h = self.hom(x, y)
try:
k = h.index(f)
except ValueError:
raise SyntaxError("The string '" + f + "' doesn't define a morphism " + str(x) + " -----> " + str(y))
self.msn[(x, f, y)] = k
return k
def object_to_latex(self, o):
return self.object_latex_law(o)
def morphism_to_latex(self, x, f, y):
return self.morphism_latex_law(x, f, y)
# This function is used to parse linear combinations of morphisms
# from the category. It greedily searches for morphisms in a string
# and returns a list of morphisms appearing, as well as a list of
# between strings. If n morphisms appear in the string, then
# morphs will be a list of length n giving these strings in order.
# In this case, len(coeffs) = n + 1.
# The function satisfies
# entry_string = coefficients[0] + morphisms[0] + coefficients[1] + ... + morphisms[n - 1] + coefficients[n]
def split_string_on_morphisms(self, x, entry_string, y):
ss = entry_string
hom_list = list(self.hom(x, y))
hom_list.sort(key=len, reverse=True)
for f in hom_list:
ss = ss.replace(f, '~' * len(f))
tt = ''
for i, c in enumerate(ss):
if c == '~':
tt += entry_string[i]
else:
tt += '~'
import re
morphs = re.split(r'~+', tt)
coeffs = re.split(r'~+', ss)
return morphs, coeffs
def left_action_matrix(self, x, f, y, z):
if self.cache and (x, f, y, z) in self.lact:
return self.lact[(x, f, y, z)]
rows = self.hom(y, z)
cols = self.hom(x, z)
ret = matrix(ZZ, len(rows), len(cols), [1 if self.compose(x, f, y, r, z) == c
else 0 for r in rows for c in cols])
self.lact[(x, f, y, z)] = ret
return ret
def middle_action_matrix(self, x, f, z, y):
if self.cache and (x, f, z, y) in self.mact:
return self.mact[(x, f, z, y)]
rows = self.hom(x, y)
cols = self.hom(y, z)
ret = matrix(ZZ, len(rows), len(cols), [1 if self.compose(x, r, y, c, z) == f
else 0 for r in rows for c in cols])
self.mact[(x, f, z, y)] = ret
return ret
def right_action_matrix(self, x, y, f, z):
if self.cache and (x, y, f, z) in self.ract:
return self.ract[(x, y, f, z)]
rows = self.hom(x, y)
cols = self.hom(x, z)
ret = matrix(ZZ, len(rows), len(cols), [1 if self.compose(x, r, y, f, z) == c
else 0 for r in rows for c in cols])
self.ract[(x, y, f, z)] = ret
return ret
def op(self):
return self.op_cat
# Bug: since objects of the category might be iterable
# you must always give a list of degrees.
# TODO: go through code and fix every appearance of free_module(ring, single_degree)
def free_module(self, ring, degrees):
try:
iter(degrees)
except TypeError:
print('Warning! You have passed a non-iterable list of degrees to free_module.')
print('Figure out when it happened, and fix it!')
return self.free_module(ring, (degrees,))
def law(x, f, y):
ret = matrix(ring, 0, 0, [])
for d in degrees:
ret = ret.block_sum(self.right_action_matrix(d, x, f, y))
return ret
return MatrixRepresentation(self, ring, law, target_cat=None)
def free_op_module(self, ring, degrees):
return self.op_cat.free_module(ring, degrees)
def cofree_module(self, ring, degrees):
try:
iter(degrees)
except TypeError:
return self.cofree_module(ring, (degrees,))
def law(x, f, y):
ret = matrix(ring, 0, 0, [])
for d in degrees:
ret = ret.block_sum(self.left_action_matrix(x, f, y, d).transpose())
return ret
return MatrixRepresentation(self, ring, law, target_cat=None)
# TODO: reimplement to avoid recomputing structure matrices
def full_subcategory_inclusion(self, objects):
def full_subcat_one(x):
return self.identity(x)
def full_subcat_hom(x, y):
return self.hom(x, y)
def full_subcat_comp(x, f, y, g, z):
return self.compose(x, f, y, g, z)
full_subcat = FiniteCategory(objects, full_subcat_one, full_subcat_hom, full_subcat_comp)
def law(x, f, y):
return x, f, y
return Functor(full_subcat, law, self)
def hom_bimodule(self, ring):
def hom_bimodule_law(bx, fg, ay):
b, x = bx
a, y = ay
f, g = self.double_cat.break_string(fg)
free = self.free_module(ring, [b])
cofree = self.cofree_module(ring, [y])
return free(x, g, y) * cofree(a, f, b).transpose()
return MatrixRepresentation(self.double_cat, ZZ, hom_bimodule_law, target_cat=None)
def trivial_representation(self, ring):
def law(x, f, y):
return matrix(ring, 1, 1, [1])
return MatrixRepresentation(self, ring, law, target_cat=None)
def test(self):
for x in self.objects:
if self.identity(x) not in self.hom(x, x):
print('The identity morphism for the object ' + str(x) + \
', which is supposed to be given by the string ' + self.identity(x) + \
', fails to appear in the hom-set ' + str(self.hom(x, x)) + '.')
for x in self.objects:
for y in self.objects:
for z in self.objects:
for f in self.hom(x, y):
for g in self.hom(y, z):
if self.compose(x, f, y, g, z) not in self.hom(x, z):
print('The composition ' + str((x, f, y, g, z)) + ', which is supposed ' + \
'to be given by the string ' + self.compose(x, f, y, g, z) + \
', fails to appear in the hom-set ' + str(self.hom(x, z)) + '. ')
for w, x, y, z in itertools.product(*([self.objects] * 4)):
for f in self.hom(w, x):
for g in self.hom(x, y):
for h in self.hom(y, z):
left = self.compose(w, f, x, self.compose(x, g, y, h, z), z)
right = self.compose(w, self.compose(w, f, x, g, y), y, h, z)
if left != right:
print('The following triple of morphisms do not associate:')
print (w, f, x, g, y, h, z)
# More efficient than naively recomputing
class OppositeCategory(FiniteCategory):
def __init__(self, cat):
self.op_cat = cat
self.objects = cat.objects
def oll(o):
return self.op_cat.object_latex_law(o) + '^{op}'
def mll(x, f, y):
return self.op_cat.morphism_latex_law(y, f, x) + '^{op}'
self.object_latex_law = oll
self.morphism_latex_law = mll
def identity(self, x):
return self.op_cat.identity(x)
def hom(self, x, y):
return self.op_cat.hom(y, x)
def compose(self, x, f, y, g, z):
return self.op_cat.compose(z, g, y, f, x)
def left_action_matrix(self, x, f, y, z):
return self.op_cat.right_action_matrix(z, y, f, x)
def middle_action_matrix(self, x, f, z, y):
return self.op_cat.middle_action_matrix(z, f, x, y).transpose()
def right_action_matrix(self, x, y, f, z):
return self.op_cat.left_action_matrix(z, f, y, x)
def object_to_latex(self, o):
return self.op_cat.object_latex_law(o)
def morphism_to_latex(self, x, f, y):
return self.op_cat.morphism_latex_law(x, f, y)
def morphism_to_number(self, x, f, y):
return self.op_cat.morphism_to_number(y, f, x)
def op(self):
return self.op_cat
def free_module(self, ring, degrees):
try:
iter(degrees)
except TypeError:
return self.free_module(ring, (degrees,))
def law(x, f, y):
ret = matrix(ring, 0, 0, [])
for d in degrees:
ret = ret.block_sum(self.right_action_matrix(d, x, f, y))
return ret
return MatrixRepresentation(self, ring, law, target_cat=None)
def free_op_module(self, ring, degrees):
return self.op_cat.free_module(ring, degrees)
# More efficient than naively recomputing
class ProductCategory(FiniteCategory):
def __init__(self, arg0, *list_of_cats):
if type(arg0) is str:
self.left = '('
self.sep = arg0
self.right = ')'
self.cats = list(list_of_cats)
else:
self.left = '('
self.sep = ','
self.right = ')'
self.cats = [arg0] + list(list_of_cats)
self.ecats = list(enumerate(self.cats))
self.n_factors = len(self.cats)
# If the number of factors is one
# the convention is to have the same objects
# not one-objects tuples.
if self.n_factors == 1:
self.objects = list_of_cats[0].objects
else:
self.objects = list(itertools.product(*[cat.objects for cat in self.cats]))
def oll(o):
if self.n_factors == 1:
return self.cats[0].object_to_latex(o)
z = self.left
for i, x in enumerate(o):
z += self.cats[i].object_latex_law(x)
z += self.sep
z = z[:-1] + self.right
return z
def mll(x, f, y):
if self.n_factors == 1:
return self.cats[0].morphism_to_latex(x, f, y)
z = self.left
for i, ff in enumerate(self.break_string(f)):
z += self.cats[i].morphism_latex_law(x[i], ff, y[i])
z += self.sep
z = z[:-1] + self.right
return z
self.object_latex_law = oll
self.morphism_latex_law = mll
self.op_cat = None
self.mns = {}
self.msn = {}
def identity(self, x):
# Broken for additive categories
if self.n_factors == 1:
return self.cats[0].identity(x)
try:
return self.combine_strings(*[cat.identity(x[i]) for i, cat in self.ecats])
except(TypeError):
return CatMat.kronecker_product(self.sep, *[CatMat.identity_matrix(ZZ, cat, [x[i]]) for i, cat in self.ecats]).data_vector
def hom(self, x, y):
if self.n_factors == 1:
return self.cats[0].hom(x, y)
return [self.combine_strings(*ss) for ss in itertools.product(*[cat.hom(x[i], y[i]) for i, cat in self.ecats])]
def compose(self, x, f, y, g, z):
if self.n_factors == 1:
return self.cats[0].compose(x, f, y, g, z)
fb = self.break_string(f)
gb = self.break_string(g)
return self.combine_strings(*[cat.compose(x[i], fb[i], y[i], gb[i], z[i]) for i, cat in self.ecats])
# Projection functor onto the nth factor
def pi(self, n):
def law(x, f, y):
return x[n], self.break_string(f)[n], y[n]
return Functor(self, law, self.cats[n])
def combine_strings(self, *strings):
if len(strings) != self.n_factors:
raise ValueError('Wrong number of factors for this product category: '
+ str((len(strings), self.n_factors)))
if len(strings) == 0:
return '*'
if len(strings) == 1:
return strings[0]
ts = self.left
for s in strings:
ts += s + self.sep
return ts[:-1] + self.right
# TODO: This code is badly broken for products of products
def break_string(self, s):
# If the string is not a tuple, then we may have a zero- or one-fold product
if s[:len(self.left)] != self.left or s[-len(self.right):] != self.right:
return [s]
return s[1:-1].split(self.sep)
def left_action_matrix(self, x, f, y, z):
ret_n_rows = 1
ret_n_cols = 1
ret = matrix(ZZ, 1, 1, [1])
fb = self.break_string(f)
kfactors = []
for i, cat in self.ecats:
kf = cat.left_action_matrix(x[i], fb[i], y[i], z[i])
ret_n_rows *= kf.nrows()
ret_n_cols *= kf.ncols()
kfactors += [kf]
# This is to avoid a 0-dim bug present in my version of sage
if ret_n_rows * ret_n_cols == 0:
return matrix(ZZ, ret_n_rows, ret_n_cols, [])
for kf in kfactors:
ret = ret.tensor_product(kf)
return ret
def middle_action_matrix(self, x, f, z, y):
ret_n_rows = 1
ret_n_cols = 1
ret = matrix(ZZ, 1, 1, [1])
fb = self.break_string(f)
for i, cat in self.ecats:
kf = cat.middle_action_matrix(x[i], fb[i], z[i], y[i])
ret_n_rows *= kf.nrows()
ret_n_cols *= kf.ncols()
if ret_n_rows * ret_n_cols != 0:
ret = ret.tensor_product(kf)
# This is to avoid a 0-dim bug present in my version of sage
if ret_n_rows * ret_n_cols == 0:
return matrix(ZZ, ret_n_rows, ret_n_cols, [])
return ret
def right_action_matrix(self, x, y, f, z):
ret_n_rows = 1
ret_n_cols = 1
kfactors = []
fb = self.break_string(f)
for i, cat in self.ecats:
kf = cat.right_action_matrix(x[i], y[i], fb[i], z[i])
ret_n_rows *= kf.nrows()
ret_n_cols *= kf.ncols()
kfactors += [kf]
# This is to avoid a 0-dim bug present in my version of sage
if ret_n_rows * ret_n_cols == 0:
return matrix(ZZ, ret_n_rows, ret_n_cols, [])
ret = matrix(ZZ, 1, 1, [1])
for kf in kfactors:
ret = ret.tensor_product(kf)
return ret
def op(self):
if self.op_cat is None:
self.op_cat = ProductCategory(self.sep, *[cat.op() for cat in self.cats])
self.op_cat.op_cat = self
return self.op_cat
class Functor(object):
# To build a functor, you supply a source category,
# a target category, and a law
# law(x, f, y)
# that returns a triple (x', f', y')
# and must be functorial.
#
# What if I want to build a functor from its action matrices? This should be allowed.
def __init__(self, source, law, target):
self.source = source
self.law = law
self.target = target
self.objs = {}
self.acts = {}
def action_matrix(self, x, y):
if (x, y) in self.acts:
return self.acts[(x, y)]
rows = self.source.hom(x, y)
xx = self(x)
yy = self(y)
cols = self.target.hom(xx, yy)
ret = matrix(ZZ, len(rows), len(cols), [1 if self.law(x, r, y) == (xx, c, yy) else 0 for r in rows for c in cols])
self.acts[(x, y)] = ret
return ret
# Can be called on a single object
# or on a triple (x, f, y)
# or on a CatMat
def __call__(self, *args):
if len(args) == 1:
if isinstance(args[0], CatMat):
cm = args[0]
ring = cm.ring
vd = []
for i, x in enumerate(cm.source):
for j, y in enumerate(cm.target):
vd += cm.entry_vector(i, j) * self.action_matrix(x, y)
new_source = [self(x) for x in cm.source]
new_target = [self(y) for y in cm.target]
return CatMat(ring, self.target, new_source, vector(cm.ring, vd), new_target)
o = args[0]
if o in self.objs:
return self.objs[o]
ret = self.law(o, self.source.identity(o), o)[0]
self.objs[o] = ret
return ret
if len(args) == 3:
return self.law(*args)
raise SyntaxError('Arguments could not be interpreted: ' + str(args))
# Should return a functor of some kind
# but current implementation is very crude
# and just returns a function that accepts MatrixRepresentations and dgModules
def upper_star(self):
def upper_star_function(module):
if isinstance(module, MatrixRepresentation):
def law(x, f, y):
return module(*self(x, f, y))
return MatrixRepresentation(self.source, module.ring, law, target_cat=module.target_cat)
if isinstance(module, dgModule):
def d_laws(k):
def d_law(x, dd):
return module.differential(x, dd, a=k)
return d_law
def f_law(dd, x, f, y):
return module.module_in_degree(dd)(*self(x, f, y))
return dgModule(self.source, module.ring, f_law,
[d_laws(k) for k in range(module.n_diff)], target_cat=module.target_cat)
return upper_star_function
# Gives the entrywise action of this functor on a matrix space of format (source, target)
def matrix_action_matrix(functor, source, target):
blocks = []
for x in source:
for y in target:
blocks += [functor.action_matrix(x, y)]
return block_diagonal_matrix(blocks)
def test(self):
for x in self.source.objects:
for y in self.source.objects:
for z in self.source.objects:
for f in self.source.hom(x, y):
for g in self.source.hom(y, z):
if self(x, self.source.compose(x, f, y, g, z), z)[1] != \
self.target.compose(self(x), self(x, f, y)[1], self(y), self(y, g, z)[1], self(z)):
print('Functoriality fails for the morphisms ' + str((x, f, y, g, z)) + '.')
# CatMat is the class for matrices over a category
# Main job is to implement M*N, M<<N, M>>N, ~M, and +M
# Also has classmethods for these operations with sagemath matrices
class CatMat(object):
# source and target are the row and column labels
# v a vector whose entries give the matrix
# The ordering:
# upper left entry is first.
# then the entry just right of it,
# then the rest of the first row,
# then the next row, left to right.
# etc.
# If you don't want to deal with that, then use the
# class method from_string.
#
# Actually, though, on reflection I think rows and columns
# should certainly not be (always) indexed 0, 1, 2, ..., k
# since we often will want more interesting indexing data
# The source objects and target objects should be allowed
# to be dictionaries once I get around to it.
#
# TODO: reimplement so that the entries are stored as a dict of entries
# TODO: and where the source and target can be lists of hashable things
# TODO: and then implement slicing
def __init__(self, ring, cat, source, data_vector, target):
"""
:type cat: FiniteCategory
"""
self.cat = cat
self.ring = ring
self.source = source
self.target = target
# I think sparse vectors are allowed here
# but I haven't tested this.
self.data_vector = data_vector
self.intervals = {}
self.m_to_n = {}
self.n_to_m = {}
# We should also have a dict going
# where we have evaluated (-,d) and (d,-) on self
count = 0
for i, x in enumerate(source):
for j, y in enumerate(target):
h = self.cat.hom(x, y)
self.intervals[(i, j)] = (count, count + len(h))
for f in h:
self.m_to_n[(i, f, j)] = count
self.n_to_m[count] = (i, f, j)
count += 1
self.ambient_rank = count
if len(data_vector) != count:
raise SyntaxError('Matrix cannot be built from this data_vector, which has rank '
+ str(len(data_vector)) + '. Expected rank: ' + str(count))
self.res = {0: self}
def nrows(self):
return len(self.source)
def ncols(self):
return len(self.target)
@classmethod
def identity_matrix(cls, ring, cat, source_target):
vd = []
for i, x in enumerate(source_target):
for j, y in enumerate(source_target):
h = len(cat.hom(x, y))
if i == j:
try:
one_position = cat.morphism_to_number(x, cat.identity(x), x)
vd += [0] * one_position
vd += [1]
vd += [0] * (h - one_position - 1)
except(TypeError):
# In this case, cat is a preadditive category so the identity is a vector
vd += list(cat.identity(x))
else:
vd += [0] * h
return CatMat(ring, cat, source_target, vector(ring, vd), source_target)
@classmethod
def zero_matrix(cls, ring, cat, source, target):
if cat is None:
return zero_matrix(ring, source, target)
z = 0
for x in source:
for y in target:
z += len(cat.hom(x, y))
return CatMat(ring, cat, source, zero_vector(ring, z), target)
@classmethod
def from_string(cls, ring, cat, source, matrix_string, target):
matrix_string = matrix_string.replace(' ', '')
r = len(source)
c = len(target)
def read_next(s, t, string):
ss = string
hom_list = list(cat.hom(s, t))
hom_list.sort(key=len, reverse=True)
for f in hom_list:
ss = ss.replace(f, '~' * len(f))
end_codon_position = [ss.find(','), ss.find(']')]
# What happens if this codon is not found?
# It would mean that some morphism has characters
# that imitate the syntax of a matrix.
return min([x for x in end_codon_position if x != -1])
left_to_parse = matrix_string
if left_to_parse[0] != '[':
raise SyntaxError('Matrix must start with the symbol \'[\'' + matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
output_matrix = []
for i in range(r - 1):
s = source[i]
if left_to_parse[0] != '[':
raise SyntaxError('Row must start with the symbol \'[\'' + matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
row = []
for j in range(c - 1):
t = target[j]
k = read_next(s, t, left_to_parse)
row.append(left_to_parse[:k])
left_to_parse = left_to_parse[k:]
if left_to_parse[0] != ',':
raise SyntaxError('Row ended before ' + str(c) + ' entries.'
+ matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
t = target[c - 1]
k = read_next(s, t, left_to_parse)
row.append(left_to_parse[:k])
left_to_parse = left_to_parse[k:]
if left_to_parse[0] != ']':
raise SyntaxError('Row should have ended after ' + str(c) + ' entries: '
+ matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
output_matrix.append(row)
if left_to_parse[0] != ',':
raise SyntaxError('Rows must be separated with the symbol \',\'' + matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
s = source[r - 1]
if left_to_parse[0] != '[':
raise SyntaxError('Row must start with the symbol \'[\'' + matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
row = []
for j in range(c - 1):
t = target[j]
k = read_next(s, t, left_to_parse)
row.append(left_to_parse[:k])
left_to_parse = left_to_parse[k:]
if left_to_parse[0] != ',':
raise SyntaxError('Row ended before ' + str(c) + ' entries.' + matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
t = target[c - 1]
k = read_next(s, t, left_to_parse)
row.append(left_to_parse[:k])
left_to_parse = left_to_parse[k:]
if left_to_parse[0] != ']':
raise SyntaxError('Row should have ended after ' + str(c) + ' entries.'
+ matrix_string + '\n' + left_to_parse)
left_to_parse = left_to_parse[1:]
if left_to_parse != ']':
raise SyntaxError('Matrix should have ended after ' + str(r) + ' rows.'
+ matrix_string + '\n' + left_to_parse)
output_matrix.append(row)
# output matrix is still strings.
return CatMat.from_string_entries(ring, cat, source, output_matrix, target)
# Here list_of_lists_of_strings must be len(source)
# lists of vectors, with each list of length len(target).
# We don't fall into the 0 x n trap because the source and target are given.
@classmethod
def from_string_entries(cls, ring, cat, source, list_of_lists_of_strings, target):
r = len(source)
c = len(target)
lls = list_of_lists_of_strings
if len(lls) != r:
raise SyntaxError('Incorrect number of rows. Found '
+ str(len(lls)) + ', expected ' + str(r) + '.')
for i, row in enumerate(lls):
if len(row) != c:
raise SyntaxError('Incorrect number of columns in row ' + str(i) +
'. Found ' + str(len(row)) + ', expected ' + str(c) + '.')
def string_to_ring(ss):
s = ss.replace(' ', '')
if s == '':
return ring(1)
if s[0] == '+':
return string_to_ring(s[1:])
if s == '-':
return ring(-1)
return ring(s)
llv = []
for i, x in enumerate(source):
lv = []
for j, y in enumerate(target):
h = cat.hom(x, y)
v = zero_vector(ring, len(h))
if lls[i][j] == '0':
lv.append(v)
continue
morphs, coeffs = cat.split_string_on_morphisms(x, lls[i][j], y)
if morphs[0] == '':
morphs = morphs[1:]
for k, f in enumerate(morphs):
try:
ring_element = string_to_ring(coeffs[k])
except TypeError as e:
raise TypeError('While parsing the coefficient of the morphism "' + morphs[k] +
'" which appears as term ' + str(k) + ' in entry ' + str((i, j)) +
', the following error was generated: ' + e.message)
v[cat.morphism_to_number(x, f, y)] += ring_element
lv.append(v)
llv.append(lv)
return CatMat.from_vector_entries(ring, cat, source, llv, target)
# Here list_of_lists_of_vectors must be len(source)
# lists of vectors, with each list of length len(target).
# We don't fall into the 0 x n trap because the source and target are given.
@classmethod
def from_vector_entries(cls, ring, cat, source, list_of_lists_of_vectors, target):
r = len(source)
c = len(target)
llv = list_of_lists_of_vectors
if len(llv) != r:
raise SyntaxError('Incorrect number of rows. Found '
+ str(len(llv)) + ', expected ' + str(r) + '.')
for i, row in enumerate(llv):
if len(row) != c:
raise SyntaxError('Incorrect number of columns in row ' + str(i) +
'. Found ' + str(len(row)) + ', expected ' + str(c) + '.')
vd = []
for lv in llv:
for v in lv:
vd.extend(v)
return cls(ring, cat, source, vector(ring, vd), target)
# Here table is a list of lists of CatMats
# to be assembled into a single CatMat.
# If an entry is not a CatMat, it will be replaced with a zero matrix.
# TODO: that's horrible
# In all but casual usage: provide ring, cat, sources, and targets up front
# to avoid the 0 x n and n x 0 traps. Otherwise these will be inferred
# by looking at table.
@classmethod
def block_matrix(cls, table, ring=None, cat=None, sources=None, targets=None):
if ring is None:
try:
ring = table[0][0].ring
except AttributeError:
ring = table[0][0].base_ring()
if cat is None:
try:
cat = table[0][0].cat
except AttributeError:
# TODO: This line is probably falling in the 0 x n trap
return block_matrix(table)
if sources is None:
sources = []
for i, row in enumerate(table):
found = False
for entry in row:
if isinstance(entry, CatMat):
sources += [entry.source]
found = True
break
if not found:
# TODO:
# There is another way to infer sources and targets
# when a nonzero scalar appears in the table
# we know that multiple of the identity matrix goes there
# and so that block is square.
# It makes sense to use this information in practice.
raise SyntaxError('Could not infer source of row ' + str(i))
if targets is None:
targets = []
for j in range(len(table[0])):
found = False
for i in range(len(table)):
if isinstance(table[i][j], CatMat):
targets += [table[i][j].target]
found = True
break
if not found:
raise SyntaxError('Could not infer target of column ' + str(j))
for i, row in enumerate(table):
for j, entry in enumerate(row):
if isinstance(entry, CatMat):
if list(entry.source) != list(sources[i]):
raise SyntaxError('Entry ' + str((i, j)) + ' has wrong source. Found ' +
str(entry.source) + ', expected ' + str(sources[i]) + ".")
if list(entry.target) != list(targets[j]):
raise SyntaxError('Entry ' + str((i, j)) + ' has wrong target. Found ' +
str(entry.target) + ', expected ' + str(targets[j]) + ".")
else:
try:
ring(entry)
except:
raise SyntaxError('Could not interpret entry ' + str((i, j)) + ' as either ' +
'a CatMat or a scalar.')
if ring(entry) == ring(0):
table[i][j] = CatMat.zero_matrix(ring, cat, sources[i], targets[j])
else:
if sources[i] == targets[j]:
table[i][j] = ring(entry) * CatMat.identity_matrix(ring, cat, sources[i])
else:
raise SyntaxError('A nonzero scalar is only permitted in an entry where ' +
'an identity matrix makes sense; this is not the case ' +
'for block entry ' + str((i, j)))
vd = []
for i, s in enumerate(sources):
for k in range(len(s)):
for j, t in enumerate(targets):
for l in range(len(t)):
vd.extend(table[i][j].entry_vector(k, l))
source = []
for s in sources:
for x in s:
source += [x]
target = []
for t in targets:
for y in t:
target += [y]
return cls(ring, cat, source, vector(ring, vd), target)
# If there's any chance that cat_mats might have length zero
# then it is important to provide the three optional arguments
@classmethod
def block_row(cls, cat_mats, ring=None, cat=None, source=None):
if (ring is None or cat is None or source is None) and len(cat_mats) == 0:
raise ValueError('Cannot infer optional arguments since no columns were given.')
if ring is None:
ring = cat_mats[0].ring
if cat is None:
try:
cat = cat_mats[0].cat
except AttributeError:
return block_matrix([cat_mats], ring=ring)
if source is None:
source = cat_mats[0].source
return CatMat.block_matrix([cat_mats], ring=ring, cat=cat,
sources=[source], targets=[m.target for m in cat_mats])
# If cat=None, then we assume that these cat_mats are actually sagemath matrices
@classmethod
def block_diagonal(cls, cat_mats, ring=None, cat=None):
k = len(cat_mats)
# This code is in flux. TODO: cat=None should mean it's a sagemath matrix
if False:
raise ValueError('Cannot infer optional arguments since no blocks were given.')
if ring is None:
try:
ring = cat_mats[0].ring
except AttributeError:
return block_diagonal_matrix(cat_mats)
if cat is None:
try:
return block_diagonal_matrix(cat_mats)
# AttributeError?
except (TypeError, AttributeError):
cat = cat_mats[0].cat
sources = [m.source for m in cat_mats]
targets = [m.target for m in cat_mats]
table = [[cat_mats[i] if i == j else 0 for j in range(k)] for i in range(k)]
return CatMat.block_matrix(table, ring=ring, cat=cat, sources=sources, targets=targets)
@classmethod
def kronecker_product(cls, *mats_pre):
if type(mats_pre[0]) is str:
sep = mats_pre[0]
mats = mats_pre[1:]
else:
sep = ','
mats = mats_pre
row_counts = [range(m.nrows()) for m in mats]
col_counts = [range(m.ncols()) for m in mats]
#zero_dim_matrix = any([(m.nrows() == 0) or (m.ncols() == 0) for m in mats])
cmf = [i for i, m in enumerate(mats) if isinstance(m, CatMat)]
cat_factors = [mats[i].cat for i in cmf]
prod_cat = ProductCategory(sep, *cat_factors)
one_fold = (len(cat_factors) == 1)
if len(mats) == 0:
# ZZ is the initial ring, so this is reasonable
return matrix(ZZ, 1, 1, [1])
# From now on mats cannot be empty
# so we can set about detecting the ring
if len(cmf) == 0:
ring = mats[0].base_ring()
else:
ring = mats[cmf[0]].ring
# Check if every factor is a usual sagemath matrix;
# in this case build and return the usual kronecker_product
# with care to handle 0xn and nx0 traps