Beispiel #1
0
def OptimalEvacuation(
        start_pos, realRoute, resultFlag, disaster,
        disasterScale):  #最適な避難場所の探索、及び最適な避難経路の探索、実際に避難した経路と最適な避難場所を同じ画像に出力
    if (resultFlag):
        #そこから取得
        with open("../data/result.json", encoding="utf-8_sig") as f:
            resultJson = json.load(f)
        places = resultJson["EvacuationPlaces"]
        goal_pos = places["0"]["coordinates"]
        optimal_goal = HazapModules.Coordinates()
        optimal_goal.lat, optimal_goal.lon = float(goal_pos[0]), float(
            goal_pos[1])
    else:
        places = getplace.searchplace(start_pos, disaster,
                                      disasterScale)  #最適な避難場所を取得
        resultJson = {}
        resultJson["EvacuationPlaces"] = places
        with open("../data/result.json", "w", encoding="utf-8_sig") as f:
            json.dump(resultJson, f, ensure_ascii=False, indent=4)
        goal_pos = places[0]["coordinates"]
        optimal_goal = HazapModules.Coordinates()
        optimal_goal.lat, optimal_goal.lon = float(goal_pos[0]), float(
            goal_pos[1])
    Routes.Search_route(start_pos, optimal_goal, realRoute,
                        resultFlag)  #最適なルートを作成
    return places  #評価の高かった場所のリストを返す
Beispiel #2
0
def Result(start_pos, realRoute, hp, disaster,
           disasterScale):  #リザルト画面に必要な処理を行う関数。主に、経路作成や生存率の計算など
    if (os.path.exists("../data/result.json")):
        ResultFlag = True
    else:
        ResultFlag = False
    places = OptimalEvacuation(start_pos, realRoute, ResultFlag, disaster,
                               disasterScale)  #経路作成と最適な場所を取得
    optimal_goal = HazapModules.Coordinates()
    if (ResultFlag):
        optimal_goal.lat, optimal_goal.lon = float(
            places["0"]["coordinates"][0]), float(
                places["0"]["coordinates"][1])  #最適な場所の座標
    else:
        optimal_goal.lat, optimal_goal.lon = float(
            places[0]["coordinates"][0]), float(
                places[0]["coordinates"][1])  #最適な場所の座標
    real_goal = HazapModules.Coordinates()
    real_goal.lat, real_goal.lon = list(
        map(float, realRoute[len(realRoute) - 1].split(",")))  #実際の避難場所の座標
    optimalEva = getplace.CarcuEva(optimal_goal, disaster, disasterScale)
    realEva = getplace.CarcuEva(real_goal, disaster, disasterScale)
    rate = ""
    placePercentage = 0
    if (optimalEva < realEva):
        placePercentage = 100
    else:
        placePercentage = (realEva / optimalEva) * 100
    print("Place:" + str(placePercentage))
    rate += str(placePercentage) + ":"
    #rate+=(100/(placePercentage+0.01)*0.4)
    print("HP:" + str(hp))
    rate += str(hp) + ":"
    #rate+=(100/(hp+0.01)*0.2)
    return rate
Beispiel #3
0
def Search_safty(list_places, start, goal):  #安全な場所を探索する関数。
    list_ARV = []  #ARV(最大増振率)を格納
    for i in range(len(list_places)):
        url = "http://www.j-shis.bosai.go.jp/map/api/sstrct/V3/meshinfo.geojson?position={current_pos}&epsg=4301"
        access_url = url.format(current_pos=list_places[i])  #必要なデータを代入
        result = requests.get(access_url)  #データをjsonで取得、連想配列に変換
        result = result.json()
        list_ARV.append(result["features"][0]["properties"]["ARV"])  #ARVを格納
        place = list_places[i].split(",")
        list_places[i] = place[1] + "," + place[0]
    if (len(list_places) == 0):  #例外処理(スタートからゴールまでの距離が近いとき)
        return None
    Sort_places(list_places, list_ARV, 0,
                len(list_places) - 1)  #ARVが小さい順に取得した場所をソート
    min_val = list_ARV[0]
    safty_places = []  #ARVが小さい場所の緯度、経度を格納
    for i in range(len(list_ARV)):
        if (not (min_val == list_ARV[i]
                 or i < len(list_ARV) / 2)):  #最低でも半分の場所を格納
            break
        if (not (list_places[i] in safty_places)):
            safty_places.append(list_places[i])
    safty_places = list(map(lambda data: data.split(","), safty_places))
    safty_places = HazapModules.TwoDimensionsSort(safty_places, 1, 0,
                                                  len(safty_places) - 1)
    if (goal.lat > start.lat):  #ゴール地点のほうがスタート地点よりも上の方にある
        safty_places = Cut_places(safty_places, 1)
    else:
        safty_places = Cut_places(safty_places, -1)
    safty_places = list(
        map(lambda data: ",".join(data), safty_places)
    )  #安全な場所が入ったリストを、経度の小さい順にソートし、ある地点の緯度が前の地点の緯度と比べてゴール地点と逆方向の場所にあるときその地点を削除
    return safty_places
