network/ 0000755 0001762 0000144 00000000000 14725552272 011756 5 ustar ligges users network/tests/ 0000755 0001762 0000144 00000000000 14317471453 013116 5 ustar ligges users network/tests/general.tests2.R 0000644 0001762 0000144 00000006453 14363704145 016107 0 ustar ligges users #Set to TRUE to run tests
if(FALSE){
# additional tests of misc network functionality split off from general.tests.R to avoid speed warnings
library(network)
# ----- check memory saftey with a big assignment ---
net<-network.initialize(100000)
net<-add.edges(net,1:99999,2:100000)
set.edge.attribute(net,'LETTERS',LETTERS)
# --- tests for get.induced.subgraph additions --
data(emon)
# extract the network of responders in MtStHelens network with interaction Frequency of 4
subG4<-get.inducedSubgraph(emon$MtStHelens,eid=which(emon$MtStHelens%e%'Frequency'==4))
if(network.size(subG4)!=24){
stop('wrong size eid induced subgraph')
}
if (any(subG4%e%'Frequency'!=4)){
stop('bad edges in eid induced subgraph')
}
# checks for error conditions
# can't specify eid with v or alter
# get.inducedSubgraph(v=1:2,emon$MtStHelens,eid=which(emon$MtStHelens%e%'Frequency'==4))
# get.inducedSubgraph(alter=1:2,emon$MtStHelens,eid=which(emon$MtStHelens%e%'Frequency'==4))
# get.inducedSubgraph(emon$MtStHelens,eid=200:300)
# ---- tests for specific bugs/edgecases -----
# ticket #180 (used to throw error if no edges exist)
set.edge.attribute(network.initialize(3),"test","a")
# check for network of zero size --used to give error ticket #255
set.vertex.attribute(network.initialize(0),'foo','bar')
# check for is.na.network problems #619
x2<-network.initialize(3)
x2[1,2]<-NA
if(is.na.network(x2)[1,2]!=1){
stop('problem iwth is.na.netowrk')
}
# check for na problems in which.matrix.type #926
mat <- matrix(rbinom(200, 1, 0.2), nrow = 20)
naIndices <- sample(1:200, 20)
mat[naIndices] <- NA
nw <- network(mat)
# ---- check for undirected loops getID cases #327 #609 -----
net<-network.initialize(2,loops=TRUE,directed=FALSE)
net[1,1]<-1
net[1,2]<-1
net[2,2]<-1
if(get.edgeIDs(net,v=1,alter=1)!=1){
stop("problem with get.edgeIDs on undirected network with loops")
}
if(get.edgeIDs(net,v=2,alter=2)!=3){
stop("problem with get.edgeIDs on undirected network with loops")
}
net<-network.initialize(2,loops=TRUE,directed=FALSE)
net[1,2]<-1
if(length(get.edgeIDs(net,v=2,alter=2))>0){
stop("problem with get.edgeIDs on undirected network with loops")
}
# check for problem with as.network.edgelist with zero edges #1138
result1 <- as.matrix.network.edgelist(network.initialize(5),as.sna.edgelist = TRUE)
if (nrow(result1) != 0){
stop('as.matrix.network.edgelist did not return correct value for net with zero edges')
}
result1a <- tibble::as_tibble(network.initialize(5))
if (nrow(result1a) != 0){
stop('as_tibble.network did not return correct value for net with zero edges')
}
result2<-as.matrix.network.adjacency(network.initialize(5))
if(nrow(result2) != 5 & ncol(result2) != 5){
stop('as.matrix.network.adjacency did not return matrix with correct dimensions')
}
result3<-as.matrix.network.adjacency(network.initialize(0))
if(nrow(result3) != 0 & ncol(result3) != 0){
stop('as.matrix.network.adjacency did not return matrix with correct dimensions')
}
result4<-as.matrix.network.incidence(network.initialize(5))
if(nrow(result4) != 5 & ncol(result4) != 0){
stop('as.matrix.network.incidence did not return matrix with correct dimensions')
}
result5<-as.matrix.network.incidence(network.initialize(0))
if(nrow(result5) != 0 & ncol(result5) != 0){
stop('as.matrix.network.incidence did not return matrix with correct dimensions')
}
#End test
}
network/tests/plotflo.R 0000644 0001762 0000144 00000002367 14363704177 014733 0 ustar ligges users #Set to TRUE to run tests
if(FALSE){
#
# load the library
#
library(network)
#
# attach the sociomatrix for the Florentine marriage data
# This is not yet a graph object.
#
data(flo)
#
# print out the sociomatrix for the Florentine marriage data
#
flo
#
# Create a network object out of the adjacency matrix and print it out
#
nflo <- network(flo,directed=FALSE)
nflo
#
# print out the sociomatrix for the Florentine marriage data
#
print(nflo,matrix.type="adjacency")
#
# plot the Florentine marriage data
#
plot(nflo)
#
# create a vector indicating the Medici family and add it as a covariate to the
# graph object.
#
nflo <- set.vertex.attribute(nflo,"medici",c(0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0))
nflo
#
# create a vector indicating the Medici family for the graph
#
medici <- rep("",nrow(flo))
names(medici) <- dimnames(flo)[[1]]
medici[names(medici)=="Medici"] <- "Medici"
#
# plot the marriage data, highlighting the Medici family
#
plot(nflo,vertex.col=1+get.vertex.attribute(nflo,"medici"))
# plot the emon St. Helens network, with edge widths proportional
# to 'Frequency', and edges labeled by their id
data(emon)
par(mar=c(0,0,0,0))
plot(emon[[5]],edge.label=TRUE,edge.label.cex=0.6,
edge.col='gray',edge.lwd=(emon[[5]]%e%'Frequency')*2)
#End tests
}
network/tests/list.attribute.tests.R 0000644 0001762 0000144 00000004103 14363704157 017356 0 ustar ligges users #Set to TRUE to run tests
if(FALSE){
require(network)
# --------- test list.vertex.attributes ---
net<-network.initialize(3)
list.vertex.attributes(net)
if(!all(list.vertex.attributes(net)==c('na','vertex.names'))){
stop('list.vertex.attribute did not report default attributes corrrectly')
}
set.vertex.attribute(net,'letters',c("a","b","c"))
if(!all(list.vertex.attributes(net)==c('letters','na','vertex.names'))){
stop('list.vertex.attribute did not report added attributes corrrectly')
}
# ----- test list.edge.attributes ----
net<-network.initialize(3)
if(length(list.edge.attributes(net))!=0){
stop("list.edge.attributes did not return empty list for network with no edges")
}
add.edges(net,1,2)
add.edges(net,2,3)
if(list.edge.attributes(net)!='na'){
stop("list.edge.attributes did not return 'na' for network with only edges")
}
set.edge.attribute(net,'letter',c("a","b"))
if(!all(list.edge.attributes(net)==c('letter','na'))){
stop("list.edge.attributes did not return attribute names for network with edges")
}
delete.edges(net,eid=1)
if(!all(list.edge.attributes(net)==c('letter','na'))){
stop("list.edge.attributes did not return attribute names for network deleted edge")
}
# ---- test list.network.attributes ----
net<-network.initialize(3)
if(!all(list.network.attributes(net)==c("bipartite", "directed", "hyper","loops","mnext", "multiple","n" ))){
stop("list.network.attributes returned unexpected values for default attributes of a network")
}
set.network.attribute(net,'letter',"a")
if(!all(list.network.attributes(net)==c("bipartite", "directed", "hyper","letter","loops","mnext", "multiple","n" ))){
stop("list.network.attributes returned unexpected values for network with attribute added")
}
# ----- tests for printing function for edges cases ------
net<-network.initialize(100)
net%n%'a_matrix'<-matrix(1:100,nrow=10,ncol=10)
net%n%'a_null'<-NULL
net%n%'a_list'<-list(part1=list(c("A","B")),part2=list("c"))
net%n%'a_desc_vec'<-numeric(rep(100,1))
net%n%'a_net'<-network.initialize(5)
print.network(net)
#End tests
}
network/tests/general.tests.R 0000644 0001762 0000144 00000017107 14363704151 016020 0 ustar ligges users #The following battery of tests is intended to verify the functionality of
#the network library
#Set to TRUE to run tests
if(FALSE){
library(network)
# ----- check assigning multiple attribute values in a single call ------
test<-network.initialize(3)
set.vertex.attribute(test,c('a','b'),c(1,2))
if(!all(test%v%'a'==c(1,1,1) & test%v%'b'==c(2,2,2))){
stop('setting multiple attribute values with set.vertex.attribute failed')
}
test<-network.initialize(3)
set.vertex.attribute(test,list('a','b'),c(1,2))
if(!all(test%v%'a'==c(1,1,1) & test%v%'b'==c(2,2,2))){
stop('setting multiple attribute values with set.vertex.attribute failed')
}
test<-network.initialize(3)
set.vertex.attribute(test,c('a','b'),list(c(1,2,3),c(4,5,6)))
if(!all(test%v%'a'==c(1,2,3) & test%v%'b'==c(4,5,6))){
stop('setting multiple attribute values with set.vertex.attribute failed')
}
test<-network.initialize(3)
set.vertex.attribute(test,c('a','b'),list(list(1,2,3),list(4,5,6)))
if(!all(test%v%'a'==c(1,2,3) & test%v%'b'==c(4,5,6))){
stop('setting multiple attribute values with set.vertex.attribute failed')
}
test<-network.initialize(3)
obj<-list(one='a complex object',two=c('with muliple','parts'))
set.vertex.attribute(test,c('a','b'),list(list(as.list(obj)),list(as.list(obj))))
if(!all(all.equal(get.vertex.attribute(test,'a',unlist=FALSE)[[1]],obj) & all.equal(get.vertex.attribute(test,'b',unlist=FALSE)[[1]],obj))){
stop('setting multiple attribute values with list values in set.vertex.attribute failed')
}
# check assignment to list of networks
net <- network.initialize(2)
netlist <- list(net)
set.network.attribute(netlist[[1]],"test","a value")
if (!"test" %in% list.network.attributes(netlist[[1]]))
stop('assignment to list of networks failed')
# test multiple assignment for network
test<-network.initialize(3)
set.network.attribute(test,c("a","b"),1:2)
if (!all(test%n%'a'==1,test%n%'b'==2)){
stop('mulltiple attribute assignment failed for set.network.attribute')
}
test<-network.initialize(3)
set.network.attribute(test,list("a","b"),as.list(1:2))
if (!all(test%n%'a'==1,test%n%'b'==2)){
stop('mulltiple attribute assignment failed for set.network.attribute')
}
# test multiple assignment for edges
test<-network.initialize(3)
add.edges(test,tail=1:3,head=c(2,3,1))
net<-test
set.edge.attribute(net,c("a","b"),1:2)
if (!all(net%n%'a'==1,net%n%'b'==2)){
stop('mulltiple attribute assignment failed for set.edge.attribute')
}
net<-test
set.edge.attribute(net,c('a','b'),list(c(1,2,3),c(4,5,6)))
if(!all(net%e%'a'==c(1,2,3) & net%e%'b'==c(4,5,6))){
stop('setting multiple attribute values with set.edge.attribute failed')
}
net<-test
set.edge.attribute(net,c('a','b'),list(list(1,2,3),list(4,5,6)))
if(!all(net%e%'a'==c(1,2,3) & net%e%'b'==c(4,5,6))){
stop('setting multiple attribute values with set.edge.attribute failed')
}
net<-test
obj<-list(one='a complex object',two=c('with muliple','parts'))
set.edge.attribute(net,c('a','b'),list(list(as.list(obj)),list(as.list(obj))))
if(!all(all.equal(get.edge.attribute(net,'a',unlist=FALSE)[[1]],obj) & all.equal(get.edge.attribute(net,'b',unlist=FALSE)[[1]],obj))){
stop('setting multiple attribute values with list values in set.edge.attribute failed')
}
# ---- checks for get.edge.attribute overloading and omit args ----
net<-network.initialize(3)
add.edges(net,c(1,2,3),c(2,3,1))
set.edge.attribute(net,'test',"a")
if(!all(get.edge.attribute(net,'test')==c("a","a","a"))){stop("overloading of get.edge.attribute to get.edge.value not working correctly ")}
# check list output of get.edge.attribute with deleted.edges.omit
delete.edges(net,2)
set.edge.attribute(net,'foo','bar',1)
if(!identical(list('bar',NULL,NULL),get.edge.attribute(net,'foo',unlist=FALSE, deleted.edges.omit = FALSE))){
stop("deleted.edges.omit argument causing bad return values in get.edge.attribute ")
}
if(!identical(list('bar',NULL),get.edge.attribute(net,'foo',unlist=FALSE, deleted.edges.omit = TRUE))){
stop("deleted.edges.omit argument causing bad return values in get.edge.attribute ")
}
# check unlisted output of get.edge.attribute with na.omit and deleted.edges.omit
if(!identical(c('bar'),get.edge.attribute(net,'foo',unlist=TRUE,deleted.edges.omit=TRUE))){
stop("omission argument causing bad return values in get.edge.attribute")
}
if(!identical(c('bar'),get.edge.attribute(net,'foo',unlist=TRUE,deleted.edges.omit=TRUE))){
stop("omission arguments causing bad return values in get.edge.attribute")
}
# check for null.na recoding of non-set attributes
if(!identical(c('bar'),get.edge.attribute(net,'foo',unlist=TRUE,null.na=FALSE))){
stop("null.na arguments causing bad return values in get.edge.attribute")
}
if(!identical(c('bar',NA),get.edge.attribute(net,'foo',unlist=TRUE,null.na=TRUE))){
stop("null.na arguments causing bad return values in get.edge.attribute")
}
if(!identical(list('bar',NULL,NULL),get.edge.attribute(net,'foo',unlist=FALSE,null.na=FALSE))){
stop("null.na arguments causing bad return values in get.edge.attribute")
}
if(!identical(list('bar',NULL,NA),get.edge.attribute(net,'foo',unlist=FALSE,null.na=TRUE))){
stop("null.na arguments causing bad return values in get.edge.attribute")
}
#mark an edge as missing to test na.omit
set.edge.attribute(net,'na',TRUE,e=1)
# check that values corresponding to missing edges are ommited
if(!identical(list('bar',NULL,NULL),get.edge.attribute(net,'foo',unlist=FALSE,na.omit=FALSE))){
stop("na.omit argument causing bad return values in get.edge.attribute")
}
if(!identical(list(NULL,NULL),get.edge.attribute(net,'foo',unlist=FALSE,na.omit=TRUE))){
stop("na.omit argument causing bad return values in get.edge.attribute")
}
if(!identical(c('bar'),get.edge.attribute(net,'foo',unlist=TRUE,na.omit=FALSE))){
stop("na.omit argument causing bad return values in get.edge.attribute")
}
if(!identical(NULL,get.edge.attribute(net,'foo',unlist=TRUE,na.omit=TRUE))){
stop("na.omit argument causing bad return values in get.edge.attribute")
}
# check for behavior when querying the 'na' attribute
if(!identical(c(TRUE,FALSE),get.edge.attribute(net,'na',na.omit=FALSE))){
stop("get.edge.attribute did not return correct values for 'na' attribute with na.omit=FALSE")
}
if(!identical(c(FALSE),get.edge.attribute(net,'na',na.omit=TRUE))){
stop("get.edge.attribute did not return correct values for 'na' attribute with na.omit=TRUE")
}
# check behavior on a network with no edges
if(!identical(list(),get.edge.attribute(network.initialize(3),'foo',unlist=FALSE))){
stop("get.edge.attribute did not return correct values network with no edges")
}
if(!identical(NULL,get.edge.attribute(network.initialize(3),'foo',unlist=TRUE))){
stop("get.edge.attribute did not return correct values network with no edges")
}
if(!identical(NULL,get.edge.attribute(net,'bar'))){
stop("get.edge.attribute did not return correct values for attribute that does not exist")
}
# check for behavior of attribute values explicitly set to null
net<-network.initialize(3)
net[1,2]<-1
net[1,3]<-1
set.edge.attribute(net,'nullval',list(NULL))
# expect NULL,NULL
if(!identical(list(NULL,NULL),get.edge.attribute(net,'nullval',unlist=FALSE,null.na=FALSE))){
stop("get.edge.attribute not returning NULL values stored as edge attribute correctly")
}
# expect that this should return NULL values, which will dissappear on unlisting
# do NOT want to see NA,NA
if(!identical(NULL,get.edge.attribute(net,'nullval',null.na=FALSE))){
stop("get.edge.attribute not returning NULL values stored as edge attribute correctly")
}
if(!identical(NULL,get.edge.attribute(net,'nullval',null.na=TRUE))){
stop("get.edge.attribute not returning NULL values stored as edge attribute correctly")
}
#End tests
}
network/tests/network.battery.R 0000644 0001762 0000144 00000024075 14363704166 016414 0 ustar ligges users #The following battery of tests is intended to verify the functionality of
#the network library
#Set to TRUE to run tests
if(FALSE){
library(network)
#These functions are intended to mimic functionality from the sna package.
#Said package is not required to use network, but was used in creating this
#battery of tests.
rgraph<-function(n){
m<-matrix(rbinom(n*n,1,0.5),n,n)
diag(m)<-0
m
}
degree<-function(d,cmode = "freeman")
{
n <- dim(d)[1]
diag(d) <- NA
switch(cmode, indegree = apply(d, 2, sum, na.rm = TRUE),
outdegree = apply(d, 1, sum, na.rm = TRUE), freeman = apply(d,
2, sum, na.rm = TRUE) + apply(d, 1, sum, na.rm = TRUE))
}
#gctorture(TRUE) #Uncomment to perform a more intensive (SLOW) test
# ---- Check assignment, deletion, and adjacency for dyadic graphs ----
check<-vector()
temp<-network(matrix(0,5,5))
temp[1,2]<-1 #Add edge
check[1]<-temp[1,2]==1 #Check adjacency
check[2]<-get.network.attribute(temp,"mnext")==2 #Check count
temp[1,2]<-1 #Should have no effect
check[3]<-get.network.attribute(temp,"mnext")==2 #Check count
temp[1,1]<-1 #Should have no effect
check[4]<-temp[1,1]==0 #Shouldn't be present
check[5]<-get.network.attribute(temp,"mnext")==2 #Check count
temp[,2]<-1 #Should add 3 edges
check[6]<-get.network.attribute(temp,"mnext")==5 #Check count
check[7]<-all(temp[,2]==c(1,0,1,1,1)) #Verify row
temp[3:4,3:4]<-1 #Should add 2 edges
check[8]<-get.network.attribute(temp,"mnext")==7 #Check count
temp[,]<-0 #Delete edges
check[9]<-all(temp[,]==matrix(0,5,5)) #Verify that edges were removed
temp[1:2,3:5]<-1 #Add new edges
check[10]<-sum(temp[,])==6 #Check edge sum
temp<-add.vertices(temp,3) #Add vertices
check[11]<-network.size(temp)==8
check[12]<-sum(temp[,])==6 #Edges should still be there
check[13]<-all(temp[,5]==c(1,1,0,0,0,0,0,0))
temp[8,]<-1 #Add edges to new vertex
check[14]<-all(temp[8,]==c(1,1,1,1,1,1,1,0)) #Verify
temp<-delete.vertices(temp,c(7,8)) #Remove vertices
check[15]<-network.size(temp)==6 #Verify removal
check[16]<-sum(temp[,])==6 #Check edge sum
check[17]<-!any(c(7,8)%in%c(sapply(temp$mel,"[[","inl"),sapply(temp$mel,"[[","outl"))) #Make sure they're really gone!
temp<-network(matrix(0,5,5),directed=FALSE,loops=TRUE) #Create undir graph
check[18]<-is.directed(temp)==FALSE #Some simple gal tests
check[19]<-has.loops(temp)==TRUE
temp[1,]<-1
check[20]<-all(temp[,1]==temp[1,]) #Verify edges
temp<-permute.vertexIDs(temp,5:1) #Permute
check[21]<-all(temp[1,]==c(0,0,0,0,1)) #Verify permutation
check[22]<-all(temp[,5]==rep(1,5))
check[23]<-all(get.neighborhood(temp,1)%in%c(5,1)) #Check neighborhoods
check[24]<-all(sort(get.neighborhood(temp,5))==1:5)
check[25]<-length(get.edges(temp,5))==5 #Check get.edges
check[26]<-length(get.edges(temp,5,2))==1
g<-rgraph(10)
temp<-network(g)
check[27]<-all(g==temp[,]) #Yet more edge checkage
check[28]<-all(g[3:1,-(4:3)]==temp[3:1,-(4:3)])
temp[,,,names.eval="newval"]<-matrix(1:100,10,10) #Edge value assignment
check[29]<-all(as.sociomatrix(temp,"newval")==matrix(1:100,10,10)*g)
check[30]<-all(apply(as.matrix.network.incidence(temp),1,sum)==(degree(g,cmode="indegree")-degree(g,cmode="outdegree"))) #Check incidence matrix
check[31]<-all(dim(as.matrix.network.incidence(temp))==c(10,sum(g)))
check[32]<-all(apply(as.matrix.network.incidence(temp,"newval"),1,sum)==(degree(matrix(1:100,10,10)*g,cmode="indegree")-degree(matrix(1:100,10,10)*g,cmode="outdegree")))
check[33]<-all(as.matrix.network.edgelist(temp,"newval")==cbind(row(g)[g>0],col(g)[g>0],matrix(1:100,10,10)[g>0]))
temp[1:3,1:5,names.eval="newval"]<-matrix(1:15,3,5)
check[34]<-all(as.sociomatrix(temp,"newval")[1:3,1:5]==g[1:3,1:5]*matrix(1:15,3,5))
temp[,,"na"]<-TRUE #Verify NA filtering
check[35]<-sum(temp[,,na.omit=TRUE])==0
check[36]<-sum(is.na(temp[,,na.omit=FALSE]))==sum(g)
#---- Check assignment, deletion, and adjacency for hypergraphs ----
temp<-network.initialize(10,directed=F,hyper=T,loops=T)
check[37]<-sum(temp[,])==0
temp<-add.edge(temp,1:4,1:4,"value",list(5))
temp<-add.edge(temp,3:5,3:5,"value",list(6))
temp<-add.edge(temp,4:7,4:7,"value",list(7))
temp<-add.edge(temp,6:10,6:10,"value",list(8))
check[38]<-all(as.matrix.network.incidence(temp)==cbind(c(1,1,1,1,0,0,0,0,0,0),c(0,0,1,1,1,0,0,0,0,0),c(0,0,0,1,1,1,1,0,0,0),c(0,0,0,0,0,1,1,1,1,1)))
check[39]<-all(as.matrix.network.incidence(temp,"value")==cbind(5*c(1,1,1,1,0,0,0,0,0,0),6*c(0,0,1,1,1,0,0,0,0,0),7*c(0,0,0,1,1,1,1,0,0,0),8*c(0,0,0,0,0,1,1,1,1,1)))
check[40]<-all(temp[,]==((as.matrix.network.incidence(temp)%*%t(as.matrix.network.incidence(temp)))>0))
#---- Check coercion and construction methods ----
g<-rgraph(10)
temp<-network(g)
check[41]<-all(temp[,]==g)
temp<-as.network(g*matrix(1:100,10,10),names.eval="value",ignore.eval=FALSE)
check[42]<-all(as.sociomatrix(temp,"value")==g*matrix(1:100,10,10))
temp<-as.network.matrix(as.matrix.network.edgelist(temp,"value"),matrix.type="edgelist",names.eval="value",ignore.eval=FALSE)
check[43]<-all(as.sociomatrix(temp,"value")==g*matrix(1:100,10,10))
temp<-as.network.matrix(as.matrix.network.incidence(temp,"value"),matrix.type="incidence",names.eval="value",ignore.eval=FALSE)
check[44]<-all(as.sociomatrix(temp,"value")==g*matrix(1:100,10,10))
# check functioning of na.rm argument #922
plain<-as.network.matrix(matrix(c(0,1,NA,NA),ncol=2),na.rm=TRUE)
if (network.naedgecount(plain) != 0){
stop('problem with na values in adjacency matrix coericon')
}
plain<-as.network.matrix(matrix(c(0,1,NA,NA),ncol=2),na.rm=FALSE)
if (network.naedgecount(plain) != 1){
stop('problem with na values in adjacnecy matrix coericon')
}
# test for as.matrix.network edgelist bug #935
x <- network.initialize(10)
add.edge(x,1,2)
add.edge(x,2,3)
set.edge.attribute(x,'foo','bar',e=2) # i.e. the edge from 2 to 3
if (!identical(as.matrix.network.edgelist(x,'foo'),structure(c("1", "2", "2", "3", NA, "bar"), .Dim = 2:3, n = 10, vnames = 1:10))){
stop("problem with as.matrix.network.edgelist with attribute and deleted edge")
}
#---- Check attribute assignment/access ----
g<-rgraph(10)
temp<-network(g)
temp<-set.vertex.attribute(temp,"value",1:10)
check[45]<-all(get.vertex.attribute(temp,"value")==1:10)
temp<-delete.vertex.attribute(temp,"value")
check[46]<-all(is.na(get.vertex.attribute(temp,"value")))
temp<-set.vertex.attribute(temp,"value",1:5,c(2,4,6,8,10))
check[47]<-all(get.vertex.attribute(temp,"value")[c(2,4,6,8,10)]==1:5)
temp<-set.network.attribute(temp,"value","pork!")
check[48]<-get.network.attribute(temp,"value")=="pork!"
temp<-delete.network.attribute(temp,"value")
check[49]<-is.null(get.network.attribute(temp,"value"))
temp<-set.edge.attribute(temp,"value",5)
check[50]<-all(get.edge.attribute(temp$mel,"value")==5)
temp<-delete.edge.attribute(temp,"value")
check[51]<-all(is.null(get.edge.attribute(temp$mel,"value")))
temp<-set.edge.value(temp,"value",g*matrix(1:100,10,10))
check[52]<-all(get.edge.value(temp,"value")==(g*matrix(1:100,10,10))[g>0])
check[53]<-all(as.sociomatrix(temp,"value")==(g*matrix(1:100,10,10)))
#---- Check additional operators ----
g<-rgraph(10)
temp<-network(g,names.eval="value",ignore.eval=FALSE)
temp2<-network(g*2,names.eval="value",ignore.eval=FALSE)
check[54]<-all(g==as.sociomatrix(temp+temp2))
check[55]<-all(g*3==as.sociomatrix(sum(temp,temp2,attrname="value"),"value"))
check[56]<-all(g==as.sociomatrix(temp*temp2))
check[57]<-all(g*2==as.sociomatrix(prod(temp,temp2,attrname="value"),"value"))
check[58]<-all(0==as.sociomatrix(temp-temp2))
check[59]<-all(-g==as.sociomatrix(sum(temp,-as.sociomatrix(temp2,"value"),attrname="value"),"value"))
check[60]<-all(((g%*%g)>0)==as.sociomatrix("%c%.network"(temp,temp2)))
check[61]<-all(((g%*%g)>0)==as.sociomatrix(temp%c%temp2))
check[62]<-all(((!temp)[,]==!g)[diag(10)<1])
check[63]<-all((temp|temp2)[,]==g)
check[64]<-all((temp&temp2)[,]==g)
temp%v%"value"<-1:10
check[65]<-all(temp%v%"value"==1:10)
temp%n%"value"<-"pork!"
check[66]<-temp%n%"value"=="pork!"
# ---- Check to ensure that in-place modification is not producing side effects ----
g<-network.initialize(5); checkg<-g; add.vertices(g,3)
check[67]<-(network.size(checkg)==5)&&(network.size(g)==8)
g<-network.initialize(5); checkg<-g; delete.vertices(g,2)
check[68]<-(network.size(checkg)==5)&&(network.size(g)==4)
g<-network.initialize(5); checkg<-g; add.edge(g,2,3)
check[69]<-(sum(checkg[,])==0)&&(sum(g[,])==1)
g<-network.initialize(5); checkg<-g; add.edges(g,c(2,2,2),c(1,3,4))
check[70]<-(sum(checkg[,])==0)&&(sum(g[,])==3)
g<-network.initialize(5); checkg<-g; g%v%"boo"<-1:5
check[71]<-all(is.na(checkg%v%"boo"))&&all(g%v%"boo"==1:5)
g<-network.initialize(5); checkg<-g; g%n%"boo"<-1:5
check[72]<-is.null(checkg%n%"boo")&&all(g%n%"boo"==1:5)
g<-network.initialize(5); g[1,]<-1; checkg<-g; g%e%"boo"<-col(matrix(0,5,5))
check[73]<-is.null(checkg%e%"boo")&&all(g%e%"boo"==2:5)
g<-network.initialize(5); checkg<-g; permute.vertexIDs(g,5:1)
check[74]<-all(checkg%v%"vertex.names"==1:5)&&all(g%v%"vertex.names"==5:1)
g<-network.initialize(5); temp<-(function(){add.vertices(g,3); network.size(g)})()
check[75]<-(network.size(g)==5)&&(temp==8)
g<-network.initialize(5); (function(){g<-network.initialize(4); add.vertices(g,3)})()
check[76]<-(network.size(g)==5)
# check for operators with undirected edge error ticket #279
# nw1 is assigned tail
head
nw2<-network.initialize(3,directed=FALSE)
nw2[2,1]<-1
# Which, the binary network operators don't take into account:
check[77]<-network.edgecount(nw1-nw2)==0 # Should have 0, has 1.
check[78]<-network.edgecount(nw1|nw2)==1 # Should have 1, has 2 (1->2 and 2->1).
check[79]<-network.edgecount(nw1&nw2)==1 # Should have 1, has 0 (since it treats 1->2 and 2->1 differently).
check[80]<-network.edgecount(!nw1)==2 # Should have choose(3,2)-1=2, has 3.
check[81]<-network.edgecount(!nw2)==2 # Should have choose(3,2)-1=2, has 2.
#If everything worked, check is TRUE
if(!all(check)){ #Should be TRUE
stop(paste("network package test failed on test(s):",which(!check)))
}
#End test
}
network/tests/benchmarks 0000644 0001762 0000144 00000000412 13357022000 015132 0 ustar ligges users "elapsed"
"init" 0.947000000000116
"setv" 0.266000000000076
"getv" 0.346000000000004
"listv" 0.130999999999858
"adde" 1.29500000000007
"sete" 3.89800000000014
"gete" 0.196000000000367
"liste" 0.240999999999985
"addmoree" 2.10499999999956
"addmorev" 1.60500000000002
network/tests/pathological.tests.R 0000644 0001762 0000144 00000001315 14363704173 017047 0 ustar ligges users #Set to TRUE to run tests
if(FALSE){
library(network)
if (require(statnet.common,quietly=TRUE)){
opttest({
gctorture(TRUE)
n <- 10
test <- network.initialize(n)
for (i in 1:(n-1)){
for (j in (i+1):n){
cat(i,j,'\n')
get.inducedSubgraph(test,v=i:j)
}
}
gctorture(FALSE)
},'Ticket #180 Test 1','NETWORK_pathology_TESTS')
opttest({
gctorture(TRUE)
test <- network.initialize(10)
delete.vertices(test,5)
gctorture(FALSE)
},'Ticket #180 Test 2','NETWORK_pathology_TESTS')
opttest({
x <- network.initialize(10)
x[,] <- 1
try(set.edge.value(x,'foo',matrix('bar',5,5)))
},'Ticket #827','NETWORK_pathology_TESTS')
}
#End tests
}
network/tests/testthat/ 0000755 0001762 0000144 00000000000 14725552272 014760 5 ustar ligges users network/tests/testthat/test-indexing.R 0000644 0001762 0000144 00000002043 13740520334 017652 0 ustar ligges users test_that("proper error messages for out of bounds indexing (unipartite)",{
nw <- network.initialize(10)
expect_error(nw[1,100], "subscript out of bounds")
expect_error(nw[1,100] <- 1, "subscript out of bounds")
expect_error(nw[100,1], "subscript out of bounds")
expect_error(nw[100,1] <- 1, "subscript out of bounds")
})
test_that("proper error messages (or lack thereof) for out of bounds indexing (bipartite)",{
nw <- network.initialize(10, bipartite=3, directed=FALSE)
expect_error(nw[1,3], "subscript out of bounds")
expect_error(nw[1,3] <- 1, "subscript out of bounds")
expect_error(nw[4,5], "subscript out of bounds")
expect_error(nw[4,5] <- 1, "subscript out of bounds")
expect_error(nw[4,1], NA)
expect_error(nw[5,3], NA)
})
test_that("wildcard assignment (bipartite)",{
nw <- network.initialize(10, bipartite=3, directed=FALSE)
nw[1,] <- 1
expect_equal(network.edgecount(nw), 7) # 7
nw[,4] <- 1
expect_equal(network.edgecount(nw), 9) # 7 + 3 - 1
nw[,] <- 1
expect_equal(network.edgecount(nw), 21) # 3*7
})
network/tests/testthat/test-i22-summary-character.R 0000644 0001762 0000144 00000001125 13740520334 022066 0 ustar ligges users td <- data.frame(
lettres = letters[1:10],
values = 1:10,
stringsAsFactors = FALSE
)
# Correct output
correct <-
structure(
c(
"Length:10 ",
"Class :character ",
"Mode :character ",
NA,
NA,
NA,
"Min. : 1.00 ",
"1st Qu.: 3.25 ",
"Median : 5.50 ",
"Mean : 5.50 ",
"3rd Qu.: 7.75 ",
"Max. :10.00 "
),
.Dim = c(6L, 2L),
.Dimnames = list(c("", "", "", "", "", ""), c(" lettres", " values")),
class = "table"
)
actual <- summary(td)
expect_identical(actual, correct)
network/tests/testthat/test-dataframe.R 0000644 0001762 0000144 00000066602 14317402074 020005 0 ustar ligges users test_that("invalid or conflicting arguments throw", {
edge_df <- data.frame(from = 1:3, to = 4:6)
expect_error(
as.network(edge_df, directed = "should be true or false"),
"The following arguments must be either `TRUE` or `FALSE`:\n\t- directed",
fixed = TRUE
)
expect_error(
as.network(edge_df, hyper = NULL),
"The following arguments must be either `TRUE` or `FALSE`:\n\t- hyper",
fixed = TRUE
)
expect_error(
as.network(edge_df, loops = NA),
"The following arguments must be either `TRUE` or `FALSE`:\n\t- loops",
fixed = TRUE
)
expect_error(
as.network(edge_df, bipartite = 1),
"The following arguments must be either `TRUE` or `FALSE`:\n\t- bipartite",
fixed = TRUE
)
hyper_edge_df <- data.frame(from = c("a,b", "b,c"), to = c("c,d", "e,f"),
stringsAsFactors = FALSE)
hyper_edge_df[] <- lapply(hyper_edge_df, strsplit, split = ",")
expect_warning(
as.network(hyper_edge_df, hyper = TRUE, directed = FALSE),
"If `hyper` is `TRUE` and `directed` is `FALSE`, `loops` must be `TRUE`.",
fixed = TRUE
)
expect_error(
suppressWarnings(
as.network(hyper_edge_df, hyper = TRUE,
bipartite = TRUE, loops = TRUE, directed = FALSE)
),
"Both `hyper` and `bipartite` are `TRUE`, but bipartite hypergraphs are not supported.",
fixed = TRUE
)
})
test_that("simple networks are built correctly", {
simple_edge_df <- data.frame(.tail = c("b", "c", "c", "d", "d", "e"),
.head = c("a", "b", "a", "a", "b", "a"),
time = 1:6,
stringsAsFactors = FALSE)
simple_vertex_df <- data.frame(vertex.names = letters[1:5],
type = letters[1:5],
stringsAsFactors = FALSE)
expect_s3_class(
as.network(x = simple_edge_df),
"network"
)
expect_s3_class(
as.network(x = simple_edge_df, vertices = simple_vertex_df),
"network"
)
expect_true(
is.directed(as.network(x = simple_edge_df))
)
expect_false(
is.directed(as.network(x = simple_edge_df, directed = FALSE))
)
expect_false(
has.loops(as.network(x = simple_edge_df))
)
expect_false(
is.multiplex(as.network(x = simple_edge_df))
)
expect_equal(
network.edgecount(as.network(x = simple_edge_df)),
nrow(simple_edge_df)
)
expect_equal(
network.size(as.network(x = simple_edge_df)),
nrow(simple_vertex_df)
)
simple_g <- as.network(x = simple_edge_df, vertices = simple_vertex_df)
delete.edges(simple_g, 2)
expect_identical(
`rownames<-`(simple_edge_df[-2, ], NULL),
as.data.frame(simple_g)
)
delete.vertices(simple_g, 2)
expect_identical(
`rownames<-`(simple_vertex_df[-2, , drop = FALSE], NULL),
as.data.frame(simple_g, unit = "vertices")
)
})
test_that("simple and complex edge/vertex/R-object attributes are safely handled", {
vertex_df <- data.frame(name = letters[5:1],
lgl_attr = c(TRUE, FALSE, TRUE, FALSE, TRUE),
int_attr = as.integer(seq_len(5)),
dbl_attr = as.double(seq_len(5)),
chr_attr = LETTERS[1:5],
date_attr = seq.Date(as.Date("2019-12-22"),
as.Date("2019-12-26"),
by = 1),
dttm_attr = as.POSIXct(
seq.Date(as.Date("2019-12-22"), as.Date("2019-12-26"), by = 1)
),
stringsAsFactors = FALSE)
attr(vertex_df$date_attr, "tzone") <- "PST"
attr(vertex_df$dttm_attr, "tzone") <- "EST"
vertex_df$list_attr <- replicate(5, LETTERS, simplify = FALSE)
vertex_df$mat_list_attr <- replicate(5, as.matrix(mtcars), simplify = FALSE)
vertex_df$df_list_attr <- replicate(5, mtcars, simplify = FALSE)
vertex_df$sfg_attr <- list(
structure(c(1, 2, 3), class = c("XY", "POINT", "sfg")),
structure(1:10, .Dim = c(5L, 2L), class = c("XY", "MULTIPOINT", "sfg")),
structure(1:10, .Dim = c(5L, 2L), class = c("XY", "LINESTRING", "sfg")),
structure(list(structure(c(0, 10, 10, 0, 0, 0, 0, 10, 10, 0), .Dim = c(5L, 2L)),
structure(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1), .Dim = c(5L, 2L)),
structure(c(5, 5, 6, 6, 5, 5, 6, 6, 5, 5), .Dim = c(5L, 2L))),
class = c("XY", "MULTILINESTRING", "sfg")),
structure(list(structure(c(0, 10, 10, 0, 0, 0, 0, 10, 10, 0),.Dim = c(5L, 2L)),
structure(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1), .Dim = c(5L, 2L)),
structure(c(5, 5, 6, 6, 5, 5, 6, 6, 5, 5), .Dim = c(5L, 2L))),
class = c("XY", "POLYGON", "sfg"))
)
edge_df <- data.frame(from = c("b", "c", "c", "d", "d", "e"),
to = c("a", "b", "a", "a", "b", "a"),
lgl_attr = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE),
int_attr = as.integer(seq_len(6)),
dbl_attr = as.double(seq_len(6)),
chr_attr = LETTERS[1:6],
date_attr = seq.Date(as.Date("2019-12-22"), as.Date("2019-12-27"),
by = 1),
dttm_attr = as.POSIXct(
seq.Date(as.Date("2019-12-22"), as.Date("2019-12-27"), by = 1)
),
stringsAsFactors = FALSE)
attr(edge_df$date_attr, "tzone") <- "PST"
attr(edge_df$dttm_attr, "tzone") <- "EST"
edge_df$list_attr <- replicate(6, LETTERS, simplify = FALSE)
edge_df$mat_list_attr <- replicate(6, as.matrix(mtcars), simplify = FALSE)
edge_df$df_list_attr <- replicate(6, mtcars, simplify = FALSE)
edge_df$sfg_attr <- list(
structure(c(1, 2, 3), class = c("XY", "POINT", "sfg")),
structure(1:10, .Dim = c(5L, 2L), class = c("XY", "MULTIPOINT", "sfg")),
structure(1:10, .Dim = c(5L, 2L), class = c("XY", "LINESTRING", "sfg")),
structure(list(structure(c(0, 10, 10, 0, 0, 0, 0, 10, 10, 0), .Dim = c(5L, 2L)),
structure(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1), .Dim = c(5L, 2L)),
structure(c(5, 5, 6, 6, 5, 5, 6, 6, 5, 5), .Dim = c(5L, 2L))),
class = c("XY", "MULTILINESTRING", "sfg")),
structure(list(structure(c(0, 10, 10, 0, 0, 0, 0, 10, 10, 0),.Dim = c(5L, 2L)),
structure(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1), .Dim = c(5L, 2L)),
structure(c(5, 5, 6, 6, 5, 5, 6, 6, 5, 5), .Dim = c(5L, 2L))),
class = c("XY", "POLYGON", "sfg")),
structure(list(list(structure(c(0, 10, 10, 0, 0, 0, 0, 10, 10, 0), .Dim = c(5L, 2L)),
structure(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1), .Dim = c(5L, 2L)),
structure(c(5, 5, 6, 6, 5, 5, 6, 6, 5, 5), .Dim = c(5L, 2L))),
list(structure(c(12, 22, 22, 12, 12, 12, 12, 22, 22, 12), .Dim = c(5L, 2L)),
structure(c(13, 13, 14, 14, 13, 13, 14, 14, 13, 13), .Dim = c(5L, 2L))),
list(structure(c(24, 34, 34, 24, 24, 24, 24, 34, 34, 24), .Dim = c(5L, 2L)))),
class = c("XY", "MULTIPOLYGON", "sfg"))
)
g_many_attrs <- as.network(edge_df, vertices = vertex_df)
# edge attributes ======================================================================
# bare atomic vectors
expect_identical(
get.edge.attribute(g_many_attrs, "lgl_attr"),
edge_df$lgl_attr
)
expect_identical(
get.edge.attribute(g_many_attrs, "int_attr"),
edge_df$int_attr
)
expect_identical(
get.edge.attribute(g_many_attrs, "dbl_attr"),
edge_df$dbl_attr
)
expect_identical(
get.edge.attribute(g_many_attrs, "chr_attr"),
edge_df$chr_attr
)
# atomic vectors w/ attributes
# TODO is there a way to get atomic vectors back while preserving attributes?
# `c()` `v/sapply()` strip attributes
edge_date_attr <- get.edge.attribute(g_many_attrs, "date_attr", unlist = FALSE)
edge_date_attr_to_test <- `attributes<-`(unlist(edge_date_attr),
attributes(edge_date_attr[[1]]))
expect_identical(
edge_date_attr_to_test,
edge_df$date_attr
)
edge_dttm_attr <- get.edge.attribute(g_many_attrs, "dttm_attr", unlist = FALSE)
edge_dttm_attr_to_test <- `attributes<-`(unlist(edge_dttm_attr),
attributes(edge_dttm_attr[[1]]))
expect_identical(
edge_dttm_attr_to_test,
edge_df$dttm_attr
)
# list of bare atomic vectors
expect_identical(
get.edge.attribute(g_many_attrs, "list_attr", unlist = FALSE),
edge_df$list_attr
)
# list of vectors with attributes
expect_identical(
get.edge.attribute(g_many_attrs, "mat_list_attr", unlist = FALSE),
edge_df$mat_list_attr
)
# recursive lists
expect_identical(
get.edge.attribute(g_many_attrs, "df_list_attr", unlist = FALSE),
edge_df$df_list_attr
)
# sf objects
expect_identical(
get.edge.attribute(g_many_attrs, "sfg_attr", unlist = FALSE),
edge_df$sfg_attr
)
# vertex attributes ====================================================================
# bare atomic vectors
expect_identical(
get.vertex.attribute(g_many_attrs, "vertex.names"),
vertex_df[[1]]
)
expect_identical(
get.vertex.attribute(g_many_attrs, "lgl_attr"),
vertex_df$lgl_attr
)
expect_identical(
get.vertex.attribute(g_many_attrs, "int_attr"),
vertex_df$int_attr
)
expect_identical(
get.vertex.attribute(g_many_attrs, "dbl_attr"),
vertex_df$dbl_attr
)
expect_identical(
get.vertex.attribute(g_many_attrs, "chr_attr"),
vertex_df$chr_attr
)
# atomic vectors w/ attributes
# TODO is there a way to get atomic vectors back while preserving attributes?
# `c()` `v/sapply()` strip attributes
vertex_date_attr <- get.vertex.attribute(g_many_attrs, "date_attr", unlist = FALSE)
vertex_date_attr_to_test <- `attributes<-`(unlist(vertex_date_attr),
attributes(vertex_date_attr[[1]]))
expect_identical(
vertex_date_attr_to_test,
vertex_df$date_attr
)
vertex_dttm_attr <- get.vertex.attribute(g_many_attrs, "dttm_attr", unlist = FALSE)
vertex_dttm_attr_to_test <- `attributes<-`(unlist(vertex_dttm_attr),
attributes(vertex_dttm_attr[[1]]))
expect_identical(
vertex_dttm_attr_to_test,
vertex_df$dttm_attr
)
# list of bare atomic vectors
expect_identical(
get.vertex.attribute(g_many_attrs, "list_attr", unlist = FALSE),
vertex_df$list_attr
)
# list of vectors with attributes
expect_identical(
get.vertex.attribute(g_many_attrs, "mat_list_attr", unlist = FALSE),
vertex_df$mat_list_attr
)
# recursive lists
expect_identical(
get.vertex.attribute(g_many_attrs, "df_list_attr", unlist = FALSE),
vertex_df$df_list_attr
)
# sf objects
expect_identical(
get.vertex.attribute(g_many_attrs, "sfg_attr", unlist = FALSE),
vertex_df$sfg_attr
)
# conversion back to data.frame ========================================================
names(edge_df)[[1]] <- ".tail"
names(edge_df)[[2]] <- ".head"
edge_df$sfc_attr <- NULL
names(vertex_df)[[1]] <- "vertex.names"
vertex_df$sfc_attr <- NULL
g_many_attrs <- delete.vertex.attribute(g_many_attrs, "sfc_attr")
g_many_attrs <- delete.edge.attribute(g_many_attrs, "sfc_attr")
expect_identical(
edge_df,
as.data.frame(g_many_attrs)
)
expect_identical(
vertex_df,
as.data.frame(g_many_attrs, unit = "vertices")
)
})
test_that("`multiple` arguments work", {
dir_parallel_edge_df <- data.frame(from = c("a", "a"),
to = c("b", "b"),
stringsAsFactors = FALSE)
expect_error(
as.network(dir_parallel_edge_df),
"`multiple` is `FALSE`, but `x` contains parallel edges."
)
expect_s3_class(
as.network(dir_parallel_edge_df, multiple = TRUE),
"network"
)
expect_true(
is.multiplex(as.network(dir_parallel_edge_df, multiple = TRUE))
)
expect_true(
is.directed(as.network(dir_parallel_edge_df, multiple = TRUE))
)
undir_parallel_edge_df <- data.frame(from = c("a", "b"),
to = c("b", "a"),
stringsAsFactors = FALSE)
expect_s3_class(
as.network(undir_parallel_edge_df),
"network"
)
expect_error(
as.network(undir_parallel_edge_df, directed = FALSE),
"`multiple` is `FALSE`, but `x` contains parallel edges."
)
expect_s3_class(
as.network(undir_parallel_edge_df, directed = FALSE, multiple = TRUE),
"network"
)
expect_true(
is.multiplex(as.network(undir_parallel_edge_df, directed = FALSE, multiple = TRUE))
)
expect_false(
is.directed(as.network(undir_parallel_edge_df, directed = FALSE, multiple = TRUE))
)
})
test_that("`loops` works", {
df_with_loops <- data.frame(from = c("b", "c", "c", "d", "d", "e", "f"),
to = c("a", "b", "a", "a", "b", "a", "f"),
stringsAsFactors = FALSE)
expect_error(
as.network(df_with_loops),
"`loops` is `FALSE`"
)
expect_s3_class(
as.network(df_with_loops, loops = TRUE),
"network"
)
})
test_that("missing vertex names are caught", {
missing_vertex_df <- data.frame(name = letters[1:5],
stringsAsFactors = FALSE)
missing_edge_df <- data.frame(from = c("b", "c", "c", "d", "d", "e", "f"),
to = c("a", "b", "a", "a", "b", "a", "g"),
stringsAsFactors = FALSE)
expect_error(
as.network(missing_edge_df, vertices = missing_vertex_df),
"The following vertices are in `x`, but not in `vertices`:\n\t- f\n\t- g", fixed = TRUE
)
})
test_that("duplicate vertex names are caught", {
dup_vertex_df <- data.frame(name = c("a", "a", "b", "c", "d", "e"),
stringsAsFactors = FALSE)
dup_edge_df <- data.frame(from = c("b", "c", "c", "d", "d", "e"),
to = c("a", "b", "a", "a", "b", "a"),
stringsAsFactors = FALSE)
expect_error(
as.network(dup_edge_df, vertices = dup_vertex_df),
"The following vertex names are duplicated in `vertices`:\n\t- a", fixed = TRUE
)
})
test_that("bad data frames are caught", {
edge_df_with_NAs1 <- data.frame(from = c(letters, NA),
to = c("a", letters),
stringsAsFactors = FALSE)
edge_df_with_NAs2 <- data.frame(from = c(letters, "a"),
to = c(NA, letters),
stringsAsFactors = FALSE)
empty_vertex_df <- data.frame()
expect_error(
as.network(edge_df_with_NAs2),
"The first two columns of `x` cannot contain `NA` values.", fixed = TRUE
)
expect_error(
as.network(edge_df_with_NAs2),
"The first two columns of `x` cannot contain `NA` values.", fixed = TRUE
)
expect_error(
as.network(edge_df_with_NAs1[0, 0]),
"`x` should be a data frame with at least two columns and one row.",
fixed = TRUE
)
expect_error(
as.network(na.omit(edge_df_with_NAs1), vertices = empty_vertex_df, loops = TRUE),
"`vertices` should contain at least one column and row.", fixed = TRUE
)
incompat_edge_types <- data.frame(
from = c("a", "b"),
to = c(1, 2),
stringsAsFactors = FALSE
)
expect_error(
as.network(incompat_edge_types),
"The first two columns of `x` must be of the same type.",
fixed = TRUE
)
non_df_vertices_edge_df <- data.frame(from = 1, to = 2)
non_df_vertices <- list(name = 1:2)
expect_error(
as.network(non_df_vertices_edge_df, vertices = non_df_vertices),
"If provided, `vertices` should be a data frame.",
fixed = TRUE
)
bad_vertex_names_col <- data.frame(name = I(list(1)))
expect_error(
as.network(non_df_vertices_edge_df, vertices = bad_vertex_names_col),
"The first column of `vertices` must be an atomic vector.",
fixed = TRUE
)
incompat_types_edge_df <- data.frame(from = 1:3, to = 4:6)
incompat_types_vertex_df <- data.frame(name = paste(1:6), stringsAsFactors = FALSE)
expect_error(
as.network(incompat_types_edge_df, vertices = incompat_types_vertex_df),
"The first column of `vertices` must be the same type as the value with which they are referenced in `x`'s first two columns.",
fixed = TRUE
)
recursive_edge_df <- data.frame(from = I(list(1:2)), to = 3)
expect_error(
as.network(recursive_edge_df),
"If `hyper` is `FALSE`, the first two columns of `x` should be atomic vectors.",
fixed = TRUE
)
})
test_that("bipartite networks work", {
bip_edge_df <- data.frame(.tail = c("a", "a", "b", "b", "c", "d", "d", "e"),
.head = c("e1", "e2", "e1", "e3", "e3", "e2", "e3", "e1"),
an_edge_attr = letters[1:8],
stringsAsFactors = FALSE)
bip_node_df <- data.frame(vertex.names = c("a", "e1", "b", "e2", "c", "e3", "d", "e"),
node_type = c("person", "event", "person", "event", "person",
"event", "person", "person"),
color = c("red", "blue", "red", "blue", "red", "blue",
"red", "red"),
stringsAsFactors = FALSE)
expect_silent( # vertices already in correct order
as.network(bip_edge_df, directed = FALSE,
vertices = data.frame(name = unique(unlist(bip_edge_df[1:2]))))
)
expect_warning( # warn that vertices are reordered once
as.network(bip_edge_df, directed = FALSE, vertices = bip_node_df,
bipartite = TRUE)
)
expect_silent( # do not warn again in the same session
as.network(bip_edge_df, directed = FALSE, vertices = bip_node_df,
bipartite = TRUE)
)
expect_warning(
as.network(bip_edge_df, vertices = bip_node_df,
bipartite = TRUE),
"If `bipartite` is `TRUE`, edges are interpreted as undirected.", fixed = TRUE
)
expect_warning(
as.network(bip_edge_df, directed = FALSE, vertices = bip_node_df,
bipartite = TRUE, loops = TRUE),
"If `bipartite` is `TRUE`, `loops` must be `FALSE`.", fixed = TRUE
)
bip_g <- as.network(bip_edge_df, directed = FALSE, vertices = bip_node_df,
loops = FALSE, bipartite = TRUE)
expect_identical(
bip_edge_df,
as.data.frame(bip_g)
)
expect_identical(
# tracking modes by vertex order means we have to reorder the data frame
# and reset row.names to test
`rownames<-`(
bip_node_df[order(bip_node_df$node_type == "person", decreasing = TRUE), ],
NULL
),
as.data.frame(bip_g, unit = "vertices")
)
expect_s3_class(
bip_g,
"network"
)
expect_true(
is.bipartite(bip_g)
)
expect_false(
has.loops(bip_g)
)
expect_false(
is.directed(bip_g)
)
expect_identical(
get.network.attribute(bip_g, "bipartite"),
5L
)
expect_identical(
get.vertex.attribute(bip_g, attrname = "node_type"),
c(rep("person", 5), rep("event", 3))
)
expect_identical(
get.vertex.attribute(bip_g, attrname = "vertex.names"),
c("a", "b", "c", "d", "e", "e1", "e2", "e3")
)
expect_identical(
get.edge.attribute(bip_g, attrname = "an_edge_attr"),
letters[1:8]
)
# check if bipartite networks with isolates are caught
bip_isolates_node_df <- data.frame(
vertex.names = c("a", "e1", "b", "e2", "c", "e3", "d", "e", "f", "g"),
stringsAsFactors = FALSE
)
expect_error(
as.network(x = bip_edge_df, directed = FALSE, vertices = bip_isolates_node_df,
bipartite = TRUE),
"`bipartite` is `TRUE`, but the `vertices` you provided contain names that are not present in `x`"
)
bip_isolates_node_df$is_actor <- !grepl("^e\\d$", bip_isolates_node_df$vertex.names)
bip_isoaltes_g <- as.network(x = bip_edge_df, directed = FALSE,
vertices = bip_isolates_node_df,
bipartite = TRUE)
expect_s3_class(
bip_isoaltes_g,
"network"
)
expect_identical(
bip_edge_df,
as.data.frame(bip_isoaltes_g)
)
expect_identical(
`rownames<-`(
bip_isolates_node_df[order(bip_isolates_node_df$is_actor, decreasing = TRUE), ],
NULL
),
as.data.frame(bip_isoaltes_g, unit = "vertices")
)
# use custom `bipartite_col` name
bip_isolates_node_df$my_bipartite_col <- bip_isolates_node_df$is_actor
expect_identical(
as.network(x = bip_edge_df, directed = FALSE, vertices = bip_isolates_node_df,
bipartite = TRUE),
as.network(x = bip_edge_df, directed = FALSE, vertices = bip_isolates_node_df,
bipartite = TRUE, bipartite_col = "my_bipartite_col")
)
# throw errors on invalid `bipartite_col`s
expect_error(
as.network(x = bip_edge_df, directed = FALSE, vertices = bip_isolates_node_df,
bipartite = TRUE, bipartite_col = NA_character_)
)
expect_error(
as.network(x = bip_edge_df, directed = FALSE, vertices = bip_isolates_node_df,
bipartite = TRUE, bipartite_col = list())
)
expect_error(
as.network(x = bip_edge_df, directed = FALSE, vertices = bip_isolates_node_df,
bipartite = TRUE, bipartite_col = c("bad", "arg"))
)
bip_isolates_node_df$is_actor <- as.integer(bip_isolates_node_df$is_actor)
expect_error(
as.network(x = bip_edge_df, directed = FALSE, vertices = bip_isolates_node_df,
bipartite = TRUE),
"`bipartite` is `TRUE` and vertex types are specified via a column in `vertices` named `\"is_actor\"`.\n\t- If provided, all values in `vertices[[\"is_actor\"]]` must be `TRUE` or `FALSE`.",
fixed = TRUE
)
# check if nodes that appear in both of the first 2 `edge` columns are caught
bip_confused_edge_df <- data.frame(
actor = c("a", "a", "b", "b", "c", "d", "d", "e", "e1"),
event = c("e1", "e2", "e1", "e3", "e3", "e2", "e3", "e1", "e2"),
stringsAsFactors = FALSE
)
expect_error(
as.network(x = bip_confused_edge_df, directed = FALSE, bipartite = TRUE),
"`bipartite` is `TRUE`, but there are vertices that appear in both of the first two columns of `x`."
)
})
test_that("hyper-edges work", {
hyper_edge_df <- structure(
list(.tail = list(1:4, 3:5, 4:7, 6:10),
.head = list(1:4, 3:5, 4:7, 6:10),
value = as.double(5:8)),
row.names = 1:4,
class = "data.frame"
)
hyper_target_net <- network.initialize(10, directed = FALSE, hyper = TRUE, loops = TRUE)
hyper_target_net <- add.edge(hyper_target_net, 1:4, 1:4, "value", list(5))
hyper_target_net <- add.edge(hyper_target_net, 3:5, 3:5, "value", list(6))
hyper_target_net <- add.edge(hyper_target_net, 4:7, 4:7, "value", list(7))
hyper_target_net <- add.edge(hyper_target_net, 6:10, 6:10, "value", list(8))
expect_identical(
as.network(hyper_edge_df, directed = FALSE, hyper = TRUE, loops = TRUE),
hyper_target_net
)
expect_identical(
hyper_edge_df,
as.data.frame(hyper_target_net)
)
MtSHbyloc_edge_df <- structure(
list(
.tail = list(
as.integer(c(1, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27)),
as.integer(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20, 26, 27))
),
.head = list(
as.integer(c(1, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27)),
as.integer(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20, 26, 27))
)
),
row.names = 1:2,
class = "data.frame"
)
MtSHbyloc_vertex_df <- data.frame(
vertex.names = 1:27
)
data("emon")
MtSHloc <- emon$MtStHelens %v% "Location"
MtSHimat <- cbind(MtSHloc %in% c("L", "B"), MtSHloc %in% c("NL", "B"))
MtSHbyloc <- network(MtSHimat, matrix.type = "incidence", hyper = TRUE,
directed = FALSE, loops = TRUE)
expect_identical(
as.network(MtSHbyloc_edge_df, directed = FALSE, vertices = MtSHbyloc_vertex_df,
loops = TRUE, hyper = TRUE),
MtSHbyloc
)
expect_identical(
MtSHbyloc_edge_df,
as.data.frame(MtSHbyloc)
)
expect_identical(
MtSHbyloc_vertex_df,
as.data.frame(MtSHbyloc, unit = "vertices")
)
delete.edges(MtSHbyloc, 2)
expect_identical(
`rownames<-`(MtSHbyloc_edge_df[-2, ], NULL),
as.data.frame(MtSHbyloc)
)
delete.vertices(MtSHbyloc, 2)
expect_identical(
`rownames<-`(MtSHbyloc_vertex_df[-2, , drop = FALSE], NULL),
as.data.frame(MtSHbyloc, unit = "vertices")
)
hyper_edges_with_NA <- data.frame(
from = I(list(c(NA, "a", "b"))),
to = I(list(c("c", "d")))
)
expect_error(
as.network(hyper_edges_with_NA, hyper = TRUE),
"`x`'s first two columns contain invalid values."
)
non_hyper_edges <- data.frame(
from = 1:3,
to = 4:6
)
expect_error(
as.network(non_hyper_edges, hyper = TRUE),
"If `hyper` is `TRUE`, the first two columns of `x` should be list columns."
)
incompat_type_hyper_edges <- data.frame(
from = I(list(letters[1:5], 1:5)),
to = I(list(letters[6:10], letters[11:15]))
)
expect_error(
as.network(incompat_type_hyper_edges, hyper = T),
"The values in the first two columns of `x` must be of the same type and cannot be `NULL`, `NA`, or recursive values."
)
loop_hyper_edges <- data.frame(
from = I(list(c("a", "b"))),
to = I(list(c("a", "b")))
)
expect_error(
as.network(loop_hyper_edges, hyper = TRUE),
"`loops` is `FALSE`, but `x` contains loops."
)
})
test_that("edge/vertex-less networks return empty data frames", {
empty_g <- network.initialize(0)
expect_identical(
nrow(as.data.frame(empty_g)),
0L
)
expect_identical(
ncol(as.data.frame(empty_g)),
2L
)
expect_identical(
ncol(as.data.frame(empty_g, attrs_to_ignore = NULL)),
3L
)
expect_identical(
nrow(as.data.frame(empty_g, unit = "vertices")),
0L
)
expect_identical(
ncol(as.data.frame(empty_g, unit = "vertices")),
1L
)
expect_identical(
ncol(as.data.frame(empty_g, unit = "vertices", attrs_to_ignore = NULL)),
2L
)
})
test_that("deleted edges/vertices and na attributes are handled correctly", {
na_edge_df <- data.frame(.tail = c("b", "c", "c", "d", "d", "e"),
.head = c("a", "b", "a", "a", "b", "a"),
na = c(rep(FALSE, 5), TRUE),
stringsAsFactors = FALSE)
na_vertex_df <- data.frame(vertex.names = letters[1:5],
na = c(rep(FALSE, 4), TRUE),
stringsAsFactors = FALSE)
na_g <- as.network(na_edge_df, vertices = na_vertex_df)
expect_identical(
as.data.frame(na_g, na.rm = FALSE, attrs_to_ignore = NULL),
na_edge_df
)
expect_identical(
as.data.frame(na_g, unit = "vertices", na.rm = FALSE, attrs_to_ignore = NULL),
na_vertex_df
)
delete.edges(na_g, 1)
expect_identical(
`rownames<-`(na_edge_df[-c(1, which(na_edge_df$na)), ], NULL),
as.data.frame(na_g, attrs_to_ignore = NULL)
)
delete.vertices(na_g, 1)
expect_identical(
`rownames<-`(na_vertex_df[-c(1, which(na_vertex_df$na)), ], NULL),
as.data.frame(na_g, unit = "vertices", attrs_to_ignore = NULL)
)
})
test_that("as.data.frame.network() handles missing vertex.names ", {
# addresses https://github.com/statnet/network/issues/43
nw_no_vertex.names <- network.initialize(5)
delete.vertex.attribute(nw_no_vertex.names, "vertex.names")
expect_identical(
as.data.frame(nw_no_vertex.names, unit = "vertices"),
data.frame(vertex.names = as.character(1:5))
)
})
network/tests/testthat/test-plot.R 0000644 0001762 0000144 00000007044 13740520334 017031 0 ustar ligges users # various tests for network plotting functions
# mostly recent functionality added by skyebend
# Open null device
pdf(file = NULL, onefile = TRUE)
dev_id <- dev.cur()
# ----- test edge labels ------
ymat<-matrix(c(0,1,2,3, 0,0,0,0, 1,0,0,0, 0,0,0,0),ncol=4)
ynet<-network(ymat,ignore.eval=FALSE,names.eval='weight')
# don't do anything if no value given
plot(ynet,edge.label.col='blue',edge.label.cex='weight')
# use edge ids is if edge.label=TRUE
plot(ynet,edge.label=TRUE)
plot(ynet,edge.label='weight',edge.label.col='blue',edge.label.cex='weight')
# labels for curved edges
plot(ynet,edge.label='weight',edge.label.col='blue',edge.label.cex='weight',usecurve=TRUE)
plot(ynet,edge.label='weight',edge.label.col='blue',edge.label.cex='weight',usecurve=TRUE,edge.curve=0.5)
data(emon)
par(mar=c(0,0,0,0))
plot(emon[[5]],edge.label=TRUE,edge.label.cex=0.6,edge.col='gray',edge.lwd=(emon[[5]]%e%'Frequency')*2)
# test for labeling network with no edges #521
plot(network.initialize(1),edge.label=TRUE)
# test color stuff
col.list<-c('red','#800000','#80000505',NA)
# test is.color for vector NA processing bug #491
if(!all(is.color(col.list)[1:3] & is.na(is.color(col.list)[4]))){
stop('is.color did not correctly recognize colors and NA values in a character vector')
}
col.list<-list('red','#800000','#80000505',NA)
# test is.color for list NA processing bug #491
if(!all(is.color(col.list)[1:3] & is.na(is.color(col.list)[4]))){
stop('is.color did not correctly recognize colors and NA values in a list')
}
# ------------ as.color --------
expect_equal(as.color(c('a','b','c')),1:3) # character
expect_equal(as.color(1:3),1:3) # numeric
expect_equal(as.color(as.factor(c('a','b','c'))),1:3) # factor
expect_equal(as.color(c('red','green','blue')),c('red','green','blue')) # color name
expect_equal(as.color(c(1,0.5,0)),c("#FFFFFF", "#808080", "#000000"))# real valued (gray)
# transparency/ opacity
expect_equal(as.color(c('red','green','blue'),0.5),c("#FF000080", "#00FF0080", "#0000FF80"))
if(R.Version()$major <= 3) expect_equal(as.color(1:3,0.5),c("#00000080", "#FF000080", "#00CD0080")) else expect_equal(as.color(1:3,0.5),c("#00000080", "#DF536B80", "#61D04F80"))
expect_error(as.color(c('red','green','blue'),1.5),regexp = 'opacity parameter must be a numeric value in the range 0 to 1')
# ----- plot fixes ----
plot(network.initialize(5),vertex.lwd=c(1,2,3,5,10))
# test for expansion of label attribute name bug #785
# this should produce a plot with vertices labeled A to E, instead
# used to plot single vertex is labeled with "Label'
test<-network.initialize(5)
set.vertex.attribute(test,'Label',LETTERS[1:5])
plot(test,label='Label')
# replicates non-matching label name
plot(test,label='A')
plot(test,label=1)
# should error if all values are missing
#set.vertex.attribute(test,'bad',NA,v=1:3)
#plot(test,label='bad')
# tests for #673 plot.network.default gives error when rendering labels if two connected vertices have the same position
test<-network.initialize(2)
test[1,2]<-1
plot(test,coord=cbind(c(1,1),c(1,1)),jitter=FALSE,displaylabels=TRUE)
test<-network.initialize(3)
test[1,2:3]<-1
plot(test,coord=cbind(c(1,1,2),c(1,1,2)),jitter=FALSE,displaylabels=TRUE)
# tests for polygon sizes/sides
plot(network.initialize(7),vertex.sides=c(50,4,3,2,1,0,NA),vertex.cex=40,coord=matrix(0,ncol=7,nrow=7),jitter=F,vertex.col='#CCCCCC00',vertex.border =c('red','green','blue','orange'))
plot(network.initialize(7),vertex.sides=c(50,4,3,2,1,0,NA),vertex.cex=0)
plot(network.initialize(7),vertex.sides=c(50,4,3,2,1,0,NA),vertex.cex=NA)
# close the device
dev.off(which = dev_id)
network/tests/testthat/test-read.paj.R 0000644 0001762 0000144 00000024170 14723241675 017550 0 ustar ligges users # test for reading pajek formatted files
# test for case of verticse, but no edges/arcs
tmptest<-tempfile()
cat("*Vertices 2
1 1231062
2 1231095
*Arcs
*Edges
",file=tmptest)
noEdges<-read.paj(tmptest)
expect_equal(network.size(noEdges),2)
expect_equal(network.edgecount(noEdges),0)
# check arcs vs edges parsing
# arcs only
tmptest<-tempfile()
cat("*Vertices 3
1 'A'
2 'B'
3 'C'
*Arcs
1 2 1
1 3 1
",file=tmptest)
arcsOnly<-read.paj(tmptest)
expect_true(is.directed(arcsOnly))
expect_equal(network.edgecount(arcsOnly),2)
# edges only
tmptest<-tempfile()
cat('*Vertices 9
1 "1" 0.3034 0.7561
2 "2" 0.4565 0.6039
3 "3" 0.4887 0.8188
4 "4" 0.5687 0.4184
5 "5" 0.3574 0.4180
6 "6" 0.7347 0.2678
7 "7" 0.9589 0.3105
8 "8" 0.8833 0.1269
9 "9" 0.7034 0.0411
*Arcs
*Edges
1 2 1
1 3 1
2 3 1
2 4 1
2 5 1
4 5 1
4 6 1
6 7 1
6 8 1
6 9 1
7 8 1
8 9 1
',file=tmptest)
edgesOnly<-read.paj(tmptest)
expect_false(is.directed(edgesOnly))
expect_equal(network.edgecount(edgesOnly),12)
# both arcs and edges
# network will be directed, each *edges record will create one arc in each direction
tmptest<-tempfile()
cat("*Vertices 4
1 'A'
2 'B'
3 'C'
4 'D'
*Arcs
1 2 1
1 3 1
*Edges
3 4 1
",file=tmptest)
arcsNEdges<-read.paj(tmptest)
expect_true(is.directed(arcsNEdges))
expect_equal(network.edgecount(arcsNEdges),4)
as.matrix(arcsNEdges)
# ----- error testing
tmptest<-tempfile()
cat("*Vertices 2
1 'A'
2 'B'
*Arcs
1
",file=tmptest)
expect_error(read.paj(tmptest),regexp = 'does not appear to have the required')
tmptest<-tempfile()
cat("*Vertices 2
1 'A'
2 'B'
*Arcs
1 A 1
",file=tmptest)
expect_error(suppressWarnings(read.paj(tmptest)),regexp = 'contains non-numeric or NA values')
tmptest<-tempfile()
cat("*Vertices 2
1 'A'
2 'B'
*Arcs
1 2.5 1
",file=tmptest)
expect_error(read.paj(tmptest),regexp = 'contains non-integer values')
# check vertex graphic attribute fill-in
tmptest<-tempfile()
cat("*Vertices 4
1 'A' 0 0 0 box
2 'B' 0 0 0
3 'C' 0 0 0
4 'D' 0 0 0 ellipse
*Arcs
1 2 1
1 3 1
",file=tmptest)
fillIn<-read.paj(tmptest)
expect_equal(fillIn%v%'shape',c('box','box','box','ellipse'))
# test stuff in file comments
########## but multirelational ############ only ~200 nodes
#GulfLDays.net
#GulfLMonths.net
#GulfLDow.net
#gulfAllDays.net #GulfADays.zip
#gulfAllMonths.net #GulfAMonths.zip
#LevantDays.net
#LevantMonths.net
#BalkanDays.net
#BalkanMonths.net
#arcs and edges both present search for " #these have both arc and edge lines " or "URL has a net file"
#Graph drawing competition page (GD)
#C95,C95,B98,A99,C99,A99m
#things to do:
#handle ragged array .net files like "CSphd.net" DONE!!
#handel two mode networks DONE!!
#handle mix of edges and arcs DONE!!
#handle multirelational pajek files
#issue with read.table and number.cols and fill...SanJuanSur_deathmessage.net has one row with 8 all the rest (including the first 5 have 5)
## # this file has character encoding issues
## scotland<-tempfile('scotland',fileext='.zip')
## download.file(
## 'http://vlado.fmf.uni-lj.si/pub/networks/data/esna/scotland.zip',
## scotland,
## quiet = TRUE)
## scotpaj<-tempfile('Scotland',fileext='.paj')
## con <- unz(scotland,'Scotland.paj')
## cat(
## readLines(con, encoding = "UTF-8"),
## sep='\n',
## file = scotpaj
## )
## close(con)
## scotproj<-read.paj(scotpaj)
## # produces two element list, containing networks and partitions
## expect_equal(names(scotproj),c("networks","partitions"))
## expect_equal(network.size(scotproj[[1]][[1]]),244)
## expect_equal(names(scotproj$partitions),c("Affiliation.partition.of.N1.[108,136]","Industrial_categories.clu"))
## A95net<-read.paj("http://vlado.fmf.uni-lj.si/pub/networks/data/GD/gd95/A95.net")
## expect_equal(network.size(A95net),36)
## expect_equal(network.vertex.names(A95net)[1:5],c("MUX","INSTRUCTION BUFFER (4 x 16)", "RCV","DRV","ROM REG"))
## # test reading a .paj project file
## bkfratProj<-read.paj('http://vlado.fmf.uni-lj.si/pub/networks/data/ucinet/bkfrat.paj')
## # should have two networks
## expect_equal(sapply(bkfratProj,class),c('network','network'),check.attributes=FALSE)
## # .. with wierd names
## expect_equal(names(bkfratProj),c('UciNet\\BKFRAT.DAT : BKFRAB','UciNet\\BKFRAT.DAT : BKFRAC'))
## # and 58 vertices
## expect_equal(sapply(bkfratProj,network.size),c(58,58),check.attributes=FALSE)
## expect_equal(sapply(bkfratProj,network.edgecount),c(1934,3306),check.attributes=FALSE)
## #check edge values and attribute naming
## expect_equal((bkfratProj[[1]]%e%"UciNet\\BKFRAT.DAT : BKFRAB")[1900:1934],c(1, 1, 1, 5, 2, 4, 2, 1, 3, 1, 3, 1, 2, 5, 1, 1, 1, 2, 1, 2, 2, 1, 6, 2, 1, 2, 2, 1, 1, 1, 1, 3, 3, 1, 1))
## # check vert attrs
## expect_equal(list.vertex.attributes(bkfratProj[[1]]),c('na','vertex.names','x','y','z'))
## # check network attrs
## expect_equal(bkfratProj[[1]]%n%'title',"UciNet\\BKFRAT.DAT : BKFRAB")
## expect_equal(bkfratProj[[2]]%n%'title',"UciNet\\BKFRAT.DAT : BKFRAC")
## # check loop flagging
## tmptest<-tempfile()
## cat("*Vertices 2
## 1 'A'
## 2 'B'
## *Arcs
## 1 1 1
## ",file=tmptest)
## loopTest<-read.paj(tmptest,verbose=FALSE)
## expect_true(has.loops(loopTest))
## # check edge.name argument
## tmptest<-tempfile()
## cat("*Vertices 2
## 1 'A'
## 2 'B'
## *Arcs
## 1 1 1
## ",file=tmptest)
## loopTest<-read.paj(tmptest,verbose=FALSE,edge.name='weight')
## expect_equal(list.edge.attributes(loopTest),c('na','weight'))
## # the rest of these will take longer, so including in opttest block so won't run on CRAN
## require(statnet.common)
## opttest(testvar = "ENABLE_statnet_TESTS",{
## # ----- examples from http://vlado.fmf.uni-lj.si/pub/networks/doc/ECPR/08/ECPR01.pdf ---
## GraphSet<-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/GraphSet.net')
## expect_true(is.directed(GraphSet))
## expect_equal(network.edgecount(GraphSet),27)
## # network contains some repeated edges
## expect_true(is.multiplex(GraphSet))
## expect_equal(network.vertex.names(GraphSet),letters[1:12])
## Tina<-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/TinaSet.net')
## # arcslist
## GraphList<-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/GraphList.net')
## # http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/TinaList.net # arcslist
## # matrix
## GraphMat <-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/GraphMat.net')
## expect_equal(network.vertex.names(GraphMat),letters[1:12])
## # check that edge attribute created and parsed correctly
## expect_equal(as.matrix(GraphMat,attrname='GraphMat')[3,7],2)
## # partition
## TinaPaj<-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Tina.paj')
## expect_equal(class(TinaPaj$partitions),'data.frame')
## expect_equal( TinaPaj$partitions[,1],c(2,1,2,2,2,2,2,2,3,3,3),use.names=FALSE)
## expect_true(is.network(TinaPaj$networks$Tina))
## # --- crude timing info --
## # by default timing info should be added as attribute
## timetest<-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Time.net')
## expect_equal(timetest%e%'pajekTiming',c("[7]","[6-8]"))
## expect_equal(timetest%v%'pajekTiming',c("[5-10,12-14]", "[1-3,7]", "[4-*]"))
## expect_true(setequal(list.vertex.attributes(timetest),c('na','pajekTiming','vertex.names'))) # no x or y
## expect_true(setequal(list.edge.attributes(timetest),c('na','pajekTiming','Time')))
## # test converting to networkDynamic format
## timetestNd<-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Time.net',time.format='networkDynamic')
## expect_equal(class(timetestNd),c('networkDynamic','network'))
## # check that activiy matrices are built as expected
## expect_equal(get.vertex.attribute(timetestNd,'active',unlist=FALSE),list(structure(c(5, 12, 11, 15), .Dim = c(2L, 2L)), structure(c(1, 7, 4, 8), .Dim = c(2L, 2L)), structure(c(4, Inf), .Dim = 1:2)))
## expect_equal(get.edge.attribute(timetestNd,'active',unlist=FALSE),list(structure(c(7, 8), .Dim = 1:2), structure(c(6, 9), .Dim = 1:2)))
## # read a *big* one http://vlado.fmf.uni-lj.si/pub/networks/data/CRA/Days.zip
## # 1.3 Mb, 13k vertices, 256K lines.
## # days<-tempfile('days',fileext='.zip')
## # download.file('http://vlado.fmf.uni-lj.si/pub/networks/data/CRA/Days.zip',days)
## # terrorTerms<-read.paj(unz(days,'Days.net'),verbose=TRUE,time.format='networkDynamic',edge.name='count')
## # multiple networks
## sampson<-read.paj('http://vlado.fmf.uni-lj.si/pub/networks/pajek/data/Sampson.net')
## lapply(sampson,class) # for some reason it is a formula?
## expect_equal(names(sampson$networks),c("SAMPLK1", "SAMPLK2", "SAMPLK3", "SAMPDLK", "SAMPES","SAMPDES","SAMPIN","SAMPNIN","SAMPPR","SAMNPR"))
## # multiple networks in arcslist format
## # sampsonL<-read.paj('http://vlado.fmf.uni-lj.si/pub/networks/pajek/data/SampsonL.net')
## # two-mode
## sandi<-read.paj('http://vlado.fmf.uni-lj.si/pub/networks/data/2mode/sandi/sandi.net')
## expect_true(is.bipartite(sandi))
## expect_equal(sandi%n%'bipartite',314)
## Davis<-read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Davis.paj') # two-mode
## expect_equal(Davis$networks[[1]]%n%'bipartite',18)
## # lots of edge and vertex attributes
## A96<-read.paj('http://vlado.fmf.uni-lj.si/pub/networks/data/GD/gd96/A96.net')
## expect_equal(network.size(A96),1096)
## expect_equal(list.vertex.attributes(A96),c("bw","fos","na","shape","vertex.names", "x","x_fact","y","y_fact")) # note no z attribute
## expect_equal(head(A96%v%'shape'),c("box","ellipse", "ellipse", "ellipse", "ellipse", "ellipse"))
## # check edge attribute parsing
## expect_equal(list.edge.attributes(A96),c("A96", "fos", "l" , "lr", "na", "s", "w" ))
## # l is the only one with unique values
## expect_equal(head(A96%e%'l'),c("a", "s","n","r","s","t"))
## }) # end of non-cran tests
# temporal versions http://vlado.fmf.uni-lj.si/pub/networks/data/KEDS/KEDS.htm
# temporal events data (not supported)
# http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Time.tim
# http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Friends.tim
network/tests/testthat/test-as.edgelist.R 0000644 0001762 0000144 00000011550 14317402074 020253 0 ustar ligges users test<-network.initialize(5)
add.edges(test,5,1)
add.edges(test,1,5)
set.edge.attribute(test,'value',c('a','b'))
set.edge.attribute(test,'weight',10:11)
expect_equal(
as.matrix.network.edgelist(test),
structure(c(5L, 1L, 1L, 5L), .Dim = c(2L, 2L), n = 5, vnames = 1:5)
)
# sort order should be different
if(Sys.getenv("_R_CLASS_MATRIX_ARRAY_") == "" & getRversion() < "4.0.0"){
expect_equal(
as.edgelist(test),
structure(c(1L, 5L, 5L, 1L), .Dim = c(2L, 2L), n = 5, vnames = 1:5, directed = TRUE, bipartite = FALSE, loops = FALSE, class = c("matrix_edgelist", "edgelist","matrix"))
)
}else{
expect_equal(
as.edgelist(test),
structure(c(1L, 5L, 5L, 1L), .Dim = c(2L, 2L), n = 5, vnames = 1:5, directed = TRUE, bipartite = FALSE, loops = FALSE, class = c("matrix_edgelist", "edgelist","matrix","array"))
)
}
expect_true(is.edgelist(as.edgelist(test)))
# numeric attribute
expect_equal(as.matrix.network.edgelist(test,attrname='weight'),structure(c(5L, 1L, 1L, 5L, 10L, 11L), .Dim = 2:3, n = 5, vnames = 1:5))
# character attribute NOTE makes the matrix character as well
expect_equal(as.matrix.network.edgelist(test,attrname='value'),structure(c('5', '1', '1', '5', 'a', 'b'), .Dim = 2:3, n = 5, vnames = 1:5))
# character attribute with tibble output: does not make matrix character
expect_equal(as.edgelist(test,attrname='value', output="tibble"),
structure(list(.tail = c(1L, 5L), .head = c(5L, 1L),
value = c("b", "a")), row.names = c(NA, -2L),
class = c("tibble_edgelist", "edgelist", "tbl_df", "tbl", "data.frame"),
n = 5, vnames = 1:5, directed = TRUE, bipartite = FALSE, loops = FALSE)
)
undir<-network.initialize(5,directed=FALSE)
add.edges(undir,5,1)
# direction will be swapped to tail < head
expect_equal(as.edgelist(undir)[,], c(1,5))
# empty network
as.edgelist(network.initialize(0))
# deleted edges
deledge<-network.initialize(5)
add.edges(deledge,1:3,2:4)
delete.edges(deledge,2)
if(Sys.getenv("_R_CLASS_MATRIX_ARRAY_")=="" & getRversion() < "4.0.0"){
expect_equal(
as.edgelist(deledge),
structure(c(1L, 3L, 2L, 4L), .Dim = c(2L, 2L), n = 5, vnames = 1:5, directed = TRUE, bipartite = FALSE, loops = FALSE, class = c("matrix_edgelist", "edgelist", "matrix"))
)
}else{
expect_equal(
as.edgelist(deledge),
structure(c(1L, 3L, 2L, 4L), .Dim = c(2L, 2L), n = 5, vnames = 1:5, directed = TRUE, bipartite = FALSE, loops = FALSE, class = c("matrix_edgelist", "edgelist", "matrix", "array"))
)
}
nw <- network.initialize(10L, directed = FALSE)
nw[1L,5L] <- 1L
nw[1L,10L] <- 1L
nw %e% "attr" <- c("a","b")
expect_identical(as.edgelist(nw), structure(matrix(c(1L,1L,5L,10L), nrow = 2L),
n = 10L,
vnames = seq_len(10L),
directed = FALSE,
bipartite = FALSE,
loops = FALSE,
class = c("matrix_edgelist", "edgelist", "matrix", "array")))
expect_identical(as.edgelist(nw, attrname = "attr"), structure(matrix(c("1","1","5","10","a","b"), nrow = 2L),
n = 10L,
vnames = seq_len(10L),
directed = FALSE,
bipartite = FALSE,
loops = FALSE,
class = c("matrix_edgelist", "edgelist", "matrix", "array")))
nw %n% "bipartite" <- 4L
expect_identical(as.edgelist(nw), structure(matrix(c(1L,1L,5L,10L), nrow = 2L),
n = 10L,
vnames = seq_len(10L),
directed = FALSE,
bipartite = 4L,
loops = FALSE,
class = c("matrix_edgelist", "edgelist", "matrix", "array")))
expect_identical(as.edgelist(nw, attrname = "attr"), structure(matrix(c("1","1","5","10","a","b"), nrow = 2L),
n = 10L,
vnames = seq_len(10L),
directed = FALSE,
bipartite = 4L,
loops = FALSE,
class = c("matrix_edgelist", "edgelist", "matrix", "array")))
network/tests/testthat/test-misc_tests.R 0000644 0001762 0000144 00000000501 13740520334 020217 0 ustar ligges users # tests for misc R functions
test<-network.initialize(5)
test[1,2]<-1
expect_equal(has.edges(test), c(TRUE,TRUE,FALSE,FALSE,FALSE))
expect_equal(has.edges(test,v=2:3),c(TRUE,FALSE))
expect_error(has.edges(test,v=10),regexp = 'argument must be a valid vertex id')
expect_equal(length(has.edges(network.initialize(0))),0)
network/tests/testthat/test-mixingmatrix.R 0000644 0001762 0000144 00000014040 14057014734 020571 0 ustar ligges users # Directed networks -------------------------------------------------------
test_that("mixingmatrix() just works on a directed network", {
net <- network.initialize(4, directed=TRUE)
net[1,2] <- net[3,4] <- 1
net %v% "a" <- c(1,1,2,2)
mm <- mixingmatrix(net, "a")
expect_type(mm, "integer")
expect_s3_class(mm, c("mixingmatrix", "table"), exact=TRUE)
expect_true(is.directed(mm))
expect_false(is.bipartite(mm))
})
test_that("mixingmatrix() works on emon$Texas (directed)", {
data(emon, package="network")
a <- get.vertex.attribute(emon$Texas, "Location")
el <- as.matrix(emon$Texas, matrix.type="edgelist")
emm <- table(From=a[el[,1]], To=a[el[,2]])
expect_equivalent(
as.integer(mixingmatrix(emon$Texas, "Location")),
as.integer(emm)
)
})
test_that("NA rows & cols are present for emon$MtSi unless useNA='no'", {
mm.no <- mixingmatrix(emon$MtSi, "Formalization", useNA="no")
expect_type(mm.no, "integer")
expect_identical(dim(mm.no), c(2L,2L))
mm.default <- mixingmatrix(emon$MtSi, "Formalization")
mm.ifany <- mixingmatrix(emon$MtSi, "Formalization", useNA="ifany")
mm.always <- mixingmatrix(emon$MtSi, "Formalization", useNA="always")
expect_identical(mm.ifany, mm.default)
expect_identical(mm.ifany, mm.always)
expect_identical(dim(mm.ifany), c(3L, 3L))
expect_identical(
mm.default,
structure(
c(19L, 4L, 1L, 4L, 0L, 0L, 4L, 1L, 0L),
.Dim = c(3L, 3L),
.Dimnames = list(From = c("1", "2", NA), To = c("1", "2", NA)),
class = c("mixingmatrix", "table"),
directed = TRUE,
bipartite = FALSE
)
)
} )
test_that("mixingmatrix(directed with categories without incident ties)", {
net <- network.initialize(4, directed = TRUE)
net %v% "a" <- c(1,1,2,3)
net[1,2] <- net[1,3] <- 1 # no ties incident on a=3
mm <- mixingmatrix(net, "a")
expect_type(mm, "integer")
expect_equivalent(
mm,
structure(
matrix(as.integer(c(1,0,0, 1,0,0, 0,0,0)), 3, 3),
dimnames = list(From=1:3, To=1:3),
class = c("mixingmatrix", "table")
)
)
})
test_that("mixingmatrx() warns on exclude=NULL", {
net <- network.initialize(4, directed=TRUE)
net[1,2] <- net[3,4] <- 1
net %v% "a" <- c(1,1,2,2)
expect_warning(
r <- mixingmatrix(net, "a", exclude=NULL),
regexp = "passing `exclude=NULL`"
)
expect_identical(r, mixingmatrix(net, "a"))
})
# Undirected networks -----------------------------------------------------
test_that("mixingmatrix() just works on a undirected network", {
net <- network.initialize(4, directed=FALSE)
net[1,2] <- net[1,3] <- 1
net %v% "a" <- c(1,1, 2,2)
mm <- mixingmatrix(net, "a")
expect_type(mm, "integer")
expect_equivalent(
mm,
structure(
matrix(as.integer(c(1,1,1,0)), 2, 2),
dimnames = list(From = 1:2, To = 1:2),
class = c("mixingmatrix", "table")
)
)
expect_false(is.directed(mm))
expect_false(is.bipartite(mm))
})
test_that("NA rows & cols are shown for undirected net unless useNA='no'", {
net <- network.initialize(2, directed=FALSE)
net %v% "a" <- c(1, NA)
net[1,2] <- 1
mm.default <- mixingmatrix(net, "a")
mm.ifany <- mixingmatrix(net, "a", useNA="ifany")
mm.always <- mixingmatrix(net, "a", useNA="always")
expect_identical(mm.default, mm.ifany)
expect_identical(mm.default, mm.always)
expect_identical(
mm.default,
structure(
c(0L, 1L, 1L, 0L),
.Dim = c(2L, 2L),
class = c("mixingmatrix", "table"),
.Dimnames = list(From = c("1", NA), To = c("1", NA)),
directed = FALSE,
bipartite = FALSE
)
)
mm.no <- mixingmatrix(net, "a", useNA="no")
expect_type(mm.no, "integer")
expect_identical(dim(mm.no), c(1L, 1L))
})
# Bipartite networks ------------------------------------------------------
am <- matrix(0, 5, 5)
am[1,3] <- am[1,4] <- am[2,3] <- am[2,5] <- 1
net <- as.network(am, directed=FALSE, bipartite=2)
net %v% "mode" <- c(1,1,2,2,2)
net %v% "a" <- c(1,2,3,4,4)
net %v% "withNA" <- c(1,2,NA, 4,NA)
set.vertex.attribute(net, "p1", value = c(20, 30), v = 1:2)
set.vertex.attribute(net, "p2", value = c(0.1, 0.2, 0.1), v = 3:5)
# plot(net, vertex.col="mode", displaylabels=TRUE)
test_that("mixingmatrix for bipartite net with expand.bipartite=FALSE is correct", {
# On `mode` so all ties between groups
expect_silent(
mm <- mixingmatrix(net, "mode", expand.bipartite = FALSE)
)
expect_type(mm, "integer")
expect_false(is.directed(mm))
expect_true(is.bipartite(mm))
expect_equivalent(
mm,
structure(
matrix(4L, 1, 1),
dimnames = list(From = 1, To = 2),
class = "mixingmatrix"
)
)
# On `a`
expect_silent(
mm <- mixingmatrix(net, "a", expand.bipartite = FALSE)
)
expect_type(mm, "integer")
expect_false(is.directed(mm))
expect_true(is.bipartite(mm))
expect_equivalent(
mm,
structure(
matrix(as.integer(c(1,1, 1,1)), 2, 2),
dimnames = list(From = 1:2, To=3:4),
class = "mixingmatrix"
)
)
})
test_that("mixingmatrix for bipartite net with expand.bipartite=TRUE is correct", {
# On `mode`
expect_silent(
mm <- mixingmatrix(net, "mode", expand.bipartite = TRUE)
)
expect_type(mm, "integer")
expect_equivalent(
mm,
structure(
matrix(as.integer(c(0,0, 4,0)), 2, 2),
dimnames = list(From = 1:2, To=1:2),
class = "mixingmatrix"
)
)
# On `a`
expect_silent(
mm <- mixingmatrix(net, "a", expand.bipartite = TRUE)
)
expect_identical(dim(mm), c(4L, 4L))
expect_identical(
as.integer(mm),
as.integer(c(0,0,0,0, 0,0,0,0, 1,1,0,0, 1,1,0,0))
)
})
test_that("NA rows & cols are shown for bipartite net unless useNA='no'", {
expect_silent(
mm.default <- mixingmatrix(net, "withNA")
)
expect_silent(
mm.no <- mixingmatrix(net, "withNA", useNA="no")
)
expect_silent(
mm.always <- mixingmatrix(net, "withNA", useNA="always")
)
expect_identical(mm.default, mm.always)
expect_identical(
as.integer(mm.default),
as.integer(c(1,0,0, 1,2,0))
)
expect_identical(dim(mm.no), c(2L, 1L))
expect_identical(
as.integer(mm.no),
as.integer(c(1, 0))
)
})
network/tests/testthat/test-networks.R 0000644 0001762 0000144 00000005666 14317402074 017740 0 ustar ligges users # ----- checks for network edgecount ------
test<-network.initialize(4)
# directed
expect_equal(network.dyadcount(test),12)
# undirected
test%n%'directed'<-FALSE
expect_equal(network.dyadcount(test),6)
# loops allowed
test%n%'loops'<-TRUE
#undirected
expect_equal(network.dyadcount(test),10)
# directed
test%n%'directed'<-TRUE
expect_equal(network.dyadcount(test),16)
# directed bipartite
test%n%'loops'<-FALSE
test%n%'bipartite'<-1
expect_equal(network.dyadcount(test),6)
# undirected bipartite
test%n%'directed'<-FALSE
expect_equal(network.dyadcount(test),3)
# NA values
test[1,2]<-NA
expect_equal(network.dyadcount(test,na.omit = TRUE),2)
# ----- checks for dyads eids -----
data(emon)
el<-as.matrix.network.edgelist(emon[[1]])
expect_equal(get.dyads.eids(emon[[1]],el[,1],el[,2]),as.list(1:83))
expect_equal(get.dyads.eids(emon[[1]],el[5:10,1],el[5:10,2]),as.list(5:10))
expect_error(get.dyads.eids(emon[[1]],1,2:3),regexp = 'heads and tails vectors must be the same length')
expect_error(get.dyads.eids(network.initialize(0),1,2),regexp = 'invalid vertex id in heads or tails vector')
mult<-network.initialize(5,multiple=TRUE)
add.edges(mult,1,2)
add.edges(mult,1,2)
expect_warning(expect_true(is.na(get.dyads.eids(mult,1,2)[[1]])),regexp = 'multiple edge ids for dyad')
expect_equal(get.dyads.eids(network.initialize(0),numeric(0),numeric(0)), list())
expect_equal(get.dyads.eids(network.initialize(5),tails=1:2,heads=3:4),list(numeric(0),numeric(0)))
# check oposite matching for undirected nets
undir<-network.initialize(3,directed=FALSE)
undir[1,2]<-1
expect_equal(get.dyads.eids(undir,2,1),list(1))
expect_equal(get.dyads.eids(undir,1,2),list(1))
undir%n%'directed'<-TRUE
expect_equal(get.dyads.eids(undir,2,1),list(integer(0)))
expect_equal(get.dyads.eids(undir,1,2),list(1))
expect_equal(get.dyads.eids(undir,2,1,neighborhood='in'),list(1))
expect_equal(get.dyads.eids(undir,1,2,neighborhood='in'),list(integer(0)))
nw <- network.initialize(10, directed = FALSE)
el <- matrix(c(1,2,3,5,2,9,9,10,6,7),ncol=2,byrow=TRUE)
nw[el]<-1
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = FALSE), as.list(seq_len(NROW(el))))
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = TRUE), as.list(seq_len(NROW(el))))
nw[el[2,1],el[2,2]] <- NA
nw[el[5,1],el[5,2]] <- NA
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = FALSE), as.list(seq_len(NROW(el))))
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = TRUE), list(1L, integer(0), 3L, 4L, integer(0)))
delete.edges(nw, 2)
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = FALSE), list(1L, integer(0), 3L, 4L, 5L))
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = TRUE), list(1L, integer(0), 3L, 4L, integer(0)))
delete.edges(nw, 3)
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = FALSE), list(1L, integer(0), integer(0), 4L, 5L))
expect_identical(get.dyads.eids(nw, el[,1], el[,2], na.omit = TRUE), list(1L, integer(0), integer(0), 4L, integer(0)))
network/tests/testthat.R 0000644 0001762 0000144 00000000072 13737227152 015100 0 ustar ligges users library(testthat)
library(network)
test_check("network")
network/tests/speedTests.R 0000644 0001762 0000144 00000004243 14363704204 015361 0 ustar ligges users #Set to TRUE to run tests
if(FALSE){
# some really basic speed checks to help us know if we make changes that massively degrade performance
require(network)
init<-system.time(net<-network.initialize(100000))[3]
setv<-system.time(set.vertex.attribute(net,"foo","bar"))[3]
getv<-system.time(get.vertex.attribute(net,"foo"))[3]
listv<-system.time(list.vertex.attributes(net))[3]
adde<-system.time(add.edges(net,tail=1:99999,head=2:100000))[3]
sete<-system.time(set.edge.attribute(net,"foo","bar"))[3]
gete<-system.time(get.edge.attribute(net,"foo"))[3]
liste<-system.time(list.edge.attributes(net))[3]
addmoree<-system.time(add.edge(net,100000,1))[3]
addmorev<-system.time(add.vertices(net,1))[3]
# optionally compare to benchmarks saved in test folder to see if things have changed
# benchmarks<-rbind(init,setv,getv,listv,adde,sete,gete,liste,addmoree,addmorev)
# oldmarks<-read.table(file.choose(),header=TRUE,colClasses=c('character','numeric'))
# all.equal(oldmarks[,1],benchmarks[,1],check.attributes=FALSE)
# optionally save out benchmarks to test directory
# write.table(benchmarks,file=file.choose())
# some absolute thresholds
if(init>5){
stop("initializing network for large number of vertices took much longer than expected")
}
if(setv>5){
stop("set.vertex.attribute for large number of vertices took much longer than expected")
}
if(getv>5){
stop("get.vertex.attribute for large number of vertices took much longer than expected")
}
if(listv>1){
stop("list.vertex.attributes for large number of vertices took much longer than expected")
}
if(adde>5){
stop("add.edges for a large number of edges took much longer than expected")
}
if(sete>10){
stop("set.edge.attribute for a large number of edges took much longer than expected")
}
if(gete>1){
stop("get.edge.attribute for a large number of edges took much longer than expected")
}
if(liste>1){
stop("list.edge.attribute for a large number of edges took much longer than expected")
}
if(addmoree>5){
stop("add.edge for a network with a large number of edges took much longer than expected")
}
if(addmorev>5){
stop("add.vertices for a network with large number of vertices took longer than expected")
}
#End tests
}
network/tests/network.access.test.R 0000644 0001762 0000144 00000005553 14363704162 017155 0 ustar ligges users #Set to TRUE to run tests
if(FALSE){
library(network)
binet = network.initialize(10, bipartite = 6)
set.vertex.attribute(binet, 'myval', paste('b1', 1:6), v=1:6)
set.vertex.attribute(binet, 'myval', paste('b2', 1:4), v=7:10)
check <- vector()
check[1] <- all(get.vertex.attribute(binet, 'myval') == c("b1 1", "b1 2", "b1 3", "b1 4", "b1 5", "b1 6", "b2 1", "b2 2", "b2 3" ,"b2 4"))
# check for distinction between bipartite=FALSE and bipartite=0
testA<-network.initialize(3,bipartite=0)
if(!is.bipartite(testA)){
stop('failed test of is.bipartite for bipartite=0')
}
testB<-network.initialize(3,bipartite=FALSE)
if(is.bipartite(testB)){
stop('failed test of is.bipartite for bipartite=FALSE')
}
testC<-network.initialize(3,bipartite=TRUE)
if(!is.bipartite(testC)){
stop('failed test of is.bipartite for bipartite=TRUE')
}
if(!is.bipartite(binet)){
stop('failed test of is.bipartite for bipartite=6')
}
# add vertices to bipartite graphs
g = binet; add.vertices(g, 5, last.mode=F)
check[2] <- network.size(g) == 15
check[3] <- get.network.attribute(g, 'bipartite') == 11
check[4] <- identical(get.vertex.attribute(g, 'myval'),
c("b1 1", "b1 2", "b1 3", "b1 4", "b1 5", "b1 6", NA,NA,NA,NA,NA,"b2 1","b2 2","b2 3","b2 4"))
test<-network.initialize(3,bipartite=0)
test%v%'letters'<-LETTERS[1:3]
add.vertices(test,nv=1,last.mode=FALSE)
if(!identical(test%v%'letters',c(NA,"A","B","C"))){
stop("Error adding vertices to first mode of network with biparite=0")
}
test<-network.initialize(3,bipartite=0)
test%v%'letters'<-LETTERS[1:3]
add.vertices(test,nv=1,last.mode=TRUE)
if(!identical(test%v%'letters',c("A","B","C",NA))){
stop("Error adding vertices to last mode of network with biparite=0")
}
g = binet
add.vertices(g, 5, last.mode=T)
check[5] <- network.size(g) == 15
check[6] <- get.network.attribute(g, 'bipartite') == 6
check[7] <- identical(get.vertex.attribute(g, 'myval'),
c("b1 1", "b1 2", "b1 3", "b1 4", "b1 5", "b1 6","b2 1","b2 2","b2 3","b2 4", NA,NA,NA,NA,NA))
# replacement operators should always replace
y <- network.initialize(4,dir=FALSE) # This network can have at most 1 edge.
y[1,2] <- NA # Assign NA to (1,2)
y[1,2] <- NA
check[8] <- network.edgecount(y) == 0
check[9] <- network.edgecount(y, na.omit=F) == 1
y[,] <- 1
check[10] <- network.edgecount(y) == 6
y[,] <- NA
check[11] <- network.edgecount(y) == 0
check[12] <- network.edgecount(y, na.omit=F) == 6
y[,] <- 0
check[13] <- network.edgecount(y, na.omit=F) == 0
# ------ test valid.eids function
net<-network.initialize(4)
net[,]<-1
delete.edges(net,eid=4:6)
if(!all(valid.eids(net)==c(1,2,3,7,8,9,10,11,12))){
stop('valid.eids did not return correct ids for non-null elements of network')
}
#If everything worked, check is TRUE
if(!all(check)){ #Should be TRUE
stop(paste("network package test failed on test(s):",which(!check)))
}
#End tests
}
network/tests/vignette.R 0000644 0001762 0000144 00000010450 13357022000 015045 0 ustar ligges users require("network")
set.seed(1702)
results = NULL
data("flo")
data("emon")
net <- network.initialize(5)
net
nmat <- matrix(rbinom(25, 1, 0.5), nr = 5, nc = 5)
net <- network(nmat, loops = TRUE)
net
summary(net)
results[1] = all(nmat == net[,])
net <- as.network(nmat, loops = TRUE)
results[2] = all(nmat == net[,])
nflo <- network(flo, directed = FALSE)
nflo
results[3] = all(nflo[9,] == c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1))
results[4] = nflo[9,1] == 1
results[5] = nflo[9,4] == 0
results[6] = is.adjacent(nflo, 9, 1) == TRUE
results[7] = is.adjacent(nflo, 9, 4) == FALSE
results[8] = network.size(nflo) == 16
results[9] = network.edgecount(nflo) == 20
results[10] = network.density(nflo) == 1/6
results[11] = has.loops(nflo) == FALSE
results[12] = is.bipartite(nflo) == FALSE
results[13] = is.directed(nflo) == FALSE
results[14] = is.hyper(nflo) == FALSE
results[15] = is.multiplex(nflo) == FALSE
as.sociomatrix(nflo)
results[16] = all(nflo[,] == as.sociomatrix(nflo))
results[17] = all(as.matrix(nflo) == as.sociomatrix(nflo))
as.matrix(nflo,matrix.type = "edgelist")
net <- network.initialize(5, loops = TRUE)
net[nmat>0] <- 1
results[18] = all(nmat == net[,])
net[,] <- 0
net[,] <- nmat
results[19] = all(nmat == net[,])
net[,] <- 0
for(i in 1:5)
for(j in 1:5)
if(nmat[i,j])
net[i,j] <- 1
results[20] = all(nmat == net[,])
net[,] <- 0
add.edges(net, row(nmat)[nmat>0], col(nmat)[nmat>0])
results[21] = all(nmat == net[,])
net[,] <- as.numeric(nmat[,])
results[22] = all(nmat == net[,])
net <- network.initialize(5)
add.edge(net, 2, 3)
net[,]
results[23] = net[2,3] == 1
add.edges(net, c(3, 5), c(4, 4))
net[,]
results[24] = (net[3,4] == 1 && net[5,4] == 1)
net[,2] <- 1
net[,]
results[25] = net[2,2] == 0
delete.vertices(net, 4)
results[26] = all(net[,] == matrix(c(0,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0), byrow=T, nrow=4))
add.vertices(net, 2)
net[,]
get.edges(net, 1)
get.edges(net, 2, neighborhood = "in")
get.edges(net, 1, alter = 2)
results[27] = get.edgeIDs(net, 1) == 4
results[28] = all(get.edgeIDs(net, 2, neighborhood = "in") == c(7, 5, 4))
results[29] = get.edgeIDs(net, 1, alter = 2) == 4
results[30] = get.neighborhood(net, 1) == 2
results[31] = all(get.neighborhood(net, 2, type = "in") == c(4, 3, 1))
net[2,3] <- 0
results[32] = net[2,3] == 0
delete.edges(net, get.edgeIDs(net, 2, neighborhood = "in"))
results[33] = all(net[,] == matrix(0, 6,6))
net <- network.initialize(5)
set.network.attribute(net, "boo", 1:10)
net %n% "hoo" <- letters[1:7]
results[34] = 'boo' %in% list.network.attributes(net)
results[35] = 'hoo' %in% list.network.attributes(net)
results[36] = all(get.network.attribute(net, "boo") == c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
results[37] = all(net %n% "hoo" == c("a", "b", "c", "d", "e", "f", "g"))
delete.network.attribute(net, "boo")
results[38] = 'boo' %in% list.network.attributes(net) == FALSE
set.vertex.attribute(net, "boo", 1:5)
net %v% "hoo" <- letters[1:5]
results[39] = 'boo' %in% list.vertex.attributes(net)
results[40] = 'hoo' %in% list.vertex.attributes(net)
results[41] = all(get.vertex.attribute(net, "boo") == 1:5)
results[42] = all(net %v% "hoo" == letters[1:5])
delete.vertex.attribute(net, "boo")
results[43] = 'boo' %in% list.vertex.attributes(net) == FALSE
net <- network(nmat)
set.edge.attribute(net, "boo", sum(nmat):1)
set.edge.value(net, "hoo", matrix(1:25, 5, 5))
net %e% "woo" <- matrix(rnorm(25), 5, 5)
net[,, names.eval = "zoo"] <- nmat * 6
results[44] = 'boo' %in% list.edge.attributes(net)
results[45] = 'hoo' %in% list.edge.attributes(net)
results[46] = all(get.edge.attribute(get.edges(net, 1), "boo") == c(3,7))
results[47] = all(get.edge.value(net, "hoo") == c(2, 3, 11, 14, 17, 18, 21))
net %e% "woo"
as.sociomatrix(net, "zoo")
delete.edge.attribute(net, "boo")
results[48] = 'boo' %in% list.edge.attributes(net) == FALSE
MtSHloc <- emon$MtStHelens %v% "Location"
MtSHimat <- cbind(MtSHloc %in% c("L", "B"), MtSHloc %in% c("NL", "B"))
MtSHbyloc <- network(MtSHimat, matrix = "incidence", hyper = TRUE,
directed = FALSE, loops = TRUE)
MtSHbyloc %v% "vertex.names" <- emon$MtStHelens %v% "vertex.names"
MtSHbyloc
plot(nflo, displaylabels = TRUE, boxed.labels = FALSE)
plot(nflo, displaylabels = TRUE, mode = "circle")
plot(emon$MtSi)
if (!all(results)) {
stop(paste('The following tests in vignette.R failed:', which(results==FALSE)))
}
network/MD5 0000644 0001762 0000144 00000013165 14725552272 012274 0 ustar ligges users 9b699d8131bbe4e391b88e47beef1f74 *COPYING
7ee6d13e044da36fca54c2667e7ba68e *ChangeLog
c8e1da4dfc7e7a33ee760f81062877b7 *DESCRIPTION
42874c30088916fe52b52bde58004616 *NAMESPACE
c35534074c68d3e8532eff68bac3fbb8 *R/access.R
ab7d8f7ebc9e05f36453547778f15bf5 *R/as.edgelist.R
1589770cd6defbc3704ee0d2f9b1cfe4 *R/assignment.R
49f964e7fa56f199ec5613a346582748 *R/coercion.R
5dd6d1de5eb0aed5ad74aee242fcf343 *R/constructors.R
6cf83e2a1248ff367885588a3dd30ad0 *R/dataframe.R
bb6c33aa4d09e59807e7e086444fc2a2 *R/fileio.R
1eed18aeadf7aba09cf6ccee6b91c74b *R/layout.R
988141d57785384812c92452357549eb *R/misc.R
2dd2a513cd133a048885abcb71711c95 *R/network-package.R
f0a9dafcc8594f8b12cae79b46231dbf *R/operators.R
a8bf80a257042a755961ba7691316a55 *R/plot.R
c32f1c0c9fcaa343a872dd12ee309c8c *R/printsum.R
263822ebe70c081f9b90a05790829538 *R/zzz.R
d30fb62438e3e6c40920c2d12cebb683 *build/partial.rdb
2bce853f8f2923f9e2b005959d2bdba4 *build/vignette.rds
4e1fd0dcead8991dc32c05e2d7301c40 *data/emon.RData
bb3e0d4d549b892aa8701af630adb78a *data/flo.RData
32bcc50a43d7a2258b65404072039bbd *inst/CITATION
3e06997d5f02a81dfdccf3d00ff43d0f *inst/doc/networkVignette.R
e426433ac42ea149a73be4923359cf0d *inst/doc/networkVignette.Rnw
1ba1e108053322695a598c35f4d7fc51 *inst/doc/networkVignette.pdf
2fce00a65f9969063ffe26e50ccbd87c *inst/include/netregistration.h
4b9aa09dd1d9f3ff6e9cd5236188d653 *inst/include/network.h
c78b6af71f6256929251472b1d75fbe1 *inst/network.api/networkapi.c
1c85daf92af86106d5fb3e0797eda213 *inst/network.api/networkapi.h
46a54d46bce4e3a330ec6891fb65fe4e *man/add.edges.Rd
a9c706fec81a7986064c9eadecb36766 *man/add.vertices.Rd
050041ed9630847918d1f5aef7bb559a *man/as.color.Rd
c60986b288e28d7992293d62c363c936 *man/as.data.frame.network.Rd
b8b8958545e188d91a0557955097fa38 *man/as.edgelist.Rd
d3d729d0346adf0132e581d5f7a14783 *man/as.matrix.network.Rd
50405c74fa075fe651209f00d4ab1c33 *man/as.network.matrix.Rd
59bc37e0c19b9f826a0433804d63e26a *man/as.sociomatrix.Rd
6c497d2ad362ffd4e91f582ca384b7f5 *man/attribute.methods.Rd
41ff8acb100b8f4f545b9f92937c1e04 *man/deletion.methods.Rd
f2aa48b10ad6172c2df9549551a25cce *man/edgeset.constructors.Rd
49bf9f0e4d8ab192a342caa561136a80 *man/emon.Rd
ceec9dfc3b6392adf7a859e7fae9bdec *man/flo.Rd
1f89ec3a0d6a8832f7cca034512abf70 *man/get.edges.Rd
d3c06b6dc056630f833877378d3c71b4 *man/get.inducedSubgraph.Rd
8bc3e34cdcf75858c83fde19e21c8f52 *man/get.neighborhood.Rd
531bf734d867ce44efcf534a16416d31 *man/has.edges.Rd
6e9ce9c60e54ac57ad5c95a6c50b3869 *man/is.adjacent.Rd
d5d0b66c338fb9be202e09a901bcf6d5 *man/loading.attributes.Rd
f777f59c54627809aa77690959b60252 *man/mixingmatrix.Rd
10f5aea0ed5403e0703bbdd87dc876ae *man/network-internal.Rd
34b8d7dcd350d858f40d0b7fe0329ef0 *man/network-operators.Rd
4d77d220b874d59945a90d78f9a26afc *man/network-package.Rd
86624c1a0ca4d45d129325f571ece024 *man/network.Rd
e58c2e14f66d2707c4e472bad5cc0908 *man/network.arrow.Rd
d6a10ac1493144969691c10cfd25106d *man/network.density.Rd
b753f4fdcb96c4457997d4526f65f386 *man/network.dyadcount.Rd
582c047604d9ebe9f9ca237cebbd4150 *man/network.edgecount.Rd
436db36c5955e9f78d3aa2a94bc85b39 *man/network.edgelabel.Rd
72968b207881146c28a3655b9172c45a *man/network.extraction.Rd
bb29d45ecd04d4aef2bc8ed2c428bce2 *man/network.indicators.Rd
e50b00cc5cb5490f34cb1cae2a97658c *man/network.initialize.Rd
c0cf0381c4499d4284f5ae5dbdb6fae8 *man/network.layout.Rd
eca169ee58fa0c8719bc057641d0d21c *man/network.loop.Rd
b1553bbcab4eafcf90a03ecf5f13565a *man/network.naedgecount.Rd
5785845e981b649f14cc5e876eb35a92 *man/network.size.Rd
fcfa2816525915c11ae1c70b2ab19e30 *man/network.vertex.Rd
73586605bcd4528bead84bdb7c9a9243 *man/permute.vertexIDs.Rd
ddf6e098b0e233fbca298b57b47de713 *man/plot.network.Rd
0a6ddb702f25ad304107148b72b7ddd1 *man/preparePlotArgs.Rd
acc67a3bf7f6b5dfed930571a3bdea43 *man/prod.network.Rd
60e96d3792c7beb88145f6ec81c5bc24 *man/read.paj.Rd
e0a1a69a99e16a00e9e55abc35fb0634 *man/sum.network.Rd
b1dd30b318f7fb788bcd4704bc49f9b4 *man/valid.eids.Rd
824796c13b47e234d6f981e17642f30c *man/which.matrix.type.Rd
1c5cf8036602f903a2699b928fc0ca93 *src/Rinit.c
5b5e94035b4b085f46ea24586924b6bb *src/access.c
96fc95a8ae2941d6e411b38c80cee9af *src/access.h
739756cc9b67f775864fa7f6aa19745e *src/constructors.c
58ac8ab29e39950e95390b86a5de4c83 *src/constructors.h
99ad146ab20fdd5dd38725385c7f2dda *src/layout.c
c929fe23f5a09c76c8c11aa83dbb2ed1 *src/layout.h
c624cbb55190d144a79c1fea041fab68 *src/utils.c
b5ed5be00b1bddd126b1bd7e4937ee3f *src/utils.h
59fde81bf25fff109743e99b70fbdc4f *tests/benchmarks
9f3d1462baf551cdb0e760358e7fbce8 *tests/general.tests.R
7182bab37ffc7577c4508076ca86fa40 *tests/general.tests2.R
a7f96e9a09fc13489cb4c5760a5f9f7a *tests/list.attribute.tests.R
5a176c0519643a156eee9e1a31fe3c18 *tests/network.access.test.R
fda3f32b65c3ac83b367338be7b190e6 *tests/network.battery.R
36275927d8cc11b77b18c9ca8bcb0e27 *tests/pathological.tests.R
563df50e729d2995ea313959f39a61ab *tests/plotflo.R
790025d02a15dd4d9c8061bf37975f6d *tests/speedTests.R
b2c97b33a2d412dc5d5e11f14b3c4e6f *tests/testthat.R
c2b0eaea326f8b60cca4011ee0cd5eb6 *tests/testthat/test-as.edgelist.R
5bd10799a112f9a02df4f94ca0d94a7d *tests/testthat/test-dataframe.R
87cfdbb310dad8da648dc6433d58b2a1 *tests/testthat/test-i22-summary-character.R
52da4d470df06df454cbc61ac1842807 *tests/testthat/test-indexing.R
93c5263fc884f28035b4a626f25cadf3 *tests/testthat/test-misc_tests.R
0e4bed5f2503c875e914efb4bb1b702a *tests/testthat/test-mixingmatrix.R
c62d074345596fbaaed03aee9c82f220 *tests/testthat/test-networks.R
8514de6d9548451f179969d8e8f29c82 *tests/testthat/test-plot.R
3cc36bdc9454722288b4eca4bf505960 *tests/testthat/test-read.paj.R
ada28de34c8d472fc95aa852611895b6 *tests/vignette.R
e426433ac42ea149a73be4923359cf0d *vignettes/networkVignette.Rnw
network/R/ 0000755 0001762 0000144 00000000000 14725233503 012150 5 ustar ligges users network/R/plot.R 0000644 0001762 0000144 00000174011 14723241675 013264 0 ustar ligges users ######################################################################
#
# plot.R
#
# Written by Carter T. Butts ; portions contributed by
# David Hunter and Mark S. Handcock
# .
#
# Last Modified 06/06/21
# Licensed under the GNU General Public License version 2 (June, 1991)
# or greater
#
# Part of the R/network package
#
# This file contains various routines related to network visualization.
#
# Contents:
#
# network.arrow
# network.loop
# network.vertex
# plot.network
# plot.network.default
#
######################################################################
#Introduce a function to make coordinates for a single polygon
make.arrow.poly.coords<-function(x0,y0,x1,y1,ahangle,ahlen,swid,toff,hoff,ahead, curve,csteps){
slen<-sqrt((x0-x1)^2+(y0-y1)^2) #Find the total length
if(curve==0){ #Straight edges
if(ahead){
coord<-rbind( #Produce a "generic" version w/head
c(-swid/2,toff),
c(-swid/2,slen-0.5*ahlen-hoff),
c(-ahlen*sin(ahangle),slen-ahlen*cos(ahangle)-hoff),
c(0,slen-hoff),
c(ahlen*sin(ahangle),slen-ahlen*cos(ahangle)-hoff),
c(swid/2,slen-0.5*ahlen-hoff),
c(swid/2,toff),
c(NA,NA)
)
}else{
coord<-rbind( #Produce a "generic" version w/out head
c(-swid/2,toff),
c(-swid/2,slen-hoff),
c(swid/2,slen-hoff),
c(swid/2,toff),
c(NA,NA)
)
}
}else{ #Curved edges
if(ahead){
inc<-(0:csteps)/csteps
coord<-rbind(
cbind(-curve*(1-(2*(inc-0.5))^2)-swid/2-sqrt(2)/2*(toff+inc*(hoff-toff)), inc*(slen-sqrt(2)/2*(hoff+toff)-ahlen*0.5)+sqrt(2)/2*toff),
c(ahlen*sin(-ahangle-pi/16)-sqrt(2)/2*hoff, slen-ahlen*cos(-ahangle-pi/16)-sqrt(2)/2*hoff),
c(-sqrt(2)/2*hoff,slen-sqrt(2)/2*hoff),
c(ahlen*sin(ahangle-pi/16)-sqrt(2)/2*hoff, slen-ahlen*cos(ahangle-pi/16)-sqrt(2)/2*hoff),
cbind(-curve*(1-(2*(rev(inc)-0.5))^2)+swid/2-sqrt(2)/2*(toff+rev(inc)*(hoff-toff)), rev(inc)*(slen-sqrt(2)/2*(hoff+toff)-ahlen*0.5)+sqrt(2)/2*toff),
c(NA,NA)
)
}else{
inc<-(0:csteps)/csteps
coord<-rbind(
cbind(-curve*(1-(2*(inc-0.5))^2)-swid/2-sqrt(2)/2*(toff+inc*(hoff-toff)), inc*(slen-sqrt(2)/2*(hoff+toff))+sqrt(2)/2*toff),
cbind(-curve*(1-(2*(rev(inc)-0.5))^2)+swid/2-sqrt(2)/2*(toff+rev(inc)*(hoff-toff)), rev(inc)*(slen-sqrt(2)/2*(hoff+toff))+sqrt(2)/2*toff),
c(NA,NA)
)
}
}
theta<-atan2(y1-y0,x1-x0)-pi/2 #Rotate about origin
rmat<-rbind(c(cos(theta),sin(theta)),c(-sin(theta),cos(theta)))
coord<-coord%*%rmat
coord[,1]<-coord[,1]+x0 #Translate to (x0,y0)
coord[,2]<-coord[,2]+y0
coord
}
#Custom arrow-drawing method for plot.network
#' Add Arrows or Segments to a Plot
#'
#' \code{network.arrow} draws a segment or arrow between two pairs of points;
#' unlike \code{\link{arrows}} or \code{\link{segments}}, the new plot element
#' is drawn as a polygon.
#'
#' \code{network.arrow} provides a useful extension of \code{\link{segments}}
#' and \code{\link{arrows}} when fine control is needed over the resulting
#' display. (The results also look better.) Note that edge curvature is
#' quadratic, with \code{curve} providing the maximum horizontal deviation of
#' the edge (left-handed). Head/tail offsets are used to adjust the end/start
#' points of an edge, relative to the baseline coordinates; these are useful
#' for functions like \code{\link{plot.network}}, which need to draw edges
#' incident to vertices of varying radii.
#'
#' @param x0 A vector of x coordinates for points of origin
#' @param y0 A vector of y coordinates for points of origin
#' @param x1 A vector of x coordinates for destination points
#' @param y1 A vector of y coordinates for destination points
#' @param length Arrowhead length, in current plotting units
#' @param angle Arrowhead angle (in degrees)
#' @param width Width for arrow body, in current plotting units (can be a
#' vector)
#' @param col Arrow body color (can be a vector)
#' @param border Arrow border color (can be a vector)
#' @param lty Arrow border line type (can be a vector)
#' @param offset.head Offset for destination point (can be a vector)
#' @param offset.tail Offset for origin point (can be a vector)
#' @param arrowhead Boolean; should arrowheads be used? (Can be a vector))
#' @param curve Degree of edge curvature (if any), in current plotting units
#' (can be a vector)
#' @param edge.steps For curved edges, the number of steps to use in
#' approximating the curve (can be a vector)
#' @param \dots Additional arguments to \code{\link{polygon}}
#' @return None.
#' @note \code{network.arrow} is a direct adaptation of
#' \code{\link[sna]{gplot.arrow}} from the \code{sna} package.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{plot.network}}, \code{\link{network.loop}},
#' \code{\link{polygon}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords aplot graphs
#' @examples
#'
#' #Plot two points
#' plot(1:2,1:2)
#'
#' #Add an edge
#' network.arrow(1,1,2,2,width=0.01,col="red",border="black")
#'
#' @export network.arrow
network.arrow<-function(x0,y0,x1,y1,length=0.1,angle=20,width=0.01,col=1,border=1,lty=1,offset.head=0,offset.tail=0,arrowhead=TRUE,curve=0,edge.steps=50,...){
if(length(x0)==0) #Leave if there's nothing to do
return()
#"Stretch" the arguments
n<-length(x0)
angle<-rep(angle,length.out=n)/360*2*pi
length<-rep(length,length.out=n)
width<-rep(width,length.out=n)
col<-rep(col,length.out=n)
border<-rep(border,length.out=n)
lty<-rep(lty,length.out=n)
arrowhead<-rep(arrowhead,length.out=n)
offset.head<-rep(offset.head,length.out=n)
offset.tail<-rep(offset.tail,length.out=n)
curve<-rep(curve,length.out=n)
edge.steps<-rep(edge.steps,length.out=n)
#Obtain coordinates
coord<-vector()
for(i in 1:n)
coord<-rbind(coord,make.arrow.poly.coords(x0[i],y0[i],x1[i],y1[i],angle[i],length[i], width[i],offset.tail[i],offset.head[i],arrowhead[i],curve[i],edge.steps[i]))
coord<-coord[-NROW(coord),]
#Draw polygons.
# the coord matrix has some NA rows, which will break it into multiple polygons
polygon(coord,col=col,border=border,lty=lty,...)
}
#Introduce a function to make coordinates for a single polygon
make.loop.poly.coords<-function(x0,y0,xctr,yctr,ahangle,ahlen,swid,off,rad,ahead,edge.steps){
#Determine the center of the plot
xoff <- x0-xctr
yoff <- y0-yctr
roff <- sqrt(xoff^2+yoff^2)
x0hat <- xoff/roff
y0hat <- yoff/roff
r0.vertex <- off
r0.loop <- rad
x0.loop <- x0hat*r0.loop
y0.loop <- y0hat*r0.loop
ang <- (((0:edge.steps)/edge.steps)*(1-(2*r0.vertex+0.5*ahlen*ahead)/ (2*pi*r0.loop))+r0.vertex/(2*pi*r0.loop))*2*pi+atan2(-yoff,-xoff)
ang2 <- ((1-(2*r0.vertex)/(2*pi*r0.loop))+r0.vertex/(2*pi*r0.loop))*2*pi+ atan2(-yoff,-xoff)
if(ahead){
x0.arrow <- x0.loop+(r0.loop+swid/2)*cos(ang2)
y0.arrow <- y0.loop+(r0.loop+swid/2)*sin(ang2)
coord<-rbind(
cbind(x0.loop+(r0.loop+swid/2)*cos(ang),
y0.loop+(r0.loop+swid/2)*sin(ang)),
cbind(x0.arrow+ahlen*cos(ang2-pi/2),
y0.arrow+ahlen*sin(ang2-pi/2)),
cbind(x0.arrow,y0.arrow),
cbind(x0.arrow+ahlen*cos(-2*ahangle+ang2-pi/2),
y0.arrow+ahlen*sin(-2*ahangle+ang2-pi/2)),
cbind(x0.loop+(r0.loop-swid/2)*cos(rev(ang)),
y0.loop+(r0.loop-swid/2)*sin(rev(ang))),
c(NA,NA)
)
}else{
coord<-rbind(
cbind(x0.loop+(r0.loop+swid/2)*cos(ang),
y0.loop+(r0.loop+swid/2)*sin(ang)),
cbind(x0.loop+(r0.loop-swid/2)*cos(rev(ang)),
y0.loop+(r0.loop-swid/2)*sin(rev(ang))),
c(NA,NA)
)
}
coord[,1]<-coord[,1]+x0 #Translate to (x0,y0)
coord[,2]<-coord[,2]+y0
coord
}
#Custom loop-drawing method for plot.network
#' Add Loops to a Plot
#'
#' \code{network.loop} draws a "loop" at a specified location; this is used to
#' designate self-ties in \code{\link{plot.network}}.
#'
#' \code{network.loop} is the companion to \code{\link{network.arrow}}; like
#' the latter, plot elements produced by \code{network.loop} are drawn using
#' \code{\link{polygon}}, and as such are scaled based on the current plotting
#' device. By default, loops are drawn so as to encompass a circular region of
#' radius \code{radius}, whose center is \code{offset} units from \code{x0,y0}
#' and at maximum distance from \code{xctr,yctr}. This is useful for functions
#' like \code{\link{plot.network}}, which need to draw loops incident to
#' vertices of varying radii.
#'
#' @param x0 a vector of x coordinates for points of origin.
#' @param y0 a vector of y coordinates for points of origin.
#' @param length arrowhead length, in current plotting units.
#' @param angle arrowhead angle (in degrees).
#' @param width width for loop body, in current plotting units (can be a
#' vector).
#' @param col loop body color (can be a vector).
#' @param border loop border color (can be a vector).
#' @param lty loop border line type (can be a vector).
#' @param offset offset for origin point (can be a vector).
#' @param edge.steps number of steps to use in approximating curves.
#' @param radius loop radius (can be a vector).
#' @param arrowhead boolean; should arrowheads be used? (Can be a vector.)
#' @param xctr x coordinate for the central location away from which loops
#' should be oriented.
#' @param yctr y coordinate for the central location away from which loops
#' should be oriented.
#' @param \dots additional arguments to \code{\link{polygon}}.
#' @return None.
#' @note \code{network.loop} is a direct adaptation of
#' \code{\link[sna]{gplot.loop}}, from the \code{sna} package.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network.arrow}}, \code{\link{plot.network}},
#' \code{\link{polygon}}
#' @keywords aplot graphs
#' @examples
#'
#' #Plot a few polygons with loops
#' plot(0,0,type="n",xlim=c(-2,2),ylim=c(-2,2),asp=1)
#' network.loop(c(0,0),c(1,-1),col=c(3,2),width=0.05,length=0.4,
#' offset=sqrt(2)/4,angle=20,radius=0.5,edge.steps=50,arrowhead=TRUE)
#' polygon(c(0.25,-0.25,-0.25,0.25,NA,0.25,-0.25,-0.25,0.25),
#' c(1.25,1.25,0.75,0.75,NA,-1.25,-1.25,-0.75,-0.75),col=c(2,3))
#'
#'
#' @export network.loop
network.loop<-function(x0,y0,length=0.1,angle=10,width=0.01,col=1,border=1,lty=1,offset=0,edge.steps=10,radius=1,arrowhead=TRUE,xctr=0,yctr=0,...){
if(length(x0)==0) #Leave if there's nothing to do
return()
#"Stretch" the arguments
n<-length(x0)
angle<-rep(angle,length.out=n)/360*2*pi
length<-rep(length,length.out=n)
width<-rep(width,length.out=n)
col<-rep(col,length.out=n)
border<-rep(border,length.out=n)
lty<-rep(lty,length.out=n)
rad<-rep(radius,length.out=n)
arrowhead<-rep(arrowhead,length.out=n)
offset<-rep(offset,length.out=n)
#Obtain coordinates
coord<-vector()
for(i in 1:n)
coord<-rbind(coord,make.loop.poly.coords(x0[i],y0[i],xctr,yctr,angle[i],length[i], width[i],offset[i],rad[i],arrowhead[i],edge.steps))
coord<-coord[-NROW(coord),]
#Draw polygons
polygon(coord,col=col,border=border,lty=lty,...)
}
#Introduce a function to make coordinates for a single vertex polygon
# this version just uses the raw radius, so triangles appear half the size of circles
old.make.vertex.poly.coords<-function(x,y,r,s,rot){
ang<-(1:s)/s*2*pi+rot*2*pi/360
rbind(cbind(x+r*cos(ang),y+r*sin(ang)),c(NA,NA))
}
#Introduce a function to make coordinates for a single vertex polygon
# all polygons produced will have equal area
make.vertex.poly.coords<-function(x,y,r,s,rot){
# trap some edge cases
if(is.na(s) || s<2){
return(rbind(c(x,y),c(NA,NA))) # return a single point
} else {
#scale r (circumradius) to make area equal
area<-pi*r^2 # target area based desired r as radius of circle
# solve for new r as polygon radius that would match the area of the circle
r<-sqrt(2*area / (s*sin(2*pi/s)))
ang<-(1:s)/s*2*pi+rot*2*pi/360
return(rbind(cbind(x+r*cos(ang),y+r*sin(ang)),c(NA,NA)))
}
}
#Routine to plot vertices, using polygons
#' Add Vertices to a Plot
#'
#' \code{network.vertex} adds one or more vertices (drawn using
#' \code{\link{polygon}}) to a plot.
#'
#' \code{network.vertex} draws regular polygons of specified radius and number
#' of sides, at the given coordinates. This is useful for routines such as
#' \code{\link{plot.network}}, which use such shapes to depict vertices.
#'
#' @param x a vector of x coordinates.
#' @param y a vector of y coordinates.
#' @param radius a vector of vertex radii.
#' @param sides a vector containing the number of sides to draw for each
#' vertex.
#' @param border a vector of vertex border colors.
#' @param col a vector of vertex interior colors.
#' @param lty a vector of vertex border line types.
#' @param rot a vector of vertex rotation angles (in degrees).
#' @param lwd a vector of vertex border line widths.
#' @param \dots Additional arguments to \code{\link{polygon}}
#' @return None
#' @note \code{network.vertex} is a direct adaptation of
#' \code{\link[sna]{gplot.vertex}} from the \code{sna} package.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{plot.network}}, \code{\link{polygon}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords aplot graphs
#' @examples
#'
#'
#' #Open a plot window, and place some vertices
#' plot(0,0,type="n",xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),asp=1)
#' network.vertex(cos((1:10)/10*2*pi),sin((1:10)/10*2*pi),col=1:10,
#' sides=3:12,radius=0.1)
#'
#'
#' @export network.vertex
network.vertex<-function(x,y,radius=1,sides=4,border=1,col=2,lty=NULL,rot=0,lwd=1,...){
#Prep the vars
n<-length(x)
radius<-rep(radius,length.out=n)
sides<-rep(sides,length.out=n)
border<-rep(border,length.out=n)
col<-rep(col,length.out=n)
lty<-rep(lty,length.out=n)
rot<-rep(rot,length.out=n)
lwd<-rep(lwd,length.out=n)
#Obtain the coordinates
coord<-vector()
for(i in 1:length(x)) {
coord<-make.vertex.poly.coords(x[i],y[i],radius[i],sides[i],rot[i])
polygon(coord,border=border[i],col=col[i],lty=lty[i],lwd=lwd[i], ...)
}
#Plot the polygons
}
# draw a label for a network edge
#' Plots a label corresponding to an edge in a network plot.
#'
#' Draws a text labels on (or adjacent to) the line segments connecting
#' vertices on a network plot.
#'
#' Called internally by \code{\link{plot.network}} when \code{edge.label}
#' parameter is used. For directed, non-curved edges, the labels are shifted
#' towards the tail of the edge. Labels for curved edges are not shifted
#' because opposite-direction edges curve the opposite way. Makes a crude
#' attempt to shift labels to either side of line, and to draw the edge labels
#' for self-loops near the vertex. No attempt is made to avoid overlap between
#' vertex and edge labels.
#'
#' @param px0 vector of x coordinates of tail vertex of the edge
#' @param py0 vector of y coordinates of tail vertex of the edge
#' @param px1 vector of x coordinates of head vertex of the edge
#' @param py1 vector of y coordinate of head vertex of the edge
#' @param label vector strings giving labels to be drawn for edge edge
#' @param directed logical: is the underlying network directed? If FALSE,
#' labels will be drawn in the middle of the line segment, otherwise in the
#' first 3rd so that the labels for edges pointing in the opposite direction
#' will not overlap.
#' @param loops logical: if true, assuming the labels to be drawn belong to
#' loop-type edges and render appropriately
#' @param cex numeric vector giving the text expansion factor for each label
#' @param curve numeric vector controling the extent of edge curvature (0 =
#' straight line edges)
#' @param \dots additional arguments to be passed to \code{\link{text}}
#' @return no value is returned but text will be rendered on the active plot
#' @author skyebend
#' @export network.edgelabel
network.edgelabel<-function(px0,py0,px1,py1,label,directed,loops=FALSE,cex,curve=0,...){
curve<-rep(curve,length(label))
posl<-rep(0,length(label))
offsets<-rep(0.1,length(label))
if (loops){ # loops version
# assume coordinates are the first pair
# math is hard. For now just draw label near the vertex
lpx<-px0
lpy<-py0
# compute crude offset so that label doesn't land on vertex
# todo, this doesn't work well on all edge orientations
posl<-rep(0,length(label))
posl[(px0>px1) & (py0>py1)]<-4
posl[(px0<=px1) & (py0<=py1)]<-2
posl[(px0>px1) & (py0<=py1)]<-1
posl[(px0<=px1) & (py0>py1)]<-3
offsets<-rep(0.5,length(label))
} else { # either curved or straight line
if (all(curve==0)){ # straight line non-curved version
if (directed){
# draw labels off center of line so won't overlap
lpx<-px0+((px1-px0)/3)
lpy<-py0+((py1-py0)/3)
} else {
# draw labels on center of line
lpx<-px0+((px1-px0)/2)
lpy<-py0+((py1-py0)/2)
# assumes that line is straight
}
} else { # curved edge case
coords<-sapply(seq_len(length(label)),function(p){
make.arrow.poly.coords(px0[p],py0[p],px1[p],py1[p],ahangle = 0,ahlen=0,swid = 0,toff = 0,hoff=0,ahead = 0,curve=curve[p],csteps=2)[2,] # pick a point returned from the middle of the curve
})
lpx<-coords[1,]
lpy<-coords[2,]
# this should
}
# compute crude offset so that label doesn't land on line
# todo, this doesn't work well on all edge orientations
posl[(px0>px1) & (py0>py1)]<-1
posl[(px0<=px1) & (py0<=py1)]<-3
posl[(px0>px1) & (py0<=py1)]<-2
posl[(px0<=px1) & (py0>py1)]<-4
}
# debug coord location
text(lpx,lpy,labels=label,cex=cex,pos=posl,offset=offsets,...)
}
#Generic plot.network method.
#' Two-Dimensional Visualization for Network Objects
#'
#' \code{plot.network} produces a simple two-dimensional plot of network
#' \code{x}, using optional attribute \code{attrname} to set edge values. A
#' variety of options are available to control vertex placement, display
#' details, color, etc.
#'
#' \code{plot.network} is the standard visualization tool for the
#' \code{network} class. By means of clever selection of display parameters, a
#' fair amount of display flexibility can be obtained. Vertex layout -- if not
#' specified directly using \code{coord} -- is determined via one of the
#' various available algorithms. These should be specified via the \code{mode}
#' argument; see \code{\link{network.layout}} for a full list. User-supplied
#' layout functions are also possible -- see the aforementioned man page for
#' details.
#'
#' Note that where \code{is.hyper(x)==TRUE}, the network is converted to
#' bipartite adjacency form prior to computing coordinates. If
#' \code{interactive==TRUE}, then the user may modify the initial network
#' layout by selecting an individual vertex and then clicking on the location
#' to which this vertex is to be moved; this process may be repeated until the
#' layout is satisfactory.
#'
#' @rdname plot.network
#' @name plot.network.default
#'
#' @param x an object of class \code{network}.
#' @param attrname an optional edge attribute, to be used to set edge values.
#' @param label a vector of vertex labels, if desired; defaults to the vertex
#' labels returned by \code{\link{network.vertex.names}}. If \code{label} has
#' one element and it matches with a vertex attribute name, the value of the
#' attribute will be used. Note that labels may be set but hidden by the
#' \code{displaylabels} argument.
#' @param coord user-specified vertex coordinates, in an network.size(x)x2
#' matrix. Where this is specified, it will override the \code{mode} setting.
#' @param jitter boolean; should the output be jittered?
#' @param thresh real number indicating the lower threshold for tie values.
#' Only ties of value >\code{thresh} are displayed. By default,
#' \code{thresh}=0.
#' @param usearrows boolean; should arrows (rather than line segments) be used
#' to indicate edges?
#' @param mode the vertex placement algorithm; this must correspond to a
#' \code{\link{network.layout}} function.
#' @param displayisolates boolean; should isolates be displayed?
#' @param interactive boolean; should interactive adjustment of vertex
#' placement be attempted?
#' @param xlab x axis label.
#' @param ylab y axis label.
#' @param xlim the x limits (min, max) of the plot.
#' @param ylim the y limits of the plot.
#' @param pad amount to pad the plotting range; useful if labels are being
#' clipped.
#' @param label.pad amount to pad label boxes (if \code{boxed.labels==TRUE}),
#' in character size units.
#' @param displaylabels boolean; should vertex labels be displayed?
#' @param boxed.labels boolean; place vertex labels within boxes?
#' @param label.pos position at which labels should be placed, relative to
#' vertices. \code{0} results in labels which are placed away from the center
#' of the plotting region; \code{1}, \code{2}, \code{3}, and \code{4} result in
#' labels being placed below, to the left of, above, and to the right of
#' vertices (respectively); and \code{label.pos>=5} results in labels which are
#' plotted with no offset (i.e., at the vertex positions).
#' @param label.bg background color for label boxes (if
#' \code{boxed.labels==TRUE}); may be a vector, if boxes are to be of different
#' colors.
#' @param vertex.sides number of polygon sides for vertices; may be given as a
#' vector or a vertex attribute name, if vertices are to be of different types.
#' As of v1.12, radius of polygons are scaled so that all shapes have equal
#' area
#' @param vertex.rot angle of rotation for vertices (in degrees); may be given
#' as a vector or a vertex attribute name, if vertices are to be rotated
#' differently.
#' @param vertex.lwd line width of vertex borders; may be given as a vector or
#' a vertex attribute name, if vertex borders are to have different line
#' widths.
#' @param arrowhead.cex expansion factor for edge arrowheads.
#' @param label.cex character expansion factor for label text.
#' @param loop.cex expansion factor for loops; may be given as a vector or a
#' vertex attribute name, if loops are to be of different sizes.
#' @param vertex.cex expansion factor for vertices; may be given as a vector or
#' a vertex attribute name, if vertices are to be of different sizes.
#' @param edge.col color for edges; may be given as a vector, adjacency matrix,
#' or edge attribute name, if edges are to be of different colors.
#' @param label.col color for vertex labels; may be given as a vector or a
#' vertex attribute name, if labels are to be of different colors.
#' @param vertex.col color for vertices; may be given as a vector or a vertex
#' attribute name, if vertices are to be of different colors.
#' @param label.border label border colors (if \code{boxed.labels==TRUE}); may
#' be given as a vector, if label boxes are to have different colors.
#' @param vertex.border border color for vertices; may be given as a vector or
#' a vertex attribute name, if vertex borders are to be of different colors.
#' @param edge.lty line type for edge borders; may be given as a vector,
#' adjacency matrix, or edge attribute name, if edge borders are to have
#' different line types.
#' @param label.lty line type for label boxes (if \code{boxed.labels==TRUE});
#' may be given as a vector, if label boxes are to have different line types.
#' @param vertex.lty line type for vertex borders; may be given as a vector or
#' a vertex attribute name, if vertex borders are to have different line types.
#' @param edge.lwd line width scale for edges; if set greater than 0, edge
#' widths are scaled by \code{edge.lwd*dat}. May be given as a vector,
#' adjacency matrix, or edge attribute name, if edges are to have different
#' line widths.
#' @param edge.label if non-\code{NULL}, labels for edges will be drawn. May be
#' given as a vector, adjacency matrix, or edge attribute name, if edges are to
#' have different labels. A single value of \code{TRUE} will use edge ids as
#' labels. NOTE: currently doesn't work for curved edges.
#' @param edge.label.cex character expansion factor for edge label text; may be
#' given as a vector or a edge attribute name, if edge labels are to have
#' different sizes.
#' @param edge.label.col color for edge labels; may be given as a vector or a
#' edge attribute name, if labels are to be of different colors.
#' @param label.lwd line width for label boxes (if \code{boxed.labels==TRUE});
#' may be given as a vector, if label boxes are to have different line widths.
#' @param edge.len if \code{uselen==TRUE}, curved edge lengths are scaled by
#' \code{edge.len}.
#' @param edge.curve if \code{usecurve==TRUE}, the extent of edge curvature is
#' controlled by \code{edge.curv}. May be given as a fixed value, vector,
#' adjacency matrix, or edge attribute name, if edges are to have different
#' levels of curvature.
#' @param edge.steps for curved edges (excluding loops), the number of line
#' segments to use for the curve approximation.
#' @param loop.steps for loops, the number of line segments to use for the
#' curve approximation.
#' @param object.scale base length for plotting objects, as a fraction of the
#' linear scale of the plotting region. Defaults to 0.01.
#' @param uselen boolean; should we use \code{edge.len} to rescale edge
#' lengths?
#' @param usecurve boolean; should we use \code{edge.curve}?
#' @param suppress.axes boolean; suppress plotting of axes?
#' @param vertices.last boolean; plot vertices after plotting edges?
#' @param new boolean; create a new plot? If \code{new==FALSE}, vertices and
#' edges will be added to the existing plot.
#' @param layout.par parameters to the \code{\link{network.layout}} function
#' specified in \code{mode}.
#' @param \dots additional arguments to \code{\link{plot}}.
#' @return A two-column matrix containing the vertex positions as x,y
#' coordinates
#' @note \code{plot.network} is adapted (with minor modifications) from the
#' \code{\link[sna]{gplot}} function of the \code{sna} library (authors: Carter
#' T. Butts and Alex Montgomery); eventually, these two packages will be
#' integrated.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network}}, \code{\link{network.arrow}},
#' \code{\link{network.loop}}, \code{\link{network.vertex}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#'
#' Wasserman, S., and Faust, K. (1994). \emph{Social Network Analysis:
#' Methods and Applications.} Cambridge: Cambridge University Press.
#' @keywords hplot graphs
#' @examples
#'
#' #Construct a sparse graph
#' m<-matrix(rbinom(100,1,1.5/9),10)
#' diag(m)<-0
#' g<-network(m)
#'
#' #Plot the graph
#' plot(g)
#'
#' #Load Padgett's marriage data
#' data(flo)
#' nflo<-network(flo)
#' #Display the network, indicating degree and flagging the Medicis
#' plot(nflo, vertex.cex=apply(flo,2,sum)+1, usearrows=FALSE,
#' vertex.sides=3+apply(flo,2,sum),
#' vertex.col=2+(network.vertex.names(nflo)=="Medici"))
#' @export plot.network
#' @export
plot.network <- function(x, ...){
plot.network.default(x, ...)
}
#Two-dimensional network visualization; this was originally a direct port of the gplot
#routine from sna (Carter T. Butts )
#' @rdname plot.network
#' @usage \method{plot.network}{default}(x, attrname = NULL,
#' label = network.vertex.names(x), coord = NULL, jitter = TRUE,
#' thresh = 0, usearrows = TRUE, mode = "fruchtermanreingold",
#' displayisolates = TRUE, interactive = FALSE, xlab = NULL,
#' ylab = NULL, xlim = NULL, ylim = NULL, pad = 0.2, label.pad = 0.5,
#' displaylabels = !missing(label), boxed.labels = FALSE, label.pos = 0,
#' label.bg = "white", vertex.sides = 50, vertex.rot = 0, vertex.lwd=1,
#' arrowhead.cex = 1, label.cex = 1, loop.cex = 1, vertex.cex = 1,
#' edge.col = 1, label.col = 1, vertex.col = 2, label.border = 1,
#' vertex.border = 1, edge.lty = 1, label.lty = NULL, vertex.lty = 1,
#' edge.lwd = 0, edge.label = NULL, edge.label.cex = 1,
#' edge.label.col = 1, label.lwd = par("lwd"), edge.len = 0.5,
#' edge.curve = 0.1, edge.steps = 50, loop.steps = 20,
#' object.scale = 0.01, uselen = FALSE, usecurve = FALSE,
#' suppress.axes = TRUE, vertices.last = TRUE, new = TRUE,
#' layout.par = NULL, \dots)
#' @export plot.network.default
#' @rawNamespace S3method(plot.network,default)
plot.network.default<-function(x,
attrname=NULL,
label=network.vertex.names(x),
coord=NULL,
jitter=TRUE,
thresh=0,
usearrows=TRUE,
mode="fruchtermanreingold",
displayisolates=TRUE,
interactive=FALSE,
xlab=NULL,
ylab=NULL,
xlim=NULL,
ylim=NULL,
pad=0.2,
label.pad=0.5,
displaylabels=!missing(label),
boxed.labels=FALSE,
label.pos=0,
label.bg="white",
vertex.sides=50,
vertex.rot=0,
vertex.lwd=1,
arrowhead.cex=1,
label.cex=1,
loop.cex=1,
vertex.cex=1,
edge.col=1,
label.col=1,
vertex.col=2,
label.border=1,
vertex.border=1,
edge.lty=1,
label.lty=NULL,
vertex.lty=1,
edge.lwd=0,
edge.label=NULL,
edge.label.cex=1,
edge.label.col=1,
label.lwd=par("lwd"),
edge.len=0.5,
edge.curve=0.1,
edge.steps=50,
loop.steps=20,
object.scale=0.01,
uselen=FALSE,
usecurve=FALSE,
suppress.axes=TRUE,
vertices.last=TRUE,
new=TRUE,
layout.par=NULL,
...){
#Check to see that things make sense
if(!is.network(x))
stop("plot.network requires a network object.")
if(network.size(x)==0)
stop("plot.network called on a network of order zero - nothing to plot.")
#Turn the annoying locator bell off, and remove recursion limit
old.opts <- options(locatorBell=FALSE,expressions=500000)
on.exit(options(old.opts))
#Create a useful interval inclusion operator
"%iin%"<-function(x,int) (x>=int[1])&(x<=int[2])
#Extract the network to be displayed
if(is.hyper(x)){ #Is this a hypergraph? If so, use two-mode form.
#Create a new graph to store the two-mode structure
xh<-network.initialize(network.size(x)+sum(!sapply(x$mel, is.null)),
directed=is.directed(x))
#Port attributes, in case we need them
for(i in list.vertex.attributes(x)){
set.vertex.attribute(xh,attrname=i,
value=get.vertex.attribute(x,attrname=i,null.na=FALSE,unlist=FALSE),
v=1:network.size(x))
}
for(i in list.network.attributes(x)){
if(!(i%in%c("bipartite","directed","hyper","loops","mnext","multiple",
"n")))
set.network.attribute(xh,attrname=i,
value=get.network.attribute(x,attrname=i,unlist=FALSE))
}
#Now, import the edges
cnt<-1
for(i in 1:length(x$mel)){ #Not a safe way to do this, long-term
if(!is.null(x$mel[[i]])){
for(j in x$mel[[i]]$outl){
if(!is.adjacent(xh,j,network.size(x)+cnt))
add.edge(xh,j,network.size(x)+cnt,names.eval=names(x$mel[[i]]$atl),
vals.eval=x$mel[[i]]$atl)
}
for(j in x$mel[[i]]$inl){
if(!is.adjacent(xh,network.size(x)+cnt,j)){
add.edge(xh,network.size(x)+cnt,j,names.eval=names(x$mel[[i]]$atl),
vals.eval=x$mel[[i]]$atl)
}
}
cnt<-cnt+1 #Increment the edge counter
}
}
cnt<-cnt-1
if(length(label)==network.size(x)) #Fix labels, if needed
label<-c(label,paste("e",1:cnt,sep=""))
xh%v%"vertex.names"<-c(x%v%"vertex.names",paste("e",1:cnt,sep=""))
x<-xh
n<-network.size(x)
d<-as.matrix.network(x,matrix.type="edgelist",attrname=attrname)
if(!is.directed(x))
usearrows<-FALSE
}else if(is.bipartite(x)){
n<-network.size(x)
d<-as.matrix.network(x,matrix.type="edgelist",attrname=attrname)
usearrows<-FALSE
}else{
n<-network.size(x)
d<-as.matrix.network(x,matrix.type="edgelist",attrname=attrname)
if(!is.directed(x))
usearrows<-FALSE
}
#Make sure that edge values are in place, matrix has right shape, etc.
if(NCOL(d)==2){
if(NROW(d)==0)
d<-matrix(nrow=0,ncol=3)
else
d<-cbind(d,rep(1,NROW(d)))
}
diag<-has.loops(x) #Check for existence of loops
#Replace NAs with 0s
d[is.na(d)]<-0
#Determine which edges should be used when plotting
edgetouse<-d[,3]>thresh
d<-d[edgetouse,,drop=FALSE]
#Save original matrix, which we may use below
d.raw<-d
#Determine coordinate placement
if(!is.null(coord)){ #If the user has specified coords, override all other considerations
cx<-coord[,1]
cy<-coord[,2]
}else{ #Otherwise, use the specified layout function
layout.fun<-try(match.fun(paste("network.layout.",mode,sep="")), silent=TRUE)
if(inherits(layout.fun,"try-error"))
stop("Error in plot.network.default: no layout function for mode ",mode)
temp<-layout.fun(x,layout.par)
cx<-temp[,1]
cy<-temp[,2]
}
#Jitter the coordinates if need be
if(jitter){
cx<-jitter(cx)
cy<-jitter(cy)
}
#Which nodes should we use?
use<-displayisolates|(((sapply(x$iel,length)+sapply(x$oel,length))>0))
#Deal with axis labels
if(is.null(xlab))
xlab=""
if(is.null(ylab))
ylab=""
#Set limits for plotting region
if(is.null(xlim))
xlim<-c(min(cx[use])-pad,max(cx[use])+pad) #Save x, y limits
if(is.null(ylim))
ylim<-c(min(cy[use])-pad,max(cy[use])+pad)
xrng<-diff(xlim) #Force scale to be symmetric
yrng<-diff(ylim)
xctr<-(xlim[2]+xlim[1])/2 #Get center of plotting region
yctr<-(ylim[2]+ylim[1])/2
if(xrng0){
#Edge color
edge.col<-plotArgs.network(x,'edge.col',edge.col,d=d)
#Edge line type
edge.lty<-plotArgs.network(x,'edge.lty',edge.lty,d=d)
#Edge line width
edge.lwd<-plotArgs.network(x,'edge.lwd',edge.lwd,d=d)
#Edge curve
# TODO: can't move this into prepare plot args becaue it also sets the e.curve.as.mult
# but I think it could be refactored to use the d[] array as the other edge functions do
if(!is.null(edge.curve)){
if(length(dim(edge.curve))==2){
edge.curve<-edge.curve[d[,1:2]]
e.curv.as.mult<-FALSE
}else{
if(length(edge.curve)==1)
e.curv.as.mult<-TRUE
else
e.curv.as.mult<-FALSE
edge.curve<-rep(edge.curve,length.out=NROW(d))
}
}else if(is.character(edge.curve)&&(length(edge.curve)==1)){
temp<-edge.curve
edge.curve<-(x%e%edge.curve)[edgetouse]
if(all(is.na(edge.curve)))
stop("Attribute '",temp,"' had illegal missing values for edge.curve or was not present in plot.network.default.")
e.curv.as.mult<-FALSE
}else{
edge.curve<-rep(0,length.out=NROW(d))
e.curv.as.mult<-FALSE
}
# only evaluate edge label stuff if we will draw label
if(!is.null(edge.label)){
#Edge label
edge.label<-plotArgs.network(x,'edge.label',edge.label,d=d)
#Edge label color
edge.label.col<-plotArgs.network(x,'edge.label.col',edge.label.col,d=d)
#Edge label cex
edge.label.cex<-plotArgs.network(x,'edge.label.cex',edge.label.cex,d=d)
} # end edge label setup block
#Proceed with edge setup
dist<-((cx[d[,1]]-cx[d[,2]])^2+(cy[d[,1]]-cy[d[,2]])^2)^0.5 #Get the inter-point distances for curves
tl<-d.raw*dist #Get rescaled edge lengths
tl.max<-max(tl) #Get maximum edge length
for(i in 1:NROW(d)){
if(use[d[i,1]]&&use[d[i,2]]){ #Plot edges for displayed vertices (wait,doesn't 'use' track isolates, which don't have edges anyway?)
px0[i]<-as.double(cx[d[i,1]]) #Store endpoint coordinates
py0[i]<-as.double(cy[d[i,1]])
px1[i]<-as.double(cx[d[i,2]])
py1[i]<-as.double(cy[d[i,2]])
e.toff[i]<-vertex.radius[d[i,1]] #Store endpoint offsets
e.hoff[i]<-vertex.radius[d[i,2]]
e.col[i]<-edge.col[i] #Store other edge attributes
e.type[i]<-edge.lty[i]
e.lwd[i]<-edge.lwd[i]
e.diag[i]<-d[i,1]==d[i,2] #Is this a loop?
e.rad[i]<-vertex.radius[d[i,1]]*loop.cex[d[i,1]]
if(uselen){ #Should we base curvature on interpoint distances?
if(tl[i]>0){
e.len<-dist[i]*tl.max/tl[i]
e.curv[i]<-edge.len*sqrt((e.len/2)^2-(dist[i]/2)^2)
}else{
e.curv[i]<-0
}
}else{ #Otherwise, use prespecified edge.curve
if(e.curv.as.mult) #If it's a scalar, multiply by edge str
e.curv[i]<-edge.curve[i]*d.raw[i]
else
e.curv[i]<-edge.curve[i]
}
}
}
}# end edges block
#Plot loops for the diagonals, if diag==TRUE, rotating wrt center of mass
if(diag&&(length(px0)>0)&&sum(e.diag>0)){ #Are there any loops present?
network.loop(as.vector(px0)[e.diag],as.vector(py0)[e.diag], length=1.5*baserad*arrowhead.cex,angle=25,width=e.lwd[e.diag]*baserad/10,col=e.col[e.diag],border=e.col[e.diag],lty=e.type[e.diag],offset=e.hoff[e.diag],edge.steps=loop.steps,radius=e.rad[e.diag],arrowhead=usearrows,xctr=mean(cx[use]),yctr=mean(cy[use]))
if(!is.null(edge.label)){
network.edgelabel(px0,py0,0,0,edge.label[e.diag],directed=is.directed(x),cex=edge.label.cex[e.diag],col=edge.label.col[e.diag],loops=TRUE)
}
}
#Plot standard (i.e., non-loop) edges
if(length(px0)>0){ #If edges are present, remove loops from consideration
px0<-px0[!e.diag]
py0<-py0[!e.diag]
px1<-px1[!e.diag]
py1<-py1[!e.diag]
e.curv<-e.curv[!e.diag]
e.lwd<-e.lwd[!e.diag]
e.type<-e.type[!e.diag]
e.col<-e.col[!e.diag]
e.hoff<-e.hoff[!e.diag]
e.toff<-e.toff[!e.diag]
e.rad<-e.rad[!e.diag]
}
if(!usecurve&!uselen){ #Straight-line edge case
if(length(px0)>0){
network.arrow(as.vector(px0),as.vector(py0),as.vector(px1), as.vector(py1),length=2*baserad*arrowhead.cex,angle=20,col=e.col,border=e.col,lty=e.type,width=e.lwd*baserad/10,offset.head=e.hoff,offset.tail=e.toff,arrowhead=usearrows)
if(!is.null(edge.label)){
network.edgelabel(px0,py0,px1,py1,edge.label[!e.diag],directed=is.directed(x),cex=edge.label.cex[!e.diag],col=edge.label.col[!e.diag])
}
}
}else{ #Curved edge case
if(length(px0)>0){
network.arrow(as.vector(px0),as.vector(py0),as.vector(px1), as.vector(py1),length=2*baserad*arrowhead.cex,angle=20,col=e.col,border=e.col,lty=e.type,width=e.lwd*baserad/10,offset.head=e.hoff,offset.tail=e.toff,arrowhead=usearrows,curve=e.curv,edge.steps=edge.steps)
if(!is.null(edge.label)){
network.edgelabel(px0,py0,px1,py1,edge.label[!e.diag],directed=is.directed(x),cex=edge.label.cex[!e.diag],col=edge.label.col[!e.diag],curve=e.curv)
}
}
}
#Plot vertices now, if we haven't already done so
if(vertices.last)
network.vertex(cx[use],cy[use],radius=vertex.radius[use], sides=vertex.sides[use],col=vertex.col[use],border=vertex.border[use],lty=vertex.lty[use],rot=vertex.rot[use], lwd=vertex.lwd[use])
#Plot vertex labels, if needed
if(displaylabels&(!all(label==""))&(!all(use==FALSE))){
if (label.pos==0){
xhat <- yhat <- rhat <- rep(0,n)
#Set up xoff yoff and roff when we get odd vertices
xoff <- cx[use]-mean(cx[use])
yoff <- cy[use]-mean(cy[use])
roff <- sqrt(xoff^2+yoff^2)
#Loop through vertices
for (i in (1:n)[use]){
#Find all in and out ties that aren't loops
ij <- unique(c(d[d[,2]==i&d[,1]!=i,1],d[d[,1]==i&d[,2]!=i,2]))
ij.n <- length(ij)
if (ij.n>0) {
#Loop through all ties and add each vector to label direction
for (j in ij){
dx <- cx[i]-cx[j]
dy <- cy[i]-cy[j]
dr <- sqrt(dx^2+dy^2)
xhat[i] <- xhat[i]+dx/dr
yhat[i] <- yhat[i]+dy/dr
}
#Take the average of all the ties
xhat[i] <- xhat[i]/ij.n
yhat[i] <- yhat[i]/ij.n
rhat[i] <- sqrt(xhat[i]^2+yhat[i]^2)
if (!is.nan(rhat[i]) && rhat[i]!=0) { # watch out for NaN when vertices have same position
# normalize direction vector
xhat[i] <- xhat[i]/rhat[i]
yhat[i] <- yhat[i]/rhat[i]
} else { #if no direction, make xhat and yhat away from center
xhat[i] <- xoff[i]/roff[i]
yhat[i] <- yoff[i]/roff[i]
}
} else { #if no ties, make xhat and yhat away from center
xhat[i] <- xoff[i]/roff[i]
yhat[i] <- yoff[i]/roff[i]
}
if ( is.nan(xhat[i]) || xhat[i]==0 ) xhat[i] <- .01 #jitter to avoid labels on points
if (is.nan(yhat[i]) || yhat[i]==0 ) yhat[i] <- .01
}
xhat <- xhat[use]
yhat <- yhat[use]
} else if (label.pos<5) {
xhat <- switch(label.pos,0,-1,0,1)
yhat <- switch(label.pos,-1,0,1,0)
} else if (label.pos==6) {
xoff <- cx[use]-mean(cx[use])
yoff <- cy[use]-mean(cy[use])
roff <- sqrt(xoff^2+yoff^2)
xhat <- xoff/roff
yhat <- yoff/roff
} else {
xhat <- 0
yhat <- 0
}
os<-par()$cxy*mean(label.cex,na.rm = TRUE) # don't think this is actually used?
lw<-strwidth(label[use],cex=label.cex)/2
lh<-strheight(label[use],cex=label.cex)/2
if(boxed.labels){
rect(cx[use]+xhat*vertex.radius[use]-(lh*label.pad+lw)*((xhat<0)*2+ (xhat==0)*1),
cy[use]+yhat*vertex.radius[use]-(lh*label.pad+lh)*((yhat<0)*2+ (yhat==0)*1),
cx[use]+xhat*vertex.radius[use]+(lh*label.pad+lw)*((xhat>0)*2+ (xhat==0)*1),
cy[use]+yhat*vertex.radius[use]+(lh*label.pad+lh)*((yhat>0)*2+ (yhat==0)*1),
col=label.bg,border=label.border,lty=label.lty,lwd=label.lwd)
}
text(cx[use]+xhat*vertex.radius[use]+(lh*label.pad+lw)*((xhat>0)-(xhat<0)),
cy[use]+yhat*vertex.radius[use]+(lh*label.pad+lh)*((yhat>0)-(yhat<0)),
label[use],cex=label.cex,col=label.col,offset=0)
}
#If interactive, allow the user to mess with things
if(interactive&&((length(cx)>0)&&(!all(use==FALSE)))){
#Set up the text offset increment
os<-c(0.2,0.4)*par()$cxy
#Get the location for text messages, and write to the screen
textloc<-c(min(cx[use])-pad,max(cy[use])+pad)
tm<-"Select a vertex to move, or click \"Finished\" to end."
tmh<-strheight(tm)
tmw<-strwidth(tm)
text(textloc[1],textloc[2],tm,adj=c(0,0.5)) #Print the initial instruction
fm<-"Finished"
finx<-c(textloc[1],textloc[1]+strwidth(fm))
finy<-c(textloc[2]-3*tmh-strheight(fm)/2,textloc[2]-3*tmh+strheight(fm)/2)
finbx<-finx+c(-os[1],os[1])
finby<-finy+c(-os[2],os[2])
rect(finbx[1],finby[1],finbx[2],finby[2],col="white")
text(finx[1],mean(finy),fm,adj=c(0,0.5))
#Get the click location
clickpos<-unlist(locator(1))
#If the click is in the "finished" box, end our little game. Otherwise,
#relocate a vertex and redraw.
if((clickpos[1]%iin%finbx)&&(clickpos[2]%iin%finby)){
cl<-match.call() #Get the args of the current function
cl$interactive<-FALSE #Turn off interactivity
cl$coord<-cbind(cx,cy) #Set the coordinates
cl$x<-x #"Fix" the data array
return(eval.parent(cl)) #Execute the function and return
}else{
#Figure out which vertex was selected
clickdis<-sqrt((clickpos[1]-cx[use])^2+(clickpos[2]-cy[use])^2)
selvert<-match(min(clickdis),clickdis)
#Create usable labels, if the current ones aren't
if(all(label==""))
label<-1:n
#Clear out the old message, and write a new one
rect(textloc[1],textloc[2]-tmh/2,textloc[1]+tmw,textloc[2]+tmh/2, border="white",col="white")
tm<-"Where should I move this vertex?"
tmh<-strheight(tm)
tmw<-strwidth(tm)
text(textloc[1],textloc[2],tm,adj=c(0,0.5))
fm<-paste("Vertex",label[use][selvert],"selected")
finx<-c(textloc[1],textloc[1]+strwidth(fm))
finy<-c(textloc[2]-3*tmh-strheight(fm)/2,textloc[2]-3*tmh+ strheight(fm)/2)
finbx<-finx+c(-os[1],os[1])
finby<-finy+c(-os[2],os[2])
rect(finbx[1],finby[1],finbx[2],finby[2],col="white")
text(finx[1],mean(finy),fm,adj=c(0,0.5))
#Get the destination for the new vertex
clickpos<-unlist(locator(1))
#Set the coordinates accordingly
cx[use][selvert]<-clickpos[1]
cy[use][selvert]<-clickpos[2]
#Iterate (leaving interactivity on)
cl<-match.call() #Get the args of the current function
cl$coord<-cbind(cx,cy) #Set the coordinates
cl$x<-x #"Fix" the data array
return(eval.parent(cl)) #Execute the function and return
}
}
#Return the vertex positions, should they be needed
invisible(cbind(cx,cy))
}
# moving all of the plot argument checking and expansion into a single function
# so that it will be acessible from other plot-related tools (like ndtv)
# argName = character named of argument to be checked/expaneded
# argValue = value passed in by user, to be processed/expanded
# d is an edgelist matrix of edge values optionally used by some edge attribute functions
# edgetouse the set of edge ids to be used (in case some edges are not being shown)
#' Expand and transform attributes of networks to values appropriate for
#' aguments to plot.network
#'
#' This is primairly an internal function called by \code{plot.network} or by
#' external packages such as \code{ndtv} that want to prepare
#' \code{plot.network} graphic arguments in a standardized way.
#'
#' Given a network object, the name of graphic parameter argument to
#' \code{plot.network} and value, it will if necessary transform the value, or
#' extract it from the network, according to the description in
#' \code{\link{plot.network}}. For some attributes, if the value is the name of
#' a vertex or edge attribute, the appropriate values will be extracted from
#' the network before transformation.
#'
#' @rdname preparePlotArgs
#' @name plotArgs.network
#'
#' @param x a \code{network} object which is going to be plotted
#' @param argName character, the name of \code{plot.network} graphic parameter
#' @param argValue value for the graphic paramter named in \code{argName} which
#' to be transformed/prepared. For many attributes, if this is a single
#' character vector it will be assumed to be the name of a vertex or edge
#' attribute to be extracted and transformed
#' @param d is an edgelist matrix of edge values optionally used by some edge
#' attribute functions
#' @param edgetouse numeric vector giving set of edge ids to be used (in case
#' some edges are not being shown) required by some attributes
#' @return returns a vector with length corresponding to the number of vertices
#' or edges (depending on the paramter type) giving the appropriately prepared
#' values for the parameter type. If the values or specified attribute can not
#' be processed correctly, and Error may occur.
#' @author skyebend@@uw.edu
#' @seealso See also \code{\link{plot.network}}
#' @examples
#'
#' net<-network.initialize(3)
#' set.vertex.attribute(net,'color',c('red','green','blue'))
#' set.vertex.attribute(net,'charm',1:3)
#' # replicate a single colorname value
#' plotArgs.network(net,'vertex.col','purple')
#' # map the 'color' attribute to color
#' plotArgs.network(net,'vertex.col','color')
#' # similarly for a numeric attribute ...
#' plotArgs.network(net,'vertex.cex',12)
#' plotArgs.network(net,'vertex.cex','charm')
#'
#' @export plotArgs.network
plotArgs.network<-function(x,argName, argValue,d=NULL,edgetouse=NULL){
n<-network.size(x)
# count the number of edges
# not sure if nrow d is every differnt, than network edgecount, but just being safe
if(!is.null(d)){
nE<-NROW(d)
} else {
nE<-network.edgecount(x)
}
if(is.null(edgetouse)){
edgetouse<-seq_len(nE) # use all the edges
}
# if d exists, it may need to be subset to the number of edges
if (!is.null(d)){
d<-d[edgetouse,,drop=FALSE]
}
# assign the value to a local variable with the appropriate name
assign(argName,argValue)
#Fill out vertex vectors; assume we're using attributes if chars used
# TODO: only one of the code blocks below should execute, set up as a switch?
switch(argName,
# ----- vertex labels ---------------------------
label=if(is.character(label)&(length(label)==1)){
temp<-label
if(temp%in%list.vertex.attributes(x)){
label <- rep(get.vertex.attribute(x,temp),length.out=n)
if(all(is.na(label))){
stop("Attribute '",temp,"' had illegal missing values for label or was not present in plot.network.default.")
}
} else { # didn't match with a vertex attribute, assume we are supposed to replicate it
label <- rep(label,length.out=n)
}
}else{
label <- rep(as.character(label),length.out=n)
}
,
# ------ vertex sizes (vertex.cex) --------------------
vertex.cex=if(is.character(vertex.cex)&(length(vertex.cex)==1)){
temp<-vertex.cex
vertex.cex <- rep(get.vertex.attribute(x,vertex.cex),length.out=n)
if(all(is.na(vertex.cex)))
stop("Attribute '",temp,"' had illegal missing values for vertex.cex or was not present in plot.network.default.")
}else
vertex.cex <- rep(vertex.cex,length.out=n)
,
# ------ vertex sides (number of sides for polygon) ---------
vertex.sides=if(is.character(vertex.sides)&&(length(vertex.sides==1))){
temp<-vertex.sides
vertex.sides <- rep(get.vertex.attribute(x,vertex.sides),length.out=n)
if(all(is.na(vertex.sides)))
stop("Attribute '",temp,"' had illegal missing values for vertex.sides or was not present in plot.network.default.")
}else
vertex.sides <- rep(vertex.sides,length.out=n)
,
# --------- vertex border --------------------
vertex.border=if(is.character(vertex.border)&&(length(vertex.border)==1)){
temp<-vertex.border
vertex.border <- rep(get.vertex.attribute(x,vertex.border),length.out=n)
if(all(is.na(vertex.border)))
vertex.border <- rep(temp,length.out=n) #Assume it was a color word
else{
if(!all(is.color(vertex.border),na.rm=TRUE))
vertex.border<-as.color(vertex.border)
}
}else
vertex.border <- rep(vertex.border,length.out=n)
,
# -------- vertex color ------------------------
vertex.col=if(is.character(vertex.col)&&(length(vertex.col)==1)){
temp<-vertex.col
vertex.col <- rep(get.vertex.attribute(x,vertex.col),length.out=n)
if(all(is.na(vertex.col)))
vertex.col <- rep(temp,length.out=n) #Assume it was a color word
else{
if(!all(is.color(vertex.col),na.rm=TRUE))
vertex.col<-as.color(vertex.col)
}
}else
vertex.col <- rep(vertex.col,length.out=n)
,
# ------- vertex line type (vertex.lty) --------------------
vertex.lty=if(is.character(vertex.lty)&&(length(vertex.lty)==1)){
temp<-vertex.lty
vertex.lty <- rep(get.vertex.attribute(x,vertex.lty),length.out=n)
if(all(is.na(vertex.lty)))
stop("Attribute '",temp,"' had illegal missing values for vertex.col or was not present in plot.network.default.")
}else
vertex.lty <- rep(vertex.lty,length.out=n)
,
# ------- vertex rotation --------------------------------------
vertex.rot=if(is.character(vertex.rot)&&(length(vertex.rot)==1)){
temp<-vertex.rot
vertex.rot <- rep(get.vertex.attribute(x,vertex.rot),length.out=n)
if(all(is.na(vertex.rot)))
stop("Attribute '",temp,"' had illegal missing values for vertex.rot or was not present in plot.network.default.")
}else
vertex.rot <- rep(vertex.rot,length.out=n)
,
# -------- vertex line width --------------------------
vertex.lwd=if(is.character(vertex.lwd)&&(length(vertex.lwd)==1)){
temp<-vertex.lwd
vertex.lwd <- rep(get.vertex.attribute(x,vertex.lwd),length.out=n)
if(all(is.na(vertex.lwd)))
stop("Attribute '",temp,"' had illegal missing values for vertex.lwd or was not present in plot.network.default.")
}else
vertex.lwd <- rep(vertex.lwd,length.out=n)
,
# -------- vertex self-loop size -----------------------
loop.cex=if(is.character(loop.cex)&&(length(loop.cex)==1)){
temp<-loop.cex
loop.cex <- rep(get.vertex.attribute(x,loop.cex),length.out=n)
if(all(is.na(loop.cex)))
stop("Attribute ",temp," had illegal missing values for loop.cex or was not present in plot.network.default.")
}else
loop.cex <- rep(loop.cex,length.out=n)
,
# --------- vertex label color -----------------------------
label.col=if(is.character(label.col)&&(length(label.col)==1)){
temp<-label.col
label.col <- rep(get.vertex.attribute(x,label.col),length.out=n)
if(all(is.na(label.col)))
label.col <- rep(temp,length.out=n) #Assume it was a color word
else{
if(!all(is.color(label.col),na.rm=TRUE))
label.col<-as.color(label.col)
}
}else
label.col <- rep(label.col,length.out=n)
,
# -------- vertex label border ------------------------------
label.border=if(is.character(label.border)&&(length(label.border)==1)){
temp<-label.border
label.border <- rep(get.vertex.attribute(x,label.border),length.out=n)
if(all(is.na(label.border)))
label.border <- rep(temp,length.out=n) #Assume it was a color word
else{
if(!all(is.color(label.border),na.rm=TRUE))
label.border<-as.color(label.border)
}
}else{
label.border <- rep(label.border,length.out=n)
}
,
# ------- vertex label border background color ----------------
label.bg=if(is.character(label.bg)&&(length(label.bg)==1)){
temp<-label.bg
label.bg <- rep(get.vertex.attribute(x,label.bg),length.out=n)
if(all(is.na(label.bg)))
label.bg <- rep(temp,length.out=n) #Assume it was a color word
else{
if(!all(is.color(label.bg),na.rm=TRUE))
label.bg<-as.color(label.bg)
}
}else{
label.bg <- rep(label.bg,length.out=n)
}
,
# ------ Edge color---------
edge.col=if(length(dim(edge.col))==2) #Coerce edge.col/edge.lty to vector form
edge.col<-edge.col[d[,1:2]]
else if(is.character(edge.col)&&(length(edge.col)==1)){
temp<-edge.col
edge.col<-x%e%edge.col
if(!is.null(edge.col)){
edge.col<-edge.col[edgetouse]
if(!all(is.color(edge.col),na.rm=TRUE))
edge.col<-as.color(edge.col)
}else{
edge.col<-rep(temp,length.out=nE) #Assume it was a color word
}
}else{
edge.col<-rep(edge.col,length.out=nE)
}
,
# ----------- Edge line type ------------------
edge.lty=if(length(dim(edge.lty))==2){
edge.lty<-edge.lty[d[,1:2]]
}else if(is.character(edge.lty)&&(length(edge.lty)==1)){
temp<-edge.lty
edge.lty<-(x%e%edge.lty)[edgetouse]
if(all(is.na(edge.lty)))
stop("Attribute '",temp,"' had illegal missing values for edge.lty or was not present in plot.network.default.")
}else{
edge.lty<-rep(edge.lty,length.out=nE)
}
,
# ----------- Edge line width ------
edge.lwd=if(length(dim(edge.lwd))==2){
edge.lwd<-edge.lwd[d[,1:2]] # what is going on here? aren't these the incident vertices? # for later matrix lookup?
}else if(is.character(edge.lwd)&&(length(edge.lwd)==1)){
temp<-edge.lwd
edge.lwd<-(x%e%edge.lwd)[edgetouse]
if(all(is.na(edge.lwd))){
stop("Attribute '",temp,"' had illegal missing values for edge.lwd or was not present in plot.network.default.")
}
}else{
if(length(edge.lwd)==1){ # if lwd has only one element..
if(edge.lwd>0){ # ... and that element > 0 ,use it as a scale factor for the edge values in d
# .. unless d is missing
if (!is.null(d)){
edge.lwd<-edge.lwd*d[,3]
} else {
# d is missing, so just replicate
}
edge.lwd<-rep(edge.lwd,length.out=nE)
}else{ # edge is zero or less, so set it to 1
edge.lwd<-rep(1,length.out=nE)
}
} else { # just replacte for the number of edges
edge.lwd<-rep(edge.lwd,length.out=nE)
}
}
,
# ----------- Edge curve---------------
edge.curve=if(!is.null(edge.curve)){
if(length(dim(edge.curve))==2){
edge.curve<-edge.curve[d[,1:2]]
e.curv.as.mult<-FALSE
}else{
if(length(edge.curve)==1){
e.curv.as.mult<-TRUE
}else{
e.curv.as.mult<-FALSE
}
edge.curve<-rep(edge.curve,length.out=nE)
}
}else if(is.character(edge.curve)&&(length(edge.curve)==1)){
temp<-edge.curve
edge.curve<-(x%e%edge.curve)[edgetouse]
if(all(is.na(edge.curve))){
stop("Attribute '",temp,"' had illegal missing values for edge.curve or was not present in plot.network.default.")
}
e.curv.as.mult<-FALSE
}else{
edge.curve<-rep(0,length.out=nE)
e.curv.as.mult<-FALSE
}
,
# -------- edge label ----------------------
edge.label=if(length(dim(edge.label))==2){ #Coerce edge.label to vector form
edge.label<-edge.label[d[,1:2]]
}else if(is.character(edge.label)&&(length(edge.label)==1)){
temp<-edge.label
edge.label<-x%e%edge.label
if(!is.null(edge.label)){
edge.label<-edge.label[edgetouse]
}else
edge.label<-rep(temp,length.out=nE) #Assume it was a value to replicate
}else if(is.logical(edge.label)&&(length(edge.label)==1)) {
if (edge.label){
# default to edge ids.
edge.label<-valid.eids(x)[edgetouse]
} else {
# don't draw edge labels if set to FALSE
edge.label<-NULL
}
}else{
# do nothing and hope for the best!
edge.label<-rep(edge.label,length.out=nE)
}
,
# ------ edge label color --------------------
#Edge label color
edge.label.col=if(length(dim(edge.label.col))==2){ #Coerce edge.label.col
edge.label.col<-edge.label.col[d[,1:2]]
} else if(is.character(edge.label.col)&&(length(edge.label.col)==1)){
temp<-edge.label.col
edge.label.col<-x%e%edge.label.col
if(!is.null(edge.label.col)){
edge.label.col<-edge.label.col[edgetouse]
if(!all(is.color(edge.label.col),na.rm=TRUE))
edge.label.col<-as.color(edge.label.col)
}else
edge.label.col<-rep(temp,length.out=nE) #Assume it was a color word
}else{
edge.label.col<-rep(edge.label.col,length.out=nE)
}
,
# ------- edge.label.cex --------------------
#Edge label cex
edge.label.cex=if(length(dim(edge.label.cex))==2)
edge.label.cex<-edge.label.cex[d[,1:2]]
else if(is.character(edge.label.cex)&&(length(edge.label.cex)==1)){
temp<-edge.label.cex
edge.label.cex<-(x%e%edge.label.cex)[edgetouse]
if(all(is.na(edge.label.cex)))
stop("Attribute '",temp,"' had illegal missing values for edge.label.cex or was not present in plot.network.default.")
}else{
edge.label.cex<-rep(edge.label.cex,length.out=nE)
}
# case in which none of the argument names match up
# stop('argument "',argName,'"" does not match with any of the plot.network arguments')
# can't error out, because this function will be called with non-network args, so just
# return the value passed in
) # end switch block
# now return the checked / expanded value
return(get(argName))
}
network/R/printsum.R 0000644 0001762 0000144 00000027457 13737227152 014200 0 ustar ligges users ######################################################################
#
# printsum.R
#
# Written by Carter T. Butts ; portions contributed by
# David Hunter and Mark S. Handcock
# .
#
# Last Modified 11/26/19
# Licensed under the GNU General Public License version 2 (June, 1991)
# or greater
#
# Part of the R/network package
#
# This file contains various routines for printing/summarizing
# network class objects.
#
# Contents:
#
# print.network
# print.summary.network
# summary.character
# summary.network
#
######################################################################
# Printing for network class objects.
#
#' @rdname network
#' @export print.network
#' @export
print.network<-function(x, matrix.type=which.matrix.type(x),
mixingmatrices=FALSE, na.omit=TRUE, print.adj=FALSE, ...)
{
cat(" Network attributes:\n")
for(i in 1:length(x$gal)){
if (names(x$gal)[i]=="n"){
attributeName<-"vertices"
attributeValue<-x$gal[[i]]
} else {
attributeName<-names(x$gal)[i]
attributeValue<-x$gal[[i]]
}
if(is.network(attributeValue)){
if(attributeName=="design"){
cat(" ",attributeName,"=\n")
cat(" total missing =",network.edgecount(attributeValue),"\n")
cat(" percent missing =",network.density(attributeValue),"\n")
}else{
cat(" ",attributeName,":\n",sep="")
if(is.discrete(attributeValue)){
assign(paste(" ",attributeName),attributeValue)
print(table(get(paste(" ",attributeName))))
if(mixingmatrices){
cat("\n","mixing matrix for ",attributeName,":\n",sep="")
print(mixingmatrix(x,attributeName))
}
}else{
print(summary(attributeValue))
}
}
}else{
if(attributeName!="mnext"){
if(is.discrete(attributeValue)){
#assign(paste(" ",attributeName),attributeValue)
#print(table(get(paste(" ",attributeName))))
print(table(attributeValue,dnn=paste(' ',attributeName,':',sep='')))
}else{
# for short attributes, just print out the values
if(inherits(attributeValue,c("factor","character","numeric", "logical","integer","double","NULL","call","formula"))&&(length(attributeValue) < 10)){
# handle NULL case because cat won't print NULL
if (is.null(attributeValue)){
cat(" ",attributeName,"= NULL\n")
} else {
if(is.call(attributeValue)) attributeValue <- deparse(attributeValue)
cat(" ",attributeName,"=",attributeValue,"\n")
}
} else{
# special handling for classes where summary would give messy or non-useful output
# don't print summary for net obs period or active attributes
if (attributeName=='net.obs.period' || grepl('.active$',attributeName) ){
cat(" ",attributeName,": (not shown)\n", sep="")
} else if (inherits(attributeValue,c("matrix"))){
cat(" ",attributeName,": ",nrow(attributeValue),"x",ncol(attributeValue)," matrix\n", sep="")
} else {
# default to printing out the summary for the attribute
cat(" ",attributeName,":\n", sep="")
if(is.call(attributeValue)){
# (unless it's a call like a formula)
print(attributeValue)
}else{
print(summary(attributeValue))
}
}
}
}
}
}
}
cat(" total edges=",network.edgecount(x,na.omit=FALSE),"\n")
cat(" missing edges=",network.naedgecount(x),"\n")
cat(" non-missing edges=",network.edgecount(x,na.omit=TRUE),"\n")
vna<-list.vertex.attributes(x)
if(na.omit){
vna<-vna[vna!="na"]
}
if(length(vna)==0){
cat("\n","No vertex attributes","\n",sep="")
}else{
cat("\n","Vertex attribute names:","\n")
cat(" ",vna,"\n")
}
# Print list of edge attributes, but only if there are not very many edges
# because list.edge.attributes is expensive on large nets
if(length(x$mel)<=1000){
ena<-list.edge.attributes(x)
if(na.omit){
ena<-ena[ena!='na']
}
if(length(ena)==0){
cat("\n","No edge attributes","\n",sep="")
}else{
cat("\n","Edge attribute names:","\n")
cat(" ",ena,"\n")
}
} else {
cat("\n","Edge attribute names not shown","\n")
}
#Print the adjacency structure, if desired
if(print.adj){
if(is.multiplex(x)&&(matrix.type=="adjacency"))
matrix.type<-"edgelist"
if(is.hyper(x))
matrix.type<-"incidence"
cat("\n",matrix.type,"matrix:\n")
if(network.edgecount(x)>0){
mat<-as.matrix.network(x,matrix.type=matrix.type)
attr(mat,"n")<-NULL #Get rid of any extra attributes
attr(mat,"vnames")<-NULL
attr(mat,"bipartite")<-NULL
print(mat)
}else
cat("Empty Graph\n")
}
invisible(x)
}
#Print method for summary.character
print.summary.character <- function(x, max.print=10, ...){
x<-table(x)
nam<-names(x)
x<-as.vector(x)
names(x)<-nam
if(length(x) <= max.print){
print(x)
}else{
ord<-order(as.vector(x),decreasing=TRUE)
cat(paste(" the ",max.print," most common values are:\n",sep=""))
print(x[ord][1:max.print])
}
invisible(x)
}
#Print method for summary.network
#' @export print.summary.network
#' @export
print.summary.network<-function(x, ...){
#Pull any extra goodies from summary.network (stored in gal)
na.omit<-x%n%"summary.na.omit"
mixingmatrices<-x%n%"summary.mixingmatrices"
print.adj<-x%n%"summary.print.adj"
#Print the network-level attributes
class(x)<-"network"
cat("Network attributes:\n")
for(i in 1:length(x$gal)){
if (names(x$gal)[i]=="n"){
attributeName<-"vertices"
attributeValue<-x$gal[[i]]
} else {
attributeName<-names(x$gal)[i]
attributeValue<-x$gal[[i]]
}
if(!(attributeName%in%c("mnext","summary.na.omit", "summary.mixingmatrices","summary.print.adj"))){
if(is.network(attributeValue)){
if(attributeName=="design"){
cat(" ",attributeName,"=\n")
cat(" total missing = ",network.edgecount(attributeValue),"\n", sep="")
cat(" percent missing =",network.density(attributeValue),"\n", sep="")
}else{
cat(" ",attributeName,"=\n")
print(attributeValue)
}
}else{
if(is.discrete(attributeValue)){
assign(paste(" ",attributeName),attributeValue)
print(table(get(paste(" ",attributeName))))
if(mixingmatrices){
cat("\n","mixing matrix for ",attributeName,":\n",sep="")
print(mixingmatrix(x,attributeName))
}
}else{
if(inherits(attributeValue,c("factor","character","numeric", "logical","integer","double","call","formula"))&& (length(attributeValue) < 10)){
if(is.call(attributeValue)) attributeValue <- deparse(attributeValue)
cat(" ",attributeName," = ",attributeValue,"\n",sep="")
}else{
cat(" ",attributeName,":\n", sep="")
if(is.call(attributeValue)){
print(attributeValue)
}else{
print(summary(attributeValue))
}
}
}
}
}
}
cat(" total edges =",network.edgecount(x,na.omit=FALSE),"\n")
cat(" missing edges =",network.naedgecount(x),"\n")
cat(" non-missing edges =",network.edgecount(x,na.omit=TRUE),"\n")
cat(" density =",network.density(x),"\n")
#Print the network-level attributes
van<-list.vertex.attributes(x)
if(na.omit){
van<-van[van!="na"]
}
if(length(van)==0){
cat("\n","No vertex attributes","\n",sep="")
}else{
cat("\nVertex attributes:\n")
for (i in (1:length(van))){
if(van[i]=="vertex.names"){
cat(" vertex.names:\n")
cat(" character valued attribute\n")
cat(" ",sum(!is.na(network.vertex.names(x)))," valid vertex names\n",sep="")
}else{
cat("\n ",van[i],":\n",sep="")
aaval<-get.vertex.attribute(x,van[i],unlist=FALSE)
aaclass<-unique(sapply(aaval,class))
aaclass<-aaclass[aaclass!="NULL"]
if(length(aaclass)>1){
cat(" mixed class attribute\n")
cat(" ",sum(!sapply(aaval,is.null)),"values\n")
}else if(aaclass%in%c("logical","numeric","character","list")){
cat(" ",aaclass," valued attribute\n",sep="")
aalen<-sapply(aaval,length)
if(all(aalen<=1)&&(aaclass!="list")){
cat(" attribute summary:\n")
print(summary(unlist(aaval)))
if(is.discrete(unlist(aaval))&&mixingmatrices){
cat(" mixing matrix:\n")
print(mixingmatrix(x,van[i]))
}
}else{
cat(" uneven attribute lengths; length distribution is\n")
print(table(aalen))
}
}else{
cat(" ",aaclass," valued attribute\n",sep="")
cat(" ",length(aaval)," values\n",sep="")
}
}
}
}
#Print the edge-level attributes
ean <- list.edge.attributes(x)
if(na.omit){
ean<-ean[ean!="na"]
}
if(length(ean)==0){
cat("\n","No edge attributes","\n",sep="")
}else{
cat("\nEdge attributes:\n")
for (i in (1:length(ean))){
cat("\n ",ean[i],":\n",sep="")
eaval<-get.edge.attribute(x$mel,ean[i],unlist=FALSE)
eaclass<-unique(sapply(eaval,class))
eaclass<-eaclass[eaclass!="NULL"]
if(length(eaclass)>1){
cat(" mixed class attribute\n")
cat(" ",sum(!sapply(eaval,is.null)),"values\n")
}else if(eaclass%in%c("logical","numeric","character","list")){
cat(" ",eaclass," valued attribute\n",sep="")
ealen<-sapply(eaval,length)
if(all(ealen<=1)&&(eaclass!="list")){
cat(" attribute summary:\n")
print(summary(unlist(eaval)))
}else{
cat(" uneven attribute lengths; length distribution is\n")
print(table(ealen))
}
}else{
cat(" ",eaclass," valued attribute\n",sep="")
cat(" ",length(eaval),"values\n",sep="")
}
}
}
#Print the adjacency structure
if(print.adj){
matrix.type=which.matrix.type(x)
if(is.multiplex(x)&&(matrix.type=="adjacency"))
matrix.type<-"edgelist"
if(is.hyper(x))
matrix.type<-"incidence"
cat("\nNetwork ",matrix.type," matrix:\n",sep="")
if(network.edgecount(x)>0){
mat<-as.matrix.network(x,matrix.type=matrix.type)
attr(mat,"n")<-NULL #Get rid of any extra attributes
attr(mat,"vnames")<-NULL
attr(mat,"bipartite")<-NULL
print(mat)
}else
cat("Empty Graph\n")
}
invisible(x)
}
#An internal routine to handle summaries of characters
summary.character <- function(object, ...){
class(object)<-c("summary.character",class(object))
object
}
# Summaries of network objects
#
#' @rdname network
#' @export summary.network
#' @export
summary.network<-function(object, na.omit=TRUE, mixingmatrices=FALSE, print.adj=TRUE, ...){
#Add printing parameters as network objects, and change the class
object%n%"summary.na.omit"<-na.omit
object%n%"summary.mixingmatrices"<-mixingmatrices
object%n%"summary.print.adj"<-print.adj
class(object)<-c("summary.network", class(object))
#Return the object
object
}
network/R/fileio.R 0000644 0001762 0000144 00000152146 14724032651 013553 0 ustar ligges users ######################################################################
#
# fileio.R
#
# Written by Carter T. Butts ; portions contributed by
# David Hunter and Mark S. Handcock
# .
#
# Last Modified 11/26/19
# Licensed under the GNU General Public License version 2 (June, 1991)
# or greater
#
# Part of the R/network package
#
# This file contains various routines related to reading/writing network
# objects from external files.
#
# Contents:
#
# read.paj
# read.paj.simplify
# readAndVectorizeLine
# switchArcDirection
#
######################################################################
#Read an input file in Pajek format
# some details at http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/pajekman.pdf p. 73
# generally this steps through the file until it finds markers for specific sub sections
# when it sees one ('*Vertices*') it drops into a sub-loop that keeps advancing the file read
# however, note that the overall loop may run multiple times in order to correctly detect all of the pieces in the file
# things are made more complicated becaue there can be multiple *Edges or *Arcs definitions in a network
# when it is a "mutliple network" (multiplex) http://vlado.fmf.uni-lj.si/pub/networks/doc/ECPR/08/ECPR01.pdf slide 21
# TODO: not sure if multiplex is set appropriately for this case
# Also, attributes can be have 'default' values (the previous record) if not explicitly set on each row
# TODO: need an argument to indicate if multiple sets of relations on the same vertex set should be returned
# as a multiplex network or a list of networks.
#' Read a Pajek Project or Network File and Convert to an R 'Network' Object
#'
#' Return a (list of) \code{\link{network}} object(s) after reading a
#' corresponding .net or .paj file. The code accepts ragged array edgelists,
#' but cannot currently handle 2-mode, multirelational (e.g. KEDS), or networks
#' with entries for both edges and arcs (e.g. GD-a99m). See \code{network},
#' \code{statnet}, or \code{sna} for more information.
#'
#'
#' If the \code{*Vertices} block includes the optional graphic attributes
#' (coordinates, shape, size, etc.) they will be read attached to the network
#' as vertex attributes but values will not be interperted (i.e. Pajek's color
#' names will not be translated to R color names). Vertex attributes included
#' in a \code{*Vector} block will be attached as vertex attributes.
#'
#' Edges or Arc weights in the \code{*Arcs} or \code{*Edges} block are include
#' in the network as an attribute with the same name as the network. If no
#' weight is included, a default weight of 1 is used. Optional graphic
#' attributes or labels will be attached as edge attributes.
#'
#' If the file contains an empty \code{Arcs} block, an undirected network will
#' be returned. Otherwise the network will be directed, with two edges (one in
#' each direction) added for every row in the \code{*Edges} block.
#'
#' If the \code{*Vertices}, \code{*Arcs} or \code{*Edges} blocks having timing
#' information included in the rows (indicated by `...` tokens), it will be
#' attached to the vertices with behavior determined by the \code{time.format}
#' option. If the \code{'networkDynamic'} format is used, times will be
#' translated to \code{networkDynamic}'s spell model with the assumtion that
#' the original Pajek representation was indicating discrete time chunks. For
#' example \code{"[5-10]"} will become the spell \code{[5,11]}, \code{"[2-*]"}
#' will become \code{[2,Inf]} and \code{"[7]"} will become \code{[7,8]}. See
#' documentation for \code{networkDynamic}'s \code{?activity.attribute} for
#' details.
#'
#' The \code{*Arcslist}, \code{*Edgelist} and \code{*Events} blocks are not yet
#' supported.
#'
#' As there is no known single complete specification for the file format,
#' parsing behavior has been infered from references and examples below.
#'
#' @aliases read.paj.simplify switchArcDirection readAndVectorizeLine
#' @param file the name of the file whence the data are to be read. If it does
#' not contain an absolute path, the file name is relative to the current
#' working directory (as returned by \code{\link{getwd}}). \code{file} can
#' also be a complete URL.
#' @param verbose logical: Should longer descriptions of the reading and
#' coercion process be printed out?
#' @param debug logical: Should very detailed descriptions of the reading and
#' coercion process be printed out? This is typically used to debug the reading
#' of files that are corrupted on coercion.
#' @param edge.name optional name for the edge variable read from the file. The
#' default is to use the value in the project file if found.
#' @param simplify Should the returned network be simplified as much as
#' possible and saved? The values specifies the name of the file which the data
#' are to be stored. If it does not contain an absolute path, the file name is
#' relative to the current working directory (see \code{\link{getwd}}). If
#' \code{specify} is TRUE the file name is the name \code{file}.
#' @param time.format if the network has timing information attached to
#' edges/vertices, how should it be processed? \code{'pajekTiming'} will
#' attach the timing information unchanged in an attribute named
#' \code{pajek.timing}. \code{'networkDynamic'} will translate it to a spell
#' matrix format, attach it as an \code{'activity'} attribute and add the class
#' \code{'networkDynamic'} -- formating it for use by the \code{networkDynamic}
#' package.
#' @return The structure of the object returned by \code{read.paj} depends on
#' the contents of the file it parses. \itemize{ \item if input file contains
#' information about a single 'network' object (i.e .net input file) a single
#' network object is returned with attribute data set appropriately if
#' possible. or a list of networks (for .paj input). \item if input file
#' contains multiple sets of relations for a single network, a list of network
#' objects ('network.series') is returned, along with a formula object?. \item
#' if input .paj file contains additional information (like partition
#' information), or multiple \code{*Network} definitions a two element list is
#' returned. The first element is a list of all the network objects created,
#' and the second is a list of partitions, etc. (how are these matched up) }
#' @author Dave Schruth \email{dschruth@@u.washington.edu}, Mark S. Handcock
#' \email{handcock@@stat.washington.edu} (with additional input from Alex
#' Montgomery \email{ahm@@reed.edu}), Skye Bender-deMoll
#' \email{skyebend@@uw.edu}
#' @seealso \code{\link{network}}
#' @references Batagelj, Vladimir and Mrvar, Andrej (2011) Pajek Reference
#' Manual version 2.05
#' \url{http://web.archive.org/web/20240906013709/http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/pajekman.pdf} Section
#' 5.3 pp 73-79
#'
#' Batageli, Vladimir (2008) "Network Analysis Description of Networks"
#' \url{http://web.archive.org/web/20240511173536/http://vlado.fmf.uni-lj.si/pub/networks/doc/ECPR/08/ECPR01.pdf}
#'
#' Pajek Datasets \url{http://web.archive.org/web/20240411203537/http://vlado.fmf.uni-lj.si/pub/networks/data/esna}
#' @keywords datasets
#' @examples
#'
#' \dontrun{
#' require(network)
#'
#' par(mfrow=c(2,2))
#'
#' test.net.1 <- read.paj("http://vlado.fmf.uni-lj.si/pub/networks/data/GD/gd98/A98.net")
#' plot(test.net.1,main=test.net.1%n%'title')
#'
#' test.net.2 <- read.paj("http://vlado.fmf.uni-lj.si/pub/networks/data/mix/USAir97.net")
#' # plot using coordinates from the file in the file
#' plot(test.net.2,main=test.net.2%n%'title',
#' coord=cbind(test.net.2%v%'x',
#' test.net.2%v%'y'),
#' jitter=FALSE)
#'
#' # read .paj project file
#' # notice output has $networks and $partitions
#' read.paj('http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Tina.paj')
#' }
#'
#' @export read.paj
read.paj <- function(file,verbose=FALSE,debug=FALSE,
edge.name=NULL, simplify=FALSE,time.format=c('pajekTiming','networkDynamic'))
{
time.format<-match.arg(time.format)
# process filename
if(inherits(file, "connection")){
fileNameParts0 <- strsplit(summary(file)$'description',"/")[[1]]
} else {
fileNameParts0<-strsplit(file,"/")[[1]]
}
# split again to try to get file extension
fileNameParts1 <- strsplit(fileNameParts0[length(fileNameParts0)],"\\.")[[1]]
# filename may not have extension
if(length(fileNameParts1)>1){
fileName <- paste(fileNameParts1[1:length(fileNameParts1)-1],collapse=".")
fileExt <- fileNameParts1[length(fileNameParts1)] #should be "net" or "paj" (but never used ?)
} else {
fileName<-fileNameParts1
fileExt<-""
}
# open connection (if it is not one already)
if (is.character(file)) {
file <- file(file, "rt")
on.exit(close(file))
}
if (!inherits(file, "connection"))
stop("argument 'file' must be a character string or connection")
if (!isOpen(file)) {
open(file, "rt")
on.exit(close(file))
}
isSeekable <- regexpr("http",file)>0
# also disable seeking if a gz connection, as it will break
if(summary(file)$'class'=='unz'){
isSeekable<-FALSE
}
# initialize state tracking variables
lineNumber<-0 # input line number parsed for debugging
nnetworks <- 0 # number of networks (edge types) in current *Network block
network.names <- NULL # names of networks (edge types) in current *Network block
vertex <- NULL # has the vertex block been found?
nvertex <- 0 # number of vertices in currently processing network
network.title <- fileName # default name for network is filename
partition <- NULL # partitions, if found
names.partition <- NULL # names of partitions, if found
vector <- NULL # vectors, if found
colnames.vector <- NULL # names of vectors if found
projects <- list() # projects if found (each set of related networks is a 'project')
nprojects <- 0 # number of projects found
names.projects <- NULL # names of projects if found.
nextline <- TRUE # control flag to indicate if should proceede to next line
line <- " " # usually tokens corresponding to line being red
previousArcs<-NULL
previousEdges<-NULL
edgeData<-NULL
is2mode <- FALSE # flag indicating if currently processing biparite network
nevents <- 0 # for two-mode data, size of first mode
nactors <- 0 # for two-mode data, size of second mode
multiplex<-FALSE # flag indicating if currently processing multiplex network
loops<-FALSE
# begin file parsing
while(!inherits(line,"try-error")){
while(any(grep("^%", line)) | nextline){
if(debug) print(paste("new parsing loop started at line",lineNumber))
options(show.error.messages=FALSE)
# read the next line with error messages disabled
line <- try(readLines(file, 1, ok = FALSE))
options(show.error.messages=TRUE)
# If the line was not an error, tokenize using space as seperator
if(!inherits(line,"try-error") & length(line)>0){
line <- strsplit(line, " ")[[1]]
line <- line[line!=""]
lineNumber<-lineNumber+1
}
nextline <- FALSE # there was an error (probably end of file) so don't parse anymore
}
nextline <- TRUE
# if(verbose) warning(paste("afterbeingWhileLoop",line))
#
# ---- Network parsing -------
# Search for lines begining with *Network within the .paj file
# not all files will include a *Network heading (usually only .paj)
# it indicates that all the following sections (vertices, partitions, etc) belong to that network
if(any(grep("\\*Network", line, ignore.case = TRUE))){
if (verbose) print(paste('parsing *Network block at line',lineNumber))
if(debug){
print(paste(" nnetworks=",nnetworks))
print(paste(" network.names=",network.names))
print(paste(" vertex null?",is.null(vertex)))
print(paste(" network.title=",network.title))
print(paste(" vector null?",is.null(vector)))
print(paste(" colnames.vector=",colnames.vector))
print(paste(" names.projects=",names(projects)))
}
if(verbose) print(paste("number of networks",nnetworks)) #dschruth added
# we are about to start a new network, so need to run the post-processing
# code on the previously parsed network (if there is one)
if(nnetworks > 0 ){
if(debug) print("assembleing networks into 'project'")
# grab all the named networks from the environment
# and put 'em in a list
networksData<-lapply(network.names,function(netName){get(netName)})
# TODO: delete networks from environment to clear up space?
# take the various objects that have been parsed from the .paj file and assemble
# them into a network object (or list of network objects, a 'project'), doing some appropriate conversion
projects <- postProcessProject( network.title,
vector,
colnames.vector,
vertex, # data for building vertices,
edgeData,
nnetworks, # number of networks found,
network.names, # names of networks found
networksData,
projects,
time.format,
verbose
)
} else { # networks have not been created, but need to check if only vertices have been found and empty network needed
if(!is.null(vertex)){
# need to initialize a network here to deal with the case where no arcs/edge in the file
# Note that without the arcs/edge, we have no way to know if network was supposed to be directed or multiplex
networksData<-list( network.initialize(n=nvertex, bipartite=nactors))
projects <- postProcessProject( network.title,
vector,
colnames.vector,
vertex, # data for building vertices,
edgeData,
nnetworks, # number of networks found,
network.names=network.title, # names of networks found
networksData,
projects,
time.format,
verbose)
}
}
# since we are starting a new network, reset all of the network level info, directed, 2mode, etc
network.title <-NULL
network.names <- NULL
vertex<-NULL
nvertex<-0
nnetworks <- 0
vector <- NULL
colnames.vector <- NULL
nextline <- TRUE
arcsLinePresent<-FALSE
edgesLinePresent<-FALSE
previousArcs<-NULL
previousEdges<-NULL
is2mode <- FALSE #for two-mode data
nevents <- 0 #for two-mode data
nactors <- 0 #for two-mode data
multiplex<-FALSE
loops<-FALSE
# now parse the new network title
network.title <- paste(line[-1],collapse=" ")
if(is.null(network.title)){
network.title <- network.name # this seems wrong, should be file name?
warning('no name found for network, using "',network.name,'"')
}
} # END NETWORK PARSING BLOCK
#
# vertices specification
# search for lines beignning with *Vertices
# and then read in the number of lines equal to the expected number of vertices
if(any(grep("\\*Vertices", line, ignore.case = TRUE))){
if (verbose) print(paste('parsing *Vertices block at line',lineNumber))
previousArcs <- NULL #used for arc+edge specified networks.... reset to null for every new network.. might be sufficient here
previousEdges<-NULL
nvertex <- as.numeric(line[2]) # parse the number of vertices
#nnetworks <- nnetworks + 1 # if we found vertices, we must have a network
# give the network a default name (may be overwritten later)
network.name <- paste(network.title,sep="")
if(!is.na(line[3])){ #dschruth added for two-mode
is2mode <- TRUE #used in matrix below #dschruth added for two-mode
nactors <- as.numeric(line[3]) #used for error check #dschruth added for two-mode
nevents <- nvertex-nactors #used for error check #dschruth added for two-mode
} #dschruth added for two-mode
if(isSeekable){
# cache the table position in the input file in case we need to jump pack here later
preReadTablePosition <- seek(file,where=NA)
}
# if(network.title =="SanJuanSur_deathmessage.net") #read.third paragraph in details of documentation of read table about how it determines the number of columns in the first 5 lines...
# vertex <- read.table(file,skip=-1,nrows=nvertex,col.names=1:8,comment.char="%",fill=TRUE,as.is=FALSE) #dschruth added 'comment.char="%"' and 'fill=TRUE'
# else
# read it as table
# NOTE: rows may omit values ()
vertex <- read.table(file,skip=-1,nrows=nvertex, comment.char="%",fill=TRUE,as.is=FALSE,row.names=NULL)
if(ncol(vertex)==1){ vertex <- cbind(1:nrow(vertex),vertex)}
#need to check to see if we are reading in more vertex rows than there actually are (some edges are implied)
edgelistPosition <- grep("\\*(arcs|edges|matrix)",as.matrix(vertex),ignore.case=TRUE, useBytes = TRUE)
if(any(edgelistPosition)){
if(verbose){
print("vertex list has missing entries or n was mis-specified, re-reading it...")
} else {
warning('vertex list has missing entries or n was mis-specified, re-reading it...')
}
if(!isSeekable) stop("Resize of abbreviated vertex list via seek is not possible with URLs. Try downloading file and loading locally")
nVertexRows <- edgelistPosition-1
dummyNotUsed <- seek(file,where=preReadTablePosition) #reset the file position back to before the table was read
vertex <- read.table(file,skip=-1,nrows=nVertexRows,comment.char="%",fill=TRUE,as.is=FALSE,) #dschruth added 'comment.char="%"' and 'fill=TRUE'
if(ncol(vertex)==1){ vertex <- cbind(1:nrow(vertex),vertex)}
}
if(nvertex!=nrow(vertex)){
if(verbose){
print(paste("vertex list (length=",nrow(vertex),") is being re-sized to conform with specified network size (n=",nvertex,")",sep=""))
}
colnames(vertex)[1:2] <- c("vn","name")
vertex <- merge(data.frame(vn=1:nvertex),vertex,all.x=TRUE,all.y=FALSE,by.y="vn") #fill in the holes with NA names
}
# increment the debugging line counter
lineNumber<-lineNumber+nvertex
if(verbose) print(paste(" found",nvertex,'vertices'))
} # end vertices parsing block
#
# partition specification (vertex level attribute)
#
if(any(grep("\\*Partition", line, ignore.case = TRUE))){
if (verbose) print(paste('parsing *Partition block at line',lineNumber))
partition.name <- as.character(paste(line[-1],collapse="."))
names.partition <- c(names.partition,partition.name)
line <- readAndVectorizeLine(file)
lineNumber<-lineNumber+1 # update debugging line number
# skip comments
while(any(grep("^%", line))){
line <- readAndVectorizeLine(file)
lineNumber<-lineNumber+1 # update debugging line number
}
nvertex <- as.numeric(line[2])
if(is.null(partition)){
partition <- read.table(file,skip=0,nrows=nvertex)
lineNumber<-lineNumber+nvertex # update debugging line number
}else{
partition <- c(partition,
read.table(file,skip=0,nrows=nvertex))
lineNumber<-lineNumber+nvertex # update debugging line number
}
if(verbose) print("partition found and set")
# TODO: why is partition not attached as vertex attribute?
}
#
# ----- Vector specification (vetex-level attribute) -----
#
if(any(grep("\\*Vector", line, ignore.case = TRUE))){
if (verbose) print(paste('parsing *Vector block at line',lineNumber))
vector.name <- as.character(paste(line[-1],collapse="."))
colnames.vector <- c(colnames.vector,vector.name)
line <- readAndVectorizeLine(file)
lineNumber<-lineNumber+1 # update debugging line number
# skip comments
while(any(grep("^%", line))){
line <- readAndVectorizeLine(file)
lineNumber<-lineNumber+1 # update debugging line number
}
nvertex <- as.numeric(line[2])
if(is.null(vector)){
vector <- read.table(file,skip=0,nrows=nvertex)
lineNumber<-lineNumber+nvertex # update debugging line number
}else{
vector <- data.frame(vector,
read.table(file,skip=0,nrows=nvertex))
lineNumber<-lineNumber+nvertex # update debugging line number
}
if(verbose) print("vector found and set")
}
#
# ----- arcs / edges specification --------
#
arcsLinePresent<-any(grep("\\*Arcs$", line, ignore.case = TRUE))
edgesLinePresent<-any(grep("\\*Edges$", line, ignore.case = TRUE))
if(arcsLinePresent | edgesLinePresent){
if(arcsLinePresent){
if(verbose) print(paste("parsing *Arcs block at line",lineNumber))
# if we had already parsed an arcs block, and we just found another one, better clear the old
if(!is.null(previousArcs)){
previousArcs<-NULL
}
} else {
if(verbose) print(paste("parsing *Edges block at line",lineNumber))
# if we had already parsed an edges block, and we just found another one, better clear the old
if(!is.null(previousEdges)){
previousEdges<-NULL
}
}
if(missing(edge.name)){
if(length(line)>1){ # this *Arcs / *Edges block is definding a named 'network' of relationships
network.name <- strsplit(paste(line[3:length(line)],collapse="."),'\"')[[1]][2] #dschruth added collapse to allow for multi work network names
#Note: don't increment the number of networks found until later, because this is executed for both arcs and edges block
}else{
# append an index to the network name (to be used as edge attribute) only if we've seen multiple networks
network.name <- paste(network.title,ifelse(nnetworks>0,nnetworks,''),sep="")
#network.name <- network.title #old way
}
}else{
# define the network name as the edge name passed in by user
# TODO: seems like if user passes in edge.name, multirelational edges will not be parsed correctly
# because they will be given the same name
network.name <- edge.name
}
dyadList <- list() #dschruth changed (was NULL)
listIndex <- 1 #dschruth added
line <- readAndVectorizeLine(file)
lineNumber<-lineNumber+1 # update debugging line number
# skip comments / blank lines
while(any(grep("^%", line))){
line <- readAndVectorizeLine(file)
lineNumber<-lineNumber+1 # update debugging line number
}
# keep reading lines until reaching the end of the block
while(!any(grep("\\*[a-zA-Z]", line)) & length(line)>0){ #dschruth changed \\* to \\*[a-zA-Z] to allow for time asterisks
# check line length for parse problems
# should be fromId,toId, weight
# if there are not 3, matrix reform will go bad later on
if(length(line)<2){
stop("Arc/Edge record on line ",lineNumber," does not appear to have the required 2 elements:'",paste(line,collapse=' '),"'")
}
dyadList[[listIndex]] <- gsub("Newline","",line) # replace any newlines
line <- readAndVectorizeLine(file)
lineNumber<-lineNumber+1 # update debugging line number
listIndex <- listIndex+1
}
if(verbose) print(paste(" length of dyad list",length(dyadList)))
nextline <- FALSE
# check if we found any dyads
if(length(dyadList)>0){
### deal with the possible Ragged Array [RA] dyad list .. see Lederberg.net ###
#TODO: I think this was for dealing with *arcslist / *edgelist, move to seperate section or do detection directly
RAlengths <- unlist(lapply(dyadList,length))
maxRAwidth <- max(RAlengths)
# TODO: this is an ugly error-prone way to check if there are attributes, need to fix
# dyadsHaveAttributes <- any(is.na(as.numeric(unlist(dyadList)))) # handling edge attributes (NAs introduced by coersion)
# if(dyadsHaveAttributes){
# warning(paste("don't worry about these",length(dyadList),"warnings,the dyads have attributes and were NA'ed during as.numeric() call. \n the actual dyad matrix width is only 2 "))
# }
#
# if(maxRAwidth > 4 & !dyadsHaveAttributes){# #needs to be 4 because of normal edgelist can have sender reciever weight and time
# if(verbose)print(" stacking ragged dyad array ")
# dyads0 <- unlist(lapply(dyadList, function(x) c(x, rep(NA, maxRAwidth - length(x)))))
# dyads1 <- data.frame(matrix(dyads0,nrow=length(dyadList),ncol=maxRAwidth,byrow=TRUE))
#
# colnames(dyads1) <- c("sender","receiver",paste("r",seq(3,maxRAwidth),sep=""))
#
# dyads2 <- reshape(dyads1,idvar="senderNo",ids=row.names(dyads1),direction="long",
# times=names(dyads1)[-1],timevar="receiverNo",
# varying=list(names(dyads1)[-1]))
#
# dyads <- as.matrix(dyads2[!is.na(dyads2$receiver),c("sender","receiver")])
#
# if(verbose)print("finished stacking ragged dyad array")
# }else{ # not a ragged array
### done dealing with RA possiblity ### all written by dschruth
if(debug) print(" unlisting dyad list to matrix")
# check if weight was ommited
if (all(RAlengths==2)){
# assume default weight of 1
# convert to data.frame by first unlisting and dumping into 3 col matrix
edgeData <- as.data.frame(stringsAsFactors=TRUE,matrix(unlist(lapply(dyadList,function(x){
c(as.numeric(x[1:2]),1)})),
nrow=length(dyadList),ncol=3,byrow=TRUE))
if(verbose) print('weights ommited from arcs/edges lines, assuming weight of 1')
} else {
# create a data frame from the (possibly ragged) rows of the dyadList
edgeData<-as.data.frame(stringsAsFactors=TRUE,fillMatrixFromListRows(dyadList))
# convert to appropriate class, have to convert to character first because it is a factor and NA will be recoded wrong
edgeData[,1]<-as.numeric(as.character(edgeData[,1]))
edgeData[,2]<-as.numeric(as.character(edgeData[,2]))
edgeData[,3]<-as.numeric(as.character(edgeData[,3]))
}
# }
# version with just first two columns to make checking easier
dyads<-cbind(edgeData[,1:2])
# check for non-numeric ids (bad coercion)
if(any(is.na(dyads))){
badRows<-lineNumber-(which(is.na(dyads),arr.ind=TRUE)[,1])
stop('vertex id columns in arcs/edges definition contains non-numeric or NA values on line(s) ',paste(badRows,collapse=' '))
}
# check for non-integer vertex ids
if(any(round(dyads)!=dyads)){
badRows<-lineNumber-(which(round(dyads)!=dyads,arr.ind=TRUE)[,1])
stop('vertex id columns in arcs/edges definition contains non-integer values on line(s) ',paste(badRows,collapse=' '))
}
# check for out of range vertex ids
if((max(dyads) > nvertex)){ # nrow(dyads)==1 is for C95.net
# figure out which rows are bad
badRows<-1+lineNumber-(which(dyads > nvertex,arr.ind=TRUE)[,1])
stop("vertex id(s) in arcs/edge definition is out of range on line(s) ",paste(badRows,collapse=' '))
#if(verbose) print("first dyad list (arcs?), is too short to be a full network, skipping to next dyad list (edges?)")
}
if(is.null(previousArcs) & is.null(previousEdges)){ #first time through (always an arc list?)
# definitly creating a network, so increment the counter and names
nnetworks <- nnetworks + 1
network.names <- c(network.names, network.name)
if(arcsLinePresent){
directed <- TRUE
previousArcs <- edgeData
} else {
previousEdges <- edgeData
# there must not be an arcs block, so assume undirected
directed <-FALSE
}
}else{ #second time through (always an edge list?)
if(verbose) print(paste("previous dyads exist!! symmetrizing edges and combining with arcs"))
if(edgesLinePresent){
# should only be edges
edgeData.flipped <- switchArcDirection(edgeData)
edgeData <- rbind(previousArcs,edgeData,edgeData.flipped) # TODO: what if arcs and edges don't have same number of cols
}else{
stop('reached sequence of multiple *Arcs blocks, parsing code must have bad logic')
}
previousArcs <- NULL # we've used 'em, so null it out
}
# check for multiple ties
repeatLines<-anyDuplicated(dyads)
if(repeatLines>0){
multiplex<-TRUE
if(verbose) print('network contains duplicated dyads so will be marked as multiplex')
}
# check for self-loops
loopLines<-which(dyads[,1]==dyads[,2])
if (length(loopLines)>0){
loops<-TRUE
if(verbose) print('network contains self-loop edges so will be marked as such')
}
## initialize the appropriate type of network
# NOTE: network creation occurs TWICE for networks with both arcs and edges, but the first network
# is overwritten by the second. Needlessly slow on large nets, but difficult to avoid, since
# we don't know if there is a 2nd block on the first pass
if(is2mode){
temp <- network.initialize(n=nvertex, directed=directed,
bipartite=nactors,multiple=multiplex,loops=loops)
}else{
temp <- network.initialize(n=nvertex, directed=directed,multiple=multiplex,loops=loops)
}
# add in the edges
add.edges(temp,tail=edgeData[,1],head=edgeData[,2])
# temp <- network(x=dyads[,1:2],directed=directed)#arcsLinePresent)#dschruth added
if(ncol(edgeData)>2){ #only try to set the edge value if there is a third column (there always is?)
temp <- set.edge.attribute(temp,network.names[nnetworks], edgeData[,3])
if(verbose) print(paste(" edge weight attribute named",network.names[nnetworks],"created from edge/arc list"))
}
assign(network.names[nnetworks], temp)
rm(temp)
if(verbose) print("network created from edge/arc list")
# if(arcsLinePresent) nextline <- TRUE #{ print(" 'arcs' line followed by dyads present... skip past the current 'edges' line");}
# end of edge/arc adding
}
}
#
# ----- matrix parsing -------
#
if(any(grep("\\*Matrix", line, ignore.case = TRUE))){
if(verbose) print(paste('parsing *Matrix block at line',lineNumber))
if(length(line)>1){
# if a network name is given, use that
network.name <- strsplit(line[3],'\"')[[1]][2]
}else{
# otherwise name it acoding to the file name, adding a digit if we've seen multiple nets
#network.name <- paste("network",nnetworks+1,sep="")
network.name <- paste(network.title,ifelse(nnetworks>0,nnetworks,''),sep="")
}
nnetworks <- nnetworks + 1
network.names <- c(network.names, network.name)
temp0 <- as.matrix(read.table(file,skip=0,nrows=nvertex,as.is=TRUE))
lineNumber<-lineNumber+nvertex
lastColNum <- ncol(temp0)
if(all(apply(temp0[,-lastColNum],1,sum)==temp0[,lastColNum])){
if(verbose) print("removing final marginal sum column of matrix")
temp0 <- temp0[,-lastColNum]
}
if(verbose) print(paste(" matrix dimensions: dim1",dim(temp0)[1],"na",nactors,"dim2",dim(temp0)[2],"ne",nevents)) #checking
if(is2mode & (dim(temp0)[1]!=nactors | dim(temp0)[2]!=nevents)){
stop("dimensions do not match bipartite specifications")
}else{
# check for self-loops
loops<-
# convert the adjacency matrix to a network, using values as an edge attribute
temp <- as.network.matrix(x=temp0,
matrix.type='adjacency',
bipartite=is2mode, #dschruth added "bipartate=is2mode" for two-mode
ignore.eval=FALSE,
names.eval=network.name,
loops=any(diag(temp0)>0) # check for self-looops
)
if(verbose) print("network created from matrix")
}
assign(network.names[nnetworks], temp)
rm(temp)
}
# detect and report some formats that we cannot yet parse
if(any(grep("\\*Arcslist", line, ignore.case = TRUE))){
warning(paste('skipped *Arcslist block at line',lineNumber, ' read.paj does not yet know how to parse it '))
#TODO: see http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/TinaList.net
}
if(any(grep("\\*Edgeslist", line, ignore.case = TRUE))){
warning(paste('skipped *Edgeslist block at line',lineNumber, ' read.paj does not yet know how to parse it '))
# TODO: see http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/TinaList.net
}
if(any(grep("\\*Events", line, ignore.case = TRUE))){
stop(paste('found *Events block at line',lineNumber, ' read.paj does not yet know how to parse Event timing format '))
# TODO: see http://vlado.fmf.uni-lj.si/vlado/podstat/AO/net/Friends.tim
}
} # end file-parsing while loop
if(verbose){
print(paste('End of file reached at line',lineNumber))
}
#if(is.null(network.title)) network.title <- network.name
if(debug){
print(paste("nnetworks=",nnetworks))
print(paste("network.names=",network.names))
print(paste("vertex null?",is.null(vertex)))
print(paste("network.title=",network.title))
print(paste("vector null?",is.null(vector)))
print(paste("colnames.vector=",colnames.vector))
print(paste("nprojects=",length(projects)))
print(paste("names.projects=",names(projects)))
}
if(verbose) print(paste("number of networks found:",nnetworks)) #dschruth added
# ------------ post-processing --------------------
if(nnetworks > 0){
if(debug) print("assembling networks into 'project' before returning")
# grab all the named networks from the environment
# and put 'em in a list
networksData<-lapply(network.names,function(netName){get(netName)})
# TODO: delete networks from environment to clear up space?
# this code takes the various objects that have been parsed from the .paj file and assembles
# them into a network object (or list of network objects, a 'project'), doing some appropriate conversion
projects <- postProcessProject( network.title,
vector,
colnames.vector,
vertex, # data for building vertices,
edgeData,
nnetworks, # number of networks found,
network.names, # names of networks found
networksData,
projects,
time.format,
verbose
)
} else { # networks have not been created, but need to check if only vertices have been found
if(!is.null(vertex)){
# need to initialize a network here to deal with the case where no arcs/edge in the file
# Note that without the arcs/edge, we have no way to know if network was supposed to be directed or multiplex
networksData<-list( network.initialize(n=nvertex, bipartite=nactors))
projects <- postProcessProject( network.title,
vector,
colnames.vector,
vertex, # data for building vertices,
edgeData=NULL,
nnetworks, # number of networks found,
network.names = network.title, # names of networks found
networksData,
projects,
time.format,
verbose)
}
}
if(is.null(partition)){
if(verbose) print(paste("number of projects",length(projects))) #dschruth added
# if there is only one 'project' (network) remove it from the list and return it that way.
if(length(projects)==1){
projects <- projects[[1]]
}
if(nnetworks>1){
if (verbose){
print('appending network objects into a network.series')
}
class(projects) <- "network.series"
}
}else{
names(partition) <- names.partition
if (verbose){
print('returning projects and partitions as seperate list elements')
}
projects <- list(networks=projects, partitions=partition)
} #end ifelse
#
# Simplify
#
if(is.logical(simplify)){
if(simplify){
simplify <- fileName
}else{
return(projects)
}
}
read.paj.simplify(x=projects,file=simplify,verbose=verbose)
} #end read.paj
# this code takes the various objects that have been parsed from the .paj file and assembles
# them into a network object (or list of network objects, a 'project'), doing some appropriate conversion
# this is called whenever the main parsing loop believes that it has finished with a section of
# the .paj file describing a group of networks.
# this code is extracted here because it can be called from two different places and must remain identical
postProcessProject<-function(
network.title,
vector,
colnames.vector,
vertex, # data for building vertices,
edgeData, # data for building edges
nnetworks, # number of networks found,
network.names, # names of networks found
networksData, # list of basic networks created
projects,
time.format,
verbose
){
colnames(vector) <- colnames.vector
colnames(vertex) <- c("vertex.numbers","vertex.names","cen1","cen2")[1:ncol(vertex)]
networks <- vector("list",length=nnetworks)
if(verbose) print(paste("processing networks:",paste(network.names,collapse=', ')))
for(i in seq(along.with=network.names)){
temp <- networksData[[i]]
isDynamic<-FALSE
if(!is.null(vertex)){
if (nrow(as.data.frame(stringsAsFactors=TRUE,vertex)) == network.size(temp)) {
# set the vertex names to match names in file
temp <- set.vertex.attribute(temp, "vertex.names",
as.character(vertex[as.numeric(vertex[,1]),2]))
if (ncol(vertex)>2) { # number of columns > 2 -> vertex has attributes
#vert.attr.nam <- c("na","vertex.names","x","y") #assume first three are coords (true?)
vert.attr.nam <- c("na","vertex.names",seq_len(ncol(vertex))) #temp names for rest
# verify that coordinates are numeric
if(ncol(vertex)>=3 && all(is.numeric(vertex[,3]))){
vert.attr.nam[3] <- 'x'
}
if(ncol(vertex)>=4 && all(is.numeric(vertex[,4]))){
vert.attr.nam[4] <- 'y'
}
# check if z coordinate exists and add it if it does
if(ncol(vertex)>=5 && all(is.numeric(vertex[,5]))){
vert.attr.nam[5] <- 'z'
}
# loop over each column of vertex attributes
for (vert.attr.i in 3:ncol(vertex)){
v <- vertex[,vert.attr.i]
if (is.factor(v)){ # if it's a factor (non-numeric), then
vert.attr.nam.tmp <- levels(v)[1] # see if the first factor is an attribute name
if (vert.attr.nam.tmp=="") vert.attr.nam.tmp <- levels(v)[2] # in case of missing data
if (nlevels(v)<=2&!is.na(match(vert.attr.nam.tmp, # check for match if # factors <=2
c("s_size","x_fact","y_fact","phi","r","q",
"ic","bc","bw","lc","la","lr",
"lphi","fos","font")))) { #from pajekman.pdf v1.2.3 p.69-70
vert.attr.nam[vert.attr.i+1] <- vert.attr.nam.tmp #if match, name the next column
} else { #if not, set the attribute, converting to character (networks incompat w/factors)
# if this is the 6th column, assume it is a shape name
# but it could be the 5th column if z is missing (ugg, I hate this format!)
if('z'%in%vert.attr.nam){
if(vert.attr.i==6 ){
vert.attr.nam[6]<-'shape'
}
} else {
if(vert.attr.i==5 ){
vert.attr.nam[5]<-'shape'
}
}
# spec says missing values should be filled in by row above
values<-as.character(vertex[as.numeric(vertex[,1]),vert.attr.i])
missingVals<-which(values=='')
while(length(missingVals)>0){
values[min(missingVals)]<-values[min(missingVals)-1]
missingVals<-which(values=='')
}
# special processing:
# check if it has brackets for time info, if so added
if (length(grep('^\\[.+\\]$',values))>0) {
isDynamic<-TRUE
# if using pajeck time structure, just assign it
if(time.format=='pajekTiming'){
vert.attr.nam[vert.attr.i]<-'pajekTiming'
} else if (time.format =='networkDynamic'){
# if using nd, convert to spell matrix and assign as 'active' attribute
vert.attr.nam[vert.attr.i]<-'active'
values<-lapply(values,as.spells.pajek)
}
}
temp <- set.vertex.attribute(temp,vert.attr.nam[vert.attr.i], values)
}
} else { #not a factor, set the attribute and don't convert to character
temp <- set.vertex.attribute(temp,vert.attr.nam[vert.attr.i],
vertex[as.numeric(vertex[,1]),vert.attr.i])
}
if (verbose) print(paste(' set vertex attribute',vert.attr.nam[vert.attr.i]))
}
}
} else {
stop('number of rows in vertex data does not match number of vertices')
}
} # end vertex data processing
# process edge data
if(!is.null(edgeData)){
if (ncol(edgeData)>3) { # number of columns > 3 means dyads have attributes
edge.attr.nam <- c("from","to","weight",4:ncol(edgeData)) #temp names for rest
# loop over each column of edge attributes
for (edge.attr.i in 4:ncol(edgeData)){
e <- edgeData[,edge.attr.i]
if (is.factor(e)){ # if it's a factor (non-numeric), then
edge.attr.nam.tmp <- levels(e)[1] # see if the first factor is an attribute name
if (edge.attr.nam.tmp=="") edge.attr.nam.tmp <- levels(e)[2] # in case of missing data
if (nlevels(e)<=2&!is.na(match(edge.attr.nam.tmp, # check for match if # factors <=2
c("w","c","p","s","a","ap","l","lp","lr","lphi","lc","la","fos","font",'h1','h2','a1','k1','k2','a2')))) {
edge.attr.nam[edge.attr.i+1] <- edge.attr.nam.tmp #if match, name the next column
} else { #if not, set the attribute, converting to character (networks incompat w/factors)
# spec says missing values should be filled in by row above
values<-as.character(edgeData[,edge.attr.i])
missingVals<-which(values=='')
while(length(missingVals)>0){
values[min(missingVals)]<-values[min(missingVals)-1]
missingVals<-which(values=='')
}
# special processing:
# if name is 'l' (line label) it needs to have possible enclosing quotes removed
# check if it has brackets for time info, if so added
if (length(grep('^\\[.+\\]$',values))>0) {
isDynamic<-TRUE
# if using pajeck time structure, just assign it
if(time.format=='pajekTiming'){
edge.attr.nam[edge.attr.i]<-'pajekTiming'
} else if (time.format =='networkDynamic'){
# if using nd, convert to spell matrix and assign as 'active' attribute
edge.attr.nam[edge.attr.i]<-'active'
values<-lapply(values,as.spells.pajek)
}
}
if(edge.attr.nam[edge.attr.i] == 'l'){
values<-gsub('"','',values)
}
temp <- set.edge.attribute(temp,edge.attr.nam[edge.attr.i], values)
}
} else { #not a factor, set the attribute and don't convert to character
temp <- set.edge.attribute(temp,edge.attr.nam[vert.attr.i],
edgeData[,edge.attr.i])
}
if (verbose) print(paste(' set edge attribute',edge.attr.nam[edge.attr.i]))
}
}
} # end arc/edge data processing
if(!is.null(network.title)){
temp <- set.network.attribute(temp, "title", network.title) # not sure if this should also be the edges relation?
}else{
warning("null network title")
}
if(nrow(as.data.frame(stringsAsFactors=TRUE,vertex))== network.size(temp)){ #should i be doing this? why don't these numbers match all time
temp <- set.vertex.attribute(temp,"vertex.names",as.character(vertex[as.numeric(vertex[,1]),2]))
}
# if it is a dynamic network and we are doing nD format, secretly give it the networkDynamic class
if(isDynamic){
if(time.format=='networkDynamic'){
if(verbose) print(" network has dynamics and is assigned 'networkDynamic' class")
# using this instead of the safer as.networkDynamic() to avoid adding Suggests dependency on networkDynamic
class(temp)<-c('networkDynamic',class(temp))
} else {
if(verbose) print(' network has dynamic info which was saved without interpretation. see argument "time.format" for details')
}
}
networks[[i]] <- temp
if (verbose) print(paste("processed and added",network.names[i],"to list of networks"))
}
names(networks) <- network.names
if(nnetworks > 1){
networks <- list(formula = ~1, networks = networks,
stats = numeric(0),coef=0)
class(networks) <- "network.series"
} else{
networks <- networks[[1]]
}
projNames<-names(projects)
projects <- c(projects,list(networks))
names(projects) <-c(projNames, network.title)
return(projects)
}
# reads a single line of a file, splits it into tokens on ' ' and returns as string vector
readAndVectorizeLine <- function(file){
line <- readLines(file, 1, ok = TRUE)
if(!inherits(line,"try-error") & length(line)>0){
line <- strsplit(line," ")[[1]]
line <- line[line!=""]
}
line
}
read.paj.simplify <- function(x,file,verbose=FALSE)
{
classx <- class(x)
if(inherits(x,"network")){
cat(paste(file," is a single network object.\n",sep=""))
assign(file,x)
save(list=file,
file=paste(file,".RData",sep=""))
cat(paste("network saved as a 'network' object in ",file,".RData.\n",sep=""))
return(x)
}
if(inherits(x,"network.series")){
nnets <- length(x$networks)
cat(paste(file," is a set of ",nnets," networks on the same set of nodes.\n",sep=""))
cat(paste("The network names are:\n ",
paste(names(x$networks),collapse="\n "),"\n",sep=""))
cnames <- names(x$networks)
if(length(cnames) == 1){
assign(cnames,x$networks[[1]])
save(list=cnames,
file=paste(file,".RData",sep=""))
cat(paste("network simplified to a network object.\n",sep=""))
cat(paste("network saved as a 'network' object in ",file,".RData.\n",sep=""))
return(x$networks[[1]])
}else{
assign(file,x)
save(list=file,
file=paste(file,".RData",sep=""))
cat(paste("network saved as a 'network.series' object in ",file,".RData.\n",sep=""))
return(x)
}
}
if(classx=="list"){
ncollects <- length(x$networks)
nnets <- length(x$networks)
npart <- length(x$partitions)
cnames <- names(x$networks)
if(length(cnames) > 1){
cat(paste(file," is a set of ",ncollects," collections of networks\n",
"as well as Pajek 'partiton' information.\n",sep=""))
cat(paste("The collection names are:\n ",
paste(cnames,collapse="\n "),"\n",sep=""))
for(i in seq(along.with=cnames)){
thisnet <- x$networks[[i]]
classthisnet <- class(thisnet)
if(inherits(thisnet,"network.series") & length(thisnet$networks)==1){
thisnet <- thisnet$networks[[1]]
classthisnet <- class(thisnet)
}
if(inherits(thisnet,"network")){
cat(paste("The collection ",cnames[i]," is a single network object.\n",
sep=""))
}else{
cat(paste("The collection ",cnames[i], " is a set of networks on the same nodes.\n",sep=""))
cat(paste("The network names are:\n ",
paste(names(thisnet$networks),collapse="\n "),"\n",sep=""))
}
}
cat(paste("There are ",npart," partitions on the networks.\n",sep=""))
cat(paste("The partition names are:\n ",
paste(names(x$partitions),collapse="\n "),"\n",sep=""))
cat(paste(".RData file unchanged.\n",sep=""))
}else{
thisnet <- x$networks[[1]]
classthisnet <- class(thisnet)
if(inherits(thisnet,"network")){
cat(paste(file," is a single network object called ", cnames,"\n",
"as well as Pajek 'partiton' information.\n",sep=""))
cat(paste("There are ",npart," partitions on the networks.\n",sep=""))
cat(paste("The partition names are:\n ",
paste(names(x$partitions),collapse="\n "),"\n",sep=""))
}else{
cat(paste(file," is a collection of networks called ", cnames,"\n",
"as well as Pajek 'partiton' information.\n",sep=""))
cat(paste("The network names are:\n ",
paste(names(thisnet$networks),collapse="\n "),"\n",sep=""))
cat(paste("There are ",npart," partitions on the networks.\n",sep=""))
cat(paste("The partition names are:\n ",
paste(names(x$partitions),collapse="\n "),"\n",sep=""))
}
assign(cnames,x$networks[[1]])
assign(paste(cnames,"partitions",sep="."),x$partitions)
save(list=c(cnames, paste(cnames,"partitions",sep=".")),
file=paste(file,".RData",sep=""))
if(inherits(x$networks[[1]],"network")){
cat(paste("network simplified to a 'network' object plus partition.\n",sep=""))
cat(paste("network saved as a 'network' object and a separate partition list in ",file,".RData.\n",sep=""))
}else{
cat(paste("network simplified to a 'network.series' object plus partition.\n",sep=""))
cat(paste("network saved as a 'network.series' object and a separate partition list in ",file,".RData.\n",sep=""))
}
}
}
return(x)
}
# swaps the first two columns (tail, heads) in a matrix
switchArcDirection <- function(edgelist){
edgelist[,1:2] <- edgelist[,2:1]
edgelist
}
# return a character matrix with number of rows equal to length of list x
# and ncol = longest element in x
# assumes that list elements may not be all the same length
# each row is filled in fro
fillMatrixFromListRows<-function(x){
maxLen<-max(sapply(x,length))
paddedRows<-lapply(x,function(r){
row<-rep('',maxLen)
row[1:length(r)]<-unlist(r)
row
})
return(do.call(rbind,paddedRows))
}
# convert strings in pajek's timing notation into a spell matrix
# example "[5-10,12-14]", "[1-3,7]", "[4-*]"
# does not check spells for correctness of spell definitions
as.spells.pajek <-function(pajekTiming,assume.discrete=TRUE){
# strip off brackets
p<-gsub('\\[','',pajekTiming)
p<-gsub('\\]','',p)
# split on comma
splStrings<-strsplit(p,',')
spls<-sapply(splStrings[[1]],function(s){
# default always active
spl<-c(-Inf,Inf)
elements<-strsplit(s,'-')[[1]]
if(length(elements)==2){
# replace Infs
if (elements[1]=='*'){
elements[1]<-'-Inf'
}
if (elements[2]=='*'){
elements[2]<-'Inf'
}
# convert to numeric and form spell
spl<-c(as.numeric(elements[1]),as.numeric(elements[2]))
} else if (length(elements)==1){
# only one element, so duplicate
spl[1:2]<-as.numeric(elements[1])
} else {
stop('unable to parse token: ',s)
}
if (assume.discrete){
# add one time unit to the ending value to conform with networkDynamic's 'until' spell definition
spl[2]<-spl[2]+1
}
return(spl)
})
# reshape vector of spell data into a 2-column matrix
return(matrix(spls,ncol=2,byrow=TRUE))
}
network/R/access.R 0000644 0001762 0000144 00000236600 14724557111 013546 0 ustar ligges users ######################################################################
#
# access.R
#
# Written by Carter T. Butts ; portions contributed by
# David Hunter and Mark S. Handcock
# .
#
# Last Modified 12/04/24
# Licensed under the GNU General Public License version 2 (June, 1991)
# or greater
#
# Part of the R/network package
#
# This file contains various routines for accessing network class objects.
#
# Contents:
#
# add.edge
# add.edges
# add.vertices
# delete.edge.attribute
# delete.edges
# delete.network.attribute
# delete.vertex.attribute
# delete.vertices
# get.edge.attribute
# get.edge.value
# get.edgeIDs
# get.edges
# get.inducedSubgraph
# get.network.attribute
# get.neighborhood
# get.vertex.attribute
# has.loops
# is.adjacent
# is.bipartite
# is.directed
# is.hyper
# is.multiplex
# is.network
# list.edge.attributes
# list.network.attributes
# list.vertex.attributes
# network.dyadcount
# network.edgecount
# network.naedgecount
# network.size
# network.vertex.names
# network.vertex.names<-
# permute.vertexIDs
# set.edge.attribute
# set.edge.value
# set.network.attribute
# set.vertex.attribute
# valid.eids
#
######################################################################
#Add a single edge to a network object.
# S3 method dispatch for add edge
#' @name add.edges
#'
#' @title Add Edges to a Network Object
#'
#' @description Add one or more edges to an existing network object.
#'
#' @details The edge checking procedure is very slow, but should always be employed when
#' debugging; without it, one cannot guarantee that the network state is
#' consistent with network level variables (see
#' \code{\link{network.indicators}}). For example, by default it is possible to
#' add multiple edges to a pair of vertices.
#'
#' Edges can also be added/removed via the extraction/replacement operators.
#' See the associated man page for details.
#'
#' @aliases add.edges.network add.edge.network
#' @param x an object of class \code{network}
#' @param tail for \code{add.edge}, a vector of vertex IDs reflecting the tail
#' set for the edge to be added; for \code{add.edges}, a list of such vectors
#' @param head for \code{add.edge}, a vector of vertex IDs reflecting the head
#' set for the edge to be added; for \code{add.edges}, a list of such vectors
#' @param names.eval for \code{add.edge}, an optional list of names for edge
#' attributes; for \code{add.edges}, a list of length equal to the number of
#' edges, with each element containing a list of names for the attributes of
#' the corresponding edge
#' @param vals.eval for \code{add.edge}, an optional list of edge attribute
#' values (matching \code{names.eval}); for \code{add.edges}, a list of such
#' lists
#' @param edge.check logical; should we perform (computationally expensive)
#' tests to check for the legality of submitted edges?
#' @param ... additional arguments
#' @return Invisibly, \code{add.edge} and \code{add.edges} return pointers to
#' their modified arguments; both functions modify their arguments in place..
#' @note \code{add.edges} and \code{add.edge} were converted to an S3 generic
#' funtions in version 1.9, so they actually call \code{add.edges.network} and
#' \code{add.edge.network} by default, and may call other versions depending on
#' context (i.e. when called with a \code{networkDynamic} object).
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network}}, \code{\link{add.vertices}},
#' \code{\link{network.extraction}}, \code{\link{delete.edges}},
#' \code{\link{network.edgelist}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' #Initialize a small, empty network
#' g<-network.initialize(3)
#'
#' #Add an edge
#' add.edge(g,1,2)
#' g
#'
#' #Can also add edges using the extraction/replacement operators
#' #note that replacement operators are much slower than add.edges()
#' g[,3]<-1
#' g[,]
#'
#' #Add multiple edges with attributes to a network
#'
#' # pretend we just loaded in this data.frame from a file
#' # Note: network.edgelist() may be simpler for this case
#' elData<-data.frame(
#' from_id=c("1","2","3","1","3","1","2"),
#' to_id=c("1", "1", "1", "2", "2", "3", "3"),
#' myEdgeWeight=c(1, 2, 1, 2, 5, 3, 9.5),
#' someLetters=c("B", "W", "L", "Z", "P", "Q", "E"),
#' edgeCols=c("red","green","blue","orange","pink","brown","gray"),
#' stringsAsFactors=FALSE
#' )
#'
#' valueNet<-network.initialize(3,loops=TRUE)
#'
#' add.edges(valueNet,elData[,1],elData[,2],
#' names.eval=rep(list(list("myEdgeWeight","someLetters","edgeCols")),nrow(elData)),
#' vals.eval=lapply(1:nrow(elData),function(r){as.list(elData[r,3:5])}))
#'
#' list.edge.attributes(valueNet)
#'
#'
#' @export
add.edge <- function(x, tail, head, names.eval=NULL, vals.eval=NULL, edge.check=FALSE, ...) UseMethod("add.edge")
#' @export add.edge.network
#' @export
add.edge.network<-function(x, tail, head, names.eval=NULL, vals.eval=NULL, edge.check=FALSE, ...){
xn<-substitute(x)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
if(is.null(edge.check)||(length(edge.check)<1)||is.na(edge.check[1]))
edge.check<-FALSE
x<-.Call(addEdge_R,x,tail,head,names.eval,vals.eval,edge.check)
invisible(x)
}
# S3 method dispatch for add.edges
#' @rdname add.edges
#' @export add.edges
add.edges <- function(x, tail, head, names.eval=NULL, vals.eval=NULL, ...) UseMethod("add.edges")
# Add multiple edges to network x. Tail must be a list, each element of
# which is the tail set for a given edge (ditto for head). If edge values
# are provided, they must be given similarly as lists of lists.
#' @export add.edges.network
#' @export
add.edges.network<-function(x, tail, head, names.eval=NULL, vals.eval=NULL, ...){
#Ensure that the inputs are set up appropriately
if(!is.list(tail))
tail<-as.list(tail)
if(!is.list(head))
head<-as.list(rep(head,length.out=length(tail)))
if(is.null(names.eval))
names.eval<-replicate(length(tail),NULL)
else if(!is.list(names.eval))
names.eval<-as.list(rep(names.eval,length.out=length(tail)))
if(is.null(vals.eval))
vals.eval<-replicate(length(tail),NULL)
else if(!is.list(vals.eval))
vals.eval<-as.list(rep(vals.eval,length.out=length(names.eval)))
if(length(unique(c(length(tail),length(head),length(names.eval), length(vals.eval))))>1)
stop("head, tail, names.eval and vals.eval lists passed to add.edges must be of the same length!\n")
edge.check<-list(...)$edge.check
if(is.null(edge.check)||(length(edge.check)<1)||is.na(edge.check[1]))
edge.check<-FALSE
#Pass the inputs to the C side
xn<-substitute(x)
x<-.Call(addEdges_R,x,tail,head,names.eval,vals.eval,edge.check)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
invisible(x)
}
# S3 method dispatch for add.vertices
#' Add Vertices to an Existing Network
#'
#' \code{add.vertices} adds a specified number of vertices to an existing
#' network; if desired, attributes for the new vertices may be specified as
#' well.
#'
#' New vertices are generally appended to the end of the network (i.e., their
#' vertex IDs begin with \code{network.size(x)} an count upward). The one
#' exception to this rule is when \code{x} is bipartite and
#' \code{last.mode==FALSE}. In this case, new vertices are added to the end of
#' the first mode, with existing second-mode vertices being permuted upward in
#' ID. (\code{x}'s \code{bipartite} attribute is adjusted accordingly.)
#'
#' Note that the attribute format used here is based on the internal
#' (vertex-wise) storage method, as opposed to the attribute-wise format used
#' by \code{\link{network}}. Specifically, \code{vattr} should be a list with
#' one entry per new vertex, the ith element of which should be a list with an
#' element for every attribute of the ith vertex. (If the required \code{na}
#' attribute is not given, it will be automatically created.)
#'
#' @aliases add.vertices.network
#' @param x an object of class \code{network}
#' @param nv the number of vertices to add
#' @param vattr optionally, a list of attributes with one entry per new vertex
#' @param last.mode logical; should the new vertices be added to the last
#' (rather than the first) mode of a bipartite network?
#' @param ... possible additional arguments to add.vertices
#' @return Invisibly, a pointer to the updated \code{network} object;
#' \code{add.vertices} modifies its argument in place.
#' @note \code{add.vertices} was converted to an S3 generic funtion in version
#' 1.9, so it actually calls \code{add.vertices.network} by default and may
#' call other versions depending on context (i.e. when called with a
#' \code{networkDynamic} object).
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network}}, \code{\link{get.vertex.attribute}},
#' \code{\link{set.vertex.attribute}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' #Initialize a network object
#' g<-network.initialize(5)
#' g
#'
#' #Add five more vertices
#' add.vertices(g,5)
#' g
#'
#' #Create two more, with attributes
#' vat<-replicate(2,list(is.added=TRUE,num.added=2),simplify=FALSE)
#' add.vertices(g,2,vattr=vat)
#' g%v%"is.added" #Values are only present for the new cases
#' g%v%"num.added"
#'
#' #Add to a bipartite network
#' bip <-network.initialize(5,bipartite=3)
#' get.network.attribute(bip,'bipartite') # how many vertices in first mode?
#' add.vertices(bip,3,last.mode=FALSE)
#' get.network.attribute(bip,'bipartite')
#'
#' @export add.vertices
add.vertices <- function(x, nv, vattr=NULL, last.mode=TRUE, ...) UseMethod("add.vertices")
# Add nv vertices to network x. Vertex attributes (in addition to those which
# are required) are to be provided in vattr; vattr must be a list containing
# nv elements, each of which is equal to the desired val[i] entry.
#' @export add.vertices.network
#' @export
add.vertices.network<-function(x, nv, vattr=NULL, last.mode=TRUE, ...){
#Check to be sure we were called with a network
if(!is.network(x))
stop("add.vertices requires an argument of class network.\n")
#Check the vertex attributes, to be sure that they are legal
if(!is.null(vattr)){
if(is.list(vattr))
vattr<-rep(vattr,length.out=nv)
else
vattr<-as.list(rep(vattr,length.out=nv))
}
#Perform the addition
xn<-substitute(x)
if(nv>0){
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
if(last.mode||(!is.bipartite(x))){
x<-.Call(addVertices_R,x,nv,vattr)
}else{
nr<-nv
nc<-0
nnew<-nr+nc
nold<-network.size(x)
bip<-x%n%"bipartite"
x<-.Call(addVertices_R, x, nv, vattr)
if(nr>0){
if(bip>0)
orow<-1:bip
else
orow<-NULL
if(nold-bip>0)
ocol<-(bip+1):nold
else
ocol<-NULL
ncol<-NULL
nrow<-(nold+nnew-nr+1):(nold+nnew)
permute.vertexIDs(x,c(orow,nrow,ocol,ncol))
set.network.attribute(x,"bipartite",bip+nr)
}
}
}
invisible(x)
}
# Remove all instances of the specified attribute(s) from the edge set
#
#' @name attribute.methods
#'
#' @title Attribute Interface Methods for the Network Class
#'
#' @description These methods get, set, list, and delete attributes at the
#' network, edge, and vertex level.
#'
#' @details The \code{list.attributes} functions return the names of all edge,
#' network, or vertex attributes (respectively) in the network. All
#' attributes need not be defined for all elements; the union of all extant
#' attributes for the respective element type is returned.
#'
#' The \code{get.attribute} functions look for an edge, network, or vertex
#' attribute (respectively) with the name \code{attrname}, returning its
#' values. Note that, to retrieve an edge attribute from all edges within
#' a network \code{x}, \code{x$mel} should be used as the first argument to
#' \code{get.edge.attribute}; \code{get.edge.value} is a convenience function
#' which does this automatically. As of v1.7.2, if a \code{network} object is
#' passed to \code{get.edge.attribute} it will automatically call
#' \code{get.edge.value} instead of returning NULL. When the parameters
#' \code{na.omit}, or \code{deleted.edges.omit} are used, the position index
#' of the attribute values returned will not correspond to the vertex/edge
#' id. To preserved backward compatibility, if the edge attribute
#' \code{attrname} does not exist for any edge, \code{get.edge.attribute}
#' will still return \code{NULL} even if \code{null.na=TRUE}
#'
#' \code{network.vertex.names} is a convenience function to extract the
#' \code{"vertex.names"} attribute from all vertices.
#'
#' The \code{set.attribute} functions allow one to set the values of edge,
#' network, or vertex attributes. \code{set.edge.value} is a convenience
#' function which allows edge attributes to be given in adjacency matrix
#' form, and the assignment form of \code{network.vertex.names} is likewise
#' a convenient front-end to \code{set.vertex.attribute} for vertex names.
#' The \code{delete.attribute} functions, by contrast, remove the named
#' attribute from the network, from all edges, or from all vertices (as
#' appropriate). If \code{attrname} is a vector of attribute names, each
#' will be removed in turn. These functions modify their arguments in place,
#' although a pointer to the modified object is also (invisibly) returned.
#'
#' Additional practical example of how to load and attach attributes are on the
#' \code{\link{loading.attributes}} page.
#'
#' Some attribute assignment/extraction can be performed conveniently through
#' the various extraction/replacement operators, although they may be less
#' efficient. See the associated man page for details.
#'
#'
#' @param x an object of class \code{network}, or a list of edges
#' (possibly \code{network$mel}) in \code{get.edge.attribute}.
#' @param el Deprecated; use \code{x} instead.
#' @param attrname the name of the attribute to get or set.
#' @param unlist logical; should retrieved attribute values be
#' \code{\link{unlist}}ed prior to being returned?
#' @param na.omit logical; should retrieved attribute values corresponding to
#' vertices/edges marked as 'missing' be removed?
#' @param deleted.edges.omit logical: should the elements corresponding to
#' deleted edges be removed?
#' @param null.na logical; should \code{NULL} values (corresponding to vertices
#' or edges with no values set for the attribute) be replaced with \code{NA}s
#' in output?
#' @param value values of the attribute to be set; these should be in
#' \code{vector} or \code{list} form for the \code{edge} and \code{vertex}
#' cases, or \code{matrix} form for \code{set.edge.value}.
#' @param e IDs for the edges whose attributes are to be altered.
#' @param v IDs for the vertices whose attributes are to be altered.
#' @param ... additional arguments
#'
#' @return For the \code{list.attributes} methods, a vector containing
#' attribute names. For the \code{get.attribute} methods, a list containing
#' the values of the attribute in question (or simply the value itself, for
#' \code{get.network.attribute}). For the \code{set.attribute} and
#' \code{delete.attribute} methods, a pointer to the updated \code{network}
#' object.
#' @note As of version 1.9 the \code{set.vertex.attribute} function can accept
#' and modify multiple attributes in a single call to improve efficiency.
#' For this case \code{attrname} can be a list or vector of attribute names
#' and \code{value} is a list of values corresponding to the elements of
#' \code{attrname} (can also be a list of lists of values if elements in v
#' should have different values).
#' @seealso \code{\link{loading.attributes}},\code{\link{network}},
#' \code{\link{as.network.matrix}}, \code{\link{as.sociomatrix}},
#' \code{\link{as.matrix.network}}, \code{\link{network.extraction}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @author Carter T. Butts \email{buttsc@uci.edu}
#' @examples
#' #Create a network with three edges
#' m<-matrix(0,3,3)
#' m[1,2]<-1; m[2,3]<-1; m[3,1]<-1
#' g<-network(m)
#'
#' #Create a matrix of values corresponding to edges
#' mm<-m
#' mm[1,2]<-7; mm[2,3]<-4; mm[3,1]<-2
#'
#' #Assign some attributes
#' set.edge.attribute(g,"myeval",3:5)
#' set.edge.value(g,"myeval2",mm)
#' set.network.attribute(g,"mygval","boo")
#' set.vertex.attribute(g,"myvval",letters[1:3])
#' network.vertex.names(g) <- LETTERS[1:10]
#'
#' #List the attributes
#' list.edge.attributes(g)
#' list.network.attributes(g)
#' list.vertex.attributes(g)
#'
#' #Retrieve the attributes
#' get.edge.attribute(g$mel,"myeval") #Note the first argument!
#' get.edge.value(g,"myeval") #Another way to do this
#' get.edge.attribute(g$mel,"myeval2")
#' get.network.attribute(g,"mygval")
#' get.vertex.attribute(g,"myvval")
#' network.vertex.names(g)
#'
#' #Purge the attributes
#' delete.edge.attribute(g,"myeval")
#' delete.edge.attribute(g,"myeval2")
#' delete.network.attribute(g,"mygval")
#' delete.vertex.attribute(g,"myvval")
#'
#' #Verify that the attributes are gone
#' list.edge.attributes(g)
#' list.network.attributes(g)
#' list.vertex.attributes(g)
#'
#' #Note that we can do similar things using operators
#' g %n% "mygval" <- "boo" #Set attributes, as above
#' g %v% "myvval" <- letters[1:3]
#' g %e% "myeval" <- mm
#' g[,,names.eval="myeval"] <- mm #Another way to do this
#' g %n% "mygval" #Retrieve the attributes
#' g %v% "myvval"
#' g %e% "mevval"
#' as.sociomatrix(g,"myeval") # Or like this
#'
#' @keywords classes graphs
#' @export delete.edge.attribute
delete.edge.attribute <- function(x, attrname, ...) UseMethod("delete.edge.attribute")
#' @rdname attribute.methods
#' @export
delete.edge.attribute.network <- function(x, attrname, ...) {
#Remove the edges
xn<-substitute(x)
x<-.Call(deleteEdgeAttribute_R,x,attrname)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
invisible(x)
}
# Remove specified edges from the network.
#
#' @name deletion.methods
#'
#' @title Remove Elements from a Network Object
#'
#' @description \code{delete.edges} removes one or more edges (specified by
#' their internal ID numbers) from a network; \code{delete.vertices}
#' performs the same task for vertices (removing all associated edges in
#' the process).
#'
#' @details Note that an edge's ID number corresponds to its order within
#' \code{x$mel}. To determine edge IDs, see \code{\link{get.edgeIDs}}.
#' Likewise, vertex ID numbers reflect the order with which vertices are
#' listed internally (e.g., the order of \code{x$oel} and \code{x$iel}, or
#' that used by \code{as.matrix.network.adjacency}). When vertices are
#' removed from a network, all edges having those vertices as endpoints are
#' removed as well. When edges are removed, the remaining edge ids are NOT
#' permuted and \code{NULL} elements will be left on the list of edges, which
#' may complicate some functions that require eids (such as
#' \code{\link{set.edge.attribute}}). The function \code{\link{valid.eids}}
#' provides a means to determine the set of valid (non-NULL) edge ids.
#'
#' Edges can also be added/removed via the extraction/replacement operators.
#' See the associated man page for details.
#'
#' @param x an object of class \code{network}.
#' @param eid a vector of edge IDs.
#' @param vid a vector of vertex IDs.
#' @param ... additional arguments to methods.
#'
#' @return Invisibly, a pointer to the updated network; these functions modify
#' their arguments in place.
#'
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @author Carter T. Butts \email{buttsc@uci.edu}
#'
#' @seealso \code{\link{get.edgeIDs}}, \code{\link{network.extraction}},
#' \code{\link{valid.eids}}
#' @examples
#' #Create a network with three edges
#' m<-matrix(0,3,3)
#' m[1,2]<-1; m[2,3]<-1; m[3,1]<-1
#' g<-network(m)
#'
#' as.matrix.network(g)
#' delete.edges(g,2) #Remove an edge
#' as.matrix.network(g)
#' delete.vertices(g,2) #Remove a vertex
#' as.matrix.network(g)
#'
#' #Can also remove edges using extraction/replacement operators
#' g<-network(m)
#' g[1,2]<-0 #Remove an edge
#' g[,]
#' g[,]<-0 #Remove all edges
#' g[,]
#'
#' @keywords classes graphs
#' @export
delete.edges <- function(x, eid, ...) UseMethod("delete.edges")
#' @rdname deletion.methods
#' @export
delete.edges.network <- function(x, eid, ...) {
xn<-substitute(x)
if(length(eid)>0){
#Perform a sanity check
if((min(eid)<1)|(max(eid)>length(x$mel)))
stop("Illegal edge in delete.edges.\n")
#Remove the edges
x<-.Call(deleteEdges_R,x,eid)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
}
invisible(x)
}
# Remove the specified network-level attribute(s)
#
#' @rdname attribute.methods
#' @export
delete.network.attribute <- function(x, attrname, ...) UseMethod("delete.network.attribute")
#' @rdname attribute.methods
#' @export
delete.network.attribute.network <- function(x, attrname, ...){
#Remove the edges
xn<-substitute(x)
x<-.Call(deleteNetworkAttribute_R,x,attrname)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
invisible(x)
}
# Remove all instances of the specified attribute(s) from the vertex set
#
#' @rdname attribute.methods
#' @export
delete.vertex.attribute <- function(x, attrname, ...) UseMethod("delete.vertex.attribute")
#' @rdname attribute.methods
#' @export
delete.vertex.attribute.network <- function(x, attrname, ...) {
#Remove the attribute (or do nothing, if there are no vertices)
if(network.size(x)>0){
xn<-substitute(x)
x<-.Call(deleteVertexAttribute_R,x,attrname)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
}
invisible(x)
}
# Remove specified vertices (and associated edges) from the network.
#
#' @rdname deletion.methods
#' @export
delete.vertices <- function(x, vid, ...) UseMethod("delete.vertices")
#' @rdname deletion.methods
#' @export
delete.vertices.network <- function(x, vid, ...) {
#Remove any vids which are out of bounds
vid<-vid[(vid>0)&(vid<=network.size(x))]
#Do the deed, if still needed
xn<-substitute(x)
if(length(vid)>0){
if(is.bipartite(x)){ #If bipartite, might need to adjust mode 1 count
m1v<-get.network.attribute(x,"bipartite") #How many mode 1 verts?
set.network.attribute(x,"bipartite",m1v-sum(vid<=m1v))
}
x<-.Call(deleteVertices_R,x,vid)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
}
invisible(x)
}
# Retrieve a specified edge attribute from edge list or network x. The attribute
# is returned as a list, unless unlist is TRUE.
# if deleted.edges.omit is TRUE, then only attribute values on existing (non-null) edges will be returned.
# if na.omit is TRUE, than values corresponding to 'missing' edges (edges with attribute 'na' set to TRUE) should be ommited. (NULL edgs count as not-missing)
# If null.na is TRUE, then values corresponding to edges for which the attribute name was never set will be set to NA. Otherwise, they will be NULL, which means they will be included when unlist=TRUE
#
#' @rdname attribute.methods
#' @export
get.edge.attribute <- function(x, ..., el) {
if(!missing(el)) {
warning("Argument ", sQuote("el"), " to ", sQuote("get.edge.attribute"), " is deprecated and will be removed in a future version. Use ", sQuote("x"), " instead.")
UseMethod("get.edge.attribute", object = el)
} else {
UseMethod("get.edge.attribute", object = x)
}
}
#' @rdname attribute.methods
#' @export
get.edge.attribute.network <- function(x, attrname, unlist=TRUE, na.omit=FALSE, null.na=FALSE, deleted.edges.omit=FALSE, ..., el) {
if(!missing(el)) x <- el
if (is.network(x)) x <- x$mel
if (!is.list(x))
stop("x must be a network object or a list.")
if (!is.character(attrname) || (length(attrname)==0))
stop("attrname must be a character vector.")
if (!is.logical(unlist) || !is.logical(na.omit) || !is.logical(null.na) ||
!is.logical(deleted.edges.omit) || (length(unlist)*length(na.omit)*length(null.na)*length(deleted.edges.omit)==0))
stop("na.omit, null.na, deleted.edges.omit must be a logical vector.")
edges <- .Call(getEdgeAttribute_R,x,attrname,na.omit,null.na,deleted.edges.omit)
if(unlist)
unlist(edges)
else
edges
}
#' @rdname attribute.methods
#' @export
get.edge.attribute.list <- get.edge.attribute.network
# Retrieve a specified edge attribute from all edges in x.
#
#' @rdname attribute.methods
#' @export
get.edge.value <- function(x, ...) UseMethod("get.edge.value")
#' @rdname attribute.methods
#' @export
get.edge.value.network <- function(x, attrname, unlist=TRUE, na.omit=FALSE, null.na=FALSE, deleted.edges.omit=FALSE, ...){
get.edge.attribute(x,attrname,unlist,na.omit,null.na,deleted.edges.omit)
}
#' @rdname attribute.methods
#' @export
get.edge.value.list <- get.edge.value.network
# Retrieve the ID numbers for all edges incident on v, in network x.
# Outgoing or incoming edges are specified by neighborhood, while na.omit
# indicates whether or not missing edges should be omitted. The return value
# is a vector of edge IDs.
#
#' @name get.edges
#'
#' @title Retrieve Edges or Edge IDs Associated with a Given Vertex
#'
#' @description \code{get.edges} retrieves a list of edges incident on a given vertex;
#' \code{get.edgeIDs} returns the internal identifiers for those edges,
#' instead. Both allow edges to be selected based on vertex neighborhood and
#' (optionally) an additional endpoint.
#'
#' @details By default, \code{get.edges} returns all out-, in-, or out- and in-edges
#' containing \code{v}. \code{get.edgeIDs} is identical, save in its return
#' value, as it returns only the ids of the edges. Specifying a vertex in
#' \code{alter} causes these edges to be further selected such that alter must
#' also belong to the edge -- this can be used to extract edges between two
#' particular vertices. Omission of missing edges is accomplished via
#' \code{na.omit}. Note that for multiplex networks, multiple edges or edge
#' ids can be returned.
#'
#' The function \code{get.dyads.eids} simplifies the process of looking up the
#' edge ids associated with a set of 'dyads' (tail and head vertex ids) for
#' edges. It only is intended for working with non-multiplex networks and will
#' return a warning and \code{NA} value for any dyads that correspond to
#' multiple edges. The value \code{numeric(0)} will be returned for any dyads
#' that do not have a corresponding edge.
#'
#' @param x an object of class \code{network}
#' @param v a vertex ID
#' @param alter optionally, the ID of another vertex
#' @param neighborhood an indicator for whether we are interested in in-edges,
#' out-edges, or both (relative to \code{v}). defaults to \code{'combined'} for
#' undirected networks
#' @param na.omit logical; should we omit missing edges?
#' @param tails a vector of vertex ID for the 'tails' (v) side of the dyad
#' @param heads a vector of vertex ID for the 'heads' (alter) side of the dyad
#' @return For \code{get.edges}, a list of edges. For \code{get.edgeIDs}, a
#' vector of edge ID numbers. For \code{get.dyads.eids}, a list of edge IDs
#' corresponding to the dyads defined by the vertex ids in \code{tails} and
#' \code{heads}
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{get.neighborhood}}, \code{\link{valid.eids}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' #Create a network with three edges
#' m<-matrix(0,3,3)
#' m[1,2]<-1; m[2,3]<-1; m[3,1]<-1
#' g<-network(m)
#'
#' get.edges(g,1,neighborhood="out")
#' get.edgeIDs(g,1,neighborhood="in")
#'
#' @export get.edgeIDs
get.edgeIDs<-function(x, v, alter=NULL, neighborhood=c("out","in","combined"), na.omit=TRUE){
#Check to be sure we were called with a network
if(!is.network(x))
stop("get.edgeIDs requires an argument of class network.")
#Do some reality checking
n<-network.size(x)
if((v<1)||(v>n))
return(numeric(0))
if((!is.null(alter))&&((alter<1)||(alter>n)))
return(numeric(0))
#Retrieve the edges
if(!is.directed(x))
neighborhood="combined" #If undirected, out==in==combined
else
neighborhood=match.arg(neighborhood)
#Do the deed
.Call(getEdgeIDs_R,x,v,alter,neighborhood,na.omit)
}
# Retrieve all edges incident on v, in network x. Outgoing or incoming
# edges are specified by neighborhood, while na.omit indicates whether
# or not missing edges should be omitted. The return value is a list of
# edges.
#
#' @rdname get.edges
#' @export get.edges
get.edges<-function(x, v, alter=NULL, neighborhood=c("out","in","combined"), na.omit=TRUE){
#Check to be sure we were called with a network
if(!is.network(x))
stop("get.edges requires an argument of class network.")
#Do some reality checking
n<-network.size(x)
if((v<1)||(v>n))
return(list())
if((!is.null(alter))&&((alter<1)||(alter>n)))
return(list())
#Retrieve the edges
if(!is.directed(x))
neighborhood="combined" #If undirected, out==in==combined
else
neighborhood=match.arg(neighborhood)
#Do the deed
.Call(getEdges_R,x,v,alter,neighborhood,na.omit)
}
# get the the edge ids associated with a set of dayds
# as defined by a vector of tails and heads vertex ids
#' @rdname get.edges
#' @export get.dyads.eids
get.dyads.eids<-function(x,tails,heads,neighborhood = c("out", "in", "combined"),na.omit = TRUE){
if(length(tails)!=length(heads)){
stop('heads and tails vectors must be the same length for get.dyads.eids')
}
if (any(heads>network.size(x) | heads<1) | any(tails>network.size(x) | tails<1)){
stop('invalid vertex id in heads or tails vector')
}
neighborhood<-match.arg(neighborhood)
if (!is.directed(x)){
neighborhood = "combined"
}
lapply(seq_along(tails),function(e){
eid<-get.edgeIDs(x,v = tails[e],alter=heads[e],neighborhood=neighborhood,na.omit=na.omit)
if(length(eid)>1){
eid<-NA
warning('get.dyads.eids found multiple edge ids for dyad ',tails[e],',',heads[e],' NA will be returned')
}
eid
})
}
# Given a network and a set of vertices, return the subgraph induced by those
# vertices (preserving all associated metadata); if given two such sets,
# return the edge cut (along with the associated vertices and meta-data) as
# a bipartite network.
#
#' Retrieve Induced Subgraphs and Cuts
#'
#' Given a set of vertex IDs, \code{get.inducedSubgraph} returns the subgraph
#' induced by the specified vertices (i.e., the vertices and all associated
#' edges). Optionally, passing a second set of alters returns the cut from the
#' first to the second set (i.e., all edges passing between the sets), along
#' with the associated endpoints. Alternatively, passing in a vector of edge
#' ids will induce a subgraph containing the specified edges and their incident
#' vertices. In all cases, the result is returned as a network object, with
#' all attributes of the selected edges and/or vertices (and any network
#' attributes) preserved.
#'
#' For \code{get.inducedSubgraph}, \code{v} can be a vector of vertex IDs. If
#' \code{alter=NULL}, the subgraph induced by these vertices is returned.
#' Calling \code{\%s\%} with a single vector of vertices has an identical effect.
#'
#' Where \code{alters} is specified, it must be a vector of IDs disjoint with
#' \code{v}. Where both are given, the edges spanning \code{v} and
#' \code{alters} are returned, along with the vertices in question.
#' (Technically, only the edges really constitute the \dQuote{cut,} but the
#' vertices are included as well.) The same result can be obtained with the
#' \code{\%s\%} operator by passing a two-element list on the right hand side;
#' the first element is then interpreted as \code{v}, and the second as
#' \code{alters}.
#'
#' When \code{eid} is specified, the \code{v} and \code{alters} argument will
#' be ignored and the subgraph induced by the specified edges and their
#' incident vertices will be returned.
#'
#' Any network, vertex, or edge attributes for the selected network elements
#' are retained (although features such as vertex IDs and the network size will
#' typically change). These are copies of the elements in the original
#' network, which is not altered by this function.
#'
#' @param x an object of class \code{network}.
#' @param v a vector of vertex IDs, or, for \code{\%s\%}, optionally a list containing two disjoint vectors of vertex IDs (see below).
#'
#' @param alters optionally, a second vector of vertex IDs. Must be disjoint
#' with \code{v}.
#'
#' @param eid optionally, a numeric vector of valid edge ids in \code{x} that
#' should be retained (cannot be used with \code{v} or \code{alter})
#'
#' @param ... additional arguments for methods.
#'
#' @return A \code{\link{network}} object containing the induced subgraph.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network}}, \code{\link{network.extraction}}
#' @keywords graphs manip
#' @examples
#'
#' #Load the Drabek et al. EMON data
#' data(emon)
#'
#' #For the Mt. St. Helens, EMON, several types of organizations are present:
#' type<-emon$MtStHelens %v% "Sponsorship"
#'
#' #Plot interactions among the state organizations
#' plot(emon$MtStHelens %s% which(type=="State"), displaylabels=TRUE)
#'
#' #Plot state/federal interactions
#' plot(emon$MtStHelens %s% list(which(type=="State"),
#' which(type=="Federal")), displaylabels=TRUE)
#'
#' #Plot state interactions with everyone else
#' plot(emon$MtStHelens %s% list(which(type=="State"),
#' which(type!="State")), displaylabels=TRUE)
#'
#' # plot only interactions with frequency of 2
#' subG2<-get.inducedSubgraph(emon$MtStHelens,
#' eid=which(emon$MtStHelens%e%'Frequency'==2))
#' plot(subG2,edge.label='Frequency')
#'
#'
#' @export get.inducedSubgraph
get.inducedSubgraph <- function(x, ...) UseMethod("get.inducedSubgraph")
#' @rdname get.inducedSubgraph
#' @export
get.inducedSubgraph.network <- function(x, v, alters=NULL, eid=NULL, ...){
#Check to be sure we were called with a network
if(!is.network(x))
stop("get.inducedSubgraph requires an argument of class network.")
#Do some reality checking
n<-network.size(x)
# are we doing this via eids, or v and alters
if (is.null(eid)){ # do checks for v and alters
if((length(v)<1)||any(is.na(v))||any(v<1)||any(v>n))
stop("Illegal vertex selection in get.inducedSubgraph")
if(!is.null(alters)){
if((length(alters)<1)||any(is.na(alters))||any(alters<1)||any(alters>n)|| any(alters%in%v))
stop("Illegal vertex selection (alters) in get.inducedSubgraph")
}
if (!is.null(eid)){
warning('eid argument to get.inducedSubgraph ignored when using v or alter argument')
}
} else { # do checks for eids
if (!is.numeric(eid)){
stop('eid must be a numeric vector of edge ids')
}
if (!missing(v)){
warning('v argument to get.inducedSubgraph ignored when using eid argument')
}
if (!is.null(alters)){
warning('alters argument to get.inducedSubgraph ignored when using eid argument')
}
# check that eids are valid
if (any(!eid%in%valid.eids(x))){
stop('eid argument contains non-valid edge ids')
}
}
#Start by making a copy of our target network (yes, this can be wasteful)
#TODO: in most cases, probably faster to create a new network and only copy over what is needed
newNet<-network.copy(x)
if (is.null(eid)){ # using v and alter
#Now, strip out what is needed, and/or permute in the two-mode case
if(is.null(alters)){ #Simple case
delete.vertices(newNet,(1:n)[-v]) #Get rid of everyone else
}else{ #Really an edge cut, but w/vertices
nv<-length(v)
na<-length(alters)
newids<-sort(c(v,alters))
newv<-match(v,newids)
newalt<-match(alters,newids)
delete.vertices(newNet,(1:n)[-c(v,alters)]) #Get rid of everyone else
permute.vertexIDs(newNet,c(newv,newalt)) #Put the new vertices first
#Remove within-group edges
for(i in 1:nv)
for(j in (i:nv)[-1]){
torem<-get.edgeIDs(newNet,i,alter=j,neighborhood="combined",na.omit=FALSE)
if(length(torem)>0)
delete.edges(newNet,torem)
}
for(i in (nv+1):(nv+na))
for(j in (i:(nv+na))[-1]){
torem<-get.edgeIDs(newNet,i,alter=j,neighborhood="combined",na.omit=FALSE)
if(length(torem)>0)
delete.edges(newNet,torem)
}
newNet%n%"bipartite"<-nv #Set bipartite attribute
}
} else { # using eids instead of v and alters
# delete all the edges not in eid
removeEid<-setdiff(valid.eids(newNet),eid)
delete.edges(newNet,removeEid)
# find the set of vertices incident on the remaining edges
v<-unique(c(unlist(sapply(newNet$mel, "[[", "outl")),unlist(sapply(newNet$mel, "[[", "inl"))))
removeV<-setdiff(seq_len(network.size(newNet)),v)
delete.vertices(newNet,removeV)
}
#Return the updated object
newNet
}
# Retrieve a specified network-level attribute from network x. The attribute
# type depends on the underlying storage mode, and cannot be guaranteed.
#
#' @rdname attribute.methods
#' @export
get.network.attribute <- function(x, ...) UseMethod("get.network.attribute")
#' @rdname attribute.methods
#' @export
get.network.attribute.network <- function(x, attrname, unlist=FALSE, ...) {
x <- x$gal[[attrname]]
if(unlist){unlist(x)}else{x}
}
# Retrieve the neighborhood of v in network x. Depending on the value of
# type, the neighborhood in question may be in, out, or the union of the two.
# The return value for the function is a vector containing vertex IDs.
#
#' Obtain the Neighborhood of a Given Vertex
#'
#' \code{get.neighborhood} returns the IDs of all vertices belonging to the in,
#' out, or combined neighborhoods of \code{v} within network \code{x}.
#'
#' Note that the combined neighborhood is the union of the in and out
#' neighborhoods -- as such, no vertex will appear twice.
#'
#' @param x an object of class \code{network}
#' @param v a vertex ID
#' @param type the neighborhood to be computed
#' @param na.omit logical; should missing edges be ignored when obtaining
#' vertex neighborhoods?
#' @return A vector containing the vertex IDs for the chosen neighborhood.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{get.edges}}, \code{\link{is.adjacent}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#'
#' Wasserman, S. and Faust, K. 1994. \emph{Social Network Analysis: Methods
#' and Applications.} Cambridge: Cambridge University Press.
#' @keywords graphs
#' @examples
#'
#' #Create a network with three edges
#' m<-matrix(0,3,3)
#' m[1,2]<-1; m[2,3]<-1; m[3,1]<-1
#' g<-network(m)
#'
#' #Examine the neighborhood of vertex 1
#' get.neighborhood(g,1,"out")
#' get.neighborhood(g,1,"in")
#' get.neighborhood(g,1,"combined")
#'
#' @export get.neighborhood
get.neighborhood<-function(x, v, type=c("out","in","combined"), na.omit=TRUE){
#Check to be sure we were called with a network
if(!is.network(x))
stop("get.neighborhood requires an argument of class network.")
#Do some reality checking
n<-network.size(x)
if((v<1)||(v>n))
return(numeric(0))
#Retrieve the edges
if(!is.directed(x))
type="combined" #If undirected, out==in==combined
else
type=match.arg(type)
#Do the deed
.Call(getNeighborhood_R,x,v,type,na.omit)
}
# Retrieve a specified vertex attribute (indicated by attrname) from network x.
# Where na.omit==TRUE, values for missing vertices are removed; where
# null.na==TRUE, NULL values are converted to NAs. The return value of this
# function is a list.
#
#' @rdname attribute.methods
#' @export
get.vertex.attribute <- function(x, ...) UseMethod("get.vertex.attribute")
#' @rdname attribute.methods
#' @export
get.vertex.attribute.network <- function(x, attrname, na.omit=FALSE, null.na=TRUE, unlist=TRUE, ...) {
#Check to see if there's anything to be done
if(network.size(x)==0){
return(NULL)
}
# MB: Showing warnings if attribute not present is infeasible and causes an
# avalanche of problems downstream. Hence, it is commented-out here as a
# warning to future generations of Statnet developers before they decide to
# revisit the problem. C.f. https://github.com/statnet/network/issues/41
#
#if(!(attrname %in% list.vertex.attributes(x)))
# warning(paste('attribute', attrname,'is not specified for these vertices'))
#Get the list of attribute values
va<-lapply(x$val,"[[",attrname)
#If needed, figure out who's missing
if(na.omit)
vna<-unlist(lapply(x$val,"[[","na"))
else
vna<-rep(FALSE,length(va))
#Replace NULL values with NAs, if requested
if(null.na)
va[sapply(va,is.null)]<-NA
#Return the result
if (na.omit){
x <- va[!vna]
} else {
x<-va
}
if(unlist){unlist(x)}else{x}
}
# Return TRUE iff network x has loops.
#
#' Indicator Functions for Network Properties
#'
#' Various indicators for properties of \code{network} class objects.
#'
#' These methods are the standard means of assessing the state of a
#' \code{network} object; other methods can (and should) use these routines in
#' governing their own behavior. As such, improper setting of the associated
#' attributes may result in unpleasantly creative results. (See the
#' \code{edge.check} argument to \code{\link{add.edges}} for an example of code
#' which makes use of these network properties.)
#'
#' The functions themselves behave has follows:
#'
#' \code{has.loops} returns \code{TRUE} iff \code{x} is allowed to contain
#' loops (or loop-like edges, in the hypergraphic case).
#'
#' \code{is.bipartite} returns \code{TRUE} iff the \code{x} has been explicitly
#' bipartite-coded. Values of \code{bipartite=NULL}, and \code{bipartite=FALSE}
#' will evaluate to \code{FALSE}, numeric values of \code{bipartite>=0} will
#' evaluate to \code{TRUE}. (The value \code{bipartite==0} indicates that it is
#' a bipartite network with a zero-sized first partition.) Note that
#' \code{is.bipartite} refers only to the storage properties of \code{x} and
#' how it should be treated by some algorithms; \code{is.bipartite(x)==FALSE}
#' it does \emph{not} mean that \code{x} cannot admit a bipartition!
#'
#' \code{is.directed} returns \code{TRUE} iff the edges of \code{x} are to be
#' interpreted as directed.
#'
#' \code{is.hyper} returns \code{TRUE} iff \code{x} is allowed to contain
#' hypergraphic edges.
#'
#' \code{is.multiplex} returns \code{TRUE} iff \code{x} is allowed to contain
#' multiplex edges.
#'
#' @name network.indicators
#'
#' @param x an object of class \code{network}
#' @return \code{TRUE} or \code{FALSE}
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network}}, \code{\link{get.network.attribute}},
#' \code{set.network.attribute}, \code{\link{add.edges}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' g<-network.initialize(5) #Initialize the network
#' is.bipartite(g)
#' is.directed(g)
#' is.hyper(g)
#' is.multiplex(g)
#' has.loops(g)
#'
#' @export
has.loops<-function(x){
if(!is.network(x))
stop("has.loops requires an argument of class network.")
else
get.network.attribute(x,"loops")
}
# Return TRUE iff (vi,vj) in network x. Where na.omit==TRUE, edges flagged
# as missing are ignored.
#
#' Determine Whether Two Vertices Are Adjacent
#'
#' \code{is.adjacent} returns \code{TRUE} iff \code{vi} is adjacent to
#' \code{vj} in \code{x}. Missing edges may be omitted or not, as per
#' \code{na.omit}.
#'
#' Vertex \eqn{v} is said to be adjacent to vertex \eqn{v'} within directed
#' network \eqn{G} iff there exists some edge whose tail set contains \eqn{v}
#' and whose head set contains \eqn{v'}. In the undirected case, head and tail
#' sets are exchangeable, and thus \eqn{v} is adjacent to \eqn{v'} if there
#' exists an edge such that \eqn{v} belongs to one endpoint set and \eqn{v'}
#' belongs to the other. (In dyadic graphs, these sets are of cardinality 1,
#' but this may not be the case where hyperedges are admitted.)
#'
#' If an edge which would make \eqn{v} and \eqn{v'} adjacent is marked as
#' missing (via its \code{na} attribute), then the behavior of
#' \code{is.adjacent} depends upon \code{na.omit}. If \code{na.omit==FALSE}
#' (the default), then the return value is considered to be \code{NA} unless
#' there is also \emph{another} edge from \eqn{v} to \eqn{v'} which is
#' \emph{not} missing (in which case the two are clearly adjacent). If
#' \code{na.omit==TRUE}, on the other hand the missing edge is simply
#' disregarded in assessing adjacency (i.e., it effectively treated as not
#' present). It is important not to confuse \dQuote{not present} with
#' \dQuote{missing} in this context: the former indicates that the edge in
#' question does not belong to the network, while the latter indicates that the
#' state of the corresponding edge is regarded as unknown. By default, all
#' edge states are assumed \dQuote{known} unless otherwise indicated (by
#' setting the edge's \code{na} attribute to \code{TRUE}; see
#' \code{\link{attribute.methods}}).
#'
#' Adjacency can also be determined via the extraction/replacement operators.
#' See the associated man page for details.
#'
#' @param x an object of class \code{network}
#' @param vi a vertex ID
#' @param vj a second vertex ID
#' @param na.omit logical; should missing edges be ignored when assessing
#' adjacency?
#' @return A logical, giving the status of the (i,j) edge
#' @note Prior to version 1.4, \code{na.omit} was set to \code{TRUE} by
#' default.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{get.neighborhood}}, \code{\link{network.extraction}},
#' \code{\link{attribute.methods}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#'
#' Wasserman, S. and Faust, K. 1994. \emph{Social Network Analysis: Methods
#' and Applications}. Cambridge: Cambridge University Press.
#' @keywords graphs
#' @examples
#'
#' #Create a very simple graph
#' g<-network.initialize(3)
#' add.edge(g,1,2)
#' is.adjacent(g,1,2) #TRUE
#' is.adjacent(g,2,1) #FALSE
#' g[1,2]==1 #TRUE
#' g[2,1]==1 #FALSE
#'
#' @export is.adjacent
is.adjacent<-function(x,vi,vj,na.omit=FALSE){
if(!is.network(x))
stop("is.adjacent requires an argument of class network.\n")
if(length(vi)!=length(vj)){
vi<-rep(vi,length.out=max(length(vi),length(vj)))
vj<-rep(vj,length.out=max(length(vi),length(vj)))
}
#Do the deed
.Call(isAdjacent_R,x,vi,vj,na.omit)
}
# Return TRUE iff network x is bipartite
#
#' @rdname network.indicators
#' @param ... other arguments passed to/from other methods
#' @export
is.bipartite <- function(x, ...) UseMethod("is.bipartite")
#' @rdname network.indicators
#' @export
is.bipartite.network<-function(x, ...){
bip <- get.network.attribute(x,"bipartite")
if(is.null(bip)){
return(FALSE)
} else if (is.logical(bip)){
return(bip)
}else{
return(bip>=0)
}
}
# Return TRUE iff network x is directed.
#
#' @rdname network.indicators
#' @export
is.directed <- function(x, ...) UseMethod("is.directed")
#' @rdname network.indicators
#' @export
is.directed.network<-function(x, ...){
get.network.attribute(x,"directed")
}
# Return TRUE iff network x is hypergraphic.
#
#' @rdname network.indicators
#' @export
is.hyper<-function(x){
if(!is.network(x))
stop("is.hyper requires an argument of class network.\n")
else
get.network.attribute(x,"hyper")
}
# Return TRUE iff network x is multiplex.
#
#' @rdname network.indicators
#' @export
is.multiplex<-function(x){
if(!is.network(x))
stop("is.multiplex requires an argument of class network.\n")
else
get.network.attribute(x,"multiple")
}
# Return a network whose edges are the missing edges of x
#
#' @rdname network.naedgecount
#' @name missing.edges
#' @title Identifying and Counting Missing Edges in a Network Object
#'
#' @description \code{network.naedgecount} returns the number of edges within a
#' \code{network} object which are flagged as missing. The \code{is.na}
#' network method returns a new network containing the missing edges.
#'
#' @details The missingness of an edge is controlled by its \code{na} attribute (which
#' is mandatory for all edges); \code{network.naedgecount} returns the number
#' of edges for which \code{na==TRUE}. The \code{is.na} network method
#' produces a new network object whose edges correspond to the missing
#' (\code{na==TRUE}) edges of the original object, and is thus a covenient
#' method of extracting detailed missingness information on the entire network.
#' The network returned by \code{is.na} is guaranteed to have the same base
#' network attributes (directedness, loopness, hypergraphicity, multiplexity,
#' and bipartite constraint) as the original network object, but no other
#' information is copied; note too that edge IDs are \emph{not} preserved by
#' this process (although adjacency obviously is). Since the resulting object
#' is a \code{\link{network}}, standard coercion, print/summary, and other
#' methods can be applied to it in the usual fashion.
#'
#' It should be borne in mind that \dQuote{missingness} in the sense used here
#' reflects the assertion that an edge's presence or absence is unknown,
#' \emph{not} that said edge is known not to be present. Thus, the \code{na}
#' count for an empty graph is properly 0, since all edges are known to be
#' absent. Edges can be flagged as missing by setting their \code{na}
#' attribute to \code{TRUE} using \code{\link{set.edge.attribute}}, or by
#' appropriate use of the network assignment operators; see below for an
#' example of the latter.
#'
#' @param x an object of class \code{network}
#' @param \dots additional arguments, not used
#' @return \code{is.na(x)} returns a network object, and
#' \code{network.naedgecount(x)} returns the number of missing edges.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network.edgecount}},
#' \code{\link{get.network.attribute}}, \code{is.adjacent}, \code{\link{is.na}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' #Create an empty network with no missing data
#' g<-network.initialize(5)
#' g[,] #No edges present....
#' network.naedgecount(g)==0 #Edges not present are not "missing"!
#'
#' #Now, add some missing edges
#' g[1,,add.edges=TRUE]<-NA #Establish that 1's ties are unknown
#' g[,] #Observe the missing elements
#' is.na(g) #Observe in network form
#' network.naedgecount(g)==4 #These elements do count!
#' network.edgecount(is.na(g)) #Same as above
#'
#'
#' @export is.na.network
#' @export
is.na.network<-function(x){
#Create an empty network with the same properties as x
y<-network.initialize(network.size(x),directed=is.directed(x), hyper=is.hyper(x),loops=has.loops(x),multiple=is.multiplex(x), bipartite=x%n%"bipartite")
#Add the missing edges of x to y
y<-.Call(isNANetwork_R,x,y)
#Return the updated network
y
}
# Return TRUE iff x is a network.
#
#' Network Objects
#'
#' Construct, coerce to, test for and print \code{network} objects.
#'
#' \code{network} constructs a \code{network} class object from a matrix
#' representation. If the \code{matrix.type} parameter is not specified, it
#' will make a guess as to the intended \code{edgeset.constructors} function to
#' call based on the format of these input matrices. If the class of \code{x}
#' is not a matrix, network construction can be dispatched to other methods.
#' For example, If the \code{ergm} package is loaded, \code{network()} can
#' function as a shorthand for \code{as.network.numeric} with
#' \code{x} as an integer specifying the number of nodes to be created in the
#' random graph.
#'
#' If the \code{ergm} package is loaded, \code{network} can function as a
#' shorthand for \code{as.network.numeric} if \code{x} is an integer specifying
#' the number of nodes. See the help page for
#' \code{as.network.numeric} in \code{ergm} package for details.
#'
#' \code{network.copy} creates a new \code{network} object which duplicates its
#' supplied argument. (Direct assignment with \code{<-} should be used rather
#' than \code{network.copy} in most cases.)
#'
#' \code{as.network} tries to coerce its argument to a network, using the
#' \code{as.network.matrix} functions if \code{x} is a matrix. (If the argument
#' is already a network object, it is returned as-is and all other arguments
#' are ignored.)
#'
#' \code{is.network} tests whether its argument is a network (in the sense that
#' it has class \code{network}).
#'
#' \code{print.network} prints a network object in one of several possible
#' formats. It also prints the list of global attributes of the network.
#'
#' \code{summary.network} provides similar information.
#'
#' @name network
#'
#' @aliases as.network.network print.summary.network $<-.network <-.network
#' @param x for \code{network}, a matrix giving the network structure in
#' adjacency, incidence, or edgelist form; otherwise, an object of class
#' \code{network}.
#' @param vertex.attr optionally, a list containing vertex attributes.
#' @param vertex.attrnames optionally, a list containing vertex attribute
#' names.
#' @param directed logical; should edges be interpreted as directed?
#' @param hyper logical; are hyperedges allowed?
#' @param loops logical; should loops be allowed?
#' @param multiple logical; are multiplex edges allowed?
#' @param bipartite count; should the network be interpreted as bipartite? If
#' present (i.e., non-NULL, non-FALSE) it is the count of the number of actors
#' in the bipartite network. In this case, the number of nodes is equal to the
#' number of actors plus the number of events (with all actors preceeding all
#' events). The edges are then interpreted as nondirected. Values of
#' bipartite==0 are permited, indicating a bipartite network with zero-sized
#' first partition.
#' @param matrix.type one of \code{"adjacency"}, \code{"edgelist"},
#' \code{"incidence"}. See \code{\link{edgeset.constructors}} for details and
#' optional additional arguments
#' @param object an object of class \code{network}.
#' @param na.omit logical; omit summarization of missing attributes in
#' \code{network}?
#' @param mixingmatrices logical; print the mixing matrices for the discrete
#' attributes?
#' @param print.adj logical; print the network adjacency structure?
#' @param ... additional arguments.
#' @return \code{network}, \code{as.network}, and \code{print.network} all
#' return a network class object; \code{is.network} returns TRUE or FALSE.
#' @note Between versions 0.5 and 1.2, direct assignment of a network object
#' created a pointer to the original object, rather than a copy. As of version
#' 1.2, direct assignment behaves in the same manner as \code{network.copy}.
#' Direct use of the latter is thus superfluous in most situations, and is
#' discouraged.
#'
#' Many of the network package functions modify their network object arguments
#' in-place. For example, \code{set.network.attribute(net,"myVal",5)} will have
#' the same effect as \code{net<-set.network.attribute(net,"myVal",5)}.
#' Unfortunately, the current implementation of in-place assignment breaks when
#' the network argument is an element of a list or a named part of another
#' object. So \code{set.network.attribute(myListOfNetworks[[1]],"myVal",5)}
#' will silently fail to modify its network argument, likely leading to
#' incorrect output.
#' @author Carter T. Butts \email{buttsc@@uci.edu} and David Hunter
#' \email{dhunter@@stat.psu.edu}
#' @seealso \code{\link{network.initialize}}, \code{\link{attribute.methods}},
#' \code{\link{as.network.matrix}}, \code{\link{as.matrix.network}},
#' \code{\link{deletion.methods}}, \code{\link{edgeset.constructors}},
#' \code{\link{network.indicators}}, \code{\link{plot.network}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' m <- matrix(rbinom(25,1,.4),5,5)
#' diag(m) <- 0
#' g <- network(m, directed=FALSE)
#' summary(g)
#'
#' h <- network.copy(g) #Note: same as h<-g
#' summary(h)
#'
#' @export
is.network<-function(x){
inherits(x, "network")
}
# List attributes present on any edge
#
#' @rdname attribute.methods
#' @export
list.edge.attributes <- function(x, ...) UseMethod("list.edge.attributes")
#' @rdname attribute.methods
#' @export
list.edge.attributes.network <- function(x, ...) {
# no edges in the network
if (network.edgecount(x, na.omit=F) == 0) return(character(0))
#Accumulate names
allnam<-sapply(lapply(x$mel[!is.null(x$mel)],"[[","atl"),names)
#Return the sorted, unique attribute names
sort(unique(as.vector(unlist(allnam))))
}
# List network-level attributes
#
#' @rdname attribute.methods
#' @export
list.network.attributes <- function(x, ...) UseMethod("list.network.attributes")
#' @rdname attribute.methods
#' @export
list.network.attributes.network <- function(x, ...) {
#Return the attribute names
sort(names(x$gal))
}
# List attributes present on any vertex
#
#' @rdname attribute.methods
#' @export
list.vertex.attributes <- function(x, ...) UseMethod("list.vertex.attributes")
#' @rdname attribute.methods
#' @export
list.vertex.attributes.network <- function(x, ...) {
if(network.size(x)==0){
return(NULL)
}
#Accumulate names
allnam<-unlist(sapply(x$val,names))
#Return the sorted, unique attribute names
sort(unique(as.vector(allnam)))
}
# Retrieve the number of free dyads (i.e., number of non-missing) of network x.
#
#' @export
network.dyadcount<-function(x, ...) UseMethod("network.dyadcount")
#' Return the Number of (Possibly Directed) Dyads in a Network Object
#'
#' \code{network.dyadcount} returns the number of possible dyads within a
#' \code{network}, removing those flagged as missing if desired. If the
#' network is directed, directed dyads are counted accordingly.
#'
#' The return value \code{network.dyadcount} is equal to the number of dyads,
#' minus the number of \code{NULL} edges (and missing edges, if
#' \code{na.omit==TRUE}). If \code{x} is directed, the number of directed
#' dyads is returned. If the network allows loops, the number of possible
#' entries on the diagnonal is added. Allthough the function does not give an
#' error on multiplex networks or hypergraphs, the results probably don't make
#' sense.
#'
#' @name network.dyadcount
#'
#' @param x an object of class \code{network}
#' @param na.omit logical; omit edges with \code{na==TRUE} from the count?
#' @param \dots possible additional arguments, used by other implementations
#' @return The number of dyads in the network
#' @author Mark S. Handcock \email{handcock@@stat.washington.edu}, skyebend
#' @seealso \code{\link{get.network.attribute}},
#' \code{\link{network.edgecount}}, \code{\link{is.directed}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' #Create a directed network with three edges
#' m<-matrix(0,3,3)
#' m[1,2]<-1; m[2,3]<-1; m[3,1]<-1
#' g<-network(m)
#' network.dyadcount(g)==6 #Verify the directed dyad count
#' g<-network(m|t(m),directed=FALSE)
#' network.dyadcount(g)==3 #nC2 in undirected case
#'
#' @export
network.dyadcount.network<-function(x,na.omit=TRUE,...){
nodes <- network.size(x)
if(is.directed(x)){
if(is.bipartite(x)){ # directed bipartite
nactor <- get.network.attribute(x,"bipartite")
nevent <- nodes - nactor
dyads <- nactor * nevent *2
}else{ # directed unipartite
dyads <- nodes * (nodes-1)
if(has.loops(x)){
# add in the diagonal
dyads<-dyads+nodes
}
}
}else{ # undirected
if(is.bipartite(x)){ # undirected bipartite
nactor <- get.network.attribute(x,"bipartite")
nevent <- nodes - nactor
dyads <- nactor * nevent
}else{ # undirected unipartite
dyads <- nodes * (nodes-1)/2
if(has.loops(x)){
# add in the diagonal
dyads<-dyads+nodes
}
}
}
if(na.omit){
#
# Adjust for missing
#
design <- get.network.attribute(x,"design")
if(!is.null(design)){
dyads <- dyads - network.edgecount(design)
}else{
design <- get.network.attribute(x,"mClist.design")
if(!is.null(design)){
dyads <- dyads - design$nedges
}else{
dyads <- dyads - network.naedgecount(x)
}
}
}
dyads
}
#Retrieve the number of edges in network x.
#
#' @export
network.edgecount<-function(x, ...) UseMethod("network.edgecount")
#' Return the Number of Edges in a Network Object
#'
#' \code{network.edgecount} returns the number of edges within a
#' \code{network}, removing those flagged as missing if desired.
#'
#' The return value is the number of distinct edges within the network object,
#' including multiplex edges as appropriate. (So if there are 3 edges from
#' vertex i to vertex j, each contributes to the total edge count.)
#'
#' The return value \code{network.edgecount} is in the present implementation
#' related to the (required) \code{mnext} network attribute. \code{mnext} is
#' an internal legacy attribute that currently indicates the index number of
#' the next edge to be added to a network object. (Do not modify it unless you
#' enjoy unfortunate surprises.) The number of edges returned by
#' \code{network.edgecount} is equal to \code{x\%n\%"mnext"-1}, minus the number
#' of \code{NULL} edges (and missing edges, if \code{na.omit==TRUE}). Note
#' that \code{g\%n\%"mnext"-1} cannot, by itself, be counted upon to be an
#' accurate count of the number of edges! As \code{mnext} is not part of the
#' API (and is not guaranteed to remain), users and developers are urged to use
#' \code{network.edgecount} instead.
#'
#' @name network.edgecount
#'
#' @param x an object of class \code{network}
#' @param na.omit logical; omit edges with \code{na==TRUE} from the count?
#' @param \dots additional arguments, used by extending functio
#' @return The number of edges
#' @section Warning : \code{network.edgecount} uses the real state of the
#' network object to count edges, not the state it hypothetically should have.
#' Thus, if you add extra edges to a non-multiplex network, directed edges to
#' an undirected network, etc., the actual number of edges in the object will
#' be returned (and not the number you would expect if you relied only on the
#' putative number of possible edges as reflected by the
#' \link{network.indicators}). Don't create \code{network} objects with
#' contradictory attributes unless you know what you are doing.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{get.network.attribute}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' #Create a network with three edges
#' m<-matrix(0,3,3)
#' m[1,2]<-1; m[2,3]<-1; m[3,1]<-1
#' g<-network(m)
#' network.edgecount(g)==3 #Verify the edgecount
#'
#' @export
network.edgecount.network<-function(x,na.omit=TRUE,...){
.Call(networkEdgecount_R,x,na.omit)
}
#Retrieve the number of missing edges in network x
#
#' @rdname network.naedgecount
#' @export
network.naedgecount<-function(x, ...) UseMethod("network.naedgecount")
#' @export
network.naedgecount.network<-function(x, ...){
na<-get.edge.attribute(x$mel,"na")
if(is.null(na))
0
else
sum(na)
}
# Retrieve the size (i.e., number of vertices) of network x.
#
#' Return the Size of a Network
#'
#' \code{network.size} returns the order of its argument (i.e., number of
#' vertices).
#'
#' \code{network.size(x)} is equivalent to \code{get.network.attribute(x,"n")};
#' the function exists as a convenience.
#'
#' @param x an object of class \code{network}
#' @param \dots additional arguments, not used
#' @return The network size
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{get.network.attribute}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords classes graphs
#' @examples
#'
#' #Initialize a network
#' g<-network.initialize(7)
#' network.size(g)
#'
#' @export network.size
network.size<-function(x, ...) UseMethod("network.size")
#' @export
network.size.network<-function(x, ...){
get.network.attribute(x,"n")
}
# Retrieve the vertex names of network x (if present).
#
#' @rdname attribute.methods
#' @export
network.vertex.names<-function(x){
if(!is.network(x)){
stop("network.vertex.names requires an argument of class network.")
}else{
if(network.size(x)==0)
return(NULL)
vnames <- get.vertex.attribute(x,"vertex.names")
if(is.null(vnames) | all(is.na(vnames)) ){
as.character(1:network.size(x))
}else{
vnames
}
}
}
# Set the vertex names of network x
#
#' @rdname attribute.methods
#' @export
"network.vertex.names<-"<-function(x,value){
set.vertex.attribute(x,attrname="vertex.names",value=value)
}
# Permute the internal IDs (ordering) of the vertex set
#' Permute (Relabel) the Vertices Within a Network
#'
#' \code{permute.vertexIDs} permutes the vertices within a given network in the
#' specified fashion. Since this occurs internally (at the level of vertex
#' IDs), it is rarely of interest to end-users.
#'
#' \code{permute.vertexIDs} alters the internal ordering of vertices within a
#' \code{\link{network}}. For most practical applications, this should not be
#' necessary -- de facto permutation can be accomplished by altering the
#' appropriate vertex attributes. \code{permute.vertexIDs} is needed for
#' certain other routines (such as \code{\link{delete.vertices}}), where it is
#' used in various arcane and ineffable ways.
#'
#' @param x an object of class \code{\link{network}}.
#' @param vids a vector of vertex IDs, in the order to which they are to be
#' permuted.
#' @param ... additional arguments to methods.
#' @return Invisibly, a pointer to the permuted network.
#' \code{permute.vertexIDs} modifies its argument in place.
#' @author Carter T. Butts \email{buttsc@@uci.edu}
#' @seealso \code{\link{network}}
#' @references Butts, C. T. (2008). \dQuote{network: a Package for Managing
#' Relational Data in R.} \emph{Journal of Statistical Software}, 24(2).
#' \doi{10.18637/jss.v024.i02}
#' @keywords manip graphs
#' @examples
#'
#' data(flo) #Load the Florentine Families data
#' nflo<-network(flo) #Create a network object
#' n<-network.size(nflo) #Get the number of vertices
#' permute.vertexIDs(nflo,n:1) #Reverse the vertices
#' all(flo[n:1,n:1]==as.sociomatrix(nflo)) #Should be TRUE
#'
#' @export permute.vertexIDs
permute.vertexIDs <- function(x, vids, ...) UseMethod("permute.vertexIDs")
#' @rdname permute.vertexIDs
#' @export
permute.vertexIDs.network <- function(x, vids, ...) {
#First, check to see that this is a graph object
if(!is.network(x))
stop("permute.vertexIDs requires an argument of class network.\n")
#Sanity check: is this a permutation vector?
n<-network.size(x)
if((length(unique(vids))!=n)||any(range(vids)!=c(1,n)))
stop("Invalid permutation vector in permute.vertexIDs.")
if(is.bipartite(x)){ #If bipartite, enforce partitioning
bpc<-get.network.attribute(x,"bipartite")
if(any(vids[0:bpc]>bpc)||any(vids[(bpc+1):n]<=bpc))
warning("Performing a cross-mode permutation in permute.vertexIDs. I hope you know what you're doing....")
}
#Return the permuted graph
xn<-substitute(x)
x<-.Call(permuteVertexIDs_R,x,vids)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
invisible(x)
}
# Set an edge attribute for network x.
#
# set.edge.attribute<-function(x,attrname,value,e=seq_along(x$mel)){
# #Check to be sure we were called with a network
# if(!is.network(x))
# stop("set.edge.attribute requires an argument of class network.")
# #Make sure that value is appropriate, coercing if needed
# if(!is.list(value)){
# if(!is.vector(value))
# stop("Inappropriate edge value given in set.edge.attribute.\n")
# else
# value<-as.list(rep(value,length.out=length(e)))
# }else
# if(length(value)!=length(e))
# value<-rep(value,length.out=length(e))
# xn<-deparse(substitute(x))
# ev<-parent.frame()
# if(length(e)>0){
# if((min(e)<1)|(max(e)>length(x$mel)))
# stop("Illegal edge in set.edge.attribute.\n")
# #Do the deed
# x<-.Call("setEdgeAttribute_R",x,attrname,value,e, PACKAGE="network")
# if(exists(xn,envir=ev)) #If x not anonymous, set in calling env
# on.exit(assign(xn,x,pos=ev))
# invisible(x)
# }else
# invisible(x)
# }
#' @rdname attribute.methods
#' @export
set.edge.attribute <- function(x, attrname, value, e, ...) UseMethod("set.edge.attribute")
#' @rdname attribute.methods
#' @export
set.edge.attribute.network <- function(x, attrname, value, e=seq_along(x$mel), ...) {
# determine if we have to do anything at all
if(length(e)>0){
if((min(e)<1)|(max(e)>length(x$mel))){
stop("Illegal edge in set.edge.attribute.\n")
}
xn<-substitute(x)
# determine if we will be setting single or multiple values
if(length(attrname)==1){
#Make sure that value is appropriate, coercing if needed
if(!is.list(value)){
if(!is.vector(value)){
stop("Inappropriate edge value given in set.edge.attribute.\n")
} else {
value<-as.list(rep(value,length.out=length(e)))
}
} else {
if(length(value)!=length(e)) {
value<-rep(value,length.out=length(e))
}
}
#Do the deed, call the set single value version
x<-.Call(setEdgeAttribute_R,x,attrname,value,e)
} else { # we will be setting multiple values
if (length(attrname)!=length(value)){
stop("the 'value' attribute must have an element corresponding to each attribute name in 'attrname' in set.edge.attribute")
}
#Make sure that value is appropriate, coercing if needed
if(!is.list(value)){
if(!is.vector(value)){
stop("Inappropriate edge value given in set.edge.attribute.\n")
} else { # value must be a vector
# replicate each element of value e times if needed
value<-lapply(1:length(value),function(n){
if (length(value[n])length(x$mel)))
stop("Illegal edge in set.edge.value.\n")
#Make sure that value is appropriate, coercing if needed
n<-network.size(x)
if(!is.matrix(value)){
if(is.vector(value))
value<-matrix(rep(value,length.out=n*n),n,n)
else
value<-matrix(value,n,n)
} else if (min(dim(value)) < n) {
stop("set.edge.value requires a matrix whose dimension is equal to or larger than the network size")
}
#Ensure that the attribute name is legit
attrname<-as.character(attrname)
if(length(attrname)==0)
stop("Attribute name required in set.edge.value.network.")
#Do the deed
xn<-substitute(x)
x<-.Call(setEdgeValue_R,x,attrname,value,e)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
invisible(x)
}
# Set a network-level attribute for network x.
#
#' @rdname attribute.methods
#' @export
set.network.attribute <- function(x, attrname, value, ...) UseMethod("set.network.attribute")
#' @rdname attribute.methods
#' @export
set.network.attribute.network <- function(x, attrname, value, ...) {
#Make sure the values are consistent
if(length(attrname)==1){
value<-list(value)
}else{
if(is.list(value)){
value<-rep(value,length.out=length(attrname))
}else if(is.vector(value)){
value<-as.list(rep(value,length.out=length(attrname)))
}else
stop("Non-replicable value with multiple attribute names in set.network.attribute.\n")
}
#Do the deed
xn<-substitute(x)
x<-.Call(setNetworkAttribute_R,x,attrname,value)
if(.validLHS(xn,parent.frame())){ #If x not anonymous, set in calling env
on.exit(eval.parent(call('<-',xn,x)))
}
invisible(x)
}
# Set a vertex attribute for network x.
# This version has been removed so we can test one that can set multiple values at once
# set.vertex.attribute<-function(x,attrname,value,v=seq_len(network.size(x))){
# #Check to be sure we were called with a network
# if(!is.network(x))
# stop("set.vertex.attribute requires an argument of class network.")
# #Perform some sanity checks
# if(any((v>network.size(x))|(v<1)))
# stop("Vertex ID does not correspond to actual vertex in set.vertex.attribute.\n")
# #Make sure that value is appropriate, coercing if needed
# if(!is.list(value)){
# if(!is.vector(value))
# stop("Inappropriate value given in set.vertex.attribute.\n")
# else
# value<-as.list(rep(value,length.out=length(v)))
# }else
# if(length(value)!=length(v))
# value<-rep(value,length.out=length(v))
# #Do the deed
# xn<-deparse(substitute(x))
# ev<-parent.frame()
# x<-.Call("setVertexAttribute_R",x,attrname,value,v, PACKAGE="network")
# if(exists(xn,envir=ev)) #If x not anonymous, set in calling env
# on.exit(assign(xn,x,pos=ev))
# invisible(x)
# }
# valid.eids returns a list of non-null edge ids for a given network
#' Get the ids of all the edges that are valid in a network
#'
#' Returns a vector of valid edge ids (corresponding to non-NULL edges) for a
#' network that may have some deleted edges.
#'
#' The edge ids used in the network package are positional indices on the
#' internal "mel" list. When edges are removed using \code{\link{delete.edges}}
#' \code{NULL} elements are left on the list. The function \code{valid.eids}
#' returns the ids of all the valid (non-null) edge ids for its \code{network}
#' argument.
#'
#' @param x a network object, possibly with some deleted edges.
#' @param ... additional arguments to methods.
#' @return a vector of integer ids corresponding to the non-null edges in x
#' @note If it is known that x has no deleted edges, \code{seq_along(x$mel)} is
#' a faster way to generate the sequence of possible edge ids.
#' @author skyebend
#' @seealso See also \code{\link{delete.edges}}
#' @examples
#'
#' net<-network.initialize(100)
#' add.edges(net,1:99,2:100)
#' delete.edges(net,eid=5:95)
#' # get the ids of the non-deleted edges
#' valid.eids(net)
#'
#' @export
valid.eids <- function(x, ...) UseMethod("valid.eids")
#' @rdname valid.eids
#' @export
valid.eids.network <- function(x, ...) {
# get the ids of all the non-null elements on the edgelist of x
return(which(!sapply(x$mel,is.null)))
}
#' @rdname attribute.methods
#' @export
set.vertex.attribute <- function(x, attrname, value, v = seq_len(network.size(x)), ...) UseMethod("set.vertex.attribute")
#' @rdname attribute.methods
#' @export
set.vertex.attribute.network <- function(x, attrname, value, v = seq_len(network.size(x)), ...) {
#Perform some sanity checks
if(any((v>network.size(x))|(v<1)))
stop("Vertex ID does not correspond to actual vertex in set.vertex.attribute.\n")
xn<-substitute(x)
#Make sure that value is appropriate, coercing if needed
if (length(attrname)==1){ # if we are only setting a single attribute use old version
if(!is.list(value)){
if(!is.vector(value)){
stop("Inappropriate value given in set.vertex.attribute.\n")
} else {
value<-as.list(rep(value,length.out=length(v)))
}
} else {
if(length(value)!=length(v)){
value<-rep(value,length.out=length(v))
}
}
# call older singular value version
x<-.Call(setVertexAttribute_R,x,attrname,value,v)
} else { # setting multiple values
if (length(value)!=length(attrname)){
stop("the 'value' attribute must have an element corresponding to each attribute name in 'attrnames' in set.vertex.attribute")
}
if(!is.list(value)){
if(!is.vector(value)){
stop("Inappropriate value given in set.vertex.attribute.\n")
} else { # value is a vector
# replicate each element of value v times if needed
value<-lapply(1:length(value),function(n){
if (length(value[n])