Python Forum
Advanced Algorithms and Computational Models
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Advanced Algorithms and Computational Models
#1
import random
import math
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import matplotlib

  
 
class graph:
    
    def vertex_count(graph): 
        vertex = []
        for x in graph.keys():
            vertex.append(x)
        return len(vertex)

    def vertices(graph): 
        vertices = []
        for x in graph.keys():
            vertices.append(x)
        return list(graph.keys())

    def edges_count(graph):
        edges = []
        count = 0
        for k,v in graph.items():
            if k not in edges:
                edges.append(k)
        for i in v:
            if i not in edges:
                count += 1
        return count

    def edges(graph):
        edges = []
        for k,v in graph.items():
            for i in v:
                edges.append((k,i))
        return edges
    
    def get_vertex(x,graph):
        for k in graph.key():
            if k[0]==x:
                return x
            return 'None'
        


    def get_edge(x,y,graph):
        for k,v in graph.items():
            if x == k and y in v:
                return x,y
        return "None"

    def degree(x,graph):
        for k,v in graph.items():
            if x == k:
                return len(v)

    def incident_edges(x, graph):
        for k,v in graph.items():
            if x == k:
                return graph[v]

    def insert_vertex(x,graph):
        if x not in graph.keys():
            graph[x] = {}
        return graph

    def insert_edge(u,v,graph):
        if u in graph.keys():
            if v not in graph[u].values():
                graph[u]=[v]
                for q in graph[u]:
                    if q==v:
                        graph[v]=[u]
            return graph
        else:
            return 'does not exist'

    def remove_vertex(v,graph):
        del graph[v]
        return graph

    def remove_edge(u,v,graph):
        test = 0
        if u in graph.keys():
            for q in graph[u]:
                if q==v:
                    graph[u].remove(q)
        return graph
     
    def binomial_degree_distribution( p, k,graph):
        for N in graph.items():
       
            numerator = math.factorial(N-1)
            denominator = math.factorial(k)*math.factorial((N-1-k))
            x = numerator/denominator
            pk = x*(pow(p, k))*(pow(1-p, N-1-k))
        return pk
   
    
    def degree_distribution(graph,initial_nodes):
        dd=[]
        for i in range (initial_nodes):
            dd[i]=0
            for j in graph:
                x=len(graph[j])
                dd[x]=dd[x]+1
                
        degrees=[]
        for i in dd:
            degree[i]=(dd[i]/inital_nodes)
        return degrees
    
    def create_network():
        g = graph(False)
        
   
        for i in range (4):
            g.insert_vetrex((i,'r'))
            g.insert_vertex((4+i,'b'))
        return g

     
  
  
    
def main():
    matplotlib.rcParams.update({'figure.autolayout': True})
    N=int(input('number of  nodes in the graph: '))
    m = random.randint(0,4)
    k=0
    kk=0
    p_list=list()
    r_list =  []  
    for i in range(4):
        p = float(input("kindky enter a value for p: "))
        p_list.append(p)

    for i in range(4):
        r = float(input("kindly enter a value for r: "))
        r_list.append(r)

    for p in p_list:
        j =0
        q = 1-p
        
        for r in r_list:
            if k>0 and j>0:
                break
  
   

    

       
    
        g=create_network()
        for y in range (4):
            red_nodes=[y,'r']
        for y in range(4,8):
            blue_nodes=[y,'b']
        
        for u in g.vertices():
            for v in g.vertices():
                r_u=random_uniform(0.0,1.0)
                if ((u!=v) and u[1]==v[1]):
                    if (r_u < p or p==1.0):
                        g.insert_edge(u,v)
                    else:
                        if ((r_u > p or q==1.0) and (u!=v)):
                                g.insert_edge(u,v)
                        
          
            for i in range(8,N):
                
                red_size = list()
                blue_size = list()
                degrees = list()
                k_nodes_of_same_color = int(round(p*m))
                k_nodes_of_different_color = m-k_nodes_of_same_color
            
             
            for vertex in g.vertices():
                degree = g.degree(vertex)
                degrees.append(degree)
        
            for h in range(g.vertex_count()):
                t = g.get_vertex(h)
                if t[1] == 'r':
                    red_size.append(degrees[h])
                    total_of_red_degrees += degrees[h]
                else:
                    blue_size.append(degrees[h])
                    total_of_blue_degrees += degrees[h]
                    
                    sum_r_s = sum( red_size)
                    sum_b_s = sum( blue_size)
                    for x in red_nodes[0]:
                        vec_r = x[0] 
                    for x in blue_nodes[0]:
                        vec_b = x[0]          
                    for f in red_size ():
                        P_r = [f/ sum_r_s]
                    for f in blue_size ():
                        P_b = [f/ sum_b_s]          
                                 
                
                    rand_uf=random_uniform(0.0,1.0)
                    the_preferential_attachement_of_red_nodes=[]
                    the_preferential_attachement_of_blue_nodes=[]
                    generated_node = ()
                    if ((rand_uf >=r) and len(red_nodes)<int(round(N*r))):
                        generated_node = (i,'r')
                        g.insert_vertex(generated_node)
                        
                        
                        choices=np.random.choice(vec_r,size=k_nodes_of_different_color,replace=False, p=P_r)
                       
                            
                        the_preferential_attachement_of_red_nodes=[x for x in red_nodes if x[0] in choices]
                        
                        choices=np.random.choice(vec_b,size=k_nodes_of_different_color,replace=False, p=P_b)
                        
                        the_preferential_attachement_of_blue_nodes=[x for x in blue_nodes if x[0] in choices]
                        red_nodes.append(generated_node)
                 
                    elif ((rand_uf<r) and N-len(red_nodes)>N-int(round(N*r))):
                        generated_node = (i,'b')
                        g.insert_vertex(generated_node)
                        choices = np.random.choice(vec_r,size=k_nodes_of_different_color,replace=False, p=P_r)
                       
                        the_preferential_attachement_of_red_nodes=[x for x in red_nodes if x[0] in choices]
                        choices = np.random.choice(vec_b,size=k_nodes_of_same_color,replace=False, p=P_b)
                        
                        
                        
                        
                        the_preferential_attachement_of_blue_nodes=[x for x in blue_nodes if x[0] in choices]
                        blue_nodes.append(generated_node)
                     
                        
                        for n in the_preferential_attachement_of_red_nodes:
                            g.insert_edge(generated_node,n)
                        for n in bthe_preferential_attachement_of_blue_nodes:
                            g.insert_edge(generated_node,n)
                            
                            
                            
                            
                            
                            
                            
                            
                            degs_count = g.degree_distribution()
            x, y = zip(*degs_count.items())
            degs = x
            counts = y
            plt.subplot(int(str(24)+str(kk+1)))
            plt.bar(degs, counts,width=.5)
            plt.xlabel('degrees')
            plt.ylabel('counts')
            plt.title('r = '+str(r)+', p = '+str(p))
            kk+=1
            j+=1
        k+=1

    plt.show()

