Python networkx.NetworkXError() Examples

The following are 30 code examples of networkx.NetworkXError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def _spectral(A, dim=2):
    # Input adjacency matrix A
    # Uses dense eigenvalue solver from numpy
    try:
        import numpy as np
    except ImportError:
        raise ImportError("spectral_layout() requires numpy: http://scipy.org/ ")
    try:
        nnodes,_=A.shape
    except AttributeError:
        raise nx.NetworkXError(\
            "spectral() takes an adjacency matrix as input")

    # form Laplacian matrix
    # make sure we have an array instead of a matrix
    A=np.asarray(A)
    I=np.identity(nnodes,dtype=A.dtype)
    D=I*np.sum(A,axis=1) # diagonal of degrees
    L=D-A

    eigenvalues,eigenvectors=np.linalg.eig(L)
    # sort and keep smallest nonzero
    index=np.argsort(eigenvalues)[1:dim+1] # 0 index is zero eigenvalue
    return np.real(eigenvectors[:,index]) 
Example #2
Source File: dyndigraph.py    From dynetx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def predecessors_iter(self, n, t=None):
        """Return an iterator over predecessors nodes of n at time t (optional).

        Parameters
        ----------
        n : node
            Nodes can be, for example, strings or numbers.
            Nodes must be hashable (and not None) Python objects.
        t : snapshot id (default=None)
            If None will be returned the presence of the interaction on the flattened graph.


        """
        try:
            if t is None:
                return iter(self._pred[n])
            else:
                return iter([i for i in self._pred[n] if self.__presence_test(i, n, t)])
        except KeyError:
            raise nx.NetworkXError("The node %s is not in the graph." % (n,)) 
Example #3
Source File: test_gml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_relabel_duplicate(self):
        data = """
graph
[
	label	""
	directed	1
	node
	[
		id	0
		label	"same"
	]
	node
	[
		id	1
		label	"same"
	]
]
"""
        fh = io.BytesIO(data.encode('UTF-8'))
        fh.seek(0)
        assert_raises(
            nx.NetworkXError, nx.read_gml, fh, label='label') 
Example #4
Source File: state_hierarchy.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _remove_history(self, h):
        try:
            predecessors = self._graph.predecessors(h)
            successors = self._graph.successors(h)

            for p,s in itertools.product(predecessors, successors):
                self._graph.add_edge(p, s)

            self._graph.remove_node(h)
        except networkx.NetworkXError:
            pass

        self._leaves.discard(h)
        self._twigs.discard(h)
        hh = h()
        if hh is not None:
            hh.demote() 
Example #5
Source File: test_gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_directed_edge_in_undirected(self):
        s="""<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.1draft" version="1.1">
    <graph mode="static" defaultedgetype="undirected">
        <nodes>
            <node id="0" label="Hello" />
            <node id="1" label="Word" />
        </nodes>
        <edges>
            <edge id="0" source="0" target="1" type="directed"/>
        </edges>
    </graph>
</gexf>
"""
        fh = io.BytesIO(s.encode('UTF-8'))
        assert_raises(nx.NetworkXError,nx.read_gexf,fh) 
Example #6
Source File: test_gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_key_error(self):
        s="""<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.1draft" version="1.1">
    <graph mode="static" defaultedgetype="directed">
        <nodes>
            <node id="0" label="Hello">
              <attvalues>
                <attvalue for='0' value='1'/>
              </attvalues>
            </node>
            <node id="1" label="Word" />
        </nodes>
        <edges>
            <edge id="0" source="0" target="1" type="undirected"/>
        </edges>
    </graph>
</gexf>
"""
        fh = io.BytesIO(s.encode('UTF-8'))
        assert_raises(nx.NetworkXError,nx.read_gexf,fh) 
