How to use the networkx.DiGraph function in networkx

To help you get started, we’ve selected a few networkx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bboczeng / Nyxar / backtest / BackExchange.py View on Github external
def fetch_balance_in(self, target: str, fee: bool=False) -> float:
        """
        Return the value of current portfolio all in target asset. The transfer rate is computed from the most
        profitable way possible. If there is no possible way to transfer an asset to the target one, an exception will
        be raised.

        Args:
            target: Name of the target asset
            fee: If exchange fee is considered when computing the portfolio value. Defaults to False.

        Returns:
            Portfolio value
        """

        di_graph = nx.DiGraph()
        multiplier = 1.0 - self._fee_rate / 100.0 if fee else 1.0

        for symbol in self._symbols:
            quote_name = self._quotes.get_ticker(symbol).quote_name
            base_name = self._quotes.get_ticker(symbol).base_name

            di_graph.add_edge(quote_name, base_name,
                              weight=-math.log(multiplier * self.__get_price(symbol, self._sell_price)))
            di_graph.add_edge(base_name, quote_name,
                              weight=math.log(self.__get_price(symbol, self._buy_price) / multiplier))

        balance = 0
        for asset in self._total_balance:
            if self._total_balance[asset]:
                if asset == target:
                    balance += self._total_balance[asset]
github jasperlinthorst / reveal / reveal / chain.py View on Github external
tree=IntervalTree()
    
    for fasta in fastas:
        sample=os.path.basename(fasta)
        idx.addsample(sample)
        for i,t in enumerate(fasta_reader(fasta)):
            name,seq=t
            f,t=idx.addsequence(seq)
            tree[f:t]=sample
            if i==1:
                logging.error("Can't handle multi-fasta input. Use single fasta file per sequence.")
                sys.exit(1)
    
    idx.construct()
    
    G=nx.DiGraph()
    G.graph['paths']=idx.samples
    G.graph['path2id']=dict()
    G.graph['id2path']=dict()

    for sid,sample in enumerate(G.graph['paths']):
        G.graph['path2id'][sample]=sid
        G.graph['id2path'][sid]=sample
    
    k=len(idx.samples)
    
    T=idx.T
    
    istart=tuple([-1]+[sep for sep in idx.nsep]) #no matches possible at these loci
    iend=tuple([sep for sep in idx.nsep]+[idx.n-1]) #loci of sentinels, also no matches possible
    startcoords=tuple([0]+[sep+1 for sep in idx.nsep])
    G.add_node(istart,l=0)
github PacificBiosciences / FALCON / src / py / generate_string_bundle2.py View on Github external
x = max( [len(s[1]) for s in u_edges[ (v,w) ] ] )
        if x > max_weight:
            max_weight = x
            
    in_edges = {}
    out_edges = {}
    for v, w in u_edges:
        in_edges.setdefault(w, []) 
        out_edges.setdefault(w, []) 
        in_edges[w].append( (v, w) )

        out_edges.setdefault(v, [])
        in_edges.setdefault(v, [])
        out_edges[v].append( (v, w) )

    u_graph = nx.DiGraph()
    for v,w in u_edges:

        u_graph.add_edge(v, w, n_weight = max_weight - max( [len(s[1]) for s in  u_edges[ (v,w) ] ] ) )
    
    bundle_index = 0
    G = u_graph.copy()
    while len(G) > 0:
        
        root_nodes = set() 
        for n in G: 
            if G.in_degree(n) != 1 or G.out_degree(n) !=1 : 
                root_nodes.add(n) 
        
        if len(root_nodes) == 0:  
            root_nodes.add( G.nodes()[0] )
github networkx / networkx / networkx / algorithms / isomorphism / temporalisomorphvf2.py View on Github external
def get_pred_dates(self, Gx, Gx_node, core_x, pred):
        """
        Get the dates of edges from predecessors.
        """
        pred_dates = []
        if isinstance(Gx, nx.DiGraph):  # Graph G[u][v] returns the data dictionary.
            for n in pred:
                pred_dates.append(Gx[n][Gx_node][self.temporal_attribute_name])
        else:  # MultiGraph G[u][v] returns a dictionary of key -> data dictionary.
            for n in pred:
                for edge in Gx[n][Gx_node].values():  # Iterates all edge data between node pair.
                    pred_dates.append(edge[self.temporal_attribute_name])
        return pred_dates
