Пример #1
0
def SelectFinalRoutes(candidatewaypath, savefinalroutespath):
    """
    本函数与SelectFinalRoute功能相同,只是本函数处理完整的轨迹时,如果大于50.会重新开始计算最大连通性
    根据坐标点的候选路段选出路网的匹配路线
    保存格式为:车辆名:路线(如果不确定,可能为多条),车辆名为txt文件名
    :param candidatewaypath:  坐标点候选路段的txt文件路径,如H:\\CandidateWay\\NewStrategy\\334e4763-f125-425f-ae42-8028245764fe.txt
    :param savefinalroutespath: 最终路线保存路径
    :return:
    """
    #file = open("H:\GPS_Data\Road_Network\BYQBridge\FinalRoutes\\334e4763-f125-425f-ae42-8028245764fe.txt", 'a')
    max_connect = 0
    (tempath, tempfilename) = os.path.split(
        candidatewaypath)  # tempfilename为txt文件名(包含后缀)
    (trunkname, extension) = os.path.splitext(
        tempfilename)  # filename 为传入的csv文件名 extension为后缀
    savetxtfilename = trunkname + '.txt'
    file = open(os.path.join(savefinalroutespath, savetxtfilename), 'a')
    with open(candidatewaypath) as candidatewayfile:
        filelines = candidatewayfile.readlines()
        linesnum = len(filelines)
        finalline = []  #存储最终路线,可能为多条,随着坐标点的迭代,会变化,直到处理完最有一个坐标点
        for key in eval(filelines[0].strip('\n').split(">>>")[-1]).keys():
            finalline.append([key])
        predict = eval(filelines[0].strip('\n').split(">>>")[-1])
        # 遍历每个坐标点的候选路段
        print(f"需要处理坐标数为:{linesnum}")

        for lineindex in range(1, linesnum):
            templine = []  #存储临时路线
            curdict = eval(filelines[lineindex].strip('\n').split(">>>")[-1])
            flag = 0  #标记之前的路线与当前轨迹点的所有候选路段是否能连通,不能连通,舍弃该轨迹点
            newdic = {}
            for subline in finalline:  #遍历每一条的候选路线
                #print(f"ID{lineindex-1}:{predict},{curdict}")
                for key in curdict.keys():  #遍历每个轨迹点的候选路段
                    connectroute = Common_Functions.InquireConn(
                        subline[-1], key, "connects")  #先查表
                    if connectroute != 0:
                        #print(subline[-1], predict[subline[-1]], key, curdict[key])
                        connectroute = GridMapNavigation.CandidateWay_Connect(
                            subline[-1], predict[subline[-1]], key,
                            curdict[key])  # 双重列表
                        #print(f"next:{connectroute}")
                        if connectroute:
                            flag = 1
                            for line in connectroute:
                                temsubline = copy.deepcopy(subline)
                                temsubline.extend(line)  # 将走通的路线加入到子路线,扩展当前路线
                                templine.append(temsubline)
                                #newdic[line[-1]] = curdict[line[-1]]
                        else:
                            pass
                    else:
                        pass

            if flag == 1:
                finalline.clear()
                predict = curdict
                templine = Common_Functions.DoubleDel(templine)
                templine = Common_Functions.Main_Auxiliary_road(
                    templine)  #去除头尾路段一样的候选路线,路线只有一个路段 不会处理
                templine = Common_Functions.Start_End(
                    templine
                )  # 对于[wayid1,wayid2,wayid3] [wayid1,wayid4,wayid5,wayid3]  去除路段多的,如果包含路段数量一致 暂不处理
                Common_Functions.Sequential_subset(
                    finalline)  # 最后去路线(至少两个及以上的其他路线是其前缀)
                for sub in templine:
                    finalline.append(Common_Functions.del_adjacent(sub))
            else:
                pass
            #print(f"final:{finalline}")
        print("共选出{}条路".format(len(finalline)))
        for sub in finalline:
            print(sub)
            file.write(str(sub) + "\n")
        file.close()
def Nodirectionwaytoway(way_id1,way_id2,max_sum=8):
    """
    无方向  有交点就会认为通行
    :param way_id1:
    :param way_id2:
    :param max_sum:
    :return:
    """
    if way_id1 == way_id2:
        return [way_id1,way_id2]
    finalroute = []
    node_id = TwoWay_intersection(way_id1, way_id2)  #两条路段交点
    if node_id:
        if JudgeTwoWay(way_id1,way_id2):
            finalroute.extend([way_id1, way_id2])
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 1)
            return finalroute
        else:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
            return False
    else:
        #两条路段没有直接交点
        Candidate_Routes = [[way_id1]]  # 候选路线
        flag = 0
        count = 0   #迭代多少次之后仍然没有找到可行路线,则认为不可走
        exitflag = 0   #标记是否是通过找到满足条件的路线而退出的
        grid1 = Getway_startendnode_grid(way_id1,flag=0)
        startx = grid1[0]
        starty = grid1[1]
        grid2 = Getway_startendnode_grid(way_id1, flag=0)
        Endx = grid2[0]
        Endy = grid2[1]
        while True:
            temCandidate_Routes = []  # 存储当前这一轮新的候选路线
            AllNextways = []
            MaxDel = []   #存因路段数目大于阈值,而筛除的路线
            for sub in Candidate_Routes:
                if way_id2 in sub:
                    flag = 1
                    break
                if len(sub) > max_sum:   #防止寻找时间过长,如果目的是为了查找路线,可将此条件删除
                    MaxDel.append(sub)
            for sub in MaxDel:
                Candidate_Routes.remove(sub)
            if len(Candidate_Routes)==0:
                flag = 1
                exitflag = 1
            if count==8:
                flag=1
                exitflag = 1
            if flag == 1:
                break
            for subroute in Candidate_Routes:
                # subroute 表示正在处理的路线
                preways = subroute   #表示当前路线已有的路段
                processingway = subroute[-1]  # 表示要处理的路段
                nextway = NodirectionFindNextWay(processingway,preways)  # 下一步的可选路段

                if len(nextway)==0:
                    #当前路线下一步没有能走的路
                    pass
                else:
                    AllNextways.extend(nextway)
                    for next in nextway:
                        temroute = copy.deepcopy(subroute)
                        temroute.append(next)
                        temCandidate_Routes.append(temroute)

            count += 1
            Candidate_Routes.clear()
            Candidate_Routes = temCandidate_Routes
            Candidate_Routes = Common_Functions.Double_layer_list(Candidate_Routes)
            Candidate_Routes = Common_Functions.Main_Auxiliary_road(Candidate_Routes)  # 去除头尾路段一样的候选路线
            Candidate_Routes = Common_Functions.Start_End(Candidate_Routes)  # 对于[wayid1,wayid2,wayid3] [wayid1,wayid4,wayid5,wayid3]  去除路段多的,如果包含路段数量一致 暂不处理
            Candidate_Routes = Common_Functions.Sequential_subset(Candidate_Routes)  # 最后去前缀
            #print(len(Candidate_Routes))
            delsub = []
            for sub in Candidate_Routes:
                #判断行驶方向
                secondgrid = Getway_startendnode_grid(sub[-1], flag=0)
                if secondgrid:
                    curx = secondgrid[0]
                    cury = secondgrid[1]
                    if Endx > startx and Endy>starty:   #路段way_id2 在way_id1 的右上部
                        if curx < startx and cury < starty:
                            delsub.append(sub)            #此路线方向向左下部走  删除此路线
                    if Endx > startx and Endy < starty:  # 路段way_id2 在way_id1 的右下部
                        if curx < startx and cury > starty:
                            delsub.append(sub)  # 此路线方向向左上部走  删除此路线
                    if Endx <startx and Endy < starty:  # 路段way_id2 在way_id1 的左下部
                        if curx > startx and cury > starty:
                            delsub.append(sub)  # 此路线方向向右上部走  删除此路线
                    if Endx < startx and Endy > starty:  # 路段way_id2 在way_id1 的左上部
                        if curx > startx and cury < starty:
                            delsub.append(sub)  # 此路线方向向右上部走  删除此路线
                else:
                    delsub.append(sub)


            for sub in Common_Functions.Double_layer_list(delsub):
                Candidate_Routes.remove(sub)
            #print(len(Candidate_Routes))
            if len(AllNextways)==0:
                #所有的候选路线都没有下一步路可走
                flag=1
                exitflag = 1
        minnum = float("inf")
        if exitflag==1:
            #证明是循环跳出不是因为找到路径跳出的
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
            return False
        Deleteways = []
        #print(Candidate_Routes)
        for sub in Candidate_Routes:
            #由于以上为没有方向的判断,所以在此循环中要加入方向的判断
            if way_id2 in sub:
                if len(sub)==1:
                    return sub
                elif len(sub)==2 and JudgeTwoWay(sub[0],sub[1]):
                    pass
                elif len(sub) >= 3 and JudgeLines(sub):
                    pass
                else:
                    Deleteways.append(sub)
            else:
                Deleteways.append(sub)
        if len(Deleteways)!=0:
            for delsub in Common_Functions.Double_layer_list(Deleteways):
                Candidate_Routes.remove(delsub)
        if len(Candidate_Routes)==0:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
            return False
        for sub in Candidate_Routes:
            if way_id2 in sub:
                if len(sub) < minnum:
                    finalroute = sub
                    minnum = len(sub)
            else:
                pass
        if len(finalroute)==0:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2,0)
            return False
        else:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 1)
            return finalroute
Пример #3
0
def SelectFinalRoutes(candidatewaypath, savefinalroutespath):
    """
    本函数与SelectFinalRoute功能相同,只是本函数处理完整的轨迹时,如果大于50.会重新开始计算最大连通性
    根据坐标点的候选路段选出路网的匹配路线
    保存格式为:车辆名:路线(如果不确定,可能为多条),车辆名为txt文件名
    :param candidatewaypath:  坐标点候选路段的txt文件路径,如H:\\CandidateWay\\NewStrategy\\334e4763-f125-425f-ae42-8028245764fe.txt
    :param savefinalroutespath: 最终路线保存路径
    :return:
    """
    #file = open("H:\GPS_Data\Road_Network\BYQBridge\FinalRoutes\\334e4763-f125-425f-ae42-8028245764fe.txt", 'a')
    max_connect = 0
    (tempath, tempfilename) = os.path.split(
        candidatewaypath)  # tempfilename为txt文件名(包含后缀)
    (trunkname, extension) = os.path.splitext(
        tempfilename)  # filename 为传入的csv文件名 extension为后缀
    savetxtfilename = trunkname + '.txt'
    file = open(os.path.join(savefinalroutespath, savetxtfilename), 'a')
    with open(candidatewaypath) as candidatewayfile:
        filelines = candidatewayfile.readlines()
        linesnum = len(filelines)
        finalline = []  #存储最终路线,可能为多条,随着坐标点的迭代,会变化,直到处理完最有一个坐标点
        for key in eval(filelines[0].strip('\n').split(">>>")[-1]).keys():
            finalline.append([key])
        #print(finalline)
        # 遍历每个坐标点的候选路段
        print("需要处理坐标数为:{}".format(linesnum))
        for lineindex in range(1, linesnum):
            templine = []  #存储临时路线
            # 遍历到最后一行
            print(len(finalline))
            print(finalline)
            print("处理坐标{}:{}".format(
                lineindex,
                eval(filelines[lineindex].strip('\n').split(">>>")[-1])))
            #print("处理路段{}".format(eval(filelines[lineindex].strip('\n').split(">>>")[-1])))
            for subline in finalline:  #遍历每一条的候选路线
                for key in eval(filelines[lineindex].strip('\n').split(">>>")
                                [-1]).keys():  #遍历每个轨迹点的候选路段
                    temsubline = []

                    #此代码块只加入key,不加入完整路线
                    print("路段:{}匹配key:{}".format(subline[-1], key))
                    # 只需要查看subline的最后一个路段与路段key是否连通即可,因为subline的连通性是通过测试的
                    connectroute = Common_Functions.InquireConn(
                        subline[-1], key, "connects")  #先查表
                    #connectroute = -1
                    if connectroute != 0 and connectroute != 1:  #表中没有记录 再用简易导航
                        connectroute = MapNavigation.waytoway(
                            subline[-1], key)  # 为列表
                    if connectroute:
                        temsubline = copy.deepcopy(subline)
                        temsubline.append(key)  # 只加入轨迹点所属路段,而不加入这两个路段走通的路线
                        templine.append(temsubline)
                    else:
                        # 此路线不连通,舍弃当前路段key
                        pass
                    """
                    #此代码块是加入完整路线
                    #connectroute = Common_Functions.InquireConn(subline[-1], key,"connects")   #先查表
                    #connectroute = -1
                    connectroute = MapNavigation.Nodirectionwaytoway(subline[-1], key)  # 为列表
                    if subline[-1] == key:
                        temsubline = copy.deepcopy(subline)
                        templine.append(temsubline)
                    #elif connectroute !=0 and connectroute!= 1:   #表中没有记录 再用简易导航
                        #connectroute = MapNavigation.Nodirectionwaytoway(subline[-1], key)  # 为列表
                    elif connectroute:
                        #路段可连通
                        temsubline = copy.deepcopy(subline)
                        temsubline.extend(connectroute[1:])   #将走通的路线加入到子路线,扩展当前路线
                        templine.append(temsubline)
                    else:pass
                    """

                    # print(temsubline)
                    # print(templine)
            finalline.clear()
            #print(templine)
            finalline = Common_Functions.DoubleDel(templine)  #去相邻重复 再去重
            finalline = Common_Functions.Main_Auxiliary_road(
                finalline)  #去除头尾路段一样的候选路线,路线只有一个路段 不会处理
            #print(finalline)
            finalline = Common_Functions.Start_End(
                finalline
            )  # 对于[wayid1,wayid2,wayid3] [wayid1,wayid4,wayid5,wayid3]  去除路段多的,如果包含路段数量一致 暂不处理
            finalline = Common_Functions.Sequential_subset(
                finalline)  # 最后去路线(至少两个及以上的其他路线是其前缀)
            #print(finalline)
            # finalline = Common_Functions.Double_layer_list(templine)  #去重
            # finalline = Common_Functions.Sequential_subset(finalline)  #去除前缀(两个及以上)
            #file.write(str(finalline) + "\n")
            #file.flush()
        print("共选出{}条路".format(len(finalline)))
        for sub in finalline:
            file.write(str(sub) + "\n")
            file.flush()
        print(finalline)
        file.close()
def waytoway(way_id1,way_id2,max_num=8):
    """
    实现从way_id1到way_id2的路线规划,当此函数完全用作简易导航,可设置max_num为无穷
    设置 max_num 与Count 的原因为防止查找完全不通的两个路段而耗费过长的时间
    有方向通行
    问题:即使很近的两个路段(实际短距离不能通行),但是会花费较多的时间去判断是否能通行
    47574526,403874395两个路段不能互通 但是只在北野场桥一部分就花费了5分钟去判断可行性
    :param way_id1:
    :param way_id2:
    :return:
    首先判断两个路段是否有交集,有交集则这两条路不需要经过其他路线的连接
    """
    if way_id1 == way_id2:
        return [way_id1,way_id2]
    finalroute = []
    node_id = TwoWay_intersection(way_id1, way_id2)  #两条路段交点
    if node_id:
        if JudgeTwoWay(way_id1,way_id2):
            finalroute.extend([way_id1, way_id2])
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 1)
            return finalroute
        else:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
            return False
    else:
        #两条路段没有直接交点
        Candidate_Routes = [[way_id1]]  # 候选路线
        flag = 0
        count = 0  # 迭代多少次之后仍然没有找到可行路线,则认为不可走
        exitflag = 0  #标记是否是通过找到满足条件的路线而退出的
        grid1 = Getway_startendnode_grid(way_id1, flag=0)
        startx = grid1[0]
        starty = grid1[1]
        grid2 = Getway_startendnode_grid(way_id1, flag=0)
        Endx = grid2[0]
        Endy = grid2[1]
        startendwaydis = twoway_distance(way_id1, way_id2)+ 0.01 # 加1000米弹性范围,0.0003为30米
        while True:
            print(Candidate_Routes)

            temCandidate_Routes = []  # 存储当前这一轮新的候选路线
            AllNextways = []
            print(count)
            for subroute in Candidate_Routes:
                # subroute 表示正在处理的路线
                processingway = subroute[-1]  # 表示要处理的路段
                wayflag,nextway = FindNextWay(processingway,subroute,way_id2)  # 下一步的可选路段
                #wayflag为FALSE 标记wayid2在nextway,但是由于方向问题,被删除,所以直接判定为不通
                if not wayflag:
                    Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
                    return False

                if len(nextway) == 0:
                    # 当前路线下一步没有能走的路
                    pass
                else:
                    AllNextways.extend(nextway)
                    for next in nextway:
                        temroute = copy.deepcopy(subroute)
                        temroute.append(next)
                        temCandidate_Routes.append(temroute)
            if len(AllNextways)==0:
                #所有的候选路线都没有下一步路可走
                flag=1
                exitflag = 1
            count += 1
            Candidate_Routes.clear()
            Candidate_Routes = temCandidate_Routes
            Candidate_Routes = Common_Functions.Double_layer_list(Candidate_Routes)
            Candidate_Routes = Common_Functions.Main_Auxiliary_road(Candidate_Routes)  # 去除头尾路段一样的候选路线
            Candidate_Routes = Common_Functions.Start_End(Candidate_Routes)  # 对于[wayid1,wayid2,wayid3] [wayid1,wayid4,wayid5,wayid3]  去除路段多的,如果包含路段数量一致 暂不处理
            Candidate_Routes = Common_Functions.Sequential_subset(Candidate_Routes)  # 最后去前缀
            delsub = []
            for sub in Candidate_Routes:
                if way_id2 in sub:
                    flag = 1
                    break
            if len(Candidate_Routes) == 0:
                flag = 1
                exitflag = 1
            if count == max_num:
                flag = 1
                exitflag = 1

            if flag == 1:
                break
            for sub in Candidate_Routes:
                if len(sub) >= 3:
                    if JudgeLines(sub):  # 判断当前路线是否能通
                        for i in combinations(sub,2):
                            Common_Functions.SaveRoutesConn("connects", i[0],i[1], 1)

                    elif not JudgeLines(sub) and way_id2 in sub:  # 目标路段在子路线中  但是不能走通
                        Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
                        return False
                    else:
                        delsub.append(sub)
                        continue
                elif len(sub) == 2:
                    if JudgeTwoWay(sub[0], sub[1]):
                        Common_Functions.SaveRoutesConn("connects", sub[0], sub[1], 1)
                        pass
                    elif JudgeTwoWay(sub[0], sub[1]) and way_id2 in sub:  # 目标路段在子路线中  但是不能走通
                        Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
                        return False
                    else:
                        delsub.append(sub)
                        continue
                else:
                    pass
            for sub in Candidate_Routes:
                # 判断行驶方向
                secondgrid = Getway_startendnode_grid(sub[-1], flag=0)
                if secondgrid:
                    curx = secondgrid[0]
                    cury = secondgrid[1]
                    if Endx > startx and Endy > starty:  # 路段way_id2 在way_id1 的右上部
                        if abs(startx - curx) <= 5 or abs(starty - cury) <= 5:  # 防止道路过近,出现偏差,方向加500米偏差
                            pass
                        elif curx <= startx and cury <= starty:
                            delsub.append(sub)  # 此路线方向向左下部走  删除此路线
                    if Endx > startx and Endy < starty:  # 路段way_id2 在way_id1 的右下部
                        if abs(startx - curx) <= 5 or abs(starty - cury) <= 5:  # 防止道路过近,出现偏差,方向加500米偏差
                            pass
                        elif curx < startx and cury > starty:
                            delsub.append(sub)  # 此路线方向向左上部走  删除此路线
                    if Endx < startx and Endy < starty:  # 路段way_id2 在way_id1 的左下部
                        if abs(startx - curx) <= 5 or abs(starty - cury) <= 5:  # 防止道路过近,出现偏差,方向加500米偏差
                            pass
                        elif curx > startx and cury > starty:
                            delsub.append(sub)  # 此路线方向向右上部走  删除此路线
                    if Endx < startx and Endy > starty:  # 路段way_id2 在way_id1 的左上部
                        if abs(startx - curx) <= 5 or abs(starty - cury) <= 5:  # 防止道路过近,出现偏差,方向加500米偏差
                            pass
                        elif curx > startx and cury < starty:
                            delsub.append(sub)  # 此路线方向向右上部走  删除此路线
                else:
                    pass

                temstaryendwaydis = twoway_distance(way_id1, sub[-1])
                if temstaryendwaydis > startendwaydis:
                    delsub.append(sub)
            for sub in Common_Functions.Double_layer_list(delsub):
                Candidate_Routes.remove(sub)

        if exitflag==1:
            #证明是循环跳出不是因为找到路径跳出的
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
            return False
        Deleteways = []
        for sub in Candidate_Routes:
            if way_id2 in sub:
                if len(sub) == 1:
                    return sub
                elif len(sub) == 2 and JudgeTwoWay(sub[0], sub[1]):
                    pass
                elif len(sub) >= 3 and JudgeLines(sub):
                    for i in combinations(sub, 2):
                        Common_Functions.SaveRoutesConn("connects", i[0], i[1], 1)
                    pass
                else:
                    Deleteways.append(sub)
            else:
                Deleteways.append(sub)
        if len(Deleteways)!=0:
            for delsub in Common_Functions.Double_layer_list(Deleteways):
                Candidate_Routes.remove(delsub)
        if len(Candidate_Routes)==0:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
            return False
        minnum = float("inf")
        for sub in Candidate_Routes:
            if way_id2 in sub:
                if len(sub) < minnum:
                    finalroute = sub
                    minnum = len(sub)
            else:
                pass
        if len(finalroute)==0:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 0)
            return False

        else:
            Common_Functions.SaveRoutesConn("connects", way_id1, way_id2, 1)
            return finalroute