示例#1
0
文件: graph.py 项目: marcinz/nx3k
 def __init__(self, data=None, **attr):
     # the init could be
     # graph = Graph(g) where g is a Graph
     # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
     # graph = Graph(({},e)) for an edgelist with no specified nodes
     # others with classmethods like
     # Graph.from_adjacency_matrix(m)
     # Graph.from_adjacency_list(l)
     #
     # should abstract the data here
     self._nodedata = {}  # empty node attribute dict
     self._adjacency = {}  # empty adjacency dict
     # the interface is n,e,a,data
     self.n = Nodes(self._nodedata, self._adjacency) # rename to self.nodes
     self.e = Edges(self._nodedata, self._adjacency) # rename to self.edges
     self.a = Adjacency(self._adjacency) # rename to self.adjacency
     self.data = {}   # dictionary for graph attributes
     # load with data
     if hasattr(data,'n') and not hasattr(data,'name'): # it is a new graph
         self.n.update(data.n)
         self.e.update(data.e)
         self.data.update(data.data)
         data = None
     try:
         nodes,edges = data # containers of edges and nodes
         self.n.update(nodes)
         self.e.update(edges)
     except: # old style
         if data is not None:
             convert.to_networkx_graph(data, create_using=self)
     # load __init__ graph attribute keywords
     self.data.update(attr)
示例#2
0
 def setUp(self):
     self.Graph = nxGraph
     # build dict-of-dict-of-dict K3
     ed1, ed2, ed3 = ({}, {}, {})
     self.k3adj = {
         0: {
             1: ed1,
             2: ed2
         },
         1: {
             0: ed1,
             2: ed3
         },
         2: {
             0: ed2,
             1: ed3
         }
     }
     self.k3edges = [(0, 1), (0, 2), (1, 2)]
     self.k3nodes = [0, 1, 2]
     self.K3 = self.Graph()
     self.K3.adj = self.K3._adjacency = self.K3.edge = self.k3adj
     self.K3.node = self.K3._nodedata = {}
     self.K3.node[0] = {}
     self.K3.node[1] = {}
     self.K3.node[2] = {}
     self.K3.n = Nodes(self.K3._nodedata, self.K3._adjacency)
     self.K3.e = Edges(self.K3._nodedata, self.K3._adjacency)
     self.K3.a = Adjacency(self.K3._adjacency)
示例#3
0
    def addEdges(self, v1, v2, weight=None, orientation=None):
        """
            Add a new edges in the Graph

            Required parameters :
            v1 : the first edge
            v2 : the second edge

            Optional parameters :
            weight : if weighted graph, must add a weight (default : None)
            orientation : if oriented graph, must add an orientation (default : None)
        """
        existing_vertices = self.getVertices()
        if v1 in existing_vertices and v2 in existing_vertices:
            if not self.existingEdges(v1, v2):
                if not self.weighted:
                    weight = None
                else:
                    if weight == None:
                        print("Error : Weighted graph, must add a weight.")
                        return -1
                if not self.oriented:
                    orientation = None
                else:
                    if orientation == None:
                        print(
                            "Error : Oriented Graph, must add an orientation.")
                        return -1
                new_edges = Edges(v1, v2, weight, orientation)
                self.edges.append(new_edges)
            else:
                print("Error : [" + v1 + "," + v2 + "]" + " already exists.")
        else:
            print("Error : " + v1 + " or " + v2 + " doesn't exist.")
示例#4
0
文件: graph.py 项目: hagberg/nx3k
 def __init__(self, data=None, **attr):
     # the init could be
     # graph = Graph(g) where g is a Graph
     # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
     # graph = Graph(({},e)) for an edgelist with no specified nodes
     # others with classmethods like
     # Graph.from_adjacency_matrix(m)
     # Graph.from_adjacency_list(l)
     #
     # should abstract the data here
     self._nodedata = {}  # empty node attribute dict
     self._adjacency = {}  # empty adjacency dict
     # the interface is n,e,a,data
     self.n = Nodes(self._nodedata, self._adjacency)  # rename to self.nodes
     self.e = Edges(self._nodedata, self._adjacency)  # rename to self.edges
     self.a = Adjacency(self._adjacency)  # rename to self.adjacency
     self.data = {}  # dictionary for graph attributes
     # load with data
     if hasattr(data, "n") and not hasattr(data, "name"):  # it is a new graph
         self.n.update(data.n)
         self.e.update(data.e)
         self.data.update(data.data)
         data = None
     try:
         nodes, edges = data  # containers of edges and nodes
         self.n.update(nodes)
         self.e.update(edges)
     except:  # old style
         if data is not None:
             convert.to_networkx_graph(data, create_using=self)
     # load __init__ graph attribute keywords
     self.data.update(attr)
示例#5
0
 def __init__(self, graph, subnodes):
     # TODO Can we replace nbunch_iter with set(subnodes) & set(graph)?
     #      We lose the Error messages...
     self._subnodes = set(self._nbunch_iter(graph, subnodes))
     self._nodedata = SubNbrDict(self._subnodes, graph._nodedata)
     self._adjacency = SubAdjacency(self._subnodes, graph._adjacency)
     self.data = graph.data
     self.n = Nodes(self._nodedata, self._adjacency)
     self.e = Edges(self._nodedata, self._adjacency)
     self.a = self._adjacency
示例#6
0
 def do_POST(self):
     if re.search('/edge/status_report/*', self.path) is not None:
         edge_id = self.path.split('/')[-1]
         data = self.rfile.read()
         edge = json.loads(data)
         self.send_response(200)
         self.end_headers()
         edges = Edges.get_instance()
         edges.update_edge(edge_id, edge)
         log.info('edge {} report status {}'.format(edge_id, edge))
     else:
         self.send_response(403)
         self.send_header('Content-Type', 'application/json')
         self.end_headers()
     return
示例#7
0
 def do_GET(self):
     if re.search('/content/*', self.path) is not None:
         content_id = self.path.split('/')[-1]
         self.send_response(200)
         self.send_header('Content-Type', 'application/json')
         self.end_headers()
         edges = Edges.get_instance()
         target = edges.get_edge(content_id)
         json_string = json.dumps(target)
         self.wfile.write(bytes(json_string, 'utf-8'))
         log.info('Access {} in {}'.format(content_id, json_string))
     else:
         self.send_response(403)
         self.send_header('Content-Type', 'application/json')
         self.end_headers()
     return
示例#8
0
 def setUp(self):
     self.v1 = Vertex()
     self.v2 = Vertex()
     self.v3 = Vertex()
     self.v4 = Vertex()
     self.v5 = Vertex()
     self.e1 = Edge(self.v1, self.v2)
     self.e2 = Edge(self.v2, self.v3)
     self.e3 = Edge(self.v3, self.v4)
     self.e4 = Edge(self.v4, self.v5)
     self.e5 = Edge(self.v1, self.v3)
     self.e6 = Edge(self.v1, self.v4)
     self.e7 = Edge(self.v1, self.v5)
     self.edges = Edges({self.e1, self.e2, \
           self.e3, self.e4, self.e5, \
           self.e6, self.e7})
示例#9
0
class Sketch:
    def __init__(self, image):
        self.img = cv.imread(image)

    def sketch(self):
        grey = cv.cvtColor(self.img, cv.COLOR_BGR2GRAY)
        inv = 255 - grey
        blur = cv.GaussianBlur(inv, (13,13), 0)
        return cv.divide(grey, 255-blur, scale=256)

img = Image.open(filename)

sketch = Sketch(filename).sketch()
cv.imwrite("sketch.png", sketch)
bg = Background(img.size, octaves=6).background()
edges = Edges(filename).edges()
#sketchTrans = cv.cvtColor(sketch, cv.COLOR_GRAY2RGBA)

mask = edges[3]
sketch = cv.bitwise_and(sketch, edges, edges)
(thresh, sketch) = cv.threshold(sketch, 240, 255, cv.THRESH_BINARY)
#sketch = cv.multiply(sketch, np.array(bg), scale=(1./128))


h, w = sketch.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
#mask[1:h+1, 1:w+1] = sketch
sketchColor = cv.cvtColor(sketch, cv.COLOR_GRAY2RGBA)
white = np.all(sketchColor == [255,255,255,255], axis=-1)
sketchColor[white, -1] = 0
cv.imwrite("final.png", sketchColor)
示例#10
0
文件: graph.py 项目: marcinz/nx3k
class Graph(object):
    def __init__(self, data=None, **attr):
        # the init could be
        # graph = Graph(g) where g is a Graph
        # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
        # graph = Graph(({},e)) for an edgelist with no specified nodes
        # others with classmethods like
        # Graph.from_adjacency_matrix(m)
        # Graph.from_adjacency_list(l)
        #
        # should abstract the data here
        self._nodedata = {}  # empty node attribute dict
        self._adjacency = {}  # empty adjacency dict
        # the interface is n,e,a,data
        self.n = Nodes(self._nodedata, self._adjacency) # rename to self.nodes
        self.e = Edges(self._nodedata, self._adjacency) # rename to self.edges
        self.a = Adjacency(self._adjacency) # rename to self.adjacency
        self.data = {}   # dictionary for graph attributes
        # load with data
        if hasattr(data,'n') and not hasattr(data,'name'): # it is a new graph
            self.n.update(data.n)
            self.e.update(data.e)
            self.data.update(data.data)
            data = None
        try:
            nodes,edges = data # containers of edges and nodes
            self.n.update(nodes)
            self.e.update(edges)
        except: # old style
            if data is not None:
                convert.to_networkx_graph(data, create_using=self)
        # load __init__ graph attribute keywords
        self.data.update(attr)


    def s(self, nbunch):
        H = Subgraph(self, nbunch)
        return H

    # crazy use of call - get subgraph?
    def __call__(self, nbunch):
        return self.s(nbunch)

    # rewrite these in terms of new interface
    def __iter__(self):
        return iter(self.n)

    def __len__(self):
        return len(self.n)

    def clear(self):
        self.name = ''
        self.n.clear()
        self.e.clear()
        self.data.clear()

    def copy(self, with_data=True):
        if with_data:
            return deepcopy(self)
        G = self.__class__()
        G.n.update(self.n)
        G.e.update(self.e)
        return G

    def is_multigraph(self):
        """Return True if graph is a multigraph, False otherwise."""
        return False

    def is_directed(self):
        """Return True if graph is directed, False otherwise."""
        return False

    def order(self):
        return len(self.n)

    def size(self, weight=None):
        s = sum(d for v, d in self.n.degree(weight=weight))
        # If `weight` is None, the sum of the degrees is guaranteed to be
        # even, so we can perform integer division and hence return an
        # integer. Otherwise, the sum of the weighted degrees is not
        # guaranteed to be an integer, so we perform "real" division.
        return s // 2 if weight is None else s / 2

    @classmethod
    def from_adjacency_matrix(self, matrix):
        import numpy as np
        kind_to_python_type={'f':float,
                             'i':int,
                             'u':int,
                             'b':bool,
                             'c':complex,
                             'S':str,
                             'V':'void'}
        try: # Python 3.x
            blurb = chr(1245) # just to trigger the exception
            kind_to_python_type['U']=str
        except ValueError: # Python 2.6+
            kind_to_python_type['U']=unicode
        n,m=matrix.shape
        if n!=m:
            raise nx.NetworkXError("Adjacency matrix is not square.",
                               "nx,ny=%s"%(matrix.shape,))
        dt=matrix.dtype
        try:
            python_type=kind_to_python_type[dt.kind]
        except:
            raise TypeError("Unknown numpy data type: %s"%dt)

        # Make sure we get even the isolated nodes of the graph.
        nodes = range(n)
        # Get a list of all the entries in the matrix with nonzero entries. These
        # coordinates will become the edges in the graph.
        edges = zip(*(np.asarray(matrix).nonzero()))
        # handle numpy constructed data type
        if python_type is 'void':
        # Sort the fields by their offset, then by dtype, then by name.
            fields = sorted((offset, dtype, name) for name, (dtype, offset) in
                            matrix.dtype.fields.items())
            triples = ((u, v, {name: kind_to_python_type[dtype.kind](val)
                               for (_, dtype, name), val in zip(fields, matrix[u, v])})
                       for u, v in edges)
        else:  # basic data type
            triples = ((u, v, dict(weight=python_type(matrix[u, v])))
                       for u, v in edges)
        graph = self((nodes, triples))
        return graph

    @classmethod
    def from_adjacency_list(self, adjlist):
        nodes = range(len(adjlist))
        edges = [(node,n) for node,nbrlist in enumerate(adjlist) for n in nbrlist]
        return self((nodes,edges))
