-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsift_lib.py
2364 lines (2050 loc) · 117 KB
/
parsift_lib.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
from __future__ import division
import matplotlib.image as mpimg
import numpy as np
import time
import matplotlib.pyplot as plt
import scipy.stats
import random, math
from scipy.spatial import Voronoi, voronoi_plot_2d, Delaunay
from Bio import SeqIO, Seq
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
import pytess
import networkx as nx
import os, datetime
import planarity
import ipdb
from scipy.spatial import ConvexHull
from scipy.optimize import minimize
import matplotlib
import matplotlib.cm as cm
import scipy.optimize
import warnings
import itertools
from sklearn.decomposition import PCA
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
from scipy.spatial import cKDTree
from sklearn import preprocessing
import collections
try:
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
except ImportError:
raise ImportError("Matplotlib is required for draw()")
class Surface:
def __init__(self, target_nsites, directory_label, random_seed = 4, master_directory = None):
self.target_nsites = target_nsites
self.directory_label = directory_label
random.seed(a=random_seed)
today = datetime.date.today()
if not master_directory:
self.directory_name = str(today) + '_' + str(self.directory_label) + '_' + str(time.time())
os.makedirs(self.directory_name)
else:
self.directory_name = master_directory
def circular_grid_ian(self):
self.adjusted_target_nsites = int(self.target_nsites*(0.866193598020831))
self.roi_radius = np.sqrt((self.adjusted_target_nsites) / np.pi)
self.grid_radius = int(np.ceil(self.roi_radius))
self.box_dim = 2 * self.grid_radius
self.box_half_nsites = int(np.ceil((2*self.grid_radius) ** 2))
self.lattice_sites_a = np.zeros((self.box_half_nsites, 2))
self.lattice_sites_b = np.zeros((self.box_half_nsites, 2))
self.all_neighbor_sets = [[]]*self.box_half_nsites*2
# self.a_neighbor_sets = [[]]*self.box_half_nsites
# self.b_neighbor_sets = [[]] * self.box_half_nsites
self.gridID_catalog = {}
for i in range(0, self.box_dim):
for jj in range(0, self.box_dim):
current_site_identity = i * self.box_dim + jj
b_site_parallel_identity = current_site_identity + self.box_half_nsites
self.lattice_sites_a[current_site_identity, 0] = float(i) - float(self.roi_radius)
self.lattice_sites_a[current_site_identity, 1] = (float(jj) * math.sqrt(3)) - float(self.roi_radius)
a_site_neighbors = []
b_site_neighbors = []
# try:
a_above = current_site_identity - self.box_dim
if a_above < 0: #upper edge boundary
pass
else:
a_site_neighbors.append(a_above)
a_below = current_site_identity + self.box_dim
if a_below >= self.box_half_nsites: #lower edge boundary
pass
else:
a_site_neighbors.append(a_below)
a_top_left = current_site_identity - 1 - self.box_dim + self.box_half_nsites
if current_site_identity%self.box_dim - (current_site_identity - 1)%self.box_dim != 1 or current_site_identity - self.box_dim < 0:#reject
pass
else:
a_site_neighbors.append(a_top_left)
a_top_right = current_site_identity - self.box_dim + self.box_half_nsites
if current_site_identity - self.box_dim < 0 :#upper criterion
pass
else:
a_site_neighbors.append(a_top_right)
# ipdb.set_trace()
a_lower_left = current_site_identity - 1 + self.box_half_nsites
if current_site_identity%self.box_dim - (current_site_identity - 1)%self.box_dim != 1:#lower criterion, left edge criterion
pass
else:
a_site_neighbors.append(a_lower_left)
a_lower_right = current_site_identity + self.box_half_nsites
a_site_neighbors.append(a_lower_right)
b_above = current_site_identity + self.box_half_nsites - self.box_dim
if b_above - self.box_half_nsites < 0: #upper edge boundary
pass
else:
b_site_neighbors.append(b_above)
b_below = current_site_identity + self.box_half_nsites + self.box_dim
if b_below >= self.box_half_nsites*2: #upper edge boundary
pass
else:
b_site_neighbors.append(b_below)
b_top_right = current_site_identity + 1
if current_site_identity%self.box_dim - (current_site_identity + 1)%self.box_dim != -1 :#upper criterion
pass
else:
b_site_neighbors.append(b_top_right)
b_top_left = current_site_identity
b_site_neighbors.append(b_top_left)
b_lower_left = current_site_identity + self.box_dim
if b_lower_left >= self.box_half_nsites:#lower criterion, left edge criterion
pass
else:
b_site_neighbors.append(b_lower_left)
b_lower_right = current_site_identity + self.box_dim + 1
if b_lower_right >= self.box_half_nsites or current_site_identity%self.box_dim - (current_site_identity + 1)%self.box_dim != -1:
pass
else:
b_site_neighbors.append(b_lower_right)
self.all_neighbor_sets[current_site_identity] = a_site_neighbors
self.all_neighbor_sets[b_site_parallel_identity] = b_site_neighbors
# all_neighbors = np.append(a_site_neighbors,b_site_neighbors)
self.lattice_sites_b[:, 0] = self.lattice_sites_a[:, 0] + 0.5
self.lattice_sites_b[:, 1] = self.lattice_sites_a[:, 1] + math.sqrt(3) / 2
self.lattice_sites_both = np.append(self.lattice_sites_a, self.lattice_sites_b, axis=0)
self.site_coordinates = np.zeros((0, 2))
self.old_site_IDs = []
self.final_neighborsets = []
#circle criterion
new_site_counter = 0
for oldID in range(0, len(self.lattice_sites_both)):
# if point[0]**2 + point[1]**2 <= self.roi_radius ** 2: # then the point is inside the circle
if np.linalg.norm(self.lattice_sites_both[oldID]) <= self.roi_radius:
self.site_coordinates = np.append(self.site_coordinates, [self.lattice_sites_both[oldID]], axis=0)
self.old_site_IDs.append(oldID)
# ipdb.set_trace()
self.gridID_catalog.update({oldID:new_site_counter})
new_site_counter += 1
for point in self.old_site_IDs:
# ipdb.set_trace()
accepted_neighbors = [self.gridID_catalog[oldID] for oldID in list(set(self.all_neighbor_sets[point]).intersection(self.old_site_IDs))]
# [self.gridID_catalog[i] for i in self.all_neighbor_sets[point] and self.old_site_IDs]
self.final_neighborsets.append(accepted_neighbors)
# ipdb.set_trace()
self.nsites = len(self.site_coordinates)
pickasite = 1
# self.all_neighbor_sets[pickasite] = a_site_neighbors
# self.all_neighbor_sets[pickasite + self.box_half_nsites] = b_site_neighbors
# plt.scatter(self.lattice_sites_both[:,0],self.lattice_sites_both[:,1])
# plt.scatter(self.lattice_sites_both[pickasite][0], self.lattice_sites_both[pickasite][1], c='red')
# for neighbor in self.all_neighbor_sets[pickasite]:
# plt.scatter(self.lattice_sites_both[neighbor][0],self.lattice_sites_both[neighbor][1],c='yellow')
# plt.show()
# ipdb.set_trace()
# plt.scatter(self.site_coordinates[:,0],self.site_coordinates[:,1])
# plt.scatter(self.site_coordinates[pickasite][0], self.site_coordinates[pickasite][1], c='red')
# for neighbor in self.final_neighborsets[pickasite]:
# plt.scatter(self.site_coordinates[neighbor][0],self.site_coordinates[neighbor][1],c='yellow')
# plt.show()
# ipdb.set_trace()
# merge = np.vstack((lattice_sites_a, lattice_sites_b))
def plot_sites(self):
plt.scatter(self.site_coordinates[:, 0], self.site_coordinates[:, 1])
plt.show()
def scale_image_axes(self, filename = 'monalisacolor.png'):
#for resolving aspect ratio and scale differences of the image and the grid
imarray = np.array(mpimg.imread(filename))
x_length_image = len(imarray[0,:])
y_length_image = len(imarray[:,0])
x_grid_min = min(self.site_coordinates[:,0])
y_grid_min = min(self.site_coordinates[:, 1])
x_grid_max = max(self.site_coordinates[:,0])
y_grid_max = max(self.site_coordinates[:,1])
x_length_grid = x_grid_max-x_grid_min
y_length_grid = y_grid_max-y_grid_min
aspect_ratio_image = x_length_image/y_length_image
aspect_ratio_grid = x_length_grid/y_length_grid
if aspect_ratio_image <= aspect_ratio_grid: #then this means that the image is tall relative to the grid
# in this case, we add padding to the sides of the image while maintaining the original height
padding_one_side = np.ones((len(imarray[:,0]),int((1./aspect_ratio_grid*len(imarray[:,0])-len(imarray[0,:]))/2) ,np.shape(imarray)[2]))
try :self.scaled_imarray = np.concatenate((padding_one_side,imarray),axis=1)
except: ipdb.set_trace()
self.scaled_imarray = np.concatenate((self.scaled_imarray, padding_one_side), axis=1)/np.max(imarray)
elif aspect_ratio_image > aspect_ratio_grid:
# in this case, we add padding to the top and bottom with same width as the original image
padding_one_side = np.ones(( int((aspect_ratio_grid*len(imarray[0,:]) - len(imarray[:,0]))/2) , len(imarray[0,:]) , 3))
self.scaled_imarray = np.concatenate((padding_one_side, imarray), axis=0)
self.scaled_imarray = np.concatenate((self.scaled_imarray, padding_one_side), axis=0) / np.max(imarray)
else:
print 'error with aspect ratio scaling of image'
self.lookup_x_axis = np.arange(x_grid_min,x_grid_max,x_length_grid/float(len(self.scaled_imarray[:,0])-1))
self.lookup_y_axis = np.arange(y_grid_min,y_grid_max,y_length_grid/float(len(self.scaled_imarray[0,:])-1))
def seed(self,nseed,full_output=True):
self.nseed = nseed
choices = [i for i in range(0, self.nsites)]
self.seed = np.random.choice(choices, nseed, replace=False)
self.corseed = np.zeros((nseed, 2))
self.p1 = list()
for i in range(0, nseed):
n = self.seed[i]
self.corseed[i] = self.site_coordinates[n, :]
if full_output==True:
np.savetxt(self.directory_name +'/'+ 'corseed', self.corseed, delimiter=",")
np.savetxt(self.directory_name +'/'+ 'seed', self.seed, delimiter=",")
self.bc = ["" for x in range(0, nseed)]
for i in range(0, nseed):
self.bc[i] = barcode()
if i >= 0:
for j in range(0, i - 1):
while self.bc[i] == self.bc[j]:
self.bc[i] = barcode()
bc_record = ["" for i in self.bc]
for i in range(0, len(self.bc)):
bc_record[i] = SeqRecord(Seq(self.bc[i]), id=str(i))
for i in range(0, nseed):
self.p1.append(str(bc_record[i].seq.reverse_complement()))
if full_output == True:
SeqIO.write(bc_record, self.directory_name + '/' + "bc.faa", "fasta")
np.savetxt(self.directory_name + '/' + 'barcode', self.bc, delimiter=",", fmt="%s")
np.savetxt(self.directory_name+'/'+ 'p1', self.p1, delimiter=',', fmt='%s')
# return corseed, p1, bc, seed
def ideal_only_crosslink(self,full_output=True):
self.triangulated_delaunay = Delaunay(self.corseed, qhull_options="Qz Q2")
self.ideal_graph = get_ideal_graph(self.triangulated_delaunay)
self.rgb_stamp_catalog = np.zeros((self.nseed,3))
voronoi_kdtree = cKDTree(self.corseed)
test_point_dist, self.p2_proxm = voronoi_kdtree.query(self.site_coordinates)
self.polony_sizes = collections.Counter(self.p2_proxm)
# ipdb.set_trace()
# self.p2_proxm = np.zeros((self.nsites))
for i in range(0, self.nseed):
c = random.random()
for j in range(0, self.nsites):
if self.p2_proxm[j] == i:
rgb, gray = get_pixel_rgb(self.scaled_imarray,self.lookup_x_axis,self.lookup_y_axis,self.site_coordinates[j,0],self.site_coordinates[j,1])
rgb = rgb / np.sum(rgb)
p_threshold = random.random()
if p_threshold < gray: #darker means closer to zero,
try:
colorID = np.random.choice([0,1,2],p=rgb)
self.rgb_stamp_catalog[i][colorID] += 1.
except:
self.rgb_stamp_catalog[i][0] += 1
self.rgb_stamp_catalog[i][1] += 1
self.rgb_stamp_catalog[i][2] += 1
self.rgb_stamp_catalog[i] = self.rgb_stamp_catalog[i]/float(self.polony_sizes[i])
# ipdb.set_trace()
def crosslink_polonies(self, full_output=True, optimal_linking=True,bipartite=False):
if optimal_linking == False:
if full_output == True:
plt.close()
plt.figure(figsize=(10, 10), dpi=500)
# nseed = len(p1)
self.p2_proxm = np.zeros((self.nsites),dtype=int)
self.p2_secondary = np.zeros((self.nsites),dtype=int)
# self.sites_distance_matrix = np.zeros((self.nsites,self.nsites),dtype=np.float)
self.sites_nearest_neighbors = np.zeros((self.nsites, 6), dtype=np.float)
self.available_nearest_neighbors = []
self.sites_all_partners = np.zeros((self.nsites, 2), dtype=np.float)
self.site_membership = {}
self.bc_index_pair_sitelinking = []
self.self_pairing_events = []
self.cross_pairing_events = []
self.self_pairing_events_sites = []
self.cross_pairing_events_sites = []
#SITE MAPPING LOOP - gather information about site memborship and neighborhood
if full_output == True:print 'begin gathering neighborhood data of sites'
for i in range(0, self.nsites):
self.p2_dis = np.zeros((self.nseed))
for j in range(0, self.nseed):
# self.p2_dis[j] = (math.sqrt((self.site_coordinates[i, 0] - self.corseed[j, 0]) ** 2 + (self.site_coordinates[i, 1] - self.corseed[j, 1]) ** 2))
self.p2_dis[j] = np.linalg.norm(self.site_coordinates[i] - self.corseed[j])
distances_sorted = np.argsort(self.p2_dis)
self.p2_proxm[i] = distances_sorted[0] #get the membership in polony by taking the closest of distances to each seed
self.p2_secondary[i] = distances_sorted[1] #get the second closest
self.site_membership.update({i: self.p2_proxm[i]})
# for j in range(0, self.nsites):
# self.sites_distance_matrix[i, j] = np.linalg.norm(self.site_coordinates[i] - self.site_coordinates[j])
# self.sites_nearest_neighbors[i] = np.argsort(self.sites_distance_matrix[i])[1:7]
# self.available_nearest_neighbors.append(list(self.sites_nearest_neighbors[i]))
self.available_nearest_neighbors.append(list(self.final_neighborsets[i]))
#crosslinking step - pick a random nearest neighbor, update partnership, keep track of self pairing and crosspairing
self.sites_nearest_neighbors = self.final_neighborsets
if full_output == True:print 'begin linking sites'
visitation_queue = range(0,self.nsites)
while len(visitation_queue) >= 2:
arbitrary_site = visitation_queue[0]
if len(self.available_nearest_neighbors[arbitrary_site]) != 0:
partner = random.choice(self.available_nearest_neighbors[arbitrary_site])
if partner in visitation_queue:
try:
for neighbor in self.sites_nearest_neighbors[int(partner)]:
try:
self.available_nearest_neighbors[int(neighbor)].remove(partner)
except:
pass
except:
pass
nascent_pair_event = [self.site_membership[arbitrary_site],self.site_membership[partner]]
nascent_pair_event_sites = [arbitrary_site, partner]
self.bc_index_pair_sitelinking.append(nascent_pair_event)
if nascent_pair_event[0] == nascent_pair_event[1]:
self.self_pairing_events.append(nascent_pair_event)
self.self_pairing_events_sites.append(nascent_pair_event_sites)
else:
self.cross_pairing_events.append(nascent_pair_event)
self.cross_pairing_events_sites.append(nascent_pair_event_sites)
visitation_queue.remove(arbitrary_site)
visitation_queue.remove(partner)
else: #the selected partner is not available, has already been occupied, we should therefore remove it as an option all over
self.available_nearest_neighbors[arbitrary_site].remove(int(partner))
for neighbor in self.sites_nearest_neighbors[int(partner)]:
try:
self.available_nearest_neighbors[int(neighbor)].remove(partner)
except:
pass
else:
visitation_queue.remove(arbitrary_site)
# plt.scatter(self.site_coordinates[:,0],self.site_coordinates[:,1],color='black')
# plt.scatter(self.site_coordinates[pickasite][0], self.site_coordinates[pickasite][1], c='red')
# for neighbor in self.final_neighborsets[pickasite]:
# plt.scatter(self.site_coordinates[neighbor][0],self.site_coordinates[neighbor][1],c='yellow')
# plt.show()
# ipdb.set_trace()
# ipdb.set_trace()
if full_output == True: print 'end of site linking'
self.p2 = ["" for x in range(0, self.nsites)]
for i in range(0, self.nsites):
x = int(self.p2_proxm[i])
self.p2[i] = reverse(self.p1[x])
#self.bc_index_pair = zip(self.p2_proxm, self.p2_secondary) #create crosslinks, for each site, connect it to its parent and closest polony neighbor
self.bc_index_pair = self.cross_pairing_events
# ipdb.set_trace()
cmap = matplotlib.cm.get_cmap('Spectral')
vor_polony = Voronoi(self.corseed, qhull_options = "")
if full_output == True:
if self.nseed <= 500:
voronoi_plot_2d(vor_polony,show_vertices=False)
else:
voronoi_plot_2d(vor_polony, show_vertices=False,show_points = False, line_width = 0.1)
self.rgb_stamp_catalog = np.zeros((self.nseed,3))
if full_output == True:print 'begin gathering polony sizes'
self.polony_sizes = collections.Counter(self.p2_proxm) #p2_proxm stores which seed each site is closest to
# ipdb.set_trace()
if full_output == True:print 'end of gathering polony sizes'
for i in range(0, self.nseed):
c = random.random()
for j in range(0, self.nsites):
if self.p2_proxm[j] == i:
if full_output == True:
plt.scatter(self.site_coordinates[j, 0], self.site_coordinates[j, 1], color=cmap(c), s=1)
rgb, gray = get_pixel_rgb(self.scaled_imarray,self.lookup_x_axis,self.lookup_y_axis,self.site_coordinates[j,0],self.site_coordinates[j,1])
rgb = rgb / np.sum(rgb)
p_threshold = random.random()
if p_threshold < gray: #darker means closer to zero,
try:
colorID = np.random.choice([0,1,2],p=rgb)
self.rgb_stamp_catalog[i][colorID] += 1.
except:
self.rgb_stamp_catalog[i][0] += 1
self.rgb_stamp_catalog[i][1] += 1
self.rgb_stamp_catalog[i][2] += 1
self.rgb_stamp_catalog[i] = self.rgb_stamp_catalog[i]/float(self.polony_sizes[i])
# ipdb.set_trace()
if full_output == True:print 'end of stamp cataloging'
self.triangulated_delaunay = Delaunay(self.corseed, qhull_options="Qz Q2")
self.ideal_graph = get_ideal_graph(self.triangulated_delaunay)
self.untethered_graph = nx.Graph()
for edge in self.cross_pairing_events:
self.untethered_graph.add_edge(edge[0],edge[1])
self.untethered_graph.add_edge(edge[1], edge[0])
if full_output == True:
for edge in self.cross_pairing_events_sites:
plt.plot([self.site_coordinates[edge[0]][0], self.site_coordinates[edge[1]][0]],
[self.site_coordinates[edge[0]][1], self.site_coordinates[edge[1]][1]], color='red')
for edge in self.self_pairing_events_sites:
plt.plot([self.site_coordinates[edge[0]][0], self.site_coordinates[edge[1]][0]],
[self.site_coordinates[edge[0]][1], self.site_coordinates[edge[1]][1]], color='gray')
np.savetxt(self.directory_name + '/' + 'p2', self.p2, delimiter=",", fmt="%s")
np.savetxt(self.directory_name + '/' + 'polony_seed', self.p2_proxm, delimiter=",")
np.savetxt(self.directory_name + '/' + 'point_adjacent_polony', self.p2_secondary, delimiter=",")
np.savetxt(self.directory_name + '/' + 'bcindexpairlist', self.bc_index_pair, delimiter=',')
# plt.rcParams['figure.figsize'] = (20,20)
plt.xlim(-.1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.min(
self.site_coordinates[:, 0]),
.1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.max(
self.site_coordinates[:, 0]))
plt.ylim(-.1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.min(
self.site_coordinates[:, 1]),
.1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.max(
self.site_coordinates[:, 1]))
if self.nseed <= 500:
for i in range(0, self.nseed):
plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=0.5)
# plt.figure(figsize=(10, 10), dpi=500)
else:
plt.autoscale(enable=True, axis='both', tight=None)
plt.savefig(self.directory_name+'/'+'polony.svg')
plt.savefig(self.directory_name + '/' + 'polony.png')
plt.close()
plt.figure(figsize=(10, 10), dpi=500)
plt.autoscale(enable=True, axis='both', tight=None)
plt.triplot(self.corseed[:,0],self.corseed[:,1],self.triangulated_delaunay.simplices.copy(),linestyle='solid',alpha=1,marker=None,color='#3498DB')
if self.nseed <= 500:
plt.plot(self.corseed[:,0],self.corseed[:,1],'o',color='#3498DB',markerfacecolor='w',markersize=12)
# plt.rcParams['figure.figsize'] = (20, 20)
if self.nseed <= 500:
for i in range(0, self.nseed):
plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=1, fontsize=6,horizontalalignment='center', verticalalignment='center')
plt.savefig(self.directory_name + '/' +'delaunay_polony.svg')
plt.savefig(self.directory_name + '/' + 'delaunay_polony.png')
plt.close()
plt.autoscale(enable=False, axis='both', tight=None)
elif optimal_linking == True and bipartite == False:
if full_output == True:
plt.close()
plt.figure(figsize=(10, 10), dpi=500)
# nseed = len(p1)
self.p2_proxm = np.zeros((self.nsites))
self.p2_secondary = np.zeros((self.nsites))
for i in range(0, self.nsites):
self.p2_dis = np.zeros((self.nseed))
for j in range(0, self.nseed):
# self.p2_dis[j] = (math.sqrt((self.site_coordinates[i, 0] - self.corseed[j, 0]) ** 2 + (self.site_coordinates[i, 1] - self.corseed[j, 1]) ** 2))
self.p2_dis[j] = np.linalg.norm(self.site_coordinates[i] - self.corseed[j])
self.p2_proxm[i] = np.argsort(self.p2_dis)[0] #get the membership in polony by taking the closest of distances to each seed
self.p2_secondary[i] = np.argsort(self.p2_dis)[1] #get the second closest
self.p2 = ["" for x in range(0, self.nsites)]
for i in range(0, self.nsites):
x = int(self.p2_proxm[i])
self.p2[i] = reverse(self.p1[x])
self.bc_index_pair = zip(self.p2_proxm, self.p2_secondary)
# ipdb.set_trace()
cmap = matplotlib.cm.get_cmap('Spectral')
vor_polony = Voronoi(self.corseed, qhull_options = "")
if full_output == True:
if self.nseed <= 500:
voronoi_plot_2d(vor_polony,show_vertices=False)
else:
voronoi_plot_2d(vor_polony, show_vertices=False,show_points = False, line_width = 0.1)
self.rgb_stamp_catalog = np.zeros((self.nseed,3))
if full_output == True:print 'begin gathering polony sizes'
self.polony_sizes = collections.Counter(self.p2_proxm) #p2_proxm stores which seed each site is closest to
# ipdb.set_trace()
if full_output == True:print 'end of gathering polony sizes'
for i in range(0, self.nseed):
c = random.random()
for j in range(0, self.nsites):
if self.p2_proxm[j] == i:
if full_output == True:
plt.scatter(self.site_coordinates[j, 0], self.site_coordinates[j, 1], color=cmap(c), s=1)
rgb, gray = get_pixel_rgb(self.scaled_imarray,self.lookup_x_axis,self.lookup_y_axis,self.site_coordinates[j,0],self.site_coordinates[j,1])
rgb = rgb / np.sum(rgb)
p_threshold = random.random()
if p_threshold < gray: #darker means closer to zero,
try:
colorID = np.random.choice([0,1,2],p=rgb)
self.rgb_stamp_catalog[i][colorID] += 1.
except:
self.rgb_stamp_catalog[i][0] += 1
self.rgb_stamp_catalog[i][1] += 1
self.rgb_stamp_catalog[i][2] += 1
self.rgb_stamp_catalog[i] = self.rgb_stamp_catalog[i]/float(self.polony_sizes[i])
# ipdb.set_trace()
if full_output == True:print 'end of stamp cataloging'
self.triangulated_delaunay = Delaunay(self.corseed, qhull_options="Qz Q2")
self.ideal_graph = get_ideal_graph(self.triangulated_delaunay)
ajc_polony = np.zeros((len(self.bc), len(self.bc)))
ajc_polony.astype(int)
for i in range(0, len(self.bc_index_pair)):
rrr = int(self.bc_index_pair[i][0])
ccc = int(self.bc_index_pair[i][1])
ajc_polony[rrr, ccc] = 1
ajc_polony[ccc, rrr] = 1
if full_output==True: np.savetxt(self.directory_name+'/'+ 'ajc_polony', ajc_polony, delimiter=",", fmt="%i")
self.untethered_graph = nx.Graph()
for i in range(0, ajc_polony.shape[0]):
self.untethered_graph.add_node(i)
for j in range(0, ajc_polony.shape[1]):
if ajc_polony[i][j] == 1:
self.untethered_graph.add_edge(i, j)
if full_output == True:
np.savetxt(self.directory_name + '/' + 'p2', self.p2, delimiter=",", fmt="%s")
np.savetxt(self.directory_name + '/' + 'polony_seed', self.p2_proxm, delimiter=",")
np.savetxt(self.directory_name + '/' + 'point_adjacent_polony', self.p2_secondary, delimiter=",")
np.savetxt(self.directory_name + '/' + 'bcindexpairlist', self.bc_index_pair, delimiter=',')
# plt.rcParams['figure.figsize'] = (20,20)
plt.xlim(-.1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.min(
self.site_coordinates[:, 0]),
.1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.max(
self.site_coordinates[:, 0]))
plt.ylim(-.1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.min(
self.site_coordinates[:, 1]),
.1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.max(
self.site_coordinates[:, 1]))
if self.nseed <= 500:
for i in range(0, self.nseed):
plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=0.5)
# plt.figure(figsize=(10, 10), dpi=500)
else:
plt.autoscale(enable=True, axis='both', tight=None)
plt.savefig(self.directory_name+'/'+'polony.svg')
plt.savefig(self.directory_name + '/' + 'polony.png')
plt.close()
plt.figure(figsize=(10, 10), dpi=500)
plt.autoscale(enable=True, axis='both', tight=None)
plt.triplot(self.corseed[:,0],self.corseed[:,1],self.triangulated_delaunay.simplices.copy(),linestyle='solid',alpha=1,marker=None,color='#3498DB')
if self.nseed <= 500:
plt.plot(self.corseed[:,0],self.corseed[:,1],'o',color='#3498DB',markerfacecolor='w',markersize=12)
# plt.rcParams['figure.figsize'] = (20, 20)
if self.nseed <= 500:
for i in range(0, self.nseed):
plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=1, fontsize=6,horizontalalignment='center', verticalalignment='center')
plt.savefig(self.directory_name + '/' +'delaunay_polony.svg')
plt.savefig(self.directory_name + '/' + 'delaunay_polony.png')
plt.close()
plt.autoscale(enable=False, axis='both', tight=None)
print 'end of crosslink polonies'
elif optimal_linking == True and bipartite == True:
if full_output == True:
plt.close()
plt.figure(figsize=(10, 10), dpi=500)
# nseed = len(p1)
self.p2_proxm = np.zeros((self.nsites))
self.p2_secondary = np.zeros((self.nsites))
for i in range(0, self.nsites):
self.p2_dis = np.zeros((self.nseed))
for j in range(0, self.nseed):
# self.p2_dis[j] = (math.sqrt((self.site_coordinates[i, 0] - self.corseed[j, 0]) ** 2 + (self.site_coordinates[i, 1] - self.corseed[j, 1]) ** 2))
self.p2_dis[j] = np.linalg.norm(self.site_coordinates[i] - self.corseed[j])
self.p2_proxm[i] = np.argsort(self.p2_dis)[0] #get the membership in polony by taking the closest of distances to each seed
self.p2_secondary[i] = np.argsort(self.p2_dis)[1] #get the second closest
self.p2 = ["" for x in range(0, self.nsites)]
for i in range(0, self.nsites):
x = int(self.p2_proxm[i])
self.p2[i] = reverse(self.p1[x])
self.bc_index_pair = zip(self.p2_proxm, self.p2_secondary)
# ipdb.set_trace()
cmap = matplotlib.cm.get_cmap('Spectral')
vor_polony = Voronoi(self.corseed, qhull_options = "")
if full_output == True:
if self.nseed <= 500:
voronoi_plot_2d(vor_polony,show_vertices=False)
else:
voronoi_plot_2d(vor_polony, show_vertices=False,show_points = False, line_width = 0.1)
self.rgb_stamp_catalog = np.zeros((self.nseed,3))
if full_output == True:print 'begin gathering polony sizes'
self.polony_sizes = collections.Counter(self.p2_proxm) #p2_proxm stores which seed each site is closest to
# ipdb.set_trace()
if full_output == True:print 'end of gathering polony sizes'
for i in range(0, self.nseed):
c = random.random()
for j in range(0, self.nsites):
if self.p2_proxm[j] == i:
if full_output == True:
plt.scatter(self.site_coordinates[j, 0], self.site_coordinates[j, 1], color=cmap(c), s=1)
rgb, gray = get_pixel_rgb(self.scaled_imarray,self.lookup_x_axis,self.lookup_y_axis,self.site_coordinates[j,0],self.site_coordinates[j,1])
rgb = rgb / np.sum(rgb)
p_threshold = random.random()
if p_threshold < gray: #darker means closer to zero,
try:
colorID = np.random.choice([0,1,2],p=rgb)
self.rgb_stamp_catalog[i][colorID] += 1.
except:
self.rgb_stamp_catalog[i][0] += 1
self.rgb_stamp_catalog[i][1] += 1
self.rgb_stamp_catalog[i][2] += 1
self.rgb_stamp_catalog[i] = self.rgb_stamp_catalog[i]/float(self.polony_sizes[i])
# ipdb.set_trace()
if full_output == True:print 'end of stamp cataloging'
self.triangulated_delaunay = Delaunay(self.corseed, qhull_options="Qz Q2")
self.ideal_graph = get_ideal_graph(self.triangulated_delaunay)
ajc_polony = np.zeros((len(self.bc), len(self.bc)))
ajc_polony.astype(int)
for i in range(0, len(self.bc_index_pair)):
rrr = int(self.bc_index_pair[i][0])
ccc = int(self.bc_index_pair[i][1])
ajc_polony[rrr, ccc] = 1
ajc_polony[ccc, rrr] = 1
if full_output==True: np.savetxt(self.directory_name+'/'+ 'ajc_polony', ajc_polony, delimiter=",", fmt="%i")
self.untethered_graph = nx.Graph()
for i in range(0, ajc_polony.shape[0]):
self.untethered_graph.add_node(i)
for j in range(0, ajc_polony.shape[1]):
if ajc_polony[i][j] == 1:
self.untethered_graph.add_edge(i, j)
if full_output == True:
np.savetxt(self.directory_name + '/' + 'p2', self.p2, delimiter=",", fmt="%s")
np.savetxt(self.directory_name + '/' + 'polony_seed', self.p2_proxm, delimiter=",")
np.savetxt(self.directory_name + '/' + 'point_adjacent_polony', self.p2_secondary, delimiter=",")
np.savetxt(self.directory_name + '/' + 'bcindexpairlist', self.bc_index_pair, delimiter=',')
# plt.rcParams['figure.figsize'] = (20,20)
plt.xlim(-.1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.min(
self.site_coordinates[:, 0]),
.1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.max(
self.site_coordinates[:, 0]))
plt.ylim(-.1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.min(
self.site_coordinates[:, 1]),
.1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.max(
self.site_coordinates[:, 1]))
if self.nseed <= 500:
for i in range(0, self.nseed):
plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=0.5)
# plt.figure(figsize=(10, 10), dpi=500)
else:
plt.autoscale(enable=True, axis='both', tight=None)
plt.savefig(self.directory_name+'/'+'polony.svg')
plt.savefig(self.directory_name + '/' + 'polony.png')
plt.close()
plt.figure(figsize=(10, 10), dpi=500)
plt.autoscale(enable=True, axis='both', tight=None)
plt.triplot(self.corseed[:,0],self.corseed[:,1],self.triangulated_delaunay.simplices.copy(),linestyle='solid',alpha=1,marker=None,color='#3498DB')
if self.nseed <= 500:
plt.plot(self.corseed[:,0],self.corseed[:,1],'o',color='#3498DB',markerfacecolor='w',markersize=12)
# plt.rcParams['figure.figsize'] = (20, 20)
if self.nseed <= 500:
for i in range(0, self.nseed):
plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=1, fontsize=6,horizontalalignment='center', verticalalignment='center')
plt.savefig(self.directory_name + '/' +'delaunay_polony.svg')
plt.savefig(self.directory_name + '/' + 'delaunay_polony.png')
plt.close()
plt.autoscale(enable=False, axis='both', tight=None)
print 'end of crosslink polonies'
print 'end of crosslink polonies'
# return p2, p2_secondary, p2_proxm, bc_index_pair, tri, rgb_stamp_catalog
def check_continuity(self):
if (planarity.is_planar(self.untethered_graph)) == True and nx.is_connected(self.untethered_graph) == True:
self.disconnected = False
else:
self.disconnected = True
# def crosslink_poloniesbackup(self, full_output=True):
# if full_output == True:
# plt.close()
# plt.figure(figsize=(10, 10), dpi=500)
#
# # nseed = len(p1)
# self.p2_proxm = np.zeros((self.nsites))
# self.p2_secondary = np.zeros((self.nsites))
# for i in range(0, self.nsites):
# self.p2_dis = np.zeros((self.nseed))
# for j in range(0, self.nseed):
# # self.p2_dis[j] = (math.sqrt((self.site_coordinates[i, 0] - self.corseed[j, 0]) ** 2 + (self.site_coordinates[i, 1] - self.corseed[j, 1]) ** 2))
# self.p2_dis[j] = np.linalg.norm(self.site_coordinates[i] - self.corseed[j])
# self.p2_proxm[i] = np.argsort(self.p2_dis)[0] #get the membership in polony by taking the closest of distances to each seed
# self.p2_secondary[i] = np.argsort(self.p2_dis)[1] #get the second closest
#
# self.p2 = ["" for x in range(0, self.nsites)]
# for i in range(0, self.nsites):
# x = int(self.p2_proxm[i])
# self.p2[i] = reverse(self.p1[x])
#
# self.bc_index_pair = zip(self.p2_proxm, self.p2_secondary)
#
# # ipdb.set_trace()
# cmap = matplotlib.cm.get_cmap('Spectral')
# vor_polony = Voronoi(self.corseed, qhull_options = "")
# if full_output == True:
# if self.nseed <= 500:
# voronoi_plot_2d(vor_polony,show_vertices=False)
# else:
# voronoi_plot_2d(vor_polony, show_vertices=False,show_points = False, line_width = 0.1)
# self.rgb_stamp_catalog = np.zeros((self.nseed,3))
# if full_output == True:print 'begin gathering polony sizes'
# self.polony_sizes = collections.Counter(self.p2_proxm) #p2_proxm stores which seed each site is closest to
# ipdb.set_trace()
# if full_output == True:print 'end of gathering polony sizes'
# for i in range(0, self.nseed):
# c = random.random()
# for j in range(0, self.nsites):
# if self.p2_proxm[j] == i:
# if full_output == True:
# plt.scatter(self.site_coordinates[j, 0], self.site_coordinates[j, 1], color=cmap(c), s=1)
# rgb, gray = get_pixel_rgb(self.scaled_imarray,self.lookup_x_axis,self.lookup_y_axis,self.site_coordinates[j,0],self.site_coordinates[j,1])
# rgb = rgb / np.sum(rgb)
# p_threshold = random.random()
# if p_threshold < gray: #darker means closer to zero,
# try:
# colorID = np.random.choice([0,1,2],p=rgb)
# self.rgb_stamp_catalog[i][colorID] += 1.
# except:
# self.rgb_stamp_catalog[i][0] += 1
# self.rgb_stamp_catalog[i][1] += 1
# self.rgb_stamp_catalog[i][2] += 1
# self.rgb_stamp_catalog[i] = self.rgb_stamp_catalog[i]/float(self.polony_sizes[i])
# # ipdb.set_trace()
# if full_output == True:print 'end of stamp cataloging'
# self.triangulated_delaunay = Delaunay(self.corseed, qhull_options="Qz Q2")
#
# self.ideal_graph = get_ideal_graph(self.triangulated_delaunay)
#
# ajc_polony = np.zeros((len(self.bc), len(self.bc)))
# ajc_polony.astype(int)
# for i in range(0, len(self.bc_index_pair)):
# rrr = int(self.bc_index_pair[i][0])
# ccc = int(self.bc_index_pair[i][1])
# ajc_polony[rrr, ccc] = 1
# ajc_polony[ccc, rrr] = 1
#
# if full_output==True: np.savetxt(self.directory_name+'/'+ 'ajc_polony', ajc_polony, delimiter=",", fmt="%i")
#
# self.untethered_graph = nx.Graph()
# for i in range(0, ajc_polony.shape[0]):
# self.untethered_graph.add_node(i)
# for j in range(0, ajc_polony.shape[1]):
# if ajc_polony[i][j] == 1:
# self.untethered_graph.add_edge(i, j)
#
#
# if full_output == True:
# np.savetxt(self.directory_name + '/' + 'p2', self.p2, delimiter=",", fmt="%s")
# np.savetxt(self.directory_name + '/' + 'polony_seed', self.p2_proxm, delimiter=",")
# np.savetxt(self.directory_name + '/' + 'point_adjacent_polony', self.p2_secondary, delimiter=",")
# np.savetxt(self.directory_name + '/' + 'bcindexpairlist', self.bc_index_pair, delimiter=',')
# # plt.rcParams['figure.figsize'] = (20,20)
# plt.xlim(-.1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.min(
# self.site_coordinates[:, 0]),
# .1 * (np.max(self.site_coordinates[:, 0]) - np.min(self.site_coordinates[:, 0])) + np.max(
# self.site_coordinates[:, 0]))
# plt.ylim(-.1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.min(
# self.site_coordinates[:, 1]),
# .1 * (np.max(self.site_coordinates[:, 1]) - np.min(self.site_coordinates[:, 1])) + np.max(
# self.site_coordinates[:, 1]))
# if self.nseed <= 500:
# for i in range(0, self.nseed):
# plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=0.5)
#
# # plt.figure(figsize=(10, 10), dpi=500)
# else:
# plt.autoscale(enable=True, axis='both', tight=None)
# plt.savefig(self.directory_name+'/'+'polony.svg')
# plt.savefig(self.directory_name + '/' + 'polony.png')
# plt.close()
# plt.figure(figsize=(10, 10), dpi=500)
# plt.autoscale(enable=True, axis='both', tight=None)
# plt.triplot(self.corseed[:,0],self.corseed[:,1],self.triangulated_delaunay.simplices.copy(),linestyle='solid',alpha=1,marker=None,color='#3498DB')
# if self.nseed <= 500:
# plt.plot(self.corseed[:,0],self.corseed[:,1],'o',color='#3498DB',markerfacecolor='w',markersize=12)
# # plt.rcParams['figure.figsize'] = (20, 20)
# if self.nseed <= 500:
# for i in range(0, self.nseed):
# plt.text(self.corseed[i, 0], self.corseed[i, 1], '%s' % i, alpha=1, fontsize=6,horizontalalignment='center', verticalalignment='center')
# plt.savefig(self.directory_name + '/' +'delaunay_polony.svg')
# plt.savefig(self.directory_name + '/' + 'delaunay_polony.png')
# plt.close()
# plt.autoscale(enable=False, axis='both', tight=None)
# print 'end of crosslink polonies'
class Reconstruction:
def __init__(self, directory_name, corseed, ideal_graph, untethered_graph, rgb_stamp_catalog):
self.directory_name = directory_name
self.corseed = corseed
self.nseed = len(corseed)
self.ideal_graph = ideal_graph
self.untethered_graph = untethered_graph
self.rgb_stamp_catalog = rgb_stamp_catalog
def conduct_pca_peripheral(self,full_output=False,image_only=False):
plt.close()
self.npolony = len(self.untethered_graph.nodes)
face_enumeration_t0 = time.time()
faces = self.fast_planar_embedding(self.untethered_graph, title='tutte', full_output=False)
self.face_enumeration_runtime = time.time() - face_enumeration_t0
self.max_face = []
for face in range(0, len(faces)):
if len(faces[face]) > len(self.max_face):
self.max_face = faces[face]
peripheral_nodes_list = np.fromiter(itertools.chain.from_iterable(self.max_face), dtype=int)
self.peripheral_nodes = set(peripheral_nodes_list)
# length_of_outer_face = len(self.peripheral_nodes)
# tridistance = int(length_of_outer_face/10)
# self.equidistant_three_nodes = [peripheral_nodes_list[0], peripheral_nodes_list[tridistance], peripheral_nodes_list[2*tridistance]]
self.distance_matrix = np.zeros((self.npolony,len(self.peripheral_nodes)), dtype=int)
# csr_graph = csr_matrix(nx.adjacency_matrix(self.untethered_graph))
# self.distance_matrix = np.array(floyd_warshall(csgraph=csr_graph, directed=False, return_predecessors=True))[0]
#
for node in self.untethered_graph.nodes:
peripheral_node_count = 0
for peripheral_node in self.peripheral_nodes:
# print node, peripheral_node
# distance_matrix[node,peripheral_node] = \
shortest_paths = [p for p in nx.algorithms.shortest_paths.generic.all_shortest_paths(self.untethered_graph,source=node,target=peripheral_node)]
self.distance_matrix[node,peripheral_node_count] = len(shortest_paths[0])
peripheral_node_count += 1
# ipdb.set_trace()
pca = PCA(n_components = 2)
principal_components = pca.fit_transform(self.distance_matrix)
self.reconstructed_pos = dict(zip(self.untethered_graph.nodes, tuple(principal_components)))
self.reconstructed_points = np.array(convert_dict_to_list(self.reconstructed_pos))
self.reconstructed_points = self.reconstructed_points / np.max(np.sqrt(self.reconstructed_points ** 2))
# ipdb.set_trace()
# self.reconstructed_pos = 1
# self.reconstructed_points = np.array(convert_dict_to_list(self.reconstructed_pos))
# self.rgb_stamp_catalog = (self.rgb_stamp_catalog)
# # maxima = np.max(self.rgb_stamp_catalog)
# # self.rgb_stamp_catalog = self.rgb_stamp_catalog / maxima
if full_output == True or image_only == True:
draw_embedding_diagram(self.untethered_graph, self.reconstructed_points, self.directory_name, nseed=self.nseed, graph_name='embedding_graph_topodist_peripheral')
draw_voronoi_image(self.reconstructed_points, self.rgb_stamp_catalog, self.directory_name, nseed = self.nseed, voronoi_name='voronoi_topodist_peripheral')
def conduct_shortest_path_matrix(self,full_output=False,image_only=False):
plt.close()
self.npolony = len(self.untethered_graph.nodes)
csr_graph = csr_matrix(nx.adjacency_matrix(self.untethered_graph))
self.distance_matrix = np.array(floyd_warshall(csgraph=csr_graph, directed=False, return_predecessors=True))[0]
maxdistance = np.max(self.distance_matrix)
# self.distance_matrix[self.distance_matrix < 0.45*maxdistance] = 0
pca = PCA(n_components = 2)
principal_components = pca.fit_transform(self.distance_matrix)
self.reconstructed_pos = dict(zip(self.untethered_graph.nodes, tuple(principal_components)))
self.reconstructed_points = np.array(principal_components)
self. reconstructed_points = self.reconstructed_points / np.max(np.sqrt(self.reconstructed_points ** 2))
# self.rgb_stamp_catalog = (self.rgb_stamp_catalog)
# maxima = np.max(self.rgb_stamp_catalog)
# self.rgb_stamp_catalog = self.rgb_stamp_catalog / maxima
if full_output == True or image_only == True:
draw_embedding_diagram(self.untethered_graph, self.reconstructed_points, self.directory_name, nseed=self.nseed,
graph_name='embedding_graph_topodist_total')
draw_voronoi_image(self.reconstructed_points, self.rgb_stamp_catalog, self.directory_name,nseed = self.nseed,
voronoi_name='voronoi_topodist_total')
def conduct_tutte_embedding_from_ideal(self,full_output=False,image_only=False):
plt.close()
#check for planarity
# metrics are removed however
if (planarity.is_planar(self.ideal_graph))==True and nx.is_connected(self.ideal_graph)==True:
if full_output == True:
ideal_faces = self.fast_planar_embedding(self.ideal_graph,title='ideal')
# plt.autoscale(enable=True, axis='both', tight=None)
# plt.savefig(self.directory_name + '/' + 'ideal_planar.png')
else:
ideal_faces = self.fast_planar_embedding(self.ideal_graph, title='ideal',full_output=False)
else:
print 'error, graph not fully connected, planarity test failed'
ipdb.set_trace()
self.ideal_max_face = []
for face in range(0, len(ideal_faces)):
if len(ideal_faces[face]) > len(self.ideal_max_face):
self.ideal_max_face = ideal_faces[face]
self.ideal_pos = tutte_embedding(self.ideal_graph, self.ideal_max_face)
self.reconstructed_points = np.array(convert_dict_to_list(self.ideal_pos))
if full_output == True:
# draw_embedding_diagram(self.untethered_graph, self.reconstructed_points, self.directory_name,nseed=self.nseed,
# graph_name='embedding_graph_tutte_ideal')
draw_voronoi_image(self.reconstructed_points, self.rgb_stamp_catalog, self.directory_name,nseed = self.nseed,
voronoi_name='voronoitutteideal')
def conduct_spring_embedding(self,full_output=True,image_only=False):
plt.close()
self.reconstructed_pos = nx.drawing.nx_agraph.pygraphviz_layout(self.untethered_graph, args='-Gepsilon=0.0000000001')
#nx.draw_networkx_edges(self.untethered_graph, self.reconstructed_pos, alpha=0.3)
#ipdb.set_trace()
self.reconstructed_points = np.array(convert_dict_to_list(self.reconstructed_pos))
normalizing_factor = np.max(np.sqrt(self.reconstructed_points ** 2))
self.reconstructed_points = self.reconstructed_points / normalizing_factor
# self.rgb_stamp_catalog = (self.rgb_stamp_catalog)
# maxima = np.max(self.rgb_stamp_catalog)
# self.rgb_stamp_catalog = self.rgb_stamp_catalog / maxima
# self.untethered_graph.add_edges_from(triangulation_fix(faces, self.reconstructed_pos))
if full_output == True or image_only == True:
draw_embedding_diagram(self.untethered_graph, self.reconstructed_points, self.directory_name,nseed=self.nseed,
graph_name='embedding_graph_spring')
draw_voronoi_image(self.reconstructed_points, self.rgb_stamp_catalog, self.directory_name,nseed = self.nseed,
voronoi_name='voronoi_spring')
def conduct_tutte_embedding(self,full_output=True,image_only=False):
plt.close()
# blind reconstruction here, if there are missed edges, then they will distort final reconstruction
face_enumeration_t0 = time.time()
# if (planarity.is_planar(self.untethered_graph)) == True and nx.is_connected(self.untethered_graph) == True:
# if full_output == True:
# faces = self.fast_planar_embedding(self.untethered_graph, title='tutte')
# else:
faces = self.fast_planar_embedding(self.untethered_graph, title='tutte', full_output=False)
# else:
# print 'error, graph not fully connected, planarity test failed'
# ipdb.set_trace()
self.face_enumeration_runtime = time.time() - face_enumeration_t0
self.max_face = []
for face in range(0, len(faces)):
if len(faces[face]) > len(self.max_face):
self.max_face = faces[face]
self.reconstructed_pos = tutte_embedding(self.untethered_graph, self.max_face) # need to update self.untethered_graph
self.reconstructed_points = np.array(convert_dict_to_list(self.reconstructed_pos))
###########
# if len(self.untethered_graph) != len(self.reconstructed_points):
# ipdb.set_trace()
# self.untethered_graph.add_edges_from(triangulation_fix(faces,reconstructed_pos))
# self.updated_reconstructed_pos = self.tutte_embedding(self.untethered_graph, self.max_face)
if full_output == True or image_only == True: