Пример #1
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
Пример #2
0
def narrowDiGraphTo10MainCharacters(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.DiGraph()
    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
Пример #3
0
def buildGraphFromListDirectedUnweighted(speakers):
    edges = []
    G = nx.DiGraph()
    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
Пример #4
0
def level2Nodes(filename):
	
	DG = nx.DiGraph()
	with open(filename, "r") as f2:
		for line in f2:
			di = eval(line)
			TG = json_graph.tree_graph(di)
			DG.add_edges_from(TG.edges())

	return DG
Пример #5
0
 def best(self):
     d = nx.DiGraph()
     d.add_nodes_from([expert.name for expert in self.expert_list])
     for exp in self.expert_list:
         for expert in self.expert_list:
             if exp.reinforce_dominate(expert):
                 d.add_edge(exp.name, expert.name)
     return [
         self.find_by_name(elem[0]) for elem in d.out_degree
         if max(d.out_degree, key=lambda x: x[1])[1] == elem[1]
     ]
Пример #6
0
def buildGraphFromListDirectedWeighted(speakers):
    edges = []
    G = nx.DiGraph()
    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 combineEverything(fname, allNodes, toOutput = 2):
	DG = level2Nodes(fname)
	DGN_s1Nodes = DG.nodes()
	tmpDict = level1Nodes()
	for n in DGN_s1Nodes: #ex: Root1: {science:{[psychology, linguistics]}}
		if n in tmpDict:
			#print n, type(tmpDict[n]) == list
		
			for v in tmpDict[n]:
				DG.add_edge(n, v)
			del	tmpDict[n]

	###print nodes have hierachy but not grouped
	"""
	for k, vd in tmpDict.iteritems():
		if len(vd) > 1:
			for v in vd:
				DG.add_edge(k , v)
			DG.add_edge("ROOT0", k)
	"""
	###

	DGN_s2Nodes = DG.nodes()
	isolatedNodes = allNodes - set(DGN_s2Nodes)
	for d in DGN_s2Nodes:
		if d.startswith("Root") or d.startswith("L"):
			#print d, DG.neighbors(d)
			DG.add_edge("ROOT0", d)
			#print DG.neighbors("ROOT0")

	DG2 = nx.DiGraph()
	for sn in isolatedNodes:
		DG2.add_edge("ROOT0", sn)
		#if sn in DG.nodes():
		#	DG.remove_node(sn)
	if toOutput == 2:
		try:
			tmpout1 = str(json_graph.tree_data(DG, "ROOT0")).replace("'id'", "'name'")
			out1 = "var data1 ="+tmpout1+";"
			tmpout2 = str(json_graph.tree_data(DG2, "ROOT0")).replace("'id'", "'name'")
			out2 = "var data2 ="+tmpout2+";"
			fout = open("file"+str(file_id)+"_final.js", "w")
			fout.write(out1+"\n"+out2)
			fout.close()
		except:
			nx.write(DG, "out.gml")	
	else: 
		try:
			print json_graph.tree_data(DG, "ROOT0")
			print json_graph.tree_data(DG2, "ROOT0")
		except:
			nx.write_gml(DG,"out.gml")
Пример #8
0
def graph_problem():
    g = nx.DiGraph()
    g.add_edge(0, 1, weight=-7)
    g.add_edge(1, 2, weight=-7)
    g.add_edge(2, 3, weight=-7)
    g.add_edge(3, 0, weight=-9)
    g.add_edge(1, 0, weight=-3)
    g.add_edge(2, 1, weight=-3)
    g.add_edge(3, 2, weight=-3)
    g.add_edge(0, 3, weight=-1)
    g.add_edge(0, 2, weight=-4)
    g.add_edge(1, 3, weight=-4)
    g.add_edge(2, 0, weight=-6)
    g.add_edge(3, 1, weight=-6)
    return g
Пример #9
0
def graph_problem():
    g = nx.DiGraph()
    g.add_edge(0, 1, weight=7)
    g.add_edge(1, 2, weight=7)
    g.add_edge(2, 3, weight=7)
    g.add_edge(3, 0, weight=9)
    g.add_edge(1, 0, weight=3)
    g.add_edge(2, 1, weight=3)
    g.add_edge(3, 2, weight=3)
    g.add_edge(0, 3, weight=1)
    g.add_edge(0, 2, weight=4)
    g.add_edge(1, 3, weight=4)
    g.add_edge(2, 0, weight=6)
    g.add_edge(3, 1, weight=6)
    return g
Пример #10
0
 def displayGraph(self):
     G = nx.DiGraph()
     for key, value in self.time_exchange_data_job_dict.items():
         if value.time != 0:
             if not G.has_node(value.from_storage_id):
                 G.add_node(value.from_storage_id)
             if not G.has_node(value.to_storage_id):
                 G.add_node(value.to_storage_id)
             G.add_edge(value.from_storage_id, value.to_storage_id, weight=value.time)
     pos = nx.spring_layout(G, scale=2)
     nx.draw(G, pos,  with_labels=True)
     labels = nx.get_edge_attributes(G, 'weight')
     nx.draw_networkx_edge_labels(G, pos , edge_labels= labels)
     plt.savefig('Graph'+key+'.png', format="PNG")
     plt.show()
Пример #11
0
def checkHypernymWNBeta(itemArr, rootid, fp = None, debug = False):
	global synonym
	itemArr = map(checkSynonym, itemArr)
	tmpItemArr = itemArr
	allHypoHyper = set()
	hypo = {}
	iid = 0
	for i in itemArr[0:-1]:
		iid += 1
		for j in itemArr[iid:]:
			#print i, j
			h = isRelated(i, j)
			if h != None and (h in itemArr):
				allHypoHyper.add(h)
				hypo.setdefault(h, [])
				if h != i:
					hypo[h].append(i)
				if h != j:
					hypo[h].append(j)
	DG = nx.DiGraph()
	in_edge = set()

	#kk = hypo.keys()
	for k, v in hypo.iteritems():
		#print k, set(v)
		for vs in list(set(v)):
			if vs not in in_edge:
				DG.add_edge(k, vs)
				in_edge.add(vs)
			if vs in tmpItemArr:
				tmpItemArr.remove(vs)

	### from here, the code merge some nodes by their common hypernym
	hiddenNodes = hiddenHypo(tmpItemArr)
	dup = set()
	hid = 1
	middleNodes = set()
	for k, v in sorted(hiddenNodes.iteritems(), key=lambda k:len(k[1]), reverse=True):
		if debug:
			print "K", k, v, tmpItemArr
		#continue
		if v == set(tmpItemArr):
			break

		vt = v - dup
		#dup.update(v)
		if len(vt) <= 1:
			#dup.update(vt)
			continue
		if k in itemArr:
			#print "k = ", k, vt
			#dup.discard(k)
			vt.discard(k)
			for vs in vt:
				DG.add_edge(k, vs)
		else:
			for vs in vt:
				##DG.add_edge(str(rootid)+"_Hidden"+str(hid), vs)
				DG.add_edge(str(rootid)+"_M_"+k, vs)
				
			##hid += 1
			middleNodes.add(str(rootid)+"_M_"+k)

		dup.update(vt)
	###ends here;
	if len(tmpItemArr) == 1:
		RootName = tmpItemArr[0]
	else:
		"""
		@quickHyper(tmpItemArr) => find a common hypernym of input['head', 'optic', 'lobe', 'valve', 'tissue', 'nose', 'vessel', 'tongue']
		output might be the same as middleNodes
		quickHyper(tmpItemArr - dup | middleNodes) = > input becomes "nose" and body_part
		"""
		RootName = quickHyper(tmpItemArr)
		#RootName = quickHyper(list(set(tmpItemArr)- dup | middleNodes))
	if RootName == "Root":
		RootName = "Root"+str(rootid)	
	else:
		RootName = "L"+str(rootid)+"_"+RootName

	for t in tmpItemArr:		
		if t not in dup:
			DG.add_edge(RootName, t)
	
	##for l in range(1, hid):
	##	DG.add_edge("Root"+str(rootid), str(rootid)+"_Hidden"+str(l))
	for l in list(middleNodes):
		DG.add_edge(RootName, l)

	if fp != None:
		try:
			
			fp.write(json_graph.tree_data(DG, RootName).__str__()+"\n")
			
		except:
			fp.write(nx.to_dict_of_lists(DG).__str__()+"\n")
			nx.write_gml(DG,"out.gml")

	else:
		try:
			#print json_graph.tree_data(DG, "Root"+str(rootid))
			print json_graph.tree_data(DG, RootName)
		except:
			print nx.to_dict_of_lists(DG)
			nx.write_gml(DG,"out.gml")