Exemplo n.º 1
0
def is_branch_decomposition(graph, initial_nodes):
    if graph.number_of_nodes() != initial_nodes:
        print "nodes do not match", graph.number_of_nodes(), initial_nodes
        return False
    set_degree = set(dict(graph.degree()).values())
    print "connected?", nx.is_connected(graph), "cycles", nx.cycle_basis(graph)
    if set_degree != {1, 3}:
        print "degrees not matched"
        return False
    if not nx.is_connected(graph):
        print "not connected"
        return False
    if nx.cycle_basis(graph):
        print "has cycles"
        return False
    for node in graph.nodes():
        neigh = list(graph.neighbors(node))
        if len(neigh) == 3:
            cut1 = set(graph.edge[node][neigh[0]])
            cut2 = set(graph.edge[node][neigh[1]])
            cut3 = set(graph.edge[node][neigh[2]])
            if cut1.issubset(cut2 | cut3) == False or cut3.issubset(
                    cut2 | cut1) == False or cut2.issubset(cut1
                                                           | cut3) == False:
                print "different cuts"
                return False
    return True
Exemplo n.º 2
0
    def connected_words2(self):
        word_graph = self.words_graph()
        #graph = nx.connected_component_subgraphs(graph)[0]

        #TODO: which condition to use?
        #if len(graph.nodes() > 7):

        # for each connected component:
        # if maximum distance between any 2 nodes is <= 4, return connected component
        # otherwise, find cycles and use them + the remaining nodes each with their corresponding cycle
        # (the first node adjacent to it that is in the final components list)
        #TODO: maybe pick the list to which to attach remaining nodes better

        # For grouping lower level categories we allow larger groups
        if (self.level == 1):
            path_limit = 4
        else:
            path_limit = 7

        res_components = []
        for graph in nx.connected_component_subgraphs(word_graph):

            # if connected component's diameter is smaller than limit add it as is

            # get maximum length
            lengths = nx.all_pairs_shortest_path_length(graph)
            m = 0
            for subdict in lengths.itervalues():
                for value in subdict.itervalues():
                    if value > m:
                        m = value

            # if diameter is lower than a limit or there are no cycles (so the else branch wouldn't work)
            if m <= path_limit or not nx.cycle_basis(graph):
                res_components.append(graph.nodes())
            else:
                # else try to remove bridges
                word_groups = []
                subgraphs = nx.cycle_basis(graph)
                # add the remaining nodes
                subgraphs_nodes = [node for subgraph in subgraphs for node in subgraph]
                remaining_nodes = [node for node in graph.nodes() if node not in subgraphs_nodes]

                 # # find largest cycles by building new graph from these cycles and finding connected components - then add the remaining nodes
                 # large_cycles = nx.Graph()
                 # for subgraph in subgraphs:
                 #     for node in subgraph[1:]:
                 #         large_cycles.add_edge(node, subgraph[0])
                 # components = nx.connected_components(large_cycles)
                 components = subgraphs

                # add edges found in the original graph for the remaining nodes
                for node in remaining_nodes:
                    for neighbor in graph.neighbors(node):
                        for component in components:
                            if neighbor in component:
                                component.append(node)
                                break
                res_components += components
Exemplo n.º 3
0
def get_minor(remaining_graph, real_graph, graph, cut_vertices):
    local_minor = graph.copy()
    copy_vertices = list(cut_vertices)
    leaf_in_y = []
    leaf_in_g = []
    for i1 in [
            i2 for i2, value in enumerate(
                dict(remaining_graph.degree()).values()) if value == 1
    ]:
        vertex = dict(remaining_graph.degree()).keys()[i1]
        leaf_in_y.append(vertex)
    for i1 in [
            i2 for i2, value in enumerate(dict(real_graph.degree()).values())
            if value == 1
    ]:
        vertex = dict(real_graph.degree()).keys()[i1]
        leaf_in_g.append(vertex)
    common_leaves = list(set(leaf_in_g).intersection(set(leaf_in_y)))
    contracted = dict()
    incident = list()
    while len(common_leaves) > 0 and local_minor.number_of_edges() > 50:
        vertex = random.choice(common_leaves)
        common_leaves.remove(vertex)
        neighbour = list(real_graph.neighbors(vertex))
        #         print "neigh:",neighbour,vertex,original_graph.neighbors(vertex)
        contract_list = real_graph.edge[vertex][neighbour[0]]['label']
        contract_list[0] += 1
        contract_list[1] += 1
        # print copy_vertices,contracted,contract_list,
        if contract_list[0] in contracted.keys():
            contract_list[0] = contracted[contract_list[0]]
        if contract_list[1] in contracted.keys():
            contract_list[1] = contracted[contract_list[1]]
        # print contract_list
        if contract_list[0] in copy_vertices and contract_list[
                1] in copy_vertices:
            incident.append(vertex)
            continue
        if max(contract_list) in copy_vertices:
            copy_vertices.remove(max(contract_list))
            copy_vertices.append(min(contract_list))
        print vertex, neighbour[
            0], "contract_list:", contract_list, real_graph.edge[vertex][
                neighbour[0]]['label']
        merge_nodes(local_minor, contract_list)
        contracted[max(contract_list)] = min(contract_list)
    while local_minor.number_of_edges() > limit_on_size:
        edge = random.choice(list(local_minor.edges()))
        merge_nodes(local_minor, edge)
    # write_graph(local_minor, 'test')
    print local_minor.nodes(), sorted(cut_vertices), sorted(copy_vertices)
    print local_minor.number_of_edges(), local_minor.edges()
    # write_graph(graph, 'original')
    nx.cycle_basis(local_minor)
    return local_minor
 def remove(G, loops=None):
     if loops is None:
         loops = nx.cycle_basis(G)
     for l in loops:
         s1, s2 = l[0], l[1]
         if (s1, s2) in G.edges():
             G.remove_edge(s1, s2)
         elif (s2, s1) in G.edges():
             G.remove_edge(s2, s1)
     loops2 = nx.cycle_basis(G)
     print('New graph has %i loops' % len(loops2))
     return G
 def remove(G, loops=None):
   if loops is None:
     loops = nx.cycle_basis(G)
   for l in loops:
     s1, s2 = l[0], l[1]
     if (s1, s2) in G.edges():
       G.remove_edge(s1, s2)
     elif (s2, s1) in G.edges():
       G.remove_edge(s2, s1)
   loops2 = nx.cycle_basis(G)
   print('New graph has %i loops' %len(loops2))
   return G
Exemplo n.º 6
0
def correctLoops(code, loops_graph, charge_type):
    while nx.cycle_basis(loops_graph) != []:
        cycle = nx.cycle_basis(loops_graph)[0]
        loop = path.Path(cycle)
        for data in code.Primal.nodes():
            if loop.contains_points([data]) == [True]:
                charge = code.Primal.node[data]['charge'][charge_type]
                code.Primal.node[data]['charge'][charge_type] = (charge + 1)%2

        l = len(cycle)
        for i in range(l):
            n1, n2 = cycle[i], cycle[(i+1)%l]
            loops_graph.remove_edge(*(n1,n2))

    return code, loops_graph
Exemplo n.º 7
0
def main():
    g = nx.Graph()

    nx.add_cycle(g, range(5))
    nx.add_cycle(g, range(5, 10))
    g.add_node(20)

    # 循環しているノードのリストを返す
    print(nx.cycle_basis(g)) #=> [[1, 2, 3, 4, 0], [9, 8, 7, 6, 5]]

    # もう1つ循環を作ってみる
    g.add_edges_from([(0, 5), (3, 8)])
    
    # 循環しているノードが1つ増えている
    print(nx.cycle_basis(g)) #=> [[9, 8, 7, 6, 5],
