Esempio n. 1
0
    def __init__(self, query=None, router=None):
        self._events = {}
        self._results = {}
        self._query = query
        if not query:
            self._shadow = True
            manager = Manager()
            self._edge = Edge(core=manager.core)
            self._vrtx = Vrtx(core=manager.core)
            self._attr = Attr(core=manager.core)
            self._data = Data(self._vrtx, self._edge, self._attr, core=manager.core)

            from lib.link import Uplink
            self._link = Uplink(manager)
        else:
            manager = None
            self._shadow = False
            self._edge = Edge(router=router)
            self._vrtx = Vrtx(router=router)
            self._attr = Attr(router=router, rdonly=False)
            self._data = Data(self._vrtx, self._edge, self._attr, router=router, rdonly=False)

            from lib.link import Downlink
            link = Downlink(query)
            self._query.link = link
            self._link = link

        self._manager = manager
        self._lock = NamedLock()
        if manager:
            manager.start()
Esempio n. 2
0
    def _proc_edge_stmt(self, toks):
        """ Returns a tuple of the form (ADD_EDGE, src, dest, options).
        """
        opts = toks[3]
        dummy_edge = Edge("dummy1", "dummy2")
        # Coerce attribute types.
        for key, value in opts.iteritems():
            trait = dummy_edge.trait(key)
            if trait is not None:
                # FIXME: Implement Graphviz spline types.
                if trait.is_trait_type( List ):
                    p = [] # List of float doublets.
                    for t in value.split( " " ):
                        l = t.split( "," )
                        if len(l) == 3: # pos="e,39,61 39,97 39,89 39,80 39,71"
                            l.pop(0)
                        f = [ float(a) for a in l ]
                        p.append( tuple(f) )
                    opts[key] = p

                elif trait.is_trait_type( Float ):
                    opts[key] = float( value )

                elif trait.is_trait_type( Tuple ):
                    opts[key] = tuple( [float(c) for c in value.split(",")] )

        return super(GodotDataParser, self)._proc_edge_stmt(toks)
Esempio n. 3
0
 def setUp(self):
     self.v1 = Vertex(1)
     self.v2 = Vertex(2)
     self.x = Vertex('x')
     self.another_x = Vertex('x')
     self.e12 = Edge(self.v1, self.v2)
     self.e21 = Edge(self.v2, self.v1)
Esempio n. 4
0
    def _get_link_details(entity, link_name):
        """"Lookup the (edge_class, left_edge_id, right_edge_id, node_class)
        for the given entity and link_name.

        param entity: The current entity Node subclass
        :param str link_name: The association proxy name

        edge_class: The Edge subclass the association is proxied through
        left_edge_id: The edge.{src,dst}_id
        right_edge_id: The edge.{dst,src}_id (opposit of left_edge_id)
        node_class: The target node the association_proxy points to

        """

        # Look for the link_name in OUTBOUND edges from the current
        # entity
        for edge in Edge._get_edges_with_src(entity.__name__):
            if edge.__src_dst_assoc__ == link_name:
                return (edge, edge.src_id, edge.dst_id,
                        Node.get_subclass_named(edge.__dst_class__))

        # Look for the link_name in INBOUND edges from the current
        # entity
        for edge in Edge._get_edges_with_dst(entity.__name__):
            if edge.__dst_src_assoc__ == link_name:
                return (edge, edge.dst_id, edge.src_id,
                        Node.get_subclass_named(edge.__src_class__))

        raise AttributeError(
            "type object '{}' has no attribute '{}'"
            .format(entity.__name__, link_name))
Esempio n. 5
0
    def __addNode(self, current_time, nodeStatData):
        # adding nodes
        key = nodeStatData[0] #(file_path, ligne_number, method_name)
        value = nodeStatData[1] #(count, countWithRecursive, exclusiveTime, cummulatedTime, callersData)
        node = self.__searchNode(key)
        count_data = StampedData(value[0], value[1], value[2], value[3])
        if node is None:
            node = Node(key[0], key[1], key[2], self.__program_folder, self.__program_path)
            self.__nodes.append(node)
        node.setStats(current_time, count_data)

        # adding edges
        callersData = value[4]
        for c in callersData.items():
            caller = c[0] # same structure as key: (file_path, ligne_number, method_name)
            callerStats = c[1] # same structure as value (without callersData): (count, countWithRecursive, exclusiveTime, cummulatedTime)
            count_data = StampedData(callerStats[0], callerStats[1], callerStats[2], callerStats[3])

            callerNode = self.__searchNode(caller)   
            if callerNode is None:
                callerNode = Node(caller[0], caller[1], caller[2], self.__program_folder, self.__program_path)
                self.__nodes.append(callerNode)

            edge = self.__searchEdge(callerNode.getId(), node.getId())
            if edge is None:
                edge = Edge(callerNode.getId(), node.getId())
                self.__edges.append(edge)
            edge.setStats(current_time, count_data)
Esempio n. 6
0
class TestEdge(unittest.TestCase):


    def setUp(self):
        self.v1 = Vertex(1)
        self.v2 = Vertex(2)
        self.x = Vertex('x')
        self.another_x = Vertex('x')
        self.e12 = Edge(self.v1, self.v2)
        self.e21 = Edge(self.v2, self.v1)


    def test_a_edge_cant_have_autoloop(self):
        """Uma aresta não possui autoloop"""
        with self.assertRaises(Exception):
            Edge(self.x, self.another_x)

    def test_two_edges_are_equal_independent_of_vertices_order(self):
        """Duas arestas são iguais, independentemente da ordem dos vértice"""
        self.assertEqual(self.e12, self.e21)


    def test_incide(self):
        """Um Vértice incide numa aresta, se ele é um de seus componentes"""
        self.assertTrue(self.e12.incide(self.v1))
        self.assertTrue(self.e21.incide(self.v1))
        self.assertTrue(self.e12.incide(self.v2))
        self.assertTrue(self.e21.incide(self.v2))
        self.assertFalse(self.e12.incide(self.x))
        self.assertFalse(self.e21.incide(self.x))
        self.assertTrue(self.x not in self.e21)
        self.assertTrue(self.v1 in self.e12)
        self.assertTrue(self.v1 in self.e21)
        self.assertTrue(self.v2 in self.e12)
        self.assertTrue(self.v2 in self.e12)

    def test_adjacent(self):
        """Os vértices que são pontas das arestas são adjacentes"""
        self.assertTrue(self.e12.adjacent(self.v1), self.v2)
        self.assertTrue(self.e12.adjacent(self.v2), self.v1)
        self.assertTrue(self.e21.adjacent(self.v1), self.v2)
        self.assertTrue(self.e21.adjacent(self.v2), self.v1)

    def test_adjacent_error(self):
        """Se um vértice não pertence à aresta, adjacent retorna um erro"""
        with self.assertRaises(Exception):
            self.e12.adjacent(self.x)

    def test_edge_iteration(self):
        """É possível iterar sobre os vértices de uma aresta"""
        i = 0
        for u in self.e12:
            if i == 0:
               self.assertTrue(u == self.v1)
            if i == 1:
               self.assertTrue(u == self.v2)
            i = i + 1
Esempio n. 7
0
def delete_all_edges(options):
    """ Function to delete all edges on given VSM

    @param options cli options to this script
    @return None
    """
    edge  = Edge(vsm_obj)
    edges = (edge.query())
    edge_id = None
    for item in edges.edgePage.list_schema:
       edge.id = item.objectId
       edge.delete()
 def edge(self, value): # intermediates=set()
   if value not in self.edges:
     edge = Edge(value, self)
     self.edges[value] = edge
     for condition in value.conditions:
       self.connector(condition).connect(edge)
     if CONNECT_EFFECTS and hasattr(value, 'effects'):
       for variable, effect in value.effects.iteritems():
         if isinstance(effect, ValueEffect):
           print effect
           edge.connect(self.vertex(Substate({variable: effect(None)})))
   return self.edges[value]
Esempio n. 9
0
 def testEdgeNormal(self):
     a = Node((0,0),(0,0))
     b = Node((1,0),(0,0))
     c = Node((0,1),(0,0))
     t = Triangle(a, b, c)
     xaxisedge = t.edges[0]
     reversedxaxisedge = Edge(xaxisedge.nodes[1], xaxisedge.nodes[0])
     diagonaledge = t.edges[1]
     yaxisedge = t.edges[2]
     self.assertTrue((xaxisedge.getNormal(t) == (0, -1)).all())
     self.assertTrue((reversedxaxisedge.getNormal(t) == (0, -1)).all())
     self.assertTrue((yaxisedge.getNormal(t) == (-1, 0)).all())
     self.assertTrue((diagonaledge.getNormal(t) == (1/sqrt(2), 1/sqrt(2))).all())
Esempio n. 10
0
 def test_creat_edge(self):
     # create a box
     b = get_test_box_shape()
     # take the first edge
     t = Topo(b)
     edge_0 = t.edges().next()  # it's a TopoDS_Edge
     assert not edge_0.IsNull()
     # then create an edge
     my_edge = Edge(edge_0)
     assert not my_edge.IsNull()
     assert my_edge.tolerance == 1e-06
     assert my_edge.type == 'line'
     assert my_edge.length() == 30.
Esempio n. 11
0
class PreStopAcc(Rule):
    """classify the trip as high based on the minimum of pre_stop_acc, which is the maximum of deceleration"""

    def __init__(self):
        self.name = "PreStopAcc"
        self.high_edge = Edge(self.name, "high")

    def classify(self, vertex):
        min_pre_stop_acc = vertex.stop_points[2]
        if min_pre_stop_acc < -3.0:
            self.high_edge.add_vertex(vertex)
            return self.high_edge.id

    def edges(self):
        return [self.high_edge]
Esempio n. 12
0
class PostStopAcc(Rule):
    """classify the trip as high based on maximum of post_stop_acc"""

    def __init__(self):
        self.name = "PostStopAcc"
        self.high_edge = Edge(self.name, "high")

    def classify(self, vertex):
        max_post_stop_acc = vertex.stop_points[5]
        if max_post_stop_acc > 2.0:
            self.high_edge.add_vertex(vertex)
            return self.high_edge.id

    def edges(self):
        return [self.high_edge]
Esempio n. 13
0
def delete_network(options, vsm_obj):
    """ function to delete network

    @param options cli options to this script
    @param vsm_obj reference to vsm client object
    @return True/False True - success False - error
    """
    print("Disconnecting edge interface attached to this network")
    edge_id = get_edge(vsm_obj)
    edge = Edge(vsm_obj, '4.0')
    edge.id = edge_id
    vnics = Vnics(edge)
    vnics_schema = vnics.query()
    network = get_network_id(options, get_network_name_on_vc(options))
    for vnic in vnics_schema.vnics:
       if network and vnic.portgroupId == network:
          print("Found a matching vnic %s %s" % (options.name, vnic.index))
          vnic.isConnected = "False"
          vnic.portgroupId = None
          vnic.name = "vnic%s" % vnic.index
          vnics_schema = VnicsSchema()
          vnics_schema.vnics = [vnic]
          result = vnics.create(vnics_schema)
          if (result[0].response.status != 204):
             print "update vnic error: %s %s" \
                % (result[0].response.status, result[0].response.reason)
             return False
          else:
             break
    else:
        print ("No matching vnic found")

    vdn_scope = get_transport_zone(options)
    virtual_wire = VirtualWire(vdn_scope)
    vwire = virtual_wire.read_by_name(get_network_name(options))
    name = get_network_name(options)
    if vwire != "FAILURE":
       print("Found a matching network %s" % (options.name))
       virtual_wire.id = vwire.objectId
       result = virtual_wire.delete()
       if (result.response.status != 200):
          print ("Delete vwire error: %s" % result.response.reason)
          return False
    else:
        print ("No matching network found")
    print("Network %s deleted" % (options.name))

    return True
Esempio n. 14
0
 def __declare_last__(cls):
     src_ids, dst_ids = [], []
     for scls in Edge.get_subclasses():
         name = scls.__name__
         name_in = '_{}_in'.format(name)
         name_out = '_{}_out'.format(name)
         src_assoc = getattr(scls, SRC_DST_ASSOC)
         dst_assoc = getattr(scls, DST_SRC_ASSOC)
         if scls.__dst_class__ == cls.__name__:
             if not hasattr(cls, name_in):
                 edge_in = relationship(
                     name,
                     foreign_keys=[scls.dst_id],
                     backref='dst',
                     cascade='all, delete, delete-orphan',
                 )
                 setattr(cls, name_in, edge_in)
                 cls._edges_in.append(name_in)
                 dst_ids.append(scls.dst_id)
             cls._set_association_proxy(scls, dst_assoc, name_in, 'src')
         if scls.__src_class__ == cls.__name__:
             if not hasattr(cls, name_out):
                 edge_out = relationship(
                     name,
                     foreign_keys=[scls.src_id],
                     backref='src',
                     cascade='all, delete, delete-orphan',
                 )
                 setattr(cls, name_out, edge_out)
                 cls._edges_out.append(name_out)
                 src_ids.append(scls.src_id)
             cls._set_association_proxy(scls, src_assoc, name_out, 'dst')
Esempio n. 15
0
    def addEdge(self, beginPoint, endPoint, beginSide, endSide, edgeSelfLoops, src, dst, tokenValues, pRates, cRates, color):
        newEdge = Edge(beginPoint, endPoint, beginSide, endSide, edgeSelfLoops, pRates, cRates, color)

        #Place edges always behind nodes
        newEdge.setZValue(1)

        #Give edge a cluster of tokens
        tokenCluster = TokenCluster(self, self.scene, self.view, newEdge, src, dst, tokenValues)
        self.scene.addItem(tokenCluster)
        self.clusterList.append(tokenCluster)
        
        #Add edge to the scene and list
        self.scene.addItem(newEdge)
        self.edgeList.append(newEdge)

        return newEdge
Esempio n. 16
0
    def next(self):
        if self.index == self.number_of_vertices:
            raise StopIteration

        vert = self.vertsA[self.index]
        closest = self.closest_point(vert)
        edges_a = self.tp_A.edges_from_vertex(vert)
        edges_b = self.tp_B.edges_from_vertex(closest)
        a1, a2 = Edge(edges_a.next()), Edge(edges_a.next())
        b1, b2 = Edge(edges_b.next()), Edge(edges_b.next())
        mpA = a1.mid_point()
        self.index += 1

        if mpA.Distance(b1.mid_point()) < mpA.Distance(b2.mid_point()):
            return iter([a1, a2]), iter([b1, b2])
        else:
            return iter([a1, a2]), iter([b2, b1])
Esempio n. 17
0
def get_edge(vsm_obj):
    """ function to get edge id for the current user

    @param vsm_obj reference to vsm client object
    @return edge_id edge id from vsm
    """
    edge  = Edge(vsm_obj, '4.0')
    edges = (edge.query())
    edge_id = None
    for item in edges.edgePage.list_schema:
       user = pwd.getpwuid(os.getuid())[0]
       if item.name and re.search(user, item.name):
          print "Got Edge VM %s for user %s" % (item.name, user)
          edge_id = item.objectId
          break

    return edge_id
Esempio n. 18
0
    def insertParabola(self, p):
        if not p:
            raise Exception("p is None")
            exit(-1)
        if not self.root:
            self.root = parabola.Parabola(p.copy())
            self.fp = p.copy()
            return
        if self.root.isLeaf and self.root.site.y - p.y < 0.01:
            self.root.isLeaf = False
            self.root.setLeft(parabola.Parabola(self.fp.copy()))
            self.root.setRight(parabola.Parabola(p.copy()))
            s = Point((p.x + self.fp.x) / 2.0, self.height)
            if p.x > self.fp.x:
                self.root.edge = Edge(s, self.fp.copy(), p.copy())
            else:
                self.root.edge = Edge(s, p, self.fp.copy())
            return
        par = self.getParabolaByX(p.x)
        if par.event:
            self.queue.remove(par.event)
            par.event = None
        start = Point(p.x, self.getY(par.site, p.x))

        e1 = Edge(start, par.site, p)
        er = Edge(start, p, par.site)

        e1.neighbor = er
        self.edges.append(e1)

        par.edge  = er
        par.isLeaf = False

        p0 = parabola.Parabola(par.site.copy())
        p1 = parabola.Parabola(p.copy())
        p2 = parabola.Parabola(par.site.copy())

        par.setRight(p2)
        par.setLeft(parabola.Parabola(None))
        par.left.edge = e1

        par.left.setLeft(p0)
        par.left.setRight(p1)
        print "checking circles"
        self.checkCircle(p0)
        self.checkCircle(p2)
Esempio n. 19
0
class MedianSpeedyTurning(Rule):
    """
        classify the trip as high speedy turning based on median
        output: high
    """

    def __init__(self):
        self.name = "MedianSpeedyTurning"
        self.high_edge = Edge(self.name, "high")

    def classify(self, vertex):
        median_speedy_angle = vertex.turning[16]
        if median_speedy_angle > 1.0:
            self.high_edge.add_vertex(vertex)
            return self.high_edge.id

    def edges(self):
        return [self.high_edge]
Esempio n. 20
0
 def swap_edge_node(self, edge, node_from, node_to):
     """
     Swap a node
     :param edge:
     :param node_from:
     :param node_to:
     :return:
     """
     assert hasattr(edge, 'path')
     assert edge in edge.path.edges
     path = edge.path
     if edge.source == node_from:
         new_edge = Edge(source=node_to, target=edge.target)
     else:
         new_edge = Edge(source=edge.source, target=node_to)
     new_edge.path = path
     idx = path.edges.index(edge)
     path.remove_edge(edge)
     path.edges.insert(idx, new_edge)
Esempio n. 21
0
    def swap_edge(self, edge, nodes_from, nodes_to):
        """

        :param nodes_from:
        :param nodes_to:
        :return:
        """
        assert len(nodes_from) == 2
        assert len(nodes_to) == 2
        assert edge in edge.path.edges
        assert len(edge.path.edges) == 1
        if edge.source == nodes_from[0]:
            new_edge = Edge(source=nodes_to[0], target=nodes_to[1])
        else:
            new_edge = Edge(source=nodes_to[1], target=nodes_to[0])
        path = edge.path
        new_edge.path = path
        path.remove_edge(edge)
        path.edges.append(new_edge)
Esempio n. 22
0
    def remove_node(self, node):
        """
        This method removes a node from a path. This method should be called from GeometricGraph's method only.

        :param node:
        :return:
        """
        assert len(self.edges) > 1

        nodes = self.get_nodes()
        if node == nodes[0]:
            self.remove_edge(self.edges[0])
        elif node == nodes[-1]:
            self.remove_edge(self.edges[-1])
        else:
            idx = nodes.index(node)
            new_edge = Edge(nodes[idx - 1], nodes[idx + 1])
            new_edge.path = self
            new_edges = self.edges[:idx - 1] + [new_edge] + self.edges[idx + 1:]
            self.remove_edge(self.edges[idx])
            self.edges = new_edges
Esempio n. 23
0
def create_dhcp_pool(options, vsm_obj, range, default_gateway):
    """ function to create dhcp ip pool

    @param options cli options to this script
    @param vsm_obj reference to vsm client object
    @param range dhcp ip range
    @param default_gateway default gateway
    @return True/False True - success False - error
    """
    edge = Edge(vsm_obj, '4.0')
    edge_id = get_edge(vsm_obj)
    edge.id = edge_id

    dhcp_py_dict = {
        'enabled': True,
        'logging': {'loglevel': 'info', 'enable': False},
        'ippools': [
                   {
                       'autoconfiguredns': True,
                       'defaultGateway': default_gateway,
                       'iprange': range,
                   }
        ],
    }
    dhcp_client = DHCP(edge)
    print("Creating dhcp ippool with range %s" % range)
    dhcp_schema_object = dhcp_client.get_schema_object(dhcp_py_dict)
    existing_dhcp_schema = dhcp_client.read()
    if existing_dhcp_schema and existing_dhcp_schema.ipPools:
       print "append dhcp ippool to existing list"
       dhcp_schema_object.ipPools = existing_dhcp_schema.ipPools + \
          dhcp_schema_object.ipPools
    result = dhcp_client.create(dhcp_schema_object)

    if (result[0].response.status != 204):
       r_vars = vars(result[0])
       print("Create IP Pool error: %s" % result[0].response.reason)
       print ', '.join("%s: %s" % item for item in r_vars.items())
       return False
    return True
Esempio n. 24
0
def add_edge_interface(options, edge_id):
    """ function to add an interface on edge

    @param options cli options to this script
    @param edge_id edge id on vsm
    @return True/False True - success False - error
    """
    vsm_obj = get_vsm_object(options)
    edge = Edge(vsm_obj, '4.0')
    edge.id = edge_id
    vnics = Vnics(edge)
    vnics_schema = vnics.query()
    active = []*10
    index = 0
    active_nics = 0
    for vnic in vnics_schema.vnics:
       if vnic.isConnected == "true":
          active.append(True)
          active_nics =+ 1
       else:
          active.append(False)
    if active_nics < 10:
       free_index = next((i for i, x in enumerate(active) if not x), None)
       vnic_schema =  VnicSchema()
       vnics_schema =  VnicsSchema()
       vnic_schema = get_vnic(options, free_index)
       vnics_schema.vnics = [vnic_schema]
       print("Creating vnic on edge %s" % edge_id)
       result = vnics.create(vnics_schema)
       if (result[0].response.status != 204):
          r_vars = vars(result[0])
          print("Create vnic error: %s" % result[0].response.reason)
          print ', '.join("%s: %s" % item for item in r_vars.items())
          return False
       range = get_dhcp_range(options, free_index)
       default_gateway = get_primary_ip(options, free_index)
       return create_dhcp_pool(options, vsm_obj, range, default_gateway)
    return True
Esempio n. 25
0
class MedianSpeed(Rule):
    """
        classify the trip as high / low median speed
        output : high , low
    """

    def __init__(self):
        self.name = "MedianSpeed"
        self.high_edge = Edge(self.name, "high")
        self.low_edge = Edge(self.name, "low")

    def classify(self, vertex):
        median_speed = vertex.speed[5]
        # high median speed
        if median_speed > 25.0:
            self.high_edge.add_vertex(vertex)
            return self.high_edge.id
        if median_speed < 8:
            self.low_edge.add_vertex(vertex)
            return self.low_edge.id

    def edges(self):
        return [self.high_edge, self.low_edge]
Esempio n. 26
0
def add_edge(options):
    """ function to add on edge

    @param options cli options to this script
    @return True/False True - success False - error
    """
    vsm_obj = get_vsm_object(options, '4.0')
    edge = Edge(vsm_obj, '4.0')
    edge_schema = EdgeSchema(None)
    edge_schema.datacenterMoid = get_datacenter_id(options)
    edge_schema.appliances.applianceSize = 'compact'

    appliance_schema = ApplianceSchema()
    appliance_schema.datastoreId = get_datastore_id(options)
    appliance_schema.resourcePoolId = get_cluster_id(options)

    # XXX(hchilkot):
    # set default firewall rule to accept for edge,
    # this is required to pass any traffic across networks.
    result, features_schema = set_edge_features_schema(default_firewall_rule = FW_DEFAULT_RULE_ACCEPT)
    if not result:
       print("Result : %r. Received: %r for features schema. \
              Failed to set edge features." % (result, features_schema))
       return False
    edge_schema.features = features_schema

    edge_schema.appliances.appliance = [appliance_schema]
    edge_schema.vnics = [get_vnic(options, 0)]
    edge_schema.name = get_edge_name(options)
    print ("Creating edge %s" % edge_schema.name)
    result = edge.create(edge_schema)
    if (result[0].response.status != 201):
       r_vars = vars(result[0])
       print("Create edge error: %s" % result[0].response.reason)
       print ', '.join("%s: %s" % item for item in r_vars.items())
       return False
    return True
Esempio n. 27
0
 def swap_path_node(self, path, swap_from, swap_to):
     """
     Swap the source node in the path to target
     :param path:
     :param source:
     :param target:
     :return:
     """
     nodes = path.get_nodes()
     assert swap_from in nodes
     idx = nodes.index(swap_from)
     if idx == 0:
         # Remove the first edge and swap with a new one
         old_edge = path.edges[0]
         if old_edge.source == swap_from:
             new_edge = Edge(source=swap_to, target=old_edge.target)
         else:
             new_edge = Edge(source=old_edge.source, target=swap_to)
         new_edge.path = path
         path.remove_edge(old_edge)
         path.edges.insert(0, new_edge)
     elif idx == len(nodes) - 1:
         # Remove the last edge and swap with a new one
         old_edge = path.edges[-1]
         if old_edge.source == swap_from:
             new_edge = Edge(source=swap_to, target=old_edge.target)
         else:
             new_edge = Edge(source=old_edge.source, target=swap_to)
         new_edge.path = path
         path.remove_edge(old_edge)
         path.edges.append(new_edge)
     else:
         old_edge_1 = path.edges[idx - 1]
         old_edge_2 = path.edges[idx]
         for e_idx, old_edge in [(idx - 1, old_edge_1), (idx, old_edge_2)]:
             if old_edge.source == swap_from:
                 new_edge = Edge(source=swap_to, target=old_edge.target)
             else:
                 new_edge = Edge(source=old_edge.source, target=swap_to)
             new_edge.path = path
             path.remove_edge(old_edge)
             path.edges.insert(e_idx, new_edge)
Esempio n. 28
0
class TripLengthRule(Rule):
    """
        classify the trip as long / short based on time and distance
        output: long, short
    """

    def __init__(self):
        self.name = "TripLengthRule"
        self.long_edge = Edge(self.name, "long")
        self.short_edge = Edge(self.name, "short")

    def classify(self, vertex):
        time, distance = vertex.route[0], vertex.route[1]
        # long trip
        if distance > 1000 and time > 600:
            self.long_edge.add_vertex(vertex)
            return self.long_edge.id

        if distance <= 100:
            self.short_edge.add_vertex(vertex)
            return self.short_edge.id

    def edges(self):
        return [self.long_edge, self.short_edge]
Esempio n. 29
0
class TestEdge(unittest.TestCase):

    def setUp(self):
        self.edge = Edge(1, 2)
        self.edge2 = Edge(2, 1)

    def test_str(self):
        edge_str = self.edge.__str__()
        self.assertEqual("(1, 2)", edge_str)

        edge_str_2 = self.edge2.__str__()
        self.assertEqual("(2, 1)", edge_str_2)

    def test_eq_ne(self):
        self.assertTrue(self.edge == self.edge2)
        self.assertFalse(self.edge != self.edge2)

        edge3 = Edge(1, 2)
        self.assertTrue(self.edge == edge3)
        self.assertFalse(self.edge != edge3)

        edge4 = Edge(1, 3)
        self.assertFalse(edge3 == edge4)
        self.assertTrue(edge3 != edge4)
Esempio n. 30
0
    def merge_edges(self, edge1, edge2):
        """
        Merge two edges in this path
        :param edge1:
        :param edge2:
        :return:
        """
        assert len(self.edges) > 1
        assert edge1 in self.edges
        assert edge2 in self.edges
        assert len({edge1.source, edge1.target} & {edge2.source, edge2.target}) == 1

        shared_node = list({edge1.source, edge1.target} & {edge2.source, edge2.target})[0]
        if edge1.source == shared_node:
            node1 = edge1.target
        else:
            node1 = edge1.source
        if edge2.source == shared_node:
            node2 = edge2.target
        else:
            node2 = edge2.source
        new_edge = Edge(node1, node2)
        new_edge.path = self
        self.edges.insert(self.edges.index(edge1), new_edge)

        # Clean up
        edge1.source.remove_edge(edge1)
        edge1.target.remove_edge(edge1)
        edge2.source.remove_edge(edge2)
        edge2.target.remove_edge(edge2)
        edge1.path = None
        edge2.path = None

        self.edges.remove(edge1)
        self.edges.remove(edge2)
        return new_edge
Esempio n. 31
0
    def initial_triangulation(self):
        n1 = Edge()
        n2 = Edge()
        n3 = Edge()
        n4 = Edge()
        p1 = Edge()
        p2 = Edge()
        p3 = Edge()
        p4 = Edge()
        c1 = Edge()
        c2 = Edge()

        self.edges = [n1, n2, n3, n4, p1, p2, p3, p4, c1, c2]

        topleft = Vertex(Vector(-0.1, 1.1, 0), p2)
        topright = Vertex(Vector(1.1, 1.1, 0), p1)
        bottomleft = Vertex(Vector(-0.1, -0.1, 0), p3)
        bottomright = Vertex(Vector(1.1, -0.1, 0), p4)
        self.vertices = [topleft, topright, bottomleft, bottomright]
        self.initial_vertices = [topleft, topright, bottomleft, bottomright]

        a = Face(p1)
        b = Face(p2)
        self.faces = [a, b]

        n1.setAttributes(topleft, p1, None, n4, n2)
        n2.setAttributes(bottomleft, p2, None, n1, n3)
        n3.setAttributes(bottomright, p3, None, n2, n4)
        n4.setAttributes(topright, p4, None, n3, n1)

        p1.setAttributes(topright, n1, a, c1, p4)
        p2.setAttributes(topleft, n2, b, p3, c2)
        p3.setAttributes(bottomleft, n3, b, c2, p2)
        p4.setAttributes(bottomright, n4, a, p1, c1)

        c1.setAttributes(topleft, c2, a, p4, p1)
        c2.setAttributes(bottomright, c1, b, p2, p3)

        self.updated = True
Esempio n. 32
0
 def setUp(self):
     self.edge = Edge(i='A', f='B', d=1)
Esempio n. 33
0
    n, m = [int(i) for i in map_file.readline().split()]

    # Reading vertices
    for i in range(n):
        identity, y, x = (float(i) for i in map_file.readline().split())
        identity = int(identity)
        vertex = Vertex(identity, y, x)
        graph.append(vertex)
        graph_dict[identity] = vertex

    # Reading edges
    for i in range(m):
        id1, id2 = (int(i) for i in map_file.readline().split())
        graph_dict[id1].adjacent_vertices.append(id2)
        graph_dict[id2].adjacent_vertices.append(id1)
        edge = Edge(graph_dict[id1], graph_dict[id2])
        roads[id1, id2] = edge
        roads[id2, id1] = edge

# Processing requests
while True:
    vertices = deepcopy(graph)
    edges = deepcopy(roads)
    heap = MinHeap(vertices)

    print('Enter "time start_id end_id": ', end=' ')
    time, start_id, end_id = [float(i) for i in input().split()]
    start_id = int(start_id)
    end_id = int(end_id)
    users.append(User(len(users), time, start_id, end_id))
Esempio n. 34
0
def create_edge(u, v) :
    e = Edge(u, v)

    return e
Esempio n. 35
0
 def setUp(self):
     self.edge = Edge(1, 2)
     self.edge2 = Edge(2, 1)
Esempio n. 36
0
 def add_edge(self, edge: Edge) -> None:
     self._edges[edge.u].append(edge)
     self._edges[edge.v].append(edge.reversed())
Esempio n. 37
0
def is_psqlgraph_entity(target):
    """Only attempt to track history on Nodes and Edges

    """
    return target.__class__ in (Node.__subclasses__() + Edge.__subclasses__())
Esempio n. 38
0
from vsm import VSM
from edge import Edge
from expect_client import ExpectClient
import connection
import re
from vmware.common.global_config import pylogger


class EdgeExecuteCli():
    def __init__(self):
        pass


if __name__ == '__main__':
    vsm_obj = VSM("10.112.243.232", "admin", "default", "", "")
    edge_create_controller = Edge(vsm_obj)
    edge_username = "******"
    edge_password = "******"

    schema_key = 'dhcp'
    vtysh_command = "show configuration dhcp"
    edge_create_controller.execute_edge_cli(vtysh_command, edge_username,
                                            edge_password, schema_key)

    schema_key = 'ospf'
    vtysh_command = "show configuration ospf"
    edge_create_controller.execute_edge_cli(vtysh_command, edge_username,
                                            edge_password, schema_key)
 def setUp(self):
     self.v = 0
     self.w = 1
     self.A = Edge(self.v, self.w, 5)
     self.B = Edge(self.v, self.w, 5)
     self.C = Edge(self.v, self.w, 7)
Esempio n. 40
0
 def test_has_edge(self):
     self.assertTrue(self.dGraph.has_edge(Edge(2, 5)))
     self.assertFalse(self.dGraph.has_edge(Edge(10, 1)))
     with self.assertRaises(IndexError):
         self.dGraph.has_edge(Edge(40, 8))
Esempio n. 41
0
    def setUp(self):
        self.dGraph = Graph(15, directed=True)
        self.uGraph = Graph(15)

        self.dGraph.add_edge(Edge(0, 2))
        self.dGraph.add_edge(Edge(2, 6, 7))
        self.dGraph.add_edge(Edge(2, 7))
        self.dGraph.add_edge(Edge(7, 13))
        self.dGraph.add_edge(Edge(5, 11, 4))
        self.dGraph.add_edge(Edge(5, 12))
        self.dGraph.add_edge(Edge(0, 1))
        self.dGraph.add_edge(Edge(3, 14))
        self.dGraph.add_edge(Edge(1, 4))
        self.dGraph.add_edge(Edge(2, 5))
        self.dGraph.add_edge(Edge(1, 3))
        self.dGraph.add_edge(Edge(3, 8))
        self.dGraph.add_edge(Edge(4, 10, 11))
        self.dGraph.add_edge(Edge(4, 9))


        self.uGraph.add_edge(Edge(0, 1))
        self.uGraph.add_edge(Edge(0, 2))
        self.uGraph.add_edge(Edge(1, 3))
        self.uGraph.add_edge(Edge(2, 5))
        self.uGraph.add_edge(Edge(2, 6, 6))
        self.uGraph.add_edge(Edge(1, 4))
        self.uGraph.add_edge(Edge(2, 7))
        self.uGraph.add_edge(Edge(3, 8))
        self.uGraph.add_edge(Edge(4, 9))
        self.uGraph.add_edge(Edge(5, 11))
        self.uGraph.add_edge(Edge(4, 10, 12))
        self.uGraph.add_edge(Edge(5, 12))
        self.uGraph.add_edge(Edge(7, 13))
        self.uGraph.add_edge(Edge(3, 14))
Esempio n. 42
0
 def test_weight(self):
     self.assertEqual(7, self.dGraph.weight(Edge(2, 6)))
     self.assertEqual(None, self.dGraph.weight(Edge(0, 6,)))
     self.assertEqual(11, self.dGraph.weight(Edge(4, 10)))
     with self.assertRaises(IndexError):
         self.dGraph.weight(Edge(1111, 6))