Beispiel #4
0
def sumDisinList(coordinatelist):  #全ての座標の間の距離の総和を返す。投げる座標の区切りは,であること
    sumdis = 0.0
    count = 0
    pos1 = HazapModules.Coordinates()
    pos2 = HazapModules.Coordinates()
    for i in range(len(coordinatelist)):
        count += 1
        if count == 1:
            pos1.lat = float(coordinatelist[str(i)].split(",")[1])
            pos1.lon = float(coordinatelist[str(i)].split(",")[0])
            continue
        pos2.lat = float(coordinatelist[str(i)].split(",")[1])
        pos2.lon = float(coordinatelist[str(i)].split(",")[0])
        sumdis += HazapModules.Calculatedistance(
            pos1, pos2)  #pos1,pos2に値を設定し、距離を測定。総距離に足していく
        pos1.lat = float(coordinatelist[str(i)].split(",")[1])
        pos1.lon = float(coordinatelist[str(i)].split(",")[0])
    return sumdis
Beispiel #5
0
def searchplace(pos, disaster, disasterScale):
    #この関数は座標を投げるとその地点からいい避難場所への道のりにある建物の階数、つまり高さを足していって低い順にソートして返す
    data = get_Coordinates(pos)
    jsondata = {}
    name = {}
    sumstep = []
    for i in range(len(data)):
        sumstep.append(0)

    for i in range(len(data)):
        pos2 = HazapModules.Coordinates()
        pos2.lat = data[i][0]
        pos2.lon = data[i][1]
        jsondata[i] = Reray(pos, pos2, name)
        value = 0
        for k in jsondata[i]:
            #sumstep[i]+=jsondata[i][k][2]
            value += (jsondata[i][k][2] * jsondata[i][k][3])
        #jsondata[i]["step"]=sumstep[i]
        jsondata[i]["coordinates"] = data[i]
        jsondata[i]["Evaluation"] = CarcuEva(pos2, disaster, disasterScale)
        jsondata[i]["value"] = value - jsondata[i]["Evaluation"]
        wes = create_connection("ws://" + HazapModules.addres + ":5000")
        wes.send("long:" + str(pos.lat) + "," + str(pos.lon) + ":" +
                 data[i][0] + "," + data[i][1])
        dist = 0
        while True:
            result = wes.recv()
            ravel = result.split(":")
            if ravel[0] == "value":
                dist = float(ravel[1])
                break
        wes.close()
        jsondata[i]["range"] = dist
        #if dist==0:
        #    jsondata[i]["value"]=0
        #else:
        #    jsondata[i]["value"]=sumstep[i]/dist

    jsondata = HazapModules.TwoDimensionsSort(jsondata, "value", 0,
                                              len(jsondata) - 1)  #stepsort
    return jsondata
Beispiel #6
0
def Coastplaces_get(interval,prefCode):#海岸線取得用の関数
    url="http://nlftp.mlit.go.jp/ksj/api/1.0b/index.php/app/getKSJURL.xml?appId={key}&lang={lang}&dataformat=1&identifier=C23&prefCode={pref}&fiscalyear={year}"
    url=url.format(key="ksjapibeta1",lang="J",pref=prefCode,year="2006")
    result=requests.get(url)
    tree=etree.fromstring(result.content)
    for i in tree.iter():
        if(i.tag=="zipFileUrl"):
            HazapModules.Download_zip(i.text)
    coastDict=Xml_parse(interval,prefCode)
    with open("../data/coastplaces.json","w") as f:
        json.dump(coastDict,f,ensure_ascii=False,indent=4)
Beispiel #7
0
def Fullpos(pos,evacuFlag):#pos:探索したい座標 evacuFlag:Carcuevaで使うかどうか(一番近いところまでの海岸線の距離を取得するため)
    asize=60
    placelist=json.load(open("../data/coastplaces.json",encoding="utf-8_sig"))#全ての座標が入っているリスト
    size=len(placelist)
    pos2=HazapModules.Coordinates()
    pos2.lat=float(placelist[str(0)].split(" ")[0])
    pos2.lon=float(placelist[str(0)].split(" ")[1])
    mindis=HazapModules.Calculatedistance(pos,pos2)
    index=0
    for i in range(1,size):
        pos2.lat=float(placelist[str(i)].split(" ")[0])
        pos2.lon=float(placelist[str(i)].split(" ")[1])
        dis=HazapModules.Calculatedistance(pos,pos2)
        if(mindis>dis):
            mindis=dis
            index=i

    print("Index:",index)
    if(evacuFlag):
        return index 
    returnlist={}#最終的に書き出すjsonのやつ
    count=0
    #searchedlist=[False for i in range(len(placelist))]
    #searchedlist[index]=True
    #sublist={}
    #sublist[str(asize)]=placelist[str(index)]
    #Reclist(placelist,sublist,asize-1,asize,searchedlist)
    #Reclist(placelist,sublist,asize+1,asize,searchedlist)
    #print(json.dumps(sublist,indent=2))
    #for i in range(len(sublist)):
    #    returnlist[str(i)]=sublist[str(i)]
    for i in range(max(index-asize,0),min(index+asize,size)):
        returnlist[str(count)]=placelist[str(i)]
        count+=1
    with open("../data/squeezed.json","w") as f:
        json.dump(returnlist,f,ensure_ascii=False,indent=4)
