-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfuchsia.py
2020 lines (1826 loc) · 66.6 KB
/
fuchsia.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
#!/usr/bin/env sage
"""\
Usage:
fuchsia [options] <command> <args>...
Commands:
reduce [-x <name>] [-e <name>] [-m <path>] [-t <path>] <matrix>
find an epsilon form of the given matrix
fuchsify [-x <name>] [-m <path>] [-t <path>] <matrix>
find a transformation that will transform a given matrix
into Fuchsian form
normalize [-x <name>] [-e <name>] [-m <path>] [-t <path>] <matrix>
find a transformation that will transform a given Fuchsian
matrix into normalized form
factorize [-x <name>] [-e <name>] [-m <path>] [-t <path>] <matrix>
find a transformation that will make a given normalized
matrix proportional to the infinitesimal parameter
info [-x <name>] <matrix>
show a description of a given matrix, listing singular
points and residue eigenvalues (in verbose more)
sort [-m <path>] [-t <path>] <matrix>
find a block-triangular form of the given matrix
transform [-x <name>] [-m <path>] <matrix> <transform>
transform a given matrix using a given transformation
changevar [-x <name>] [-y <name>] [-m <path>] <matrix> <expr>
transform a given matrix by susbtituting free variable
by a given expression
Options:
-h show this help message
-f <fmt> matrix file format: mtx or m (default: m)
-l <path> write log to this file
-v produce a more verbose log
-P <path> save profile report into this file
-x <name> use this name for the free variable (default: x)
-y <name> use this name for the new free variable (default: y)
-e <name> use this name for the infinitesimal parameter (default: eps)
-m <path> save the resulting matrix into this file
-t <path> save the resulting transformation into this file
-s <number> use this random seed when applicable (default: 0)
--use-maple speed up calculations by using Maple when possible
Arguments:
<matrix> read the input matrix from this file
<transform> read the transformation matrix from this file
<expr> arbitrary expression
"""
__author__ = "Oleksandr Gituliar, Vitaly Magerya"
__author_email__ = "[email protected]"
__version__ = "17.06.28"
__all__ = [
"FuchsianSystem",
"NormalizeAssistant",
"balance",
"balance_transform",
"block_triangular_form",
"epsilon_form",
"export_matrix_to_file",
"factorize",
"fuchsify",
"fuchsify_off_diagonal_blocks",
"import_matrix_from_file",
"is_fuchsian",
"matrix_c0",
"matrix_c1",
"matrix_complexity",
"matrix_residue",
"normalize",
"reduce_diagonal_blocks",
"setup_fuchsia",
"simple",
"simplify_by_factorization",
"simplify_by_jordanification",
"singularities",
"transform"
]
from collections import defaultdict
from functools import wraps
from itertools import combinations, permutations
from random import Random
import inspect
import logging
import time
from sage.all import *
from sage.misc.parser import Parser
from sage.libs.ecl import ecl_eval
def logcall(f):
@wraps(f)
def wrapper(*args, **kwargs):
logger.enter(f.__name__)
r = f(*args, **kwargs)
logger.exit(f.__name__)
return r
return wrapper
class ElapsedTimeFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None):
super(ElapsedTimeFormatter, self).__init__(fmt, datefmt)
self.start_time = time.time()
def formatTime(self, record, datefmt=None):
if datefmt is None:
return "%7.1fs" % (record.created - self.start_time)
return time.strftime(datefmt, time.localtime(record.created))
class FuchsiaLogger(object):
def __init__(self):
log_handler = logging.StreamHandler()
log_handler.setFormatter(ElapsedTimeFormatter(
"\033[32m[%(asctime)s]\033[0m %(message)s"
))
logger = logging.getLogger('fuchsia')
logger.addHandler(log_handler)
logger.setLevel(logging.WARNING)
self.addHandler = logger.addHandler
self.error = logger.error
self.isEnabledFor = logger.isEnabledFor
self.logger = logger
self.setLevel = logger.setLevel
self.depth = 0
def indent(self):
return " " * self.depth
def is_verbose(self):
return self.isEnabledFor(logging.INFO)
def enter(self, name):
self.info("-> %s" % name)
self.depth += 1
def exit(self, name):
self.depth -= 1
self.info("<- %s" % name)
def debug(self, msg):
self.logger.debug(self.indent() + msg)
def info(self, msg):
self.logger.info(self.indent() + msg)
if True:
ecl_eval("(ext:set-limit 'ext:heap-size 0)")
logger = FuchsiaLogger()
USE_MAPLE = False
def setup_fuchsia(verbosity=0, use_maple=False):
global USE_MAPLE
USE_MAPLE = bool(use_maple)
logger.setLevel(
logging.WARNING if verbosity <= 0 else \
logging.INFO if verbosity == 1 else
logging.DEBUG
)
class FuchsiaError(Exception):
pass
def cross_product(v1, v2):
m1, m2 = matrix(v1), matrix(v2)
return m1.transpose() * m2
def dot_product(v1, v2):
m1, m2 = matrix(v1), matrix(v2)
sp = m1 * m2.transpose()
return sp[0,0]
def partial_fraction(M, var):
return M.apply_map(lambda ex: ex.partial_fraction(var))
#@logcall
def fuchsia_simplify(obj, x=None):
if USE_MAPLE:
def maple_simplify(ex):
if hasattr(ex, "variables") and ((x is None) or (x in ex.variables())):
res = maple.factor(maple.radnormal(ex))
return parse(str(res))
else:
return ex
if hasattr(obj, "apply_map"):
return obj.apply_map(maple_simplify)
else:
return maple_simplify(obj)
else:
return obj.simplify_rational()
def fuchsia_solve(eqs, var):
if USE_MAPLE:
s = maple.solve(eqs, var)
solutions = s.parent().get(s._name).strip('[]').split('],[')
solutions = [s.split(',') for s in solutions if s != '']
result = []
for solution in solutions:
r = []
for s in solution:
try:
expr = fuchsia_simplify(parse(s))
r.append(expr)
except SyntaxError as error:
print("ERROR: \n%s\n %s\n" % (s, error))
continue
result.append(r)
return result
else:
return solve(eqs, var, solution_dict=True)
def change_variable(m, x, y, fy):
mm = m.subs({x: fy}) * derivative(fy, y)
return mm
def transform(M, x, T):
"""Given a system of differential equations dF/dx = M*F,
and a transformation of base functions F = T*F', compute
and return M', such that dF'/dx = M'*F'.
Note: M' = inverse(T)*(M*T - dT/dx)
"""
mm = T.inverse()*(M*T - derivative(T, x))
return mm
def balance(P, x1, x2, x):
assert P.is_square()
assert (P*P - P).is_zero()
assert not bool(x1 == x2)
coP = identity_matrix(P.nrows()) - P
if x1 == oo:
b = coP - (x - x2)*P
elif x2 == oo:
b = coP - 1/(x - x1)*P
else:
b = coP + (x - x2)/(x - x1)*P
return b
def balance_transform(M, P, x1, x2, x):
"""Same thing as transform(M, x, balance(P, x1, x2, x)), but faster."""
assert P.is_square()
#assert (P*P - P).is_zero()
assert not bool(x1 == x2)
coP = identity_matrix(P.nrows()) - P
if x1 == oo:
k = -(x - x2)
d = -1
elif x2 == oo:
k = -1/(x - x1)
d = 1/(x - x1)**2
else:
k = (x - x2)/(x - x1)
d = (x2 - x1)/(x - x1)**2
mm = (coP + 1/k*P)*M*(coP + k*P) - d/k*P
return mm
#@logcall
def limit_fixed(expr, x, x0):
#logger.debug("[%s -> %s] %s" % (x, x0, expr))
res = None
if USE_MAPLE:
res = limit_fixed_maple(expr, x, x0)
else:
res = limit_fixed_maxima(expr, x, x0)
#logger.debug("res = %s" % res)
return res
def limit_fixed_maple(expr, x, x0):
res = maple.limit(expr, **{str(x): x0})
try:
res = parse(str(res))
except:
res = NaN
return res
def limit_fixed_maxima(expr, x, x0):
"""Return a limit of expr when x->lim.
The standard 'limit()' function of SageMath does not allow
you to specify the variable, only it's name as a keyword
argument. If you have a variable, and not it's name, use
this function instead.
"""
l = maxima_calculus.sr_limit(expr, x, x0)
return expr.parent()(l)
@logcall
def singularities(m, x):
"""Find values of x around which rational matrix M has
a singularity; return a dictionary with {val: p} entries,
where p is the Poincare rank of M at x=val.
Example:
>>> x = var("x")
>>> s = singularities(matrix([[1/x, 0], [1/(x+1)**3, 1/(x+1)]]), x)
>>> sorted(s.items())
[(-1, 2), (0, 0), (+Infinity, 0)]
>>> s = singularities(matrix([[x, 1, 1/x]]), x)
>>> sorted(s.items())
[(0, 0), (+Infinity, 2)]
"""
m = fuchsia_simplify(m)
result = {}
for expr in m.list():
points_expr = singularities_expr(expr, x)
for x0, p in points_expr.items():
if x0 in result:
result[x0] = max(result[x0], p)
else:
result[x0] = p
return result
def singularities_expr(expr, x):
if USE_MAPLE:
return singularities_expr_maple(expr, x)
else:
return singularities_expr_maxima(expr, x)
def singularities_expr_maple(expr, x):
if bool(expr == 0):
return {}
result = {}
sols = fuchsia_solve(1/expr, x)
points = [x0 for x0 in sols[0]] if len(sols) > 0 else []
for x0 in points:
if x0 not in result:
result[x0] = 0
else:
result[x0] += 1
sols = fuchsia_solve((1/(expr.subs({x: 1/x})/x**2)).simplify_rational(), x)
points = [x0 for x0 in sols[0]] if len(sols) > 0 else []
for x0 in points:
if x0 == 0:
if oo not in result:
result[oo] = 0
else:
result[oo] += 1
return result
def singularities_expr_maxima(expr, x):
if expr.is_zero():
return {}
result = {}
eq = factor(1/expr)
points, ps = solve(eq, x, solution_dict=True, multiplicities=True)
for sol, p in zip(points, ps):
if x not in sol:
raise Exception("Maxima can't solve this equation: %s" % eq)
x0 = expand(sol[x])
if p >= 1:
result[x0] = p-1
eq = factor(1/(expr.subs({x: 1/x})/x**2))
points, ps = solve(eq, x, solution_dict=True, multiplicities=True)
for sol, p in zip(points, ps):
if x not in sol:
raise Exception("Maxima can't solve this equation: %s" % eq)
if sol[x] == 0 and p >= 1:
result[oo] = p-1
return result
def matrix_taylor0(m, x, x0, exp):
"""Return the 0-th coefficient of Taylor expansion of
a matrix M around a finite point x=point, assuming that
M(x->point)~1/(x-point)**exp.
Example:
>>> x = var('x')
>>> matrix_taylor0(matrix([[x/(x-1), 1/x, x, 1]]), x, 1, 1)
[1 0 0 0]
"""
return m.apply_map(lambda ex: limit_fixed(ex*(x-x0)**exp, x, x0))
def matrix_taylor1(M, x, point, exp):
"""Return the 1-th coefficient of Taylor expansion of
a matrix M around a finite point x=point, assuming that
M(x->point)~1/(x-point)**exp.
Example:
>>> x = var('x')
>>> matrix_taylor1(matrix([[x/(x-1), 1/x, x, 1]]), x, 0, 1)
[0 0 0 1]
"""
def taylor1(e, x):
l0 = limit_fixed(e, x, 0)
l1 = limit_fixed((e - l0)/x, x, 0)
return l1
return matrix([
[taylor1(e, x) for e in row]
for row in M.subs({x: x+point})*x**exp
])
def matrix_c0(M, x, point, p):
"""Return the 0-th coefficient of M's expansion at x=point,
assuming Poincare rank of M at that point is p. If point is
+Infinity, return minus the coefficient at the highest power of x.
Examples:
>>> x = var("x")
>>> m = matrix([[1/x, 1/x**2], [1, 1/(x-1)]])
>>> matrix_c0(m, x, 0, 1)
[0 1]
[0 0]
>>> matrix_c0(m, x, 1, 0)
[0 0]
[0 1]
>>> matrix_c0(m, x, oo, 1)
[ 0 0]
[-1 0]
>>> matrix_c0(m*x, x, oo, 2)
[ 0 0]
[-1 0]
"""
if point == oo:
return -matrix_taylor0(M.subs({x: 1/x}), x, 0, p-1)
else:
return matrix_taylor0(M, x, point, p+1)
def matrix_c1(M, x, point, p):
"""Return the 1-st coefficient of M's expansion at x=point,
assuming Poincare rank of M at that point is p. If point is
+Infinity, return minus the coefficient at the second-to-highest
power of x.
Examples:
>>> x = var("x")
>>> m = matrix([[1/x, 1/x**2], [1, 1/(x-1)]])
>>> matrix_c1(m, x, 0, 1)
[1 0]
[0 0]
>>> matrix_c1(m, x, oo, 1)
[-1 0]
[ 0 -1]
"""
if point == oo:
return -matrix_taylor1(M.subs({x: 1/x}), x, 0, p-1)
else:
return matrix_taylor1(M, x, point, p+1)
def matrix_residue(M, x, x0):
"""Return matrix residue of M at x=x0, assuming that M's
Poincare rank at x=x0 is zero.
Example:
>>> x = var("x")
>>> m = matrix([[1/x, 2/x], [3/x, 4/x]])
>>> matrix_residue(m, x, 0)
[1 2]
[3 4]
>>> matrix_residue(m, x, oo)
[-1 -2]
[-3 -4]
"""
if M._cache is None:
M._cache = {}
key = "matrix_residue_%s_%s" % (x, x0)
if key in M._cache:
return M._cache[key]
m0 = matrix_c0(M, x, x0, 0)
M._cache[key] = m0
return m0
def matrix_is_nilpotent(M):
"""Return True if M is always nilpotent, False otherwise.
Examples:
>>> a, b, c = var('a b c')
>>> matrix_is_nilpotent(matrix([[0,a,b],[0,0,c],[0,0,0]]))
True
>>> matrix_is_nilpotent(matrix([[a,0,0],[0,b,0],[0,0,c]]))
False
"""
for v in M.eigenvalues():
if not v.is_zero():
return False
return True
def jordan_cell_sizes(J):
"""Return a tuple of Jordan cell sizes from a matrix J in Jordan
normal form.
Examples:
>>> jordan_cell_sizes(matrix([[1,1,0,0],[0,1,0,0],[0,0,1,1],[0,0,0,1]]))
(2, 2)
>>> jordan_cell_sizes(matrix([[1,1,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,1]]))
(3, 1)
>>> jordan_cell_sizes(zero_matrix(5,5))
(1, 1, 1, 1, 1)
"""
assert J.is_square()
sizes = []
n = 1
for i in range(J.nrows() - 1):
if J[i, i+1].is_zero():
sizes.append(n)
n = 1
else:
n += 1
sizes.append(n)
assert sum(sizes) == J.nrows()
return tuple(sizes)
def solve_right_fixed(A, B):
"""As of SageMath 6.10, 'Matrix.solve_right' method uses a broken
check for solution correctness; this function corrects that check.
"""
C = A.solve_right(B, check=False)
if C.nrows() and C.ncols():
# Sometimes 'solve_right' returns a giant expression,
# which can be simplified into a tiny one; without this
# simplification 'is_zero' call below may take forever
# to finish.
#
# Note that the condition above is there to make sure
# that an empty matrix is not passed into 'simplify_rational',
# otherwise you'll get this error:
# TypeError: unable to make sense of Maxima expression
# 'matrix()' in Sage
C = C.simplify_rational()
if not (A*C - B).simplify_rational().is_zero():
raise ValueError("matrix equation has no solutions")
return C
def solve_left_fixed(A, B):
"""As of SageMath 6.10, 'Matrix.solve_left' method uses a broken
check for solution correctness; this function corrects that check.
"""
return solve_right_fixed(A.transpose(), B.transpose()).transpose()
def any_integer(rng, ring, excluded):
r = 2
while True:
p = ring(rng.randint(-r, r))
if p not in excluded:
return p
r *= 2
#==================================================================================================
# Transformation routines
#==================================================================================================
def block_triangular_form(m):
"""Find a lower block-triangular form of a given matrix.
Return a tuple `(M, T, B)` where:
* `M` is a new matrix;
* `T` is a transformation matrix;
* `B` is a list of tuples (ki, ni), such that M's i-th
diagonal block is given by `M.submatrix(ki, ki, ni, ni)`.
"""
logger.enter("block_triangular_form")
if logger.is_verbose():
logger.debug("matrix before transformation:\n%s\n" % matrix_mask_str(m))
n = m.nrows()
deps_1_1 = {}
for i, row in enumerate(m.rows()):
deps_1_1[i] = set(j for j,ex in enumerate(row) if not bool(ex==0))
deps_1_all = {}
def find_deps_1_all(i):
if i in deps_1_all:
return deps_1_all[i]
deps_1_all[i] = deps_1_1[i]
for j in deps_1_1[i]:
if i == j:
continue
find_deps_1_all(j)
deps_1_all[i] = deps_1_all[i].union(deps_1_all[j])
[find_deps_1_all(j) for j in range(n)]
deps_coup = dict((i, set([])) for i in range(n))
for i in range(n):
for j in range(n):
if (i in deps_1_all[j]) and (j in deps_1_all[i]):
deps_coup[i].update([i,j])
deps_coup[j].update([i,j])
shuffle = []
error = False
while not error:
if not deps_coup:
break
error = True
for i in range(n):
if i not in deps_coup:
continue
b = deps_coup[i].copy()
if b != deps_1_all[i]:
continue
if b == set([]):
b = set([i])
shuffle += [b]
for j in deps_1_all[i].copy():
if j in deps_1_all:
del deps_1_all[j]
del deps_coup[j]
for j in range(n):
if j not in deps_coup:
continue
deps_coup[j].difference_update(b)
deps_1_all[j].difference_update(b)
if i in deps_coup:
del deps_coup[i]
if i in deps_1_all:
del deps_1_all[i]
error = False
break
if error:
raise FuchsiaError("Infinite loop")
t = zero_matrix(SR,n)
i = 0
blocks = []
for block in shuffle:
blocks.append((i, len(block)))
for j in list(block):
t[j,i] = 1
i += 1
logger.info("found %d blocks" % len(blocks))
mt = transform(m, None, t)
if logger.is_verbose():
logger.debug("matrix after transformation:\n%s\n" % matrix_mask_str(mt))
logger.exit("block_triangular_form")
return mt, t, blocks
def epsilon_form(m, x, eps, seed=0):
logger.enter("epsilon_form")
m, t1, b = block_triangular_form(m)
m, t2 = reduce_diagonal_blocks(m, x, eps, b=b, seed=seed)
m, t3 = fuchsify_off_diagonal_blocks(m, x, eps, b=b)
m, t4 = factorize(m, x, eps, b=b, seed=seed)
t = t1*t2*t3*t4
logger.exit("epsilon_form")
return m, t
def matrix_mask(m):
n = m.nrows()
return matrix(SR, n, n, [int(not bool(ex==0)) for ex in m.list()])
def matrix_mask_str(m):
s = ''
for row in matrix_mask(m).rows():
s += ' '.join([str(ex) for ex in row]).replace('0', '.').replace('1','x') + "\n"
return s
def matrix_str(m, n=2):
buf = ""
ind = " "*n
for col in m.columns():
for ex in col:
buf += ind + str(ex) + "\n"
buf += "\n"
buf = buf[:-1]
return buf
#==================================================================================================
# Step I: Fuchsify
#==================================================================================================
def is_fuchsian(m, x):
for i, expr in enumerate(m.list()):
if expr.is_zero():
continue
points = singularities_expr(expr, x)
for x0, p in points.items():
if p > 0:
return False
return True
def fuchsify(M, x, seed=0):
"""Given a system of differential equations of the form dF/dx=M*F,
try to find a transformation T, which will reduce M to Fuchsian
form. Return the transformed M and T. Raise FuchsiaError if
M can not be transformed into Fuchsian form.
Note that such transformations are not unique; you can obtain
different ones by supplying different seeds.
"""
logger.enter("fuchsify")
assert M.is_square()
rng = Random(seed)
poincare_map = singularities(M, x)
def iter_reductions(p1, U):
for p2, prank2 in poincare_map.items():
if bool(p2 == p1): continue
while prank2 >= 0:
B0 = matrix_c0(M, x, p2, prank2)
if not B0.is_zero(): break
poincare_map[p2] = prank2 = prank2 - 1
if prank2 < 0: continue
v = find_dual_basis_spanning_left_invariant_subspace(B0, U, rng)
if v is None: continue
P = fuchsia_simplify(U*v, x)
M2 = fuchsia_simplify(balance_transform(M, P, p1, p2, x), x)
yield p2, P, M2
combinedT = identity_matrix(M.base_ring(), M.nrows())
reduction_points = [pt for pt,p in poincare_map.items() if p >= 1]
reduction_points.sort()
if reduction_points == []:
logger.info("already fuchsian")
else:
for pt in reduction_points:
logger.info("rank = %d, x = %s" % (poincare_map[pt], pt))
while reduction_points:
pointidx = rng.randint(0, len(reduction_points) - 1)
point = reduction_points[pointidx]
prank = poincare_map[point]
if prank < 1:
del reduction_points[pointidx]
continue
while True:
A0 = matrix_c0(M, x, point, prank)
if A0.is_zero(): break
A1 = matrix_c1(M, x, point, prank)
try:
U, V = alg1x(A0, A1, x)
except FuchsiaError as e:
logger.debug("Managed to fuchsify matrix to this state:\n"
"%s\nfurther reduction is pointless:\n%s" % (M, e))
raise FuchsiaError("matrix cannot be reduced to Fuchsian form")
try:
point2, P, M = min(iter_reductions(point, U), \
key=lambda point2_P_M2: matrix_complexity(point2_P_M2[2]))
except ValueError as e:
point2 = any_integer(rng, M.base_ring(), poincare_map)
P = fuchsia_simplify(U*V, x)
M = balance_transform(M, P, point, point2, x)
M = fuchsia_simplify(M, x)
logger.info("Will introduce an apparent singularity at %s." % point2)
logger.debug(
"Applying balance between %s and %s with projector:\n%s" % (point, point2, P))
combinedT = combinedT * balance(P, point, point2, x)
if point2 not in poincare_map:
poincare_map[point2] = 1
poincare_map[point] = prank - 1
combinedT = fuchsia_simplify(combinedT, x)
logger.exit("fuchsify")
return M, combinedT
def fuchsify_off_diagonal_blocks(m, x, eps, b=None):
logger.enter("fuchsify_off_diagonal_blocks")
n = m.nrows()
if b is None:
m, t, b = block_triangular_form(m)
else:
t = identity_matrix(SR, n)
for i, (ki, ni) in enumerate(b):
for j, (kj, nj) in enumerate(reversed(b[:i])):
pts = singularities(m.submatrix(ki, kj, ni, nj), x)
printed = False
while any(pts.values()):
bj = m.submatrix(ki, kj, ni, nj)
if bj.is_zero():
break
for x0, p in pts.items():
if p < 1:
continue
if not printed:
printed = True
logger.info("Fuchsifying block (%d, %d) (%d, %d)" % (ki, ni, kj, nj))
logger.debug(" singular points = %s" % (pts,))
a0 = matrix_residue(m.submatrix(ki, ki, ni, ni)/eps, x, x0)
b0 = matrix_c0(bj, x, x0, p)
c0 = matrix_residue(m.submatrix(kj, kj, nj, nj)/eps, x, x0)
d_vars = [gensym() for i in range(ni*nj)]
d = matrix(SR, ni, nj, d_vars)
eq = d + eps/p*(a0*d - d*c0) + b0/p
sol = solve(eq.list(), *d_vars, solution_dict=True)
d = d.subs(sol[0])
t0 = identity_matrix(SR, n)
t0[ki:ki+ni, kj:kj+nj] = \
d/(x-x0)**p if not (x0 == oo) else d*(x**p)
m = fuchsia_simplify(transform(m, x, t0), x)
t = fuchsia_simplify(t*t0, x)
pts[x0] -= 1
logger.exit("fuchsify_off_diagonal_blocks")
return m, t
def reduce_at_one_point(M, x, v, p, v2=oo):
"""Given a system of differential equations of the form dF/dx=M*F,
with M having a singularity around x=v with Poincare rank p,
try to find a transformation T, which will reduce p by 1 (but
possibly introduce another singularity at x=v2). Return the
transformed M and T.
"""
assert M.is_square()
assert p > 0
n = M.nrows()
combinedT = identity_matrix(M.base_ring(), n)
while True:
A0 = matrix_c0(M, x, v, p)
if A0.is_zero(): break
A1 = matrix_c1(M, x, v, p)
U, V = alg1x(A0, A1, x)
P = U*V
M = balance_transform(M, P, v, v2, x)
M = fuchsia_simplify(M, x)
combinedT = combinedT * balance(P, v, v2, x)
combinedT = fuchsia_simplify(combinedT, x)
return M, combinedT
def find_dual_basis_spanning_left_invariant_subspace(A, U, rng):
"""Find matrix V, such that it's rows span a left invariant
subspace of A and form a dual basis with columns of U (that
is, V*U=I).
"""
evlist = []
for eigenval, eigenvects, evmult in A.eigenvectors_left():
evlist.extend(eigenvects)
rng.shuffle(evlist)
W = matrix(evlist)
try:
M = solve_left_fixed(W*U, identity_matrix(U.ncols()))
return M*W
except ValueError:
return None
def alg1x(A0, A1, x):
#if not matrix_is_nilpotent(A0):
# raise FuchsiaError("matrix is irreducible (non-nilpotent residue)")
# We will rely on undocumented behavior of jordan_form() call:
# we will take it upon faith that it sorts Jordan cells by
# their size, and puts the largest ones closer to (0, 0).
A0J, U = A0.jordan_form(transformation=True)
invU = U.inverse()
A0J_cs = jordan_cell_sizes(A0J)
assert all(A0J_cs[i] >= A0J_cs[i+1] for i in range(len(A0J_cs) - 1))
ncells = len(A0J_cs)
A0J_css = [sum(A0J_cs[:i]) for i in range(ncells + 1)]
nsimplecells = sum(1 if s == 1 else 0 for s in A0J_cs)
u0 = [U[:,A0J_css[i]] for i in range(ncells)]
v0t = [invU[A0J_css[i+1]-1,:] for i in range(ncells)]
L0 = matrix([
[(v0t[k]*(A1)*u0[l])[0,0] for l in range(ncells)]
for k in range(ncells)
])
L0 = fuchsia_simplify(L0, x)
L1 = matrix([
[(v0t[k]*u0[l])[0,0] for l in range(ncells)]
for k in range(ncells)
])
assert (L1 - diagonal_matrix(
[0]*(ncells-nsimplecells) + [1]*nsimplecells)).is_zero()
#zero_rows = [i for i in range(A0.nrows()) if A0J[i,:].is_zero()]
#zero_cols = [j for j in range(A0.nrows()) if A0J[:,j].is_zero()]
#assert len(zero_rows) == len(zero_cols) == ncells
#_L0 = (invU*A1*U)[zero_rows, zero_cols]
#assert (L0 - _L0).is_zero()
lam = SR.symbol()
if not (L0 - lam*L1).determinant().is_zero():
raise FuchsiaError("matrix is Moser-irreducible")
S, D = alg1(L0, A0J_cs)
I_E = identity_matrix(D.base_ring(), A0.nrows())
for i in range(ncells):
for j in range(ncells):
if not D[i,j].is_zero():
ni = A0J_css[i]
nj = A0J_css[j]
for k in range(min(A0J_cs[i], A0J_cs[j])):
I_E[ni+k,nj+k] += D[i,j]
U_t = U*I_E
invU_t = U_t.inverse()
return \
U_t[:, [A0J_css[i] for i in S]], \
invU_t[[A0J_css[i] for i in S], :]
def alg1(L0, jordan_cellsizes):
assert L0.is_square()
ring = L0.base_ring()
N = L0.nrows()
I_N = identity_matrix(N)
S = set()
D = zero_matrix(ring, N)
K = sum(1 if s > 1 else 0 for s in jordan_cellsizes)
while True:
Lx = copy(L0)
for i in S:
Lx[:, i] = 0
Lx[i, :] = 0
fi = None
c = None
for i in range(0, N):
if i not in S:
try:
c = solve_right_fixed(Lx[:,0:i], Lx[:,i])
except ValueError:
# No solution found; vectors are independent.
continue
fi = i
break
assert fi is not None
assert c is not None
D0 = matrix(ring, N)
invD0 = matrix(ring, N)
for j in range(fi):
D0[j, fi] = -c[j, 0]
invD0[j, fi] = -c[j, 0] \
if jordan_cellsizes[j] == jordan_cellsizes[fi] else 0
L0 = (I_N - invD0)*L0*(I_N + D0)
D = D + D0 + D*D0
if fi < K:
break
S.add(fi)
# Check Alg.1 promise
for j in range(N):
for k in range(N):
if (j not in S) and ((k in S) or k == fi):
assert L0[j,k] == 0
S.add(fi)
return S, D
#==================================================================================================
# Step II: Normalize
#==================================================================================================
def is_normalized(M, x, eps):
"""Return True if (a Fuchsian) matrix M is normalized, that
is all the eigenvalues of it's residues in x lie in [-1/2, 1/2)
range (in limit eps->0). Return False otherwise.
Examples:
>>> x, e = var("x epsilon")
>>> is_normalized(matrix([[(1+e)/3/x, 0], [0, e/x]]), x, e)
True
"""
points = singularities(M, x)
for x0, p in points.items():
M0 = matrix_residue(M, x, x0)
for ev in M0.eigenvalues():
ev = limit_fixed(ev, eps, 0)
if not (Rational((-1, 2)) <= ev and ev < Rational((1, 2))):
return False
return True
def are_diagonal_blocks_reduced(m, b, x, eps):
"""Return True if diagonal blocks of `m` are normalized, that is all the eigenvalues of theirs
residues in `x` lie in the range [-1/2, 1/2) in eps->0 limit; return False otherwise. Diagonal
blocks are defined by the list `b` which corresponds to the equivalent value returned by the
`block_triangular_form` routine.
Examples:
>>> x, e = var("x epsilon")
>>> are_diagonal_blocks_reduced(matrix([[(1+e)/3/x, 0], [0, e/x]]), [(0,1),(1,1)], x, e)
True
"""
for ki, ni in b:
mi = fuchsia_simplify(m.submatrix(ki, ki, ni, ni), x)
if not is_normalized(mi, x, eps):
return False
return True
def reduce_diagonal_blocks(m, x, eps, b=None, seed=0):
"""Given a lower block-triangular system of differential equations of the form dF/dx=m*F,
find a transformation that will shift all eigenvalues of all residues of all its diagonal
blocks into the range [-1/2, 1/2) in eps->0 limit. Return the transformed matrix m and the
transformation; raise FuchsiaError if such transformation is not found. Diagonal blocks
are defined by the list `b` which corresponds to the equivalent value returned by the
`block_triangular_form` routine.
"""
logger.enter("reduce_diagonal_blocks")
n = m.nrows()
if b is None:
m, t, b = block_triangular_form(m)
else:
t = identity_matrix(SR, n)
for i, (ki, ni) in enumerate(b):
mi = fuchsia_simplify(m.submatrix(ki, ki, ni, ni), x)
ti = identity_matrix(SR, ni)
logger.info("reducing block #%d (%d,%d)" % (i,ki,ni))
if logger.is_verbose():
logger.debug("\n%s" % matrix_str(mi, 2))
mi_fuchs, ti_fuchs = fuchsify(mi, x, seed=seed)
ti = ti*ti_fuchs
mi_norm, ti_norm = normalize(mi_fuchs, x, eps, seed=seed)
ti = ti*ti_norm
mi_eps, ti_eps = factorize(mi_norm, x, eps, seed=seed)
ti = ti*ti_eps
t[ki:ki+ni, ki:ki+ni] = ti