Esempio n. 43
0
    def __init__(self):
        super(OverlayParser, self).__init__()
        self.__sub_overlays = []
        self.__sub_overlays.append(
            Overlay([['\.']], [Node(0.5, 0.5)], options=['dotted']))
        self.__sub_overlays.append(
            Overlay([['\.', '[^\.]'], ['[^\.]', '\.']], [
                Edge(Node(0.5, 0.5, fusable=False),
                     Node(1.5, 1.5, fusable=False))
            ],
                    options=['dotted']))
        self.__sub_overlays.append(
            Overlay([['[^\.]', '\.'], ['\.', '[^\.]']], [
                Edge(Node(1.5, 0.5, fusable=False),
                     Node(0.5, 1.5, fusable=False))
            ],
                    options=['dotted']))
        self.__sub_overlays.append(
            Overlay([['\.', '\.']], [
                Edge(Node(0.5, 0.5, fusable=False),
                     Node(1.5, 0.5, fusable=False))
            ],
                    options=['dotted']))
        self.__sub_overlays.append(
            Overlay([['\.'], ['\.']], [
                Edge(Node(0.5, 0.5, fusable=False),
                     Node(0.5, 1.5, fusable=False))
            ],
                    options=['dotted']))
        self.__sub_overlays.append(
            Overlay([['\.', '\|', '\.']], [
                Edge(Node(0.5, 0.5),
                     Node(2.5, 0.5),
                     below=Edge(Node(1.5, 0), Node(1.5, 1)))
            ],
                    options=['dotted']))
        self.__sub_overlays.append(
            Overlay([['\.'], ['-'], ['\.']], [
                Edge(Node(0.5, 0.5),
                     Node(0.5, 2.5),
                     below=Edge(Node(0, 1.5), Node(1, 1.5)))
            ],
                    options=['dotted']))
        self.__sub_overlays.append(
            Overlay([['\.'], ['v']], [Edge(Node(0.5, 0.5), Node(0.5, 1.5))]))
        self.__sub_overlays.append(
            Overlay([['\^'], ['\.']], [Edge(Node(0.5, 0.5), Node(0.5, 1.5))]))
        self.__sub_overlays.append(
            Overlay([['\.', '>']], [Edge(Node(0.5, 0.5), Node(1.0, 0.5))]))
        self.__sub_overlays.append(
            Overlay([['<', '\.']], [Edge(Node(1.5, 0.5), Node(1.0, 0.5))]))

        self.__sub_overlays.append(
            Overlay([['=']], [Edge(Node(0, 0.5), Node(1, 0.5))],
                    options=['emph']))
        self.__sub_overlays.append(
            Overlay([['=', '[\|\.]', '=']], [
                Edge(Node(1, 0.5),
                     Node(2, 0.5),
                     below=Edge(Node(1.5, 0), Node(1.5, 1)))
            ],
                    options=['emph']))

        self.__sub_overlays.append(Overlay([['\+']], [Node(0.5, 0.5)]))
        self.__sub_overlays.append(
            Overlay([['-']], [Edge(Node(0, 0.5), Node(1, 0.5))]))
        self.__sub_overlays.append(
            Overlay([['\|']], [Edge(Node(0.5, 0), Node(0.5, 1))]))
        self.__sub_overlays.append(
            Overlay([['/']], [Edge(Node(0, 1), Node(1, 0))]))
        self.__sub_overlays.append(
            Overlay([["\\\\"]], [Edge(Node(1, 1), Node(0, 0))]))
        self.__sub_overlays.append(
            Overlay([["[^-]", '\|', '-']],
                    [Edge(Node(1.5, 0.5), Node(2, 0.5))]))
        self.__sub_overlays.append(
            Overlay([['-', '\|', "[^-]"]],
                    [Edge(Node(1.5, 0.5), Node(1, 0.5))]))
        self.__sub_overlays.append(
            Overlay([["[^\|]"], ['-'], ['\|']],
                    [Edge(Node(0.5, 1.5), Node(0.5, 2))]))
        self.__sub_overlays.append(
            Overlay([['\|'], ['-'], ["[^\|]"]],
                    [Edge(Node(0.5, 1.5), Node(0.5, 1))]))
        self.__sub_overlays.append(
            Overlay([['-', '[\|\.]', '-']], [
                Edge(Node(1, 0.5),
                     Node(2, 0.5),
                     below=Edge(Node(1.5, 0), Node(1.5, 1)))
            ]))
        self.__sub_overlays.append(
            Overlay([['\|'], ['[-\.=]'], ['\|']], [
                Edge(Node(0.5, 1),
                     Node(0.5, 2),
                     below=Edge(Node(0, 1.5), Node(1, 1.5)))
            ]))
        self.__sub_overlays.append(
            Overlay([['\+', '-']],
                    [Edge(Node(0.5, 0.5, fusable=False), Node(1, 0.5))]))
        self.__sub_overlays.append(
            Overlay([['-', '\+']],
                    [Edge(Node(1, 0.5), Node(1.5, 0.5, fusable=False))]))
        self.__sub_overlays.append(
            Overlay([['\+'], ['\|']],
                    [Edge(Node(0.5, 0.5, fusable=False), Node(0.5, 1))]))
        self.__sub_overlays.append(
            Overlay([['\|'], ['\+']],
                    [Edge(Node(0.5, 1), Node(0.5, 1.5, fusable=False))]))
        self.__sub_overlays.append(
            Overlay([[None, '/'], ['\+', None]],
                    [Edge(Node(1, 1), Node(0.5, 1.5, fusable=False))]))
        self.__sub_overlays.append(
            Overlay(
                [['[^\+\*]', '\*'], ['\+', '[^\+\*]']],
                [Edge(Node(1.5, 0.5, 'curve'), Node(0.5, 1.5, fusable=False))
                 ]))
        self.__sub_overlays.append(
            Overlay(
                [['\*', '[^\+\*]'], ['[^\+\*]', '\+']],
                [Edge(Node(0.5, 0.5, 'curve'), Node(1.5, 1.5, fusable=False))
                 ]))
        self.__sub_overlays.append(
            Overlay([['\+', '[^\+\*]'], ['[^\+\*]', '\+']], [
                Edge(Node(0.5, 0.5, fusable=False),
                     Node(1.5, 1.5, fusable=False))
            ]))
        self.__sub_overlays.append(
            Overlay(
                [['[^\+\*]', '\+'], ['\*', '[^\+\*]']],
                [Edge(Node(1.5, 0.5), Node(0.5, 1.5, 'curve', fusable=False))
                 ]))
        self.__sub_overlays.append(
            Overlay([['[^\+\*]', '\+'], ['\+', '[^\+\*]']], [
                Edge(Node(1.5, 0.5, fusable=False),
                     Node(0.5, 1.5, fusable=False))
            ]))
        self.__sub_overlays.append(
            Overlay(
                [['\+', '[^\+\*]'], ['[^\+\*]', '\*']],
                [Edge(Node(0.5, 0.5), Node(1.5, 1.5, 'curve', fusable=False))
                 ]))
        self.__sub_overlays.append(
            Overlay([["\\\\", None], [None, '\+']],
                    [Edge(Node(1, 1), Node(1.5, 1.5, fusable=False))]))
        self.__sub_overlays.append(
            Overlay([['\+', None], [None, "\\\\"]],
                    [Edge(Node(0.5, 0.5, fusable=False), Node(1, 1))]))
        self.__sub_overlays.append(
            Overlay([[None, '\+'], ['/', None]],
                    [Edge(Node(1.5, 0.5, fusable=False), Node(1, 1))]))
        self.__sub_overlays.append(
            Overlay([['\|'], ['\*']],
                    [Edge(Node(0.5, 1), Node(0.5, 1.5, 'curve'))]))
        self.__sub_overlays.append(
            Overlay([['\*'], ['\|']],
                    [Edge(Node(0.5, 0.5, 'curve'), Node(0.5, 1))]))
        self.__sub_overlays.append(
            Overlay([['\*', '-']],
                    [Edge(Node(0.5, 0.5, 'curve'), Node(1, 0.5))]))
        self.__sub_overlays.append(
            Overlay([['-', '\*']],
                    [Edge(Node(1, 0.5), Node(1.5, 0.5, 'curve'))]))
        self.__sub_overlays.append(
            Overlay([['\+', '\+']], [
                Edge(Node(0.5, 0.5, fusable=False),
                     Node(1.5, 0.5, fusable=False))
            ]))
        self.__sub_overlays.append(
            Overlay([['\+'], ['\+']], [
                Edge(Node(0.5, 0.5, fusable=False),
                     Node(0.5, 1.5, fusable=False))
            ]))

        self.__sub_overlays.append(
            Overlay([['\|'], ['v']], [Edge(Node(0.5, 1), Node(0.5, 1.5))]))
        self.__sub_overlays.append(
            Overlay([['\^'], ['\|']], [Edge(Node(0.5, 0.5), Node(0.5, 1))]))
        # self.__sub_overlays.append(Overlay([['-', '>']], [Edge(Node(1, 0.5), Node(1.5, 0.5))]))
        # self.__sub_overlays.append(Overlay([['<', '-']], [Edge(Node(1, 0.5), Node(0.5, 0.5))]))

        self.__sub_overlays.append(
            Overlay([['\+'], ['v']], [Edge(Node(0.5, 0.5), Node(0.5, 1.5))]))
        self.__sub_overlays.append(
            Overlay([['\^'], ['\+']], [Edge(Node(0.5, 0.5), Node(0.5, 1.5))]))
        self.__sub_overlays.append(
            Overlay([['\+', '>']], [Edge(Node(0.5, 0.5), Node(1.0, 0.5))]))
        self.__sub_overlays.append(
            Overlay([['<', '\+']], [Edge(Node(1.5, 0.5), Node(1.0, 0.5))]))

        self.__sub_overlays.append(
            Overlay([['\*', '\*']],
                    [Edge(Node(0.5, 0.5, 'curve'), Node(1.5, 0.5, 'curve'))]))
        self.__sub_overlays.append(
            Overlay([['\*'], ['\*']],
                    [Edge(Node(0.5, 0.5, 'curve'), Node(0.5, 1.5, 'curve'))]))
        self.__sub_overlays.append(
            Overlay([['[^\+\*]', '\*'], ['\*', '[^\+\*]']],
                    [Edge(Node(1.5, 0.5, 'curve'), Node(0.5, 1.5, 'curve'))]))
        self.__sub_overlays.append(
            Overlay([['\*', '[^\+\*]'], ['[^\+\*]', '\*']],
                    [Edge(Node(0.5, 0.5, 'curve'), Node(1.5, 1.5, 'curve'))]))

        crossing_top = (1.0 - OverlayParser.CROSSING_LENGTH) / 2.0
        crossing_bottom = 1.0 - (1.0 - OverlayParser.CROSSING_LENGTH) / 2.0
        crossing_top_curve = crossing_top + OverlayParser.CROSSING_LENGTH / 5.0
        crossing_bottom_curve = crossing_bottom - OverlayParser.CROSSING_LENGTH / 5.0
        crossing_left = 0.5 - OverlayParser.CROSSING_HEIGHT
        crossing_right = 0.5 + OverlayParser.CROSSING_HEIGHT

        left_bracked_node_list = [
            Edge(Node(0.5, 0), Node(0.5, crossing_top)),
            Edge(Node(0.5, crossing_top), Node(crossing_left, crossing_top)),
            Edge(Node(crossing_left, crossing_top),
                 Node(crossing_left, crossing_bottom),
                 z_order='above'),
            Edge(Node(0.5, crossing_bottom),
                 Node(crossing_left, crossing_bottom)),
            Edge(Node(0.5, 1), Node(0.5, crossing_bottom))
        ]
        right_bracket_node_list = [
            Edge(Node(0.5, 0), Node(0.5, crossing_top)),
            Edge(Node(0.5, crossing_top), Node(crossing_right, crossing_top)),
            Edge(Node(crossing_right, crossing_top),
                 Node(crossing_right, crossing_bottom),
                 z_order='above'),
            Edge(Node(0.5, crossing_bottom),
                 Node(crossing_right, crossing_bottom)),
            Edge(Node(0.5, 1), Node(0.5, crossing_bottom))
        ]
        left_parentheses_node_list = [
            Edge(Node(0.5, 0, 'curve', fusable=False),
                 Node(0.5, crossing_top, 'curve')),
            Edge(Node(0.5, crossing_top, 'curve'),
                 Node(crossing_left, crossing_top_curve, 'curve')),
            Edge(Node(crossing_left, crossing_top_curve, 'curve'),
                 Node(crossing_left, crossing_bottom_curve, 'curve'),
                 z_order='above'),
            Edge(Node(0.5, crossing_bottom, 'curve'),
                 Node(crossing_left, crossing_bottom_curve, 'curve')),
            Edge(Node(0.5, 1, 'curve', fusable=False),
                 Node(0.5, crossing_bottom, 'curve', fusable=False))
        ]
        right_parentheses_node_list = [
            Edge(Node(0.5, 0, 'curve', fusable=False),
                 Node(0.5, crossing_top, 'curve')),
            Edge(Node(0.5, crossing_top, 'curve'),
                 Node(crossing_right, crossing_top_curve, 'curve')),
            Edge(Node(crossing_right, crossing_top_curve, 'curve'),
                 Node(crossing_right, crossing_bottom_curve, 'curve'),
                 z_order='above'),
            Edge(Node(0.5, crossing_bottom, 'curve'),
                 Node(crossing_right, crossing_bottom_curve, 'curve')),
            Edge(Node(0.5, 1, 'curve', fusable=False),
                 Node(0.5, crossing_bottom, 'curve', fusable=False))
        ]
        self.__sub_overlays.append(Overlay([['\[']], left_bracked_node_list))
        self.__sub_overlays.append(Overlay([['\]']], right_bracket_node_list))
        self.__sub_overlays.append(
            Overlay([['\(']], left_parentheses_node_list))
        self.__sub_overlays.append(
            Overlay([['\)']], right_parentheses_node_list))

        crossing_left = (1.0 - OverlayParser.CROSSING_LENGTH) / 4.0
        crossing_right = 1.0 - (1.0 - OverlayParser.CROSSING_LENGTH) / 4.0
        crossing_left_curve = crossing_left + OverlayParser.CROSSING_LENGTH / 5.0
        crossing_right_curve = crossing_right - OverlayParser.CROSSING_LENGTH / 5.0
        crossing_top = 0.5 - OverlayParser.CROSSING_HEIGHT / 2
        tilde_node_list = [
            Edge(Node(0, 0.5, 'curve', fusable=False),
                 Node(crossing_left, 0.5, 'curve')),
            Edge(Node(crossing_left, 0.5, 'curve'),
                 Node(crossing_left_curve, crossing_top, 'curve')),
            Edge(Node(crossing_left_curve, crossing_top, 'curve'),
                 Node(crossing_right_curve, crossing_top, 'curve'),
                 z_order='above'),
            Edge(Node(crossing_right_curve, crossing_top, 'curve'),
                 Node(crossing_right, 0.5, 'curve')),
            Edge(Node(crossing_right, 0.5, 'curve'),
                 Node(1, 0.5, 'curve', fusable=False))
        ]
        self.__sub_overlays.append(Overlay([['\~']], tilde_node_list))

        for crossing_indicator in ['\[', '\]', '\(', '\)']:
            self.__sub_overlays.append(
                Overlay([['-', crossing_indicator]], [
                    Edge(Node(1, 0.5, fusable=False),
                         Node(1.5, 0.5, fusable=False))
                ]))
            self.__sub_overlays.append(
                Overlay([[crossing_indicator, '-']], [
                    Edge(Node(0.5, 0.5, fusable=False),
                         Node(1, 0.5, fusable=False))
                ]))

        self.__sub_overlays.append(
            Overlay([['\~'], ['\|']], [
                Edge(Node(0.5, 1, fusable=False), Node(0.5, 0.5,
                                                       fusable=False))
            ]))
        self.__sub_overlays.append(
            Overlay([['\|'], ['\~']], [
                Edge(Node(0.5, 1, fusable=False), Node(0.5, 1.5,
                                                       fusable=False))
            ]))
        return
