Example #1
0
def get_from_dict(data_dict, graph_type):

    h = nx.from_dict_of_dicts(
        data_dict, create_using=nx.DiGraph
    ) if graph_type == 'dig' else nx.from_dict_of_dicts(data_dict,
                                                        create_using=nx.Graph)
    return nx.from_dict_of_dicts(data_dict, h)
Example #2
0
    def treeUnion(self, agglomeratedShot1, agglomeratedShot2):
        has_joined = False
        subtree_at_2 = None
        tree1 = None
        if (agglomeratedShot1.root.name in nx.to_dict_of_dicts(
                agglomeratedShot2.tree)
                and (agglomeratedShot1.pause > agglomeratedShot2.pause)):
            subtree_at_2 = dfs_tree(agglomeratedShot2.tree,
                                    agglomeratedShot1.root.name)
            children = nx.to_dict_of_dicts(subtree_at_2)
            tree1 = nx.to_dict_of_dicts(agglomeratedShot1.tree)
            tree1[agglomeratedShot1.root.name] = children
            tree1 = nx.from_dict_of_dicts(tree1)

            has_joined = True
        else:

            for key in nx.to_dict_of_dicts(agglomeratedShot1.tree)[
                    agglomeratedShot1.root.name].keys():
                if key in nx.to_dict_of_dicts(agglomeratedShot2.tree):
                    subtree_at_2 = dfs_tree(agglomeratedShot2.tree, key)
                    children = nx.to_dict_of_dicts(subtree_at_2)
                    tree1 = nx.to_dict_of_dicts(agglomeratedShot1.tree)
                    tree1[key] = children
                    tree1 = nx.from_dict_of_dicts(tree1)

                    has_joined = True

        if (has_joined):
            ocr = ''
            ids = agglomeratedShot1.ids + agglomeratedShot2.ids
            transcript = agglomeratedShot1.transcript + ' ' + agglomeratedShot2.transcript
            if self.ocr_on:
                ocr = agglomeratedShot1.ocr + ' ' + agglomeratedShot2.ocr

            pitch = agglomeratedShot1.pitch
            volume = agglomeratedShot1.volume
            pause = agglomeratedShot1.pause
            root = agglomeratedShot1.root
            join = agglomeratedShot1.ids + agglomeratedShot2.ids
            self.boundaries.append(join[0])
            T = nx.minimum_spanning_tree(tree1)

            a_node = AgglomeratedNode(0, ids, transcript, ocr, pitch, volume,
                                      pause, root, T)
            for id in a_node.ids:
                self.agglomerate_shots = [
                    s for s in self.agglomerate_shots if id not in s.ids
                ]
            self.agglomerate_shots.append(a_node)
            self.agglomerate_shots = sorted(self.agglomerate_shots,
                                            key=lambda x: x.ids)

        return self.agglomerate_shots, has_joined
Example #3
0
def create_graph(df, what, initials_only):
    r = get_adjacency_and_weights(df, what=what,
                                  author_initials_only=initials_only)
    adjacency, weights = r
    G = nx.from_dict_of_dicts(adjacency)
    nx.set_node_attributes(G, 'weight', weights)
    return G
    def __init__(self,
                 dendrogram,
                 classes,
                 distances=None,
                 distance_increment=1.0):
        super(DendrogramLoss, self).__init__()

        self.register_buffer('distance_increment',
                             torch.tensor(distance_increment).float())

        if type(dendrogram) == dict:
            key = next(iter(dendrogram))
            val = dendrogram[key]
            if type(val) == dict:
                self.dendrogram = nx.from_dict_of_dicts(dendrogram)
            elif type(val) in (list, tuple):
                self.dendrogram = nx.from_dict_of_lists(dendrogram)
            else:
                raise ValueError(
                    f'Received a dendrogram dictionary with unknown value type: {type(val)}'
                )

        elif type(dendrogram) == nx.classes.graph.Graph:
            self.dendrogram = dendrogram

        else:
            raise ValueError(
                f'Received a dendrogram of unknown type: {type(dendrogram)}')

        self.classes = classes
        if distances is not None:
            self.distances = distances
        else:
            self._dendrogram_to_distances()
Example #5
0
def construct_graph_from_df(df,
                            adjacency_type,
                            geoid_col=None,
                            cols_to_add=None):
    """Construct initial graph from information about neighboring VTDs.

    :df: Geopandas dataframe.
    :returns: NetworkX Graph.
    """
    # reproject to a UTM projection for accurate areas and perimeters in meters
    df = reprojected(df)

    if geoid_col is not None:
        df = df.set_index(geoid_col)

    # Generate rook or queen neighbor lists from dataframe.
    neighbors = get_neighbors(df, adjacency_type)

    vtds = neighbors_with_shared_perimeters(neighbors, df)
    graph = networkx.from_dict_of_dicts(vtds)

    add_boundary_perimeters(graph, neighbors, df)

    add_areas(graph, df)

    add_columns(graph, cols_to_add, df, geoid_col)

    return graph
