Python networkx.readwrite.json_graph.node_link_data() Examples

The following are code examples for showing how to use networkx.readwrite.json_graph.node_link_data(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: psst   Author: power-system-simulation-toolbox   File: plotmpld3.py    MIT License 6 votes vote down vote up
def __init__(self, G, pos, ax,
                 gravity=1,
                 link_distance=20,
                 charge=-30,
                 node_size=5,
                 link_strength=1,
                 friction=0.9,
                 draggable=True):

        if pos is None:
            pass

        self.dict_ = {"type": "networkxd3forcelayout",
                      "graph": node_link_data(G),
                      "ax_id": mpld3.utils.get_id(ax),
                      "gravity": gravity,
                      "charge": charge,
                      "friction": friction,
                      "link_distance": link_distance,
                      "link_strength": link_strength,
                      "draggable": draggable,
                      "nominal_radius": node_size} 
Example 2
Project: ICASSP-2020-clustering   Author: xavierfav   File: clustering.py    GNU General Public License v3.0 6 votes vote down vote up
def cluster_kmeans(X, num_clusters=5):
    """
    Applies k-means clustering and creates a knn graph for visualisation.
    Returns the labels in an array.

    """
    labels = KMeans(n_clusters=num_clusters, random_state=0).fit_predict(X)
    classes = {idx: str(v) for idx, v in enumerate(labels)}

    similarity_matrix = compute_similarity_matrix(X)
    graph = create_knn_graph(similarity_matrix, 8)

    # export clustered graph as json
    nx.set_node_attributes(graph, classes, 'group')
    graph_json = json_graph.node_link_data(graph)
    
    return list(map(int,labels)), graph_json 
Example 3
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 6 votes vote down vote up
def wordspan(text, startindex, endindex, graph):
	logger.logger.debug('INPUT TEXT <' + text.strip() + '>')
	logger.logger.debug('INPUT STARTINDEX <' + str(startindex) + '>')
	logger.logger.debug('INPUT ENDINDEX <' + str(endindex) + '>')
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	spannedwords = set(text[startindex: endindex + 1].split())
	start = 1
	end = graph.number_of_nodes() - 1
	bestscore = 0.0
	while True:
		score = setsimilarity(set([graph.node[node]['token'] for node in range(start, end + 1)]), spannedwords)
		if score <= bestscore:
			break
		start += 1
	start -= 1
	while True:
		score = setsimilarity(set([graph.node[node]['token'] for node in range(start, end + 1)]), spannedwords)
		if score <= bestscore:
			break
		end -= 1
	end += 1
	span = set(range(start, end + 1))
	logger.logger.log(logger.details, 'OUTPUT <' + str(span) + '>')
	return span 
Example 4
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 6 votes vote down vote up
def labellist(nestedlist, graph, alignment, node = 1):
	if type(nestedlist[1]) == str:
		if node < len(alignment) and alignment[node]:
			nestedlist[1] = alignment[node]
		node += 1
		logger.logger.debug('INPUT NESTEDLIST <' + str(nestedlist) + '>')
		logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
		logger.logger.debug('INPUT ALIGNMENT <' + str(alignment) + '>')
		logger.logger.log(logger.details, 'OUTPUT <' + str(node) + '>')
		return node
	for nest in nestedlist[1: ]:
		node = labellist(nest, graph, alignment, node)
	logger.logger.debug('INPUT NESTEDLIST <' + str(nestedlist) + '>')
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT ALIGNMENT <' + str(alignment) + '>')
	logger.logger.log(logger.details, 'OUTPUT <' + str(node) + '>')
	return node 
Example 5
Project: JARVIS   Author: aaiijmrtt   File: modeler.py    MIT License 6 votes vote down vote up
def model(graph, sentences, annotations):
	logger.logger.debug('INPUT <' + str(json_graph.node_link_data(graph)) + '>')
	bestscore = 0.0
	bestalignment = None
	bestsentence = None
	bestgraph = None
	bestannotation = None
	for sentence, annotation in zip(sentences, annotations):
		sentencetext = sentence[0][1].encode('ascii', 'ignore')
		sentenceparse = parser.dependencyparse(sentencetext)
		sentencegraph = grapher.graphparse(sentenceparse)
		contractedgraph = grapher.contractsubgraph(sentencegraph)
		score, alignment = aligner.align(contractedgraph, graph)
		if score > bestscore:
			bestscore = score
			bestalignment = alignment
			bestgraph = contractedgraph
			bestsentence = sentence
			bestannotation = annotation
	logger.logger.info('OUTPUT BESTSCORE <' + str(bestscore) + '>')
	logger.logger.info('OUTPUT BESTALIGNMENT <' + str(bestalignment) + '>')
	logger.logger.info('OUTPUT BESTSENTENCE <' + str(bestsentence) + '>')
	logger.logger.info('OUTPUT BESTGRAPH <' + str(bestgraph) + '>')
	logger.logger.info('OUTPUT BESTANNOTATION <' + str(bestannotation) + '>')
	return bestscore, bestalignment, bestsentence, bestgraph, bestannotation 
Example 6
Project: JARVIS   Author: aaiijmrtt   File: modeler.py    MIT License 6 votes vote down vote up
def stimulate(graph):
	logger.logger.debug('INPUT <' + str(json_graph.node_link_data(graph)) + '>')
	sentences = list()
	annotations = list()
	for edge in networkx.bfs_edges(graph, 0):
		name = graph.node[edge[1]]['token']
		newsentences, newannotations = querier.smartquery('getsentencesandannotationsbyunitname', (name, ))
		sentences.extend(newsentences)
		annotations.extend(newannotations)
	bestscore, bestalignment, bestsentence, bestgraph, bestannotation = model(graph, sentences, annotations)
	labeler.labelgraph(bestgraph, bestsentence[0][1], bestannotation)
	labeler.labelalign(bestgraph, graph, bestalignment)
	frame = querier.smartquery('getframesbysentenceID', (bestsentence[0][0], ))
	logger.logger.info('OUTPUT FRAME <' + str(frame) + '>')
	logger.logger.info('OUTPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	return frame, graph 
Example 7
Project: JARVIS   Author: aaiijmrtt   File: grapher.py    MIT License 6 votes vote down vote up
def augmentgraph(graph, nestedlist, node = 1):
	if type(nestedlist[1]) == str:
		if node in graph.nodes():
			if graph.node[node]['token'] != nestedlist[1]:
				logger.logger.warn('TOKEN MISMATCH <' + graph.node[node]['token'] + ', ' + nestedlist[1] + '>')
			graph.node[node]['POS'] = nestedlist[0]
		node += 1
		logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
		logger.logger.debug('INPUT NESTEDLIST <' + str(nestedlist) + '>')
		logger.logger.log(logger.details, 'OUTPUT <' + str(node) + '>')
		return node
	for nest in nestedlist[1: ]:
		node = augmentgraph(graph, nest, node)
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT NESTEDLIST <' + str(nestedlist) + '>')
	logger.logger.log(logger.details, 'OUTPUT <' + str(node) + '>')
	return node 
Example 8
Project: JARVIS   Author: aaiijmrtt   File: grapher.py    MIT License 6 votes vote down vote up
def subgraphplot(graph, POS = False, label = False, offset = 0.05):
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT LABEL <' + str(label) + '>')
	logger.logger.debug('INPUT OFFSET <' + str(offset) + '>')
	positions = networkx.shell_layout(graph)
	networkx.draw(graph, positions, labels = networkx.get_node_attributes(graph, 'token'))
	networkx.draw_networkx_edge_labels(graph, positions, edge_labels = networkx.get_edge_attributes(graph, 'relation'))
	if label:
		for position in positions:
			newposition = list(positions[position])
			newposition[1] += offset
			positions[position] = newposition
		networkx.draw_networkx_labels(graph, positions, labels = networkx.get_node_attributes(graph, 'label'))
	if POS:
		for position in positions:
			newposition = list(positions[position])
			newposition[1] += offset
			positions[position] = newposition
		networkx.draw_networkx_labels(graph, positions, labels = networkx.get_node_attributes(graph, 'POS'))
	matplotlib.pyplot.show() 
Example 9
Project: JARVIS   Author: aaiijmrtt   File: grapher.py    MIT License 6 votes vote down vote up
def insertactivenode(frameID, node):
	global graph, active
	logger.logger.debug('INPUT FRAMEID <' + str(frameID) + '>')
	logger.logger.debug('INPUT NODE <' + str(json_graph.node_link_data(node)) + '>')
	active = frameID
	if frameID not in graph.nodes():
		frame = querier.smartquery('getframebyID', (frameID, ))
		graph.add_node(frameID, name = frame[0][1], subgraph = node)
		return
	offset = max(graph.node[frameID]['subgraph'].nodes()) if 0 in graph.node[frameID]['subgraph'].nodes() else 0
	labels = dict()
	for oldnode in graph.node[frameID]['subgraph'].nodes():
		labels[oldnode] = oldnode + offset
	labels[0] = 0
	node = networkx.relabel_nodes(node, labels, True)
	graph.node[frameID]['subgraph'].add_nodes_from(node.nodes(data = True))
	graph.node[frameID]['subgraph'].add_edges_from(node.edges(data = True)) 
Example 10
Project: k9-chess-angular   Author: hopkira   File: k9_profiler.py    The Unlicense 6 votes vote down vote up
def save_profile(Tree, args):
    '''
    Save the profile, after aggregation, to files. One for white and one for black.
    '''
    for c in range(len(Tree)):
        setattr(args, 'colour', args.colours[c])
        if args.v:
            print('The',args.colour,'tree has', Tree[c].number_of_nodes(), 'nodes.')
            print('The',args.colour,'tree has', Tree[c].number_of_edges(), 'edges.')

        if args.tree:
            # for a tree format and the graph needs to be created with DiGraph
            data = json_graph.tree_data(Tree[c], root=args.root)
        else:
            Tree[c] = nx.convert_node_labels_to_integers(Tree[c], first_label=0, label_attribute='fen')
            # name is changed to: "(Carlsen (black))_with_int_labels"
            Tree[c].name = ''.join([args.player, ' (', args.colour, ')'])     # above convert also converts the name
            # for a Force directed graph
            data = json_graph.node_link_data(Tree[c])
        s = json.dumps(data)
        js = open(profile_file_name(args), 'w')
        js.write(s)
        js.close() 
Example 11
Project: kgx   Author: NCATS-Tangerine   File: transformer.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dump(g: nx.MultiDiGraph) -> Dict:
        """
        Convert networkx.MultiDiGraph as a dictionary.

        Parameters
        ----------
        g: networkx.MultiDiGraph
            Graph to convert as a dictionary

        Returns
        -------
        dict
            A dictionary
        """
        data = json_graph.node_link_data(g)
        return data 
Example 12
Project: grimoirelab-graal   Author: chaoss   File: reverse.py    GNU General Public License v3.0 5 votes vote down vote up
def __dotfile2json(self, dot_file):
        g = nx.Graph(read_dot(dot_file))
        json_data = json_graph.node_link_data(g)

        return json_data 
Example 13
Project: sdcon   Author: Cloudslab   File: sdc_viz.py    GNU General Public License v3.0 5 votes vote down vote up
def get_data_base(topo, flow_name):
    g = topo.topo_graph.to_directed()
    for node in networkx.nodes(g):
        g.add_node(node, type = node_to_type(node))
        g.add_node(node, label = topo.get_host_ip(node))
        if SDCNodeIdType.is_switch(node):
            fx, fy = get_fixed_pos(node)
            g.add_node(node, fx = fx, fy = fy)
        else:
            g.add_node(node, y=SCREEN_SIZE_Y, x=SCREEN_SIZE_X/2)

    bw_usage = network_monitor.get_bw_usage_all_incoming(flow_name = flow_name)
    for this_node in bw_usage:
        if SDCNodeIdType.is_host(this_node):
            this_switch = topo.get_host_mac(this_node)
        else:
            this_switch = this_node
        if this_switch == None:
            continue
        #print this_node, bw_usage[this_node]
        for this_inport, bw in bw_usage[this_node]:
            other_switch = topo.get_connected_node_via_port(this_switch, this_inport)
            if other_switch and this_switch:
                #print "Viz: %s -> %s : %s"%(other_switch,this_switch,str(bw))
                g[other_switch][this_switch]['weight']=bw
                g[other_switch][this_switch]['width'] = bw_to_width(bw)
    return json_graph.node_link_data(g) 
Example 14
Project: ICASSP-2020-clustering   Author: xavierfav   File: clustering.py    GNU General Public License v3.0 5 votes vote down vote up
def knn_graph_clustering(similarity_matrix, k):
    """
    Apply k-nn graph-based clustering on items of the given similarity matrix.
    
    """
    graph = create_knn_graph(similarity_matrix, k)
    classes = com.best_partition(graph)

    # export clustered graph as json
    nx.set_node_attributes(graph, classes, 'group')
    graph_json = json_graph.node_link_data(graph)

    return [classes[k] for k in range(len(classes.keys()))], graph_json 
Example 15
Project: ICASSP-2020-clustering   Author: xavierfav   File: clustering.py    GNU General Public License v3.0 5 votes vote down vote up
def cluster_agglomerative(X, num_clusters=5):
    labels = AgglomerativeClustering(n_clusters=num_clusters).fit_predict(X)
    classes = {idx: str(v) for idx, v in enumerate(labels)}

    similarity_matrix = compute_similarity_matrix(X)
    graph = create_knn_graph(similarity_matrix, 8)

    # export clustered graph as json
    nx.set_node_attributes(graph, classes, 'group')
    graph_json = json_graph.node_link_data(graph)

    return list(labels), graph_json 
Example 16
Project: ICASSP-2020-clustering   Author: xavierfav   File: clustering.py    GNU General Public License v3.0 5 votes vote down vote up
def cluster_spectral(X):
    similarity_matrix = compute_similarity_matrix(X)

    labels = spectral_clustering(similarity_matrix)
    classes = {idx: str(v) for idx, v in enumerate(labels)}
    
    graph = create_knn_graph(similarity_matrix, 8)

    # export clustered graph as json
    nx.set_node_attributes(graph, classes, 'group')
    graph_json = json_graph.node_link_data(graph)

    return list(labels), graph_json 
Example 17
Project: ICASSP-2020-clustering   Author: xavierfav   File: clustering.py    GNU General Public License v3.0 5 votes vote down vote up
def cluster_DBSCAN(X):
    labels = DBSCAN().fit_predict(X)
    classes = {idx: str(v) for idx, v in enumerate(labels)}

    similarity_matrix = compute_similarity_matrix(X)
    graph = create_knn_graph(similarity_matrix, 8)

    # export clustered graph as json
    nx.set_node_attributes(graph, classes, 'group')
    graph_json = json_graph.node_link_data(graph)

    return list(labels), graph_json 
Example 18
Project: BlackWidow   Author: madisonmay   File: web.py    MIT License 5 votes vote down vote up
def visualize(self, port=None):
        """
        Dumps graph data to a dictionary and renders using d3's force-directed graph
        """
        json_data = json_graph.node_link_data(self.graph)
        json_data['package_name'] = self.module
        serve(data=json_data, port=port) 
Example 19
Project: soil   Author: gsi-upm   File: environment.py    Apache License 2.0 5 votes vote down vote up
def __getstate__(self):
        state = {}
        for prop in _CONFIG_PROPS:
            state[prop] = self.__dict__[prop]
        state['G'] = json_graph.node_link_data(self.G)
        state['environment_agents'] = self._env_agents
        state['history'] = self._history
        return state 
Example 20
Project: soil   Author: gsi-upm   File: simulation.py    Apache License 2.0 5 votes vote down vote up
def __getstate__(self):
        state={}
        for k, v in self.__dict__.items():
            if k[0] != '_':
                state[k] = v
                state['topology'] = json_graph.node_link_data(self.topology)
                state['network_agents'] = agents.serialize_distribution(self.network_agents,
                                                                        known_modules = [])
                state['environment_agents'] = agents.serialize_distribution(self.environment_agents,
                                                                            known_modules = [])
                state['environment_class'] = serialization.serialize(self.environment_class,
                                                                     known_modules=['soil.environment'])[1]  # func, name
        if state['load_module'] is None:
            del state['load_module']
        return state 
Example 21
Project: catpy   Author: catmaid   File: test_export.py    MIT License 5 votes vote down vote up
def assert_same_graph(g1, g2):
    d1 = json_graph.node_link_data(g1)
    d2 = json_graph.node_link_data(g2)
    assert d1 == d2 
Example 22
Project: disparity_filter   Author: DerwenAI   File: disparity.py    MIT License 5 votes vote down vote up
def save_graph (graph, graph_path):
    """
    save a graph as JSON
    """
    with open(graph_path, "w") as f:
        data = json_graph.node_link_data(graph)
        json.dump(data, f)


######################################################################
## testing 
Example 23
Project: CNPJ-full   Author: fabioserpa   File: rede_cnpj.py    GNU General Public License v3.0 5 votes vote down vote up
def json_G(self, G):
        return json_graph.node_link_data(G) 
Example 24
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 5 votes vote down vote up
def depth(graph, node = 0):
	height = 0
	for child in graph.edge[node]:
		height = max(height, depth(graph, child))
	height += 1
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT NODE <' + str(node) + '>')
	logger.logger.log(logger.details, 'OUTPUT <' + str(height) + '>')
	return height 
Example 25
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 5 votes vote down vote up
def dependencyspan(graph, node = 0):
	span = set()
	for child in graph.edge[node]:
		span.update(dependencyspan(graph, child))
	span.add(node)
	graph.node[node]['span'] = span
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT NODE <' + str(node) + '>')
	logger.logger.log(logger.details, 'OUTPUT <' + str(span) + '>')
	return span 
Example 26
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 5 votes vote down vote up
def relate(graph, node = 0, label = None):
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT NODE <' + str(node) + '>')
	logger.logger.debug('INPUT LABEL <' + str(label) + '>')
	if 'label' in graph.node[node] and graph.node[node]['label']:
		return
	for child in graph.edge[node]:
		relate(graph, child, label)
	graph.node[node]['label'] = label 
Example 27
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 5 votes vote down vote up
def fill(graph, sourcenode, targetnode, label):
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT SOURCENODE <' + str(sourcenode) + '>')
	logger.logger.debug('INPUT TARGETNODE <' + str(targetnode) + '>')
	logger.logger.debug('INPUT LABEL <' + str(label) + '>')
	if not networkx.has_path(graph, sourcenode, targetnode):
		return
	for node in networkx.shortest_path(graph, sourcenode, targetnode)[1: -1]:
		if 'label' in graph[node] and graph.node[node]['label']:
			return
	for node in networkx.shortest_path(graph, sourcenode, targetnode)[1: -1]:
		graph.node[node]['label'] = label 
Example 28
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 5 votes vote down vote up
def labelalign(sourcegraph, targetgraph, alignment):
	logger.logger.debug('INPUT SOURCEGRAPH <' + str(json_graph.node_link_data(sourcegraph)) + '>')
	logger.logger.debug('INPUT TARGETGRAPH <' + str(json_graph.node_link_data(targetgraph)) + '>')
	logger.logger.debug('INPUT ALIGNMENT <' + str(alignment) + '>')
	dependencyspan(targetgraph)
	relate(targetgraph)
	for i in range(len(alignment)):
		if alignment[i]:
			targetgraph.node[alignment[i]]['label'] = sourcegraph.node[i]['label']
	for sourcenode in targetgraph.nodes():
		if targetgraph.node[sourcenode]['label']:
			for targetnode in targetgraph.node[sourcenode]['span']:
				if targetgraph.node[targetnode]['label'] and targetgraph.node[sourcenode]['label'] == targetgraph.node[targetnode]['label']:
					fill(targetgraph, sourcenode, targetnode, targetgraph.node[sourcenode]['label']) 
Example 29
Project: JARVIS   Author: aaiijmrtt   File: labeler.py    MIT License 5 votes vote down vote up
def relabellist(nestedlist, graph):
	if type(nestedlist[1]) == int:
		nestedlist[1] = graph.node[nestedlist[1]]['token']
		logger.logger.debug('INPUT NESTEDLIST <' + str(nestedlist) + '>')
		logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
		return
	for nest in nestedlist[1: ]:
		relabellist(nest, graph)
	logger.logger.debug('INPUT NESTEDLIST <' + str(nestedlist) + '>')
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>') 
Example 30
Project: JARVIS   Author: aaiijmrtt   File: grapher.py    MIT License 5 votes vote down vote up
def contractsubgraph(graph):
	logger.logger.debug('INPUT <' + str(json_graph.node_link_data(graph)) + '>')
	labels = dict()
	counter = 0
	for node in graph.nodes():
		labels[node] = counter
		counter += 1
	graph = networkx.relabel_nodes(graph, labels, True)
	logger.logger.info('OUTPUT <' + str(json_graph.node_link_data(graph)) + '>')
	return graph 
Example 31
Project: JARVIS   Author: aaiijmrtt   File: grapher.py    MIT License 5 votes vote down vote up
def graphplot(graph, offset = 0.25):
	logger.logger.debug('INPUT GRAPH <' + str(json_graph.node_link_data(graph)) + '>')
	logger.logger.debug('INPUT OFFSET <' + str(offset) + '>')
	positions = networkx.shell_layout(graph)
	networkx.draw(graph, positions, labels = networkx.get_node_attributes(graph, 'name'))
	networkx.draw_networkx_edge_labels(graph, positions, edge_labels = networkx.get_edge_attributes(graph,'relation'), label_pos = offset)
	matplotlib.pyplot.show() 
Example 32
Project: JARVIS   Author: aaiijmrtt   File: aligner.py    MIT License 5 votes vote down vote up
def score(sourcegraph, targetgraph, alignment):
	logger.logger.debug('INPUT SOURCE <' + str(json_graph.node_link_data(sourcegraph)) + '>')
	logger.logger.debug('INPUT TARGET <' + str(json_graph.node_link_data(targetgraph)) + '>')
	logger.logger.debug('INPUT ALIGNMENT <' + str(alignment) + '>')
	score = 0.0
	for i in range(len(alignment)):
		if alignment[i]:
			score += similarity(sourcegraph.node[i]['token'], targetgraph.node[alignment[i]]['token'])
			for j in range(len(alignment)):
				if i != j and alignment[j]:
					if sourcegraph.has_edge(i, j) and targetgraph.has_edge(alignment[i], alignment[j]) and sourcegraph.edge[i][j] == targetgraph.edge[alignment[i]][alignment[j]]:
						score += 1.0
	logger.logger.info('OUTPUT <' + str(score) + '>')
	return score 
Example 33
Project: watsongraph   Author: ResidentMario   File: conceptmodel.py    MIT License 5 votes vote down vote up
def to_json(self):
        """
        Returns the JSON representation of a ConceptModel. Counter-operation to `load_from_dict()`.

        :param self: A ConceptModel.

        :return: The nx dictionary representation of the ConceptModel.
        """
        flattened_model = nx.relabel_nodes(self.graph, {node: node.concept for node in self.nodes()})
        data_repr = json_graph.node_link_data(flattened_model)
        for node in data_repr['nodes']:
            for prop in self.get_node(node['id']).properties.keys():
                node[prop] = self.get_node(node['id']).properties[prop]
        return data_repr 
Example 34
Project: Musical-Collab-Graph   Author: akashlevy   File: pickle_to_json.py    MIT License 5 votes vote down vote up
def pickle_to_json(source_file='graph.pickle', dest_file='graph.json'):
    # Load graph from pickle file
    print('Reading file: ' + source_file)
    G = nx.read_gpickle(source_file)
    print(nx.info(G))
    
    # Convert to table
    data = json_graph.node_link_data(G, dict(id='id', source='source', target='target', key='key'))
    
    # Write JSON to file
    print('Writing to: ' + dest_file);
    with open(dest_file, 'w') as f:
        f.write(json.dumps(data)) 
Example 35
Project: ribolands   Author: bad-ants-fleet   File: trafo.py    MIT License 5 votes vote down vote up
def graph_to_json(self, name):
        """Prints the current graph into a JSON file format.

        There exits a script to visualize the output files using d3js in your
        browser. Search for it in: ribolands/d3js/start_server.py

        Args: 
            name (str): The basename of the *.json file.
        """
        import json
        from networkx.readwrite import json_graph
        d = json_graph.node_link_data(self)
        json.dump(d, open(name+'.json', 'w')) 
Example 36
Project: pyblk   Author: mulkieran   File: _readwrite.py    GNU General Public License v2.0 5 votes vote down vote up
def write(graph, out):
        """
        Write a graph to an output stream.

        :param DiGraph graph: a graph
        :param out: an output stream
        """
        graph = graph.copy()
        Rewriter.stringize(graph)
        data = json_graph.node_link_data(graph)
        json.dump(data, out, indent=4)
        print(end=os.linesep, file=out) 
Example 37
Project: vitrage-tempest-plugin   Author: openstack   File: base.py    Apache License 2.0 5 votes vote down vote up
def _to_dict(graph):
        return json_graph.node_link_data(graph)

    # This will unzip the nodes and create a tuple of nodes with data only.
    # Using next and islice because zip returns iterator on py3
    # e.g. (id1, data1), (id2, data2) --> (data1, data2) 
Example 38
Project: iok   Author: rustielin   File: iok.py    MIT License 5 votes vote down vote up
def write_to_file(self, filename=FILENAME):
        """Writes graph to JSON in data link format"""
        # TODO: probably include a way to backup
        data = json_graph.node_link_data(self.graph)
        with open(filename, 'w') as f:
            json.dump(data, f) 
Example 39
Project: vitrage   Author: openstack   File: networkx_graph.py    Apache License 2.0 5 votes vote down vote up
def json_output_graph(self, **kwargs):
        """supports both 1.10<=networkx<2.0 and networx>=2.0 by returning the

        same json output regardless networx version

        :return: graph in json format
        """

        # TODO(annarez): when we decide to support networkx 2.0 with
        # versioning of Vitrage, we can move part of the logic to vitrageclient
        node_link_data = json_graph.node_link_data(self._g)
        node_link_data.update(kwargs)

        vitrage_id_to_index = dict()

        for index, node in enumerate(node_link_data['nodes']):
            vitrage_id_to_index[node[VProps.VITRAGE_ID]] = index
            if VProps.ID in self._g.nodes[node[VProps.ID]]:
                node[VProps.ID] = self._g.nodes[node[VProps.ID]][VProps.ID]
                node[VProps.GRAPH_INDEX] = index

        vers = nx.__version__
        if vers >= '2.0':
            for i in range(len(node_link_data['links'])):
                node_link_data['links'][i]['source'] = vitrage_id_to_index[
                    node_link_data['links'][i]['source']]
                node_link_data['links'][i]['target'] = vitrage_id_to_index[
                    node_link_data['links'][i]['target']]

        if kwargs.get('raw', False):
            return node_link_data
        else:
            return json.dumps(node_link_data) 
Example 40
Project: grafeno   Author: agarsev   File: graph.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def to_json (self, with_labels = True):
        '''Returns a JSON representation of the graph data.

        Parameters
        ----------
        with_labels : bool
            If True, a 'label' attribute is added to nodes and edges with the
            _concept_ and _functor_, respectively. Useful for further consuming
            by some libraries.

        Returns
        -------
            A string with the graph data encoded in JSON.
        '''
        class BestEffortEncoder(json.JSONEncoder):
            def default(self, obj):
                return repr(obj)
        g = self._g
        if with_labels:
            for n in g:
                node = g.node[n]
                node['label'] = '.'.join(x for x in [node.get('class'),node.get('concept'),node.get('sempos')] if x)
                for m in g[n]:
                    edge = g[n][m]
                    edge['label'] = '.'.join(x for x in [edge.get('functor'),edge.get('class')] if x)
        return json.dumps(json_graph.node_link_data(g), cls=BestEffortEncoder) 
Example 41
Project: LinearSieve   Author: gregversteeg   File: vis_sieve.py    Apache License 2.0 4 votes vote down vote up
def vis_hierarchy(sieve, column_label, max_edges=200, prefix=''):
    """Visualize a hierarchy of representations."""
    import textwrap
    column_label = map(lambda q: '\n'.join(textwrap.wrap(q, width=20)), column_label)

    def f(j):
        if j < sieve.nv:
            return j
        else:
            return (1, j - sieve.nv)

    # Construct non-tree graph
    g = nx.DiGraph()
    max_node_weight = np.max(sieve.tcs)
    for i, c in enumerate(column_label):
        if i < sieve.nv:
            g.add_node(i)
            g.node[i]['weight'] = 1
            g.node[i]['label'] = c
            g.node[i]['name'] = c  # JSON uses this field
        else:
            g.add_node(f(i))
            g.node[f(i)]['weight'] = 0.33 * np.clip(sieve.tcs[i - sieve.nv] / max_node_weight, 0.33, 1)
        if i >= sieve.nv:
            g.add_weighted_edges_from([(f(j), (1, i - sieve.nv), sieve.mi_j(i - sieve.nv)[j]) for j in range(i)])

    # Display pruned version
    h = g.copy()  # trim(g.copy(), max_parents=max_parents, max_children=max_children)
    h.remove_edges_from(sorted(h.edges(data=True), key=lambda q: q[2]['weight'])[:-max_edges])
    edge2pdf(h, prefix + '/graphs/graph_%d' % max_edges, labels='label', directed=True, makepdf=True)

    # Display tree version
    tree = g.copy()
    tree = trim(tree, max_parents=1, max_children=False)
    edge2pdf(tree, prefix + '/graphs/tree', labels='label', directed=True, makepdf=True)

    # Output JSON files
    try:
        import os
        print os.path.dirname(os.path.realpath(__file__))
        copyfile(os.path.dirname(os.path.realpath(__file__)) + '/tests/d3_files/force.html', prefix + '/graphs/force.html')
    except:
        print "Couldn't find 'force.html' file for visualizing d3 output"
    import json
    from networkx.readwrite import json_graph

    mapping = dict([(n, tree.node[n].get('label', str(n))) for n in tree.nodes()])
    tree = nx.relabel_nodes(tree, mapping)
    json.dump(json_graph.node_link_data(tree), safe_open(prefix + '/graphs/force.json', 'w+'))
    json.dump(json_graph.node_link_data(h), safe_open(prefix + '/graphs/force_nontree.json', 'w+'))

    return g 
Example 42
Project: diplomawork   Author: taras-ua   File: main.py    Apache License 2.0 4 votes vote down vote up
def get_graph(request):
    model = request.GET.get('model')
    nodes = int(request.GET.get('nodes'))
    graph = None
    model_name = ''
    model_data = 'n = ' + str(nodes)
    directed = 1
    subnodes_for_new_model = 0
    if model == 'bollobas-riordan':
        model_name = 'Bollobás–Riordan model'
        subnodes = int(request.GET.get('subnodes'))
        initweight = float(request.GET.get('initweight'))
        model_data += ' | m = ' + str(subnodes) + ' | &alpha; = ' + str(initweight)
        graph = br.BollobasRiordan(nodes, subnodes, initweight).get_nx_graph()
    elif model == 'erdos-renyi':
        model_name = 'Erdős–Rényi model'
        directed = 0
        probability = float(request.GET.get('probability'))
        model_data += ' | p = ' + str(probability)
        graph = sm.SimpleRandomGraph(nodes, probability).get_nx_graph()
    elif model == 'new-model':
        model_name = 'Model of forgetting'
        subnodes = int(request.GET.get('subnodes'))
        subnodes_for_new_model = subnodes
        initweight = float(request.GET.get('initweight'))
        forget = float(request.GET.get('forget'))
        model_data += ' | m = ' + str(subnodes) + ' | &alpha; = ' + str(initweight) + ' | &beta; = ' + str(forget)
        graph = nm.NewModel(nodes, subnodes, initweight, forget).get_nx_graph()
    if graph is not None:
        degrees, fractions = get_fraction_of_nodes_with_degree(graph)
        degree_by_node = get_degrees_list(graph)
        nodes = graph.number_of_nodes()
        if model == 'new-model':
            dead_nodes = 0
            for node in graph.nodes():
                if graph.degree(node) == 0:
                    dead_nodes += 1
            nodes -= dead_nodes
        matrix = nx.to_numpy_matrix(graph)
        np.set_printoptions(suppress=True, precision=5)
        matrix_string = ''
        for i in range(len(matrix)):
            matrix_string += str(matrix[i, :]).replace('[', '').replace(']', '').replace('\n ', '') + '\n'
        return json_graph.node_link_data(graph), degrees, fractions, degree_by_node, matrix_string, model_name, model_data, directed, \
               get_diam(graph, model), nodes, graph.number_of_edges(), subnodes_for_new_model