Ejemplo n.º 1
0
    def test_unweighted(self):
        edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)]
        G = nx.DiGraph(edges)
        assert_equal(nx.dag_longest_path_length(G), 4)

        edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
        G = nx.DiGraph(edges)
        assert_equal(nx.dag_longest_path_length(G), 4)
Ejemplo n.º 2
0
    def test_unweighted(self):
        edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)]
        G = nx.DiGraph(edges)
        assert_equal(nx.dag_longest_path_length(G), 4)

        edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
        G = nx.DiGraph(edges)
        assert_equal(nx.dag_longest_path_length(G), 4)
Ejemplo n.º 3
0
    def test_unweighted(self):
        edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)]
        G = nx.DiGraph(edges)
        assert_equal(nx.dag_longest_path_length(G), 4)

        edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
        G = nx.DiGraph(edges)
        assert_equal(nx.dag_longest_path_length(G), 4)

        # test degenerate graphs
        G = nx.DiGraph()
        G.add_node(1)
        assert_equal(nx.dag_longest_path_length(G), 0)
Ejemplo n.º 4
0
    def test_unweighted(self):
        edges = [(1, 2), (2, 3), (2, 4), (3, 5), (5, 6), (5, 7)]
        G = nx.DiGraph(edges)
        assert nx.dag_longest_path_length(G) == 4

        edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 3), (1, 5), (3, 5)]
        G = nx.DiGraph(edges)
        assert nx.dag_longest_path_length(G) == 4

        # test degenerate graphs
        G = nx.DiGraph()
        G.add_node(1)
        assert nx.dag_longest_path_length(G) == 0
Ejemplo n.º 5
0
 def report_max_delay(
     self
 ):  #a function to report the maximum delay based on the longest path of the graph
     if self.g is None:
         self._update_load_capacitance()
         self._create_graph()
     return nx.dag_longest_path_length(self.g)
Ejemplo n.º 6
0
    def sta(self, tg):
        """A vanilla STA routine.
    
        Only annotates the arrival and required times of nodes.
        Required times of sinks are set to the length of the
        longest path, while the arrival times of sources are set
        to zero.
    
        Edge delay key is assumed to be "td" and arrival time
        is annotated with "ta" while required time is annotated
        with "tr".
    
        Parameters
        ----------
        tg : networkx.DiGraph
            Graph on which we want to run the STA.
 
        Returns
        -------
        Critical path delay.
        """

        cpd = nx.dag_longest_path_length(tg, weight="td")
        topo_nodes = list(nx.topological_sort(tg))
        rev_topo_nodes = reversed(topo_nodes)

        for v in topo_nodes:
            tg.node[v]["ta"] = max([tg.node[u]["ta"] + tg[u][v]["td"]\
                                    for u in tg.pred[v]] + [0])
        for u in rev_topo_nodes:
            tg.node[u]["tr"] = min([tg.node[v]["tr"] - tg[u][v]["td"]\
                                    for v in tg[u]] + [cpd])

        return cpd
Ejemplo n.º 7
0
def rbc(graph):
    """Rbc computation."""
    a = np.where(nx.adj_matrix(graph).toarray() > 0, 1, 0)
    g = nx.DiGraph(a)

    if nx.is_directed_acyclic_graph(g):
        k = nx.dag_longest_path_length(g)
        beta = 0.95

    else:
        lamb = max(np.linalg.eig(a)[0])
        if lamb != 0:
            beta = 0.95 / lamb
        else:
            beta = 0.95
        k = 10

    n = g.number_of_nodes()
    ones = np.ones(n)
    ba = beta * a
    ba_t = np.transpose(ba)

    x = np.zeros([n, k * 2])
    for i in range(1, k + 1):
        x[:, i - 1] = np.dot(np.linalg.matrix_power(ba, i), ones)
        x[:, i + k - 1] = np.dot(np.linalg.matrix_power(ba_t, i), ones)
    x_norm = normalize(x, axis=1)
    y = np.matmul(x_norm, np.transpose(x_norm))

    return nx.Graph(y)