Example #6
0
def makeGraph(df, authorInitialsOnly=False, subsetPACS=None, subsetYears=None, what=['authors']):
	'''Actually builds a networkx graph, using the helper functions.
	what: the nodes you want to look at.
		If what = ['authors'], the nodes are authors.
		If what = ['pacs'], the nodes are PACS codes.
		If what = ['authors','pacs'], the resulting graph is a bipartite graph with author and PACS nodes.
	authorInitialsOnly: boolean indicating whether you want to only save the first and middle initials, or the full names.
	subsetPACS: an integer list of PACS codes you want to look at (only consider papers in that subject range)
		Looks at all subjects if subsetPACS is None.
	subsetYears: an integer list of years you want to consider.
		Looks at all years if subsetYears is None.'''
	aio = authorInitialsOnly
	sp = subsetPACS
	sy = subsetYears
	w = what
	if len(what) == 1:
		adjList, nodeWeights = getAdjListSimple(df, authorInitialsOnly=aio, subsetPACS=sp, subsetYears=sy, what=w[0])
	elif len(what) == 2:
		adjList, nodeWeights = getAdjListBipartite(df, authorInitialsOnly=aio, subsetYears=sy, subsetPACS=sp)

	if adjList:
		G = nx.from_dict_of_dicts(adjList)
		nx.set_node_attributes(G,'weight',nodeWeights)
		return G
	else:
		return None
Example #7
0
    def networkx_plot_measure(self, measure: str, draw_node_names = True, draw_graphweights: bool = True, draw_edges: bool = False):
        """ Plots all specimens of the main dict. A measure is selected for the edge weights.
        Graphvis tries to get the optimal arrangement based on weights, hard to do for 2d space.
        Use dot, neato and fdp seem to maximize distances and just create a circular arrangement.

        :param measure: distance measure for the edges
        :return: None
        """
        import networkx as nx
        from networkx.drawing.nx_agraph import graphviz_layout
        import matplotlib.pyplot as plt

        dist_matrix_dict = utils.dict_of_dicts_matrix_measure(data_dict=self.data_dict, measure=measure)
        print("dist_matrix_dict", dist_matrix_dict)
        G = nx.from_dict_of_dicts(d=dist_matrix_dict)
        G.graph['edges']={'arrowsize':'4.0'}
        # neato, fdp seem to mazimize --> circle shape
        # dot works best, however, 2d representation is difficult
        pos = graphviz_layout(G, prog="fdp")
        if draw_edges:
            nx.draw_networkx(G, pos=pos)
        else:
            nx.draw_networkx_nodes(G, pos=pos)
        if draw_graphweights:
            nx.draw_networkx_edge_labels(G, pos=pos)
        if draw_node_names:
            nx.draw_networkx_labels(G, pos)
        plt.tight_layout()
        # adjust the [x, y] values for fitting all the text
        axes = plt.gca()
        #axes.set_xlim([-60, 800])
        # use these to turn off axis for plotting
        #plt.xticks([])
        #plt.yticks([])
        plt.show()
Example #8
0
def graph_from_dict(graph_dict):
    if 'graph_type' not in graph_dict:
        raise ValueError('graph_dict must contain key "graph_type"')

    if graph_dict['graph_type'] == 'MultiDiGraph':
        return multi_digraph_from_dict(graph_dict['graph_dict'])
    elif graph_dict['graph_type'] == 'MultiGraph':
        return nx.from_dict_of_dicts(graph_dict['graph_dict'], multigraph_input=True)
    elif graph_dict['graph_type'] == 'DiGraph':
        return nx.from_dict_of_dicts(graph_dict['graph_dict'])
    elif graph_dict['graph_type'] == 'Graph':
        return nx.from_dict_of_dicts(graph_dict['graph_dict'])
    elif graph_dict['graph_type'] == 'other':
        return nx.from_dict_of_dicts(graph_dict['graph_dict'])
    else:
        raise ValueError("the value for 'graph_type' in graph_dict is not of the accepted values.")
