Exemple #1
0
def main(BP):
    klt_node = 'i'  #The node, where the KLT should be dropped
    klt = False

    #Determine the shortest route through Dijkstra
    shortestWay1 = Dijkstra.dijkstra('a', klt_node)
    shortestWay2 = Dijkstra.dijkstra(klt_node, 'o')
    shortestWay2.pop(0)
    shortestWay = shortestWay1 + ["klt"] + shortestWay2
    print('My route: ' + str(shortestWay))
    shortestWay.pop(0)
    #Move the robot to the startnode
    ################
    stop = follower.line_follower(BP, 400, 7, 0.01, [5])
    if stop == "Red":
        #functions.driveforward_mm(BP, functions.marker_offset)
        print("Startkoten erreicht")

    #Build a loop which leads the robot through the network by using the route calculated above by Dijkstra
    ################
    #Your code here#
    ################
    while len(shortestWay) != 0:

        find_new_path(BP, shortestWay, klt_node)
        print("Naechster Node")
        stop = follower.line_follower(BP, 400, 7, 0.01, [5])
Exemple #2
0
def find_path(source , distination , mygraph) :
    update_wieght()
    path = Dijkstra.dijkstra(mygraph , source)
    mypath = []
    while (distination != source ) :
        mypath.append(distination)
        distination = path[distination]
    mypath.append(source)
    return mypath
Exemple #3
0
def isomap(trainmatdata, testmatdata, k, type, dimenson):
    nodemat = hstack((trainmatdata, testmatdata))  #矩阵合并
    nodenum = size(nodemat, 1)  #节点数,即数据量
    wgraph = mat(zeros((nodenum, nodenum))) - 1  #节点的连接权重矩阵,初始值都设为-1,表示无穷大
    for num1 in range(nodenum):
        node1 = nodemat[:, num1]
        distances = []  #存储该节点到所有节点的距离(包括自身)
        for num2 in range(nodenum):
            node2 = nodemat[:, num2]
            distances.append(linalg.norm(node1 - node2))
        #取最近的k+1个节点,将距离写入连接权重矩阵(距离最近的为自身)
        indices = argsort(distances)
        for count in range(k + 1):
            wgraph[num1, indices[count]] = distances[indices[count]]
    #将wgraph转化为对称矩阵,即无向图
    for i in range(nodenum):
        for j in range(nodenum):
            if (wgraph[i, j] != -1):
                wgraph[j, i] = wgraph[i, j]

    #计算所有点对之间的最短距离
    if (type == 'dijkstra'):
        distgraph = []
        for i in range(nodenum):
            mindists = Dijkstra.dijkstra(wgraph, i)
            if (size(mindists) == 0):  #图不连通
                return []
            distgraph.append(mindists)
        distgraph = mat(distgraph)
    elif (type == 'floyd'):
        distgraph = Floyd.floyd(wgraph)
        if (size(distgraph) == 0):  #图不连通
            return []
    else:
        print u'最短距离算法类型错误'
        return []

    #运行MDS算法
    result = MDS.mds(distgraph, dimenson)

    return result
Exemple #4
0
def init_data():
    #拿到所有的街道节点
    # street_nodes, list = data2map()
    street_nodes, list = data_to_map()
    #节点的个数
    size = len(street_nodes)
    print("拿到所有的街道节点数据,共有%s个节点,下面开始写入文件中..." % size)

    #将计算得到的数据写入到txt文件中
    for key in street_nodes:
        node = street_nodes[key]
        distance, path = Dijkstra.dijkstra(node, street_nodes, list)
        # print(type(distance))
        print("拿到第%s节点的数据,开始写入到对应文件中.." % node.id)
        # file_path = "distances/distance" + str(node.id) + ".txt"
        file_path = "distances/distance" + str(node.id) + ".txt"
        print("%s文件写入完成" % file_path)
        DataOperate.write_distancedata_to_txt(distance, file_path)
        # file_path = "paths/path" + str(node.id) + ".txt"
        file_path = "paths/path" + str(node.id) + ".txt"
        print("%s文件写入完成" % file_path)
        DataOperate.write_distancedata_to_txt(path, file_path)
Exemple #5
0
def View_path():
    start = start_point.get()
    end = end_point.get()
    if start == "출발지 선택":
        return False
    if end == "도착지 선택":
        return False

    (arrival_time, path_list) = Dijkstra.dijkstra(start, end)
    folium_draw_line.draw_path(path_list)

    # 도착시간을 알려주는 label 추가
    arrive_time = math.ceil(arrival_time)
    hour = (arrive_time - arrive_time % 60) / 60
    arrive_time = deltaTime(hour, arrive_time % 60, 0)
    arrival_text = "도착 예정 시간은 " + \
        str(arrive_time.hour)+"시 "+str(arrive_time.minute)+"분 입니다."
    arrive_label = tk.Label(window,
                            text=arrival_text,
                            bg="white",
                            width=32,
                            height=1,
                            font=("맑은 고딕", 15),
                            bd=1)
    arrive_label.place(x=162, y=240)

    # 경로를 알려주는 web을 여는 버튼 추가
    way = tk.Button(window,
                    text="!! Go To Check !!",
                    font=("맑은 고딕", 15),
                    relief="solid",
                    fg='Green',
                    bg='white',
                    width=25,
                    height=1,
                    command=open_html)
    way.place(x=200, y=300)