Beispiel #8
0
def Reclist(placelist,returnlist,nowindex,asize,searchedlist):#一番近いところを全探索して書き込んでいく関数
    print(nowindex,asize)
    if nowindex>asize:
        pos1=HazapModules.Coordinates()
        pos1.lat=float(returnlist[str(nowindex-1)].split(" ")[0])
        pos1.lon=float(returnlist[str(nowindex-1)].split(" ")[1])
        pos2=HazapModules.Coordinates()
        mindis=10000000
        minindex=0
        for i in range(len(placelist)):
            pos2.lat=float(placelist[str(i)].split(" ")[0])
            pos2.lon=float(placelist[str(i)].split(" ")[1])
            distance=HazapModules.Calculatedistance(pos1,pos2)
            if mindis>distance and searchedlist[i]==False and distance>10:
                mindis=distance
                minindex=i
        returnlist[str(nowindex)]=placelist[str(minindex)]
        searchedlist[minindex]=True
        if nowindex==asize*2:
            return 0
        return Reclist(placelist,returnlist,nowindex+1,asize,searchedlist)
    else:
        pos1=HazapModules.Coordinates()
        pos1.lat=float(returnlist[str(nowindex+1)].split(" ")[0])
        pos1.lon=float(returnlist[str(nowindex+1)].split(" ")[1])
        pos2=HazapModules.Coordinates()
        mindis=10000000
        minindex=0
        for i in range(len(placelist)):
            pos2.lat=float(placelist[str(i)].split(" ")[0])
            pos2.lon=float(placelist[str(i)].split(" ")[1])
            distance=HazapModules.Calculatedistance(pos1,pos2)
            if mindis>distance and searchedlist[i]==False and distance>10:
                mindis=distance
                minindex=i
        returnlist[str(nowindex)]=placelist[str(minindex)]
        searchedlist[minindex]=True
        if nowindex==0:
            return 0
        return Reclist(placelist,returnlist,nowindex-1,asize,searchedlist)