Ejemplo n.º 8
0
def get_skip_lengths(system):
    """
    :param system: a system
    :return: length of skip connection for each projection in the system, i.e. the length
        of the longest path between the nodes
    """
    import networkx as nx

    g = system.make_graph()
    for u, v, d in g.edges(data=True):
        d['weight'] = -1

    lengths = {}
    for pop in system.populations:
        lengths[pop.name] = nx.bellman_ford(g, pop.name)

    result = []
    for p in system.projections:
        result.append(-lengths[p.origin.name][1][p.termination.name])

    # print some additional information ...
    print('longest skip connection: {}'.format(max(result)))
    for i in range(len(system.projections)):
        if result[i] == max(result):
            print([
                system.projections[i].origin.name,
                system.projections[i].termination.name
            ])
    print('longest path: {}'.format(nx.dag_longest_path_length(g)))
    print(nx.dag_longest_path(g))

    return result
Ejemplo n.º 9
0
def sim_lch(H, G, i, j):
    # medindo o menor caminho do grafo nao direcionado
    #G_undirected = G.to_undirected()

    #shortest_path = shortest_path_length(G_undirected, i, j)
    shortest_path = sim_spath(H, i, j)
    print('shortest_path:' + str(shortest_path))
    #print('*********************************************')
    #print('i'+str(i))
    #print('j'+str(j))

    # calcula profundidade do grafo
    Depth_ontology = nx.dag_longest_path_length(G)
    print('Depth_ontology: ' + str(Depth_ontology))
    # formula:
    Qlch = shortest_path / (2 * Depth_ontology)
    print('Quociente lch: ' + str(Qlch))
    if (i == j):
        sim_lch = 1.0
    else:
        sim_lch = -math.log10(Qlch)
    print('lch: ' + str(sim_lch))

    if i == j:
        sim_lch = 1.0

    #print('sim_lch'+str(sim_lch))

    return (sim_lch)
Ejemplo n.º 10
0
def main():
    args = parse_args()
    print("Making subgraph of significant hits in", args.infile)

    # Load heritability and graph
    targets = load_herits(args.infile, args.max_herit, args.pval_cutoff)
    graph = nx.read_gexf(args.graphfile)

    # Get sets of terminal significant ones and their ancestors
    ancestors = set()
    nodes = set(graph.nodes())
    added = 0
    for t in targets:
        if t not in nodes: continue  # Skip any hits that aren't targets
        added += 1
        for a in nx.ancestors(graph, t):
            ancestors.add(a)
    print("\tAdded ancestors of", added, "nodes to look for")

    # Make subgraph
    subgraph = graph.subgraph(targets | ancestors)
    print("Subgraph has", len(subgraph.nodes()), "nodes of the original",
          len(graph.nodes()))

    # Output
    subgraph = subgraph.reverse(
    )  #Flip so individual nodes have arrows toward their supercategory, not vice-versa
    nx.write_gexf(subgraph, args.outprefix + ".gexf")
    nx.draw_networkx(subgraph)
    plt.savefig(args.outprefix + ".png")

    # Debugging stuff
    print("Longest path legnth is", nx.dag_longest_path_length(graph))
    print("Longest path is", nx.dag_longest_path(graph))
Ejemplo n.º 11
0
def sim_lch(G, i, j):
    # medindo o menor caminho do grafo nao direcionado
    G_undirected = G.to_undirected()
    shortest_path = shortest_path_length(G_undirected, i, j)

    #print('*********************************************')
    #print('i'+str(i))
    #print('j'+str(j))
    #print('shortest_path'+str(shortest_path))
    # calcula profundidade do grafo
    Depth_ontology = nx.dag_longest_path_length(G)
    #print('Depth_ontology'+str(Depth_ontology))
    # formula:
    lch = shortest_path / (2 * Depth_ontology)
    #print('lch'+str(lch))
    if (lch == 0):
        sim_lch = 1.0
    else:
        sim_lch = -math.log10(lch)

    if i == j:
        sim_lch = 1.0

    #print('sim_lch'+str(sim_lch))

    return (sim_lch)
