# This generates PA graphs. Output is sent to file, to later be used by GraphViz to draw the structure.

runPA  <- 
function(N=100,m=2) {

    # outLink[i] is the parent of i
    outLink  <- matrix(0,N,m)

    # numlinks[i] is the number of total-links (in and out) for node i
    numLinks <- numeric(N)+m

    # Iterate the construction to build up the network in serial. (Should be possible to get same statistics from a parallel version)
    for(i in 2:N)
    {
        p <- sample(c(1:(i-1)),size=min(m,(i-1)),replace=FALSE,prob=numLinks[1:(i-1)])
#        print(p)

		if ((i-1)<m) p[i:m] <- i
        outLink[i,] <- p
        numLinks[p] <- numLinks[p]+1
    }


    dev.set(2)
    plot(c(1:N),numLinks,xlab="arrival time")

    dev.set(3)
    hist(numLinks[numLinks!=0],breaks=c(-1:max(numLinks)),xlab="In-degree,k",main="",freq=F)
    
#    plotsimple(N, m, outLink)
    plotdegree(N, m, outLink, numLinks)

    return(invisible(list(outLink=outLink, numLinks=numLinks)))
}


plotsimple <- function(N=100, m=1, outLink)
{
	# output to file: may want to add colors to show the time history.
    zz <- file("exPA.dot","w")
    cat("graph G {","node [shape=circle,color=orange,style=filled,label=\"\",width=0.15,height=0.15]",file=zz,sep="\n")
    for(i in 2:N)
    	for(j in 1:m)
    	{
        	cat(i,"--",outLink[i,j],"node [color=blue] ;",file=zz)
        	cat("\n",file=zz)
    	}
    cat("}","\n",file=zz)
    close(zz)
}

plotdegree <- function(N=100, m=1, outLink, numLinks)
{
	# coloring high degree vertices red.
    zz <- file("exPA-degree.dot","w")
    cat("graph G {","node [shape=circle,color=orange,style=filled,label=\"\",width=0.15,height=0.15]",file=zz,sep="\n")
    for(i in 2:N)
    	for(j in 1:m)
    	{
    		if(numLinks[i] > N/10)
    		{
    			#cat("node [color=red] ", file=zz)
        		cat(i,"--",outLink[i,j],"node [color=red] ;",file=zz)
        		cat("\n",file=zz)
        	}
        	else
        	{
        		cat(i,"--",outLink[i,j],"node [color=blue] ;",file=zz)
        		cat("\n",file=zz)
        	}
    	}
    cat("}","\n",file=zz)
    close(zz)
}