Beispiel #9
0
def server():
    contents = None
    startflg = 0
    endflg = 0
    port = 4000
    count = {}
    placesCoorsinates = None
    webbrowser.open_new(os.path.abspath("../HTML/websocket.html"))
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # IPアドレスとポートを指定
        n = 0
        s.bind((HazapModules.addres, 4000))

        Coordinates = {}  #最新の位置情報を格納している辞書
        CoordinateLogs = {}  #最新の座標も含めてそれぞれの人の今までの座標を記録している辞書
        timeLogs = []  #現在地を取得した最終時間を記録するリスト
        distLogs = []  #利用者が進んだ距離を保存するリスト
        disaster = ""  #災害の種類
        disasterScale = ""  #災害の規模
        ipList = []
        # 1 接続
        s.listen(1)
        # connection するまで待つ
        startPos = HazapModules.Coordinates()
        message = ""
        while True:
            send = "Invalid"
            # 誰かがアクセスしてきたら、コネクションとアドレスを入れる
            conn, addr = s.accept()
            print("connected from:", addr)
            with conn:
                while True:
                    # データを受け取る
                    data = conn.recv(1024)
                    #send="Invalid"
                    if not data:
                        break

                    rec = data.decode()
                    splited = rec.split(":")
                    print(splited[0])
                    if (splited[0] == "Recruit"
                            and startflg == 0):  #サーバに参加を伝える
                        if (not (addr[0] in ipList)):
                            send = str(n)
                            CoordinateLogs[n] = []
                            pl = splited[1].split(",")
                            CoordinateLogs[n].append(pl)
                            Coordinates[n] = splited[1].split(",")
                            send = "number:" + str(n)
                            n += 1
                            print(addr[0])
                            ipList.append(addr[0])
                            print(splited)
                        conn.sendall(send.encode())
                    elif splited[
                            0] == "Recruit" and startflg == 1:  #すでにスタートしていた場合、参加を拒否する

                        send = "started"
                        conn.sendall(send.encode())
                    elif splited[0] == "Cancel":  #参加者を除外する
                        if len(splited) > 1:
                            if (int(splited[1]) in CoordinateLogs):
                                #CoordinateLogs.pop(int(splited[1]))  #IDが変わる可能性があるかも
                                CoordinateLogs[splited[1]] = None  #とりあえずログを消す
                                send = "Canceled"
                                conn.sendall(send.encode())
                                n -= 1
                                if (n == 0):
                                    os.remove("../data/result.json")  #ログなどの初期化
                                    timeLogs = []
                                    distLogs = []
                                    CoordinateLogs = {}
                                    Coordinates = {}
                                    startflg = 0
                    elif splited[0] == "Start":  #シミュレーションをスタートする
                        message = ""
                        startflg = 1
                        ipList = []
                        disaster = splited[2]
                        disasterScale = splited[3]
                        if (disaster == "津波"):
                            disasterScale += (":" + splited[4])
                        print("serverstart")
                        #(主催者からStartが送られれば開始場所からのシミュレーションを開始
                        startPos.lat, startPos.lon = map(
                            float, splited[1].split(","))
                        placesCoorsinates = getplace.get_Coordinates(startPos)
                        if (disaster == "地震"):
                            Earthquake.get_Dangerplaces(startPos)
                        elif (disaster == "津波"):
                            prefurl = "https://map.yahooapis.jp/geoapi/V1/reverseGeoCoder?{detail}&lat={lat}&lon={lon}"
                            prefurl = prefurl.format(
                                detail=HazapModules.APIPubWord,
                                lat=startPos.lat,
                                lon=startPos.lon)
                            prefResult = requests.get(prefurl)
                            prefResult = prefResult.json()
                            Coastplace.Coastplaces_get(
                                100, prefResult["Feature"][0]["Property"]
                                ["AddressElement"][0]["Code"])
                            Coastplace.Fullpos(startPos, False)
                            #別スレッドで津波のシミュレーションを開始
                            #json.load(open("../data/squeezed.json",encoding="utf_8_sig"))
                            #thread = threading.Thread(target=simulate.simulatetunami, args=([json.load(open("../data/squeezed.json",encoding="utf_8_sig")),100,100]))
                            #thread.start()
                            simulate.simulatetunami(
                                json.load(
                                    open("../data/squeezed.json",
                                         encoding="utf_8_sig")),
                                float(splited[3]), float(splited[4]))
                        conn.sendall("DisasterStart:".encode())
                        timeLogs = [0] * n  #0で初期化
                        distLogs = [0] * n
                    elif splited[0] == "Allpeople":  #全参加者が何人か伝える
                        conn.sendall(("Allpeople:" + str(n)).encode())
                    elif splited[0] == "Message":  #主催者からのメッセージが送られる
                        message = splited[1]
                        conn.sendall("OK".encode())
                    elif splited[
                            0] == "Number" and startflg == 1:  #シミュレーションが開始されていれば参加人数と周囲にいる人数を送る
                        distflag = False
                        pos1 = HazapModules.Coordinates()
                        pos1.lat = float(splited[2].split(",")[0])
                        pos1.lon = float(splited[2].split(",")[1])
                        for i in placesCoorsinates:
                            pos2 = HazapModules.Coordinates()
                            pos2.lat = float(i[0])
                            pos2.lon = float(i[1])
                            dist = HazapModules.Calculatedistance(pos1, pos2)
                            if dist < 107:
                                distflag = True
                                break
                        if int(splited[1]) in CoordinateLogs:
                            Coordinates[int(
                                splited[1])] = splited[2].split(",")
                            CoordinateLogs[int(splited[1])].append(
                                splited[2].split(","))
                            if (distflag == True):
                                send = "Around:0,N:" + str(n)
                            else:
                                send = "Around:" + str(count[int(
                                    splited[1])]) + ",N:" + str(n)
                            nowTime = time.time()
                            runFlg = 0
                            currentPos = HazapModules.Coordinates()
                            currentPos.lat = float(splited[2].split(",")[0])
                            currentPos.lon = float(splited[2].split(",")[1])
                            beforePos = HazapModules.Coordinates()
                            beforePos.lat = float(
                                CoordinateLogs[int(splited[1])]
                                [len(CoordinateLogs[int(splited[1])]) - 2][0])
                            beforePos.lon = float(
                                CoordinateLogs[int(splited[1])]
                                [len(CoordinateLogs[int(splited[1])]) - 2][1])
                            dist = HazapModules.Calculatedistance(
                                beforePos, currentPos)
                            distLogs[int(splited[1])] += dist
                            if (timeLogs[int(splited[1])] !=
                                    0):  #走っているかどうかの判定をする
                                if ((dist /
                                     (nowTime - timeLogs[int(splited[1])])) >=
                                    (6.4 * 1000 /
                                     3600)):  #時速6.4kmよりも早ければ走ったと判定
                                    runFlg = 1
                            timeLogs[int(splited[1])] = nowTime
                            send += ":" + str(runFlg)
                            print(timeLogs)
                        conn.sendall(send.encode())
                    elif (splited[0] == "Number" or splited[0]
                          == "Wait") and startflg == 0:  #シミュレーションが開始されていない場合
                        send = "Waiting..."
                        conn.sendall(send.encode())
                    elif splited[
                            0] == "Wait" and startflg == 1:  #シミュレーションが開始されていた場合、災害ごとに必要な情報を送る
                        send = "Start:"
                        if (disaster == "地震"):
                            with open("../data/dangerplaces.json",
                                      encoding="utf_8_sig") as f:
                                jsonData = json.load(f)
                                sendData = json.dumps(
                                    jsonData, ensure_ascii=False).encode()
                        elif (disaster == "津波"):
                            with open("../data/simulated.json",
                                      encoding="utf_8_sig") as f:
                                jsonData = json.load(f)
                                sendData = json.dumps(
                                    jsonData, ensure_ascii=False).encode()
                        length = len(sendData)
                        sendSize = 32768
                        left = 0
                        right = sendSize
                        conn.sendall(("Start:" + str(length) + ":" + disaster +
                                      ":" + disasterScale).encode("utf-8")
                                     )  #プレイヤーにjsonファイルのデータの長さ、災害の種類、規模の大きさを送る
                        time.sleep(1)
                        print("sending data...")
                        while True:
                            time.sleep(0.5)
                            if (left > length):
                                break
                            conn.sendall(sendData[left:right])
                            left += sendSize
                            right += sendSize
                    elif splited[0] == "End" and message != "":
                        endflg = 1
                        startpoint = HazapModules.Coordinates()
                        startpoint.lat = float(CoordinateLogs[int(
                            splited[1])][0][0])
                        startpoint.lon = float(CoordinateLogs[int(
                            splited[1])][0][1])
                        endpoint = HazapModules.Coordinates()
                        endpoint.lat = float(CoordinateLogs[int(
                            splited[1])][len(CoordinateLogs[int(splited[1])]) -
                                         1][0])
                        endpoint.lon = float(CoordinateLogs[int(
                            splited[1])][len(CoordinateLogs[int(splited[1])]) -
                                         1][1])
                        rate = main.Result(
                            startPos,
                            list(
                                map(lambda data: ",".join(data),
                                    CoordinateLogs[int(splited[1])])),
                            int(splited[2]), disaster, disasterScale)
                        places = json.load(
                            open("../data/result.json", encoding="utf-8_sig"))
                        #ルートの長さを格納している変数
                        optimaldist = 0
                        #最適な避難場所までの目安時間
                        optimaltime = 0
                        if places["SaftyPlaces"] == None:
                            optimaldist = places["EvacuationPlaces"]["0"][
                                "range"]
                            optimaltime = optimaldist / (5000 / 3600)
                        else:
                            wes = create_connection("ws://" +
                                                    HazapModules.addres +
                                                    ":5000")
                            sendstr = "long:" + str(
                                startpoint.lat) + "," + str(startpoint.lon)

                            for i in range(len(places["SaftyPlaces"])):
                                sendstr += ":" + places["SaftyPlaces"][str(
                                    i)].split(",")[0] + "," + places[
                                        "SaftyPlaces"][str(i)].split(",")[1]
                            sendstr += places["EvacuationPlaces"]["0"][
                                "coordinates"][0] + "," + places[
                                    "EvacuationPlaces"]["0"]["coordinates"][1]
                            wes.send(sendstr)
                            while True:
                                result = wes.recv()
                                ravel = result.split(":")
                                if ravel[0] == "value":
                                    print(ravel[1])
                                    optimaldist = float(ravel[1])
                                    optimaltime = float(ravel[2])
                                    break
                            wes.close()

                        tmpimg = Image.open("../img/route.png").convert("P")
                        with io.BytesIO() as output:
                            tmpimg.save(output, format="PNG")
                            contents = output.getvalue()  #バイナリ取得
                        length = len(contents)
                        sendsize = 4096
                        left = 0
                        right = sendsize

                        time.sleep(0.5)

                        if (optimaldist >= distLogs[int(splited[1])]):
                            #rate+=(100/100*0.2)
                            rate += str(100) + ":"
                            print("Dist:", 1)
                        elif (optimaldist == 0):
                            if (distLogs[int(splited[1])] > 100):
                                distLogs[int(splited[1])] = 100
                            print("Dist:",
                                  (100 - distLogs[int(splited[1])] * 100))
                            rate += str(100 - distLogs[int(splited[1])]) + ":"
                            #rate+=(100/(100-distLogs[int(splited[1])]+0.01)*0.2)
                        else:
                            print("Dist:", (optimaldist /
                                            (distLogs[int(splited[1])]) * 100))
                            rate += str(
                                optimaldist /
                                (distLogs[int(splited[1])]) * 100) + ":"
                            #rate+=(1/(optimaldist/(distLogs[int(splited[1])]+0.01))*0.2)
                        optimaltime *= 60.0
                        resultTime = float(splited[3])
                        if (optimaltime == 0 and optimaldist != 0):
                            optimaltime = optimaldist / (5000 / 3600)
                        if (optimaltime >= resultTime):
                            print("Time:", 100)
                            rate += str(100)
                            #rate+=(100/100*0.2)
                        elif (optimaltime == 0):
                            if (resultTime > 100):
                                resultTime = 100
                            print("Time:", 100 - resultTime)
                            rate += str(100 - resultTime)
                            #rate+=(100/(100-resultTime+0.01)*0.2)
                        else:
                            print("Time:", optimaltime / (resultTime) * 100)
                            rate += str(optimal / (resultTime) * 100)
                            #rate+=(1/(optimaltime/(resultTime+0.01))*0.2)

                        #rate=int(1/rate*100)
                        params = rate.split(":")
                        evacuValue = int(
                            100 /
                            (100 / (float(params[0]) + 0.01) * 0.4 + 100 /
                             (float(params[1]) + 0.01) * 0.2 + 100 /
                             (float(params[2]) + 0.01) * 0.2 + 100 /
                             (float(params[3]) + 0.01) * 0.2))
                        print("Eva:", evacuValue)
                        conn.sendall(
                            ("Result:" + str(evacuValue) + ":" + str(length) +
                             ":" + message + ":" +
                             rate).encode())  #Result:Aliverate:byteLength

                        while True:
                            time.sleep(1)
                            if left > length:
                                break
                            conn.sendall(contents[left:right])
                            left += sendsize
                            right += sendsize

                        print("ImageSended")
                    elif splited[
                            0] == "End" and message == "":  #主催者からのメッセージがまだ送られていなければ待たせる
                        conn.sendall("Waiting...".encode())
                    elif splited[0] == "Coordinates":  #全参加者の現在地を送る
                        allplayer = "Coordinates"
                        for i in range(n):
                            allplayer += ":"
                            allplayer += (
                                CoordinateLogs[i][len(CoordinateLogs[i]) -
                                                  1][0] + "," +
                                CoordinateLogs[i][len(CoordinateLogs[i]) -
                                                  1][1])
                        conn.sendall(allplayer.encode())
                    elif splited[0] == "Image":
                        conn.sendall(contents)
                        continue
                    if (startflg == 1):
                        count = getplace.Calcudens(Coordinates)
                    #conn.sendall(send.encode())
                    print(CoordinateLogs)