Ejemplo n.º 12
0
    def compute_criticalities(self):
        """Computes the exponentiated edge criticalities,
           used for movement weighing.
    
        Parameters
        ----------
        None

        Returns
        -------
        None
        """

        cpd = nx.dag_longest_path_length(self.tg, weight="td")
        topo_nodes = list(nx.topological_sort(self.tg))
        rev_topo_nodes = reversed(topo_nodes)

        for v in topo_nodes:
            self.tg.node[v]["ta"] = max([self.tg.node[u]["ta"] + self.tg[u][v]["td"]\
                                        for u in self.tg.pred[v]] + [0])
        for u in rev_topo_nodes:
            self.tg.node[u]["tr"] = min([self.tg.node[v]["tr"] - self.tg[u][v]["td"]\
                                        for v in self.tg[u]] + [cpd])

        for u, v in self.tg.edges():
            slack = self.tg.node[v]["tr"] - self.tg.node[u]["ta"] - self.tg[u][
                v]["td"]
            crit = 1 - float(slack) / cpd
            self.tg[u][v]["t_weight"] = crit**CRIT_EXP
Ejemplo n.º 13
0
def build_graph(root, current_location, max_depth):

    if len(queue) == 0:
        return
    longest_depth = nx.dag_longest_path_length(graph, root)
    if longest_depth > max_depth:
        path = nx.dag_longest_path(graph, root)
        graph.remove_node(path[-1])
        return
    char_system_info_req = esiapp.op['get_universe_systems_system_id'](
        system_id=current_location)
    char_system_info = esiclient.request(char_system_info_req).data
    system_stargates = char_system_info['stargates']

    for stargate in system_stargates:
        char_system_stargate = esiapp.op['get_universe_stargates_stargate_id'](
            stargate_id=stargate)
        char_system_stargate = esiclient.request(char_system_stargate).data
        stargate_destination = str(
            char_system_stargate['destination']['system_id'])
        nodes = list(graph.nodes)

        # We want to avoid cycles if we want to use dag_longest_path_length, so we want to work with destination that
        # are not in the graph yet
        if (stargate_destination not in nodes):
            print('{} -> {}'.format(current_location, stargate_destination))
            graph.add_edge(current_location, stargate_destination)

        longest_depth = nx.dag_longest_path_length(graph, root)
        if longest_depth > max_depth:
            path = nx.dag_longest_path(graph, root)
            graph.remove_node(path[-1])
            return
        else:
            queue.append(stargate_destination)

    queue.pop(0)

    longest_depth = nx.dag_longest_path_length(graph, root)
    print(longest_depth)
    if longest_depth > max_depth:
        path = nx.dag_longest_path(graph, root)
        graph.remove_node(path[-1])
        return

    stargate_destination = queue[0]
    build_graph(root, stargate_destination, max_depth)
Ejemplo n.º 14
0
def topology_stages(logical_plan):
    """Return the number of stages in a logical plan."""
    graph = networkx.DiGraph(
        (input_info["component_name"], bolt_name)
        for bolt_name, bolt_info in logical_plan.get("bolts", {}).items()
        for input_info in bolt_info["inputs"])
    # this is is the same as "diameter" if treating the topology as an undirected graph
    return networkx.dag_longest_path_length(graph)
Ejemplo n.º 15
0
def topology_stages(logical_plan: TopologyInfoLogicalPlan) -> int:
    """Return the number of stages in a logical plan."""
    graph = networkx.DiGraph(
        (input_info.component_name, bolt_name)
        for bolt_name, bolt_info in logical_plan.bolts.items()
        for input_info in bolt_info.inputs)
    # this is is the same as "diameter" if treating the topology as an undirected graph
    return networkx.dag_longest_path_length(graph)