if __name__ == "__main__":

    ###FOR ADJACENCY MATRIX
    #value = weight, index=node dest
    #i.e. [0,0,0,5] this node is connected to node 4 with a cost of 5

    ###FOR WEIGHTED EDGES LIST
    #each edge is a row with three values, [source, dest, weight]

    print("Enter desired number of nodes")
    nodes = int(input())
    print("Enter desired completeness percentage as a decimal, i.e. 15% = .15")
    cGoal = float(input())
    print(
        "Note: If program runs for several seconds, try changing the distance threshold in Graph.py to reach the desired completeness more easily"
    )
    adjacencyMatrix, weightedEdges = Graph.generateGraph(nodes, cGoal)

    #Find shortest path using Dijkstra's algorithm
    print("\n~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("Dijkstra's Algorithm")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~")

    Dijkstra.dijkstra(adjacencyMatrix, nodes)

    print("\n~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("Bellman-Ford Algorithm")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~")

    BellmanFord.BellmanFord(weightedEdges, nodes)
Exemple #7
0
def start_router():
    UDP_IP_Address = "localhost"
    global port_no, Dijkstra_has_run, table_cost, predecessors
    c_port_no = port_no + 1
    seqnum = 0
    Dijkstra_has_run = False

    #Starting server socket to receive messages
    try:
        UDP_ss = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
        UDP_ss.bind((UDP_IP_Address, port_no))
        UDP_ss.setblocking(0)
    except socket.error as err:
        print("Server socket failure with error ", err)

    #Starting client socket to send messages
    try:
        UDP_cs = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
        UDP_cs.bind((UDP_IP_Address, c_port_no))
    except socket.error as err:
        print("Client socket failure with error ", err)

    #Initiate the router's log - creates the file and writes the header
    initiate_log()
    #Infinite loop to run simulation
    while True:
        try:
            data, addr = UDP_ss.recvfrom(1024)
            in_c_port = int(addr[1])
            p = Packet.frombytes(data)
            #If the packet type is a flood packet...
            if isinstance(p, Packet.FloodPack):
                if p.seq < seqnum:
                    if DEBUG: print("duplicate packet found")
                    write_to_log("flood", p.src, in_c_port, 0, "No Message",
                                 "Drop")
                    continue
                seqnum = p.seq + 1
                if DEBUG:
                    print("found viable flood packet with data" + p.payload)
                [recv_db, recv_ports] = parse_packet_load(p.payload)
                update_table(recv_db, "database")
                update_table(recv_ports, "ports_table")
                #reachable_ports contains all neighbor ports derived from the LSA
                for po in reachable_ports:
                    UDP_cs.sendto(p.tobytes(), (UDP_IP_Address, po))
                    write_to_log("flood", p.src, in_c_port, po, "No Message",
                                 "Forward")
            #If the packet type is a Dijkstra broadcast...
            elif isinstance(p, Packet.DijkPack) and not p.dest:
                if DEBUG:
                    print("found viable dijkstra broadcast packet with data" +
                          p.payload)
                if Dijkstra_has_run == False:
                    [table_cost, predecessors] = Dijkstra.dijkstra(database)
                    rt = build_routing_table(table_cost, predecessors)
                    Dijkstra_has_run == True
                [ports_to_send_to, _] = send_dijkstras(p.src)
                if len(ports_to_send_to) == 0:
                    write_to_log("broadcast: Dijkstra", p.src, in_c_port, 0,
                                 p.payload, "Drop")
                for po in ports_to_send_to:
                    UDP_cs.sendto(p.tobytes(), (UDP_IP_Address, po))
                    write_to_log("broadcast: Dijkstra", p.src, in_c_port, po,
                                 p.payload, "Forward")
            #If the packet tye is a peer-to-peer Dijkstra request...
            elif isinstance(p, Packet.DijkPack) and p.dest:
                if DEBUG:
                    print("found viable p2p dijkstra packet with data" +
                          p.payload)
                if Dijkstra_has_run == False:
                    [table_cost, predecessors] = Dijkstra.dijkstra(database)
                    build_routing_table(table_cost, predecessors)
                    Dijkstra_has_run == True
                if p.dest == IP_addr:
                    print("Arrived!")
                    write_to_log("p2p: Dijkstra", p.src, in_c_port, 0,
                                 p.payload, "Drop", p.dest)
                else:
                    dest_port = p2p_dijkstra(p.src, p.dest)
                    write_to_log("p2p: Dijkstra", p.src, in_c_port, dest_port,
                                 p.payload, "Forward", p.dest)
                    UDP_cs.sendto(p.tobytes(), (UDP_IP_Address, dest_port))
            #Any unknown type of message will print the data read and contine
            else:
                print("Message: ", data)
                #UDP_ss.close()
                #UDP_cs.close()
                #sys.exit()
        #Occurs if there is no incoming data to read
        except socket.error:
            #Non-blocking way to read the command line
            while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
                line = sys.stdin.readline().rstrip()
                #broadcast,noDijkstra is a flood request.  Creates a new flood message and sets the appropriate sequence number.  Data included is the LSA split into a data structure containing neighbor cost and a data structure containing ports associated with each neighbor
                if line == "broadcast,noDijkstra":
                    sendMe = Packet.FloodPack()
                    sendMe.seq = seqnum
                    sendMe.payload = compress_table(
                        LSA_database) + ":" + compress_table(LSA_ports_table)
                    sendMe.src = IP_addr
                    for p in reachable_ports:
                        UDP_cs.sendto(sendMe.tobytes(), (UDP_IP_Address, p))
                    seqnum += 1
                #boradcast,withDijkstra is a broadcast along the spanning tree created by running Dijkstras and this router as the source.  If this router hasn't run Dijkstra's algorithm on the network yet it first runs it.  This router checks if it is the predecessor of any routers, and only sends to those routers.
                elif line == "broadcast,withDijkstra":
                    if Dijkstra_has_run == False:
                        [table_cost,
                         predecessors] = Dijkstra.dijkstra(database)
                        rt = build_routing_table(table_cost, predecessors)
                        Dijkstra_has_run == True
                    [ports_to_send_to, sendMe] = send_dijkstras(IP_addr,
                                                                new=True)
                    if DEBUG: print(ports_to_send_to)
                    for p in ports_to_send_to:
                        UDP_cs.sendto(sendMe.tobytes(), (UDP_IP_Address, p))
                #If the request is a peer-to-peer Dijkstra, it checks to see if Dijkstras needs to be run.  It creates a message with the destination set to the specified router and determines where to send it.
                elif line.split(',')[0] == 'p2p' and line.split(
                        ',')[1] == 'Dijkstra':
                    dest_IP = line.split(',')[2]
                    if Dijkstra_has_run == False:
                        [table_cost,
                         predecessors] = Dijkstra.dijkstra(database)
                        build_routing_table(table_cost, predecessors)
                        Dijkstra_has_run == True
                    dest_port = p2p_dijkstra(IP_addr, dest_IP)
                    sendMe = Packet.DijkPack()
                    sendMe.payload = "Dijkstra at your service!"
                    sendMe.src = IP_addr
                    sendMe.dest = dest_IP
                    UDP_cs.sendto(sendMe.tobytes(),
                                  (UDP_IP_Address, dest_port))
                #Used in debugging to see the routers current knowledge of the graph topology
                elif line == "print tables":
                    print_table(database)
                    print_table(ports_table)
Exemple #8
0
input_file = "tealady_tree.json"
#input_file = "people_tree.json"
tree = ConceptTree(input_file)
tree.generateLattice_v2()
for edge in tree.lattice:
    print(edge)
for att in tree.attribute_labels:
    print att, tree.attribute_labels[att]
#tree.visualiseLattice("testvis.gz", view=True)

att_dict = tree.attribute_labels
att_list = att_dict.keys()
total = len(att_list)
dist_matrix = np.zeros((total,total))
new_edge_list = []
for edge in tree.lattice:
    new_edge_list.append((edge[0], edge[1], 1))
    new_edge_list.append((edge[1], edge[0], 1))

for i in range(total):
    if i % 100 == 0:
        print("Completed " + str(i) + " rows")
    for j in range(i+1, total):
        dist = Dijkstra.dijkstra(new_edge_list, att_dict[att_list[i]], att_dict[att_list[j]])
        try:
            dist_matrix[i][j] = dist[0]
        except:
            dist_matrix[i][j] = dist


print(dist_matrix)
y = np.random.randint(0,151,(n,2))



def heuristique1(c1):
    a = c1.dernier_point()
    arrivee = c1.arrivee()
    i = abs(a[0] - arrivee[0])
    j = abs(a[1] - arrivee[1])
    return(ftt.force_to_temps(c1.u()*i + j*c1.v()))

def heuristique2(c1):
    return(0)

t1 = time.time()
for i in range(n):
    A_star.A_star(grib,(x[i][0],y[i][0]),(x[i][1],y[i][1]),heuristique1)
print((time.time()-t1)/n)

t1 = time.time()
for i in range(n):
    A_star.A_star(grib,(x[i][0],y[i][0]),(x[i][1],y[i][1]), heuristique2)
print((time.time() - t1)/n)


t1 = time.time()
for i in range(n):
    Dijkstra.dijkstra(grib,(x[i][0],y[i][0]),(x[i][1],y[i][1]))
print((time.time()-t1)/n)