github THUDM / ProNE / proNE.py View on Github external
def __init__(self, graph_file, emb_file1, emb_file2, dimension):
		self.graph = graph_file
		self.emb1 = emb_file1
		self.emb2 = emb_file2
		self.dimension = dimension

		self.G = nx.read_edgelist(self.graph, nodetype=int, create_using=nx.DiGraph())
		self.G = self.G.to_undirected()
		self.node_number = self.G.number_of_nodes()
		matrix0 = scipy.sparse.lil_matrix((self.node_number, self.node_number))

		for e in self.G.edges():
			if e[0] != e[1]:
				matrix0[e[0], e[1]] = 1
				matrix0[e[1], e[0]] = 1
		self.matrix0 = scipy.sparse.csr_matrix(matrix0)
		print(matrix0.shape)
github sarguido / networkx-tutorial / materials / client / graph.py View on Github external
import networkx as nx
#import networkx.readwrite as rw
#from networkx.readwrite import json_graph
import json

edgelist_txt = 'retweet_relationships/retweets.txt'

# json_filename = 'graph.json'

ge = nx.read_edgelist(edgelist_txt, create_using=nx.DiGraph())
# tree = nx.read_edgelist('tree_edges.txt', create_using=nx.DiGraph())
github jambler24 / GenGraph / readAligner.py View on Github external
print(allAlignedReads[t]['nodescoveredbyread'])
            if len(inversionNodes) == 0:
                print('None')
            else:
                print(inversionNodes)
            print(allAlignedReads[t]['alignmentstartpositioninfirstnode'])
            print(allAlignedReads[t]['alignementendpositioninlastnode'])
            print(allAlignedReads[t]['percentageofqueryaligned'])
            print(allAlignedReads[t]['percentageofalignedreadtograph'])
            print()

        return allAlignedReads


if __name__ == '__main__':
    G = nx.DiGraph()
    G.add_node('Aln_1_1', ids='H37Rv,H37Rv1,H37Rv2', H37Rv_leftend=1, H37Rv_rightend=100, H37Rv1_leftend=1,
               H37Rv1_rightend=100, H37Rv2_leftend=1, H37Rv2_rightend=100,
               sequence='TTGACCGATGACCCCGGTTCAGGCTTCACCACAGTGTGGAACGCGGTCGTCTCCGAACTTAACGGCGACCCTAAGGTTGACGACGGACCCAGCAGTGATG')
    G.add_node('Aln_1_2', ids='H37Rv,H37Rv1,H37Rv2', H37Rv_leftend=101, H37Rv_rightend=200, H37Rv1_leftend=101,
               H37Rv1_rightend=200, H37Rv2_leftend=-101, H37Rv2_rightend=-200,
               sequence='CTAATCTCAGCGCTCCGCTGACCCCTCAGCAAAGGGCTTGGCTCAATCTCGTCCAGCCATTGACCATCGTCGAGGGGTTTGCTCTGTTATCCGTGCCGAG')
    G.add_node('Aln_1_3', ids='H37Rv,H37Rv1,H37Rv2', H37Rv_leftend=201, H37Rv_rightend=100, H37Rv1_leftend=201,
               H37Rv1_rightend=1000, H37Rv2_leftend=201, H37Rv2_rightend=1000,
               sequence='CAGCTTTGTCCAAAACGAAATCGAGCGCCATCTGCGGGCCCCGATTACCGACGCTCTCAGCCGCCGACTCGGACATCAGATCCAACTCGGGGTCCGCATCGCTCCGCCGGCGACCGACGAAGCCGACGACACTACCGTGCCGCCTTCCGAAAATCCTGCTACCACATCGCCAGACACCACAACCGACAACGACGAGATTGATGACAGCGCTGCGGCACGGGGCGATAACCAGCACAGTTGGCCAAGTTACTTCACCGAGCGCCCGCACAATACCGATTCCGCTACCGCTGGCGTAACCAGCCTTAACCGTCGCTACACCTTTGATACGTTCGTTATCGGCGCCTCCAACCGGTTCGCGCACGCCGCCGCCTTGGCGATCGCAGAAGCACCCGCCCGCGCTTACAACCCCCTGTTCATCTGGGGCGAGTCCGGTCTCGGCAAGACACACCTGCTACACGCGGCAGGCAACTATGCCCAACGGTTGTTCCCGGGAATGCGGGTCAAATATGTCTCCACCGAGGAATTCACCAACGACTTCATTAACTCGCTCCGCGATGACCGCAAGGTCGCATTCAAACGCAGCTACCGCGACGTAGACGTGCTGTTGGTCGACGACATCCAATTCATTGAAGGCAAAGAGGGTATTCAAGAGGAGTTCTTCCACACCTTCAACACCTTGCACAATGCCAACAAGCAAATCGTCATCTCATCTGACCGCCCACCCAAGCAGCTCGCCACCCTCGAGGACCGGCTGAGAACCCGCTTTGAGTGGGGGCTGATCACTGACGTACAACCACCCG')
    G.add_edge('Aln_1_1', 'Aln_1_2')
    G.add_edge('Aln_1_2', 'Aln_1_3')
    graph_obj = import_gg_graph('./TestGraphs/mix_of_snps.xml')
    alignerGraph = Aligner(G)
    alignerGraph.debruin_read_alignment('CCCCAGTCGCCTCGCGACTCTAATCCAGCTTTGCCAAACGAAATCGAGCG',7)
    #nx.draw(graph_obj, with_labels=True)