Example #9
0
def drawNetworkGraph(edgedict, sentiments):
    normalizeWeights(edgedict)
    nodelist = []
    colorlist = []
    for key in sentiments:
        nodelist.append(key)
        c = 150.0  # increase to push colors further to red/green extremes
        red = (int)(255.0 / (1 + c**(2 * sentiments[key]['color'] - 1)))
        colorlist.append('#' + str(hex(red))[2:] + str(hex(255 - red))[2:] +
                         '00')
    edge_list = []

    for firstKey in edgedict:
        for secondKey in edgedict[firstKey]:
            edge_list.append((firstKey, secondKey, {
                'weight': edgedict[firstKey][secondKey]['weight']
            }))

    g = nx.from_dict_of_dicts(edgedict)
    pos = nx.spring_layout(g)
    edges = g.edges()
    G = nx.Graph()
    weights = [g[u][v]['weight'] for u, v in edges]
    G.add_edges_from(g.edges())
    nx.draw(G,
            pos,
            nodelist=nodelist,
            node_color=colorlist,
            with_labels=True,
            alpha=1,
            width=weights)
    plt.show()
    plt.savefig("Graph.png", format="PNG")
Example #10
0
def getAuthorPacsInfo(bipartiteDict, authorList):
	'''Gets a dictionary of PACS information for each author in a bipartite dictionary.
	authorList is the list of authors, so we do not bother with PACS information.
	Returns a dictionary where each key is an author name,
		and the value is another dictionary storing entropy information
		and the full list of subjects and their frequencies.'''
	G = nx.from_dict_of_dicts(bipartiteDict)
	authorInfo = {a:{'pacsList':{},'pacsNum':0,'entropy':0.0} for a in authorList}
	for a in authorList:
		subjectList = G.neighbors(a)
		subjectFreq3 = {subj:G[a][subj]['weight'] for subj in subjectList}
		subjectFreq2 = {p:0 for p in range(0,100,10)}
		for s in subjectFreq3.keys():
			n = subjectFreq3[s]
			p = (s/10)*10
			if p in subjectFreq2.keys():
				subjectFreq2[p] += n
			else:
				subjectFreq2[p] = n
		entropy = parseAPS.entropy(subjectFreq2)
		pacsNum = 0
		for s in subjectFreq2.keys():
			if subjectFreq2[s] > 0:
				pacsNum += 1
		authorInfo[a]['entropy'] = entropy
		authorInfo[a]['pacsList'] = subjectFreq2
		authorInfo[a]['pacsNum'] = pacsNum
	return authorInfo 
    def from_dict(cls, d):
        """

        Args:
            d ():

        Returns:

        """
        # Reconstructs the graph with integer as nodes (json's as_dict replaces integer keys with str keys)
        cgraph = nx.from_dict_of_dicts(d["connectivity_graph"],
                                       create_using=nx.MultiGraph,
                                       multigraph_input=True)
        cgraph = nx.relabel_nodes(
            cgraph, int
        )  # Just relabel the nodes using integer casting (maps str->int)
        # Relabel multiedges (removes multiedges with str keys and adds them back with int keys)
        edges = set(cgraph.edges())
        for n1, n2 in edges:
            new_edges = {
                int(iedge): edata
                for iedge, edata in cgraph[n1][n2].items()
            }
            cgraph.remove_edges_from([
                (n1, n2, iedge) for iedge, edata in cgraph[n1][n2].items()
            ])
            cgraph.add_edges_from([(n1, n2, iedge, edata)
                                   for iedge, edata in new_edges.items()])
        return cls(
            LightStructureEnvironments.from_dict(
                d["light_structure_environments"]),
            connectivity_graph=cgraph,
            environment_subgraphs=None,
        )
Example #12
0
    def from_dict(cls, d):
        """
        Reconstructs the ConnectedComponent object from a dict representation of the
        ConnectedComponent object created using the as_dict method.

        Args:
            d (dict): dict representation of the ConnectedComponent object
        Returns:
            ConnectedComponent: The connected component representing the links of a given set of environments.
        """
        nodes_map = {
            inode_str: EnvironmentNode.from_dict(nodedict) for inode_str, (nodedict, nodedata) in d["nodes"].items()
        }
        nodes_data = {inode_str: nodedata for inode_str, (nodedict, nodedata) in d["nodes"].items()}
        dod = {}
        for e1, e1dict in d["graph"].items():
            dod[e1] = {}
            for e2, e2dict in e1dict.items():
                dod[e1][e2] = {
                    cls._edgedictkey_to_edgekey(ied): cls._retuplify_edgedata(edata) for ied, edata in e2dict.items()
                }
        graph = nx.from_dict_of_dicts(dod, create_using=nx.MultiGraph, multigraph_input=True)
        nx.set_node_attributes(graph, nodes_data)
        nx.relabel_nodes(graph, nodes_map, copy=False)
        return cls(graph=graph)