main()
Reply
#2
Consider a network of N red and N blue nodes. The probability that there is a link between nodes of
identical color is p and the probability that there is a link between nodes of different color is q (p+q = 1).
If p > q, the nodes exhibit a tendency to connect to nodes of the same color. For q = 0 the network has
at least two components, containing nodes with the same color.
The student is requested to implement a code which simulates a modified Barabasi-Albert conform to
the following workflow:
1. Create a seed network composed of 4 blue nodes and 4 red nodes
2. At each time step add a new node. Its color is randomly selected depending on a parameter r
(0 ≤ r ≤ 1): if r = 0 all nodes will be blue, if r = 1 all nodes will be red, intermediate values
will determine different percentages. For example, if r = 0.1 only 10% of nodes will be red. Hint:
create a sequence of N − 8 colors (red or blue) coherent with the chosen value of r
3. Depending on the value of p, and consequently of q, each new node will be connected to some nodes
of the same color and some others of the other color
4. When the network is complete, store the degree distribution
5. Plot the degree distributions corresponding to 4 different values of p for a fixed value of r
6. Plot the degree distributions corresponding to 4 different values of r for a fixed value of p
To do
1. Use Python 3
2. Use matplotlib for the plots
3. Choose a sufficiently large value of N (no toy networks)
4. N, p, r must be input parameters of the program
Error:
---> i have done the code but it show me this error NameError Traceback (most recent call last)
if i have to upload the code tell me please
Reply
#3
You have uploaded your code and I fixed the BBcode tags for you. Then you started new thread, that I merged into the first one.
In the second thread there is no traceback, just the NameError. Post the full traceback in error tags.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
You call create_network() from main. Your create_network() method is within the class graph. Therefore you need in instance of graph in order to call the method (or call graph.create_network()).

Within your class graph you have methods that return graph. This is going to get really messy really fast. For example, within your create_network() method, you return graph(False). This will be your next error, as graph() does not take an argument.
Reply
#5
not to mention that all your methods will get instance as first argument, but they don't expect it. they are written as staticmethods but not declared as such (e.g. with @staticmethod decorator). And I really don't think you intend them to be static methods
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue with Dynamical Models course cilyt 1 2,626 Sep-13-2020, 09:40 AM
Last Post: ibreeden
  Sorting algorithms Ayman_2001 1 1,880 Jul-01-2020, 12:04 PM
Last Post: ndc85430
  Computational linguistic program - Need some help Antoine 4 2,448 May-01-2019, 07:43 PM
Last Post: Antoine
  Advanced sorting of a built-in list Whisper40 6 4,146 Jan-11-2018, 07:27 PM
Last Post: Whisper40
  Tricky estimating three models and creating a table: regression HellinPython 1 2,796 Oct-18-2017, 02:46 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020