Beispiel #10
0
def get_Dangerplaces(centerPos):  #地震の揺れやすさを表す指標(ARV値)を取得
    if (os.path.exists("../data/" + str(int(centerPos.lat * 10**3)) +
                       str(int(centerPos.lon * 10**3)) + ".json")):
        with open("../data/" + str(int(centerPos.lat * 10**3)) +
                  str(int(centerPos.lon * 10**3)) + ".json",
                  encoding="utf_8_sig") as f:
            dangerPlaces = json.load(f, encoding="utf_8_sig")
    else:
        places_url = "https://map.yahooapis.jp/search/local/V1/localSearch?{detail}&lat={lat}&lon={lon}&sort=-dist&results=100&dist=1&distinct=false"
        places_url = places_url.format(detail=HazapModules.APIPubWord,
                                       lat=centerPos.lat,
                                       lon=centerPos.lon)
        places = requests.get(places_url)
        places = places.json()
        count = places["ResultInfo"]["Count"]
        subcount = places["ResultInfo"]["Count"]
        minplace = HazapModules.Coordinates()
        minplace.lat = float(
            places["Feature"][99]["Geometry"]["Coordinates"].split(",")[1])
        minplace.lon = float(
            places["Feature"][99]["Geometry"]["Coordinates"].split(",")[0])
        debugcount = 0
        while True:
            if subcount > 0:
                distance = HazapModules.Calculatedistance(centerPos, minplace)
                print(distance, subcount)
                subplaces_url = "https://map.yahooapis.jp/search/local/V1/localSearch?{detail}&lat={lat}&lon={lon}&sort=-dist&results=100&dist=" + str(
                    distance / 1000) + "&distinct=false"
                subplaces_url = subplaces_url.format(
                    detail=HazapModules.APIPubWord,
                    lat=centerPos.lat,
                    lon=centerPos.lon)
                subplaces = requests.get(subplaces_url)
                subplaces = subplaces.json()
                count += subplaces["ResultInfo"]["Count"]
                subcount = subplaces["ResultInfo"]["Count"]
                for i in range(subplaces["ResultInfo"]["Count"]):
                    places["Feature"].append(subplaces["Feature"][i])
                minplace.lat = float(
                    subplaces["Feature"][subplaces["ResultInfo"]["Count"] - 1]
                    ["Geometry"]["Coordinates"].split(",")[1])
                minplace.lon = float(
                    subplaces["Feature"][subplaces["ResultInfo"]["Count"] - 1]
                    ["Geometry"]["Coordinates"].split(",")[0])
                if subcount < 100:
                    break
            else:
                break

        print("success")
        before_place = ""
        dangerPlaces = {}
        dangerPlaces["MinARV"] = {}
        idx = 0
        minARV = [10**5] * 3  #ARV値を格納するリスト
        for i in range(count):
            if (before_place == places["Feature"][i]["Geometry"]["Coordinates"]
                ):
                continue
            dangerPlaces[idx] = {}
            if (places["Feature"][i]["Property"]["Genre"] == []):
                dangerPlaces[idx]["Code"] = "Null"
            else:
                dangerPlaces[idx]["Code"] = places["Feature"][i]["Property"][
                    "Genre"][0]["Code"]
            arv_url = "http://www.j-shis.bosai.go.jp/map/api/sstrct/V3/meshinfo.geojson?position={pos}&epsg=4301"
            arv_url = arv_url.format(
                pos=places["Feature"][i]["Geometry"]["Coordinates"])
            list_ARV = requests.get(arv_url)
            list_ARV = list_ARV.json()

            placesHeight_url = "https://map.yahooapis.jp/geoapi/V1/reverseGeoCoder?{detail}&lat={lat}&lon={lon}"
            lon, lat = places["Feature"][i]["Geometry"]["Coordinates"].split(
                ",")
            placesHeight_url = placesHeight_url.format(
                lat=lat, lon=lon, detail=HazapModules.APIPubWord)
            placesHeight = requests.get(placesHeight_url)
            placesHeight = placesHeight.json()
            before_place = places["Feature"][i]["Geometry"]["Coordinates"]
            dangerPlaces[idx]["Coordinates"] = before_place
            if (len(placesHeight["Feature"][0]["Property"]) != 4):
                dangerPlaces[idx]["Step"] = "0"
            else:
                dangerPlaces[idx]["Step"] = placesHeight["Feature"][0][
                    "Property"]["Building"][0]["Floor"]
            dangerPlaces[idx]["ARV"] = list_ARV["features"][0]["properties"][
                "ARV"]
            if (not (float(dangerPlaces[idx]["ARV"]) in minARV)
                    and minARV[2] > float(dangerPlaces[idx]["ARV"])):
                minARV[2] = float(dangerPlaces[idx]["ARV"])
                minARV.sort()
            idx += 1
        dangerPlaces["MinARV"] = ",".join(map(str, minARV))
        with open(
                "../data/" + str(int(centerPos.lat * 10**3)) +
                str(int(centerPos.lon * 10**3)) + ".json", "w") as f:
            json.dump(dangerPlaces, f, ensure_ascii=False, indent=4)
    with open("../data/dangerplaces.json", "w") as f:
        json.dump(dangerPlaces, f, ensure_ascii=False, indent=4)