Example #7
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_is_weighted(self):
        G = nx.Graph()
        assert_false(nx.is_weighted(G))

        G = nx.path_graph(4)
        assert_false(nx.is_weighted(G))
        assert_false(nx.is_weighted(G, (2, 3)))

        G.add_node(4)
        G.add_edge(3, 4, weight=4)
        assert_false(nx.is_weighted(G))
        assert_true(nx.is_weighted(G, (3, 4)))

        G = nx.DiGraph()
        G.add_weighted_edges_from([('0', '3', 3), ('0', '1', -5), ('1', '0', -5),
                                     ('0', '2', 2), ('1', '2', 4),
                                     ('2', '3', 1)])
        assert_true(nx.is_weighted(G))
        assert_true(nx.is_weighted(G, ('1', '0')))

        G = G.to_undirected()
        assert_true(nx.is_weighted(G))
        assert_true(nx.is_weighted(G, ('1', '0')))

        assert_raises(nx.NetworkXError, nx.is_weighted, G, (1, 2)) 
Example #8
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_info_digraph(self):
        G=nx.DiGraph(name='path_graph(5)')
        G.add_path([0,1,2,3,4])
        info=nx.info(G)
        expected_graph_info='\n'.join(['Name: path_graph(5)',
                                       'Type: DiGraph',
                                       'Number of nodes: 5',
                                       'Number of edges: 4',
                                       'Average in degree:   0.8000',
                                       'Average out degree:   0.8000'])
        assert_equal(info,expected_graph_info)

        info=nx.info(G,n=1)
        expected_node_info='\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 2'])
        assert_equal(info,expected_node_info)

        assert_raises(nx.NetworkXError,nx.info,G,n=-1) 
Example #9
Source File: descriptors.py    From PyPSA with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, data=None, **attr):
            self.node_dict_factory = ndf = self.node_dict_factory
            self.adjlist_dict_factory = self.adjlist_dict_factory
            self.edge_attr_dict_factory = self.edge_attr_dict_factory

            self.graph = {}   # dictionary for graph attributes
            self.node = ndf()  # empty node attribute dict
            self.adj = ndf()  # empty adjacency dict
            # attempt to load graph with data
            if data is not None:
                if isinstance(data, OrderedGraph):
                    try:
                        nx.convert.from_dict_of_dicts(
                            data.adj,
                            create_using=self,
                            multigraph_input=data.is_multigraph()
                        )
                        self.graph = data.graph.copy()
                        self.node.update((n,d.copy()) for n,d in data.node.items())
                    except:
                        raise nx.NetworkXError("Input is not a correct NetworkX graph.")
                else:
                    nx.convert.to_networkx_graph(data, create_using=self) 
Example #10
Source File: historical_tests.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_iterators(self):
        G=self.G()
        G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'), 
                          ('C', 'B'), ('C', 'D')])
        G.add_nodes_from('GJK')
        assert_equal(sorted(G.nodes_iter()),
                     ['A', 'B', 'C', 'D', 'G', 'J', 'K'])
        assert_edges_equal(G.edges_iter(),
        [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'B'), ('C', 'D')])

        assert_equal(sorted([v for k,v in G.degree_iter()]),
                     [0, 0, 0, 2, 2, 3, 3])
        assert_equal(sorted(G.degree_iter(),key=str),
                     [('A', 2), ('B', 3), ('C', 3), ('D', 2), 
                      ('G', 0), ('J', 0), ('K', 0)])
        assert_equal(sorted(G.neighbors_iter('A')),['B', 'C'])
        assert_raises(nx.NetworkXError,G.neighbors_iter,'X')
        G.clear()
        assert_equal(nx.number_of_nodes(G),0)
        assert_equal(nx.number_of_edges(G),0) 
Example #11
Source File: dyngraph.py    From dynetx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def neighbors_iter(self, n, t=None):
        """Return an iterator over all neighbors of node n at time t.

        Parameters
        ----------
        n : node
           A node in the graph
        t : snapshot id (default=None)
            If None will be returned an iterator over the neighbors of the node on the flattened graph.

        Examples
        --------
        >>> import dynetx as dn
        >>> G = dn.DynGraph()
        >>> G.add_path([0,1,2,3], t=0)
        >>> [n for n in G.neighbors_iter(0, t=0)]
        [1]
        """
        try:
            if t is None:
                return iter(self._adj[n])
            else:
                return iter([i for i in self._adj[n] if self.__presence_test(n, i, t)])
        except KeyError:
            raise nx.NetworkXError("The node %s is not in the graph." % (n,)) 
