-
Notifications
You must be signed in to change notification settings - Fork 0
/
bga_4_0.py
1503 lines (1268 loc) · 45.9 KB
/
bga_4_0.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 as np
import numpy.linalg
import scipy as sp
import scipy.sparse
import scipy.sparse.linalg
import scipy.optimize
import copy
#import scipy.misc
import os.path
#import cPickle
#from math import floor,cos,acos,sin
import sys
import math
from time import time
import mpmath as mp
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import manifold_reflected_brownian_motion as mrbm
mrbm = reload(mrbm)
#from mpl_toolkits.mplot3d import Axes3D
#from mpl_toolkits.mplot3d.art3d import Poly3DCollection
#import matplotlib.pyplot as plt
#import pandas as pd
#from pandas import Series, DataFrame
import polyhedra as poly
bg_version = "5_1"
def get_filename(poly_name, prefix, suffix):
"""
Return relative path filename.
"""
return os.path.join(os.path.dirname(__file__),'data',prefix + poly_name + suffix)
def get_poly(poly_name):
""""
Return data from BG input file for poly
"""
f = open(get_filename(poly_name, '', '_'+bg_version+'.txt'), 'r')
# Shape name
line = [x for x in f.readline().split()]
if line[0] != poly_name:
print "oh dear.",line[0],"is not actually the same as",poly_name
# V E F
[F,E,V] = [int(x) for x in f.readline().split()]
# face types
line_S = [int(x) for x in f.readline().split()]
S = line_S[0]
species = line_S[1:]
# Adjacency list
f_types = []
adj_list = []
for k in range(F):
line = [int(x) for x in f.readline().split()]
f_types.append(line[1:1+line[0]])
adj_list.append(line[1+line[0]:])
dual = []
for j in range(V):
line = [int(x) for x in f.readline().split()]
dual.append(line[1:])
return V,E,F,S,species,f_types,adj_list,dual
def get_bg_ss(poly_name, get_degens=False):
"""
Read BG state space from file.
"""
# Load file.
f = open(get_filename(poly_name,'bg_' + bg_version + '_', '_arc.txt'), 'r')
# Read vertices
vert_line = f.readline().split()
V = int(vert_line[-1])
ints = []
ids = []
paths = []
shell_int = []
shell_paths = []
for k in range(V):
line = [int(x) for x in f.readline().split()]
if k != line[0]:
print "OH DEAR."
ids.append(line[1])
ints.append(line[5:])
paths.append(line[3])
shell_int.append(line[2])
shell_paths.append(line[4])
ints = np.array(ints) # Switch to np arrays earlier??
paths = np.array(paths)
ids = np.array(ids)
shell_int = np.array(shell_int)
shell_paths = np.array(shell_paths)
# Read edges.
edge_line = f.readline().split()
E = int(edge_line[-1])
edges = []
shell_edge = []
if get_degens == True:
degens = []
for j in range(E):
line = [int(x) for x in f.readline().split()]
edges.append(line[0:2])
shell_edge.append(line[2])
if get_degens == True:
degens.append(line[3])
edges = np.array(edges)
shell_edge = np.array(shell_edge)
if get_degens == True:
return ints, ids, paths, shell_int, shell_paths, edges, shell_edge, degens
else:
return ints, ids, paths, shell_int, shell_paths, edges, shell_edge
def get_bg_log(poly_name):
"""
Read info about building game for poly.
"""
# Load file.
f = open(get_filename(poly_name,'bg_' + bg_version + '_', '_log.txt'), 'r')
vertices_line = f.readline().split()
v_counts = np.array([int(x) for x in f.readline().split()])
if sum(v_counts) != int(vertices_line[-1]):
print "ERROR: Differing intermediate count and sum", sum(v_counts), int(vertices_line[-1])
shell_vertices_line = f.readline().split()
s_v_counts = np.array([int(x) for x in f.readline().split()])
if sum(s_v_counts) != int(shell_vertices_line[-1]):
print "ERROR: Differing shell_intermediate count and sum", sum(s_v_counts), int(shell_vertices_line[-1])
edges_line = f.readline().split()
e_counts = np.array([int(x) for x in f.readline().split()])
if sum(e_counts) != int(edges_line[-1]):
print "ERROR: Differing edge count and sum", sum(e_counts), int(edges_line[-1])
shell_edges_line = f.readline().split()
s_e_counts = np.array([int(x) for x in f.readline().split()])
if sum(s_e_counts) != int(shell_edges_line[-1]):
print "ERROR: Differing shell edge count and sum", sum(s_e_counts), int(shell_edges_line[-1])
time_line = f.readline().split()
t_counts = np.array([int(x) for x in f.readline().split()])
if sum(t_counts) != int(time_line[-1]):
print "ERROR: Differing time count and sum", sum(t_counts), int(time_line[-1])
pathways = int(f.readline().split()[-1])
shell_pathways = int(f.readline().split()[-1])
return v_counts, s_v_counts, e_counts, s_e_counts, t_counts, pathways, shell_pathways
def print_oeis_sequences(poly_name):
"""
Take in poly_name ant print the corresponding
OEIS internal format input strings for both
general and shellable intermediates.
"""
v, s_v = get_bg_log(poly_name)[:2]
print_oeis_format(v, sc=False)
print ''
print_oeis_format(s_v, sc=True)
def print_oeis_format(v, sc=False):
"""
print sequence v in OEIS format.
"""
if sc == True:
sc_str = ' simply-connected '
else:
sc_str = ' '
print '%I'
print '%S ',
for k, x in enumerate(v):
# Don't include the 0th term
if k == 0:
continue
sys.stdout.write(str(x))
if k != len(v) - 1:
sys.stdout.write(',')
print ''
print '%N Number of'+sc_str+'one-sided n-ominoes on the',
for j, w in enumerate(poly_name.split('_')):
if j == len(poly_name.split('_')) - 1:
print w+'.'
else:
print w
print '%K nonn,fini,full'
print '%O 1'
print '%A _Daniel Johnson_'
def edge_adj_list(edges, inds=False):
"""
Take list of edge pairs and populate a forward adjacency list.
"""
num_ints = 1 + max(max(e) for e in edges)
edge_adj_list = [[] for k in range(num_ints)]
edge_adj_inds = [[] for k in range(num_ints)]
for k, e in enumerate(edges):
edge_adj_list[min(e[0], e[1])].append(max(e[0],e[1]))
edge_adj_inds[min(e[0], e[1])].append(k)
if inds == True:
return edge_adj_list, edge_adj_inds
else:
return edge_adj_list
def get_paths(edges, ints, shell_int=None, shellable=False):
"""
Find number of pathways to each intermediate.
"""
mp.mp.dps = 100
int_sizes = [sum(np.array(int_j) != 0) for int_j in ints]
edge_adj = edge_adj_list(edges)
# Initialize single faced ints to 1 path
paths = [mp.mpf(int(sum(np.array(int_j) != 0) == 1)) for int_j in ints]
F = len(ints[0])
for n in range(1,F):
for i in range(len(ints)):
if int_sizes[i] == n:
for k in edge_adj[i]:
#print n, i, k
if shellable == True:
if shell_int[i] != 0 and shell_int[k] != 0:
paths[k] += paths[i]
else:
paths[k] += paths[i]
return paths
def get_shellings(edges, ints, Ss, shell_int, poly_adj_list):
"""
Find number of pathways to each intermediate.
"""
mp.mp.dps = 100
Rs = Rs = generate_rotations(poly_adj_list)
int_sizes = [sum(np.array(int_j) != 0) for int_j in ints]
edge_adj, edge_adj_inds = edge_adj_list(edges, inds=True)
# Initialize single faced ints
#shells = [int(sum(np.array(int_j) != 0) == 1) for int_j in ints]
shells = [mp.mpf(0.0) for x in ints]
for m in range(len(ints)):
if int_sizes[m] == 1:
shells[m] += len(Rs)/get_r(Rs, ints[m])
F = len(ints[0])
for n in range(1,F):
for i in range(len(ints)):
if int_sizes[i] == n:
for ind, k in enumerate(edge_adj[i]):
if shell_int[i] != 0 and shell_int[k] != 0:
#print 'hi'
shells[k] += shells[i]*Ss[edge_adj_inds[i][ind]]
return shells
def get_open_edges(ints,adj_list):
"""
For each intermediate in ints, return the number of open edges it has.
"""
Es = []
for inter in ints:
E = 0
for k in range(len(inter)):
if inter[k] == 1:
for j in adj_list[k]:
if inter[j] == 0:
E += 1.0
Es.append(E)
return np.array(Es)
def get_closed_edges(ints, adj_list):
"""
For each intermediate in ints, return the number of closed edges it has.
"""
Es = []
for inter in ints:
E = 0
for k in range(len(inter)):
if inter[k] == 1:
for j in adj_list[k]:
if inter[j] == 1 and j < k:
E += 1
Es.append(E)
return np.array(Es)
def get_degeneracies(ints, edges, adj_list, Rs=None):
"""
For each BGSS connection in edges, compute the forward and backward degeneracy numbers.
"""
if Rs == None:
Rs = generate_rotations(adj_list)
Ss = []
Ts = []
for e in edges:
chi_j, chi_k = get_chis(ints[e[0]],ints[e[1]],Rs)
sf = 0
sb = 0
for i in range(len(chi_j)):
if chi_j[i] == 0:
chi_j_ei = copy.copy(chi_j)
chi_j_ei[i] = 1
if same_int(chi_j_ei,chi_k,Rs) == True:
sf += 1
if chi_k[i] == 1:
chi_k_ei = copy.copy(chi_k)
chi_k_ei[i] = 0
if same_int(chi_j,chi_k_ei,Rs) == True:
sb += 1
Ss.append(sf)
Ts.append(sb)
return np.array(Ss), np.array(Ts)
#def generate_rotations(adj_list):
# """
# Generate a list of index permutations corresponding to the
# rotation group of adj_list's polyhedron.
# """
# rotations = []
#
# F = len(adj_list)
#
# for j in range(F):
# for k in range(len(adj_list[j])):
# ind = rotate_ind(j,k,adj_list)
# if ind == None:
# continue
# rotations.append(ind)
#
# return rotations
#
#def rotate_ind(piv,r,adj_list):
# """
# Get index permutation coresponding to moving face 0 to piv
# and rotating that face in adj_list r times.
# """
# f = 0
# F = len(adj_list)
#
# prev = []
# nxt = []
# ind = [None for x in range(F)]
#
# if piv >= F:
# raise Exception("bad piv!")
#
# # For reindexing, recenter at piv
# ind[0] = piv
# f += 1
#
# # Number of faces adjacent to piv (must be the same for [0] and [piv])
# N = len(adj_list[0])
#
# # If base faces different, return error
# if len(adj_list[0]) != len(adj_list[piv]):
# return None
#
# # Fill in indices for faces adjacent to piv
# for j in range(N):
# ind[adj_list[0][j]] = adj_list[piv][(r+j-1+N)%N]
# prev.append(adj_list[0][j])
# f += 1
#
# while f < F:
# if len(prev) == 0:
# print "ERROR, inf-loop"
# break
#
# for k in range(len(prev)):
# Nk = len(adj_list[prev[k]])
#
# for h in range(Nk):
# # Find already indexed face
# i = adj_list[prev[k]][h]
# if ind[i] != -1:
# break
#
# for q in range(Nk):
# if adj_list[ind[prev[k]]][q] == ind[i]:
# break
#
# for g in range(Nk):
# map_from = adj_list[prev[k]][(h+g)%Nk]
# map_to = adj_list[ind[prev[k]]][(q+g)%Nk]
#
# # Check if already indexed
# if ind[map_from] != -1:
# if ind[map_from] != map_to:
# return None
#
# else:
# # If not, add index
# ind[map_from] = map_to
# nxt.append(map_from)
# f += 1
#
# prev = []
# prev = copy.copy(nxt)
# nxt = []
# return ind
#
def generate_rotations(adj_list):
"""
Generate a list of index permutations corresponding to the
rotation group of adj_list's polyhedron.
"""
rotations = []
F = len(adj_list)
for j in range(F):
for k in range(len(adj_list[j])):
try:
ind = rotate_ind(j,k,adj_list)
if ind[0] == -2:
continue
except:
continue
rotations.append(ind)
return rotations
def rotate_ind(piv,r,adj_list):
"""
Get index permutation coresponding to moving face 0 to piv
and rotating that face in adj_list r times.
"""
f = 0
F = len(adj_list)
prev = []
nxt = []
ind = [-1 for x in range(F)]
if piv >= F:
print "bad piv!"
# For reindexing, recenter at piv
ind[0] = piv
f += 1
# Number of faces adjacent to piv (must be the same for [0] and [piv])
N = len(adj_list[0])
# If base faces different, return error
if len(adj_list[0]) != len(adj_list[piv]):
return [-2]
# Fill in indices for faces adjacent to piv
for j in range(N):
ind[adj_list[0][j]] = adj_list[piv][(r+j-1+N)%N]
prev.append(adj_list[0][j])
f += 1
while f < F:
if len(prev) == 0:
print "ERROR, inf-loop"
break
for k in range(len(prev)):
Nk = len(adj_list[prev[k]])
for h in range(Nk):
# Find already indexed face
i = adj_list[prev[k]][h]
if ind[i] != -1:
#print 'a'
break
for q in range(Nk):
if adj_list[ind[prev[k]]][q] == ind[i]:
#print 'b'
break
for g in range(Nk):
map_from = adj_list[prev[k]][(h+g)%Nk]
#print k, g, Nk, ind[prev[k]], len(adj_list), len(adj_list[ind[prev[k]]]), (q+g)%Nk
map_to = adj_list[ind[prev[k]]][(q+g)%Nk]
# Check if already indexed
if ind[map_from] != -1:
if ind[map_from] != map_to:
return [-2]
else:
# If not, add index
ind[map_from] = map_to
nxt.append(map_from)
f += 1
prev = []
prev = copy.copy(nxt)
nxt = []
return ind
def get_chis(x1,x2,Rs):
"""
Purmute the entries of x2 (according to a polyhedral rotation) such that
x1 is a sub int of x2.
"""
if sum(x > 0 for x in x1) + 1 != sum(y > 0 for y in x2):
print 'ERROR: non-coresponding x1 and x2, wrong number of faces.'
print x1, x2
chi_j = x1
if sub_int(chi_j, x2) == True:
chi_k = x2
return chi_j, chi_k
else:
for R in Rs:
chi_k = np.array([x2[R[k]] for k in range(len(R))])
if sub_int(chi_j,chi_k) == True:
return chi_j, chi_k
print 'ERROR: non-coresponding x1 and x2 after search.'
return
def sub_int(x1,x2):
"""
Check if x1 == x2 in all entries except for exactly one.
"""
#if numpy.linalg.norm(x1 + x2) == (4*sum(x1)+1)**0.5:
# return True
if sum((x1[k] != 0) != (x2[k] != 0) for k in range(len(x1))) == 1:
return True
return False
def same_int(x1,x2,Rs):
"""
Check if x1 is a polyhedral rotation of x2.
"""
for R in Rs:
#if numpy.linalg.norm(np.array([x1[R[k]] for k in range(len(R))]) - np.array(x2)) == 0:
# return True
if sum((x1[R[k]] != 0) != (x2[k] != 0) for k in range(len(x2))) == 0:
return True
return False
def find_int_num(x, ints, Rs):
"""
For binary vector x of faces present determine which bg int (if any) x belongs to.
"""
num_faces = sum(x >= 1)
for k, int_k in enumerate(ints):
if sum(int_k >= 1) != num_faces:
continue
else:
if same_int(x, int_k, Rs) == True:
return k
return None
def get_rs(ints,adj_list,Rs=None):
"""
Compute the order of the rotation group for each intermediate.
"""
if Rs == None:
Rs = generate_rotations(adj_list)
rs = []
for inter in ints:
#r = 0
#for R in Rs:
# if numpy.linalg.norm(inter - np.array([inter[R[k]] for k in range(len(inter))])) == 0:
# r += 1
#rs.append(r)
rs.append(get_r(Rs, inter))
return np.array(rs)
def get_r(Rs, inter):
r = 0
for R in Rs:
if numpy.linalg.norm(inter - np.array([inter[R[k]] for k in range(len(inter))])) == 0:
r += 1
return r
def get_Q(BG_cons, betas=1.0, alpha=1.0):
"""
"""
Q_dat = np.hstack((BG_cons['Q_jk'],
BG_cons['Q_kj'],
-BG_ints['z_j']))
Q_j = np.hstack((BG_cons['x_j'],
BG_cons['x_k'],
np.arange(N)))
Q_k = np.hstack((BG_cons['x_k'],
BG_cons['x_j'],
np.arange(N)))
#Q_dat = np.hstack((BG_cons[BG_cons['x_j'] != N - 1]['Q_jk'],
# BG_cons[BG_cons['x_k'] != N - 1]['Q_kj'],
# -BG_ints['z_j'][:N-1].values))
#
#Q_j = np.hstack((BG_cons[BG_cons['x_j'] != N - 1]['x_j'],
# BG_cons[BG_cons['x_k'] != N - 1]['x_k'],
# np.arange(N - 1)))
#
#Q_k = np.hstack((BG_cons[BG_cons['x_j'] != N - 1]['x_k'],
# BG_cons[BG_cons['x_k'] != N - 1]['x_j'],
# np.arange(N - 1)))
return scipy.sparse.coo_matrix((Q_dat,(Q_j,Q_k)), shape=(N,N)).tocsc()
def get_dist(Q, T, num_times):
"""
Return 2d array with analytic solution for the dist on each intermediate starting from int 0.
"""
N = Q.shape[0]
u0 = np.zeros(N)
u0[0] = 1.0
# Identity matrix excpt with M_j,j = 0 for if j in A
Ident_Ac = scipy.sparse.coo_matrix((np.ones(N-1),(np.arange(N-1),np.arange(N-1))), shape=(N,N))
Ident_Ac = Ident_Ac.tocsc()
Q = Q.tocsc()
P = scipy.sparse.linalg.expm_multiply(Q,
u0,
start=0.0,
stop=T,
num=num_times,
endpoint=True)
return P
def get_taus(Q, N, A=None):
"""
"""
One_N = scipy.sparse.coo_matrix((np.array([1]),(np.array([N-1]),np.array([0]))), shape=(N,1))
Ones_mN = scipy.sparse.coo_matrix((np.ones(N-1),(np.arange(N-1),np.zeros(N-1))), shape=(N,1))
# Identity matrix excpt with M_j,j = 0 for if j not in A
Ident_A = scipy.sparse.coo_matrix((np.array([1]),(np.array([N-1]),np.array([N-1]))), shape=(N,N))
# Identity matrix excpt with M_j,j = 0 for if j in A
Ident_Ac = scipy.sparse.coo_matrix((np.ones(N-1),(np.arange(N-1),np.arange(N-1))), shape=(N,N))
# Column matrix with the jth row equal to one if j not in A
Ones_Ac = scipy.sparse.coo_matrix((np.ones(N-1),(np.arange(N-1),np.zeros(N-1))), shape=(N,1))
#Ident_A = Ident_A.tocsr()
#Ident_Ac = Ident_Ac.tocsr()
#Ones_Ac = Ones_Ac.tocsr()
#Q = Q.tocsr()
Ident_A = Ident_A.tocsc()
Ident_Ac = Ident_Ac.tocsc()
Ones_Ac = Ones_Ac.tocsc()
Q = Q.tocsc()
return scipy.sparse.linalg.spsolve(Ident_A - Ident_Ac*Q, Ones_Ac)
def get_us(Q, t_start, t_stop, t_num, A=None):
"""
"""
N = Q.shape[0]
u0 = np.zeros(N)
u0[N-1] = 1.0
#One_N = scipy.sparse.coo_matrix((np.array([1]),(np.array([N-1]),np.array([0]))), shape=(N,1))
#Ones_mN = scipy.sparse.coo_matrix((np.ones(N-1),(np.arange(N-1),np.zeros(N-1))), shape=(N,1))
# Identity matrix excpt with M_j,j = 0 for if j not in A
#Ident_A = scipy.sparse.coo_matrix((np.array([1]),(np.array([N-1]),np.array([N-1]))), shape=(N,N))
# Identity matrix excpt with M_j,j = 0 for if j in A
Ident_Ac = scipy.sparse.coo_matrix((np.ones(N-1),(np.arange(N-1),np.arange(N-1))), shape=(N,N))
# Column matrix with the jth row equal to one if j not in A
#Ones_Ac = scipy.sparse.coo_matrix((np.ones(N-1),(np.arange(N-1),np.zeros(N-1))), shape=(N,1))
#Ident_A = Ident_A.tocsr()
#Ident_Ac = Ident_Ac.tocsr()
#Ones_Ac = Ones_Ac.tocsr()
#Q = Q.tocsr()
#Ident_A = Ident_A.tocsc()
Ident_Ac = Ident_Ac.tocsc()
#Ones_Ac = Ones_Ac.tocsc()
Q = Q.tocsc()
#u = scipy.sparse.linalg.expm_multiply(Ident_Ac*(Q - scipy.sparse.dia_matrix((Q.diagonal()[scipy.newaxis, :], [0]), shape=(N, N))),
# u0,
# start=t_start,
# stop=t_stop,
# num=t_num,
# endpoint=True)
u = scipy.sparse.linalg.expm_multiply(Ident_Ac*Q,
u0,
start=t_start,
stop=t_stop,
num=t_num,
endpoint=True)
du = Ident_Ac*Q*u.T
#return scipy.sparse.linalg.spsolve(Ident_A - Ident_Ac*Q, Ones_Ac)
return u, du
def fit_gamma_dist(t,u):
"""
Take a np arrays of positive time points t and function values u
and find parameters for the Gamm distribution that best fit (t,u)
"""
beta = get_tail_rate(t, u)
## Function to minimize.
#f = lambda x: numpy.linalg.norm(u - gamma_pdf(t, x[0], x[1]))
#
## Initial Guess
#x0 = np.array([1.0, 1.0])
# Function to minimize.
f = lambda x: numpy.linalg.norm(u[1:] - tau_pdf_est(t[1:], x[0], x[1], x[2]))
# Initial Guess
x0 = np.array([1.0, 0.0015, 1.0])
res = scipy.optimize.minimize(f, x0)
return res
def gamma_pdf(t, alpha, beta):
"""
Return the gamma distribution PDF for each point in t.
"""
return beta**alpha*t**(alpha - 1.0)*np.exp(-beta*t)/math.gamma(alpha)
def tau_pdf_est(t, gamma, omega, zeta):
"""
Return the estimated PDF for each point in t.
"""
return zeta*np.exp(-gamma/t - omega*t)
def get_tail_rate(t, u, interval_num=10):
"""
Estimate the exponential decay parameter for the tail of u.
"""
return -((np.log(u[-1]) - np.log(u[-interval_num]))/(t[-1] - t[-interval_num]))
def get_connected_faces(dual_v, int_faces):
"""
Given a list of face indices dual_v of faces meeting at a particular vertex
and the inclussion/exclussion vector int_faces indicating which faces are in the int,
return a set of sets where each inner set contains the face indices that are edge connected
at the vertex.
"""
face_groups = set()
for f in dual_v:
if int_faces[f] != 0:
face_groups.add(frozenset([f]))
for k, f_1 in enumerate(dual_v):
f_0 = dual_v[k-1]
if int_faces[f_0] != 0 and int_faces[f_1] != 0:
fg_0 = None
fg_1 = None
for fg in face_groups:
if f_0 in fg:
fg_0 = fg
if f_1 in fg:
fg_1 = fg
if fg_0 == fg_1:
continue
try:
fg_new = fg_0.union(fg_1)
face_groups.remove(fg_0)
face_groups.remove(fg_1)
face_groups.add(fg_new)
except KeyError:
print "ERROR:", fg_0, "or", fg_1, "not found in", face_groups
raise
return face_groups
def verify_dual_order(dual):
###### NEEDS ADDING?!?!?! ###########
return dual
def load_bg_int(poly_name, int_num):
"""
Load information about specified polyhedral intermediate.
Return information for corresponding linkage.
"""
try:
poly_info = getattr(poly, poly_name)
except AttributeError:
raise Exception("ERROR: " + poly_name + " not found in polyhedra.py")
verts, face_inds, cents = poly_info()
V, E, F, S, species, f_types, adj_list, dual = get_poly(poly_name)
ints, ids, paths, shell_int, shell_paths, edges, shell_edge = get_bg_ss(poly_name)
dual = verify_dual_order(dual)
try:
int_faces = ints[int_num]
except IndexError:
raise Exception("ERROR: " + poly_name + " does not have an intermediate " + int_num)
# Reindex vertices/
verts_new, faces, face_inds_new = reindex_vertices(face_inds, V, dual, int_faces, verts)
x0 = verts_new.flatten()
#face_inds_new = [[None for f in fi] for fi in face_inds]
#verts_new = []
#new_V = 0
#
#for v in range(V):
# f_groups = get_connected_faces(dual[v], int_faces)
# for fg in f_groups:
# verts_new.append(verts[v,:])
# for f in fg:
# face_inds_new[f][face_inds[f].index(v)] = new_V
# new_V += 1
#verts = np.array(verts_new)
#x0 = verts.flatten()
#
##print 'A', face_inds_new
#faces = [f for k, f in enumerate(face_inds_new) if int_faces[k] != 0]
#print 'B',faces
# Make list of links.
links = set()
for face in faces:
#print face
for k in range(len(face)):
#print '\t', k, face[k], face[k-1]
links.add(frozenset([face[k], face[k-1]]))
links = [list(link) for link in links]
lengths = np.array([numpy.linalg.norm(verts_new[link[0],:] - verts_new[link[1],:]) for link in links])
return x0, links, lengths, faces
def reindex_vertices(face_inds, V, dual, int_faces, verts):
"""
"""
face_inds_new = [[None for f in fi] for fi in face_inds]
verts_new = []
new_V = 0
for v in range(V):
f_groups = get_connected_faces(dual[v], int_faces)
for fg in f_groups:
verts_new.append(verts[v,:])
for f in fg:
face_inds_new[f][face_inds[f].index(v)] = new_V
new_V += 1
verts_new = np.array(verts_new)
x0 = verts_new.flatten()
#print 'A', face_inds_new
faces = [f for k, f in enumerate(face_inds_new) if int_faces[k] != 0]
return verts_new, faces, face_inds_new
#def load_bg_int(poly_name, int_num):
# """
# Load information about specified polyhedral intermediate.
# Return information for corresponding linkage.
# """
#
# try:
# poly_info = getattr(poly, poly_name)
# except AttributeError:
# print "ERROR:", poly_name, "not found in polyhedra.py"
# raise
#
# verts, face_inds, cents = poly_info()
# V, E, F, S, species, f_types, adj_list, dual = get_poly(poly_name)
# ints, ids, paths, shell_int, shell_paths, edges, shell_edge = get_bg_ss(poly_name)
#
# try:
# int_faces = ints[int_num]
# except IndexError:
# print "ERROR:", poly_name, "does not have an intermediate", int_num
# raise
#
# # Reindex vertices in the intermediate.
# v_in_int = np.array([False for k in range(V)])
# for k in range(F):
# if int_faces[k] != 0:
# v_in_int[face_inds[k][0]] = True
# v_in_int[face_inds[k][1]] = True
# v_in_int[face_inds[k][2]] = True
#
# # Create table for translating between new and old vertex indexing.
# old_v_ind_from_new = []
# new_v_ind_from_old = []
#
# for v in range(V):
# if v_in_int[v] == True:
# new_v_ind_from_old.append(len(old_v_ind_from_new))
# old_v_ind_from_new.append(v)
# else:
# new_v_ind_from_old.append(-1)
#
# # Create faces, masses, links, and lengths
# N = len(old_v_ind_from_new)
# dim = 3
# face_inds_new = [[new_v_ind_from_old[face_inds[j][k]] for k in range(3)] for j in range(V) if v_in_int[j]]
# q0 = np.array([])
# for k in range(N):
# for i in range(dim):
# q0 = np.hstack((q0,verts[old_v_ind_from_new[k],i]))
# masses = np.ones(N)
#
# links = []
# faces = []
# for f in range(F):
# if int_faces[f] != 0:
# new_face = []
# for j in range(len(face_inds[f])):
# a = face_inds[f][j-1]
# b = face_inds[f][j]
# a_new = new_v_ind_from_old[a]
# b_new = new_v_ind_from_old[b]
# mx = max(a_new, b_new)
# mn = min(a_new, b_new)
# #print hi, links, mn, mx
# if ([mn, mx] in links) == False:
# links.append([mn, mx])
# new_face.append(b_new)
# faces.append(new_face)
#
# lengths = np.array([numpy.linalg.norm(verts[old_v_ind_from_new[links[k][0]],:] - verts[old_v_ind_from_new[links[k][1]],:]) for k in range(len(links))])
#
#
# return N, dim, q0, masses, links, lengths, faces
#
def face_position(bg_int, face_num, faces, dim=3):
"""
Return the current and last positions in the desired dimensions for viewing.