Exemplo n.º 8
0
def is_tree(graph):
	"""
	Checks whether graph is a tree.

	A graph is a tree if it is 
		(i) undirected - always, in our setting 
		(ii) connected, and 
		(iii) contains no cycles.

	Args:
		graph: networkx.Graph instance

	Return a boolean that indicates whether this graph is a tree.
	"""

	if len(graph.nodes()) == 0:
		return True

	if not nx.is_connected(graph):
		return False

	if len(nx.cycle_basis(graph)) > 0:
		return False

	return True
Exemplo n.º 9
0
    def order_tables(self):
        """ Sorts tables in constraint order, least constrained tables first

        Constructs a constraint graph for the tables in the supplied database
        or databases directory, sorts it in topological order with the least
        constained tables first, and returns the table names in that order in
        a list.
        """

        self.add_all_tables_to_graph()

        # With NetworkX v1.3, topological_sort raises NetworkXUnfeasible if
        # the graph is not acyclic.  With v1.2, it returns None.
        ordered_tables = None
        try:
            ordered_tables = nx.topological_sort(self.graph)
        except:
            ordered_tables = None
        if not ordered_tables:
            # Fails only if the graph has cycles.
            # The NetworkX package does not include a function that finds
            # cycles in a directed graph.  Lacking that, report the undirected
            # cycles.  Since our tables currently contain no cycles other than
            # self-loops, no need to implement a directed cycle finder.
            # @ToDo: Add a warning to the wiki about not putting cycles in
            # table relationships.  It's never necessary -- show a proper
            # relationship hierarchy.
            cycles = nx.cycle_basis(nx.Graph(self.graph))
            errmsg = "Tables and their constraints do not form a DAG.\n" + \
                     "Found possible cycles:\n" + str(cycles)
            raise ValueError, errmsg

        return ordered_tables
Exemplo n.º 10
0
    def __init__(self, graph):

        edges = {}
        vertices = {}
        faces = {}
        half_edges = {}

        cycles = nx.cycle_basis(graph)
        fi = 0
        for cycle in cycles:
            n = len(cycle)
            for i in range(n-1):
                e = (cycle[i], cycle[i+1])
                if e not in edges:
                    edges[e] = fi
                    twin_a = e[0], e[1]
                    twin_b = e[1], e[0]
                    if twin_a not in half_edges:
                        half_edges[twin_a] = fi
                    if twin_b not in half_edges:
                        half_edges[twin_b] = None
            e = cycle[n-1], cycle[0]
            if e not in edges:
                edges[e] = fi
            faces[fi] = e


            fi += 1

        self.edges = edges
        self.faces = faces
        self.half_edges = half_edges
Exemplo n.º 11
0
def VizualizeGraph(G, param):
    import os

    try:
        import matplotlib

        matplotlib.use("Agg")

        try:
            os.mkdir(param.output_directory + "/graph_regions" + str(int(param.mean_ins_size)))
        except OSError:
            # directory is already created
            pass
        # CB = nx.connected_component_subgraphs(G)
        CB = nx.cycle_basis(G)
        print "NR of SubG: ", len(CB)
        counter = 1
        for cycle in CB:
            if len(cycle) >= 6:  # at leats 6 nodes if proper cycle (haplotypic region)
                subgraph = nx.Graph()
                subgraph.add_cycle(cycle)
                nx.draw(subgraph)
                matplotlib.pyplot.savefig(
                    param.output_directory
                    + "graph_regions"
                    + str(int(param.mean_ins_size))
                    + "/"
                    + str(counter)
                    + ".png"
                )
                matplotlib.pyplot.clf()
                counter += 1
    except ImportError:
        pass
    return ()
Exemplo n.º 12
0
def planar_cycle_basis_nx(g, xs, ys):
	if g.is_directed():
		raise TypeError('Not implemented for directed graphs')
	if g.is_multigraph():
		raise TypeError('Not implemented for multi-graphs')

	if not (set(g) == set(xs) == set(ys)):
		raise ValueError('g, xs, ys must all share same set of vertices')

	my_g = nx.Graph()
	my_g.add_nodes_from(iter(g))
	my_g.add_edges_from(g.edges())

	nx.set_node_attributes(my_g, 'x', xs)
	nx.set_node_attributes(my_g, 'y', ys)

	# BAND-AID (HACK)
	# This algorithm has an unresolved issue with graphs that have at least
	#   two biconnected components, one of which is "inside" another
	#   (geometrically speaking).  Luckily, it is safe to look at each
	#   biconnected component separately, as all edges in a cycle always
	#   belong to the same biconnected component.
	result = []
	for subg in nx.biconnected_component_subgraphs(my_g):
		if len(subg) >= 3: # minimum possible size for cycles to exist
			result.extend(planar_cycle_basis_impl(subg))

	# Restore some confidence in the result...
	if len(result) != len(nx.cycle_basis(g)):
		raise RuntimeError(
			'planar_cycle_basis produced a result of incorrect '
			'length on the given graph! (does it have crossing edges?)'
		)

	return result
Exemplo n.º 13
0
    def steady_flows(self, initguess=None, extra_output=True):
        """
        Computes the steady state flows. 

        Args:
            self: A selfwork object
            initguess: Initial conditions
            extra_output: boolean

        Returns:
            A dictionary
                d = {edge1 : flow1, edge2 : flow2,...}
            If extra_output=True, returns another dictionary
                data = {initguess: the_initial_condition, 'thetas': steady_state_thetas, 'omega': winding_vector}
        """

        thetas, initguess = self._try_find_fps(NTRY, initguess=initguess)

        if thetas is None:
            return None, {'initguess': initguess}

        node_indices = {node: idx for idx, node in enumerate(self.nodes())}
        flows = FlowDict({(u, v): np.sin(thetas[node_indices[u]] - thetas[node_indices[v]])*
            dat.get(self.weight_attr, 1) for (u, v, dat) in self.edges(data=True)})

        if extra_output:
            omega = _omega(self, nx.cycle_basis(self), thetas)
            return flows, {'initguess': initguess, 'thetas': thetas, 'omega': omega}
        else:
            return flows
Exemplo n.º 14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('psf', metavar='psffile', help='PSF file')
    parser.add_argument('crd', metavar='crdfile', help='CRD file')
    args = parser.parse_args()

    # build connectivity of atoms
    psf = build_topology(args.psf)
    crd = build_atomtable(psf, args.crd)

    # sanity check
    if len(psf.nodes()) != len(crd): raise AtomMismatch('Number of atom does not match')

    # print out ring atoms
    molecules = nx.connected_component_subgraphs(psf)
    dummys = []
    fixes = []
    i = 1
    _coor = 'coor set xdir %8.3f ydir %8.3f zdir %8.3f sele segid dum .and. resi %d end'
    _fix = 'scalar wmain set 1.0 sele segid %s .and. resi %s end'
    for m in molecules:
        cycles = nx.cycle_basis(m)
        if not cycles: continue
        for cycle in cycles:
            atoms = np.array([crd[num] for num in cycle])
            com = np.sum(atoms, axis=0)/len(atoms)
            dummys.append(_coor % (com[0], com[1], com[2], i))
            if _fix % (psf.node[cycle[0]]['segid'], psf.node[cycle[0]]['resid']) not in fixes:
                fixes.append(_fix % (psf.node[cycle[0]]['segid'], psf.node[cycle[0]]['resid']))
            i += 1
    print _rings_str % (len(dummys), "\n".join(dummys), "\n".join(fixes))