Example #13
0
 def _init_graph(self, name, type_s='DiGraph', data=None):
     if self.query.have_graph(name):
         raise GraphNameError("Already have a graph by that name")
     if name in self.illegal_graph_names:
         raise GraphNameError("Illegal name")
     self.query.new_graph(name, type_s)
     if data:
         branch, turn, tick = self._btt()
         if isinstance(data, DiGraph):
             self._snap_keyframe(name, branch, turn, tick,
                                 data._node_state(), data._edges_state(),
                                 data._val_state())
         elif isinstance(data, nx.Graph):
             self._snap_keyframe(name, branch, turn, tick, data._node,
                                 data._adj, data.graph)
         elif isinstance(data, dict):
             try:
                 data = nx.from_dict_of_dicts(data)
             except AttributeError:
                 data = nx.from_dict_of_lists(data)
             self._snap_keyframe(name, branch, turn, tick, data._node,
                                 data._adj, data.graph)
         else:
             self._snap_keyframe(name, branch, turn, tick, *data)
         self._new_keyframes.add((name, branch, turn, tick))
Example #14
0
def construct_graph_from_df(df,
                            adjacency_type,
                            geoid_col=None,
                            cols_to_add=None):
    """Construct initial graph from information about neighboring VTDs.

    :df: Geopandas dataframe.
    :returns: NetworkX Graph.
    """
    if adjacency_type not in ('rook', 'queen'):
        raise ValueError('adjacency_type must be rook or queen.')

    # reproject to a UTM projection for accurate areas and perimeters in meters
    df = reprojected(df)

    if geoid_col is not None:
        df = df.set_index(geoid_col)

    # Generate rook or queen neighbor lists from dataframe.
    if adjacency_type == 'queen':
        neighbors = ps.weights.Queen.from_dataframe(
            df, geom_col="geometry").neighbors
    else:
        neighbors = ps.weights.Rook.from_dataframe(
            df, geom_col="geometry").neighbors

    vtds = {}

    for shape in neighbors:
        vtds[shape] = {}

        for neighbor in neighbors[shape]:
            shared_perim = df.loc[shape, "geometry"].intersection(
                df.loc[neighbor, "geometry"]).length
            vtds[shape][neighbor] = {'shared_perim': shared_perim}

    graph = networkx.from_dict_of_dicts(vtds)
    vtd = df['geometry']

    # creates one shape of the entire state to compare outer boundaries against
    inter = gp.GeoSeries(cascaded_union(vtd).boundary)

    # finds if it intersects on outside and sets
    # a 'boundary_node' attribute to true if it does
    # if it is set to true, it also adds how much shared
    # perimiter they have to a 'boundary_perim' attribute
    for node in neighbors:
        graph.node[node]['boundary_node'] = inter.intersects(
            df.loc[node, "geometry"]).bool()
        if inter.intersects(df.loc[node, "geometry"]).bool():
            graph.node[node]['boundary_perim'] = float(
                inter.intersection(df.loc[node, "geometry"]).length)

    if cols_to_add is not None:
        data = pd.DataFrame({x: df[x] for x in cols_to_add})
        if geoid_col is not None:
            data[geoid_col] = df.index
        add_data_to_graph(data, graph, cols_to_add, geoid_col)
    return graph
Example #15
0
    def to_networkx_graph(self):
        dod = dict()
        for i in range(self.num_nodes):
            dod[i] = dict()
            for j, w in self.adj_list[i]:
                dod[i][j] = {"weight": w}

        return nx.from_dict_of_dicts(dod)
def markov_to_graph(markovchain):
    markovmodel = {}

    for k, v in markovchain.chain.model.items():
        _sum = sum(v.values())

        markovmodel[k[-1]] = {_k: {"weight": -np.log(_v / _sum)} for _k, _v in v.items()}

    return from_dict_of_dicts(markovmodel)
Example #17
0
def read_graph(nodes_path, edges_path):
    G = nx.from_dict_of_dicts(json.load(open(edges_path,
                                             'r')))  # type: nx.Graph
    nodes = json.load(open(nodes_path, 'r'))

    for k, v in nodes.items():
        G.add_node(k, **v)

    return G
Example #18
0
def prepareData(G):
    wishedOrderOfNodesList = sorted(G.nodes(), key=lambda item: G.degree(item))
    wishedOrderOfNodesDict = dict(
        zip(wishedOrderOfNodesList, range(len(wishedOrderOfNodesList))))
    orderedDictByDegree = OrderedDict(
        sorted(nx.to_dict_of_dicts(G).items(),
               key=lambda item: wishedOrderOfNodesDict[item[0]],
               reverse=True))
    GnewD = nx.from_dict_of_dicts(orderedDictByDegree)
    return GnewD
