Ejemplo n.º 1
0
def read_gml(gml, graph=None):
    """
    Read graph in GML format

    :param gml:             GML graph data.
    :type gml:              File, string, stream or URL
    :param graph:           Graph object to import GML data in
    :type graph:            :graphit:Graph

    :return:                Graph object
    :rtype:                 :graphit:Graph
    """

    # User defined or default Graph object
    if graph is None:
        graph = Graph()
    elif not isinstance(graph, Graph):
        raise GraphitException('Unsupported graph type {0}'.format(type(graph)))

    # Parse GML into nested structure of Record class instances
    gml_stream = StreamReader(open_anything(gml))
    records = Record(gml_stream, name='root')

    gml_graphs = [g for g in records if g.name == 'graph']
    if len(gml_graphs) > 1:
        logging.warning("GML file contains {0} 'graph' objects. Only parse first".format(len(gml_graphs)))
    gml_graph_record = gml_graphs[0]

    # GML node and edge labels are unique, turn off auto_nid
    graph.data['auto_nid'] = False

    # Set graph meta-data and attributes
    graph_attr = gml_graph_record.to_dict({})
    graph.directed = True
    if 'directed' in graph_attr:
        directed = graph_attr.pop('directed')
        graph.directed = True if directed == 1 else False
        graph.data['directed'] = graph.directed

    graph.data.update(graph_attr)

    # Build graph from records
    build_nodes(graph, gml_graph_record)
    build_edges(graph, gml_graph_record)

    return graph
Ejemplo n.º 2
0
def read_tgf(tgf, graph=None, key_tag=None):
    """
    Read graph in Trivial Graph Format
    
    TGF format dictates that nodes to be listed in the file first with each
    node on a new line. A '#' character signals the end of the node list and
    the start of the edge list.
    
    Node and edge ID's can be integers, float or strings. They are parsed
    automatically to their most likely format.
    Simple node and edge labels are supported in TGF as all characters that
    follow the node or edge ID's. They are parsed and stored in the Graph
    node and edge data stores using the graphs default or custom 'key_tag'.
    
    TGF data is imported into a default Graph object if no custom Graph
    instance is provided. The graph behaviour and the data import process is
    influenced and can be controlled using a (custom) Graph class.
    
    .. note:: TGF format always defines edges in a directed fashion.
              This is enforced even for custom graphs.
    
    :param tgf:             TGF graph data.
    :type tgf:              File, string, stream or URL
    :param graph:           Graph object to import TGF data in
    :type graph:            :graphit:Graph
    :param key_tag:         Data key to use for parsed node/edge labels.
    :type key_tag:          :py:str
    
    :return:                Graph object
    :rtype:                 :graphit:Graph
    """

    tgf_file = open_anything(tgf)
    if not isinstance(graph, Graph):
        graph = Graph()

    # Define node/edge data labels
    if key_tag:
        graph.key_tag = key_tag

    # TGF defines edges in a directed fashion. Enforce but restore later
    default_directionality = graph.directed
    graph.directed = True

    # TGF node and edge labels are unique, turn off auto_nid
    graph.auto_nid = False

    # Start parsing. First extract nodes
    nodes = True
    node_dict = {}
    for line in tgf_file.readlines():

        line = line.strip()
        if len(line):

            # Reading '#' character means switching from node
            # definition to edges
            if line.startswith('#'):
                nodes = False
                continue

            # Coarse string to types
            line = [coarse_type(n) for n in line.split()]

            # Parse nodes
            if nodes:

                attr = {}
                # Has node data
                if len(line) > 1:
                    attr = {graph.key_tag: ' '.join(line[1:])}
                nid = graph.add_node(line[0], **attr)
                node_dict[line[0]] = nid

            # Parse edges
            else:
                e1 = node_dict[line[0]]
                e2 = node_dict[line[1]]

                attr = {}
                # Has edge data
                if len(line) > 2:
                    attr = {graph.key_tag: ' '.join(line[2:])}
                graph.add_edge(e1, e2, **attr)

    tgf_file.close()

    # Restore directionality
    graph.directed = default_directionality

    return graph
Ejemplo n.º 3
0
def read_lgf(lgf, graph=None):
    """
    Read graph in LEMON Graph Format (LGF)

    :param lgf:             LGF graph data.
    :type lgf:              File, string, stream or URL
    :param graph:           Graph object to import LGF data in
    :type graph:            :graphit:Graph

    :return:                Graph object
    :rtype:                 :graphit:Graph
    """

    lgf_file = open_anything(lgf)

    # User defined or default Graph object
    if graph is None:
        graph = Graph()
    elif not isinstance(graph, Graph):
        raise GraphitException('Unsupported graph type {0}'.format(
            type(graph)))

    # LGF node and edge labels are unique, turn off auto_nid
    graph.data['auto_nid'] = False

    parser = None
    header = None
    did_parse_nodes = False
    is_directed = False
    for line in lgf_file.readlines():
        line = line.strip()

        # Skip empty lines and comment lines
        if not len(line) or line.startswith('#'):
            parser = None
            continue

        # Define parser
        if line.startswith('@') or parser is None:
            if 'nodes' in line:
                parser = parse_nodes
                did_parse_nodes = True
            elif line.startswith('@edges'):
                parser = parse_edges
            elif line.startswith('@arcs'):
                parser = parse_arcs
                is_directed = True
            elif line.startswith('@attributes'):
                logging.warning(
                    'Not importing LGF @attributes. Graph attributes not supported by graphit'
                )
            header = None
            continue

        # Immediately after parser definition, parse table column headers
        if header is None:
            header = split_line(line)
            continue

        parser(line, header, graph, did_parse_nodes=did_parse_nodes)

    # Set graph to 'directed' if arcs where parsed
    if is_directed:
        graph.directed = True

    return graph
Ejemplo n.º 4
0
def read_p2g(p2g_file, graph=None):
    """
    Read graph in P2G format

    :param p2g_file:      P2G data to parse
    :type p2g_file:       File, string, stream or URL
    :param graph:         Graph object to import to or Graph by default
    :type graph:          :graphit:Graph

    :return:              Graph instance
    :rtype:               :graphit:Graph
    """

    p2g_file = open_anything(p2g_file)

    if graph is None:
        graph = Graph()
    elif not isinstance(graph, Graph):
        raise GraphitException('Unsupported graph type {0}'.format(
            type(graph)))

    # P2G graphs are directed
    graph.directed = True

    graph_name = None
    graph_layout = None
    curr_node = None
    nodes = {}
    for i, line in enumerate(p2g_file.readlines()):

        line = line.strip()
        if line:

            # Parse p2g graph name (first line)
            sline = line.split()
            if not graph_name:
                graph_name = line
                continue

            # Parse number of nodes and edges (second line)
            elif not graph_layout:
                try:
                    graph_layout = map(int, sline)
                except ValueError:
                    raise GraphitException(
                        'P2G import error: line {0} - {1}'.format(i, line))
                continue

            # Parse nodes and edges
            if len(sline) == 1:
                nodes[line] = []
                curr_node = line
            elif len(sline) == 2:
                try:
                    nodes[curr_node] = map(int, sline)
                except ValueError:
                    raise GraphitException(
                        'P2G import error: malformed edge on line {0} - {1}'.
                        format(i, line))
            else:
                raise GraphitException(
                    'P2G import error: line {0} - {1}'.format(i, line))

    graph.data['name'] = graph_name

    # Add nodes
    mapped_nodes = graph.add_nodes(nodes.keys())

    # Add edges
    for i, nid in enumerate(nodes.keys()):
        for e in nodes[nid]:
            if e < len(mapped_nodes):
                graph.add_edge(mapped_nodes[i], mapped_nodes[e])
            else:
                raise GraphitException(
                    'P2G import error: edge node index {0} not in graph'.
                    format(e))

    if len(nodes) != graph_layout[0] or (len(graph.edges)) != graph_layout[1]:
        logging.warning(
            'P2G import warning: declared number of nodes and edges {0}-{1} does not match {2}-{3}'
            .format(graph_layout[0], graph_layout[1], len(nodes),
                    len(graph.edges)))

    return graph
Ejemplo n.º 5
0
def read_lgr(lgr, graph=None, edge_label='label'):
    """
    Read graph in LEDA format

    Nodes are added to the graph using a unique ID or with the node data
    as label depending if the graph.data.auto_nid is True or False.
    Edge data is added to the edge attributes using `edge_label` as key.
    The data types for both nodes and edges is set according to the
    specifications in the LEDA header as either string, int, float or bool.

    :param lgr:             LEDA graph data.
    :type lgr:              File, string, stream or URL
    :param graph:           Graph object to import LEDA data in
    :type graph:            :graphit:Graph
    :param edge_label:      edge data label name
    :type edge_label:       :py:str

    :return:                Graph object
    :rtype:                 :graphit:Graph
    :raises:                TypeError if node/edge type conversion failed
                            GraphitException in case of malformed LEDA file
    """

    # User defined or default Graph object
    if graph is None:
        graph = Graph()
    elif not isinstance(graph, Graph):
        raise GraphitException('Unsupported graph type {0}'.format(
            type(graph)))

    # Parse LEDA file
    lgr_file = open_anything(lgr)
    header = []
    nodes = []
    edges = []
    container = header
    for line in lgr_file.readlines():
        line = line.strip()

        if line:
            if line.startswith('#header'):
                container = header
                continue
            if line.startswith('#nodes'):
                container = nodes
                continue
            if line.startswith('#edges'):
                container = edges
                continue

            container.append(line)

    # Parse LEDA header
    if not header[0] == 'LEDA.GRAPH':
        raise GraphitException('File is not a valid LEDA graph format')

    # Node and edge data types and graph directionality
    node_type = data_types.get(header[1])
    edge_type = data_types.get(header[2])
    graph.directed = int(header[3]) == -1

    # Parse LEDA nodes
    node_mapping = {}
    for i, node in enumerate(nodes[1:], start=1):
        data = node.strip('|{}|') or None
        if node_type and data:
            data = node_type(data)
        nid = graph.add_node(data)
        node_mapping[i] = nid

    # Parse LEDA edges
    for edge in edges[1:]:
        try:
            source, target, reversal, label = edge.split()
        except ValueError:
            raise GraphitException(
                'Too few fields in LEDA edge {0}'.format(edge))

        attr = {edge_label: label.strip('|{}|') or None}
        if edge_type and attr[edge_label]:
            attr[edge_label] = edge_type(attr[edge_label])
        graph.add_edge(node_mapping[int(source)], node_mapping[int(target)],
                       **attr)

    return graph
Ejemplo n.º 6
0
def read_gexf(gexf_file, graph=None):
    """
    Read graphs in GEXF format

    Uses the Python build-in etree cElementTree parser to parse the XML
    document and convert the elements into nodes.
    The XML element tag becomes the node key, XML text becomes the node
    value and XML attributes are added to the node as additional attributes.

    :param gexf_file:      XML data to parse
    :type gexf_file:       File, string, stream or URL
    :param graph:          Graph object to import dictionary data in
    :type graph:           :graphit:Graph

    :return:               GraphAxis object
    :rtype:                :graphit:GraphAxis
    """

    gexf_file = open_anything(gexf_file)

    # User defined or default Graph object
    if graph is None:
        graph = Graph()
    elif not isinstance(graph, Graph):
        raise GraphitException('Unsupported graph type {0}'.format(
            type(graph)))

    # Try parsing the string using default Python cElementTree parser
    try:
        tree = et.fromstring(gexf_file.read())
    except et.ParseError as error:
        logging.error(
            'Unable to parse GEXF file. cElementTree error: {0}'.format(error))
        return

    # Get XMLNS namespace from root
    xmlns = None
    for elem in tree.iter():
        if elem.tag.endswith('gexf'):
            xmlns = elem.tag.split('}')[0] + '}'
            break

    if xmlns is None:
        raise GraphitException(
            'Invalid GEXF file format, "gexf" tag not found')

    # Add graph meta-data and XMLNS namespace
    for meta in tree.iter('{0}meta'.format(xmlns)):
        graph.data.update(meta.attrib)
        for meta_data in meta:
            tag = meta_data.tag.split('}')[1]
            graph.data[tag] = meta_data.text

    # GEXF node and edge labels are unique, turn off auto_nid
    graph.data['auto_nid'] = False

    graph_tag = tree.find('{0}graph'.format(xmlns))
    graph.directed = graph_tag.get('defaultedgetype', 'directed') == 'directed'
    graph.data.update(graph_tag.attrib)

    # Parse all nodes
    nodes = tree.findall('.//{0}node'.format(xmlns))
    if not len(nodes):
        raise GraphitException('GEXF file containes no "node" elements')
    for node in nodes:
        attr = node.attrib
        attr = parse_attvalue_elements(node, attr, xmlns=xmlns)
        graph.add_node(attr['id'],
                       **dict([n for n in attr.items() if n[0] != 'id']))

    # Parse all edges
    edges = tree.findall('.//{0}edge'.format(xmlns))
    for edge in edges:
        attr = edge.attrib

        # Edge direction differs from global graph directionality
        edge_directed = graph.directed
        if 'type' in attr:
            edge_directed = attr['type'] == 'directed'

        attr = parse_attvalue_elements(edge, attr, xmlns=xmlns)
        graph.add_edge(attr['source'],
                       attr['target'],
                       directed=edge_directed,
                       **dict([
                           n for n in attr.items()
                           if n[0] not in ('source', 'target')
                       ]))

    logger.info('Import graph in GEXF format. XMLNS: {0}'.format(xmlns))

    return graph