Esempio n. 44
0
    def split_face(self, face, point):
        self.faces.remove(face)
        [e1, e2, e3] = face.edges
        [a, b, c] = face.vertices
        a1 = Edge()
        a2 = Edge()
        b1 = Edge()
        b2 = Edge()
        c1 = Edge()
        c2 = Edge()

        v = Vertex(point, a2)

        f1 = Face(a2)
        f2 = Face(b2)
        f3 = Face(c2)

        e1.next = b1
        e1.prev = a2
        e1.face = f1
        e2.next = c1
        e2.prev = b2
        e2.face = f2
        e3.next = a1
        e3.prev = c2
        e3.face = f3

        # setAttributes(origin, twin, face, next, prev):
        a1.setAttributes(a, a2, f3, c2, e3)
        a2.setAttributes(v, a1, f1, e1, b1)
        b1.setAttributes(b, b2, f1, a2, e1)
        b2.setAttributes(v, b1, f2, e2, c1)
        c1.setAttributes(c, c2, f2, b2, e2)
        c2.setAttributes(v, c1, f3, e3, a1)

        self.vertices.append(v)
        self.edges.extend([a1, a2, b1, b2, c1, c2])
        self.faces.extend([f1, f2, f3])

        return [v, [a1, a2, b1, b2, c1, c2], [f1, f2, f3]]

        self.updated = True
Esempio n. 45
0
 def test_comparisons(self):
     shuffled = Route(
         Edge(i='A', f='B', d=1),
         Edge(i='D', f='A', d=3),
         Edge(i='B', f='C', d=1),
         Edge(i='C', f='D', d=2),
     )
     longer_both = Route(Edge(i='A', f='B', d=1), Edge(i='B', f='C', d=1),
                         Edge(i='C', f='D', d=2), Edge(i='D', f='E', d=3),
                         Edge(i='E', f='F', d=5), Edge(i='F', f='A', d=8))
     longer_mag_fewer_stops = Route(Edge(i='A', f='B', d=1),
                                    Edge(i='B', f='C', d=2),
                                    Edge(i='C', f='A', d=8))
     peer = Route(Edge(i='A', f='B', d=1), Edge(i='B', f='C', d=1),
                  Edge(i='C', f='D', d=1), Edge(i='D', f='A', d=4))
     more_stops_same_mag = Route(Edge(i='A', f='B', d=1),
                                 Edge(i='B', f='C', d=1),
                                 Edge(i='C', f='D', d=1),
                                 Edge(i='D', f='E', d=1),
                                 Edge(i='E', f='A', d=2))
     self.assertGreater(longer_both, self.route)
     self.assertGreater(longer_mag_fewer_stops, self.route)
     self.assertNotEqual(peer, self.route)
     self.assertNotEqual(more_stops_same_mag, self.route)
     self.assertNotEqual(shuffled, self.route)
Esempio n. 46
0
    def test_comparisons(self):
        edge0 = Edge(i='A', f='B', d=2)
        edge1 = Edge(i='C', f='D', d=1)

        self.assertGreater(edge0, edge1)
        self.assertGreater(edge0, self.edge)
Esempio n. 47
0
    def build_topology_from_int(self,
                                nodes,
                                edges,
                                arrival_rate=None,
                                service_rate=None):
        # nodes -> list of int or list of (int, str) str->entry,exit
        # edges -> list of (node1, node2) or (node1, node2, capacity)
        # or (node1, node2, capacity, weight)
        # Every edge is both ways if not edge['unidir'] set or set to False
        temp_dict = dict()

        # TODO nodes.sort()
        for node in nodes:
            if type(node) == int:
                node = {'number': node}
            elif type(node) == tuple or type(node) == list:
                if len(node) == 2:
                    node = {'number': node[0], 'type': node[1]}
                else:
                    raise TypeError
            if type(node) == dict:
                node_type = node.pop('type', '')
                if not 'name' in node:
                    node['name'] = node['number']
                if not 'arrival_rate' in node:
                    node['arrival_rate'] = arrival_rate
                if not 'service_rate' in node:
                    node['service_rate'] = service_rate
                if node_type == 'entry':
                    new_node = Entry_node(**node)
                    self.entry_nodes.append(new_node)
                elif node_type == 'exit':
                    new_node = Exit_node(**node)
                    self.exit_nodes.append(new_node)
                else:
                    new_node = Node(**node)
                if node['name'] in temp_dict:
                    raise DuplicatedNodeError
                temp_dict[node['name']] = new_node
                self.add_node(new_node)
            else:
                raise TypeError

        for edge in edges:
            # TODO duplicated node -> increase capacity?
            temp_edge = dict()
            if type(edge) == tuple or type(edge) == list:
                temp_edge['nodes'] = (edge[0], edge[1])
                if len(edge) == 2:
                    pass
                elif len(edge) == 3:
                    temp_edge['capacity'] = edge[2]
                elif len(edge) == 4:
                    temp_edge['capacity'] = edge[2]
                    temp_edge['weight'] = edge[3]
                else:
                    raise TypeError
                edge = temp_edge
            if type(edge) == dict:
                nodes = edge.pop('nodes')
                weight = edge.pop('weight', 1)
                unidir = edge.pop('unidir', False)
                new_edge = Edge(**edge)
                self.add_edge(temp_dict[nodes[0]], temp_dict[nodes[1]],
                              new_edge, weight)
                if not unidir:
                    new_edge = Edge(**edge)
                    self.add_edge(temp_dict[nodes[1]], temp_dict[nodes[0]],
                                  new_edge, weight)
            else:
                raise TypeError()
Esempio n. 48
0
 def add_edge(self, edge: Edge) -> None:
     self._edges[edge.vertex_from].append(edge)
     self._edges[edge.vertex_to].append(edge.reversed())
Esempio n. 49
0
 def setUp(self):
     self.route = Route(Edge(i='A', f='B', d=1), Edge(i='B', f='C', d=1),
                        Edge(i='C', f='D', d=2), Edge(i='D', f='A', d=3))
