-
Notifications
You must be signed in to change notification settings - Fork 0
/
05_Networks.qmd
482 lines (350 loc) · 15 KB
/
05_Networks.qmd
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
---
title: "05_Networks"
author: "Jacob Cram"
format: html
---
# Preamble
# More resources
JL Weissman, Joy Buongiorno and I wrote a whole class on just network analysis. I'm pulling a few highlights here, but there a lot more resources available, here:
https://github.com/biovcnet/biovcnet.github.io/wiki/TOPIC%3A-Networks
In this project, we will build a simple spearman correlation network, ignoring time-lags, on a subset of the arisa data. But there are a few things that tutorial also focuses on. I'll list them here:
Time-lags: If you are working with time-series data, sometimes one variable tends to change *before* corresponding changes in other variabiles. Its often nice to identify these time-lags. Consider the eLSA package (Lesson 1.4), or just lagging some of your variables (Lesson 1.3).
If you want to look for associations between *trios* of variabiles, consider "Liquid-analysis" in the eLSA package.
# Loading in some data
And reformatting it
Psych, which does correlations and also returns p-values
Igraph does networks. Graph is the technical name for networks
```{r}
source(here::here("Ordination_Pre_Work.R"))
library(psych)
library(igraph)
```
Do the CLR transformation, as in the ordination lesson
Networks Pre Work does some data wrangling.
Delete isolated is a function we will use later. It removes unconnected nodes form netorks
```{r}
source(here::here("Networks_Pre_Work.R"))
delete_isolated <- function(G){
Isolated = which(degree(G) == 0)
G2 = delete.vertices(G, Isolated)
}
```
## Data wrangling
Lets make a matrix of just the ARISA fragments from 5m that show up in at least 10% of the 5m samples, with relative abundance of more than 0.001 (0.1%)
```{r}
# Just the 5m samples
arisa_5m <- arisa_fragments %>%
filter(depth_n == "5")
# Determine the fraction of the time does each ARISA fragment show up with abundance of at least 0.001
arisa_5m_summary <- arisa_5m %>%
group_by(arisa_frag) %>%
summarise(occurances = sum(rel_abund > 0.001), possible = n()) %>%
mutate(frac_present = occurances/possible)
# Identif just the ARISA fragments that are present in at least 10% of the samples
keep_these <- arisa_5m_summary %>%
filter(frac_present >= 0.1) %>%
pull(arisa_frag)
# Keep only the common arisa fragments as identified above
arisa_5m_tenpct <- arisa_5m %>%
filter(arisa_frag %in% keep_these)
## Reshape the data frame with the data we need into a wide matrix
arisa_5m_tenpct_mtx <- arisa_5m_tenpct %>%
pivot_wider(names_from = arisa_frag, values_from = rel_abund, values_fn = median) %>%
select(-depth_n) %>%
column_to_rownames("date_local") %>%
as.matrix()
```
Clr transform the data
```{r}
arisa_5m_tenpct_clr <- decostand(arisa_5m_tenpct_mtx, method = "clr", pseudocount = smz_arisa)
```
# Correlations
Get the spearman correlations of evertying against everything.
```{r}
pt0 <- proc.time()
spearCorTest <- corr.test(arisa_5m_tenpct_clr, method = "spearman", adjust = "none")
pt1 <- proc.time()
pt1 - pt0
```
Extracting correlation and p-value matrices.
```{r}
# extract the correlation r values
spearCor <- spearCorTest$r
# extract the p-values
spearP <- spearCorTest$p
```
So now we have big correlation matrices. These are hard to look at by eye, but we have a few options.
One can mds cluster with a correlation matrix, just like a distance one. We use 1 minus the correlation scores because we want more highly correlated samples to be plotted closer together
```{r}
mds_mod <- metaMDS((1-spearCor^2))
```
```{r}
plot(mds_mod)
```
Question: What can you say about the above data structure. How does it compare to the robust atchinson distances calculated in the similarity lesson?
# Heatmap
One can also plot correlations as a heatap
http://www.sthda.com/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization
```{r}
## Helper functions
# Get lower triangle of the correlation matrix
get_lower_tri<-function(cormat){
cormat[upper.tri(cormat)] <- NA
return(cormat)
}
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
cormat[lower.tri(cormat)]<- NA
return(cormat)
}
reorder_cormat <- function(cormat){
# Use correlation between variables as distance
dd <- as.dist((1-cormat)/2)
hc <- hclust(dd)
cormat <-cormat[hc$order, hc$order]
}
reorder_cor_and_p <- function(cormat, pmat){
dd <- as.dist((1-cormat)/2)
hc <- hclust(dd)
cormat <-cormat[hc$order, hc$order]
pmat <- pmat[hc$order, hc$order]
list(r = cormat, p = pmat)
}
## Make sure that the data are ordered so that more related species are closer together.
## Also ensure that the p values and correlations are in the same order
reordered_all <- reorder_cor_and_p(spearCor, spearP)
reordered_spearCor <- reordered_all$r
reordered_spearP <- reordered_all$p
## Just take the upper triangle of the correlation matrix, reshape it into a data frame, and improve the names of the variables
spearCor_processed <- reordered_spearCor %>% get_lower_tri() %>% as.data.frame() %>% rownames_to_column("Var1") %>% pivot_longer(cols = -Var1, names_to = "Var2", values_to = "rho") %>% na.omit()
spearP_processed <- reordered_spearP %>% get_lower_tri() %>% as.data.frame() %>% rownames_to_column("Var1") %>% pivot_longer(cols = -Var1, names_to = "Var2", values_to = "p") %>% na.omit()
# join the correlation and pvalue data frames
spearRhoP <- left_join(spearCor_processed, spearP_processed, by = c("Var1", "Var2")) %>%
# calculate the false discovery rate to adjust for multiple p values
mutate(fdr = p.adjust(p, method = "BH"))
spearRhoP
```
```{r, fig.width= 10, fig.height = 10}
# Identify which pairs are "statistically significant, given our fdr threshold"
fdrThresh <- 0.01 # fdr threshold
spearOkP <- spearRhoP%>% filter(fdr < fdrThresh)
spearRhoP_plot <- spearRhoP %>% ggplot(aes(x = Var2, y = Var1, fill = rho)) + geom_tile() + scale_fill_gradient2() + theme(axis.text.x = element_text(angle = 90, hjust = 1), axis.text = element_text(size = 5)) + geom_point(data = spearOkP, shape = 1)
spearRhoP_plot
```
Still kind of hard to make sense of things.
# Networks
So a convenient way to visualize things is as a network. We can plot each arisa fragment as a shape, and then connect the ones that are statistically significantly correlated (or most strongly correlated) with a line.
I often do this with igraph.
```{r}
library(igraph)
```
Lets make a data-frame of only statistically significant edges. P < 0.05, fdr < 0.2
```{r}
edges01 <- spearRhoP %>%
filter(p < 0.05, fdr < 0.02) %>%
filter(Var1 != Var2)
```
Networks are formally called "graphs", btw, so thats what I call them here
```{r}
SpearGraph00 <- graph_from_data_frame(edges01,
directed = FALSE,
vertices = tax00_surface)
```
```{r}
plot(SpearGraph00)
```
The moon shape here is all of the nodes not connected to anything. Lets get rid of them:
```{r}
SpearGraph01 <- SpearGraph00 %>% delete_isolated()
plot(SpearGraph01)
```
And now we have the classic "hairball". Very busy, hard to make sense of anything.
We can plot a little differently.
```{r}
plot(SpearGraph01,
vertex.size = 1,
vertex.label = NA,
edge.color = adjustcolor("black", alpha = 0.2))
```
Sometimes changing the layout helps.
But in this case, everything still looks pretty bad.
```{r}
## Don't ask me what this function does. Just thank JL Weissman for sharing it with me.
## You can use it too now.
ordered.degree <- function(graph){
x <- degree(graph)
y <- numeric(length(x))
i_start <- 1
for(i in min(x):max(x)){
i_finish <- sum(x==i) + i_start - 1
y[which(x==i)] <- i_start:i_finish
i_start <- i_finish + 1
}
return(y - min(y) + 1)
}
loc_layout <- layout_in_circle(SpearGraph01, order = ordered.degree(SpearGraph01))
plot(SpearGraph01,
vertex.size = 1,
vertex.label = NA,
edge.width = 1,
edge.color = adjustcolor("black", alpha = 0.2),
layout = loc_layout
)
```
Hairballs contain a lot of information but aren't so useful to look at because everything is connected to everything. However, statistics can still apply to them.
**Question:** What things can we learn about the topology of correlations from community structure from this network?
I usually try to filter networks, removing some nodes and edges to focus on others. These are often more informative.
One option is just to look at the strongest correlations. What are our correlation strengths anyway?
```{r}
edges01 %>%
ggplot(aes(x = rho)) + geom_histogram()
```
Lots of weeek correlations, fewer strong ones. There appears to be a cutoff around |rho| of 0.25 where lower values aren't statistically significant. There are more positive correlationsthan negative.
Lets just take the ones where the absolute value is larger than 0.6
```{r}
thresh = 0.6
edges02<- edges01 %>%
filter(abs(rho)>= thresh)
```
```{r}
SpearGraph02 <- graph_from_data_frame(edges02,
directed = FALSE)
plot(SpearGraph02,
vertex.size = 5,
vertex.label = NA,
edge.color = "gray10")
```
**Question:** What happens to the graph if you re-run the code chunk?
**Question:** I picked a cutoff of |rho| = 0.6 because it gave me a pretty output. Try changing my cutoff and see how the graph changes.
# Better looking graphs
Some of our correlations are negative. Lets identify them by changing their color.
We do this by adding a color column to the edges table.
And lets also make more significant edges thicker.
```{r}
edges03 <- edges02 %>%
mutate(color = if_else(rho<0, "red", "black")) %>%
mutate(width = (abs(rho) - thresh)* 20)
SpearGraph03 <- graph_from_data_frame(edges03,
directed = FALSE)
plot(SpearGraph03,
vertex.size = 5,
vertex.label = NA)
```
Question: What can you say about the negative correlations in the graph.
# Color coding the nodes
We can also provide `igraph` with a table of data about the nodes, with the first column being the same as the names defined in the edges table
tax00_surface gets us close to having all the data we need for a nodes table, the first column is indeed the node names and the other columns provide data. We can add more columns which contain `igraph` attributes. When `igraph` sees these columns, it uses them.
```{r}
phylum_colors <- tax00_surface$Phylum %>% unique %>% enframe(value = "Phylum") %>%
mutate(color = c("white", "gray", "yellow", "green", "blue", "red", "goldenrod"))
phylum_colors
nodes01 <- tax00_surface %>% left_join(phylum_colors)
```
```{r}
SpearGraph04 <- graph_from_data_frame(edges03,
directed = FALSE,
vertices = nodes01) %>%
delete_isolated()
plot(SpearGraph04,
vertex.size = 5,
vertex.label = NA)
```
**Question:** Do you see any patterns about how phyla cluster?
# Playing around with layouts
Circlular layout. I think this is worse.
```{r}
SpearGraph04 <- graph_from_data_frame(edges03,
directed = FALSE,
vertices = nodes01) %>%
delete_isolated()
loc_layout <- layout_in_circle(SpearGraph04, order = ordered.degree(SpearGraph04))
plot(SpearGraph04,
vertex.size = 5,
vertex.label = NA,
layout = loc_layout)
```
```{r}
SpearGraph04 <- graph_from_data_frame(edges03,
directed = FALSE,
vertices = nodes01) %>%
delete_isolated()
loc_layout <- layout_on_grid(SpearGraph04)
plot(SpearGraph04,
vertex.size = 5,
vertex.label = NA,
layout = loc_layout)
```
**Task:** Plot SpearGraph04 using a different layout.
# Protobacteria Only
Here is a network of just proteobacteria.
```{r}
# Identify which vertices are proteobacteria
Proteos <- V(SpearGraph01)$Phylum == "Proteobacteria"
# There are NA values. Those aren't proteobacteria, so replace with FALSE
Proteos[is.na(Proteos)] <- FALSE
# Delete all of the non protobacteria
SpearGraphPhylum01 <- delete_vertices(SpearGraph01, V(SpearGraph01)[!Proteos])
```
```{r}
SpearGraphPhylum01 %>% delete_isolated() %>% plot()
```
**Task:** This network looks too busy to be useful. Please modify the network so you show just the strongest edges and color code by *Family*?
# Topography
One can summarize networks with certain relevant statistics. I'll show you three.
Density, mean path length, and transitivity.
## Density
The density of a graph is the ratio of the number of edges and the number of possible edges.
```{r}
vcount(SpearGraph01) # number of nodes
ecount(SpearGraph01) # number of edges
```
Number of possible edges:
https://mathworld.wolfram.com/HandshakeProblem.html
```{r}
possible_edges <- vcount(SpearGraph01) * (vcount(SpearGraph01)-1)/2
ecount(SpearGraph01)/possible_edges
```
These questions assume people are working in small groups. If you are doing this alone, pretend you are in a group of four people and answer these.
**Question:** If everybody in your group shook hands with each other, and nobody shook hands with theirself, how many hand-shakes would there be?
**Question:** If one member of your group shook hands with two other people, but no other handshakes happened, what would be the density of the graph of handshakes that actually occurred in your group?
**Question:** If every member of your group shook hands with every member of the other group, how many handshakes would there be?
Or alternatively, using built in functions
```{r}
edge_density(SpearGraph01)
```
Our filtered network has a lower edge density than our unfiltered one, since we've removed a bunch of edges (though also some nodes and therefore possible edges)
```{r}
edge_density(SpearGraph04)
```
## Path Length
Mean path length is the mean number of jumps from one node to another. It only works on fully connected networks, so lets use the hairball one.
Recall that people talk about having "six degrees of separation" between any two people.
https://en.wikipedia.org/wiki/Six_degrees_of_separation
https://igraph.org/r/doc/distances.html
```{r}
mean_distance(SpearGraph01, directed = FALSE)
```
**Question:** Do the microbes have a shorter or longer path in general than people??
You can also see how far every node is from every other if you really want. We are looking at the averages of these.
Here are just the first 10 things but there are lots.
```{r}
distances(SpearGraph01)[1:10, 1:10]
```
```{r}
distance_table(SpearGraph01, directed = FALSE)
```
```{r}
distance_table(SpearGraph04, directed = FALSE)
```
Question: What is distance table telling us about these two networks?
What does $unconnected mean and why is it larger in SpearGraph04 than SpearGraph01?
## Transitivity (Clustering Coefficient)
From the help file:
Transitivity measures the probability that the adjacent vertices of a vertex are connected. This is sometimes also called the clustering coefficient.
Essentially, how likely is it that three nodes are in a triangle shape, rather than a line shape.
Often, I think of it as a measure of clumpyness.
```{r}
transitivity(SpearGraph01)
transitivity(SpearGraph04)
```
**Question:** What is the density, mean path length and transitivity of the network of protobacteria?