import numpy as np
import networkx as nx
import matplotlib.pyplot as plt


#The Barabasi-Albert Model of Preferential Attachment

n = 100
c = 10

adjList = []
#edgeList is still mostly just for drawing with networkx
edgeList = []

#Create initial complete network of c vertices
for i in range(c):
    tempList = []
    for j in range(c):
        #make sure you dont create an edge from i to i
        if i != j:
            tempList.append(j)
        #add (i,j) to the edgeList as long as i<j. 
        #The ensures we dont double count edges
        if j>i:
            edgeList.append((i,j))
    adjList.append(tempList)
    
#add vertices with c edges until size=n
while len(adjList)<n:
    #i is the index of the vertex we are adding
    i = len(adjList)
    #we want to sample proportional to degree so we need a degree list
    degList = [len(x) for x in adjList]
    totalDeg = sum(degList)
    #Now we choose who i will attach to
    #This function samples from [0,1,...,i-1] proportional to degree. 
    #replace=False ensures we sample WITHOUT replacement
    tempList = np.random.choice(i, c, replace=False, p=[x/totalDeg for x in degList])
    #np.random.choice returns a numpy array. 
    #np.ndarray.tolist turns it back into a normal list to put in adjList
    adjList.append(np.ndarray.tolist(tempList))
    for j in tempList:
        adjList[j].append(i)
        edgeList.append((i,j))
        
#This gives us the final degree list and plots the values in a histogram
degList = [len(x) for x in adjList]
plt.subplots()
plt.hist(degList)
       
# All of this is for drawing the picture of the network
G = nx.from_edgelist(edgeList)
# pos is the position of the vertices in the plane
pos = nx.spring_layout(G)
plt.subplots()
nx.draw(G,pos)


#This will be explained on 10/22
#What this does is show that the degree distribution is linear in a log-log plot
# maxDeg = max(degList)
# probs = []
# for deg in range(maxDeg+1):
#     probs.append(degList.count(deg)/n)
# plt.subplots()
# plt.plot(list(range(maxDeg+1)),probs)
# plt.xscale('log')
# plt.yscale('log')

    
    