Esempio n. 50
0
class ScrollableField(QGraphicsView):
    previous_edge = None
    last_start_socket = None
    drag_edge = None
    last_lmb_click_scene_pos = None

    def __init__(self, graphic_scene, parent=None):
        super().__init__(parent)
        self.graphic_scene = graphic_scene
        self.parent_widget = parent

        self.setRenderHints(QPainter.Antialiasing
                            | QPainter.HighQualityAntialiasing
                            | QPainter.TextAntialiasing
                            | QPainter.SmoothPixmapTransform)

        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)

        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setDragMode(QGraphicsView.RubberBandDrag)

        self.setScene(self.graphic_scene)

        self.mode = MODE_NOOP
        self.editingFlag = False

        self.zoomInFactor = 1.25
        self.zoomClamp = True
        self.zoom = 10
        self.zoomStep = 1
        self.zoomRange = [0, 10]
        self.setStyleSheet("selection-background-color: rgb(255, 255, 255);")

        # cutline
        self.cutline = LineCutter()
        self.graphic_scene.addItem(self.cutline)

        # listeners
        self._drag_enter_listeners = []
        self._drop_listeners = []

    def dragEnterEvent(self, event):
        for callback in self._drag_enter_listeners:
            callback(event)

    def dropEvent(self, event):
        for callback in self._drop_listeners:
            callback(event)

    def add_drag_enter_listener(self, callback):
        self._drag_enter_listeners.append(callback)

    def add_drop_listener(self, callback):
        self._drop_listeners.append(callback)

    def mousePressEvent(self, event):
        if event.button() == Qt.MiddleButton:
            self.middle_mouse_button_press(event)
        elif event.button() == Qt.LeftButton:
            self.left_mouse_button_press(event)
        elif event.button() == Qt.RightButton:
            self.right_mouse_button_press(event)
        else:
            super().mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.MiddleButton:
            self.middle_mouse_button_release(event)
        elif event.button() == Qt.LeftButton:
            self.left_mouse_button_release(event)
        elif event.button() == Qt.RightButton:
            self.right_mouse_button_release(event)
        else:
            super().mouseReleaseEvent(event)

    def middle_mouse_button_press(self, event):
        release_event = QMouseEvent(QEvent.MouseButtonRelease,
                                    event.localPos(), event.screenPos(),
                                    Qt.LeftButton, Qt.NoButton,
                                    event.modifiers())
        super().mouseReleaseEvent(release_event)
        self.setDragMode(QGraphicsView.ScrollHandDrag)
        fake_event = QMouseEvent(event.type(), event.localPos(),
                                 event.screenPos(), Qt.LeftButton,
                                 event.buttons() | Qt.LeftButton,
                                 event.modifiers())
        super().mousePressEvent(fake_event)

    def middle_mouse_button_release(self, event):
        fake_event = QMouseEvent(event.type(), event.localPos(),
                                 event.screenPos(), Qt.LeftButton,
                                 event.buttons() & ~Qt.LeftButton,
                                 event.modifiers())
        super().mouseReleaseEvent(fake_event)
        self.setDragMode(QGraphicsView.NoDrag)

    def left_mouse_button_press(self, event):
        # get item which we clicked on
        item = self.get_item_at_click(event)

        # we store the position of last LMB click
        self.last_lmb_click_scene_pos = self.mapToScene(event.pos())

        logger.debug("Left Click on {}".format(item))

        # logic
        if hasattr(item, "node.py") or isinstance(
                item, GraphicalPath) or item is None:
            if event.modifiers() & Qt.ShiftModifier:
                event.ignore()
                fake_event = QMouseEvent(
                    QEvent.MouseButtonPress, event.localPos(),
                    event.screenPos(), Qt.LeftButton,
                    event.buttons() | Qt.LeftButton,
                    event.modifiers() | Qt.ControlModifier)
                super().mousePressEvent(fake_event)
                return

        if type(item) is GraphicSocket:
            if self.mode == MODE_NOOP:
                self.mode = MODE_EDGE_DRAG
                self.edge_drag_start(item)
                return

        if self.mode == MODE_EDGE_DRAG:
            res = self.edge_drag_end(item)
            if res:
                return

        if item is None:
            if event.modifiers() & Qt.ControlModifier:
                self.mode = MODE_EDGE_CUT
                fake_event = QMouseEvent(QEvent.MouseButtonRelease,
                                         event.localPos(), event.screenPos(),
                                         Qt.LeftButton, Qt.NoButton,
                                         event.modifiers())
                super().mouseReleaseEvent(fake_event)
                QApplication.setOverrideCursor(Qt.CrossCursor)
                return

        super().mousePressEvent(event)

    def left_mouse_button_release(self, event):
        # get item which we release mouse button on
        item = self.get_item_at_click(event)

        # logic
        if hasattr(item, "node.py") or isinstance(
                item, GraphicalPath) or item is None:
            if event.modifiers() & Qt.ShiftModifier:
                event.ignore()
                fake_event = QMouseEvent(
                    event.type(), event.localPos(), event.screenPos(),
                    Qt.LeftButton, Qt.NoButton,
                    event.modifiers() | Qt.ControlModifier)
                super().mouseReleaseEvent(fake_event)
                return

        if self.mode == MODE_EDGE_DRAG:
            if self.distance_between_click_and_release_is_off(event):
                if self.edge_drag_end(item):
                    return

        if self.mode == MODE_EDGE_CUT:
            self.cut_intersecting_edges()
            self.cutline.line_points = []
            self.cutline.update()
            QApplication.setOverrideCursor(Qt.ArrowCursor)
            self.mode = MODE_NOOP
            return

        super().mouseReleaseEvent(event)

    def right_mouse_button_press(self, event):
        super().mousePressEvent(event)

        item = self.get_item_at_click(event)

        if isinstance(item, GraphicalPath):
            logger.debug('RMB DEBUG:', item.edge, ' connecting sockets:',
                         item.edge.start_socket, item.edge.end_socket)
        if type(item) is GraphicSocket:
            logger.debug('RMB DEBUG:', item.socket, 'has edge:',
                         item.socket.edge)

        if item is None:
            logger.debug('SCENE:')
            logger.debug('  Nodes:')
            for node in self.graphic_scene.scene.nodes:
                logger.debug('    {}'.format(node))
            logger.debug('  Edges:')
            for edge in self.graphic_scene.scene.edges:
                logger.debug('    {}'.format(edge))

    def right_mouse_button_release(self, event):
        super().mouseReleaseEvent(event)

    def mouseMoveEvent(self, event):
        if self.mode == MODE_EDGE_DRAG:
            pos = self.mapToScene(event.pos())
            self.drag_edge.graphic_edge.set_destination(pos.x(), pos.y())
            self.drag_edge.graphic_edge.update()

        if self.mode == MODE_EDGE_CUT:
            pos = self.mapToScene(event.pos())
            self.cutline.line_points.append(pos)
            self.cutline.update()

        super().mouseMoveEvent(event)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Delete:
            if not self.editingFlag:
                self.delete_selected()
            else:
                super().keyPressEvent(event)
        else:
            super().keyPressEvent(event)

    def cut_intersecting_edges(self):
        for ix in range(len(self.cutline.line_points) - 1):
            p1 = self.cutline.line_points[ix]
            p2 = self.cutline.line_points[ix + 1]

            for edge in self.graphic_scene.scene.edges:
                if edge.graphic_edge.intersects_with(p1, p2):
                    edge.remove()

    def delete_selected(self):
        response = QMessageBox.question(
            self, '', "Are you sure to remove selected item(s)?",
            QMessageBox.Yes | QMessageBox.No)
        if response == QMessageBox.Yes:
            for item in self.graphic_scene.selectedItems():
                if isinstance(item, GraphicalPath):
                    item.edge.remove()
                elif hasattr(item, 'node'):
                    item.node.remove()
                    self.parent_widget.parent_window.change_statusbar_text()

    def get_item_at_click(self, event):
        """ return the object on which we've clicked/release mouse button """
        pos = event.pos()
        obj = self.itemAt(pos)
        return obj

    def edge_drag_start(self, item):
        self.previous_edge = item.socket.edge
        self.last_start_socket = item.socket

        self.drag_edge = Edge(self.graphic_scene.scene, item.socket, None)

    # called when we append an edge
    def edge_drag_end(self, item):
        self.mode = MODE_NOOP

        if isinstance(item, GraphicSocket):
            if item.socket != self.last_start_socket:
                logger.debug('Previous edge: {}'.format(self.previous_edge))
                if item.socket.has_edge():
                    item.socket.edge.remove()
                logger.debug('End Socket {}'.format(item.socket))
                if self.previous_edge is not None:
                    self.previous_edge.remove()

                self.drag_edge.start_socket = self.last_start_socket
                self.drag_edge.end_socket = item.socket
                self.drag_edge.start_socket.set_edge(self.drag_edge)
                self.drag_edge.end_socket.set_edge(self.drag_edge)

                logger.debug(type(self.drag_edge))
                self.parent_widget.edges.append(self.drag_edge)
                self.drag_edge.update_positions()
                return True

        logger.debug('View::edgeDragEnd ~ End dragging edge')

        self.drag_edge.remove()
        self.drag_edge = None
        logger.debug(
            'View::edgeDragEnd ~ about to set socket to previous edge: {}'.
            format(self.previous_edge))
        if self.previous_edge is not None:
            self.previous_edge.start_socket.edge = self.previous_edge
        logger.debug('View::edgeDragEnd ~ everything done.')

        return False

    def distance_between_click_and_release_is_off(self, event):
        """ measures if we are too far from the last LMB click scene position """
        new_lmb_release_scene_pos = self.mapToScene(event.pos())
        dist_scene = new_lmb_release_scene_pos - self.last_lmb_click_scene_pos
        edge_drag_threshold_sq = EDGE_DRAG_START_THRESHOLD * EDGE_DRAG_START_THRESHOLD
        return (dist_scene.x() * dist_scene.x() +
                dist_scene.y() * dist_scene.y()) > edge_drag_threshold_sq

    def wheelEvent(self, event):
        # calculate our zoom Factor
        zoom_out_factor = 1 / self.zoomInFactor

        # calculate zoom
        if event.angleDelta().y() > 0:
            zoom_factor = self.zoomInFactor
            self.zoom += self.zoomStep
        else:
            zoom_factor = zoom_out_factor
            self.zoom -= self.zoomStep

        clamped = False
        if self.zoom < self.zoomRange[0]:
            self.zoom, clamped = self.zoomRange[0], True
        if self.zoom > self.zoomRange[1]:
            self.zoom, clamped = self.zoomRange[1], True

        # set scene scale
        if not clamped or self.zoomClamp is False:
            self.scale(zoom_factor, zoom_factor)