Exemplo n.º 15
0
def cycle_space (T,C):
  """Return a list of cycle graphs representing the fundamental cycles of the
     spanning tree T extended by the chords edges of the graph C

  Parameters
  ----------
  T: a tree graph
     A NetworkX graph.
  C: graph representing chords for the tree T.
    A NetworkX (multidi)graph.

  Returns
  -------
  Z : a list of cycles

  """
  Z     = list ();
  edges = C.edges_iter ();

  for idx,e in enumerate (edges):
    if T.has_edge(*e) or T.has_edge(*e[::-1]):
      Z.append (list (e))
    else:
      T.add_edge (*e)
      Z.append (nx.cycle_basis (nx.Graph(T))[0])
      T.remove_edge (*e)

  return Z
Exemplo n.º 16
0
Arquivo: mos2.py Projeto: ExpHP/defect
def main(prog, argv):
	parser = argparse.ArgumentParser(prog=prog)
	parser.add_argument('rows', metavar='LENGTH', type=int)
	parser.add_argument('cols', metavar='WIDTH', type=int)
	parser.add_argument('--verbose', '-v', action='store_true')
	parser.add_argument('--output-cb', '-C', metavar='PATH', type=str, help='generate .cyclebasis file')
	parser.add_argument('--output', '-o', type=str, required=True, help='.gpickle output file')

	args = parser.parse_args(argv)

	cellrows, cellcols = args.rows, args.cols

	if args.verbose:
		print('Generating graph and attributes')
	g = make_circuit(cellrows, cellcols)
	xys = full_xy_dict(cellrows, cellcols)
	measured_edge = battery_vertices()

	if args.verbose:
		print('Saving circuit')
	save_output(args.output, g, xys, measured_edge)

	if args.output_cb is not None:
		if args.verbose:
			print('Collecting desirable cycles')
		good = collect_good_cycles(g, cellrows, cellcols)

		assert validate_paths(g, good)

		if args.verbose:
			print('Generating fallback cycles')
		fallback = nx.cycle_basis(g)

		cyclebasis = build_cyclebasis_terminal(good, fallback, thorough=False, verbose=args.verbose)
		fileio.cycles.write_cycles(cyclebasis, args.output_cb)
Exemplo n.º 17
0
def check_closure(g, node):
    h = g.subgraph(g[node])
    if nx.cycle_basis(h): return True
    sorted_nodes = sorted(h.degree().items(), key=operator.itemgetter(1))
    nodes = [n[0] for n in sorted_nodes[:2] if n[1] == 1]
    if len(nodes) == 2:
        if g.node[nodes[0]]['vertices'] > g.degree(nodes[0]) and \
           g.node[nodes[1]]['vertices'] > g.degree(nodes[1]):
            g.add_edge(nodes[0], nodes[1])
            return False

        if g.node[nodes[0]]['vertices'] > g.degree(nodes[0]) and \
            g.node[nodes[1]]['vertices'] == g.degree(nodes[1]):
            h = g.subgraph(g[nodes[1]])
            sorted_nodes = sorted(h.degree().items(), key=operator.itemgetter(1))
            xnode = [n[0] for n in sorted_nodes if n[1] == 1 and n[0] not in [nodes[0], nodes[1], node]].pop()
            for n in g[xnode]:
                if n in [nodes[1], node]: continue
                g.add_edge(nodes[0], n)
            g.remove_node(xnode)
            return False

        if g.node[nodes[0]]['vertices'] == g.degree(nodes[0]) and \
            g.node[nodes[1]]['vertices'] > g.degree(nodes[1]):
            h = g.subgraph(g[nodes[0]])
            sorted_nodes = sorted(h.degree().items(), key=operator.itemgetter(1))
            xnode = [n[0] for n in sorted_nodes if n[1] == 1 and n[0] not in [nodes[0], nodes[1], node]].pop()
            for n in g[xnode]:
                if n in [nodes[0], node]: continue
                g.add_edge(nodes[1], n)
            g.remove_node(xnode)
            return False
Exemplo n.º 18
0
def order_tables(dbdir_str):
    """
    Sorts tables in constraint order, primary tables first

    Constructs a constraint graph for the tables in the supplied directory,
    sorts it in topological order, and returns the table names in that
    order in a list.
    """

    graph = nx.DiGraph()

    for file_str in os.listdir(dbdir_str):
        if file_str.endswith(".table"):
            add_table_to_graph(dbdir_str, file_str, graph)

    ordered_tables = None
    try:
        ordered_tables = nx.topological_sort(graph)
    except nx.NetworkXUnfeasible:
        print >> sys.stderr, "Tables and their constraints do not form a DAG"
        # The NetworkX package does not include a function that finds cycles
        # in a directed graph.  Lacking that, report the undirected cycles.
        # Since our tables currently contain no cycles other than self-loops,
        # no need to implement a directed cycle finder.
        cycles = nx.cycle_basis(nx.Graph(graph))
        print >> sys.stderr, "Found possible cycles:"
        print >> sys.stderr, cycles
        sys.exit(1)

    return ordered_tables
Exemplo n.º 19
0
    def assign_pyranose_atoms(self):

        import networkx as nx

        cm = nx.graph.Graph(self.conn_mat)
        rings = nx.cycle_basis(cm)
        an = self[0].atoms
        self.rings = []
        n = 0
        for r in rings:
            self.rings.append({})
            rd = self.rings[n]
            for at in r:
                if an[at] == 'O':
                    rd['O'] = at
                else:
                    for at2 in np.where(self.conn_mat[at] == 1)[0]:
                        if an[at2] == 'C' and at2 not in r:
                            rd['C4'] = at
            for at in rd.values():
                r.remove(at)
            for at in r:
                if self.conn_mat[at][rd['O']] == 1: rd['C0'] = at
                elif self.conn_mat[at][rd['C4']] == 1: rd['C3'] = at
            for at in [rd['C3'], rd['C0']]:
                r.remove(at)
            for at in r:
                if self.conn_mat[at][rd['C0']] == 1: rd['C1'] = at
                elif self.conn_mat[at][rd['C3']] == 1: rd['C2'] = at
            for at in [rd['C2'], rd['C1']]:
                r.remove(at)
            n += 1
Exemplo n.º 20
0
def hardy_cross(G, n, init_guess=None):
    cycles = nx.cycle_basis(G)
    cycles = np.array([[tuple([cycles[j][i], cycles[j][i+1]]) if (i < len(cycles[j])-1) else tuple([cycles[j][i], cycles[j][0]]) for i in range(len(cycles[j]))] for j in range(len(cycles))])

    L = [G.node[i]['demand'] for i in G.node.keys()]
    edges = np.array(G.edges())
    edge_idx = np.full((len(G), len(G)), 9999, dtype=int)
    edge_idx[edges[:,0], edges[:,1]] = np.arange(len(G.edges()))
    edge_idx[edges[:,1], edges[:,0]] = np.arange(len(G.edges()))
    
    edge_dir = np.zeros((len(G), len(G)), dtype=int)
    edge_dir[edges[:,0], edges[:,1]] = 1
    edge_dir[edges[:,1], edges[:,0]] = -1

    if init_guess == None:
        init_guess = np.linalg.lstsq(nx.incidence_matrix(G, oriented=True).toarray(), L)[0]
    A = init_guess.copy().astype(float)
    for i in range(n):
        for u in cycles:
            R = np.array([G[j[0]][j[1]]['weight'] for j in u])
            D = np.array(edge_dir[u[:,0], u[:,1]])
            C = np.array(A[edge_idx[u[:,0], u[:,1]]])
            C = C*D
            dV = (R*C).sum()
            di = dV/R.sum()
	    C = (C - di)*D
	    A[edge_idx[u[:,0], u[:,1]]] = C
    return A
Exemplo n.º 21
0
def vacuum_operator(edge_matrix_indices):
    """Use the stabilizers to find the vacuum state in bravyi_kitaev_fast.

    Args:
        edge_matrix_indices(numpy array): specifying the edges

    Return:
        An instance of QubitOperator

    """
    # Initialize qubit operator.
    g = networkx.Graph()
    g.add_edges_from(tuple(edge_matrix_indices.transpose()))
    stabs = numpy.array(networkx.cycle_basis(g))
    vac_operator = QubitOperator(())
    for stab in stabs:

        A = QubitOperator(())
        stab = numpy.array(stab)
        for i in range(numpy.size(stab)):
            if i == (numpy.size(stab) - 1):
                A = (1j)*A * edge_operator_aij(edge_matrix_indices,
                                               stab[i], stab[0])
            else:
                A = (1j)*A * edge_operator_aij(edge_matrix_indices,
                                               stab[i], stab[i+1])
        vac_operator = vac_operator*(QubitOperator(()) + A)/numpy.sqrt(2)

    return vac_operator
Exemplo n.º 22
0
 def test_cycle_basis(self):
     G=self.G
     cy=networkx.cycle_basis(G,0)
     sort_cy= sorted( sorted(c) for c in cy )
     assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]])
     cy=networkx.cycle_basis(G,1)
     sort_cy= sorted( sorted(c) for c in cy )
     assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]])
     cy=networkx.cycle_basis(G,9)
     sort_cy= sorted( sorted(c) for c in cy )
     assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]])
     # test disconnected graphs
     G.add_cycle(list("ABC"))
     cy=networkx.cycle_basis(G,9)
     sort_cy= sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])]
     assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5],['A','B','C']])
Exemplo n.º 23
0
    def order_tables(self):
        """ Sorts tables in constraint order, least constrained tables first

        Constructs a constraint graph for the tables in the supplied database
        or databases directory, sorts it in topological order with the least
        constained tables first, and returns the table names in that order in
        a list.
        """

        self.add_all_tables_to_graph()

        # With NetworkX v1.3, topological_sort raises NetworkXUnfeasible if
        # the graph is not acyclic.  With v1.2, it returns None.
        ordered_tables = None
        try:
            ordered_tables = nx.topological_sort(self.graph)
        except:
            ordered_tables = None
        if not ordered_tables:
            # Fails only if the graph has cycles.
            # The NetworkX package does not include a function that finds
            # cycles in a directed graph.  Lacking that, report the undirected
            # cycles.  Since our tables currently contain no cycles other than
            # self-loops, no need to implement a directed cycle finder.
            # @ToDo: Add a warning to the wiki about not putting cycles in
            # table relationships.  It's never necessary -- show a proper
            # relationship hierarchy.
            cycles = nx.cycle_basis(nx.Graph(self.graph))
            errmsg = "Tables and their constraints do not form a DAG.\n" + \
                     "Found possible cycles:\n" + str(cycles)
            raise ValueError, errmsg

        return ordered_tables
Exemplo n.º 24
0
def calc_score(smiles):
    if verify_sequence(smiles):
        molecule = MolFromSmiles(smiles)
        current_log_P_value = Descriptors.MolLogP(molecule)
        current_SA_score = -sascorer.calculateScore(molecule)
        cycle_list = nx.cycle_basis(
            nx.Graph(rdmolops.GetAdjacencyMatrix(molecule)))
        if len(cycle_list) == 0:
            cycle_length = 0
        else:
            cycle_length = max([len(j) for j in cycle_list])
        if cycle_length <= 6:
            cycle_length = 0
        else:
            cycle_length = cycle_length - 6
        current_cycle_score = -cycle_length

        current_SA_score_normalized = (current_SA_score -
                                       np.mean(SA_scores)) / np.std(SA_scores)
        current_log_P_value_normalized = (
            current_log_P_value - np.mean(logP_values)) / np.std(logP_values)
        current_cycle_score_normalized = (
            current_cycle_score - np.mean(cycle_scores)) / np.std(cycle_scores)

        score = (current_SA_score_normalized + current_log_P_value_normalized +
                 current_cycle_score_normalized)
        return score
    else:
        raise ValueError("Error in calc_score: smiles is invalid.")
Exemplo n.º 25
0
def findPath(schema_graph):
	'''Determines if the schema contains a closed curve.'''
	cycles = nx.cycle_basis(schema_graph)
	if len(cycles) > 0:
		return cycles
	else:
		raise nx.exception.NetworkXNoCycle('No closed cycle found.')
Exemplo n.º 26
0
def checkcycle(edge, G=None):
    if G == None:
        G = nx.Graph()
    (u, v, w) = edge
    G.add_edge(u, v, weight=w)
    #return (G, len(list(nx.simple_cycles(G))))
    return (G, len(nx.cycle_basis(G)))
Exemplo n.º 27
0
def main():
	import argparse
	parser = argparse.ArgumentParser()
	parser.add_argument('basename', type=str)
	args = parser.parse_args()

	circuit = load_circuit(args.basename + '.circuit')
	cycles = fileio.cycles.read_cycles(args.basename + '.cycles')

	badcycles = nx.cycle_basis(circuit)
	for c in badcycles: c.append(c[0])

#	fig, ax = plt.subplots()
#	plot2(get_rmatrix(circuit, cycles), ax)
#	fig, ax = plt.subplots()
#	plot2(get_rmatrix(circuit, badcycles), ax)
#	plt.show()

#	write_file(get_rmatrix(circuit, cycles), 'good-rmatrix.dat')
#	write_file(get_rmatrix(circuit, badcycles), 'bad-rmatrix.dat')

	print('get good')
	get_rmatrix(circuit, cycles)
	print('get bad')
	get_rmatrix(circuit, badcycles)
Exemplo n.º 28
0
    def check_G_feasibility(self):
        # This function performs three feasiblity test on the graph
        # if the graph is still conected
        subturs = [
            c for c in sorted(
                nx.connected_components(self.G), key=len, reverse=True)
        ]
        if len(subturs) != 1:
            return 0  # Graph became disconnected

        G2 = nx.Graph()
        G2.add_nodes_from(self.G.nodes())
        G2.add_edges_from(self.edges2keep)

        for i in G2.nodes():
            if G2.degree(i) >= 3:
                return 0

        cycles = nx.cycle_basis(G2)
        for c in cycles:
            if 0 not in c:
                return 0

        edgeset = list(self.G.edges())
        for n in self.G.node:
            if n != 0 and n != Node.Data.NN + 1:
                edgeset.remove((n, Node.Data.NN + 1))
        #print("Number of existed edges: %s" %(len(edgeset)-Node.Data.NN+1))
        if edgeset == []:
            return 0
        return 1
Exemplo n.º 29
0
def penalized_logp(s):
    if s is None: return -100.0
    mol = Chem.MolFromSmiles(s)
    if mol is None: return -100.0

    logP_mean = 2.4570953396190123
    logP_std = 1.434324401111988
    SA_mean = -3.0525811293166134
    SA_std = 0.8335207024513095
    cycle_mean = -0.0485696876403053
    cycle_std = 0.2860212110245455

    log_p = Descriptors.MolLogP(mol)
    SA = -sascorer.calculateScore(mol)

    # cycle score
    cycle_list = nx.cycle_basis(nx.Graph(
        Chem.rdmolops.GetAdjacencyMatrix(mol)))
    if len(cycle_list) == 0:
        cycle_length = 0
    else:
        cycle_length = max([len(j) for j in cycle_list])
    if cycle_length <= 6:
        cycle_length = 0
    else:
        cycle_length = cycle_length - 6
    cycle_score = -cycle_length

    normalized_log_p = (log_p - logP_mean) / logP_std
    normalized_SA = (SA - SA_mean) / SA_std
    normalized_cycle = (cycle_score - cycle_mean) / cycle_std
    return normalized_log_p + normalized_SA + normalized_cycle
Exemplo n.º 30
0
    def find_all_cycles(self):

        cycle_basis = nx.cycle_basis(self.G)

        cycle_graphs = [nx.Graph(self.G.subgraph(c)) for c in cycle_basis]

        edge_sets = [set([e for e in graph.edges]) for graph in cycle_graphs]

        new_edge_sets = self.analyse_cycles(edge_sets)

        new_node_sets = []
        for es in new_edge_sets:

            node_set = []

            for edge in es:
                node_set.append(edge[0])
                node_set.append(edge[1])

            if node_set not in new_node_sets:
                new_node_sets.append(tuple(set(node_set)))

        new_node_sets = set([ns for ns in new_node_sets])
        cycle_graphs = [nx.Graph(self.G.subgraph(c)) for c in new_node_sets]

        cycle_graphs = [g for g in cycle_graphs if self.true_cycle(g)]

        return cycle_graphs
Exemplo n.º 31
0
def calculate(g, voltage):
    edges_num = nx.number_of_edges(g)
    # sort nodes in edges
    edges = [edge if edge[0] < edge[1] else (edge[1], edge[0])
             for edge in nx.edges(g)]

    a = np.zeros((edges_num, edges_num))
    b = np.zeros((edges_num, 1))
    i = 0
    # first law
    for node in [node for node in nx.nodes(g) if node != 0]:
        for neighbor in nx.all_neighbors(g, node):
            edge = tuple(sorted((node, neighbor)))
            a[i][edges.index(edge)] = 1 if neighbor < node else -1
        i += 1
    # second law
    cycles = nx.cycle_basis(g, 0)
    for cycle in cycles:
        for j in range(0, len(cycle)):
            node = cycle[j]
            next_node = cycle[(j + 1) % len(cycle)]
            edge = tuple(sorted((node, next_node)))
            resistance = g[node][next_node]['weight']
            a[i][edges.index(edge)] = resistance if node < next_node else -resistance
        if 0 in cycle:
            b[i] = voltage
        i += 1
    # solve
    x = np.linalg.solve(a, b)
    for (x1, x2), res in zip(edges, x):
        g[x1][x2]['current'] = res[0]
 def f22(self):
     start = 0
     cycle_list = nx.cycle_basis(self.G)
     res = len(cycle_list)
     stop = 0
     # self.feature_time.append(stop - start)
     return res
Exemplo n.º 33
0
Arquivo: fluid.py Projeto: asrvsn/gds
def edge_fourier_transform(G, method='hodge_faces'):
    '''
	Diagonalization of 1-form laplacian with varying 2-form definitions
	'''
    if method == 'hodge_faces':  # 2-forms defined on planar faces (default)
        pass
    elif method == 'hodge_cycles':  # 2-forms defined on cycle basis
        G.faces = [tuple(f) for f in nx.cycle_basis(G)]
    elif method == 'dual':
        raise NotImplementedError()
    else:
        raise ValueError(f'Method {method} undefined')

    v = gds.edge_gds(
        G)  # TODO: assumes determinism of edge index assignment -- fix!
    L1 = -v.laplacian(np.eye(v.ndim))
    eigvals, eigvecs = np.linalg.eigh(
        L1
    )  # Important to use eigh() rather than eig() -- otherwise non-unitary eigenvectors
    eigvecs = np.asarray(eigvecs)

    # Unitary check
    assert (np.round(eigvecs @ eigvecs.T,
                     6) == np.eye(v.ndim)).all(), 'VV^T != I'
    assert (np.round(eigvecs.T @ eigvecs,
                     6) == np.eye(v.ndim)).all(), 'V^TV != I'

    return eigvals, eigvecs
def optimize_tour(n=38):
    m = model_setup()
    while True:
        m.reset()
        m.optimize()
        selected = {}
        for i in arange(38):
            for j in arange(i + 1):
                if m._vars[i, j].X >= 0.5:
                    selected[i, j] = (i, j)
        G = nx.Graph()
        G.add_edges_from(selected)
        cycle = nx.cycle_basis(G)
        if len(cycle) == 1 and len(cycle[0]) == n:
            m.optimize()
            res = selected
            break
        else:
            print(sort(cycle[-1]))
            if len(cycle) > 2:
                print(cycle[1] + cycle[-1])
                m.addConstr(
                    quicksum(m._vars[k, l] for k in sort(cycle[0])
                             for l in sort(cycle[1] + cycle[-1])) >= 2)
            else:
                m.addConstr(
                    quicksum(m._vars[k, l] for k in sort(cycle[0])
                             for l in sort(cycle[-1])) >= 2)
    resnorm = []
    for i in res.keys():
        resnorm.append(i)
    return resnorm
Exemplo n.º 35
0
    def rings_full_data(self):
        """ Returns a generator for iterating over each ring

        Yields
        ------
            For each ring, tuple composed by ring ID, list of edges, list of nodes
        Note
        -----
            Circuit breakers must be closed to find rings, this is done automatically.
        """
        #close circuit breakers
        for circ_breaker in self.circuit_breakers():
            if not circ_breaker.status == 'closed':
                circ_breaker.close()
                logger.info('Circuit breakers were closed in order to find MV '
                            'rings')
        #find True rings (cycles from station through breaker and back to station)
        for ring_nodes in nx.cycle_basis(self._graph, root=self._station):
            edges_ring = []
            for node in ring_nodes:
                for edge in self.graph_branches_from_node(node):
                    nodes_in_the_branch = self.graph_nodes_from_branch(
                        edge[1]['branch'])
                    if (nodes_in_the_branch[0] in ring_nodes
                            and nodes_in_the_branch[1] in ring_nodes):
                        if not edge[1]['branch'] in edges_ring:
                            edges_ring.append(edge[1]['branch'])
            yield (edges_ring[0].ring, edges_ring, ring_nodes)
Exemplo n.º 36
0
def closed_ways_from_multiple_ways(way_parts: List[Way]) -> List[Way]:
    """Create closed ways from multiple not closed ways where possible.
    See http://wiki.openstreetmap.org/wiki/Relation:multipolygon.
    If parts of ways cannot be used, they just get disregarded.
    The new Ways gets the osm_id from a way reused and all tags removed.
    """
    closed_ways = list()

    graph = nx.Graph()
    for way in way_parts:
        for i in range(len(way.refs) - 1):
            graph.add_edge(way.refs[i], way.refs[i + 1])

    cycles = nx.cycle_basis(graph)
    for cycle in cycles:  # we just reuse ways - it does not really matter
        way = Way(0)
        way.refs = cycle
        way.refs.append(way.refs[0])  # cycles from networkx are not closed
        closed_ways.append(way)

        # now make sure we have the original tags
        way.tags = dict()
        ways_set = set()
        for node in cycle:
            for wp in way_parts:
                if node in wp.refs:
                    ways_set.add(wp)
                    if way.osm_id == 0:
                        way.osm_id = wp.osm_id  # reuse the id from an existing way
        for wp in ways_set:
            for key, value in wp.tags.items():
                if key not in way.tags:
                    way.tags[key] = value

    return closed_ways
Exemplo n.º 37
0
def main():

    g = nx.Graph()

    g.add_cycle(range(5))
    g.add_cycle(range(5, 10))
    g.add_node(20)

    # 循環しているノードのリストを返す
    print(nx.cycle_basis(g)) #=> [[1, 2, 3, 4, 0], [9, 8, 7, 6, 5]]

    # もう一つ循環を作ってみる
    g.add_edges_from([(0, 5), (3, 8)])

    # 循環しているノードが一つ増えている
    print(nx.cycle_basis(g)) #=> [[9, 8, 7, 6, 5],
Exemplo n.º 38
0
def find_sidechains(molecule_graph):
    # Identify chiral atoms
    atoms = molecule_graph.atoms
    chiral_centres = chir.get_chiral_sets(atoms)
    # Identify sidechains (Ca-Cb-X), apart from proline and glycine.
    sidechains = {}
    # Detection of sidechains requires the multiple bonds be present in the atom graph.
    chir.multi_bonds(atoms)
    for k, v in chiral_centres.items():
        carbons = [atom for atom in v if atom.element == "C"]
        amides = [
            carbon
            for carbon in carbons
            if any([type(nb) == chir.GhostAtom and nb.element == "O" for nb in nx.neighbors(atoms, carbon)])
            and any([nb.element == "N" or nb.element == "O" for nb in nx.neighbors(atoms, carbon)])
        ]
        nbs_n = [nb for nb in v if nb.element == "N"]
        if amides and nbs_n:
            amide_bond = (k, amides[0])
            n_bond = (k, nbs_n[0])
            h_bond = (k, [h for h in nx.neighbors(atoms, k) if h.element == "H"][0])
            # Now find sidechains by cutting the Ca-C, Ca-N and Ca-H bonds
            atoms.remove_edges_from([amide_bond, n_bond, h_bond])
            sidechain_atoms = [
                atom
                for atom in [comp for comp in nx.connected_components(atoms) if k in comp][0]
                if type(atom) != chir.GhostAtom
            ]
            atoms.add_edges_from([amide_bond, n_bond, h_bond])
            if not any([k in cycle for cycle in nx.cycle_basis(atoms.subgraph(sidechain_atoms))]):
                sidechains[k] = atoms.subgraph(sidechain_atoms)
    chir.remove_ghost_atoms(atoms)
    return sidechains
Exemplo n.º 39
0
def calc_score(smiles):
    if verify_sequence(smiles):
        try:
            molecule = MolFromSmiles(smiles)
            if Descriptors.MolWt(molecule) > 500:
                return -1e10
            current_log_P_value = Descriptors.MolLogP(molecule)
            current_SA_score = -sascorer.calculateScore(molecule)
            cycle_list = nx.cycle_basis(
                nx.Graph(rdmolops.GetAdjacencyMatrix(molecule)))
            if len(cycle_list) == 0:
                cycle_length = 0
            else:
                cycle_length = max([len(j) for j in cycle_list])
            if cycle_length <= 6:
                cycle_length = 0
            else:
                cycle_length = cycle_length - 6
            current_cycle_score = -cycle_length

            current_SA_score_normalized = (current_SA_score - SA_mean) / SA_std
            current_log_P_value_normalized = (current_log_P_value -
                                              logP_mean) / logP_std
            current_cycle_score_normalized = (current_cycle_score -
                                              cycle_mean) / cycle_std

            score = (current_SA_score_normalized +
                     current_log_P_value_normalized +
                     current_cycle_score_normalized)
            return score
        except Exception:
            return -1e10
    else:
        return -1e10
Exemplo n.º 40
0
    def findNonCyclicNodes(self, subgraph):
        """
        Generates a list of nodes of the subgraph that are not in a cycle
         
        Parameters
        ---------
        subgraph : NetworkX subgraph obj
            the subgraph to check for not cycle nodes

        Returns
        -------
        missingNodesSet : set of graph nodes
            the set of graph nodes that are not in a cycle
        
        """

        missingNodesSet = set()

        cycleNodes = []

        cycleList = nx.cycle_basis(subgraph)

        cycleNodes = [node for cycle in cycleList for node in cycle]

        missingNodesSet = set(
            [node for node in subgraph.nodes() if node not in cycleNodes])

        return missingNodesSet
Exemplo n.º 41
0
def VizualizeGraph(G, param):
    import os
    try:
        import matplotlib
        matplotlib.use('Agg')

        try:
            os.mkdir(param.output_directory + '/graph_regions' +
                     str(int(param.mean_ins_size)))
        except OSError:
            #directory is already created
            pass
        #CB = nx.connected_component_subgraphs(G)
        CB = nx.cycle_basis(G)
        print 'NR of SubG: ', len(CB)
        counter = 1
        for cycle in CB:
            if len(
                    cycle
            ) >= 6:  # at leats 6 nodes if proper cycle (haplotypic region)
                subgraph = nx.Graph()
                subgraph.add_cycle(cycle)
                nx.draw(subgraph)
                matplotlib.pyplot.savefig(param.output_directory +
                                          'graph_regions' +
                                          str(int(param.mean_ins_size)) + '/' +
                                          str(counter) + '.png')
                matplotlib.pyplot.clf()
                counter += 1
    except ImportError:
        pass
    return ()
Exemplo n.º 42
0
def compute_cost_logp(G, writefile="temp.txt"):
    cost = 0.0
    sas = ""
    logP = ""
    cycle_score = ""
    #m1 = nx_to_mol(G)
    if guess_correct_molecules_from_graph(G, writefile):
        m1 = Chem.MolFromMol2File(writefile)
        if m1 != None:
            s = Chem.MolToSmiles(m1)
            sas = -sascorer.calculateScore(m1)
            logP = Descriptors.MolLogP(m1)
            cycle_list = nx.cycle_basis(G)

            if len(cycle_list) == 0:
                cycle_length = 0
            else:
                cycle_length = max([len(j) for j in cycle_list])
            if cycle_length <= 6:
                cycle_length = 0.0
            else:
                cycle_length = cycle_length - 6.0
            cycle_score = -cycle_length
            cost = sas + logP + cycle_score
        else:
            print "Error: m1 is NONE"
            cost = ""
    else:
        print "Error: gues correct molecule"
        cost = ""
    # we want to define this property value such that low vales are better
    if cost != "":
        cost = 10.00 - cost
    return (sas, logP, cycle_score)
Exemplo n.º 43
0
def check_loops(model, verbose=True):
    all_sources = []
    for i in model.models:
        if isinstance(i,PowerSource) and i.connecting_element is not None:
            all_sources.append(i)
        elif isinstance(i,PowerSource):
            print('Warning - a PowerSource element has a None connecting element')

    # TODO: Address issue in network.py where a single source is used to determine bfs order
    if len(all_sources) == 0:
        raise('Model does not contain any power source. Required to build networkx graph')

    for source in all_sources:
        print('Checking loops for source '+source.name)
        ditto_graph = Network()
        ditto_graph.build(model,source.connecting_element)
        ditto_graph.set_attributes(model)
        ditto_graph.remove_open_switches(model) # This deletes the switches inside the networkx graph only
    
        loops = nx.cycle_basis(ditto_graph.graph)
        number_of_loops = len(loops)
        if number_of_loops > 0:
            if verbose:
                print('Loops found:')
                print(loops)
        if number_of_loops == 0:
            return True
    return False
    def get_cycles(self) -> Iterable[List[int]]:
        """
        Returns the generator of cycles of this graph used by CC algorithm.
        :return: Generator of lists-cycles.
        """
        # There is no way to get only simple cycles for graph or cycle basis
        # So we use networkx (but only for getting cycles)
        import networkx as nx

        v_ind = self.vertex_index

        simple_edges = [(v_ind[e.source()], v_ind[e.target()])
                        for e in self.edges()]
        cycles = nx.cycle_basis(nx.Graph(simple_edges))
        '''
        if self.is_directed():
            g = self
        else:
            g = self.copy()
            g.is_directed = lambda: True

        cycles = all_circuits(g, unique=True)
        cl = list(cycles)
        '''
        if self.is_directed():
            for c in cycles:
                if self.has_cycle(c):
                    # print('Cycle!')
                    yield c
        else:
            return cycles
Exemplo n.º 45
0
def get_equations(G):
    equations = []
    u = []
    E = len(G.edges)
    # 1 prawo Kirchoffa
    for i in G.nodes:
        eq = [0 for i in range(E)]
        for e in G.edges(i):
            data = G.get_edge_data(*e)
            if e[0] > e[1]:
                eq[data['no'] - 1] = 1
            else:
                eq[data['no'] - 1] = -1
        equations.append(eq)
        u.append(0)
    # 2 prawo Kirchoffa
    for cycle in nx.cycle_basis(G):
        eq = [0 for i in range(E)]
        u.append(0)
        for i in range(len(cycle)):
            V1 = cycle[i]
            V2 = cycle[(i + 1) % len(cycle)]
            data = G.get_edge_data(V1, V2)
            if V1 > V2:
                eq[data['no'] - 1] = data['R']
                u[-1] += data['sem']
            else:
                eq[data['no'] - 1] = -data['R']
                u[-1] -= data['sem']
        equations.append(eq)
    return equations, u
Exemplo n.º 46
0
def vacuum_operator(fer_op):
    """Use the stabilizers to find the vacuum state in BKSF.

    This operator can be used to generate the vaccum state for
    BKSF mapping.
    Upon having this operator, operate it on `orignal` vaccum state |000...>,
    and resulted state is the vacuum state for bksf mapping.

    Args:
        fer_op (FermionicOperator): the fermionic operator in the second quanitzed form

    Returns:
        Operator: the qubit operator
    """
    edge_list = bksf_edge_list(fer_op)
    num_qubits = edge_list.shape[1]
    vac_operator = Operator(paulis=[[1.0, label_to_pauli('I' * num_qubits)]])

    g = networkx.Graph()
    g.add_edges_from(tuple(edge_list.transpose()))
    stabs = np.asarray(networkx.cycle_basis(g))
    for stab in stabs:
        a = Operator(paulis=[[1.0, label_to_pauli('I' * num_qubits)]])
        stab = np.asarray(stab)
        for i in range(np.size(stab)):
            a = a * edge_operator_aij(edge_list, stab[i],
                                      stab[(i + 1) % np.size(stab)])
            a.scaling_coeff(1j)

        a += Operator(paulis=[[1.0, label_to_pauli('I' * num_qubits)]])
        vac_operator = vac_operator * a
        vac_operator.scaling_coeff(np.sqrt(2))

    return vac_operator
Exemplo n.º 47
0
 def test_cycle_basis(self):
     G = self.G
     cy = networkx.cycle_basis(G, 0)
     sort_cy = sorted(sorted(c) for c in cy)
     assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
     cy = networkx.cycle_basis(G, 1)
     sort_cy = sorted(sorted(c) for c in cy)
     assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
     cy = networkx.cycle_basis(G, 9)
     sort_cy = sorted(sorted(c) for c in cy)
     assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5]]
     # test disconnected graphs
     nx.add_cycle(G, "ABC")
     cy = networkx.cycle_basis(G, 9)
     sort_cy = sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])]
     assert sort_cy == [[0, 1, 2, 3], [0, 1, 6, 7, 8], [0, 3, 4, 5], ["A", "B", "C"]]
Exemplo n.º 48
0
def vacuum_operator(fer_op):
    """Use the stabilizers to find the vacuum state in bravyi_kitaev_fast.

    Args:
        fer_op (FermionicOperator): the fermionic operator in the second quanitzed form

    Returns:
        Operator: the qubit operator
    """
    edge_list = bravyi_kitaev_fast_edge_list(fer_op)
    num_qubits = edge_list.shape[1]
    vac_operator = Operator(paulis=[[1.0, Pauli.from_label('I' * num_qubits)]])

    g = networkx.Graph()
    g.add_edges_from(tuple(edge_list.transpose()))
    stabs = np.asarray(networkx.cycle_basis(g))
    for stab in stabs:
        a = Operator(paulis=[[1.0, Pauli.from_label('I' * num_qubits)]])
        stab = np.asarray(stab)
        for i in range(np.size(stab)):
            a = a * edge_operator_aij(edge_list, stab[i],
                                      stab[(i + 1) % np.size(stab)])
            a.scaling_coeff(1j)
        a += Operator(paulis=[[1.0, Pauli.from_label('I' * num_qubits)]])
        vac_operator = vac_operator * a
        vac_operator.scaling_coeff(np.sqrt(2))

    return vac_operator
Exemplo n.º 49
0
 def _get_foot_graph(self):
     radius = self.distance/2.
     G = nx.Graph()
     query = ("""
         WITH origin AS
             (SELECT point
                 FROM rnodes_intersections
                 WHERE id = '%d')
         SELECT end1, end2, distance, run_score
             FROM routing_edges_latlon, origin
             WHERE
                 ST_Dwithin(origin.point::geography, point1::geography, %f) OR
                 ST_Dwithin(origin.point::geography, point2::geography, %f);"""
              % (self.start_node, radius, radius))
     self._cur.execute(query)
     G.add_edges_from([[int(node[0]), int(node[1]),
                        {'dist': node[2], 'run_score': node[3]}]
                       for node in self._cur.fetchall()])
     G_cycles = nx.Graph()
     for cycle in nx.cycle_basis(G):
         G_cycles.add_cycle(cycle)
     for edge in G.edges():
         if not G_cycles.has_edge(*edge):
             G.remove_edge(*edge)
     return G
Exemplo n.º 50
0
def get_subgraph_components(G, f):
    indgr = G.subgraph([item for sublist in f for item in sublist])
    cycles_undir = nx.cycle_basis(nx.Graph(indgr))
    cycles_undir_indgr=G.subgraph([item for sublist in cycles_undir for item in sublist])
    
    edges = []
    non_edges = [] # those arcs that go from reaction node to complex node
    for arc in indgr.edges():
        if indgr.node[arc[0]]['bipartite']==0:
            edges.append(arc)
        else:
            non_edges.append(arc)
    
    # cycle_edges = []
    # cycle_non_edges = []
    # for arc in cycles_undir_indgr.edges():
    #     if cycles_undir_indgr.node[arc[0]]['bipartite']==0:
    #         cycle_edges.append(arc)
    #     else:
    #         cycle_non_edges.append(arc)
    
    subgraph_components = {}
    for n in f[0]:
        subgraph_components[n]={'edges' : [], 'p_paths':[], 'n_paths':[]}
    
    # add edges starting in each complex node
    for e in edges:
        if e not in subgraph_components[e[0]]['edges']:
            subgraph_components[e[0]]['edges'].append(e)

    # add all positive paths
    # NOTE: it doesn't matter if a positive path is part of a cycle. here you want to add ALL positive paths
    # whether or not every positive path contributes to a sensible subgraph is decided later in validate_subgraph
    # for e in cycle_edges:
    #     for n in cycle_non_edges:
    for e in edges:
        for n in non_edges:
            if e[1]==n[0]:
                #print (e[0],e[1],n[1])
                p_edge = (e[0],e[1],n[1],'p')
                if p_edge not in subgraph_components[e[0]]['p_paths']:
                    subgraph_components[e[0]]['p_paths'].append(p_edge)

    # add all negative paths
    # NOTE: it doesn't matter if a negative path is part of a cycle. here you want to add ALL negative paths
    # whether or not every negative path contributes to a sensible subgraph is decided later in validate_subgraph
    # for e1 in cycle_edges:
    #     for e2 in cycle_edges:
    for e1 in edges:
        for e2 in edges:
            if e1[0] != e2[0] and e1[1]==e2[1]:
                #print (e1[0],e1[1],e2[0])
                n_edge = (e1[0],e1[1],e2[0],'n')
                if n_edge not in subgraph_components[e1[0]]['n_paths']:
                    subgraph_components[e1[0]]['n_paths'].append(n_edge)

    #print 'get_subgraph_components: len(subgraph_components) = '+str(len(subgraph_components))

    return subgraph_components