github MUSoC / Visualization-of-popular-algorithms-in-Python / Topological Sort / topological_sort.py View on Github external
def CreateResultGraph(sorted_list):
	D = nx.DiGraph()
	for i in range(len(sorted_list)-1): 
	 	D.add_edge(sorted_list[i], sorted_list[i+1]) 
	pos = nx.spring_layout(D)
	val_map = {}
	val_map[sorted_list[0]] = 'green'
	val_map[sorted_list[len(sorted_list)-1]] = 'red'
	values = [val_map.get(node, 'blue') for node in D.nodes()]
	nx.draw(D, pos, with_labels = True, node_color =values)
github popgenmethods / momi2 / momi / demography.py View on Github external
def _get_graph_structure(self):
        # returns just the graph structure, i.e. the "non-differentiable" part of the Demography
        # use this with _get_differentiable_part()
        # to re-organize certain computations during automatic differentiation
        ret = nx.DiGraph()
        ret.add_nodes_from(self._G.nodes(data=False))
        ret.add_edges_from(self._G.edges(data=False))

        for v, d in self._G.nodes(data=True):
            if 'lineages' in d:
                ret.node[v]['lineages'] = d['lineages']

        ret.graph['events_as_edges'] = tuple(self._G.graph['events_as_edges'])
        ret.graph['sampled_pops'] = self.sampled_pops

        return ret
github Kappa-Dev / ReGraph / _downloads / bd26f0f4352138538547dba669d28dda / tutorial2_ex2.py View on Github external
_, rhs_instance = hierarchy.rewrite("ag", cloning_rule, instances[0])

print("\tResult of rewriting with rule 1: ")
plot_instance(hierarchy.graph["ag"], cloning_rule.rhs, rhs_instance,
              parent_pos=ag_pos)
plot_graph(hierarchy.graph["n1"],
           title="Graph 'n1' after rewriting with rule 1", parent_pos=n1_pos)
print("\t\tUpdated typing 'n1'->'ag': ", hierarchy.edge["n1"]["ag"].mapping)
print("\t\tUpdated typing 'ag'->'mm': ", hierarchy.edge["ag"]["mm"].mapping)


# create a rule that adds new nodes
p = nx.DiGraph()
add_nodes_from(p, ["B"])

l = nx.DiGraph()
add_nodes_from(l, ["B"])

r = nx.DiGraph()
add_nodes_from(r, ["B", "B_res_1", "X", "Y"])
add_edges_from(r, [("B_res_1", "B")])

rule = Rule(p, l, r)
print("\nRule 2: contains addition of nodes ")
print("----------------------------------")
print(rule)
plot_rule(rule, title="Rule 2: contains addition of nodes")

instance = {"B": "B"}
plot_instance(
    hierarchy.graph["n1"], rule.lhs, instance,
    title="Graph 'n1' with the instance of a pattern highlighted",