Skip to content

Commit

Permalink
add packages
Browse files Browse the repository at this point in the history
  • Loading branch information
chengjun committed Apr 23, 2015
0 parents commit afcd910
Show file tree
Hide file tree
Showing 14 changed files with 587 additions and 0 deletions.
20 changes: 20 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Package: networkdiffusion
Type: Package
Title: Simulating and visualizing network diffusion using R
Version: 0.1
Date: 2015-04-22
Authors: Cheng-Jun Wang
Maintainer: Cheng-Jun Wang <[email protected]>
Description: To Simulate and visualize network diffusion using R.
Depends: R (>= 3.1.0), igraph
License: MIT
LazyData: TRUE
Imports:
igraph,
Rcpp
suggests:
animation, testthat
Suggests: knitr,
testthat
VignetteBuilder: knitr
LinkingTo: Rcpp
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exportPattern("^[[:alpha:]]+")
106 changes: 106 additions & 0 deletions R/diffusion.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# learn more about package authoring with RStudio at: http://r-pkgs.had.co.nz/ Some useful keyboard
# shortcuts for package authoring:
# generate R documentation using roxygen2: 'Cmd + Shift + D' (or running devtools::document())
# Build and Reload Package: 'Cmd + Shift + B'
# Check Package: 'Cmd + Shift + E'
# Test Package: 'Cmd + Shift + T'


####################
# network diffusion
####################
require(igraph)


#' Get the infected nodes
#'
#' @param g A network object generated using igraph.
#' @param transmission_rate A number.
#' @param seed_num The number of seeds.
#' @param random_seed A number for the function set.seed().
#' @return a list of infected nodes (over time).
#' @examples
#' get_infected(barabasi.game(100), 0.4, 1, 2004)
#' get_infected(erdos.renyi.game(100, 0.1), 0.4, 1, 2004)

get_infected = function(g, transmission_rate, seed_num, random_seed){
toss = function(freq) {
tossing = NULL
coins = c(1, 0)
probabilities = c(transmission_rate, 1-transmission_rate )
for (i in 1:freq ) tossing[i] = sample(coins, 1, rep=TRUE, prob=probabilities)
tossing = sum(tossing)
return (tossing)
}

update_diffusers = function(diffusers){
nearest_neighbors = data.frame(table(unlist(neighborhood(g, 1, diffusers))))
nearest_neighbors = subset(nearest_neighbors, !(nearest_neighbors[,1]%in%diffusers))
keep = unlist(lapply(nearest_neighbors[,2],toss))
new_infected = as.numeric(as.character(nearest_neighbors[,1][keep >= 1]))
diffusers = unique(c(diffusers, new_infected))
return(diffusers)
}

set.seed(random_seed); diffusers = sample(V(g),seed_num)
# initialize the infected
infected =list()
infected[[1]]= diffusers
# set the color
E(g)$color = "grey"
V(g)$color = "white"
V(g)$color[V(g)%in%diffusers] = "red"
# get infected nodes
total_time = 1
while(length(infected[[total_time]]) < vcount(g)){
infected[[total_time+1]] = sort(update_diffusers(infected[[total_time]]))
total_time = total_time + 1
}
# return the infected nodes list
return(infected)
}


#' plot the time series of network diffusion
#'
#' @param infected A list of infected nodes (over time)
#' @return plots of two time series.
#' @examples
#' plot_time_series(infected)
#' plot_time_series(infected[1:5])

plot_time_series = function(infected){
num_cum = unlist(lapply(1:length(infected),
function(x) length(infected[[x]]) ))
p_cum = num_cum/node_number
p = diff(c(0, p_cum))
time = 1:length(infected)
plot(p_cum~time, type = "b",
ylab = "CDF", xlab = "Time",
xlim = c(0,length(infected)), ylim =c(0,1))
plot(p~time, type = "h", frame.plot = FALSE,
ylab = "PDF", xlab = "Time",
xlim = c(0,length(infected)), ylim =c(0,1))
}


#' plot the diffusion network diffusion (over time)
#'
#' @param infected A list of infected nodes (over time)
#' @return several plots of diffusion networks.
#' @examples
#' plot_gif(infected)
#' plot_gif(infected[1])

plot_gif = function(infected){
m = 1
while(m <= length(infected)){
V(g)$color = "white"
V(g)$color[V(g)%in%infected[[m]]] = "red"
plot(g, layout =layout.old, edge.arrow.size=0.2)
title(paste( "Time", m))
m = m + 1}
}

# run demos

Binary file added ba.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 17 additions & 0 deletions demo/networkdiffusion.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# generate a social graph
require(igraph)
require(animation)