Esempio n. 51
0
 def test_bad_contructor_args(self):
     with self.assertRaises(KeyError):
         Edge(i='A', f='B', nonsense=1)
Esempio n. 52
0
    def edge_drag_start(self, item):
        self.previous_edge = item.socket.edge
        self.last_start_socket = item.socket

        self.drag_edge = Edge(self.graphic_scene.scene, item.socket, None)
Esempio n. 53
0
 def find_nodes_and_edges(self):
     ''' Taking all of the paths/roads in the given area, this breaks up those paths/roads into edges and stores in a list.'''
     self.edge_list = []
     for way in self.ways:
         breakpoints = []
         for i in range(len(way.nodes)):
             if way.nodes[i] in self.intersections:
                 breakpoints.append(i)
         if breakpoints == []:
             new_edge = Edge()
             new_edge.set_start_node(way.nodes[0])
             new_edge.set_end_node(way.nodes[-1])
             if len(way.nodes) > 2:
                 new_edge.add_multiple_nodes(way.nodes[1:-1])
             new_edge.update_distance()
             self.edge_list.append(new_edge)
         else:
             new_ways = []
             for point in range(len(breakpoints) - 1):
                 new_ways.append(
                     way.nodes[breakpoints[point]:breakpoints[point + 1] +
                               1])
             for edge_way in new_ways:
                 new_edge = Edge()
                 new_edge.set_start_node(edge_way[0])
                 new_edge.set_end_node(edge_way[-1])
                 if len(edge_way) > 2:
                     new_edge.add_multiple_nodes(edge_way[1:-1])
                 new_edge.update_distance()
                 self.edge_list.append(new_edge)
Esempio n. 54
0
    # retrieve by color
    method = Color()
    samples = method.make_samples(db)
    query = samples[query_idx]
    _, result = infer(query, samples=samples, depth=depth, d_type=d_type)
    print(result)

    # retrieve by daisy
    method = Daisy()
    samples = method.make_samples(db)
    query = samples[query_idx]
    _, result = infer(query, samples=samples, depth=depth, d_type=d_type)
    print(result)

    # retrieve by edge
    method = Edge()
    samples = method.make_samples(db)
    query = samples[query_idx]
    _, result = infer(query, samples=samples, depth=depth, d_type=d_type)
    print(result)

    # retrieve by gabor
    method = Gabor()
    samples = method.make_samples(db)
    query = samples[query_idx]
    _, result = infer(query, samples=samples, depth=depth, d_type=d_type)
    print(result)

    # retrieve by HOG
    method = HOG()
    samples = method.make_samples(db)
Esempio n. 55
0
 def addEdge(self, u, v, w):
     self.edges[u].append(Edge(u, v, w))
Esempio n. 56
0
 def add_edge_by_indices(self, _from: int, _to: int) -> None:
     edge: Edge = Edge(_from, _to)
     self.add_edge(edge)
Esempio n. 57
0
def parse_chem(filename):
    # Properties of the graph. Characterized in the first block of a graph-file
    n_of_nodes = 0
    n_of_edges = 0
    nodes_label = True
    edges_label = True
    directed_graph = False

    #Booleans to check in which part of the Chem-Graph we are
    into_vertices = False
    into_vertex_labels = False
    into_edges_one = False
    into_edges_two = False
    into_edges_label = False

    #Lists to save all vertices, edges and teh respective labels to then create the graph-object from
    vertices_all = []
    vertex_labels_all = []
    edges_one_all = []
    edges_two_all = []
    edges_labels_all = []

    # Vertex list is characterized in the 2nd block of a graph-file
    vertex_list = []

    # Edge list is characterized in the 3rd block of a graph-file
    edge_list = []

    # dict for accessing the vertices via their names
    vertex_dict = {}

    with open(filename, 'r') as file:
        file_content = file.readlines()
        for i in range(0, len(file_content)):
            temp: str = file_content[i].replace('\n', '')
            temp = temp.replace(' ', '')
            #finish reading the file after the important first few blocks
            if temp == '"coords":[':
                break
            if temp == '"aid":[':
                into_vertices = True
            elif temp == '"element":[':
                into_vertex_labels = True
            elif temp == '"aid1":[':
                into_edges_one = True
            elif temp == '"aid2":[':
                into_edges_two = True
            elif temp == '"order":[':
                into_edges_label = True
            elif temp == '],' and into_edges_one:
                into_edges_one = False
            elif temp == '],' and into_edges_two:
                into_edges_two = False
            elif temp == ']' and into_edges_label:
                into_edges_label = False
            elif into_vertices and temp == '],':
                into_vertices = False
            elif into_vertex_labels and temp == ']':
                into_vertex_labels = False
            elif into_vertices:
                temp2 = temp.split(',')
                vertices_all.append(temp2[0])
            elif into_vertex_labels:
                temp2 = temp.split(',')
                vertex_labels_all.append(temp2[0])
            elif into_edges_one:
                temp2 = temp.split(',')
                edges_one_all.append(temp2[0])
            elif into_edges_two:
                temp2 = temp.split(',')
                edges_two_all.append(temp2[0])
            elif into_edges_label:
                temp2 = temp.split(',')
                edges_labels_all.append(temp2[0])
        # creating graph-object after finishing reading the file
        for i in range(0, len(vertices_all)):
            v = Vertex(vertices_all[i])
            e = element(int(vertex_labels_all[i]))
            v.set_node_label(e.symbol)
            vertex_list.append(v)
            vertex_dict.update({v.name: v})

        for i in range(0, len(edges_one_all)):
            e = Edge(vertex_dict.get(edges_one_all[i]),
                     vertex_dict.get(edges_two_all[i]))
            e.set_label(edges_labels_all[i])
            edge_list.append(e)

        n_of_nodes = len(vertices_all)
        n_of_edges = len(edges_one_all)

    graph = Graph(vertex_list, edge_list, n_of_nodes, n_of_edges, nodes_label,
                  edges_label, directed_graph)
    return graph
Esempio n. 58
0
def parse(filename):

    # Properties of the graph. Characterized in the first block of a graph-file
    n_of_nodes = 0
    n_of_edges = 0
    nodes_label = False
    edges_label = False
    directed_graph = False

    # Vertex list is characterized in the 2nd block of a graph-file
    vertex_list = []

    # Edge list is characterized in the 3rd block of a graph-file
    edge_list = []

    # c is a counter to know in which block of the graph-file we are
    c = 0

    # dict für das Zugreifen auf die Vertices über ihre Namen
    vertex_dict = {}
    with open(filename, 'r') as file:
        file_content = file.readlines()
        for i in range(0, len(file_content)):
            temp = file_content[i].replace('\n', '').split(';')
            if temp == ['']:
                c += 1
            elif temp is not '' and c == 0:
                if temp[0] == '#nodes':
                    n_of_nodes = temp[1]
                elif temp[0] == '#edges':
                    n_of_edges = temp[1]
                elif temp[0] == 'Nodes labelled':
                    if temp[1] == 'True':
                        nodes_label = True
                    else:
                        nodes_label = False
                elif temp[0] == 'Edges labelled':
                    if temp[1] == 'True':
                        edges_label = True
                    else:
                        edges_label = False
                elif temp[0] == 'Directed graph':
                    if temp[1] == 'True':
                        directed_graph = True
                    else:
                        directed_graph = False
            elif c == 1:
                v = Vertex(temp[0])
                if nodes_label:
                    v.set_node_label(temp[1])
                vertex_list.append(v)
                vertex_dict.update(
                    {v.name: v}
                )  # Vertex wird für Edges-Initialiserung gespeichert (Name=Key)
            elif c == 2:
                e = Edge(vertex_dict.get(temp[0]), vertex_dict.get(temp[1]),
                         None, None, directed_graph)
                if edges_label:
                    e.set_label(temp[2])
                edge_list.append(e)

    graph = Graph(vertex_list, edge_list, n_of_nodes, n_of_edges, nodes_label,
                  edges_label, directed_graph)
    return graph
Esempio n. 59
0
 def add_edge_by_indices(self, u: int, v: int) -> None:
     edge: Edge = Edge(u, v)
     self.add_edge(edge)
Esempio n. 60
0
        # add edges to graph
        nb_edges = sum(xrange(dim))
        K = 0
        for edge in edges:
            # nodes
            (nid1, nid2) = (edge[0], edge[1])
            node_list = G.retrieve_nodes_from_id(nid1, nid2)
            n1 = node_list[0]
            n2 = node_list[0] if len(node_list) == 1 else node_list[1]
            # weight
            w = edge[2]
            # edge id
            # add edge if not circular
            if not (w == 0 and n1 == n2):
                G.add_edge(Edge(iden=K, node1=n1, node2=n2, weight=w))
                K += 1

        logging.info('Fichier lu, graphe cree')

        # Algorithme RSL
        logging.info("Debut de Rosenkrantz")
        roots = G.nodes

        if "bayg29" in finstance:
            min_tour = G.rsl(roots[14], "prim", "dfs")
            name = "bayg29_min_tour.png"
        elif "bays29" in finstance:
            min_tour = G.rsl(roots[23], "kruskal", "dfs")
            name = "bays29_min_tour.png"
        elif "brazil58" in finstance: