Creates a basic graph out of an adjacency matrix.

    The matrix has to be a list of rows of values
    representing an adjacency matrix.
    The values can be anything: bool, int, float, as long
    as they can evaluate to True or False.
17136
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
    

    node_orig = 1

    if directed:
        graph = Dot(graph_type='digraph')
    else:
        graph = Dot(graph_type='graph')

    for row in matrix:
        if not directed:
            skip = matrix.index(row)
            r = row[skip:]
        else:
            skip = 0
            r = row
        node_dest = skip + 1

        for e in r:
            if e:
                graph.add_edge(
                    Edge(
                        node_prefix + node_orig,
                        node_prefix + node_dest))
            node_dest += 1
        node_orig += 1

    return graph
883012
def p_matrix(p):
    
    if len(p) == 3:
        p[0] = node.matrix()
    else:
        p[0] = node.matrix(p[2])
599255
def get_subgraph_from_edge_list(graph, edge_list):
    """"""
    node_list = get_vertices_from_edge_list(graph, edge_list)
    subgraph = make_subgraph(graph, node_list, edge_list)

    return subgraph
680584
def create(fmt):
        
        w = None
        if fmt == 'tree':
            w = AsciiTreeGraphRenderer()
        elif fmt == 'dot':
            w = DotGraphRenderer(image_format='dot')
        elif fmt == 'png':
            w = DotGraphRenderer(image_format='png')
        elif fmt == 'ndot':
            w = NativeDotGraphRenderer()
        elif fmt == 'obo':
            w = OboFormatGraphRenderer()
        elif fmt == 'obog':
            w = OboJsonGraphRenderer()
        else:
            w = SimpleListGraphRenderer()
        return w
707088
def _make_graph(self, max_insert):
        ''''''
        if len(self.partial_links) != 0:
            raise Error('Error in _make_graph(). Cannot continue because there are partial links')
        
        self.contig_links = {}
        for key in self.links:
            for l in self.links[key]:
                insert_size = l.insert_size()
                if insert_size <= max_insert:
                    if key not in self.contig_links:
                        self.contig_links[key] = {}
                    dirs = ''.join(l.dirs)
                    self.contig_links[key][dirs] = self.contig_links[key].get(dirs, 0) + 1
163003
def create_graph(grid):
    
    try:
        import numpy as np
    except ImportError:
        print(
            "NumPY is not installed. segraph needs NumPY to function. Please use 'pip install numpy' to install numpy.")
        exit(0)
    print("Creating a graph using segmented grid..")
    # get an array of unique labels
    try:
        vertices = np.unique(grid)

        # get number of vertices
        num_vertices = len(vertices)

        # map these unique labels to [1,...,N], where N is the number of labels (vertices)
        mapping = dict(zip(vertices, np.arange(num_vertices)))
        mapped_grid = np.array([mapping[x] for x in grid.flat]).reshape(grid.shape)

        # create edges, going left to right and top to bottom
        l2r = np.c_[mapped_grid[:, :-1].ravel(), mapped_grid[:, 1:].ravel()]
        t2b = np.c_[mapped_grid[:-1, :].ravel(), mapped_grid[1:, :].ravel()]

        # stack for entire graph
        edges = np.vstack([l2r, t2b])
        edges = edges[edges[:, 0] != edges[:, 1], :]
        edges = np.sort(edges, axis=1)

        # create a edge map, a hashmap
        edge_map = edges[:, 0] + num_vertices * edges[:, 1]

        # filter unique connections as edges
        edges = np.unique(edge_map)

        # reverse map and form edges as pairs
        edges = [[vertices[edge % num_vertices],
                  vertices[edge // num_vertices]] for edge in edges]
    except:
        print("Invalid argument supplied !")
        return None

    return vertices, edges
1266598
def _create_complete_graph(node_ids):
    
    g = nx.Graph()
    g.add_nodes_from(node_ids)
    for (i, j) in combinations(node_ids, 2):
        g.add_edge(i, j)
    return g
253851
def set_matrix(self, X, input_type):
        """"""
        if input_type == 'data':
            self.set_data_matrix(X)
        elif input_type == 'adjacency':
            self.set_adjacency_matrix(X)
        elif input_type == 'affinity':
            self.set_affinity_matrix(X)
        else:
            raise ValueError("Unrecognized input_type: {0}".format(input_type))
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
1285814
def get_vertices_from_edge_list(graph, edge_list):
    
    node_set = set()
    for edge_id in edge_list:
        edge = graph.get_edge(edge_id)
        a, b = edge['vertices']
        node_set.add(a)
        node_set.add(b)

    return list(node_set)
1130715
def get_numpy_array(self):
        
        # This holds the obect's spectral data, and will be passed to
        # numpy.array() to create a numpy array (matrix) for the matrix math
        # that will be done during the conversion to XYZ.
        values = []

        # Use the required value list to build this dynamically. Default to
        # 0.0, since that ultimately won't affect the outcome due to the math
        # involved.
        for val in self.VALUES:
            values.append(getattr(self, val, 0.0))

        # Create and the actual numpy array/matrix from the spectral list.
        color_array = numpy.array([values])
        return color_array
1062136
public static <K, VV, EV> Graph<K, VV, EV> fromDataSet(DataSet<Vertex<K, VV>> vertices,
			DataSet<Edge<K, EV>> edges, ExecutionEnvironment context) {

		return new Graph<>(vertices, edges, context);
	}
180062
def makediagram(edges):
    """"""
    graph = pydot.Dot(graph_type='digraph')
    nodes = edges2nodes(edges)
    epnodes = [(node, 
        makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"]
    endnodes = [(node, 
        makeendnode(node[0])) for node in nodes if nodetype(node)=="EndNode"]
    epbr = [(node, makeabranch(node)) for node in nodes if not istuple(node)]
    nodedict = dict(epnodes + epbr + endnodes)
    for value in list(nodedict.values()):
        graph.add_node(value)
    for e1, e2 in edges:
        graph.add_edge(pydot.Edge(nodedict[e1], nodedict[e2]))
    return graph
1313739
def graph_to_dimacs(g, f):
    
    # write comments
    f.write('c Created by medpy\n')
    f.write('c Oskar Maier, oskar.maier@googlemail.com\n')
    f.write('c\n')
    
    # write problem
    f.write('c problem line\n')
    f.write('p max {} {}\n'.format(g.get_node_count() + 2, len(g.get_edges()))) # +2 as terminal nodes also count in dimacs format # no-nodes / no-edges
    
    # denote source and sink
    f.write('c source descriptor\n')
    f.write('n 1 s\n')
    f.write('c sink descriptor\n')
    f.write('n 2 t\n')
    
    # write terminal arcs (t-weights)
    f.write('c terminal arcs (t-weights)\n')
    for node, weight in list(g.get_tweights().items()):
        # Note: the nodes ids of the graph start from 1, but 1 and 2 are reserved for source and sink respectively, therefore add 2
        if not 0 == weight[0]: # 0 weights are implicit
            f.write('a 1 {} {}\n'.format(node + 2, weight[0]))
        if not 0 == weight[1]: # 0 weights are implicit
            f.write('a {} 2 {}\n'.format(node + 2, weight[1]))
    
    # write inter-node arcs (n-weights)
    f.write('c inter-node arcs (n-weights)\n')
    for edge, weight in list(g.get_nweights().items()):
        if not 0 == weight[0]: # 0 weights are implicit
            f.write('a {} {} {}\n'.format(edge[0] + 2, edge[1] + 2, weight[0]))
        # reversed weights have to follow directly in the next line
        if not 0 == weight[1]: # 0 weights are implicit
            f.write('a {} {} {}\n'.format(edge[1] + 2, edge[0] + 2, weight[1]))
            
    # end comment
    f.write('c end-of-file')
1320897
def get_adjacency_matrix(df_connected):
    '''
    
    '''
    sorted_path_keys = np.sort(np.unique(df_connected[['source', 'target']]
                                         .values.ravel()))
    indexed_paths = pd.Series(sorted_path_keys)
    path_indexes = pd.Series(indexed_paths.index, index=sorted_path_keys)

    adjacency_matrix = np.zeros((path_indexes.shape[0], ) * 2, dtype=int)
    for i_key, j_key in df_connected[['source', 'target']].values:
        i, j = path_indexes.loc[[i_key, j_key]]
        adjacency_matrix[i, j] = 1
        adjacency_matrix[j, i] = 1
    return adjacency_matrix, indexed_paths, path_indexes
120595
def _SGraphFromJsonTree(json_str):
    
    g = json.loads(json_str)
    vertices = [_Vertex(x['id'],
                dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
                                                      for x in g['vertices']]
    edges = [_Edge(x['src'], x['dst'],
             dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'src' and k != 'dst']))
                                                      for x in g['edges']]
    sg = _SGraph().add_vertices(vertices)
    if len(edges) > 0:
        sg = sg.add_edges(edges)
    return sg
737479
def convert_to_adjacency_matrix(matrix):
    
    for i in range(matrix.shape[0]):
        
        if isspmatrix(matrix):
            col = find(matrix[:,i])[2]
        else:
            col = matrix[:,i].T.tolist()[0]

        coeff = max( Fraction(c).limit_denominator().denominator for c in col )
        matrix[:,i] *= coeff

    return matrix