示例#11
0
from edges import Edges


if __name__ == '__main__':
    rng = 5
    edges = Edges(edges_filename='edges_dump').get_edges()

    print(edges[1])

    for index, edge in edges.items():
        print(index)
        print(edge.speed_indicators)
        break
示例#12
0
文件: graph.py 项目: everaldo/aed_ii
 def create(cls, vertices = Vertices()):
     edges = Edges.create(vertices)
     return Graph(vertices, edges)
示例#13
0
文件: graph.py 项目: everaldo/aed_ii
 def complement(self):
     all_edges = Edges.create(self.vertices)
     return Graph(self.vertices, all_edges - self.edges)
示例#14
0
 def test_size(self):
     """O tamanho de um conjunto de arestas é o número de arestas"""
     self.assertEqual(self.edges.size(), 7)
     e = Edges()
     self.assertEqual(e.size(), 0)
示例#15
0
class TestEdges(unittest.TestCase):


    def setUp(self):
        self.v1 = Vertex()
        self.v2 = Vertex()
        self.v3 = Vertex()
        self.v4 = Vertex()
        self.v5 = Vertex()
        self.e1 = Edge(self.v1, self.v2)
        self.e2 = Edge(self.v2, self.v3)
        self.e3 = Edge(self.v3, self.v4)
        self.e4 = Edge(self.v4, self.v5)
        self.e5 = Edge(self.v1, self.v3)
        self.e6 = Edge(self.v1, self.v4)
        self.e7 = Edge(self.v1, self.v5)
        self.edges = Edges({self.e1, self.e2, \
              self.e3, self.e4, self.e5, \
              self.e6, self.e7})


    def test_size(self):
        """O tamanho de um conjunto de arestas é o número de arestas"""
        self.assertEqual(self.edges.size(), 7)
        e = Edges()
        self.assertEqual(e.size(), 0)
 
    def test_valid_vertice(self):
        """Um vértice é válido se pertence à alguma aresta de E"""
        v = Vertex('v')
        self.assertTrue(self.edges.valid_vertice(self.v1))
        self.assertFalse(self.edges.valid_vertice(v))

    def test_eq(self):
        """Dois conjuntos de arestas são iguais, não importa a ordem"""
        es2 = Edges({self.e7, \
              self.e6, self.e5, self.e4, \
              self.e3, self.e2, self.e1})
        self.assertTrue(self.edges == es2)

    def test_eq_false(self):
        """Dois conjuntos de arestas não são iguais, se não possuem mesmos componentes"""
        es2 = Edges({self.e7, \
              self.e6, self.e5, self.e4, \
              self.e3, self.e2, self.e1, Edge(Vertex(), Vertex())})
        self.assertFalse(self.edges == es2)

    def test_contains(self):
        """É possível utilizar o operador in e not in para verificar pertencimento"""
        self.assertTrue(self.e1 in self.edges)
        self.assertTrue(self.e2 in self.edges)
        self.assertTrue(Edge(Vertex(), Vertex()) not in self.edges)
    
    def test_subset(self):
        """É possível utilizar o operador <= para verificar se é subconjunto"""
        es1 = Edges({self.e1})
        es2 = Edges({self.e2})
        es3 = Edges({self.e1, self.e2, Vertex()})
        eigual = Edges({self.e7, \
              self.e6, self.e5, self.e4, \
              self.e3, self.e2, self.e1})

        self.assertTrue(es1 <= self.edges)
        self.assertTrue(es2 <= self.edges)
        self.assertTrue(eigual <= self.edges)
        self.assertFalse(es3 <= self.edges)
 

    def test_iterator(self):
        """É possível iterar sobre o conjunto de arestas"""
        i = 0
        es = set()
        for e in self.edges:
            es.add(e)
        self.assertEqual(Edges(es), self.edges)

    def test_isdisjoint(self):
        """Dois conjuntos distintos de arestas são disjuntos"""
        self.assertTrue(self.edges.isdisjoint(Edges({Edge(Vertex(), Vertex())})))
示例#16
0
文件: graph.py 项目: hagberg/nx3k
class Graph(object):
    def __init__(self, data=None, **attr):
        # the init could be
        # graph = Graph(g) where g is a Graph
        # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
        # graph = Graph(({},e)) for an edgelist with no specified nodes
        # others with classmethods like
        # Graph.from_adjacency_matrix(m)
        # Graph.from_adjacency_list(l)
        #
        # should abstract the data here
        self._nodedata = {}  # empty node attribute dict
        self._adjacency = {}  # empty adjacency dict
        # the interface is n,e,a,data
        self.n = Nodes(self._nodedata, self._adjacency)  # rename to self.nodes
        self.e = Edges(self._nodedata, self._adjacency)  # rename to self.edges
        self.a = Adjacency(self._adjacency)  # rename to self.adjacency
        self.data = {}  # dictionary for graph attributes
        # load with data
        if hasattr(data, "n") and not hasattr(data, "name"):  # it is a new graph
            self.n.update(data.n)
            self.e.update(data.e)
            self.data.update(data.data)
            data = None
        try:
            nodes, edges = data  # containers of edges and nodes
            self.n.update(nodes)
            self.e.update(edges)
        except:  # old style
            if data is not None:
                convert.to_networkx_graph(data, create_using=self)
        # load __init__ graph attribute keywords
        self.data.update(attr)

    def s(self, nbunch):
        H = Subgraph(self, nbunch)
        return H

    # crazy use of call - get subgraph?
    def __call__(self, nbunch):
        return self.s(nbunch)

    # rewrite these in terms of new interface
    def __iter__(self):
        return iter(self.n)

    def __len__(self):
        return len(self.n)

    def clear(self):
        self.name = ""
        self.n.clear()
        self.e.clear()
        self.data.clear()

    def copy(self, with_data=True):
        if with_data:
            return deepcopy(self)
        G = self.__class__()
        G.n.update(self.n)
        G.e.update(self.e)
        return G

    def is_multigraph(self):
        """Return True if graph is a multigraph, False otherwise."""
        return False

    def is_directed(self):
        """Return True if graph is directed, False otherwise."""
        return False

    def order(self):
        return len(self.n)

    def size(self, weight=None):
        s = sum(d for v, d in self.n.degree(weight=weight))
        # If `weight` is None, the sum of the degrees is guaranteed to be
        # even, so we can perform integer division and hence return an
        # integer. Otherwise, the sum of the weighted degrees is not
        # guaranteed to be an integer, so we perform "real" division.
        return s // 2 if weight is None else s / 2

    @classmethod
    def from_adjacency_matrix(self, matrix):
        import numpy as np

        kind_to_python_type = {"f": float, "i": int, "u": int, "b": bool, "c": complex, "S": str, "V": "void"}
        try:  # Python 3.x
            blurb = chr(1245)  # just to trigger the exception
            kind_to_python_type["U"] = str
        except ValueError:  # Python 2.6+
            kind_to_python_type["U"] = unicode
        n, m = matrix.shape
        if n != m:
            raise nx.NetworkXError("Adjacency matrix is not square.", "nx,ny=%s" % (matrix.shape,))
        dt = matrix.dtype
        try:
            python_type = kind_to_python_type[dt.kind]
        except:
            raise TypeError("Unknown numpy data type: %s" % dt)

        # Make sure we get even the isolated nodes of the graph.
        nodes = range(n)
        # Get a list of all the entries in the matrix with nonzero entries. These
        # coordinates will become the edges in the graph.
        edges = zip(*(np.asarray(matrix).nonzero()))
        # handle numpy constructed data type
        if python_type is "void":
            # Sort the fields by their offset, then by dtype, then by name.
            fields = sorted((offset, dtype, name) for name, (dtype, offset) in matrix.dtype.fields.items())
            triples = (
                (
                    u,
                    v,
                    {name: kind_to_python_type[dtype.kind](val) for (_, dtype, name), val in zip(fields, matrix[u, v])},
                )
                for u, v in edges
            )
        else:  # basic data type
            triples = ((u, v, dict(weight=python_type(matrix[u, v]))) for u, v in edges)
        graph = self((nodes, triples))
        return graph

    @classmethod
    def from_adjacency_list(self, adjlist):
        nodes = range(len(adjlist))
        edges = [(node, n) for node, nbrlist in enumerate(adjlist) for n in nbrlist]
        return self((nodes, edges))