Ejemplo n.º 16
0
def dijkstraPathExample(fileName="./" + SUBDIRNAME + "/dijkstraSP.png"):
    print()
    G = nx.DiGraph()
    G.add_weighted_edges_from([
        (0, 1, 5.0),
        (0, 4, 9.0),
        (0, 7, 8.0),
        (1, 2, 12.0),
        (1, 3, 15.0),
        (1, 7, 4.0),
        (2, 3, 3.0),
        (2, 6, 11.0),
        (3, 6, 9.0),
        (4, 5, 4.0),
        (4, 6, 20.0),
        (4, 7, 5.0),
        (5, 2, 1.0),
        (5, 6, 13.0),
        (7, 5, 6.0),
        (7, 2, 7.0),
    ])

    sourceNode = 0
    sp = nx.single_source_dijkstra_path(G, sourceNode)
    spL = nx.single_source_dijkstra_path_length(G, sourceNode)

    finalEdgeTo = {}

    print('Shortest paths and weights')
    print('Node\tedgeTo\tWeight')
    for node in sorted(sp):
        # if (node != sourceNode):
        print(str(node) + '\t' + str(sp[node]) + '\t\t' + str(spL[node]))
        if (node != sourceNode):
            finalEdgeTo[(sp[node][-2], sp[node][-1])] = {
                "sp" + str(sourceNode): 'sp' + str(sourceNode)
            }
            # print (str(node) + '\t' + str((sp[node][-2], sp[node][-1]))+'\t'+str(spL[node]))

    nx.set_edge_attributes(G, finalEdgeTo)
    print('updated graph')
    print(G.edges.data())

    print('Calculating longest path using Topological sort if DAG')
    print('Is DAG: ' + str(nx.is_directed_acyclic_graph(G)))
    if (nx.is_directed_acyclic_graph(G)):
        print('Longest Path')
        print(nx.dag_longest_path(G))
        print('Longest Path Weight')
        print(nx.dag_longest_path_length(G))

    labels = nx.get_edge_attributes(G, 'sp0')
    pos = nx.spring_layout(G)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
    nx.draw(G, pos, with_labels=True, font_weight='bold')
    print("Saving file to " + str(fileName))
    plt.savefig(fileName)
    print()
Ejemplo n.º 17
0
def find_max_distance(wn, pos, relation):
    graph = DiGraph()
    for synset_id, synset in wn.dat(pos).items():
        graph.add_node(synset_id)
        for id_of_synset_in_relation, relation_name in synset.ilrs:
            if relation_name == relation:
                graph.add_node(id_of_synset_in_relation)
                graph.add_edge(id_of_synset_in_relation, synset.wnid)
    return dag_longest_path_length(graph)
Ejemplo n.º 18
0
def add_longest_ancestor_distance(graph: nx.DiGraph):
    """Add the longest ancestor distance to all nodes in the graph."""
    log.info('longest path length: {}'.format(
        max(nx.dag_longest_path_length(graph) + 1, 1)))
    for node in nx.topological_sort(graph):
        max_dist_predecessors = [graph.nodes[predecessor]['max_pred_dist'] + 1
                                 for predecessor in graph.predecessors(node)]
        graph.nodes[node]['max_pred_dist'] = max(max_dist_predecessors,
                                                default=0)