Example #12
Source File: ontology_graph.py    From indra with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _transitive_rel(self, ns, id, rel_fun, rel_types, target=None):
        source = (ns, id)
        visited = {source}
        queue = deque([(source,
                        rel_fun(*source, rel_types))])
        while queue:
            parent, children = queue[0]
            try:
                child = next(children)
                if target and child == target:
                    return [target]
                if child not in visited:
                    visited.add(child)
                    queue.append((child,
                                  rel_fun(*child, rel_types)))
            except networkx.NetworkXError as e:
                logger.debug(e)
                return []
            except StopIteration:
                queue.popleft()
        return list(visited - {source}) 
Example #13
Source File: dyndigraph.py    From dynetx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def successors_iter(self, n, t=None):
        """
        Return an iterator over successor nodes of n at time t (optional).

        Parameters
        ----------
        n : node
            Nodes can be, for example, strings or numbers.
            Nodes must be hashable (and not None) Python objects.
        t : snapshot id (default=None)
            If None will be returned the presence of the interaction on the flattened graph.

        """
        try:
            if t is None:
                return iter(self._succ[n])
            else:
                return iter([i for i in self._succ[n] if self.__presence_test(n, i, t)])
        except KeyError:
            raise nx.NetworkXError("The node %s is not in the graph." % (n,)) 
Example #14
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_is_negatively_weighted(self):
        G = nx.Graph()
        assert_false(nx.is_negatively_weighted(G))

        G.add_node(1)
        G.add_nodes_from([2, 3, 4, 5])
        assert_false(nx.is_negatively_weighted(G))

        G.add_edge(1, 2, weight=4)
        assert_false(nx.is_negatively_weighted(G, (1, 2)))

        G.add_edges_from([(1, 3), (2, 4), (2, 6)])
        G[1][3]['color'] = 'blue'
        assert_false(nx.is_negatively_weighted(G))
        assert_false(nx.is_negatively_weighted(G, (1, 3)))

        G[2][4]['weight'] = -2
        assert_true(nx.is_negatively_weighted(G, (2, 4)))
        assert_true(nx.is_negatively_weighted(G))

        G = nx.DiGraph()
        G.add_weighted_edges_from([('0', '3', 3), ('0', '1', -5), ('1', '0', -2),
                                   ('0', '2', 2), ('1', '2', -3), ('2', '3', 1)])
        assert_true(nx.is_negatively_weighted(G))
        assert_false(nx.is_negatively_weighted(G, ('0', '3')))
        assert_true(nx.is_negatively_weighted(G, ('1', '0')))

        assert_raises(nx.NetworkXError, nx.is_negatively_weighted, G, (1, 4)) 
Example #15
Source File: graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def find_graphml_keys(self, graph_element):
        """Extracts all the keys and key defaults from the xml.
        """
        graphml_keys = {}
        graphml_key_defaults = {}
        for k in graph_element.findall("{%s}key" % self.NS_GRAPHML):
            attr_id = k.get("id")
            attr_type=k.get('attr.type')
            attr_name=k.get("attr.name")
            yfiles_type=k.get("yfiles.type")
            if yfiles_type is not None:
                attr_name = yfiles_type
                attr_type = 'yfiles'
            if attr_type is None:
                attr_type = "string"
                warnings.warn("No key type for id %s. Using string"%attr_id)
            if attr_name is None:
                raise nx.NetworkXError("Unknown key for id %s in file."%attr_id)
            graphml_keys[attr_id] = {
                "name":attr_name,
                "type":self.python_type[attr_type],
                "for":k.get("for")}
            # check for "default" subelement of key element
            default=k.find("{%s}default" % self.NS_GRAPHML)
            if default is not None:
                graphml_key_defaults[attr_id]=default.text
        return graphml_keys,graphml_key_defaults

# fixture for nose tests 
Example #16
Source File: test_multidigraph.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_edges_data(self):
        G=self.K3
        assert_equal(sorted(G.edges(data=True)),
                     [(0,1,{}),(0,2,{}),(1,0,{}),(1,2,{}),(2,0,{}),(2,1,{})])
        assert_equal(sorted(G.edges(0,data=True)),[(0,1,{}),(0,2,{})])
        assert_raises((KeyError,networkx.NetworkXError), G.neighbors,-1) 
Example #17
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_freeze(self):
        G=nx.freeze(self.G)
        assert_equal(G.frozen,True)
        assert_raises(nx.NetworkXError, G.add_node, 1)
        assert_raises(nx.NetworkXError, G.add_nodes_from, [1])
        assert_raises(nx.NetworkXError, G.remove_node, 1)
        assert_raises(nx.NetworkXError, G.remove_nodes_from, [1])
        assert_raises(nx.NetworkXError, G.add_edge, 1,2)
        assert_raises(nx.NetworkXError, G.add_edges_from, [(1,2)])
        assert_raises(nx.NetworkXError, G.remove_edge, 1,2)
        assert_raises(nx.NetworkXError, G.remove_edges_from, [(1,2)])
        assert_raises(nx.NetworkXError, G.clear) 
Example #18
Source File: graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def add_data(self, name, element_type, value,
                 scope="all",
                 default=None):
        """
        Make a data element for an edge or a node. Keep a log of the
        type in the keys table.
        """
        if element_type not in self.xml_type:
            raise nx.NetworkXError('GraphML writer does not support '
                                   '%s as data values.'%element_type)
        key_id = self.get_key(name, self.xml_type[element_type], scope, default)
        data_element = Element("data", key=key_id)
        data_element.text = make_str(value)
        return data_element 
Example #19
Source File: test_function.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_nonexistent_nodes(self):
        G = nx.complete_graph(5)
        assert_raises(nx.NetworkXError, nx.common_neighbors, G, 5, 4)
        assert_raises(nx.NetworkXError, nx.common_neighbors, G, 4, 5)
        assert_raises(nx.NetworkXError, nx.common_neighbors, G, 5, 6) 
Example #20
Source File: test_multidigraph.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_in_edges(self):
        G=self.K3
        assert_equal(sorted(G.in_edges()),
                     [(0,1),(0,2),(1,0),(1,2),(2,0),(2,1)])
        assert_equal(sorted(G.in_edges(0)),[(1,0),(2,0)])
        assert_raises((KeyError,networkx.NetworkXError), G.in_edges,-1)
        G.add_edge(0,1,2)
        assert_equal(sorted(G.in_edges()),
                     [(0,1),(0,1),(0,2),(1,0),(1,2),(2,0),(2,1)])
        assert_equal(sorted(G.in_edges(0,keys=True)),[(1,0,0),(2,0,0)]) 
Example #21
Source File: test_multidigraph.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_successors(self):
        G=self.K3
        assert_equal(sorted(G.successors(0)),[1,2])
        assert_raises((KeyError,networkx.NetworkXError), G.successors,-1) 
Example #22
Source File: graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def add_edge(self, G, edge_element, graphml_keys):
        """Add an edge to the graph.
        """
        # warn on finding unsupported ports tag
        ports=edge_element.find("{%s}port" % self.NS_GRAPHML)
        if ports is not None:
            warnings.warn("GraphML port tag not supported.")

        # raise error if we find mixed directed and undirected edges
        directed = edge_element.get("directed")
        if G.is_directed() and directed=='false':
            raise nx.NetworkXError(\
                "directed=false edge found in directed graph.")
        if (not G.is_directed()) and directed=='true':
            raise nx.NetworkXError(\
                "directed=true edge found in undirected graph.")

        source = self.node_type(edge_element.get("source"))
        target = self.node_type(edge_element.get("target"))
        data = self.decode_data_elements(graphml_keys, edge_element)
        # GraphML stores edge ids as an attribute
        # NetworkX uses them as keys in multigraphs too if no key
        # attribute is specified
        edge_id = edge_element.get("id")
        if edge_id:
            data["id"] = edge_id
        if G.has_edge(source,target):
            # mark this as a multigraph
            self.multigraph=True
        if edge_id is None:
            # no id specified, try using 'key' attribute as id
            edge_id=data.pop('key',None)
        G.add_edge(source, target, key=edge_id, **data) 
Example #23
Source File: graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def make_graph(self, graph_xml, graphml_keys, defaults):
        # set default graph type
        edgedefault = graph_xml.get("edgedefault", None)
        if edgedefault=='directed':
            G=nx.MultiDiGraph()
        else:
            G=nx.MultiGraph()
        # set defaults for graph attributes
        G.graph['node_default']={}
        G.graph['edge_default']={}
        for key_id,value in defaults.items():
            key_for=graphml_keys[key_id]['for']
            name=graphml_keys[key_id]['name']
            python_type=graphml_keys[key_id]['type']
            if key_for=='node':
                G.graph['node_default'].update({name:python_type(value)})
            if key_for=='edge':
                G.graph['edge_default'].update({name:python_type(value)})
        # hyperedges are not supported
        hyperedge=graph_xml.find("{%s}hyperedge" % self.NS_GRAPHML)
        if hyperedge is not None:
            raise nx.NetworkXError("GraphML reader does not support hyperedges")
        # add nodes
        for node_xml in graph_xml.findall("{%s}node" % self.NS_GRAPHML):
            self.add_node(G, node_xml, graphml_keys)
        # add edges
        for edge_xml in graph_xml.findall("{%s}edge" % self.NS_GRAPHML):
            self.add_edge(G, edge_xml, graphml_keys)
        # add graph data
        data = self.decode_data_elements(graphml_keys, graph_xml)
        G.graph.update(data)

        # switch to Graph or DiGraph if no parallel edges were found.
        if not self.multigraph:
            if G.is_directed():
                return nx.DiGraph(G)
            else:
                return nx.Graph(G)
        else:
            return G 
Example #24
Source File: test_graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_undirected_edge_in_directed(self):
        s="""<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault='directed'>
    <node id="n0"/>
    <node id="n1"/>
    <node id="n2"/>
    <edge source="n0" target="n1"/>
    <edge source="n1" target="n2" directed='false'/>
  </graph>
</graphml>"""
        fh = io.BytesIO(s.encode('UTF-8'))
        assert_raises(nx.NetworkXError,nx.read_graphml,fh)
        assert_raises(nx.NetworkXError,nx.parse_graphml,s) 
Example #25
Source File: gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def decode_attr_elements(self, gexf_keys, obj_xml):
        # Use the key information to decode the attr XML
        attr = {}
        # look for outer "<attvalues>" element
        attr_element=obj_xml.find("{%s}attvalues" % self.NS_GEXF)
        if attr_element is not None:
            # loop over <attvalue> elements
            for a in attr_element.findall("{%s}attvalue" % self.NS_GEXF):
                key = a.get('for') # for is required
                try: # should be in our gexf_keys dictionary
                    title=gexf_keys[key]['title']
                except KeyError:
                    raise nx.NetworkXError("No attribute defined for=%s"%key)
                atype=gexf_keys[key]['type']
                value=a.get('value')
                if atype=='boolean':
                    value=self.convert_bool[value]
                else:
                    value=self.python_type[atype](value)
                if gexf_keys[key]['mode']=='dynamic':
                    # for dynamic graphs use list of three-tuples
                    # [(value1,start1,end1), (value2,start2,end2), etc]
                    ttype = self.timeformat
                    start=self.python_type[ttype](a.get('start'))
                    end=self.python_type[ttype](a.get('end'))
                    if title in attr:
                        attr[title].append((value,start,end))
                    else:
                        attr[title]=[(value,start,end)]
                else:
                    # for static graphs just assign the value
                    attr[title] = value
        return attr 
