Пример #1
0
def narrowGraphTo10MainCharacters(G, speakers):

    mainCharacters = []
    speakersDictionary = {}


   #Putting all the speakers in a dictionary
    for speaker in speakers:
        if speaker in speakersDictionary:
            speakersDictionary[speaker] = speakersDictionary[speaker] + 1
        else:
            speakersDictionary[speaker] = 1

    #sorting in order to get the main characters
    sortedSpeakers = sorted(speakersDictionary.items(), key=lambda kv: kv[1],reverse=True)
    mainCharactersNumber=10

    for i in range(mainCharactersNumber):
        mainCharacters.append(sortedSpeakers[i][0])

    print()
    G3 = nx.Graph()
    for u, v, d in G.edges(data=True):
        if (u in mainCharacters and v in mainCharacters):
            G3.add_edge(u, v, weight=d['weight'])
    return G3
Пример #2
0
def voronoi2(G,movie,isDirected):
    global color_map
    if isDirected==0:
        G2 = nx.Graph()
    else:
        G2 = nx.DiGraph()

    #Converting frequencies to distances
    for u, v, d in G.edges(data=True):
        G2.add_edge(u, v, weight=(1 / d['weight']))

    # Choosing 2 Ankers and as a result -> Dividing the Graph to 2 partitions
    if movie == 'Captain America - Civil War':
        anker1 = 'STEVE ROGERS'
        anker2 = ['TONY STARK', 'NATASHA ROMANOFF']
    else:
        anker1 = 'WAYNE'
        anker2 = ['BANE', 'SELINA']

    color_map = []
    for v in G2:
        # print('v=' +str(v)," to anker:",anker1,'|',spw(G2, v, anker1)," to anker:",anker2,'|',spw(G2, v, anker2))
        if (v == anker1):
            color_map.append('blue')
        elif (v in anker2):
            color_map.append('red')

        elif (spw(G2, v, anker1) < spw(G2, v, anker2[0]) and spw(G2, v, anker1) < spw(G2, v, anker2[1])):
            color_map.append('blue')
        else:
            color_map.append('red')
    return G2
Пример #3
0
    def __init__(self, dimension: int, graph: nx.Graph = None, id: str = ''):
        """
    Initializes the NetworkX graph representation of
    intersecting and overlapping Regions.

    Args:
      dimension:
        The number of dimensions in all of the Regions
        within the graph; the dimensionality of all Regions.
      graph:
        The internal NetworkX graph representation or
        implementation for a graph of intersecting or
        overlapping Regions.
      id:
        The unique identifier for this RIGraph.
        Randonly generated with UUID v4, if not provided.
    """
        assert isinstance(dimension, int) and dimension > 0
        assert graph == None or isinstance(graph, nx.Graph)

        self.dimension = dimension
        self.id = id = id if len(id) > 0 else str(uuid4())

        if graph == None:
            self.G = nx.Graph(id=id, dimension=dimension)
        else:
            self.G = G = graph
            self.dimension = G.graph.setdefault('dimension', dimension)
            self.id = G.graph.setdefault('id', id)
Пример #4
0
  def __init__(self, dimension: int, graph: nx.Graph = None, id: str = ''):
    """
    Initializes the NetworkX graph representation of
    intersecting and overlapping Regions.

    Args:
      dimension:
        The number of dimensions in all of the Regions
        within the graph; the dimensionality of all Regions.
      graph:
        The internal NetworkX graph representation or
        implementation for a graph of intersecting or
        overlapping Regions.
      id:
        The unique identifier for this RIGraph.
        Randonly generated with UUID v4, if not provided.
    """
    assert dimension > 0

    # TODO maybe add 'assert all(isinstance( self.G.nodes(... , Region)))' ?

    self.dimension = dimension
    self.id = id if len(id) > 0 else str(uuid4())

    self.G = graph if graph is not None else nx.Graph()
Пример #5
0
def buildGraphFromListUndirectedUnweighted(speakers):
    edges = []
    G = nx.Graph()
    for i in range(0, len(speakers) - 2):
        if(speakers[i]!=speakers[i+1]):
            G.add_edge(speakers[i], speakers[i + 1], weight=1)

    return G
Пример #6
0
def buildGraphFromListUndirectedWeighted(speakers):
    edges = []
    G = nx.Graph()
    for i in range(0, len(speakers) - 2):
        if(speakers[i]!=speakers[i+1]):
            if (G.has_edge(speakers[i], speakers[i + 1])):
                G[speakers[i]][speakers[i + 1]]['weight'] += 1

            else:
                G.add_edge(speakers[i], speakers[i + 1], weight=1)

    return G
Пример #7
0
def addGraph(fname, toOutput = 2):
	
	G = nx.Graph()
	with open(fname, "r") as f1:
		for line in f1:
			tmp = line.strip().split(" ")
			G.add_edge(tmp[0], tmp[1])
	fout = open("file"+str(file_id)+"_out4", "w")
	for g in nx.connected_components(G):
		if toOutput!=2:
			print g 
		else:
			fout.write(g.__str__()+"\n")
	fout.close()		
	return G
    def data_clust(self, origin, nodes, links):
        #print("links",links)
        edge_list = [tuple(elem.values()) for elem in links]

        g = nx.Graph()
        g.add_edges_from(edge_list)

        #clust_coefficients = nx.clustering(g)
        partition = community.best_partition(g)

        clustered_nodes = nodes

        part_set = set()
        number_of_clusters = 0
        for i, node in enumerate(clustered_nodes):
            node['cluster'] = partition[i]
            if partition[i] not in part_set:
                part_set.add(partition[i])
                number_of_clusters += 1

        return clustered_nodes, links, number_of_clusters
Пример #9
0
def grafica():
    G = nx.Graph()
    G.add_edges_from([(1, 2), (1, 3)])
Пример #10
0
def votingActualAlgo(G, firstAnker, secondAnker, movieName):
    #(i,j) are vertixes we anchored
    #drawGraph(G,0)
    directedG = nx.Graph().to_directed()# from ex1 we already have directed graph
    sum = 0
    allEdgesWeight = {}

    #For each v we sum all the edges wehight
    for v in G:
        vNeighbors = neighbors(G, v)
        for u in vNeighbors:
            sum += G[v][u]['weight']
        allEdgesWeight[v] = sum
        sum = 0
    #print('list of main characters')
    #print(allEdgesWeight.keys())

    m = nx.convert_matrix.to_numpy_matrix(G)
    #print('The graph converted to matrix')
    #print(m)


    #divide each directed egde in the sum of edges weight from vertex V  (- normelaize the matrix)
    for k in range(m.shape[0]):
        #print(m[k].sum())
        m[k]/=m[k].sum()

    #print('Normalized M - directed(!) - weight of the edge is divided by the sum of the edge from this vertex')
    #print(m)
    names = list(allEdgesWeight.keys())
    i= names.index(firstAnker)
    j=names.index(secondAnker)


    #print('\n\n\n')
    #Setting Ankers  - "Eater Vertex"
    m[i]=0
    m[i,i]=1
    m[j] = 0
    m[j,j] = 1

    #print('VOTING  - MATRIX WITH ANKORS!\n\n', m)


    #print('Multipyng\n\n')
    for k in range (0,4):
        m=np.dot(m,m)
        #print ('Mult -',k,'- :\n',m)
    list_for_return = list()
    ank1 = list()#anckor 1 full list with 0's
    ank2 = list()#anckor 2 full list with 0's
    ank1_list = list() # list without 0's
    ank2_list = list() # list without 0's
    for k in range (0,10):
        if m[k, i] >= m[k, j]:
            ank1.append(m[k, i])
            ank1_list.append(m[k, i])
            ank2.append(0)
        else:
            ank2.append(m[k, j])
            ank2_list.append(m[k, j])
            ank1.append(0)
    print('list of groups for the movie',movieName)
    names=list(allEdgesWeight.keys())
    groupI1=[]
    groupJ2=[]
    for k in range(len(names)):
        if ank1[k]>ank2[k]:
            groupI1.append(names[k])
        else:
            groupJ2.append(names[k])
    print(names[i],'=',groupI1,' | ',names[j],'=',groupJ2) #1~i 2~J

    # print(ank1)
    # print(ank2)
    print('\n')

    #
    # for u, v, d in G.edges(data=True):
    #     directedG.add_edge(u, v, weight=d['weight'])
    #     directedG.add_edge(v, u, weight=d['weight'])
    #
    # for v in directedG:
    #     vSize = allEdgesWeight[v]
    #     for u in directedG:
    #         if(directedG.has_edge(v,u)):
    #             directedG[v][u]['weight'] = directedG[v][u]['weight']/vSize
    #
    list_for_return.append(directedG)
    list_for_return.append(ank1_list)
    list_for_return.append(ank2_list)
    list_for_return.append(ank1)
    list_for_return.append(ank2)
    return list_for_return
Пример #11
0
#!/usr/bin/env python
# coding: utf-8

from networkx import networkx as nx
from itertools import combinations
from collections import defaultdict
import matplotlib.pyplot as plt
import scipy
import os
import json
import database_handler
#from data_reader import get_stackoverflow_data

BASE_PATH = 'data'

G = nx.Graph()

#xml_dict = get_stackoverflow_data(f"{BASE_PATH}/bitcoin")

# example on how to use the xml
#for row in xml_dict['Users'][:2]:
#    # row objects have tag & attrib
#    print(row.tag, row.attrib)

# Extraction of features into individual json files for each directory
database_handler.prepare_json_databases(BASE_PATH)

G.add_nodes_from(os.listdir(BASE_PATH))

edges = []
# Each directory represents a site