Ejemplo n.º 19
0
def build_graph(root, current_location, max_depth):

    if len(queue) == 0:
        return
    longest_depth = nx.dag_longest_path_length(graph, root)
    if longest_depth > max_depth:
        path = nx.dag_longest_path(graph, root)
        graph.remove_node(path[-1])
        return
    system_stargates = []
    for stargate in data['stargates']:
        curr_stargate = data['stargates'][stargate]
        if curr_stargate['system_id'] == int(current_location):
            system_stargates.append(curr_stargate)

    for stargate in system_stargates:
        stargate_destination = str(stargate['destination']['system_id'])
        nodes = list(graph.nodes)

        # We want to avoid cycles if we want to use dag_longest_path_length, so we want to work with destination that
        # are not in the graph yet
        if (stargate_destination not in nodes):
            print('{} -> {}'.format(current_location, stargate_destination))
            graph.add_edge(current_location, stargate_destination)

        longest_depth = nx.dag_longest_path_length(graph, root)
        if longest_depth > max_depth:
            path = nx.dag_longest_path(graph, root)
            graph.remove_node(path[-1])
            return
        else:
            queue.append(stargate_destination)

    queue.pop(0)

    longest_depth = nx.dag_longest_path_length(graph, root)
    print(longest_depth)
    if longest_depth > max_depth:
        path = nx.dag_longest_path(graph, root)
        graph.remove_node(path[-1])
        return

    stargate_destination = queue[0]
    build_graph(root, stargate_destination, max_depth)
Ejemplo n.º 20
0
def swc_stats(filename, scale='mum', log=False):
    a = pd.read_csv(filename, sep=' ', header=None, comment='#')
    X = a.values
    if X.shape[1] > 7:
        X = X[:, X.shape[1] - 7:]
    G = nx.DiGraph()
    distance = 0
    surface_area = 0
    volume = 0
    for i in range(X.shape[0]):
        if X[i, 6] != -1:
            G.add_node(i)
            parent = np.where(X[:, 0] == X[i, 6])[0][0]
            x_parent = X[parent, 2:5]
            x = X[i, 2:5]
            h = np.sqrt(np.sum(np.square(x_parent - x)))
            G.add_edge(parent, i, weight=h)
            distance += h
            r_parent = X[parent, 5]
            r = X[i, 5]
            surface_area += np.pi * (r + r_parent) * np.sqrt(
                np.square(r - r_parent) + np.square(h))
            volume += np.pi / 3. * (r * r + r * r_parent +
                                    r_parent * r_parent) * h

    XX = X[:, 2:5]
    w = np.abs(np.max(XX[:, 0]) - np.min(XX[:, 0]))
    h = np.abs(np.max(XX[:, 1]) - np.min(XX[:, 1]))
    d = np.abs(np.max(XX[:, 2]) - np.min(XX[:, 2]))
    bifurcations = len(X[:, 6]) - len(np.unique(X[:, 6]))
    max_euclidean_dist = np.max(pdist(XX))
    max_path_dist = nx.dag_longest_path_length(G)
    if log == True:
        print('Total Length: ', distance, scale)
        print('Total Surface Area: ', surface_area, scale + '^2')
        print('Total Volume: ', volume, scale + '^3')
        print('Maximum Euclidean Distance: ', max_euclidean_dist, scale)
        print('Width (Orientation Variant): ', w, scale)
        print('Height (Orientation Variant): ', h, scale)
        print('Depth (Orientation Variant): ', d, scale)
        print('Average Diameter: ', 2 * np.mean(X[:, 5]), scale)
        print('Number of Bifurcations:', bifurcations)
        print('Max Path Distance: ', max_path_dist, scale)
    results = {}
    results['Total Length'] = distance
    results['Total Surface Area'] = surface_area
    results['Total Volume'] = volume
    results['Maximum Euclidean Distance'] = max_euclidean_dist
    results['Width (Orientation Variant)'] = w
    results['Height (Orientation Variant)'] = h
    results['Depth (Orientation Variant)'] = d
    results['Average Diameter'] = 2 * np.mean(X[:, 5])
    results['Number of Bifurcations'] = bifurcations
    results['Max Path Distance'] = max_path_dist
    return results