Example #26
Source File: gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, stream):
        self.xml = ElementTree(file=stream)
        g=self.xml.find("{%s}graph" % self.NS_GEXF)
        if g is not None:
            return self.make_graph(g)
        # try all the versions
        for version in self.versions:
            self.set_version(version)
            g=self.xml.find("{%s}graph" % self.NS_GEXF)
            if g is not None:
                return self.make_graph(g)
        raise nx.NetworkXError("No <graph> element in GEXF file") 
Example #27
Source File: gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def set_version(self,version):
        d=self.versions.get(version)
        if d is None:
            raise nx.NetworkXError('Unknown GEXF version %s'%version)
        self.NS_GEXF = d['NS_GEXF']
        self.NS_VIZ = d['NS_VIZ']
        self.NS_XSI = d['NS_XSI']
        self.SCHEMALOCATION = d['NS_XSI']
        self.VERSION=d['VERSION']
        self.version=version

#        register_namespace('viz', d['NS_VIZ']) 
Example #28
Source File: test_graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_hyperedge_error(self):
        s="""<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
        http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <key id="d0" for="node" attr.name="color" attr.type="string">
    <default>yellow</default>
  </key>
  <key id="d1" for="edge" attr.name="weight" attr.type="double"/>
  <graph id="G" edgedefault="directed">
    <node id="n0">
      <data key="d0">green</data>
    </node>
    <node id="n1"/>
    <node id="n2">
      <data key="d0">blue</data>
    </node>
    <hyperedge id="e0" source="n0" target="n2">
       <endpoint node="n0"/>
       <endpoint node="n1"/>
       <endpoint node="n2"/>
    </hyperedge>
  </graph>
</graphml>
"""
        fh = io.BytesIO(s.encode('UTF-8'))
        assert_raises(nx.NetworkXError,nx.read_graphml,fh)
        assert_raises(nx.NetworkXError,nx.parse_graphml,s)

    # remove test until we get the "name" issue sorted
    # https://networkx.lanl.gov/trac/ticket/544 
Example #29
Source File: test_graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_key_error(self):
        s="""<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
        http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <key id="d0" for="node" attr.name="color" attr.type="string">
    <default>yellow</default>
  </key>
  <key id="d1" for="edge" attr.name="weight" attr.type="double"/>
  <graph id="G" edgedefault="directed">
    <node id="n0">
      <data key="d0">green</data>
    </node>
    <node id="n1"/>
    <node id="n2">
      <data key="d0">blue</data>
    </node>
    <edge id="e0" source="n0" target="n2">
      <data key="d2">1.0</data>
    </edge>
  </graph>
</graphml>
"""
        fh = io.BytesIO(s.encode('UTF-8'))
        assert_raises(nx.NetworkXError,nx.read_graphml,fh)
        assert_raises(nx.NetworkXError,nx.parse_graphml,s) 
Example #30
Source File: graph_canvas.py    From networkx_viewer with GNU General Public License v3.0 5 votes vote down vote up
def plot_path(self, frm_node, to_node, levels=1, add_to_exsting=False):
        """Plot shortest path between two nodes"""
        try:
            path = nx.shortest_path(self.dataG, frm_node, to_node)
        except nx.NetworkXNoPath as e:
            tkm.showerror("No path", str(e))
            return
        except nx.NetworkXError as e:
            tkm.showerror("Node not in graph", str(e))
            return

        graph = self.dataG.subgraph(self._neighbors(path,levels=levels))

        if add_to_exsting:
            self._plot_additional(graph.nodes())
        else:
            self.clear()
            self._plot_graph(graph)

        # Mark the path
        if levels > 0 or add_to_exsting:
            for u, v in zip(path[:-1], path[1:]):
                u_disp = self._find_disp_node(u)
                v_disp = self._find_disp_node(v)
                for key, value in self.dispG.edge[u_disp][v_disp].items():
                    self.mark_edge(u_disp, v_disp, key)