Beispiel #11
0
import HazapModules
pos1 = HazapModules.Coordinates()
pos1.lat = 31.760254
pos1.lon = 131.080396
pos2 = HazapModules.Coordinates()
pos2.lat = 31.770254
pos2.lon = 131.080396
x = HazapModules.Calculatedistance(pos1, pos2)
print(x)
Beispiel #12
0
def CarcuEva(Coordinates, disaster, disasterScale):
    #座標を投げたらその座標の建物の種類の評価値を返します
    url1 = "https://map.yahooapis.jp/geoapi/V1/reverseGeoCoder?" + HazapModules.APIPubWord + "&lat=" + str(
        Coordinates.lat) + "&lon=" + str(Coordinates.lon)
    res1 = urllib.request.urlopen(url1)
    data1 = json.loads(res1.read().decode())

    hoge = data1["Feature"][0]["Geometry"]["Coordinates"].split(',')
    url = "https://map.yahooapis.jp/search/local/V1/localSearch?" + HazapModules.APIPubWord + "&lat=" + hoge[
        1] + "&lon=" + hoge[
            0] + "&dist=1&gc=0425,0406,0305007,0412021&sort=dist&al=4&ar=ge"

    res = urllib.request.urlopen(url)
    data = json.loads(res.read().decode())
    targetPlace = data["Feature"][0]["Geometry"]["Coordinates"].split(",")
    addressurl = "https://map.yahooapis.jp/geocode/V1/geoCoder?{detail}&lat={lat}&lon={lon}&sort=dist&al=4&ar=ge"
    address1url = addressurl.format(detail=HazapModules.APIPubWord,
                                    lat=targetPlace[1],
                                    lon=targetPlace[0])
    address1Result = requests.get(address1url)
    address1Result = address1Result.json()  #Feature->0->Name
    address2url = addressurl.format(detail=HazapModules.APIPubWord,
                                    lat=Coordinates.lat,
                                    lon=Coordinates.lon)
    address2Result = requests.get(address2url)
    address2Result = address2Result.json()
    if (data["ResultInfo"]["Count"] == 0
            or address1Result["Feature"][0]["Property"]["Address"] !=
            address2Result["Feature"][0]["Property"]["Address"]
        ):  #建物の座標が一切取れなかった、ゴール地点の建物が取得されなかった場合
        return 0
    #Telを比較していき、同じであればそちらでも評価値を取得して、高かった方を正しい評価値とする
    value = 0
    st = ""
    for i in range(data["ResultInfo"]["Count"]):
        print("TEL:", data["Feature"][i]["Property"]["Tel1"])
        if (st != "" and data["Feature"][i]["Property"]["Tel1"] !=
                data["Feature"][i - 1]["Property"]["Tel1"]):
            break
        st = data["Feature"][i]["Property"]["Genre"][0]["Name"]
        if st.find("避難") != -1:
            if (value < 100):
                value = 100
        elif st.find("学校") != -1:
            if (value < 100):
                value = 100
        elif st.find("公園") != -1:
            if (value < 75):
                value = 75
        elif st.find("ガソリンスタンド") != -1:
            if (value < 75):
                value = 75
    #建物の高さを取得し、評価値を変更
    placeJson = json.load(
        open("../data/dangerplaces.json", encoding="utf_8_sig"))
    placeHeight = 0
    sumStep = 0
    for i in range(len(placeJson) - 1):
        sumStep += int(placeJson[str(i)]["Step"])
        if (placeHeight == 0 and math.isclose(
                round(float(Coordinates.lat), 3),
                round(float(placeJson[str(i)]["Coordinates"].split(",")[1]),
                      3),
                rel_tol=0.001,
                abs_tol=0.001) and math.isclose(
                    round(float(Coordinates.lon), 3),
                    round(
                        float(placeJson[str(i)]["Coordinates"].split(",")[0]),
                        3),
                    rel_tol=0.001,
                    abs_tol=0.001)):
            placeHeight = int(placeJson[str(i)]["Step"])
    #また、地震の場合はARV地、津波の場合は、標高と海岸線までの距離を取得し、評価値変更
    if (disaster == "地震"):
        arvurl = "http://www.j-shis.bosai.go.jp/map/api/sstrct/V3/meshinfo.geojson?position={current_pos}&epsg=4301"
        accessurl = arvurl.format(current_pos=str(Coordinates.lon) + "," +
                                  str(Coordinates.lat))
        resultARV = requests.get(accessurl)
        resultARV = resultARV.json()
        dangerJson = None
        arv = float(resultARV["features"][0]["properties"]["ARV"])
        with open("../data/dangerplaces.json", encoding="utf_8_sig") as f:
            dangerJson = json.load(f)
        minARV = float(dangerJson["MinARV"].split(",")[0])
        value *= (minARV / arv)
        if (sumStep / (len(placeJson) - 1) < placeHeight):
            print("Height:", placeHeight)
            value *= ((sumStep) / (len(placeJson) - 1)) / placeHeight
    elif (disaster == "津波"):
        #海抜(標高)を取得
        coastIdx = Coastplace.Fullpos(Coordinates, True)
        coastJson = json.load(
            open("../data/coastplaces.json", encoding="utf_8_sig"))
        coastPos = HazapModules.Coordinates()
        coastPos.lat, coastPos.lon = float(
            coastJson[str(coastIdx)].split(" ")[0]), float(
                coastJson[str(coastIdx)].split(" ")[1])
        altitudeurl = "https://map.yahooapis.jp/alt/V1/getAltitude?{detail}&coordinates={pos1},{pos2}"
        altitudeurl = altitudeurl.format(
            detail=HazapModules.APIPubWord,
            pos1=str(Coordinates.lon) + "," + str(Coordinates.lat),
            pos2=str(coastPos.lon) + "," + str(coastPos.lat))
        resultAltitude = requests.get(altitudeurl)
        resultAltitude = resultAltitude.json()
        altitude = resultAltitude["Feature"][0]["Property"]["Altitude"]
        coastAltitude = resultAltitude["Feature"][1]["Property"]["Altitude"]
        coastS = (coastAltitude + float(disasterScale.split(":")[0])) * float(
            disasterScale.split(":")[1])
        hc = coastS / HazapModules.Calculatedistance(Coordinates, coastPos)
        hc -= altitude
        if (hc > placeHeight * 5):
            value *= (placeHeight * 5) / hc
    return value