Ejemplo n.º 21
0
def test_changing_shape():
    """Ensure the node adding/removing example works."""
    random.seed(42)
    engine = shape_changing_graph.create_engine()

    # should be 3x3 before
    print(list(engine.graph.degree()))
    max_K = max(v for k, v in engine.graph.degree())
    assert max_K == shape_changing_graph.GRAPH_K + 1
    max_D = dag_longest_path_length(engine.graph) + 1
    assert max_D == shape_changing_graph.GRAPH_D

    for _ in zip(range(100), engine):
        pass

    # shape should change
    max_K = max(v for k, v in engine.graph.degree())
    assert max_K != shape_changing_graph.GRAPH_K + 1
    max_D = dag_longest_path_length(engine.graph) + 1
    assert max_D != shape_changing_graph.GRAPH_D
Ejemplo n.º 22
0
    def depth(self):
        """Return the circuit depth.
        Returns:
            int: the circuit depth
        Raises:
            DAGCircuitError: if not a directed acyclic graph
        """
        if not nx.is_directed_acyclic_graph(self._multi_graph):
            raise DAGCircuitError("not a DAG")

        depth = nx.dag_longest_path_length(self._multi_graph) - 1
        return depth if depth != -1 else 0
Ejemplo n.º 23
0
def graph_stats(G):
    total_nodes = G.number_of_nodes()
    # print('Total nodes is %d' % total_nodes)
    total_edges = G.number_of_edges()
    # print('Total edges is %d' % total_edges)

    biomaterialNodes = [
        x for x, y in G.nodes(data=True) if y['entity_type'] == "biomaterial"
    ]
    biomaterialNodes.sort()
    biomaterial_out_degrees = [x[1] for x in G.out_degree(biomaterialNodes)]
    # print('Biomaterial node outdegrees are: ', *biomaterial_out_degrees)
    biomaterial_in_degrees = [x[1] for x in G.in_degree(biomaterialNodes)]
    # print('Biomaterial node indegrees are: ', *biomaterial_in_degrees)

    processNodes = [
        x for x, y in G.nodes(data=True) if y['entity_type'] == "process"
    ]
    processNodes.sort()
    process_out_degrees = [x[1] for x in G.out_degree(processNodes)]
    # print('Process node outdegrees are: ', *process_out_degrees)
    process_in_degrees = [x[1] for x in G.in_degree(processNodes)]
    # print('Process node indegrees are: ', *process_in_degrees)

    fileNodes = [
        x for x, y in G.nodes(data=True) if y['entity_type'] == "file"
    ]
    fileNodes.sort()
    file_out_degrees = [x[1] for x in G.out_degree(fileNodes)]
    # print('File node outdegrees are: ', *file_out_degrees)
    file_in_degrees = [x[1] for x in G.in_degree(fileNodes)]
    # print('File node indegrees are: ', *file_in_degrees)

    max_depth = nx.dag_longest_path_length(G)
    # print('Max depth is %d' % max_depth)
    # print('\n')

    features = {
        'totalNodes': total_nodes,
        'totalEdges': total_edges,
        'maxDepth': max_depth,
        'nodeList': ",".join(str(x) for x in sorted(list(set(G)))),
        'biomaterialOutdegrees':
        ",".join(str(x) for x in biomaterial_out_degrees),
        'biomaterialIndegrees':
        ",".join(str(x) for x in biomaterial_in_degrees),
        'processOutdegrees': ",".join(str(x) for x in process_out_degrees),
        'processIndegrees': ",".join(str(x) for x in process_in_degrees),
        'fileOutdegrees': ",".join(str(x) for x in file_out_degrees),
        'fileIndegrees': ",".join(str(x) for x in file_in_degrees)
    }

    return features
Ejemplo n.º 24
0
def sim_lch(G, node1, node2):
    # medindo o menor caminho do grafo nao direcionado
    G_undirected = G.to_undirected()
    shortest_path = nx.shortest_path_length(G_undirected, node1, node2)

    # calcula profundidade do grafo
    Depth_ontology = nx.dag_longest_path_length(G)

    # formula:
    sim_lch = -math.log( shortest_path / (2 * Depth_ontology))

    return sim_lch
Ejemplo n.º 25
0
 def _bfs_tree(G):
     # twice BFS in undirected acyclic graph (Tree) to find endnodes
     # bfs for longest path is performed in Directed Tree
     endnodes = [x for x in G.nodes() if G.degree(x) == 1]
     DiTree1 = nx.traversal.bfs_tree(G, endnodes[0])
     SG1 = G.subgraph(nx.dag_longest_path(DiTree1, weight=weight))
     new_root = [
         x for x in SG1.nodes() if G.degree(x) == 1 and x != endnodes[0]
     ][0]
     DiTree2 = nx.traversal.bfs_tree(SG1, new_root)
     SG2 = G.subgraph(nx.dag_longest_path(DiTree2, weight=weight))
     return SG2, nx.dag_longest_path_length(DiTree2)
Ejemplo n.º 26
0
def path_entropy(graph, backward=False):
    u"""Compute the average path entropy of a graph.

    There is a more efficient algorithm defined in the paper. It is only
    partially implemented so far. This is the naive aproach.

    Corominas-Murtra, B., Goñi, J., Solé, R. V, & Rodríguez-Caso, C. (2013).
    "On the origins of hierarchy in complex networks". PNAS, 110(33), 13316–21.
    """
    gc = nx.condensation(graph)
    L = nx.dag_longest_path_length(gc)
    B = nx.adj_matrix(gc)
    return _path_entropy(gc, B, L, backward=backward)
Ejemplo n.º 27
0
    def get_depth(self):
        """Depth of the quantum circuit (longest path in the DAG)."""
        # If there are no operations in the circuit, the depth is 0
        if not self.operations:
            self._depth = 0

        # If there are operations but depth is uncomputed, compute the truncated graph
        # with only the operations, and return the longest path + 1 (since the path is
        # expressed in terms of edges, and we want it in terms of nodes).
        if self._depth is None and self.operations:
            if self._operation_graph is None:
                self._operation_graph = self.graph.subgraph(self.operations)
                self._depth = nx.dag_longest_path_length(self._operation_graph) + 1

        return self._depth
Ejemplo n.º 28
0
    def add_blocking_path(self, subg):
        """Adds a blocking path to a subgraph, modeling the longest
        path not in the subgraph.

        Parameters
        ----------
        subg : networkx.DiGraph
            Subgraph to which the blocking path is to be added.

        Returns
        -------
        networkx.DiGraph
            Subgraph with the added blocking path.
        """

        cpd = nx.dag_longest_path_length(self.graph, weight="td")
        blocked = subg.copy()
        complement = self.graph.subgraph(
            [u for u in self.graph if not u in subg])
        external_cpd = nx.dag_longest_path_length(complement, weight="td")

        dummy_cnt = 0
        while blocked.has_node("dummy_%d" % dummy_cnt):
            dummy_cnt += 1
        u = "dummy_%d" % dummy_cnt
        blocked.add_node(u, ta = 0, tr = cpd - external_cpd,\
                         coords = NodeCls(0, 0))
        while blocked.has_node("dummy_%d" % dummy_cnt):
            dummy_cnt += 1
        v = "dummy_%d" % dummy_cnt
        blocked.add_node(v, ta = external_cpd, tr = cpd,\
                         coords = NodeCls(0, 0))

        blocked.add_edge(u, v, td=external_cpd)

        return blocked
Ejemplo n.º 29
0
 def parent_graph_statistic(self, G):
     if len(G.edges()) == 0:
         return
     in_degree, out_degree = G.in_degree, G.out_degree
     max_in_degree, max_out_degree = max(
         in_degree, key=lambda x: x[1]), max(out_degree, key=lambda x: x[1])
     print('max_in_degree: ', max_in_degree)
     print('max_out_degree: ', max_out_degree)
     n_nodes, n_edges = G.number_of_nodes(), G.number_of_edges()
     print('number_of_nodes: ', n_nodes)
     print('number_of_edges: ', n_edges)
     print('avg_degree: ', 2 * n_edges / n_nodes)
     print('dag_longest_path_length: ', nx.dag_longest_path_length(G))
     cc_list = list(nx.weakly_connected_components(G))
     self.connected_components_statistic(cc_list)
     self.cc_list_source_statistic(cc_list)