Exemplo n.º 51
0
    def detect_cycles(self):
        """
        function that returns a list of all (minimum cicles in the section)
        it uses an undirected version of the graph
        """

        # TODO: can we define the undirected graph on the fly here?
        self.cycles = nx.cycle_basis(self.g_ind)
Exemplo n.º 52
0
def find_rings(atoms):
    graph = Graph()
    for i, atom1 in enumerate(atoms):
        for atom2 in atoms[i+1:]:
            if is_bound(atom1.cart, atom1.element, atom2.cart, atom2.element):
                graph.add_edge(atom1.name, atom2.name)
    ring_list = cycle_basis(graph)
    return ring_list
Exemplo n.º 53
0
	def __cyclebasis(self):
		cb = self.__cbupdater.get_cyclebasis()

		# NOTE: this test is here because it is one of the only few paths that code
		#  reliably passes through where the current state of the modified cyclebasis
		#  and graph are both available.

		# FIXME: whatever happened to validate_cyclebasis?
		if len(cb) != len(nx.cycle_basis(self.__g)):

			# FIXME: This is an error (rather than assertion) due to an unresolved issue
			#  with the builder updater algorithm;  I CANNOT say with confidence that
			#  this will not occur. -_-
			raise RuntimeError('Cyclebasis has incorrect rank ({}, need {}).'.format(
				len(cb),len(nx.cycle_basis(self.__g))))

		return cb
Exemplo n.º 54
0
def assert_connected_acyclic_graph(G):
    """
    Check that the graph is connected and has no cycles.
    @param G: networkx undirected graph
    """
    if not nx.is_connected(G):
        raise Exception('the graph is not connected')
    if nx.cycle_basis(G):
        raise Exception('the graph has a cycle')
Exemplo n.º 55
0
    def find_network_cycle(self, root):
        """
        Finds network cycle with an optional root.

        Parameters:
        ===========
        - root    (str) the amino acid sequence to find a cycle with this root
        """
        return nx.cycle_basis(self.G, root)
Exemplo n.º 56
0
    def get(self, request, **kwargs):   #kwargs字典中包含url中路径的参数
        pk = kwargs['pk']

        NodeObj = ipran_node.objects.get(pk=pk)
        NodeName = NodeObj.NeName
        Ring = NodeObj.Ring

        linkList = ipran_link.objects.filter(Q(ring=Ring)&Q(isDelete=False)).values_list("source", "dest")
        linkList = list(linkList)
        nodeTuple = reduce(lambda x,y:x+y, linkList)     #[(1,2),(2,3)]-->(1,2,2,3)
        nodeTuple = tuple(set(nodeTuple))  #(1,2,2,3)-->{1,2,3}-->(1,2,3)
        rootNodeTuple = tuple(a for a in nodeTuple if re.match(r'^(HJ)|(HX)',a)) # 以HJ,HX开头的就是ASG
        rootLinkList = zip(*[iter(rootNodeTuple[i:]) for i in range(2)])   #(1,2,3,4)-->[(1,2),(2,3),(3,4)]    (1,)-->[]   ()-->[]
        print u"ASG:"
        for i in rootNodeTuple:
            print i

        linkList.extend(rootLinkList)

        G = nx.Graph()
        G.add_edges_from(linkList)
        
        try:
            CycleNode = nx.cycle_basis(G)[0]    #根据图生成环
        except:
            CycleNode = []    #无法生成环,则设环为空列表

        # print u"环路节点:"
        # for i in CycleNode:
            # print i
        
        if NodeName in CycleNode:    #如果想要查询的节点为环上节点,则移除其它环节点(不包括支链节点)
            CycleNode.remove(NodeName)
            G.remove_nodes_from(CycleNode)
        else:    #如果想要查询的节点不为环上节点,则计算带环节点至该节点的最短路径经过的节点,并移除。
            ShortestNode = nx.dijkstra_path(G,rootNodeTuple[0],NodeName) 
            ShortestNode.remove(NodeName)
            G.remove_nodes_from(ShortestNode)
            
        # print u"剔除后余下的节点:"
        # for i in G.node:
            # print i
        H = nx.dfs_tree(G,NodeName) #最后即可通过生成树协议获得节点所下带的节点
        Nnode = H.number_of_nodes()

        #接下来得分析下带的业务数及业务名称
        BusinessDictList = {'ring': Ring, '2G':[], '3G':[], 'LTE':[]}

        for node in H.nodes():
            print node
            NodeObj = ipran_node.objects.get(NeName=node)
            BusinessQuerySet = NodeObj.ipran_business_set.all()
            for BusinessObj in BusinessQuerySet:
                BusinessDictList.setdefault(BusinessObj.BusinessType, []).append(BusinessObj.TransStationName)
        
        return JsonResponse(BusinessDictList, safe=False)
Exemplo n.º 57
0
 def _findAccessComponentsDisjoint(self):
     self._nodes = self._subGraphSkeleton.nodes()
     self._nodeDegreeDict = nx.degree(self._subGraphSkeleton)
     self._branchPoints = [k for (k, v) in self._nodeDegreeDict.items() if v != 2 and v != 1]
     self._endPoints = [k for (k, v) in self._nodeDegreeDict.items() if v == 1]
     self._branchPoints.sort()
     self._endPoints.sort()
     self._cycleList = nx.cycle_basis(self._subGraphSkeleton)
     self._cycleCount = len(self._cycleList)
     self._degreeList = list(self._nodeDegreeDict.values())
Exemplo n.º 58
-1
def prune_graph(G):
    """
        Return a graph describing the loopy part of G, which is
        implicitly described by the list of cycles.
        The loopy part does not contain any

        (a) tree subgraphs of G
        (b) bridges of G

        Thus pruning may disconnect the graph into several 
        connected components.
    """
    cycles = nx.cycle_basis(G)
    pruned = G.copy()
    cycle_nodes = set(chain.from_iterable(cycles))
    cycle_edges = []

    for c in cycles:
        cycle = c + [c[0]]
        a, b = tee(cycle)
        next(b, None)
        edges = izip(a, b)

        cycle_edges.append(edges)
    
    all_cycle_edges = set(tuple(sorted(e)) \
            for e in chain.from_iterable(cycle_edges))
    # remove treelike components and bridges by removing all
    # edges not belonging to loops and then all nodes not
    # belonging to loops.
    pruned.remove_edges_from(e for e in G.edges_iter() \
            if (not tuple(sorted(e)) in all_cycle_edges))
    pruned.remove_nodes_from(n for n in G if not n in cycle_nodes)

    return pruned