Example #19
0
    def networkx_plot_measure_spring_equal_length_edges(self, measure: str):
        import networkx as nx
        import matplotlib.pyplot as plt

        dist_matrix_dict = utils.dict_of_dicts_matrix_measure(data_dict=self.data_dict, measure=measure)
        print("dist_matrix_dict", dist_matrix_dict)
        G = nx.from_dict_of_dicts(d=dist_matrix_dict)
        G.graph['edges']={'arrowsize':'4.0'}
        pos = nx.spring_layout(G)
        nx.draw(G, pos)
        plt.show()
Example #20
0
def construct_graph(vtds):
    '''Construct initial graph from information about neighboring VTDs.

    :vtds: A dict of dict of dicts generated by :func:`.ingest`.
    :returns: Networkx Graph.

    '''

    graph = networkx.from_dict_of_dicts(vtds)
    graph = networkx.convert_node_labels_to_integers(graph,
                                                     label_attribute='old_id')

    return graph
Example #21
0
    def to_network(self):
        """Return a networkx graph object.

        Returns
        -------
        membership: nx.Graph
            the network representation of the membership in a networkx package.
            The network has to be a bipartite network.

        """
        dict_relations = self.to_dict()
        G = nx.from_dict_of_dicts(dict_relations)
        return G
Example #22
0
 def start(self):
     graph_json = self.load_graph()
     import networkx as nx
     import page_rank
     G = nx.from_dict_of_dicts(graph_json, create_using=nx.DiGraph)
     print(f"Size of the Graph is {len(graph_json)}")
     del graph_json
     rank_dict, err_log = page_rank.pagerank(G,
                                             tol=self.tolerence,
                                             max_iter=self.max_iter)
     self.error_log = err_log
     self.rank_save_path = self.save_json(
         rank_dict, save_name=f'page-rank-{current.run_id}.json')
     print(f"Saved Rank at {self.rank_save_path}")
     self.next(self.end)
def currency_nxgraph(list_codes, sleeping=0, adjmatrix=False):
    print('Lazy-search for real time rates')
    c = CurrencyRates()
    d = {}
    for currency in list_codes:
        print(f'Checking for {currency}')
        d[currency] = {}
        remaining_codes = [i for i in list_codes if i not in list(d.keys())]
        for other_currency in remaining_codes:
            log_rate = np.log(c.get_rate(currency, other_currency))
            d[currency][other_currency] = {}
            d[currency][other_currency]['weights'] = log_rate
        time.sleep(0.5)
    G = nx.from_dict_of_dicts(d)
    return G
def neighbors_with_shared_perimeters(neighbors, df):
    """Construct a graph with shared perimeter between neighbors on the edges.
    :neighbors: Adjacency information generated from pysal.
    :df: Geodataframe containing geometry information.
    :returns: NetworkX graph.
    """
    vtds = {}

    geom = df.geometry
    for shape in neighbors:
        shared_perim = geom[neighbors[shape]].intersection(geom[shape]).length
        shared_perim.name = "shared_perim"
        vtds[shape] = pd.DataFrame(shared_perim).to_dict("index")

    return networkx.from_dict_of_dicts(vtds)
Example #25
0
def nearest_neighbors(normalized_embeddings, session, k, int2gene):
    graph_dict = {}
    pairwise_distances = tf.matmul(normalized_embeddings,
                                   normalized_embeddings,
                                   transpose_b=True).eval(session=session)
    for i in range(pairwise_distances.shape[0]):
        nearest = (-pairwise_distances[i, :]).argsort()[1:k + 1]
        sorted_sim = np.sort(-pairwise_distances[i, :])[1:k + 1]
        graph_dict[int2gene[i]] = {
            int2gene[nearest[l]]: {
                'weight': -sorted_sim[l]
            }
            for l in range(k)
        }
    return nx.from_dict_of_dicts(graph_dict)
Example #26
0
def data(fname='Inter_country_trans_data'):
    """The function will load human mobility data from the input file and
    convert it into a weighted undirected NetworkX Graph.
    Each node corresponds to a country represented by its 3-letter
    ISO 3166-1 alpha-3  code. Each edge between a pair of countries is
    weighted with the number of average daily trips between the two countries.
    The dataset contains annual trips for varying numbers of years, and the daily
    average is computed and stored below.
    """

    df = pd.read_csv(fname,header=0) #Read dataset into Pandas dataframe, may take 1-2 minutes


    #Convert dataframe into D, a dictionary of dictionaries
    #Each key is a country, and the corresponding value is
    #a dictionary which has a linked country as a key
    #and a 2-element list as a value.  The 2-element list contains
    #the total number of trips between two countries and the number of years
    #over which these trips were taken
    D = {}
    for index, row in df.iterrows():
         c1,c2,yr,N = row[0],row[1],row[2],row[3]
         if len(c1)<=3:
             if c1 not in D:
                 D[c1] = {c2:[N,1]}
             else:
                 if c2 not in D[c1]:
                     D[c1][c2] = [N,1]
                 else:
                     Nold,count = D[c1][c2]
                     D[c1][c2] = [N+Nold,count+1]


    #Create new dictionary of dictionaries which contains the average daily
    #number of trips between two countries rather than the 2-element lists
    #stored in D
    Dnew = {}
    for k,v in D.items():
        Dnew[k]={}
        for k2,v2 in v.items():
            if v2[1]>0:
                v3 = D[k2][k]
                w_ave = (v2[0]+v3[0])/(730*v2[1])
                if w_ave>0: Dnew[k][k2] = {'weight':w_ave}

    G = nx.from_dict_of_dicts(Dnew) #Create NetworkX graph

    return G