Ejemplo n.º 30
0
def function(g):

    if nx.dag_longest_path_length(g.network) > 2:
        print("skip")
        return 0

    pheno = g.get_phenotype()

    nodes = cart.get_nodes(int(math.sqrt(np.size(pheno))),
                           two_dimensional,
                           symmetric,
                           input_nodes=True)
    output_nodes = cart.get_nodes(int(math.sqrt(np.size(pheno))),
                                  two_dimensional,
                                  symmetric,
                                  input_nodes=False)

    total_error = 0

    #for i in range(256):
    # set input values and activate network

    result = np.zeros((int(math.sqrt(np.size(pheno))), 256))

    input_vector = np.zeros((int(math.sqrt(np.size(pheno))), 256))

    for j in range(len(nodes)):
        input_vector[nodes[j]] += image_mat[j]

    # depth is 4
    for j in range(4):
        result = np.matmul(np.transpose(pheno), input_vector + result)
        result = activation(result)

    output_vector = np.zeros((2, 256))

    for j in range(len(output_nodes)):
        output_vector[j, :] += result[output_nodes[j]]

    output_vector = np.clip(output_vector, 0, 1)

    # calculate the error for this sample
    total_error = np.sum(np.abs(output_vector - label_mat))

    return 1000.0 / (1.0 + total_error**2)
Ejemplo n.º 31
0
    def depth(self, local: bool = True) -> int:
        """Return the circuit depth.

        Args:
            local:  If True include local one-qubit gates in depth
                calculation. Else return the multi-qubit gate depth.
        """
        G = self.graph
        if not local:
            def remove_local(dagc: DAGCircuit) \
                    -> Generator[Operation, None, None]:
                for elem in dagc:
                    if dagc.graph.degree[elem] > 2:
                        yield elem

            G = DAGCircuit(remove_local(self)).graph

        return nx.dag_longest_path_length(G) - 1
Ejemplo n.º 32
0
 def _analyze_longest_chain(graph, components):
     components_by_longest_path = [
         (nx.dag_longest_path_length(component), component)
         for component in components
     ]
     components_by_longest_path.sort(key=lambda elm: elm[0],
                                     reverse=True)
     print("### Longest chain\n\nlength: %d" %
           components_by_longest_path[0][0]
           if len(components_by_longest_path) else 0,
           end="\n\n",
           flush=True)
     for component in components_by_longest_path:
         if component[0] < components_by_longest_path[0][0]:
             break
         root = self.get_digraph_root(component[1])
         print("* %s (%s)" % (graph.nodes[root]['label'], root),
               flush=True)
     print("", flush=True)
Ejemplo n.º 33
0
def fill_parent_node(input_matrix, label_list, graph):
    """
        If child node will be penalized, the parent node's will be penalized
    """
    child_index = get_child_index_list(graph, label_list)

    m = np.empty(input_matrix.shape, dtype=int)
    for j in range(nx.dag_longest_path_length(graph)):
        if j == 0:
            matrix = input_matrix
        else:
            matrix = m

        for i, c in enumerate(child_index):
            if c == []:
                v = matrix[:, i]
            else:
                v = np.where(np.any(matrix[:, c], axis=1)==1, 1, matrix[:,i])
            m[:, i] = v
    return m
Ejemplo n.º 34
0
 def test_weighted(self):
     edges = [(1, 2, -5), (2, 3, 1), (3, 4, 1), (4, 5, 0), (3, 5, 4),
              (1, 6, 2)]
     G = nx.DiGraph()
     G.add_weighted_edges_from(edges)
     assert_equal(nx.dag_longest_path_length(G), 5)