-
Notifications
You must be signed in to change notification settings - Fork 0
/
CGraphClust.R
2026 lines (1939 loc) · 80.8 KB
/
CGraphClust.R
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
# Copyright (C) 2018 Umar Niazi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
library(methods)
if (!require(igraph)) stop('CGraphClust.R: library igraph required')
##### Class CGraph
# Name: Class CGgraph
# Desc: assigns weights to one mode projection of graphs based on observed to expected probabilities of
# vertices of the first kind i.e. with value TRUE using the igraph library
# Zweig, K. A., & Kaufmann, M. (2011). A systematic approach to the one-mode projection of
# bipartite graphs. Social Network Analysis and Mining (Vol. 1, pp. 187–218).
# doi:10.1007/s13278-011-0021-0
# declaration
# f = flag to identify type 1 or type 2 vertices
# r = total number of type 2 vertices
# ig = bipartite igraph object
# ig.p = projected and weighted igraph object
setClass('CGraph', slots=list(ig='ANY', r='numeric', f='logical', ig.p='ANY'))
# object constructor
CGraph.bipartite = function(dfGraph, bFilterLowDegreeType2Edges=T, bFilterWeakLinks=T, ivWeights=c(1, 0, -1),
mix.prior = c(m1=3/9 ,m2= 3/9 ,m3= 3/9)){
# check if igraph library present
if (!require(igraph)) stop('R library igraph required')
if (!require(LearnBayes)) stop('R library LearnBayes required')
dfGraph = na.omit(dfGraph)
# some error checks
if (ncol(dfGraph) != 2) {
stop(paste('data frame dfGraph should have 2 columns only',
'column 1 for vertex of type 1, and column 2 for vertex of',
'type 2'))
}
# create bipartite graph
oIGbp = graph.data.frame(dfGraph, directed = F)
# set the vertex type variable to make graph bipartite
f = rep(c(T, F), times = c(length(unique(dfGraph[,1])),length(unique(dfGraph[,2]))))
V(oIGbp)$type = f
# sanity check - is graph bipartite
if (!is.bipartite(oIGbp)) {
stop(paste('Graph is not bipartite'))
}
## graph cleaning
if (bFilterLowDegreeType2Edges){
# remove type 2 terms that have low degrees,
# these are rare terms that add little to the association scores
f = V(oIGbp)$type
# degree vector of type 2 vertices
ivDegGo = degree(oIGbp, V(oIGbp)[!f])
# setting this at less than 2, if 2 type 1 terms share a lot of weak terms, those should be preserved
c = names(which(ivDegGo < 2))
v = V(oIGbp)[c]
oIGbp = delete.vertices(oIGbp, v)
# check if graph is bipartite
if (!is.bipartite(oIGbp)) stop('Graph is not bipartite')
}
############################### internal private functions
### called by constructor
############# weighting functions
generate.weights = function(suc, trials){
## break the weight vector into 3 quantiles
m1.suc = quantile(suc, 0.975)
m1.fail = trials - m1.suc
m2.suc = quantile(suc, 0.75)
m2.fail = trials - m2.suc
m3.suc = quantile(suc, 0.5)
m3.fail = trials - m3.suc
## if difference between the median and 75% quantiles is small
## then increase this as it can happen if most numbers in the
## suc vector are the same
d = m2.suc - m3.suc
if (d <= 1){
d = ifelse(d==0, 2, 1)
m1.suc = m1.suc + d
m1.fail = trials - m1.suc
m2.suc = m2.suc + d
m2.fail = trials - m2.suc
}
## define 3 functions with a prior for each of the quantiles
## model m1 - green
m1 = function(th) dbeta(th, m1.suc, m1.fail, log = T)
## model m2 - yellow
m2 = function(th) dbeta(th, m2.suc, m2.fail, log = T)
## model m3 - red
m3 = function(th) dbeta(th, m3.suc, m3.fail, log = T)
## define an array that represents number of models in our parameter space
## each index has a prior weight/probability of being selected
## this can be thought of coming from a categorical distribution
## moved to arguments section of the constructor
#mix.prior = c(m1=3/9 ,m2= 3/9 ,m3= 3/9)
library(LearnBayes)
library(car)
#logit.inv = function(p) {exp(p)/(exp(p)+1) }
mylogpost_m1 = function(theta, data){
## theta contains parameters we wish to track
th = plogis(theta['theta'])
success = data['suc']
fail = data['fail']
# define likelihood function
lf = function(s, f, t) return(dbinom(s, s+f, t, log=T))
# calculate log posterior
val = lf(success, fail, th) + m1(th)
return(val)
}
mylogpost_m2 = function(theta, data){
## theta contains parameters we wish to track
th = plogis(theta['theta'])
success = data['suc']
fail = data['fail']
# define likelihood function
lf = function(s, f, t) return(dbinom(s, s+f, t, log=T))
# calculate log posterior
val = lf(success, fail, th) + m2(th)
return(val)
}
mylogpost_m3 = function(theta, data){
## theta contains parameters we wish to track
th = plogis(theta['theta'])
success = data['suc']
fail = data['fail']
# define likelihood function
lf = function(s, f, t) return(dbinom(s, s+f, t, log=T))
# calculate log posterior
val = lf(success, fail, th) + m3(th)
return(val)
}
# starting value for search - initial value
start = c(theta=logit(median(suc)/trials))
mMixs = sapply(seq_along(suc), function(x){
data = c(suc=suc[x], fail=trials-suc[x])
fit_m1 = laplace(mylogpost_m1, start, data)
fit_m2 = laplace(mylogpost_m2, start, data)
fit_m3 = laplace(mylogpost_m3, start, data)
mix.post = mix.prior
mix.post[1] = exp(fit_m1$int) * mix.prior[1] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
mix.post[2] = exp(fit_m2$int) * mix.prior[2] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
mix.post[3] = exp(fit_m3$int) * mix.prior[3] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
return(mix.post)
})
return(mMixs)
}
# Name: CGraph.project
# Desc: assigns a score to each edge based on the model scores
# the score for each model is calculated using a mixture of binomial models with beta priors
# Args: called internally no need to do it externally,
# will project on vertex with TYPE=TRUE
CGraph.project = function(obj){
# project the graph in one dimension and assign weights
g.p = bipartite.projection(obj@ig, which = 'TRUE')
w = E(g.p)$weight
if (bFilterWeakLinks) {
# remove low weight edges i.e. if two type 1 vertices share only one type 2 vertex
f = which(w < 2)
g.p = delete.edges(g.p, edges=f)
w = E(g.p)$weight
}
## assign weights and categories to weights
mWeights = generate.weights(w, obj@r)
i = apply(mWeights, 2, which.max)
cat = c('green', 'yellow', 'red')[i]
num = ivWeights[i]
E(g.p)$weight_cat = cat
E(g.p)$weight_projection = E(g.p)$weight
E(g.p)$weight = num
E(g.p)$green = mWeights[1,] # numeric prob for green model
E(g.p)$yellow = mWeights[2,] # numeric prob for yellow model
E(g.p)$red = mWeights[3,]# numeric prob for red model
obj@ig.p = g.p
return(obj)
}
######## end internal functions called by constructor
# create the object
g = new('CGraph', ig=oIGbp, r = 0, f= F, ig.p=NULL)
f = V(g@ig)$type
# r is the total numbers of vertices of the second kind
g@r = sum(!f)
g@f = f
# assign weights on one mode projection
g = CGraph.project(g)
return(g)
}
CGraph.bipartite2 = function(dfGraph, bFilterLowDegreeType2Edges=T, bFilterWeakLinks=T, ivWeights=c(1, 0, -1),
mix.prior = c(m1=3/9 ,m2= 3/9 ,m3= 3/9)){
# check if igraph library present
if (!require(igraph)) stop('R library igraph required')
if (!require(LearnBayes)) stop('R library LearnBayes required')
dfGraph = na.omit(dfGraph)
# some error checks
if (ncol(dfGraph) != 2) {
stop(paste('data frame dfGraph should have 2 columns only',
'column 1 for vertex of type 1, and column 2 for vertex of',
'type 2'))
}
# create bipartite graph
oIGbp = graph.data.frame(dfGraph, directed = F)
# set the vertex type variable to make graph bipartite
f = rep(c(T, F), times = c(length(unique(dfGraph[,1])),length(unique(dfGraph[,2]))))
V(oIGbp)$type = f
# sanity check - is graph bipartite
if (!is.bipartite(oIGbp)) {
stop(paste('Graph is not bipartite'))
}
## graph cleaning
if (bFilterLowDegreeType2Edges){
# remove type 2 terms that have low degrees,
# these are rare terms that add little to the association scores
f = V(oIGbp)$type
# degree vector of type 2 vertices
ivDegGo = degree(oIGbp, V(oIGbp)[!f])
# setting this at less than 2, if 2 type 1 terms share a lot of weak terms, those should be preserved
c = names(which(ivDegGo < 2))
v = V(oIGbp)[c]
oIGbp = delete.vertices(oIGbp, v)
# check if graph is bipartite
if (!is.bipartite(oIGbp)) stop('Graph is not bipartite')
}
############################### internal private functions
### called by constructor
############# weighting functions
generate.weights = function(iCor){
# scale value for log posterior function
iScale = sd(iCor)
# starting value for search - initial value
start = c('mu'=mean(iCor))
## break the weight vector into 3 quantiles
q1 = quantile(iCor, 0.975)
q2 = quantile(iCor, 0.75)
q3 = quantile(iCor, 0.5)
## define 3 functions with a prior for each of the quantiles
## model m1 - green
m1 = function(th) dcauchy(th, q1, log = T)
## model m2 - yellow
m2 = function(th) dcauchy(th, q2, log = T)
## model m3 - red
m3 = function(th) dcauchy(th, q3, log = T)
## define an array that represents number of models in our parameter space
## each index has a prior weight/probability of being selected
## this can be thought of coming from a categorical distribution
## moved to the arguments section of the constructor
##mix.prior = c(m1=3/9 ,m2= 3/9 ,m3= 3/9)
library(LearnBayes)
library(car)
lp1 = function(theta, data){
m = theta['mu']
d = data # data observed
log.lik = sum(dnorm(d, m, iScale, log=T))
log.prior = m1(m)
log.post = log.lik + log.prior
return(log.post)
}
lp2 = function(theta, data){
m = theta['mu']
d = data # data observed
log.lik = sum(dnorm(d, m, iScale, log=T))
log.prior = m2(m)
log.post = log.lik + log.prior
return(log.post)
}
lp3 = function(theta, data){
m = theta['mu']
d = data # data observed
log.lik = sum(dnorm(d, m, iScale, log=T))
log.prior = m3(m)
log.post = log.lik + log.prior
return(log.post)
}
mMixs = sapply(seq_along(iCor), function(x){
data = iCor[x]
fit_m1 = laplace(lp1, start, data)
fit_m2 = laplace(lp2, start, data)
fit_m3 = laplace(lp3, start, data)
mix.post = mix.prior
mix.post[1] = exp(fit_m1$int) * mix.prior[1] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
mix.post[2] = exp(fit_m2$int) * mix.prior[2] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
mix.post[3] = exp(fit_m3$int) * mix.prior[3] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
return(mix.post)
})
return(mMixs)
}
# Name: CGraph.project
# Desc: Does 2 things,
# 1: assigns a level of interestingness/leverage or observed to expected ratio to
# each edge after graph projection on the vertex of first kind i.e. type = TRUE
# Observed frequency = weight of edge / (total number of vertices of second type)
# i.e. how many shared vertices of type 2 are between the 2 type 1 vertices
# Expected frequency = how many times we expect to see them based on their
# joint probability under assumption of independence.
# (marginal.prob of V1 * marginal.prob of V2)
# 2: assigns an importance score to each edge based on the model scores
# the score for each model is calculated using a mixture of normal models with cauchy prior for mean
# and variance is fixed
# Args: called internally no need to do it externally,
# will project on vertex with TYPE=TRUE
CGraph.project = function(obj){
# project the graph in one dimension and assign weights
g.p = bipartite.projection(obj@ig, which = 'TRUE')
# get the matrix with rows representing each edge
m = get.edgelist(g.p)
w = E(g.p)$weight
if (bFilterWeakLinks) {
# remove low weight edges i.e. if two type 1 vertices share only one type 2 vertex
f = which(w < 2)
g.p = delete.edges(g.p, edges=f)
w = E(g.p)$weight
m = get.edgelist(g.p)
}
## assign weights and categories to weights
# calculate observed ratio
# weight / r
ob = w / obj@r
# calculate expected
mExp = cbind(V(g.p)[m[,1]]$prob_marginal, V(g.p)[m[,2]]$prob_marginal)
ex = mExp[,1] * mExp[,2]
E(g.p)$observed = ob
E(g.p)$expected = ex
E(g.p)$ob_to_ex = log(ob / ex)
mWeights = generate.weights(E(g.p)$ob_to_ex)
i = apply(mWeights, 2, which.max)
cat = c('green', 'yellow', 'red')[i]
num = ivWeights[i]
E(g.p)$weight_cat = cat
E(g.p)$weight_projection = E(g.p)$weight
E(g.p)$weight = num
E(g.p)$green = mWeights[1,] # numeric prob for green model
E(g.p)$yellow = mWeights[2,] # numeric prob for yellow model
E(g.p)$red = mWeights[3,]# numeric prob for red model
obj@ig.p = g.p
return(obj)
}
# assign probabilities to vertex of first kind
# Name: CGraph.assign.marginal.probabilities
# Desc: assigns probabilities to each vertex of the first kind (TRUE)
# based on how many times it is connected to the vertex of the
# second kind i.e. degree(V1) / (total number of V-type2)
# Args: internal function - object of CGraph class
CGraph.assign.marginal.probabilities = function(obj){
# vertex of the first kind will be assigned probabilities
# based on their relations with the vertices of the second kind
# flag to identify vertex types
f = V(obj@ig)$type
d = degree(obj@ig)
d = d[f]
# r is the total numbers of vertices of the second kind
r = sum(!f)
p = d/r
V(obj@ig)[f]$prob_marginal = p
obj@r = r
obj@f = f
return(obj)
}
######## end internal functions called by constructor
# create the object
g = new('CGraph', ig=oIGbp, r = 0, f= F, ig.p=NULL)
# assign marginal probabilities
g = CGraph.assign.marginal.probabilities(g)
# assign weights on one mode projection
g = CGraph.project(g)
return(g)
}
# object constructor 2 for correlation matrix
CGraph.cor = function(ig.template=NULL, mCor, ivWeights=c(1, 0, -1), mix.prior = c(m1=3/9 ,m2= 3/9 ,m3= 3/9)){
# check if igraph library present
if (!require(igraph)) stop('R library igraph required')
if (!require(LearnBayes)) stop('R library LearnBayes required')
library(car)
############################### internal private functions
### called by constructor
############# weighting functions
generate.weights = function(iCor){
# scale value for log posterior function
iScale = sd(iCor)
# starting value for search - initial value
start = c('mu'=mean(iCor))
# define a grid for calculating model scores and then
# bin the actual correlations in those grid bins
r = range(iCor)
iGrid = seq(floor(r[1]), ceiling(r[2]), length.out = 100)
## break the weight vector into 3 quantiles
q1 = quantile(iCor, 0.975)
q2 = quantile(iCor, 0.75)
q3 = quantile(iCor, 0.5)
## define 3 functions with a prior for each of the quantiles
## model m1 - green
m1 = function(th) dnorm(th, q1, log = T)
## model m2 - yellow
m2 = function(th) dnorm(th, q2, log = T)
## model m3 - red
m3 = function(th) dnorm(th, q3, log = T)
## define an array that represents number of models in our parameter space
## each index has a prior weight/probability of being selected
## this can be thought of coming from a categorical distribution
## moved to the arguments section of the constructor
##mix.prior = c(m1=3/9 ,m2= 3/9 ,m3= 3/9)
lp1 = function(theta, data){
m = theta['mu']
d = data # data observed
log.lik = sum(dnorm(d, m, iScale, log=T))
log.prior = m1(m)
log.post = log.lik + log.prior
return(log.post)
}
lp2 = function(theta, data){
m = theta['mu']
d = data # data observed
log.lik = sum(dnorm(d, m, iScale, log=T))
log.prior = m2(m)
log.post = log.lik + log.prior
return(log.post)
}
lp3 = function(theta, data){
m = theta['mu']
d = data # data observed
log.lik = sum(dnorm(d, m, iScale, log=T))
log.prior = m3(m)
log.post = log.lik + log.prior
return(log.post)
}
mMixs = sapply(seq_along(iGrid), function(x){
data = iGrid[x]
fit_m1 = laplace(lp1, start, data)
fit_m2 = laplace(lp2, start, data)
fit_m3 = laplace(lp3, start, data)
mix.post = mix.prior
mix.post[1] = exp(fit_m1$int) * mix.prior[1] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
mix.post[2] = exp(fit_m2$int) * mix.prior[2] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
mix.post[3] = exp(fit_m3$int) * mix.prior[3] / (exp(fit_m1$int) * mix.prior[1] + exp(fit_m2$int) * mix.prior[2]
+ exp(fit_m3$int) * mix.prior[3])
return(mix.post)
})
# bin the actual correlation vector on the grid bin
i = apply(mMixs, 2, which.max)
cat = c('green', 'yellow', 'red')[i]
cat = factor(cat, levels = c('red', 'yellow', 'green'))
# break points for bins
p = tapply(iGrid, cat, range)
p = c(p$red, p$yellow[2], p$green[2])
cat.all = as.character(cut(iCor, breaks = p, include.lowest = F, labels = levels(cat)))
return(cat.all)
}
######## end internal functions called by constructor
## create correlation matrix graph, by treating it as an adjacency matrix
mCor = round(mCor, 3)
diag(mCor) = 0
# create the graph of correlations
oIGcor = graph.adjacency(mCor, mode='min', weighted=T)
## house keeping and cleaning template graph to drop edge attributes
if (!is.null(ig.template)){
m = as_adjacency_matrix(ig.template)
ig.template = graph.adjacency(m, mode = 'min', weighted = NULL)
oIGcor = graph.intersection(ig.template, oIGcor)
}
c = E(oIGcor)$weight
E(oIGcor)$cor = c
c = logit(abs(c))
cat = generate.weights(c)
i = rep(NA, length(cat))
i[cat == 'green'] = ivWeights[1]
i[cat == 'yellow'] = ivWeights[2]
i[cat == 'red'] = ivWeights[3]
E(oIGcor)$weight_cat = cat
E(oIGcor)$weight = i
g = new('CGraph', ig=NULL, r = 0, f= F, ig.p=oIGcor)
return(g)
}
# data acccessor functions
setGeneric('getBipartiteGraph', function(obj)standardGeneric('getBipartiteGraph'))
setMethod('getBipartiteGraph', signature = 'CGraph', definition = function(obj){
return(obj@ig)
})
setGeneric('getProjectedGraph', function(obj)standardGeneric('getProjectedGraph'))
setMethod('getProjectedGraph', signature = 'CGraph', definition = function(obj){
return(obj@ig.p)
})
# simple plotting function for the graph
setGeneric('plot.projected.graph', function(obj, cDropEdges='red', bDropOrphans=T)standardGeneric('plot.projected.graph'))
setMethod('plot.projected.graph', signature = 'CGraph', definition = function(obj, cDropEdges='red', bDropOrphans=T){
ig = getProjectedGraph(obj)
i = which(E(ig)$weight_cat %in% cDropEdges)
if (length(i) > 0) ig = delete.edges(ig, i)
if (bDropOrphans) {
c = which(degree(ig) == 0)
ig = delete.vertices(ig, c)
}
p.old = par(mar=c(1,1,1,1)+0.1)
plot(ig, vertex.label=NA, vertex.size=2, layout=layout_with_fr(ig, weights = E(ig)$weight), vertex.frame.color=NA)
par(p.old)
})
# simple plotting function for the graph to highlight cliques
setGeneric('plot.graph.clique', function(obj, cDropEdges=c('red', 'yellow'), bDropOrphans=T)standardGeneric('plot.graph.clique'))
setMethod('plot.graph.clique', signature = 'CGraph', definition = function(obj, cDropEdges=c('red', 'yellow'), bDropOrphans=T){
ig = getProjectedGraph(obj)
i = which(E(ig)$weight_cat %in% cDropEdges)
if (length(i) > 0) ig = delete.edges(ig, i)
if (bDropOrphans) {
c = which(degree(ig) == 0)
ig = delete.vertices(ig, c)
}
cl = largest_cliques(ig)
c = rainbow(length(cl)+1)
V(ig)$color = c[length(c)]
# cliques are a list, so choose colours based on number of cliques
for (i in 1:length(cl)) V(ig)[cl[[i]]]$color = c[i]
p.old = par(mar=c(1,1,1,1)+0.1)
plot(ig, vertex.label=NA, vertex.size=2, layout=layout_with_fr(ig, weights = E(ig)$green), vertex.frame.color=NA)
par(p.old)
})
# function to perform unions of the graph objects
CGraph.union = function(g1, g2, ...){
u = graph.union(g1, g2, ...)
i = grep('weight_\\d+', edge_attr_names(u))
## add the weights together
w = do.call(cbind, args = edge.attributes(u)[i])
E(u)$weight = rowSums(w, na.rm = T)
#g = new('CGraph', ig=NULL, r = 0, f= F, ig.p=u)
return(u)
}
## utility functions
f_dfGetGeneAnnotation = function(cvEnterezID = NULL) {
if (!require(org.Hs.eg.db)) stop('org.Hs.eg.db annotation library required')
return(AnnotationDbi::select(org.Hs.eg.db, cvEnterezID, columns = c('SYMBOL', 'GENENAME'), keytype = 'ENTREZID'))
}
mCompressMatrixByRow = function(mData, ig, com){
## internal functions
getClusterSubgraph = function(ig, lab, com){
m = factor(membership(com))
m = m[m %in% lab]
ig.s = induced.subgraph(ig, V(ig)[names(m)])
return(ig.s)
}
f_edge.score = function(g, mCl){
# get the list of edges
el = get.edgelist(g)
# for each edge list row, get the
# expression matrix rows
mRet = apply(el, 1, function(x){
m = colSums(mCl[x,])
return(m)
})
return(t(mRet))
}
n = V(ig)$name
# sanity check
if (sum(rownames(mData) %in% n) == 0) stop('Row names of count matrix do not match with node names of graph')
mData = mData[n,]
if (!identical(names(membership(com)), n)) stop('community membership not in order with node names')
memb = factor(membership(com))
# get row average for each cluster
mCent = matrix(NA, nrow=nlevels(memb), ncol = ncol(mData))
rownames(mCent) = levels(memb)
colnames(mCent) = colnames(mData)
# loop and calculate marginal for each cluster
for(a in 1:nrow(mCent)){
i = rownames(mCent)[a]
# if cluster has only one or two members then remove from analysis
# issue1 - if 2 members in cluster then only one edge, which crashes the
# colSumns function in f_edge.score function, and a subgraph can have no edges
if (sum(memb == i) <= 2 || ecount(getClusterSubgraph(ig, i, com)) <= 1) {
# mCent[i,] = mCounts[memb == i,]
next;
} else {
# else if more than one member,
mCent[i,] = colMeans(f_edge.score(getClusterSubgraph(ig, i, com), mData[memb==i,]))}
}
return(mCent)
}
f_igCalculateVertexSizesAndColors = function(ig, mCounts, fGroups, bColor = FALSE, iSize=NULL, transform_function=identity){
n = V(ig)$name
# sanity check
if (sum(rownames(mCounts) %in% n) == 0) stop('f_igCalculatevertexSizesAndColors: Row names of count matrix do not match with genes')
# calculate fold changes function
lf_getFC = function(x, f){
l = levels(f)
r = tapply(x, f, mean)
fc = transform_function(r[l[length(l)]]) - transform_function(r[l[1]])
return(fc)
}
# calculate colour function
lf_getDirection = function(x, f){
l = levels(f)
r = tapply(x, f, mean)
c = ifelse(r[l[1]] < r[l[length(l)]], 'pink', 'lightblue')
return(c)
}
if (is.null(iSize)) iSize = 4000/vcount(ig)
mCounts = mCounts[n,]
s = apply(mCounts, 1, function(x) lf_getFC(x, fGroups))
V(ig)[n]$size = abs(s * iSize)
# assign colours if required
if (bColor){c = sapply(seq_along(n), function(x) lf_getDirection(mCounts[n[x], ], fGroups))
V(ig)[n]$color = c
}
return(ig)
}
############### end class CGraph
# # Name: Class CGgraphClust
# # Decs: class to create a igraph and hclust object based on 2 criteria: 1) shared
# # properties or connections with type 2 vertices in a bipartite graph.
# # 2) positive correlation value
# # Inherits properties from CGraph class
#
# # declaration
# # contains: hc = hclust object
# # com = community object
# # labels = the most frequent type 2 vertex shared with the members of the
# # community (cluster) of type 1 vertices
# # ig.p2 = projected graph after cutoffs of obs to exp frequencies
# # ig.c = correlation matrix graph
# # ig.i = intersection graph
# # CGraph object with original graph
# setClass('CGraphClust', slots=list(hc='ANY', com='ANY',
# labels='character', ig.p2 = 'ANY',
# ig.c = 'ANY', ig.i = 'ANY'),
# contains='CGraph')
#
#
# # constructor
# CGraphClust = function(dfGraph, mCor, iCorCut=0.5, bSuppressPlots = T, iMinComponentSize=6, clusterMethod=cluster_walktrap){
# dfGraph = na.omit(dfGraph)
# # some error checks
# if (ncol(dfGraph) != 2) {
# stop(paste('data frame dfGraph should have 2 columns only',
# 'column 1 for vertex of type 1, and column 2 for vertex of',
# 'type 2'))
# }
# # create bipartite graph
# oIGbp = graph.data.frame(dfGraph, directed = F)
# # set the vertex type variable to make graph bipartite
# f = rep(c(T, F), times = c(length(unique(dfGraph[,1])),length(unique(dfGraph[,2]))))
# V(oIGbp)$type = f
# # sanity check - is graph bipartite
# if (!is.bipartite(oIGbp)) {
# stop(paste('Graph is not bipartite'))
# }
#
# ## graph cleaning
# # remove type 2 terms that have low degrees,
# # these are rare terms that add little to the association scores
# f = V(oIGbp)$type
# # degree vector of type 2 vertices
# ivDegGo = degree(oIGbp, V(oIGbp)[!f])
# # # on a log scale it follows a poisson or negative binomial dist
# # t = log(ivDegGo)
# # r = range(t)
# # s = seq(floor(r[1])-0.5, ceiling(r[2])+0.5, by=1)
# # r[1] = floor(r[1])
# # r[2] = ceiling(r[2])
# # if (!bSuppressPlots){
# # # which distribution can approximate the frequency of reactome terms
# # hist(t, prob=T, main='degree distribution of type 2 vertices', breaks=s,
# # xlab='log degree', ylab='')
# # # try negative binomial and poisson distributions
# # # parameterized on the means
# # dn = dnbinom(r[1]:r[2], size = mean(t), mu = mean(t))
# # dp = dpois(r[1]:r[2], mean(t))
# # lines(r[1]:r[2], dn, col='black', type='b')
# # lines(r[1]:r[2], dp, col='red', type='b')
# # legend('topright', legend =c('nbinom', 'poi'), fill = c('black', 'red'))
# # }
# # # a poisson distribution with mean(t) fits well - use this as cutoff
# # # however a negative binomial will adjust for overdispertion, try both perhaps
# # i = round(exp(qpois(0.05, mean(t), lower.tail = F)))
# # #i = round(exp(qnbinom(0.05, size = mean(t), mu = mean(t), lower.tail = F)))
# # c = names(which(ivDegGo>i))
# c = names(which(ivDegGo<=2))
# v = V(oIGbp)[c]
# oIGbp = delete.vertices(oIGbp, v)
# # delete any orphan type 1 vertices left behind
# # d = degree(oIGbp)
# # oIGbp = delete.vertices(oIGbp, which(d == 0))
#
# ## graph projection to one dimension
# # create the CGraph object and calculate obs to exp weights after projection
# obj = CGraph(oIGbp)
# # create a projection of the graph
# # oIGProj = getProjectedGraph(obj)
# oIGProj = obj@ig.p
# ## some type 1 vertices are orphans as they don't share
# # type 2 vertices with other type 1 and will now be orphans after projection,
# # remove those
# d = degree(oIGProj)
# oIGProj = delete.vertices(oIGProj, which(d == 0))
# # switch the weights with obs to exp ratio
# E(oIGProj)$weight_old = E(oIGProj)$weight
# w = rep(0, length=ecount(oIGProj))
# w[E(oIGProj)$weight_cat == 'red'] = -1
# w[E(oIGProj)$weight_cat == 'green'] = 1
# E(oIGProj)$weight = w #E(oIGProj)$ob_to_ex
#
# ## remove low observed to expected probabilities
# w = E(oIGProj)$weight_cat
# # # choose a cutoff by modelling the distribution shape
# # # it appears that the distribution follows a power law?
# # # taking square root means we can fit a poisson or neg bin distribution
# # w2 = sqrt(w)
# # r = range(w2)
# # s = seq(floor(r[1])-0.5, ceiling(r[2])+0.5, by = 1)
# # r[1] = floor(r[1])
# # r[2] = ceiling(r[2])
# # if (!bSuppressPlots){
# # hist(w2, prob=T, breaks=s, main='distribution of obs to exp ratios',
# # xlab='square root obs to exp ratio', ylab='')
# # r = round(r)
# # dp = dpois(r[1]:r[2], lambda = median(w2))
# # dn = dnbinom(r[1]:r[2], size = median(w2), mu = median(w2))
# # lines(r[1]:r[2], dp, col='red', type='b')
# # lines(r[1]:r[2], dn, col='blue', type='b')
# # legend('topright', legend = c('poi', 'nbin'), fill = c('red', 'blue'))
# # }
# # # NOTE: this cutoff can be changed, the lower it is the more edges in the graph
# # # use negative binomial to choose cutoff
# # c = qnbinom(0.05, size = median(w2), mu=median(w2), lower.tail = F)
# # f = which(w2 < c)
# f = which(w == 'red')
# oIGProj = delete.edges(oIGProj, edges = f)
#
# ## reweight the edges
# reweight_edges = function(g.p, r=obj@r){
# w = E(g.p)$weight_old
# ob = (w+1e-6) / r
# ## assign categories to weights
# cat = cut(ob, quantile(jitter(ob), prob=c(0, 0.5, 0.75, 1)), labels = c('red', 'yellow', 'green'))
# # # calculate expected
# # mExp = cbind(V(g.p)[m[,1]]$prob_marginal, V(g.p)[m[,2]]$prob_marginal)
# # ex = mExp[,1] * mExp[,2]
# # E(g.p)$observed = ob
# # E(g.p)$expected = ex
# # E(g.p)$ob_to_ex = ob / ex
# E(g.p)$weight_cat = as.character(cat)
#
# }
#
# ## create correlation matrix graph, by treating it as an adjacency matrix
# diag(mCor) = 0
# # create the graph of correlations
# oIGcor = graph.adjacency(mCor, mode='min', weighted=T)
# ## house keeping and cleaning graph
# c = E(oIGcor)$weight
# E(oIGcor)$cor = E(oIGcor)$weight
# # keep only positively correlated genes connected
# # above chosen cutoff
# f = which(c < iCorCut)
# oIGcor = delete.edges(oIGcor, edges = f)
#
# ### graph intersection
# # this function causing problems?
# #l = list(oIGProj, oIGcor)
# #ig.1 = graph.intersection(l)
# # use non list version of function
# ig.1 = igraph::graph.intersection(oIGProj, oIGcor)
# # set observed to expected ratio as weight
# E(ig.1)$weight = E(ig.1)$ob_to_ex
# d = degree(ig.1)
# # delete any orphan edges
# ig.1 = delete.vertices(ig.1, which(d == 0))
#
# ## remove small components
# cl = clusters(ig.1)
# # t = log(cl$csize)
# # r = range(t)
# # s = seq(floor(r[1])-0.5, ceiling(r[2])+0.5, by=1)
# # r[1] = floor(r[1])
# # r[2] = ceiling(r[2])
# # # which distribution can approximate the distribution of cluster sizes
# # hist(t, prob=T, main='distribution of cluster sizes', breaks=s,
# # xlab='log size', ylab='')
# # # try negative binomial and poisson distributions
# # # parameterized on the means
# # dn = dnbinom(r[1]:r[2], size = mean(t), mu = mean(t))
# # dp = dpois(r[1]:r[2], mean(t))
# # lines(r[1]:r[2], dn, col='black', type='b')
# # lines(r[1]:r[2], dp, col='red', type='b')
# # legend('topright', legend =c('nbinom', 'poi'), fill = c('black', 'red'))
# # a poisson distribution with mean(t) fits well - use this as cutoff
# # however a negative binomial will adjust for overdispertion, try both perhaps
# ## EDIT HERE to get larger clusters i = round(exp(qpois(0.05, mean(t), lower.tail = F)))
# #i = round(exp(qnbinom(0.05, size = mean(t), mu = mean(t), lower.tail = F)))
# i = iMinComponentSize
# i = which(cl$csize < i)
# v = which(cl$membership %in% i)
# # delete the components that are small
# ig.1 = delete.vertices(ig.1, v = v)
#
# ## clean up the bipartite graph by removing type 2 nodes
# ## that are now redundant, as the intersected final graph has less type 1
# ## vertices than the original building of the bipartite graph.
# # recreate the bipartite graph but only with nodes that are in our final graph
# oIGbp = getBipartiteGraph(obj)
# # get the indices for the vertices of type 1
# f = V(oIGbp)$type
# n = V(oIGbp)[f]$name
# # get names of genes present in last graph i.e. intersected graph
# n2 = V(ig.1)$name
# # intersect the names to select those not present in the bipartite graph
# i = !(n %in% n2)
# n = n[i]
# # delete these type 1 vertices from the bipartite graph
# oIGbp = delete.vertices(oIGbp, v = n)
# d = degree(oIGbp)
# # delete orphan nodes left behind (which will include some type 2 vertices)
# oIGbp = delete.vertices(oIGbp, which(d == 0))
# # reset the type flag
# f = V(oIGbp)$type
# # create communities in the graph
# # NOTE: if number of edges in the graph larger than 5000 or so then
# # it may take too long or crash the system, so put in a safety check here
# # and choose a different community finding algorithm
# com = NULL
# if (ecount(ig.1) > 5000) {
# print('Too many edges in graph using cluster_walktrap')
# com = walktrap.community(ig.1)
# } else com = clusterMethod(ig.1)
# # get the hclust object
# hc = as.hclust(com)
# memb = membership(com)
# # variable to hold the type 2 vertex common between
# # members of a community
# rv.g = rep(NA, length=vcount(ig.1))
# rn = V(ig.1)$name
# for (i in 1:length(unique(memb))){
# # get the type 2 names names
# nei = graph.neighborhood(oIGbp, order = 1, nodes = rn[memb == i])
# # this neighbourhood graph is a list of graphs with each
# # graph consisting of type 2 vertices that are connected to the
# # corresponding type 1 vertex in condition rn[memb == i]
# # go through list to get the names
# pw = sapply(seq_along(nei), function(x) V(nei[[x]])$name)
# pw = unlist(pw)
# pw = as.data.frame(table(pw))
# # assign the most frequent type 2 vertex
# rv.g[memb == i] = as.character(pw[which.max(pw$Freq), 1])
# }
# # we are ready to create the object
# return(new('CGraphClust', hc=hc, com=com, labels=rv.g, ig.p2=oIGProj,
# ig.c = oIGcor, ig.i = ig.1, obj))
#
# } # constructor
#
#
# #### constructor 2 to create a new CGraphClust object based on subset of vertices
# # constructor
# CGraphClust.recalibrate = function(obj, ivVertexID.keep, iMinComponentSize=6, clusterMethod=cluster_walktrap){
# ig.1 = getFinalGraph(obj)
# # only keep the desired vertices
# ig.1 = induced.subgraph(ig.1, V(ig.1)[ivVertexID.keep])
# d = degree(ig.1)
# # delete any orphan edges
# ig.1 = delete.vertices(ig.1, which(d == 0))
#
# ## remove small components
# cl = clusters(ig.1)
# i = iMinComponentSize
# i = which(cl$csize < i)
# v = which(cl$membership %in% i)
# # delete the components that are small
# ig.1 = delete.vertices(ig.1, v = v)
#
# ## clean up the bipartite graph by removing type 2 nodes
# ## that are now redundant, as the intersected final graph has less type 1
# ## vertices than the original building of the bipartite graph.
# # recreate the bipartite graph but only with nodes that are in our final graph
# oIGbp = getBipartiteGraph(obj)
# # get the indices for the vertices of type 1
# f = V(oIGbp)$type
# n = V(oIGbp)[f]$name
# # get names of genes present in last graph i.e. intersected graph
# n2 = V(ig.1)$name
# # intersect the names to select those not present in the bipartite graph
# i = !(n %in% n2)
# n = n[i]
# # delete these type 1 vertices from the bipartite graph
# oIGbp = delete.vertices(oIGbp, v = n)
# d = degree(oIGbp)
# # delete orphan nodes left behind (which will include some type 2 vertices)
# oIGbp = delete.vertices(oIGbp, which(d == 0))
# # reset the type flag
# f = V(oIGbp)$type
# # create communities in the graph
# # NOTE: if number of edges in the graph larger than 5000 or so then
# # it may take too long or crash the system, so put in a safety check here
# # and choose a different community finding algorithm
# com = NULL
# if (ecount(ig.1) > 5000) {
# print('Too many edges in graph using cluster_walktrap')
# com = walktrap.community(ig.1)
# } else com = clusterMethod(ig.1)
# # get the hclust object
# hc = as.hclust(com)
# memb = membership(com)
# # variable to hold the type 2 vertex common between
# # members of a community
# rv.g = rep(NA, length=vcount(ig.1))
# rn = V(ig.1)$name
# for (i in 1:length(unique(memb))){
# # get the type 2 names names
# nei = graph.neighborhood(oIGbp, order = 1, nodes = rn[memb == i])
# # this neighbourhood graph is a list of graphs with each