Example #27
0
def startTree(ref,usr,walletData,treeData):
    global wallet
    global trees
    wallet=walletData
    trees=treeData

    for x in (list(trees.keys())):
        G=nx.from_dict_of_dicts(treeData[x])
        trees[x]=G
    print(trees)
    addNodeEdge(ref,usr)
    calculateWalletBalance()
    displayStats()
    #displayGraph()
    return(treesDict,wallet)
    
Example #28
0
 def __init__(
     self,
     model: BaseEstimator,
     hierarchy_tree: Union[str, nx.DiGraph, Dict[str, dict],
                           Dict[str, list]] = "infer",
 ):
     super().__init__(model=model)
     if type(hierarchy_tree) == dict:
         if type(hierarchy_tree[list(hierarchy_tree.keys())[0]]) == list:
             self.hierarchy_tree = nx.from_dict_of_lists(
                 hierarchy_tree, create_using=nx.DiGraph)
         elif type(hierarchy_tree[list(hierarchy_tree.keys())[0]]) == dict:
             self.hierarchy_tree = nx.from_dict_of_dicts(
                 hierarchy_tree, create_using=nx.DiGraph)
     else:
         self.hierarchy_tree = hierarchy_tree
 def extract_graph(self, graph_id: str) -> nx.Graph or None:
     # extract copy of graph from store or return None
     graph_nodes = list(
         nxq.search_nodes(
             self.graphs,
             {'eq': [ABCPropertyGraph.GRAPH_ID, graph_id]}))
     if len(graph_nodes) == 0:
         return None
     # get adjacency (only gets edges and their properties)
     edge_dict = nx.to_dict_of_dicts(self.graphs, graph_nodes)
     # create new graph from edges
     ret = nx.from_dict_of_dicts(edge_dict)
     for n in graph_nodes:
         # merge node dictionaries
         ret.nodes[n].update(self.graphs.nodes[n])
     return ret
Example #30
0
def makeDynamicGraphs(df, what='authors', authorInitialsOnly=False, subsetPACS=None, startYear=1982, endYear=2008, window=5):
	'''Actually makes the graphs - this is what you run if you want a list of graphs.
	Produces a dictionary where the keys are years and the values are graphs.
	See getDynamicNetwork for an explanation of arguments.'''
	aio = authorInitialsOnly
	sp = subsetPACS
	sy = startYear
	ey = endYear
	wi = window
	w = what
	adjLists, nodeWeights = getDynamicNetwork(df, what=w, authorInitialsOnly=aio, subsetPACS=sp, startYear=sy, endYear=ey, window=wi)
	graphsList = {y:None for y in adjLists.keys()}
	for yearKey in sorted(adjLists.keys()):
		graphDict = adjLists[yearKey]
		G = nx.from_dict_of_dicts(graphDict)
		nx.set_node_attributes(G,'weight',nodeWeights[yearKey])
		graphsList[yearKey] = G
	return graphsList
Example #31
0
    def build_graph(self):
        map_entity_to_id = dict(
            zip(self.all_entities, range(len(self.all_entities))))
        map_id_to_entity = dict(
            zip(range(len(self.all_entities)), self.all_entities))

        dod = {}
        for entity1 in self.all_entities:
            id1 = map_entity_to_id[entity1]
            dod.update({id1: {}})
            try:
                for entity2, count in self.entities_relevant_cooccurences[
                        entity1].items():
                    id2 = map_entity_to_id[entity2]
                    dod[id1].update({id2: {"weight": count}})
            except KeyError:
                continue

        self.graph = nx.from_dict_of_dicts(dod)
Example #32
0
def construct_graph(df, geoid_col=None):
    """Construct initial graph from information about neighboring VTDs.

    :df: Geopandas dataframe.
    :returns: NetworkX Graph.

    """
    if geoid_col is not None:
        df = df.set_index(geoid_col)

    # Generate rook neighbor lists from dataframe.
    neighbors = ps.weights.Rook.from_dataframe(
        df, geom_col="geometry").neighbors

    vtds = {}

    for shape in neighbors:

        vtds[shape] = {}

        for neighbor in neighbors[shape]:
            shared_perim = df.loc[shape, "geometry"].intersection(
                df.loc[neighbor, "geometry"]).length
            vtds[shape][neighbor] = {'shared_perim': shared_perim}

    graph = networkx.from_dict_of_dicts(vtds)
    vtd = df['geometry']

    # creates one shape of the entire state to compare outer boundaries against
    inter = gp.GeoSeries(cascaded_union(vtd).boundary)

    # finds if it intersects on outside and sets
    # a 'boundary_node' attribute to true if it does
    # if it is set to true, it also adds how much shared
    # perimiter they have to a 'boundary_perim' attribute
    for node in neighbors:
        graph.node[node]['boundary_node'] = inter.intersects(
            df.loc[node, "geometry"]).bool()
        if inter.intersects(df.loc[node, "geometry"]).bool():
            graph.node[node]['boundary_perim'] = float(
                inter.intersection(df.loc[node, "geometry"]).length)

    return graph
Example #33
0
def neighbors_with_shared_perimeters(neighbors, df):
    """Construct a graph with shared perimeter between neighbors on the edges.

    :neighbors: Adjacency information generated from pysal.
    :df: Geodataframe containing geometry information.
    :returns: NetworkX graph.

    """
    vtds = {}

    for shape in neighbors:
        vtds[shape] = {}

        for neighbor in neighbors[shape]:
            shared_perim = df.loc[shape, "geometry"].intersection(
                df.loc[neighbor, "geometry"]).length
            vtds[shape][neighbor] = {'shared_perim': shared_perim}

    return networkx.from_dict_of_dicts(vtds)
def build_nxGraph(graph):
    '''
    Devuelve el grafo pasado como diccionario como nx.Graph con las propiedades añadidas

    Parameters
    ----------
        graph : dict
            diccionario que tiene el formato:
            {
                autor: {
                    'name': 'nombre del autor',
                    'affiliation': 'afiliación del autor'
                    'pubs': {
                        coautor: { 'weight': int },
                        ...
                    }
                }...
            }

    Returns
    -------
        network : nx.Graph
            grafo en formato NetworkX
    '''
    # Generamos el grafo
    network = nx.from_dict_of_dicts(
        {author: props['pubs']
         for author, props in graph.items()})

    # Añadimos las propiedades de nombre y afiliación
    properties = {
        id: {
            'name': props['name'],
            'affiliation': props['affiliation']
        }
        for id, props in graph.items()
    }
    nx.set_node_attributes(network, properties)

    return network
Example #35
0
    def from_manual(self, data, **kwargs):  # pylint: disable=arguments-differ
        """Generate a new graph using a dictionary.

        Args:
            data (dict): A dictionary of dictionaries adjacency representation.
            kwargs (dict[str, object]): Depending on the resource they may
                require different sets of arguments to be able to run a raw
                API request.

        Raises:
            ValueError: If the import is not successful.
        """
        super().from_manual(**kwargs)
        if not isinstance(data, dict):
            raise ValueError("Data needs to be a dict of dictionaries")

        try:
            graph = nx.from_dict_of_dicts(data)
        except AttributeError as exc:
            raise ValueError("Unable to generate a graph") from exc

        self.from_graph(graph)