node_number = 100
g = barabasi.game(node_number)
# set up the layout
set.seed(2014); layout.old = layout.fruchterman.reingold(g, niter = 1000)
# get the infected
infected = get_infected(g, 0.4, 1, 2004)
plot_gif(infected[[2]])
plot_time_series(infected)

saveGIF({
ani.options("convert")
plot_gif(infected)
}, interval = 0.3, movie.name = "ba.gif", ani.width = 600, ani.height = 600)
28 changes: 28 additions & 0 deletions man/get_infected.Rd
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/diffusion.R
\name{get_infected}
\alias{get_infected}
\title{Get the infected nodes}
\usage{
get_infected(g, transmission_rate, seed_num, random_seed)
}
\arguments{
\item{g}{A network object generated using igraph.}

\item{transmission_rate}{A number.}

\item{seed_num}{The number of seeds.}

\item{random_seed}{A number for the function set.seed().}
}
\value{
a list of infected nodes (over time).
}
\description{
Get the infected nodes
}
\examples{
get_infected(barabasi.game(100), 0.4, 1, 2004)
get_infected(erdos.renyi.game(100, 0.1), 0.4, 1, 2004)
}

22 changes: 22 additions & 0 deletions man/plot_gif.Rd
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/diffusion.R
\name{plot_gif}
\alias{plot_gif}
\title{plot the diffusion network diffusion (over time)}
\usage{
plot_gif(infected)
}
\arguments{
\item{infected}{A list of infected nodes (over time)}
}
\value{
several plots of diffusion networks.
}
\description{
plot the diffusion network diffusion (over time)
}
\examples{
plot_gif(infected)
plot_gif(infected[1])
}

22 changes: 22 additions & 0 deletions man/plot_time_series.Rd
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/diffusion.R
\name{plot_time_series}
\alias{plot_time_series}
\title{plot the time series of network diffusion}
\usage{
plot_time_series(infected)
}
\arguments{
\item{infected}{A list of infected nodes (over time)}
}
\value{
plots of two time series.
}
\description{
plot the time series of network diffusion
}
\examples{
plot_time_series(infected)
plot_time_series(infected[1:5])
}

21 changes: 21 additions & 0 deletions networkdiffusion.Rproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Version: 1.0

RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Sweave
LaTeX: pdfLaTeX

AutoAppendNewline: Yes
StripTrailingWhitespace: Yes

BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
PackageRoxygenize: rd,collate,namespace,vignette
3 changes: 3 additions & 0 deletions src/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*.o
*.so
*.dll
4 changes: 4 additions & 0 deletions tests/testthat.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
library(testthat)
library(networkdiffusion)

test_check("networkdiffusion")
7 changes: 7 additions & 0 deletions vignettes/my-vignette.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## ----, fig.show='hold'---------------------------------------------------
plot(1:10)
plot(10:1)

## ----, echo=FALSE, results='asis'----------------------------------------
knitr::kable(head(mtcars, 10))

58 changes: 58 additions & 0 deletions vignettes/my-vignette.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
title: "networkdiffusion"
author: "Cheng-Jun Wang"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Vignette Title}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---

Vignettes are long form documentation commonly included in packages. Because they are part of the distribution of the package, they need to be as compact as possible. The `html_vignette` output type provides a custom style sheet (and tweaks some options) to ensure that the resulting html is as small as possible. The `html_vignette` format:

- Never uses retina figures
- Has a smaller default figure size
- Uses a custom CSS stylesheet instead of the default Twitter Bootstrap style

## Vignette Info

Note the various macros within the `vignette` setion of the metadata block above. These are required in order to instruct R how to build the vignette. Note that you should change the `title` field and the `\VignetteIndexEntry` to match the title of your vignette.

## Styles

The `html_vignette` template includes a basic CSS theme. To override this theme you can specify your own CSS in the document metadata as follows:

output:
rmarkdown::html_vignette:
css: mystyles.css

## Figures

The figure sizes have been customised so that you can easily put two images side-by-side.

```{r, fig.show='hold'}
plot(1:10)
plot(10:1)
```

You can enable figure captions by `fig_caption: yes` in YAML:

output:
rmarkdown::html_vignette:
fig_caption: yes

Then you can use the chunk option `fig.cap = "Your figure caption."` in **knitr**.

## More Examples

You can write math expressions, e.g. $Y = X\beta + \epsilon$, footnotes^[A footnote here.], and tables, e.g. using `knitr::kable()`.

```{r, echo=FALSE, results='asis'}
knitr::kable(head(mtcars, 10))
```

Also a quote using `>`:

> "He who gives up [code] safety for [code] speed deserves neither."
([via](https://twitter.com/hadleywickham/status/504368538874703872))
Loading

0 comments on commit afcd910

Please sign in to comment.