-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault.py
More file actions
executable file
·2538 lines (2334 loc) · 130 KB
/
default.py
File metadata and controls
executable file
·2538 lines (2334 loc) · 130 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig
import networkx as nx
import numpy as np
import scipy
exec('from applications.%s.modules import core as core'%request.application)
exec('from applications.%s.modules import community as community'%request.application)
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, cm
from reportlab.lib import colors, utils
from reportlab.lib.pagesizes import letter
import re
import time
import datetime
from gluon.storage import Storage
def user():
return dict(form=auth())
def study_networks():
if auth.user:
rows_allowed = db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)).select()
else:
rows_allowed = db((db.upload_data.share=='Public')).select()
study_names = list(set([row.study_name for row in rows_allowed]))
study_networks = ''
if request.vars.study_name or request.vars.study_name_1 or request.vars.study_name_2:
for row in rows_allowed:
if (row.study_name==request.vars.study_name) or (row.study_name==request.vars.study_name_1) or (row.study_name==request.vars.study_name_2):
study_networks = study_networks + '<option value="%s">%s</option>' %(row.network_name, row.network_name)
return study_networks
def webgl_html():
network = db(db.upload_data.network_name==request.vars.network_name).select().first()
matfilename = network.connectivity_matrix_file
matfilepath = os.path.join(request.folder,'uploads',matfilename)
centersfilepath = os.path.join(request.folder,'uploads',network.region_xyz_centers_file)
#molfile_str = plot_matrix_sim_molfile(matfilepath, centersfilepath, int(request.vars.chosen_density))
weight = request.vars.weight
weight_edges = (weight!='Binary')
if weight == 'Binary':
binarize=True
else:
binarize=False
chosen_density = int(request.vars.chosen_density)
node_metric = request.vars.node_metric
webgl_url, node_text, edge_text = plot_matrix_webgl(matfilepath,centersfilepath, network, weight=weight, chosen_density=chosen_density, node_metric=node_metric)
return dict(webgl_url=webgl_url, node_text=node_text, edge_text=edge_text)
def plot_matrix_webgl(connectmat_file,centers_file,network, chosen_density, node_metric='deg',
weight='Binary',node_scale_factor=.25, edge_radius=.05, names_file=None):
#def plot_matrix_webgl(weight='Binary',
# weight_edges=0, node_scale_factor=.25, edge_radius=.05, names_file=None):
"""Given a connectivity matrix and a (x,y,z) centers file for each region,
generate a chemdoodle webgl 3d javascript"""
#######
#network = db(db.upload_data.network_name==request.vars.network_name).select().first()
#matfilename = network.connectivity_matrix_file
#matfilepath = os.path.join(request.folder,'uploads',matfilename)
#centersfilepath = os.path.join(request.folder,'uploads',network.region_xyz_centers_file)
##molfile_str = plot_matrix_sim_molfile(matfilepath, centersfilepath, int(request.vars.chosen_density))
#weight = request.vars.weight
weight_edges = (weight!='Binary')
if weight == 'Binary':
binarize=True
else:
binarize=False
#connectmat_file = matfilepath
#centers_file = centersfilepath
#if int(request.vars.chosen_density) > 20:
if chosen_density > 20:
threshold_pct = 20
else:
#threshold_pct = int(request.vars.chosen_density)
threshold_pct = int(chosen_density)
########
matrix = core.file_reader(connectmat_file)
matrix_array = np.array(matrix)
nodes = core.file_reader(centers_file)
#metric = request.vars.node_metric
webgl_filename = os.path.join(network.network_name \
+ '_' + weight + '_' + str(threshold_pct) \
+ '_' + node_metric + '_' + 'webgl' + '.js')
webgl_filepath = os.path.join(request.folder, 'static', webgl_filename)
#if os.path.exists(webgl_filepath):
# print '1'
# webgl_url = URL(request.application, 'static', webgl_filename)
# return webgl_url
node_text = ''
if node_metric:
if node_metric == 'deg':
metric_num = 1
node_color = "orange"
node_text = 'Node radius is currently based on the node\'s <font color="orange">degree</b></font>.'
if node_metric == 'bc':
metric_num = 2
node_color = "chartreuse"
node_text = 'Node radius is currently based on the node\'s <font color="#7fff00">betweenness centrality</b></font>.'
if node_metric == 'cc':
metric_num = 3
node_color = "aqua"
node_text = 'Node radius is currently based on the node\'s <font color="#00ffff"><b>clustering coefficient</b></font>.'
if node_metric == 'mod':
metric_num = 4
node_text = 'Node color is currently based on the node\'s <b>module membership</b>.'
else:
metric_num = 0
f = open(webgl_filepath, 'w')
f.write("var transform3d = new ChemDoodle.TransformCanvas3D('transformBallAndStick', 500, 500);\n")
f.write("transform3d.specs.set3DRepresentation('Ball and Stick');\n")
f.write("transform3d.specs.backgroundColor = 'white';\n")
f.write("ChemDoodle.ELEMENT['C'].jmolColor = '#99FF00';\n")
f.write("var molecule = new ChemDoodle.structures.Molecule()\n")
if names_file:
names = core.file_reader(names_file,1)
num_nodes = len(nodes)
edge_thresh_pct = threshold_pct / 100.0
edge_text = 'Displaying the top <b>%s%%</b> strongest connections' %threshold_pct
matrix_flat=np.array(matrix).flatten()
matrix_flat[np.isinf(matrix_flat)] = 0
matrix_flat[np.isnan(matrix_flat)] = 0
edge_thresh=np.sort(matrix_flat)[len(matrix_flat)-int(len(matrix_flat)*edge_thresh_pct)]
num_edges = len(matrix_array[np.nonzero(matrix_array > edge_thresh)])/2
cutoff = 800
if num_edges > cutoff:
edge_thresh = np.sort(matrix_flat)[len(matrix_flat) - cutoff]
num_edges = cutoff
edge_thresh_pct_cap = int(((num_edges*2)/float(len(matrix_flat)))*100)
edge_text = 'Displaying the top <b>%s%%</b> strongest connections (capped to enable rendering).' %edge_thresh_pct_cap
# maximum spanning tree
inv_mat = np.matrix(matrix)
inv_mat[np.nonzero(inv_mat)] = np.max(inv_mat)+.01-inv_mat[np.nonzero(inv_mat)]
Ginv = nx.from_numpy_matrix(inv_mat)
mst = nx.minimum_spanning_edges(Ginv)
edgelist = list(mst)
edgelist_ids = [(x[0],x[1]) for x in edgelist]
show_mst = False
#####
edge_min = min(matrix_flat)
edge_max = max(matrix_flat)
edge_range = edge_max - edge_min
nodes_min = min(np.array(nodes).flatten())
nodes = nodes + (-nodes_min)
nodes_max = max(nodes.flatten())
nm10 = nodes_max / 100
nodes = nodes / (nm10 + .01)
edge_scale_factor = .09 # .19
node_scale_factor = .17 # defaults are .35
metrics = session.metrics
if metric_num:
#if metrics[0] == ['Region Name', 'Degree', 'Clustering Coefficient', 'Betweenness Centrality', 'Module']:
# metrics = metrics[1:]
metric_all = [x[metric_num] for x in metrics]
metric_max = max(metric_all)
# scale node radius to between .1 and .25
metric_all_scaled = [(((x/float(metric_max))*node_scale_factor)+.05) for x in metric_all]
for count,(x,y,z) in enumerate(nodes):
# nodes are named c0, c1, c2, c3...
if metric_num:
if node_metric == 'mod':
f.write("var c%s = new ChemDoodle.structures.Atom('C',%s,%s,%s,%s,'%s');\n" %(str(count), x/10, y/10, z/10, node_scale_factor, session.module_colors[count]))
else:
f.write("var c%s = new ChemDoodle.structures.Atom('C',%s,%s,%s,%s,'%s');\n" %(str(count), x/10, y/10, z/10, metric_all_scaled[count], node_color))
else:
f.write("var c%s = new ChemDoodle.structures.Atom('C',%s,%s,%s,%s);\n" %(str(count), x/10, y/10, z/10, node_scale_factor))
f.write("molecule.atoms[%s]=c%s;\n" %(count, str(count)))
if names_file:
pass
count = 0
for i in range(num_nodes-1):
x0,y0,z0=nodes[i]
for j in range(i+1, num_nodes):
if show_mst:
if (i,j) in edgelist_ids:
x1,y1,z1=nodes[j]
if weight_edges:
node_weight = ((matrix[i][j] / edge_max) * edge_scale_factor) + .01
f.write("var b%s = new ChemDoodle.structures.Bond(c%s, c%s,1, %s);\n" %(str(count), str(i), str(j), node_weight))
else:
f.write("var b%s = new ChemDoodle.structures.Bond(c%s, c%s,1, %s);\n" %(str(count), str(i), str(j), edge_radius))
f.write("molecule.bonds[%s]=b%s;\n" %(count, str(count)))
count += 1
else:
if matrix[i][j] > edge_thresh:
x1,y1,z1=nodes[j]
if weight_edges:
node_weight = ((matrix[i][j] / edge_max) * edge_scale_factor) + .01
f.write("var b%s = new ChemDoodle.structures.Bond(c%s, c%s,1, %s);\n" %(str(count), str(i), str(j), node_weight))
else:
f.write("var b%s = new ChemDoodle.structures.Bond(c%s, c%s,1, %s);\n" %(str(count), str(i), str(j), edge_radius))
f.write("molecule.bonds[%s]=b%s;\n" %(count, str(count)))
count += 1
f.write("transform3d.loadMolecule(molecule);\n")
f.close()
webgl_url = URL(request.application, 'static', webgl_filename)
#webgl_html = "<script type='text/javascript' src='%s'></script>" %(webgl_url)
return webgl_url, node_text, edge_text
def trunc(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
return ('%.*f' % (n + 1, f))[:-1]
#def index():
# if auth.user:
# rows_allowed = db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)).select()
# study_names = list(set([row.study_name for row in rows_allowed]))
# if request.vars.study_name:
# study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
# elif request.vars.study_name_cur:
# study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name_cur]
# else:
# study_networks = ''
# form = SQLFORM.factory(
# Field('study_name', requires=IS_IN_SET(study_names),
# default = (lambda x: x if x else '')(request.vars.study_name_cur)),
# Field('network_name',
# requires=IS_IN_SET(study_networks),
# #db.upload_data,
# #requires=IS_IN_DB(db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)),
# # 'upload_data.id',
# # '%(network_name)s'),
# default = (lambda x: x if x else '')(request.vars.network_name_cur)),
# Field('weight',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
# Field('edge_density',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
# Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
# labels = {'weight':'Weighting scheme:',
# 'edge_density':'% of edges to include:'},
# submit_button='Analyze',
# keepopts=['network_name', 'weight', 'edge_density'])
# else:
# rows_allowed = db((db.upload_data.share=='Public')).select()
# study_names = list(set([row.study_name for row in rows_allowed]))
# if request.vars.study_name:
# study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
# elif request.vars.study_name_cur:
# study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name_cur]
# else:
# study_networks = ''
# form = SQLFORM.factory(
# Field('study_name', requires=IS_IN_SET(study_names),
# default = (lambda x: x if x else '')(request.vars.study_name_cur)),
# Field('network_name',
# db.upload_data,
# requires=IS_IN_SET(study_networks),
# #requires=IS_IN_DB(db(db.upload_data.share=='Public'),
# # 'upload_data.id',
# # '%(network_name)s'),
# default = (lambda x: x if x else '')(request.vars.network_name_cur)),
# Field('weight',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
# Field('edge_density',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
# Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
# labels = {'weight':'Weighting scheme:',
# 'edge_density':'% of edges to include:'},
# submit_button='Analyze',
# keepopts=['network_name', 'weight', 'edge_density'])
# form[0][0].insert(-1,"Choose from the list of available studies")
# form[0][1].insert(-1,"Choose from the list of shared networks for the chosen study")
# form[0][2].insert(-1,"Choose a weighting scheme for the network, either weighted or binarized edges")
# form[0][3].insert(-1,"Choose the percent of connections to keep (0-100%)")
# form[0][4].insert(-1,"Choose the orientation from which to view the network")
# if form.accepts(request.vars, session):
# cache.ram.clear()
# redirect(URL(r=request,f='single_view',vars=form.vars))
# return dict(form=form)
def index():
'''
Browse all data either 1) publicly shared or 2) shared by the user who is logged in
Uses web2py plugin powertables
'''
if auth.user:
class Virtual(object):
@virtualsettings(label=T('View/Download:'))
def details_page(self):
return A("View/Download", _href=URL("update", args=[self.upload_data.id]))
@virtualsettings(label=T('View/Download:'))
#def analyze(self):
# return A("Analyze", _href=URL("index", vars={'study_name_cur':self.upload_data.study_name, 'network_name_cur':self.upload_data.network_name}))
def analyze(self):
return A("Analyze", _href=URL("analyze", vars={'study_name_cur':self.upload_data.study_name, 'network_name_cur':self.upload_data.network_name}))
@virtualsettings(label=T('Information:'))
def virtualtooltip(self):
return T('Study: %s | Network: %s | Modality: %s' % (self.upload_data.study_name, self.upload_data.network_name, self.upload_data.imaging_modality))
@virtualsettings(label=T('Shared by'))
def shared_by(self):
email = self.upload_data.email
email_safe = email_make_safe(email)
return email_safe
powerTable = plugins.powerTable
powerTable.datasource = data = db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)).select()
powerTable.virtualfields = Virtual()
powerTable.headers = 'fieldname:capitalize'
powerTable.dtfeatures['bJQueryUI'] = True
powerTable.uitheme = 'cupertino'
powerTable.extrajs = dict(tooltip={'value':'vitualtooltip'})
powerTable.dtfeatures['sScrollX'] = '100%'
powerTable.dtfeatures['sScrollY'] = '100%'
powerTable.dtfeatures['sPaginationType'] = request.vars.get('pager','full_numbers')
powerTable.showkeycolumn = False
powerTable.keycolumn = 'upload_data.id'
powerTable.dtfeatures['iDisplayLength'] = 25
powerTable.columns = ['virtual.details_page','virtual.analyze','upload_data.study_name','upload_data.network_name',
'upload_data.atlas','upload_data.imaging_modality','upload_data.share',
'upload_data.scanner_device','upload_data.age_range_min',
'upload_data.age_range_max','upload_data.gender','upload_data.subject_pool',
'upload_data.group_size','virtual.shared_by']
else:
class Virtual(object):
@virtualsettings(label=T('View/Download:'))
def details_page(self):
return A("View/Download", _href=URL("update", args=[self.upload_data.id]))
@virtualsettings(label=T('View/Download:'))
def analyze(self):
return A("Analyze", _href=URL("index", vars={'study_name_cur':self.upload_data.study_name, 'network_name_cur':self.upload_data.network_name}))
@virtualsettings(label=T('Information:'))
def virtualtooltip(self):
return T('Study: %s | Network: %s | Modality: %s' % (self.upload_data.study_name, self.upload_data.network_name, self.upload_data.imaging_modality))
@virtualsettings(label=T('Shared by'))
def shared_by(self):
email = self.upload_data.email
email_safe = email_make_safe(email)
return email_safe
powerTable = plugins.powerTable
powerTable.datasource = db((db.upload_data.share=='Public')).select()
powerTable.virtualfields = Virtual()
powerTable.headers = 'fieldname:capitalize'
powerTable.dtfeatures['bJQueryUI'] = True
powerTable.uitheme = 'cupertino'
powerTable.extrajs = dict(tooltip={'value':'vitualtooltip'})
powerTable.dtfeatures['sScrollX'] = '100%'
powerTable.dtfeatures['sScrollY'] = '100%'
powerTable.dtfeatures['sPaginationType'] = request.vars.get('pager','full_numbers')
powerTable.showkeycolumn = False
powerTable.keycolumn = 'upload_data.id'
powerTable.dtfeatures['iDisplayLength'] = 25
powerTable.columns = ['virtual.details_page','virtual.analyze','upload_data.study_name','upload_data.network_name',
'upload_data.atlas','upload_data.imaging_modality','upload_data.share',
'upload_data.scanner_device','upload_data.age_range_min',
'upload_data.age_range_max','upload_data.gender','upload_data.subject_pool',
'upload_data.group_size','virtual.shared_by']
return dict(table=powerTable.create())
def analyze():
if auth.user:
rows_allowed = db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)).select()
study_names = list(set([row.study_name for row in rows_allowed]))
if request.vars.study_name:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
elif request.vars.study_name_cur:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name_cur]
else:
study_networks = ''
form = SQLFORM.factory(
Field('study_name', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_name',
requires=IS_IN_SET(study_networks),
#db.upload_data,
#requires=IS_IN_DB(db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)),
# 'upload_data.id',
# '%(network_name)s'),
default = (lambda x: x if x else '')(request.vars.network_name_cur)),
Field('weight',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('edge_density',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
labels = {'weight':'Weighting scheme:',
'edge_density':'% of edges to include:'},
submit_button='Analyze',
keepopts=['network_name', 'weight', 'edge_density'])
else:
rows_allowed = db((db.upload_data.share=='Public')).select()
study_names = list(set([row.study_name for row in rows_allowed]))
if request.vars.study_name:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
elif request.vars.study_name_cur:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name_cur]
else:
study_networks = ''
form = SQLFORM.factory(
Field('study_name', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_name',
db.upload_data,
requires=IS_IN_SET(study_networks),
#requires=IS_IN_DB(db(db.upload_data.share=='Public'),
# 'upload_data.id',
# '%(network_name)s'),
default = (lambda x: x if x else '')(request.vars.network_name_cur)),
Field('weight',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('edge_density',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
labels = {'weight':'Weighting scheme:',
'edge_density':'% of edges to include:'},
submit_button='Analyze',
keepopts=['network_name', 'weight', 'edge_density'])
form[0][0].insert(-1,"Choose from the list of available studies")
form[0][1].insert(-1,"Choose from the list of shared networks for the chosen study")
form[0][2].insert(-1,"Choose a weighting scheme for the network, either weighted or binarized edges")
form[0][3].insert(-1,"Choose the percent of connections to keep (0-100%)")
form[0][4].insert(-1,"Choose the orientation from which to view the network")
if form.accepts(request.vars, session):
cache.ram.clear()
redirect(URL(r=request,f='single_view',vars=form.vars))
return dict(form=form)
def lesion():
if auth.user:
rows_allowed = db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)).select()
study_names = list(set([row.study_name for row in rows_allowed]))
if request.vars.study_name:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
elif request.vars.study_name_cur:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name_cur]
else:
study_networks = ''
form = SQLFORM.factory(
Field('study_name', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_name',
db.upload_data,
requires=IS_IN_SET(study_networks),
default = (lambda x: x if x else '')(request.vars.network_name_cur)),
Field('weight',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('edge_density',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
labels = {'weight':'Weighting scheme:',
'edge_density':'% of edges to include:'},
submit_button='Get Regions',
keepopts=['study_name', 'network_name', 'weight', 'edge_density', 'orientation'])
else:
rows_allowed = db((db.upload_data.share=='Public')).select()
study_names = list(set([row.study_name for row in rows_allowed]))
if request.vars.study_name:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
elif request.vars.study_name_cur:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name_cur]
else:
study_networks = ''
form = SQLFORM.factory(
Field('study_name', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_name',
db.upload_data,
requires=IS_IN_SET(study_networks),
default = (lambda x: x if x else '')(request.vars.network_name_cur)),
Field('weight',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('edge_density',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
labels = {'weight':'Weighting scheme:',
'edge_density':'% of edges to include:'},
submit_button='Get Regions',
keepopts=['study_name', 'network_name', 'weight', 'edge_density', 'orientation'])
form[0][0].insert(-1,"Choose from the list of available studies")
form[0][1].insert(-1,"Choose from the list of shared networks")
form[0][2].insert(-1,"Choose a weighting scheme for the network, either weighted or binarized edges")
form[0][3].insert(-1,"Choose the percent of connections to keep (0-100%)")
form[0][4].insert(-1,"Choose the orientation from which to view the network")
#form = SQLFORM.factory(
# Field('network_name',db.upload_data,requires=IS_IN_DB(db,'upload_data.id','%(network_name)s')),
# Field('weight',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Weighted'),
# Field('edge_density',default=100,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
# Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
# submit_button='Get Regions')
#form[0][0].insert(-1,"Choose from the list of shared networks")
#form[0][1].insert(-1,"Choose a weighting scheme for the network, either weighted or binarized edges")
#form[0][2].insert(-1,"Choose the percent of connections to keep (0-100%)")
fullnames_filepath = None
form2 = FORM()
if form.accepts(request.vars, session, keepvalues=True):
session.lesion = {}
session.lesion['network_1_name'] = request.vars.network_name
session.lesion['network_2_name'] = request.vars.network_name
session.lesion['weight_1'] = request.vars.weight
session.lesion['weight_2'] = request.vars.weight
session.lesion['edge_density_1'] = request.vars.edge_density
session.lesion['edge_density_2'] = request.vars.edge_density
session.lesion['orientation'] = request.vars.orientation
network = db(db.upload_data.network_name==request.vars.network_name).select().first()
fullnames_filepath = os.path.join(request.folder,'uploads',network.region_names_full_file)
session.fullnames = file_reader(fullnames_filepath,1)
components = [LI(INPUT(_type="checkbox", _name=region), region) for region in session.fullnames]
components.append(INPUT(_type='jackrabbit slims', _value='Go')) #, _action=URL(r=request,f='compare_view',vars=vars)))
form2 = FORM(*components)
if form2.accepts(request.vars, session):
lesion_regions = [y for y in request.vars.keys() if request.vars[y]=='on']
session.lesion['region_nums'] = [session.fullnames.index(x) for x in lesion_regions] # region numbers
cache.ram.clear()
redirect(URL(f='compare_view', args='lesion', vars=session.lesion))
#
# components = [(INPUT(_type="checkbox", _name=region), region) for region in fullnames]
#
# form2 = FORM(*components) #,INPUT(_type='submit', _value='Go')) # _onclick=URL(r=request,f='compare_view',vars=vars)))
# # *[LI(INPUT(_type="checkbox", _name=region), region) for region in fullnames]
#
# for fullname in fullnames:
# if fullname in request.vars:
# lesion_regions.append(fullname)
#return dict(form=form, fullnames=fullnames, vars=vars)
return dict(form=form, form2=form2, fullnames_filepath=fullnames_filepath)
def regionnames():
network = db(db.upload_data.id==request.vars.network_name).select().first()
fullnames_filepath = os.path.join(request.folder,'uploads',network.region_names_full_file)
fullnames = file_reader(fullnames_filepath,1)
return fullnames
@cache(request.env.path_info, time_expire=300, cache_model=cache.ram)
def single_view():
matrix_abs = False # Take absolute value of connectivity matrix
matrix_minshift = True # Shift matrix values so negative weights become weakest positive weights
network = db(db.upload_data.network_name==request.vars.network_name).select().first()
session.network = network
matfilename = network.connectivity_matrix_file
matfilepath = os.path.join(request.folder,'uploads',matfilename)
matfilepaths = []
matfilepaths.append(matfilepath)
centersfilepaths = []
centersfilepaths.append(os.path.join(request.folder,'uploads',network.region_xyz_centers_file))
namesfilepaths = []
namesfilepaths.append(os.path.join(request.folder,'uploads',network.region_names_full_file))
fullnames = []
abbrevfilepath = []
abbrevfilepath.append(os.path.join(request.folder,'uploads',network.region_names_abbrev_file))
weight = []
weight.append(request.vars.weight)
edge_density = []
edge_density.append(request.vars.edge_density)
names = []
names.append(file_reader(abbrevfilepath[0],1))
graph = []
cmat = []
centers = []
names_dict = []
num_regions = []
orientation = request.vars.orientation
fullnames_file = namesfilepaths[0]
fullnames.append(file_reader(fullnames_file,1))
threshold_pct = int(edge_density[0])
if weight[0] == 'Binary':
binarize = 1
else:
binarize = 0
edge_interval_pct = 10
connectmat_file = matfilepaths[0]
centers_file = centersfilepaths[0]
names_file = abbrevfilepath[0]
cmat_pre = file_reader(connectmat_file)
cur_cmat = np.array(cmat_pre)
cur_cmat[np.isinf(cur_cmat)] = 0
cur_cmat[np.isnan(cur_cmat)] = 0
raw_cmat = cur_cmat
num_regions.append(len(cur_cmat))
raw_density = (len(np.nonzero(cur_cmat)[0])/float(cur_cmat.shape[0]*(cur_cmat.shape[1]-1)))*100
chosen_density = threshold_pct
# transformation of weights
if matrix_abs:
cur_cmat = abs(raw_cmat)
if matrix_minshift:
min = np.amin(cur_cmat)
if min >= 0:
pass
else:
cur_cmat = cur_cmat - min
if threshold_pct:
#thresh = scipy.stats.scoreatpercentile(cur_cmat.ravel(),100-threshold_pct)
thresh = my_scoreatpercentile(cur_cmat, threshold_pct)
cmat_thresh = cur_cmat*(cur_cmat > thresh)
else:
cmat_thresh = cur_cmat
raw_cmat_thresh = raw_cmat * (cmat_thresh > 0)
edge_attributes = Storage({}) # web2py Storage class extends a dictionary
# find mean and stddev of edge weight for all edges in raw matrix, before any potential weight transformation
# assumes symmetric matrix, only looks at upper triangle
edge_attributes['cur_cmat_nz_mean'] = raw_cmat[np.nonzero(raw_cmat)].mean()
edge_attributes['cur_cmat_nz_std'] = raw_cmat[np.nonzero(raw_cmat)].std()
# find mean and stddev of edge weight for edges above threshold
edge_attributes['cmat_thresh_nz_mean'] = raw_cmat_thresh[np.nonzero(raw_cmat_thresh)].mean()
edge_attributes['cmat_thresh_nz_std'] = raw_cmat_thresh[np.nonzero(raw_cmat_thresh)].std()
if binarize:
cmat_thresh = 1*(cmat_thresh != 0)
cmat.append(cmat_thresh)
G = nx.from_numpy_matrix(cmat_thresh)
graph.append(G)
if names_file:
cur_names = file_reader(names_file,1)
cur_names_dict={}
for i in range(len(cur_names)):
cur_names_dict[i] = cur_names[i]
names_dict.append(cur_names_dict)
cur_centers = core.file_reader(centers_file)
centersa = np.array(cur_centers)
# find mean and stddev of euclidean distance for edges above threshold
eucdistmat = core.euclidean_distance(centersa)
cmat_raw_mask = (cur_cmat > 0) * 1
cmat_thresh_mask = (cmat_thresh > 0) * 1
eucdistmat_masked_raw = eucdistmat * cmat_raw_mask
eucdistmat_masked_thresh = eucdistmat * cmat_thresh_mask
edge_attributes['eucdist_mean'] = eucdistmat_masked_thresh[np.nonzero(eucdistmat_masked_thresh)].mean()
edge_attributes['eucdist_std'] = eucdistmat_masked_thresh[np.nonzero(eucdistmat_masked_thresh)].std()
# find mean and stddev of euclidean distance for all edges in raw matrix
edge_attributes['eucdist_unthresh_mean'] = eucdistmat_masked_raw[np.nonzero(np.triu(eucdistmat_masked_raw, 1))].mean()
edge_attributes['eucdist_unthresh_std'] = eucdistmat_masked_raw[np.nonzero(np.triu(eucdistmat_masked_raw, 1))].std()
if orientation == 'Sagittal':
centersxy = centersa[:,1:]
elif orientation == 'Coronal':
centersxy = np.column_stack((centersa[:,0],centersa[:,2]))
else:
centersxy = centersa[:,0:2]
centers.append(centersxy)
node_metrics={}
if binarize:
bc = nx.betweenness_centrality(G)
cc = nx.clustering(G)
ccs = []
cur_ccs = np.array([cc[x] for x in cc])
ccs.append(cur_ccs)
mcc = np.mean(cur_ccs)
try:
cpl = nx.average_shortest_path_length(G)
except nx.NetworkXError as e:
cpl = 'Inf'
sigma,lambda_cc,gamma_cpl = core.nx_small_worldness(G, True, 5000, 1, mcc, cpl)
e_glob, cur_e_regs = core.global_efficiency(G, regional=True, weight=False)
cur_e_regs = np.array(cur_e_regs)
#cur_e_locs = core.local_efficiency(G, weight=False)
cur_part_coefs = core.participation_coefficient(G)
else:
inv_cmat_thresh = 1./cmat_thresh
inv_cmat_thresh[np.isinf(inv_cmat_thresh)] = 0
G_inv = nx.from_numpy_matrix(inv_cmat_thresh)
bc = nx.betweenness_centrality(G_inv, weight='weight')
cc = nx.clustering(G_inv, weight='weight')
ccs = []
cur_ccs = np.array([cc[x] for x in cc])
ccs.append(cur_ccs)
mcc = np.mean(cur_ccs)
try:
cpl = nx.average_shortest_path_length(G_inv, weight='weight')
except nx.NetworkXError as e:
cpl = 'Inf'
sigma,lambda_cc,gamma_cpl = core.nx_small_worldness(G, False, 5000, 1, mcc, cpl)
e_glob, cur_e_regs = core.global_efficiency(G_inv, regional=True, weight=True)
cur_e_regs = np.array(cur_e_regs)
#cur_e_locs = core.local_efficiency(G_inv, weight=True)
cur_part_coefs = core.participation_coefficient(G, weighted_edges=True)
cur_part_coefs[np.isnan(cur_part_coefs)] = 0
e_regs = []
e_regs.append(cur_e_regs)
#e_locs = []
#e_locs.append(cur_e_locs)
cur_bcs = np.array([bc[x] for x in bc])
bcs = []
bcs.append(cur_bcs)
deg = nx.degree(G)
cur_degs = np.array([deg[x] for x in deg])
degs = []
degs.append(cur_degs)
num_comp = nx.number_connected_components(G)
partition = community.best_partition(G)
partition_list = []
partitions = []
for count in range(len(partition)):
partition_list.append(partition[count]) # partition is a dictionary
partitions.append(partition_list)
q = community.modularity(partition, G)
part_coefs = []
part_coefs.append(cur_part_coefs)
# Generate images
#cmatimage = URL(r=request,f='image_mat',args=[0])
cmat_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'cmat' + '.png')
degreedist_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'degreedist' + '.png')
net1_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + orientation + '_' + 'net1' + '.png')
bar1_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'bar1' + '.png')
net2_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + orientation + '_' + 'net2' + '.png')
bar2_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'bar2' + '.png')
net3_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + orientation + '_' + 'net3' + '.png')
bar3_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'bar3' + '.png')
ereg_network_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + orientation + '_' + 'ereg_network' + '.png')
ereg_hist_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'ereg_hist' + '.png')
partcoef_network_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + orientation + '_' + 'partcoef_network' + '.png')
partcoef_hist_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'partcoef_hist' + '.png')
module_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'module' + '.png')
spring_filepath = os.path.join(request.folder,'static', network.network_name \
+ '_' + weight[0] + '_' + str(chosen_density) \
+ '_' + 'spring' + '.png')
filepaths = [cmat_filepath, degreedist_filepath, net1_filepath, bar1_filepath,
net2_filepath, bar2_filepath, net3_filepath, bar3_filepath,
ereg_network_filepath, ereg_hist_filepath, partcoef_network_filepath, partcoef_hist_filepath,
module_filepath, spring_filepath]
# Make image files if they do not yet exist
if not all([os.path.exists(file) for file in filepaths]):
cmatimage = image_mat(0, cmat_filepath, cmat).split('/')[-1]
degreedistimage = degree_dist(0, degreedist_filepath, graph).split('/')[-1]
netimage1 = plot_matrix_2d(0, 's', net1_filepath, edge_density, weight, \
abbrevfilepath, names_dict, graph, centers, \
cmat, degs).split('/')[-1]
barimage1 = plot_bars(0, bar1_filepath, num_regions, degs, names).split('/')[-1]
netimage2 = plot_matrix_2d(0, 'bc', net2_filepath, edge_density, weight, \
abbrevfilepath, names_dict, graph, centers, \
cmat, bcs).split('/')[-1]
barimage2 = plot_bars(0, bar2_filepath, num_regions, bcs, names).split('/')[-1]
netimage3 = plot_matrix_2d(0, 'cc', net3_filepath, edge_density, weight, \
abbrevfilepath, names_dict, graph, centers, \
cmat, ccs).split('/')[-1]
barimage3 = plot_bars(0, bar3_filepath, num_regions, ccs, names).split('/')[-1]
ereg_hist = plot_bars(0, ereg_hist_filepath, num_regions, e_regs, names).split('/')[-1]
ereg_network = plot_matrix_2d(0, 'ereg', ereg_network_filepath, edge_density, weight, \
abbrevfilepath, names_dict, graph, centers, \
cmat, e_regs).split('/')[-1]
partcoef_hist = plot_bars(0, partcoef_hist_filepath, num_regions, part_coefs, names).split('/')[-1]
partcoef_network = plot_matrix_2d(0, 'part_coef', partcoef_network_filepath, edge_density, weight, \
abbrevfilepath, names_dict, graph, centers, \
cmat, part_coefs).split('/')[-1]
moduleimage = plot_modules(0, 0, module_filepath, matfilepaths, weight, names_dict, centers, graph, cmat).split('/')[-1]
springimage = plot_modules(0, 1, spring_filepath, matfilepaths, weight, names_dict, centers, graph, cmat).split('/')[-1]
else:
cmatimage = cmat_filepath.split('/')[-1]
degreedistimage = degreedist_filepath.split('/')[-1]
netimage1 = net1_filepath.split('/')[-1]
barimage1 = bar1_filepath.split('/')[-1]
netimage2 = net2_filepath.split('/')[-1]
barimage2 = bar2_filepath.split('/')[-1]
netimage3 = net3_filepath.split('/')[-1]
barimage3 = bar3_filepath.split('/')[-1]
ereg_hist = ereg_hist_filepath.split('/')[-1]
ereg_network = ereg_network_filepath.split('/')[-1]
partcoef_hist = partcoef_hist_filepath.split('/')[-1]
partcoef_network = partcoef_network_filepath.split('/')[-1]
# Need to run this one every time in order to get module colors for webgl
moduleimage = plot_modules(0, 0, module_filepath, matfilepaths, weight, names_dict, centers, graph, cmat).split('/')[-1]
springimage = spring_filepath.split('/')[-1]
import time
t = time.ctime()
metrics = []
for count,region in enumerate(fullnames[0]):
metrics.append([region,degs[0][count],
ccs[0][count],\
bcs[0][count],\
partitions[0][count],
e_regs[0][count],
part_coefs[0][count]]) #,e_locs[0][count]])
session.metrics = metrics
matfilepath = os.path.join(request.folder,'uploads',matfilename)
centersfilepath = os.path.join(request.folder,'uploads',network.region_xyz_centers_file)
webgl_url = plot_matrix_webgl(matfilepath,centersfilepath, network, weight=weight[0], chosen_density=chosen_density)
d = dict(network=network,raw_density=raw_density,chosen_density=chosen_density,
cmatimage=cmatimage,degreedistimage=degreedistimage,
netimage1=netimage1,barimage1=barimage1,netimage2=netimage2,barimage2=barimage2,
netimage3=netimage3,barimage3=barimage3,moduleimage=moduleimage,springimage=springimage,
ereg_hist=ereg_hist,ereg_network=ereg_network,
partcoef_hist=partcoef_hist,partcoef_network=partcoef_network,
a=edge_density[0],b=abbrevfilepath[0],
cpl=cpl,mcc=mcc,num_comp=num_comp,sigma=sigma,lambda_cc=lambda_cc,gamma_cpl=gamma_cpl,
q=q, time=t, weight=weight[0], webgl_url=webgl_url, num_regions=num_regions,
edge_attributes=edge_attributes)
report_filename = pdfreport(0, weight, network, chosen_density, raw_density, cpl,\
mcc, q, num_comp, sigma, lambda_cc, gamma_cpl,\
cmatimage, degreedistimage, barimage1, netimage1,\
barimage2, netimage2, barimage3, netimage3,\
moduleimage, springimage, metrics)
d["report_filename"] = report_filename
d["metrics_filename"] = metrics_text(metrics, network, weight[0], chosen_density)
d["e_glob"] = e_glob
#return response.render(d)
row = db(db.analysis_results.network_name==network.id).select().first()
db(db.analysis_results.network_name==network.id).update(num_times_analyzed=row.num_times_analyzed+1)
now = datetime.datetime.now()
db(db.analysis_results.network_name==network.id).update(last_time_analyzed=now.strftime("%Y-%m-%d %H:%M"))
return d
def file_reader(infile,text=0):
fin = open(infile,'rU')
values = []
if text==1:
for line in fin:
pos = line.rstrip()
values.append(pos)
else:
for line in fin:
pos = line.rstrip().split()
values.append(map(float, pos))
fin.close()
return values
def double():
if auth.user:
rows_allowed = db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)).select()
study_names = list(set([row.study_name for row in rows_allowed]))
if request.vars.study_name_1 or request.vars.study_name_2:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
else:
study_networks = ''
form = SQLFORM.factory(
Field('study_name_1', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_1_name',
#db.upload_data,
#requires=IS_IN_DB(db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)),
# 'upload_data.id',
# '%(network_name)s')),
requires=IS_IN_SET(study_networks)),
Field('study_name_2', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_2_name',
#db.upload_data,
#requires=IS_IN_DB(db((db.upload_data.share=='Public') | (db.upload_data.email==auth.user.email)),
# 'upload_data.id',
# '%(network_name)s')
requires=IS_IN_SET(study_networks)),
Field('weight_1',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('weight_2',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('edge_density_1',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('edge_density_2',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
submit_button='Analyze')
else:
rows_allowed = db((db.upload_data.share=='Public')).select()
study_names = list(set([row.study_name for row in rows_allowed]))
if request.vars.study_name:
study_networks = [row.network_name for row in rows_allowed if row.study_name==request.vars.study_name]
else:
study_networks = ''
form = SQLFORM.factory(
Field('study_name_1', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_1_name',
requires=IS_IN_SET(study_networks)),
Field('study_name_2', requires=IS_IN_SET(study_names),
default = (lambda x: x if x else '')(request.vars.study_name_cur)),
Field('network_2_name',
requires=IS_IN_SET(study_networks)),
Field('weight_1',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('weight_2',requires=IS_IN_SET([('Binary','Binary'),('Weighted','Weighted')]), default='Binary'),
Field('edge_density_1',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('edge_density_2',default=20,requires=IS_INT_IN_RANGE(0, 101, error_message=T('Must be integer in range 0-100'))),
Field('orientation',requires=IS_IN_SET([('Axial','Axial'),('Sagittal','Sagittal'),('Coronal','Coronal')]), default='Axial'),
submit_button='Analyze')
form[0][0].insert(-1,"Choose from the list of available studies")
form[0][1].insert(-1,"Choose from the list of shared networks for the first chosen study")
form[0][2].insert(-1,"Choose from the list of available studies")
form[0][3].insert(-1,"Choose from the list of shared networks for the second chosen study")
form[0][4].insert(-1,"Choose a weighting scheme for the network, either weighted or binarized edges")
form[0][5].insert(-1,"Choose a weighting scheme for the network, either weighted or binarized edges")
form[0][6].insert(-1,"Choose the percent of connections to keep (0-100%)")
form[0][7].insert(-1,"Choose the percent of connections to keep (0-100%)")
form[0][8].insert(-1,"Choose the orientation from which to view the network")
if form.accepts(request.vars, session):
cache.ram.clear()
redirect(URL(r=request,f='compare_view',vars=form.vars))
return dict(form=form)
def about():
return dict()
def contact():
return dict()
def technical_specification():
return dict()
def using_the_site():
return dict()
def reference():
return dict()
def analyze_home():
return dict()
def upload_home():
return dict()
def image_mat(num, path, cmat):
plt.figure(figsize=(5,5))
plt.imshow(cmat[num],interpolation='nearest')
plt.colorbar()
savefig(path)
plt.close()
return path
def degree_dist(num, path, graph):
deg = nx.degree(graph[num])
degs = np.array([deg[x] for x in deg])
plt.figure(figsize=(5,5))
plt.hist(degs,10)
plt.title("Node Degree Histogram")
plt.ylabel("Degree")
plt.xlabel("Number")
savefig(path)
plt.close()
return path
#def plot_bars(num, node_metric, path, num_regions, bcs, degs, ccs, names):
def plot_bars(num, path, num_regions, metric, names):
"""
Plot histogram of values of given regional metric in descending order
"""
num_regions = num_regions[num]
matplotlib.rcParams['font.size'] = 6
val = metric[num]
#if node_metric == 's':
# val = degs[num]
#elif node_metric == 'bc':
# val = bcs[num]
#elif node_metric == 'cc':
# val = ccs[num]
val_sort_indices=np.argsort(val)
val_sort=[val[x] for x in val_sort_indices]
val_names_sort=[names[num][x] for x in val_sort_indices]
pos = np.arange(num_regions)*2
figheight = num_regions/12.
plt.figure(figsize = (5, figheight))
plt.barh(pos, val_sort)
plt.yticks(pos, val_names_sort)
plt.autoscale(tight=True)
#plt.show()
savefig(path)
plt.close()
matplotlib.rcParams['font.size'] = 12
return path
def plot_modules(num, spring, path, matfilepaths, weight, names_dict, centers, graph, cmat):
import matplotlib.cm