Example #36
0
def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs):
    """Takes an adjacency list, dict, or matrix and returns a graph.

    The purpose of this function is take an adjacency list (or matrix)
    and return a :class:`.QueueNetworkDiGraph` that can be used with a
    :class:`.QueueNetwork` instance. The Graph returned has the
    ``edge_type`` edge property set for each edge. Note that the graph may
    be altered.

    Parameters
    ----------
    adjacency : dict or :class:`~numpy.ndarray`
        An adjacency list as either a dict, or an adjacency matrix.
    adjust : int ``{1, 2}`` (optional, default: 1)
        Specifies what to do when the graph has terminal vertices
        (nodes with no out-edges). Note that if ``adjust`` is not 2
        then it is assumed to be 1. There are two choices:

        * ``adjust = 1``: A loop is added to each terminal node in the
          graph, and their ``edge_type`` of that loop is set to 0.
        * ``adjust = 2``: All edges leading to terminal nodes have
          their ``edge_type`` set to 0.

    **kwargs :
        Unused.

    Returns
    -------
    out : :any:`networkx.DiGraph`
        A directed graph with the ``edge_type`` edge property.

    Raises
    ------
    TypeError
        Is raised if ``adjacency`` is not a dict or
        :class:`~numpy.ndarray`.

    Examples
    --------
    If terminal nodes are such that all in-edges have edge type ``0``
    then nothing is changed. However, if a node is a terminal node then
    a loop is added with edge type 0.

    >>> import queueing_tool as qt
    >>> adj = {
    ...     0: {1: {}},
    ...     1: {2: {},
    ...         3: {}},
    ...     3: {0: {}}}
    >>> eTy = {0: {1: 1}, 1: {2: 2, 3: 4}, 3: {0: 1}}
    >>> # A loop will be added to vertex 2
    >>> g = qt.adjacency2graph(adj, edge_type=eTy)
    >>> ans = qt.graph2dict(g)
    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE
    [(0, {1: {'edge_type': 1}}),
     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}), 
     (2, {2: {'edge_type': 0}}),
     (3, {0: {'edge_type': 1}})]

    You can use a dict of lists to represent the adjacency list.

    >>> adj = {0 : [1], 1: [2, 3], 3: [0]}
    >>> g = qt.adjacency2graph(adj, edge_type=eTy)
    >>> ans = qt.graph2dict(g)
    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE
    [(0, {1: {'edge_type': 1}}),
     (1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),
     (2, {2: {'edge_type': 0}}),
     (3, {0: {'edge_type': 1}})]

    Alternatively, you could have this function adjust the edges that
    lead to terminal vertices by changing their edge type to 0:

    >>> # The graph is unaltered
    >>> g = qt.adjacency2graph(adj, edge_type=eTy, adjust=2)
    >>> ans = qt.graph2dict(g)
    >>> sorted(ans.items())     # doctest: +NORMALIZE_WHITESPACE
    [(0, {1: {'edge_type': 1}}),
     (1, {2: {'edge_type': 0}, 3: {'edge_type': 4}}),
     (2, {}),
     (3, {0: {'edge_type': 1}})]
    """

    if isinstance(adjacency, np.ndarray):
        adjacency = _matrix2dict(adjacency)
    elif isinstance(adjacency, dict):
        adjacency = _dict2dict(adjacency)
    else:
        msg = ("If the adjacency parameter is supplied it must be a "
               "dict, or a numpy.ndarray.")
        raise TypeError(msg)

    if edge_type is None:
        edge_type = {}
    else:
        if isinstance(edge_type, np.ndarray):
            edge_type = _matrix2dict(edge_type, etype=True)
        elif isinstance(edge_type, dict):
            edge_type = _dict2dict(edge_type)

    for u, ty in edge_type.items():
        for v, et in ty.items():
            adjacency[u][v]['edge_type'] = et

    g = nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph())
    adjacency = nx.to_dict_of_dicts(g)
    adjacency = _adjacency_adjust(adjacency, adjust, True)

    return nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph())
Example #37
0
    
    # Remove sequences below length threshold
    filteredIDs = nodeTable[nodeTable.LENGTH > minLength].ID
    filteredEdges = edgeTable[edgeTable.TARGET.isin(filteredIDs) & edgeTable.SOURCE.isin(filteredIDs)]

    # for each node, get the list of neighbours and their raw weights
    ndict = {}
    for n in filteredIDs:
        links = {}
        # the neighbours of node 'n' when listed as TARGETs
        for e in filteredEdges[filteredEdges.SOURCE == n][['TARGET', 'RAWWEIGHT']].itertuples():
            links[e[1]] = {'weight': float(e[2])}
        # the neighbours of node 'n' when listed as SOURCEs
        for e in filteredEdges[filteredEdges.TARGET == n][['SOURCE', 'RAWWEIGHT']].itertuples():
            links[e[1]] = {'weight': float(e[2])}
        ndict[n] = links

    # convert this dict of dicts into a graph object
    G = networkx.from_dict_of_dicts(ndict)

    if args.format == 'metis':
        write_metis(G, args.output[0], args.node_map)
    elif args.format == 'graphml':
        networkx.write_graphml(G, args.output[0])
    else:
        raise RuntimeError('unsupported graph format requested')

except RuntimeError as er:
    sys.stderr.write('Error: {0}\n'.format(er.message))
    sys.exit(1)
Example #38
0
def makeNetwork_fromdict(genedict):
    # create a networkx network from the dictionary of gene references
    G=nx.from_dict_of_dicts(genedict)
    return G
Example #39
0
g.edges()

# <codecell>

nx.draw(g)

# <codecell>

d = nx.to_dict_of_dicts(g)
# same as 
# nx.edges

# <codecell>

# Create a new graph from our dict_of_dicts
g2 = nx.from_dict_of_dicts(d)

# <codecell>

# dumps as a json object
import simplejson
simplejson.dumps(nx.to_dict_of_dicts(g))

# <codecell>

import pickle
s = pickle.dumps(g)
g3 = pickle.loads(s)
nx.draw(g3)

# <codecell>