---
title: "networks"
author: "Claus"
date: "2023-05-08"
output: html_document
---

## Exercise 1


```{r}
nodes <- data.frame(id=1:9,
                    type=rep(c("A", "C", "B"), times=c(4,3,2)))

links <- data.frame(from=c(1, 1, 1, 3, 3, 3, 5, 5, 6, 7, 8),
                    to  =c(2, 3, 4, 4, 5, 8, 6, 8, 7, 8, 9),
                    type=c("HEJ"),
                    weight=1)

links
library("igraph")
g <- graph_from_data_frame(links, vertices = nodes, directed = FALSE)
plot(g)


centr_degree(g)

A <- as_adjacency_matrix(g)
A                    


A %*% A

A %*% A %*% A


```


## Facebook


```{r}

gg <- read_graph(url("https://biostatistics.dk/teaching/advtopicsB/download/facebook.txt"), directed = FALSE)

#gg3 <- read_graph(url("https://biostatistics.dk/teaching/advtopicsB/download/facebook.txt"), directed = TRUE)


gg
plot(gg)

centr_degree(gg)


gg2 <- simplify(gg)

centr_degree(gg2)


hist(centr_degree(gg2)$res)

labels(gg)

closeness(gg)

```


## Simulating graphs

```{r}
brg <- sample_gnp(1000, 1/1000)
brg2 <- sample_gnp(1000, 1/100)

plot(brg)
plot(brg2)

table(centr_degree(brg)$res)
table(centr_degree(brg2)$res)


mean(centr_degree(brg2)$res)


hist(
sapply(1:100, function(i) { 
  mean(
    centr_degree(sample_gnp(1000, 1/100)
  )$res) })
)

plot(sample_pa(10, .3, directed=FALSE))

plot(sample_smallworld(1, 50, 1, 0.25))

plot(sample_sbm(100, cbind(c(.4, 0.01), c(0.01, 0.4)), block.sizes = c(30, 70)))

```



## Fitting models

```{r}


gg2
str(gg2)


phat <- 2519 / (348 * 347/2)


phat

table(centr_degree(gg2)$res)

table(
centr_degree(sample_gnp(348, phat))$res)



# SFM

degs <- centr_degree(gg2)$res

table(degs)

relfreq <- table(degs)/sum(table(degs))
relfreq

degs <- centr_degree(gg2)

relfreq <- table(degs)[-1]/sum(table(degs)[-1])
logk <- log(as.numeric(labels(relfreq)$degs))

plot(logk, log(relfreq))

lm(log(relfreq) ~ logk)


lm(log(relfreq) ~ logk, weight=table(degs)[-1])


nzdegs <- degs[degs>0]



fit_power_law(degs+1)
fit_power_law(nzdegs, implementation = "R.mle")


```


