Ejemplo n.º 1
0
def hop_calc(device: Device, mecs: MEC_servers, mec: MEC_server,
             previous_mec_name, time):
    # ホップ数計算
    # 最初の割り当て
    if device._first_flag == True:
        device._hop = [1]
        device._first_flag = False
    #elif mec.name == device.mec_name:
    #keep_hop(device)
    # 切替成功
    else:
        mec.add_reboot_count(time)
        # 集約局が同一の時
        if mec_compare(device, mec) == False:
            device._three_count = device._three_count + 1
            # ---
            previous_mec = search_mec(mecs, previous_mec_name)
            distance = distance_calc(mec.lat, mec.lon, previous_mec.lat,
                                     previous_mec.lon)
            # 割り当て距離を追加
            if device._distance is None:
                device._distance = [distance]
            else:
                device._distance.append(distance)
            # 最小割り当て距離
            if device._min_distance > distance and distance != 0:
                device._min_distance = distance
            # 最大割り当て距離
            if device._max_distance < distance:
                device._max_distance = distance
        # 集約曲が違う時
        else:
            device._hop.append(5)
            previous_mec = search_mec(mecs, device.mec_name)
            # ---
            distance = distance_calc(mec.lat, mec.lon, previous_mec.lat,
                                     previous_mec.lon)
            # 割り当て距離を追加
            if device._distance is None:
                device._distance = [distance]
            else:
                device._distance.append(distance)
            # 最小割り当て距離
            if device._min_distance > distance and distance != 0:
                device._min_distance = distance
            # 最大割り当て距離
            if device._max_distance < distance:
                device._max_distance = distance
Ejemplo n.º 2
0
def traffic_congestion_calc(mecs:MEC_servers, mec:MEC_server, devices: Devices, time , search_distance):
    """
    あるMECのカバー範囲内の要求リソース量の総和を求める計算(混雑度)
    :param mec: あるMECサーバ
    :param device: デバイス群
    :param time: システムのある時間t
    :param search_distance: 加算距離
    :return ある時刻tのときのMECのカバー範囲内の要求リソース量の総和
    """
    cnt = 0
    device_num = len(devices)
    sum = 0
    # デバイスのインデックスを保存するための変数
    save = [None]
    for i in range(device_num):
        startup = devices[i].startup_time
        shutdown = devices[i].shutdown_time
        if startup <= time and shutdown >= time:
            # デバイスのplanのindex番号を計算
            index = int(time) - int(startup)
            if index < (shutdown - startup):
                # デバイスとMECとの距離を計算
                distance = distance_calc(float(devices[i].plan[index].y), float(devices[i].plan[index].x), mec.lat,
                                         mec.lon)
                # 探索距離内あるか判定
                # もしあれば追加
                if distance <= (search_distance):
                    if save[0] is None:
                        save[0] = i
                    else:
                        save.append(i)
                    cnt = cnt + 1
                    sum = sum + devices[i].use_resource
    #print(save)
    mec._congestion_status[time] = sum
    if save[0] != None:
        for save_index in save:
            # 混雑度が多ければ、値を更新する
            if devices[save_index]._congestion_status[time] == 0:
                devices[save_index]._congestion_status[time] = sum
                # 先に計算したMECと比較するために保存
                devices[save_index].mec_name = mec.name
            elif devices[save_index]._congestion_status[time] < sum:
                devices[save_index]._congestion_status[time] = sum
                devices[save_index].mec_name = mec.name
            else:
            # 値が被る時
                startup = devices[save_index].startup_time
                index = int(time) - int(startup)
                if index < (shutdown - startup):
                    previous_mec = search_mec(mecs, devices[save_index].mec_name)
                    previous_distance = distance_calc(float(devices[save_index].plan[index].y),
                                                      float(devices[save_index].plan[index].x),
                                                      previous_mec.lat, previous_mec.lon)
                    current_distance = distance_calc(float(devices[save_index].plan[index].y),
                                                      float(devices[save_index].plan[index].x), mec.lat, mec.lon)
                    if current_distance < previous_distance:
                        devices[save_index]._congestion_status[time] = sum
                        devices[save_index].mec_name = mec.name
    return mec, devices
Ejemplo n.º 3
0
import random
import numpy as np

system_end_time = 100
df = pd.read_csv(
    "/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/base_station/kddi_okayama_city.csv",
    dtype={
        'lon': 'float',
        'lat': 'float'
    })
server_type = "LTE"
MEC_resource = 100
cover_range = 200
n = len(df)
print("Number of MEC server:", n)
mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n
device_flag = False
f = open(
    '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/sumo/device.binaryfile',
    'rb')
data_length = len(df)
print("MECs", data_length)
for index, series in df.iterrows():
    mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                            series["lon"], series["lat"], cover_range,
                            system_end_time)
f = open(
    '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.binaryfile',
    'rb')
devices = pickle.load(f)
num = len(devices)  # デバイスの総数
Ejemplo n.º 4
0
def traffic_congestion_calc(mecs: MEC_servers, mec: MEC_server,
                            devices: Devices, time, search_distance):
    """
    あるMECのカバー範囲内の要求リソース量の総和を求める計算(混雑度)
    :param mec: あるMECサーバ
    :param device: デバイス群
    :param time: システムのある時間t
    :param search_distance: 加算距離
    :return ある時刻tのときのMECのカバー範囲内の要求リソース量の総和
    """

    cnt = 0
    device_num = len(devices)
    sum = 0  #デバイスの要求リソース量の総和を保存しておく変数
    save = [None]  #デバイスのインデックスを保存するための変数

    #時刻tにおけるあるMECサーバに要求されるリソース量の総和sumを求める
    for i in range(device_num):
        startup = devices[i].startup_time
        shutdown = devices[i].shutdown_time
        if startup <= time and shutdown >= time:
            # デバイスのplanのindex番号を計算
            index = int(time) - int(startup)
            if index < (shutdown - startup):
                # デバイスとMECとの距離を計算(引数で渡されたmec[m]の座標を利用):edge_server.py内のメソッド
                distance = distance_calc(float(devices[i].plan[index].y),
                                         float(devices[i].plan[index].x),
                                         mec.lat, mec.lon)

                # 探索距離内あるか判定(デバイスとMECの2点間距離<=MECの加算距離)
                # もしあれば追加、なければfor文を抜けて次のデバイスへ
                if distance <= (search_distance):
                    if save[0] is None:
                        save[0] = i  #デバイスのインデックスをsave[0]に保存
                    else:
                        save.append(i)  #デバイスの2つ目以降もsave[1~device_num-1]に追加していく

                    cnt = cnt + 1  #デバイスのインデックスを保存
                    sum = sum + devices[i].use_resource  #デバイスの要求リソース量をsumに追加する
    #print(save)

    mec._congestion_status[time] = sum  #時刻tにおけるあるMECサーバに要求されるリソース量の総和

    if save[0] != None:
        for save_index in save:
            # 混雑度が多ければ、値を更新する

            #要求リソースのあるデバイスの混雑度が初期化後の0のままなら
            if devices[save_index]._congestion_status[
                    time] == 0:  #congestion_status = [0] * system_time
                devices[save_index]._congestion_status[
                    time] = sum  #MECの要求リソース量を保存

                # 先に計算したMECと比較するために保存
                devices[save_index].mec_name = mec.name

            elif devices[save_index]._congestion_status[
                    time] < sum:  #先に計算したMECの要求リソース量より今回計算したMECの要求リソース量が多い場合
                devices[save_index]._congestion_status[
                    time] = sum  #MECの要求リソース量の総和が大きい方に値を更新
                devices[save_index].mec_name = mec.name
            else:

                # 値が被る時 or 小さい時?
                startup = devices[save_index].startup_time
                index = int(time) - int(startup)
                if index < (shutdown - startup):
                    previous_mec = search_mec(mecs,
                                              devices[save_index].mec_name)
                    previous_distance = distance_calc(
                        float(devices[save_index].plan[index].y),
                        float(devices[save_index].plan[index].x),
                        previous_mec.lat, previous_mec.lon)
                    current_distance = distance_calc(
                        float(devices[save_index].plan[index].y),
                        float(devices[save_index].plan[index].x), mec.lat,
                        mec.lon)
                    if current_distance < previous_distance:
                        devices[save_index]._congestion_status[time] = sum
                        devices[save_index].mec_name = mec.name

    return mec, devices
Ejemplo n.º 5
0
def continue_nearest_simulation(system_end_time, MEC_resource, device_num,
                                continue_distance, device_allocation_method,
                                path_w):
    df = pd.read_csv(
        "/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/base_station/kddi_okayama_city2.csv",
        dtype={
            'lon': 'float',
            'lat': 'float'
        })
    server_type = "LTE"
    cover_range = 500
    n = len(df)
    print("Number of MEC server:", n)
    mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n
    for index, series in df.iterrows():
        mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                                series["lon"], series["lat"], cover_range,
                                system_end_time)
    mec_num = len(df)

    # 集約局を対応するMECに設定する
    set_aggregation_station(mec)

    # 到着順
    if device_allocation_method == 0:
        d = open(
            '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.clone_binaryfile',
            'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
            devices[i]._allocation_plan = [None] * system_end_time
        # 順序をシャッフル
        random.shuffle(devices)
        sorted_devices = [devices] * system_end_time
        for t in range(system_end_time):
            random.shuffle(devices)
            sorted_devices[t] = devices
    # リソース順
    elif device_allocation_method == 1:
        d = open(
            '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.congestion_binaryfile',
            'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        devices = reverse_resource_sort(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
        sorted_devices = [devices] * system_end_time
    # 混雑度順
    else:
        # 混雑度計算
        # traffic_congestion(mec, devices, system_end_time, 1000)
        cd = open(
            '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/congestion_checked_devices.binaryfile',
            'rb')
        cd = pickle.load(cd)
        devices = cd
        num = len(devices)
        print("device_num", num)

        # 混雑度順で毎秒ごとのdevicesをソートする
        sorted_devices = devices_congestion_sort(devices, system_end_time)

    keep_count = 0
    # save_devices = [] * data_length
    # ---
    # ここからメインの処理
    for t in range(system_end_time):
        print("[TIME:", t, "]")
        # ある時刻tのMECに割り当てらえたデバイスを一時的に保存する用の変数
        save_devices = [None] * mec_num
        for i in range(num):
            print("---new device---", sorted_devices[t][i].name)
            # plan_indexがデバイスの稼働時間外なら処理をスキップ
            if (check_plan_index(sorted_devices[t][i].plan_index,
                                 len(sorted_devices[t][i].plan)) == False):
                print("skip")
                continue
            # plan_indexが稼働時間内なら処理開始
            if check_between_time(sorted_devices[t][i], t) == True:
                print("plan_index", sorted_devices[t][i].plan_index,
                      "max_index", len(sorted_devices[t][i].plan))
                # 継続割り当て
                device_flag, allocation_MEC_name = continue_search(
                    sorted_devices[t][i], mec, sorted_devices[t][i].plan_index,
                    cover_range, t, continue_distance)
                if device_flag == True:
                    # 継続回数
                    keep_count = keep_count + 1
                    # 最近傍選択
                if device_flag == False:
                    device_flag, allocation_MEC_name = nearest_search2(
                        sorted_devices[t][i], mec,
                        sorted_devices[t][i].plan_index, cover_range, t)
                # 割り当てが成功したら表示する
                if device_flag == True:
                    # deviceが直前で割り当てたMECを取得
                    mec_index = search_mec_index(mec, allocation_MEC_name)

                    # print("device:", sorted_devices[t][i].name, ", use_resource:", sorted_devices[t][i].use_resource, "--->", "MEC_ID:", mec[mec_index].name, ", index:", i)
                    # print(sorted_devices[t][i].mec_name, mec[mec_index].resource)
                    # print(mec_index, len(save_devices))
                    # ---
                    # なぜindexがmec_indexなの? <- mec用のリストだから
                    if save_devices[mec_index] == None:
                        save_devices[mec_index] = [sorted_devices[t][i].name]
                    else:
                        save_devices[mec_index].append(
                            sorted_devices[t][i].name)

                    mec_index = 0
                else:
                    print("NOT FIND")
                # plan_indexをインクリメント
                sorted_devices[t][
                    i]._plan_index = sorted_devices[t][i]._plan_index + 1
            # デバイスの稼働時間を超えた時の処理
            else:
                # もしデバイスの終了時間を超えた時のみ(1回だけ)、デバイスに直前に割り当てたMECのリソースをリカバリーする。
                if sorted_devices[t][i].mec_name != [] and sorted_devices[t][
                        i]._lost_flag == False:
                    print("DECREASE")
                    sorted_devices[t][i].set_mode = "decrease"
                    print(sorted_devices[t][i].mec_name)
                    mec[sorted_devices[t][i].mec_name -
                        1].custom_resource_adjustment(sorted_devices[t][i], t)
                    mec[sorted_devices[t][i].mec_name - 1].save_resource(t)
                    sorted_devices[t][i].set_mode = "add"
                    sorted_devices[t][i]._lost_flag = True

        # ある時刻tのMECに一時的に保存していた割り当てたデバイスをコピーする。
        copy_to_mec(mec, save_devices, t)

    #-----
    # リソース消費量がそれぞれで違う時のテスト用関数を作成する
    # 各秒でMECが持っているデバイスのインデックスと数がわかるものとする

    sum = 0
    mec_sum = 0
    having_device_resource_sum = 0
    sum = 0

    mec_sum = 0
    having_device_resource_sum = 0
    """
    for t in range(system_end_time):
        # print("time:", t)
        for m in range(mec_num):
            # if t == 16:
            # print("MEC_ID:", mec[m].name, ", having devices:", mec[m]._having_devices[t], mec[m]._having_devices_count[t],
            # ", mec_resouce:", mec[m]._resource_per_second[t], ", current time:", t)
            # sum = sum + mec[m]._having_devices_count[t]
            # mec_sum = mec_sum + mec[m]._resource_per_second[t]
            # sum = sum + mec[m]._having_devices_count[t]
            mec_sum = mec_sum + mec[m]._resource_per_second[t]
            if mec[m]._having_devices[t] is not None:
                # print("check", mec[m]._having_devices[t])
                device_index = device_index_search(sorted_devices[t], mec[m]._having_devices[t])
                # print(mec[m]._having_devices[t], device_index)
                having_device_resource_sum = having_device_resource_sum + device_resource_calc(sorted_devices[t],
                                                                                               device_index)
        check_allocation(t, 150, MEC_resource, having_device_resource_sum, mec_sum)
        print((150 * MEC_resource - having_device_resource_sum), mec_sum)
        having_device_resource_sum = 0
        sum = 0
        mec_sum = 0
    """
    # print(sum, (150*100-sum), mec_sum)
    num = len(sorted_devices[-1])

    print("system_time: ", system_end_time)
    print("MEC_num: ", mec_num)
    print("device_num: ", num)

    sorted_devices = sorted_devices[0:system_end_time]
    maximum = max_hop_search(sorted_devices[-1])
    print("max_hop: ", maximum)
    minimum = min_hop_search(sorted_devices[-1])
    print("min_hop: ", minimum)
    average_hop = average_hop_calc(sorted_devices[-1])
    print("average_hop: ", average_hop)
    reboot_rate = application_reboot_rate(mec, system_end_time)
    print("AP reboot rate:", reboot_rate)
    max_distance = max_distance_search(sorted_devices[-1])
    print("max_distance:", max_distance)
    min_distance = min_distance_search(sorted_devices[-1])
    print("min_distance:", min_distance)
    average_distance = average_distance_calc(sorted_devices[-1])
    print("average_distance: ", average_distance)

    result = [system_end_time]
    result.append(mec_num)
    result.append(MEC_resource)
    result.append(num)
    result.append(maximum)
    result.append(minimum)
    result.append(average_hop)
    result.append(reboot_rate)
    result.append(max_distance)
    result.append(min_distance)
    result.append(average_distance)

    # pathを動的に変えることで毎回新しいファイルを作成することができる
    write_csv(path_w, result)
    print("finish")

    return average_hop, reboot_rate
def nearest_simulation(system_end_time, MEC_resource, device_num,
                       device_allocation_method, path_w, how_compare):
    # ---
    # MECの準備
    df = pd.read_csv(
        "/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/base_station/okayama_kddi.csv",
        dtype={
            'lon': 'float',
            'lat': 'float'
        })
    server_type = "LTE"
    cover_range = 500
    n = len(df)
    print("Number of MEC server:", n)
    mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n

    #MECインスタンスをCSVを元に生成
    data_length = len(df)

    for index, series in df.iterrows():
        mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                                series["lon"], series["lat"], cover_range,
                                system_end_time)
    #mec = delete_mec(mec)

    #MECサーバにAPの情報を付与(乱数を取得し実行可能なAPを設定する)
    count = 1
    for t in range(data_length):
        if count == 1:
            mec[t]._app_ver = [1, 2]
            count = 2
        elif count == 2:
            mec[t]._app_ver = [1, 3]
            count = 3
        else:
            mec[t]._app_ver = [2, 3]
            count = 1

    mec_num = len(mec)
    #print("MECs", mec_num)

    # 集約局を対応するMECに設定する
    set_aggregation_station(mec)

    # 到着順
    if device_allocation_method == 0:

        if how_compare == "hop":
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.clone_binaryfile2',
                'rb')
        else:
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.clone_binaryfile',
                'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        sum = 0
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
            devices[i]._allocation_plan = [None] * system_end_time
            sum = sum + devices[i].use_resource
        #print(sum)
        # 順序をシャッフル(各時間ごとに到着順をランダムで決める)
        random.shuffle(devices)
        sorted_devices = [devices] * system_end_time
        for t in range(system_end_time):
            random.shuffle(devices)
            sorted_devices[t] = devices
    # リソース順
    elif device_allocation_method == 1:

        if how_compare == "hop":
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.clone_binaryfile2',
                'rb')
        else:
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.clone_binaryfile',
                'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        devices = reverse_resource_sort(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
        sorted_devices = [devices] * system_end_time  #デバイスをリソース順にソートする
    # 混雑度順
    else:
        # 混雑度計算
        # traffic_congestion(mec, devices, system_end_time, 1000)

        if how_compare == "hop":
            cd = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/script/normal/device_compare/congestion_checked_devices2.binaryfile',
                'rb')
        else:
            cd = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/script/normal/device_compare/congestion_checked_devices1.binaryfile',
                'rb')
        cd = pickle.load(cd)
        devices = cd
        num = len(devices)
        #print("device_num", num)

        # 混雑度順で毎秒ごとのdevicesをソートする
        sorted_devices = devices_ap_congestion_sort(devices, system_end_time)

    # ----------------------------------------------------------------------------------------------------------------------------------
    # ここからメインの処理
    for t in range(system_end_time):
        #print("[TIME:", t, "]")

        # ある時刻tのMECに割り当てらえたデバイス名を一時的に保存する用の変数
        save_devices = [None] * mec_num

        for i in range(num):
            #print("---new device---", sorted_devices[t][i].name)
            # plan_indexがデバイスの稼働時間外なら処理をスキップ
            if (check_plan_index(sorted_devices[t][i].plan_index,
                                 len(sorted_devices[t][i].plan)) == False):
                #print("skip")
                continue

            # plan_indexが稼働時間内なら処理開始
            if check_between_time(sorted_devices[t][i], t) == True:
                #print(sorted_devices[t][i].plan_index)
                # 最近傍割り当て処理
                device_flag, allocation_MEC_name = nearest_search(
                    sorted_devices[t][i], mec, sorted_devices[t][i].plan_index,
                    cover_range, t)

                # 最近傍割り当てが成功したら表示する
                if device_flag == True:
                    # deviceが直前で割り当てたMECのインデックスを取得
                    mec_index = search_mec_index(mec, allocation_MEC_name)

                    # print("device:", sorted_devices[t][i].name, ", use_resource:", sorted_devices[t][i].use_resource, "--->", "MEC_ID:", mec[mec_index].name, ", index:", i)
                    # print(sorted_devices[t][i].mec_name, mec[mec_index].resource)
                    # print(mec_index, len(save_devices))

                    # なぜindexがmec_indexなの? <- mec用のリストだから
                    if save_devices[
                            mec_index] == None:  #ある時刻tにMECに割り当てたデバイス名を保存
                        save_devices[mec_index] = [sorted_devices[t][i].name]
                    else:
                        save_devices[mec_index].append(
                            sorted_devices[t][i].name)  #デバイス名を追加

                    # ---
                    # print(t, mec_index, index)
                # 実行時間外の時
                #else:
                #デバイスがMECを見つけられないかった時
                #print(devices[i].name)
                #print("NOT FIND")
                # plan_indexをインクリメント

                sorted_devices[t][i]._plan_index = sorted_devices[t][
                    i]._plan_index + 1  #sorted_devicesのインスタンスのplan_indexをインクリメント

            else:
                # デバイスの稼働時間を超えた時の処理(デバイスが移動し終わって消滅した場合)
                # 前回割り当てたMECのリソースをリカバリする。
                if sorted_devices[t][i].mec_name != [] and sorted_devices[t][
                        i]._lost_flag == False:  #deviceを割り当てていたMECの名前が空でなく、lost_flag == False(割り当て完了の意味)
                    previous_index = search_mec_index(
                        mec, sorted_devices[t]
                        [i].mec_name)  #deviceを割り当ててているMECの名前からインデックスを取得
                    #print("DECREASE")
                    sorted_devices[t][
                        i].set_mode = "decrease"  #移動し終わったデバイスのmodeを変更
                    #print(sorted_devices[t][i].mec_name)
                    mec[previous_index].custom_resource_adjustment(
                        sorted_devices[t][i], t)  #MECのリソースを調整(増やす)
                    mec[previous_index].save_resource(
                        t
                    )  #時刻tにおけるリソースの状態を保存するメソッド:resource_per_second[time]に保存
                    sorted_devices[t][i].set_mode = "add"  #初期値に更新
                    sorted_devices[t][i]._lost_flag = True  #初期値に更新

        # ある時刻tのMECに一時的に保存していた割り当てたデバイスをコピーする。
        copy_to_mec(mec, save_devices,
                    t)  #having_devicesに(time,save_devices[])を追加

    #-----------------------------------------------------------------------------------------------------------------
    # リソース消費量がそれぞれで違う時のテスト用関数を作成する
    # 各秒でMECが持っているデバイスのインデックスと数がわかるものとする

    sum = 0
    mec_sum = 0  #mecのリソース容量の合計
    having_device_resource_sum = 0  #

    for t in range(system_end_time):
        # print("time:", t)

        #1つ目のMECから順に
        for m in range(mec_num):
            mec_sum = mec_sum + mec[m]._resource_per_second[
                t]  #resource_per_second[t]は時刻tにおけるリソースの状態

            if mec[m]._having_devices[t] is not None:  #時刻tに割り当てたデバイスが空でなければ
                # print("check", mec[m]._having_devices[t])
                device_index = device_index_search(
                    sorted_devices[t],
                    mec[m]._having_devices[t])  #割り当てたデバイスのインデックスを取得
                # print(mec[m]._having_devices[t], device_index)
                having_device_resource_sum = having_device_resource_sum + device_resource_calc(
                    sorted_devices[t], device_index)  #要求リソース量の和を計算

        #ある時刻tのMECへの割り当てができているかを確認するメソッド
        check_allocation(t, mec_num, MEC_resource, having_device_resource_sum,
                         mec_sum)
        #print((mec_num * MEC_resource - having_device_resource_sum), mec_sum)
        sum = 0
        mec_sum = 0
        having_device_resource_sum = 0

    # print(sum, (150*100-sum), mec_sum)
    # print("resource",resource_sum)

    print("system_time: ", system_end_time)
    print("MEC_num: ", mec_num)
    print("device_num: ", num)

    sorted_devices = sorted_devices[0:system_end_time]

    maximum = max_hop_search(sorted_devices[-1])
    print("max_hop: ", maximum)

    minimum = min_hop_search(sorted_devices[-1])
    print("min_hop: ", minimum)

    average_hop = average_hop_calc(sorted_devices[-1])
    print("average_hop: ", average_hop)

    reboot_rate = application_reboot_rate(mec, system_end_time)
    print("AP reboot rate:", reboot_rate)

    max_distance = max_distance_search(sorted_devices[-1])
    print("max_distance:", max_distance)

    min_distance = min_distance_search(sorted_devices[-1])
    print("min_distance:", min_distance)

    average_distance = average_distance_calc(sorted_devices[-1])
    print("average_distance: ", average_distance)

    # for d in range(device_num):
    # print(devices[d].hop)

    result = [system_end_time]
    result.append(mec_num)
    result.append(MEC_resource)
    result.append(num)
    result.append(maximum)
    result.append(minimum)
    result.append(average_hop)
    result.append(reboot_rate)
    result.append(max_distance)
    result.append(min_distance)
    result.append(average_distance)

    # 結果をcsvへ書き込み
    write_csv(path_w, result)
    return average_hop, reboot_rate
Ejemplo n.º 7
0
def make_congestion_binary(system_end_time, device_num, MEC_resource,
                           search_distance):
    # SUMO全体の計算時間
    #system_end_time = 4736
    #system_end_time = 100
    # CSV読み込み
    df = pd.read_csv(
        "/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/base_station/kddi_okayama_city2.csv",
        dtype={
            'lon': 'float',
            'lat': 'float'
        })
    # 基地局の種類を設定
    server_type = "LTE"

    # 基地局のカバー範囲を設定(メートル)
    cover_range = 500
    # CSVの行数を取得(基地局の数)
    n = len(df)
    print("Number of MEC server:", n)
    # 基地局の数のオブジェクト用リストを作成
    mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n

    # テスト用デバイスデータ
    device_flag = False
    # バイナリデータを読み込み
    d = open(
        '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.clone_binaryfile',
        'rb')
    devices = pickle.load(d)
    print("デバイスのMAX数", len(devices))
    devices = devices[0:device_num]
    """
    for i in range(3):
        devices2 = devices
        num = len(devices2)
        for d in range(num):
            devices2[d].name = num + d
        devices.extend(devices2)
    """

    num = len(devices)
    for i in range(num):
        devices[i].startup_time = float(
            devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
        devices[i].set_congestion_status(system_end_time)
        devices[i].set_MEC_distance(len(df))
        devices[i]._first_flag = True
        devices[i]._allocation_plan = [None] * system_end_time
        #devices[i].use_resource = random.randint(1, 3)
        devices[i].use_resource = 1

    # MECインスタンスをCSVを元に生成
    data_length = len(df)
    #data_length = 100
    for index, series in df.iterrows():
        mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                                series["lon"], series["lat"], cover_range,
                                system_end_time)
    # 時間をセット
    devices[i].startup_time = float(devices[i].plan[0].time)  # 各デバイスの起動時間を設定する

    # 事前に作成しておいたバイナリデータからデバイスインスタンスを作成
    traffic_congestion(mec, devices, system_end_time, search_distance)

    f = open(
        '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/congestion_checked_devices.binaryfile',
        'wb')
    pickle.dump(devices, f)
    f.close
def hop_calc(device: Device, mecs: MEC_servers, mec: MEC_server,
             previous_mec_name, time):
    """
    ホップ数を計算するメソッド
    :param device: デバイス
    :param mecs: MECサーバ群
    :param mec: 対象のMECサーバ
    :param previous_mec_name: 以前に割り当てたMECの名前
    :param time: 現在時刻
    """
    # ホップ数計算
    # 最初の割り当て
    if device._first_flag == True:  #first_flag 初期値True
        device._hop = [1]  #device._hop = [1]で更新
        device._first_flag = False
    #elif mec.name == device.mec_name:
    #keep_hop(device)
    # 切替成功

    #first_flag = Falseのとき
    else:
        mec.add_reboot_count(time)  #reboot_count[time]をインクリメント

        # 集約局が同一の時
        if mec_compare(device, mec) == False:
            device._three_count = device._three_count + 1  #インクリメント
            # ---

            device._hop.append(3)  # ホップ数の追加
            previous_mec = search_mec(mecs,
                                      previous_mec_name)  #以前のMECのオブジェクトを取得
            distance = distance_calc(
                mec.lat, mec.lon, previous_mec.lat,
                previous_mec.lon)  #以前のMECと今回割り当てるMECの距離を計算

            # 割り当て距離を追加
            if device._distance is None:
                device._distance = [distance]
            else:
                device._distance.append(distance)

            # 最小割り当て距離の更新
            if device._min_distance > distance and distance != 0:
                device._min_distance = distance

            # 最大割り当て距離の更新
            if device._max_distance < distance:
                device._max_distance = distance

        # 集約局が違う時
        else:
            device._hop.append(5)  #ホップ数の追加
            previous_mec = search_mec(mecs, device.mec_name)
            distance = distance_calc(mec.lat, mec.lon, previous_mec.lat,
                                     previous_mec.lon)

            # 割り当て距離を追加
            if device._distance is None:
                device._distance = [distance]
            else:
                device._distance.append(distance)

            # 最小割り当て距離の計算
            if device._min_distance > distance and distance != 0:
                device._min_distance = distance

            # 最大割り当て距離の計算
            if device._max_distance < distance:
                device._max_distance = distance
Ejemplo n.º 9
0
def make_congestion_binary1(system_end_time, device_num, MEC_resource,
                            search_distance):
    # SUMO全体の計算時間
    #system_end_time = 4736
    #system_end_time = 100
    # CSV読み込み
    df = pd.read_csv(
        "/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/base_station/okayama_kddi.csv",
        dtype={
            'lon': 'float',
            'lat': 'float'
        })
    # 基地局の種類を設定
    server_type = "LTE"

    # 基地局のカバー範囲を設定(メートル)
    cover_range = 500
    # CSVの行数を取得(基地局の数)
    n = len(df)
    print("Number of MEC server:", n)
    # 基地局の数のオブジェクト用リストを作成
    mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n

    # テスト用デバイスデータ
    device_flag = False
    # バイナリデータを読み込み
    d = open(
        '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.clone_binaryfile',
        'rb')

    devices = pickle.load(d)
    print("デバイスのMAX数", len(devices))
    devices = devices[0:device_num]
    """
    for i in range(3):
        devices2 = devices
        num = len(devices2)
        for d in range(num):
            devices2[d].name = num + d
        devices.extend(devices2)
    """

    num = len(devices)
    for i in range(num):
        devices[i].startup_time = float(
            devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
        devices[i].set_congestion_status(
            system_end_time)  # 各デバイスのcongestion_status = [0] * system_time
        devices[i].set_MEC_distance(len(df))
        devices[i]._first_flag = True
        devices[i]._allocation_plan = [None] * system_end_time
        #devices[i].use_resource = random.randint(1, 3)
        #devices[i].use_resource = 1

    #MECインスタンスをCSVを元に生成
    data_length = len(mec)

    #data_length = 100
    for index, series in df.iterrows():
        mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                                series["lon"], series["lat"], cover_range,
                                system_end_time)

    #MECサーバにAPの情報を付与(乱数を取得し実行可能なAPを設定する)
    count = 1
    for t in range(data_length):
        if count == 1:
            mec[t]._app_ver = [1, 2]
            count = 2
        elif count == 2:
            mec[t]._app_ver = [1, 3]
            count = 3
        else:
            mec[t]._app_ver = [2, 3]
            count = 1

    # 時間をセット
    #devices[i].startup_time = float(devices[i].plan[0].time) # 各デバイスの起動時間を設定する(コメントアウト)

    # 事前に作成しておいたバイナリデータからデバイスインスタンスを作成
    traffic_ap_congestion(mec, devices, system_end_time, search_distance)

    f = open(
        '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/script/normal/device_compare/congestion_checked_devices1.binaryfile',
        'wb')
    pickle.dump(devices, f)
    f.close
Ejemplo n.º 10
0
def nearest_simulation(system_end_time, MEC_resource, device_num,
                       device_allocation_method, path_w, how_compare):
    # ---
    # MECの準備
    df = pd.read_csv(
        "/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/base_station/kddi_okayama_city2.csv",
        dtype={
            'lon': 'float',
            'lat': 'float'
        })
    server_type = "LTE"
    cover_range = 500
    n = len(df)
    print("Number of MEC server:", n)
    mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n
    for index, series in df.iterrows():
        mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                                series["lon"], series["lat"], cover_range,
                                system_end_time)
    #mec = delete_mec(mec)
    mec_num = len(mec)
    print("MECs", mec_num)

    # 集約局を対応するMECに設定する
    set_aggregation_station(mec)

    # 到着順
    if device_allocation_method == 0:
        if how_compare == "hop":
            d = open(
                '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.simple_congestion_binaryfile_500',
                'rb')
        else:
            d = open(
                '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.clone_binaryfile',
                'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        sum = 0
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
            devices[i]._allocation_plan = [None] * system_end_time
            sum = sum + devices[i].use_resource
        print(sum)
        # 順序をシャッフル
        random.shuffle(devices)
        sorted_devices = [devices] * system_end_time
        for t in range(system_end_time):
            random.shuffle(devices)
            sorted_devices[t] = devices
    # リソース順
    elif device_allocation_method == 1:
        if how_compare == "hop":
            d = open(
                '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.simple_congestion_binaryfile_500',
                'rb')
        else:
            d = open(
                '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.clone_binaryfile',
                'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        devices = reverse_resource_sort(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
        sorted_devices = [devices] * system_end_time
    # 混雑度順
    else:
        # 混雑度
        # traffic_congestion(mec, devices, system_end_time, 1000)
        if how_compare == "hop":
            cd = open(
                '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/script/simple/device_compare/congestion_checked_devices2.binaryfile',
                'rb')
        else:
            cd = open(
                '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/script/simple/device_compare/congestion_checked_devices1.binaryfile',
                'rb')
        cd = pickle.load(cd)
        devices = cd
        num = len(devices)
        print("device_num", num)

        # 混雑度順で毎秒ごとのdevicesをソートする
        sorted_devices = devices_congestion_sort(devices, system_end_time)

    # ---
    # ここからメインの処理
    for t in range(system_end_time):
        print("[TIME:", t, "]")
        # ある時刻tのMECに割り当てらえたデバイスを一時的に保存する用の変数
        save_devices = [None] * mec_num
        for i in range(num):
            print("---new device---", sorted_devices[t][i].name)
            # plan_indexがデバイスの稼働時間外なら処理をスキップ
            if (check_plan_index(sorted_devices[t][i].plan_index,
                                 len(sorted_devices[t][i].plan)) == False):
                print("skip")
                continue
            # plan_indexが稼働時間内なら処理開始
            if check_between_time(sorted_devices[t][i], t) == True:
                print(sorted_devices[t][i].plan_index)
                # 最近傍割り当て処理
                device_flag, allocation_MEC_name = nearest_search2(
                    sorted_devices[t][i], mec, sorted_devices[t][i].plan_index,
                    cover_range, t)
                # 最近傍割り当てが成功したら表示する
                if device_flag == True:
                    # deviceが直前で割り当てたMECを取得
                    mec_index = search_mec_index(mec, allocation_MEC_name)
                    # print("device:", sorted_devices[t][i].name, ", use_resource:", sorted_devices[t][i].use_resource, "--->", "MEC_ID:", mec[mec_index].name, ", index:", i)
                    # print(sorted_devices[t][i].mec_name, mec[mec_index].resource)
                    # print(mec_index, len(save_devices))

                    # なぜindexがmec_indexなの? <- mec用のリストだから
                    if save_devices[mec_index] == None:
                        save_devices[mec_index] = [sorted_devices[t][i].name]
                    else:
                        save_devices[mec_index].append(
                            sorted_devices[t][i].name)
                    # ---
                    # print(t, mec_index, index)
                # 実行時間外の時
                else:
                    # デバイスがMECを見つけられないかった時
                    print(devices[i].name)
                    print("NOT FIND")
                # plan_indexをインクリメント
                sorted_devices[t][
                    i]._plan_index = sorted_devices[t][i]._plan_index + 1
            else:
                # デバイスの稼働時間を超えた時の処理
                # 前回割り当てたMECのリソースをリカバリーする。
                if sorted_devices[t][i].mec_name != [] and sorted_devices[t][
                        i]._lost_flag == False:
                    previous_index = search_mec_index(
                        mec, sorted_devices[t][i].mec_name)
                    print("DECREASE")
                    sorted_devices[t][i].set_mode = "decrease"
                    print(sorted_devices[t][i].mec_name)
                    mec[previous_index].custom_resource_adjustment(
                        sorted_devices[t][i], t)
                    mec[previous_index].save_resource(t)
                    sorted_devices[t][i].set_mode = "add"
                    sorted_devices[t][i]._lost_flag = True

        # ある時刻tのMECに一時的に保存していた割り当てたデバイスをコピーする。
        copy_to_mec(mec, save_devices, t)

    #-----
    # リソース消費量がそれぞれで違う時のテスト用関数を作成する
    # 各秒でMECが持っているデバイスのインデックスと数がわかるものとする

    sum = 0
    mec_sum = 0
    having_device_resource_sum = 0
    for t in range(system_end_time):
        # print("time:", t)
        for m in range(mec_num):
            mec_sum = mec_sum + mec[m]._resource_per_second[t]
            if mec[m]._having_devices[t] is not None:
                # print("check", mec[m]._having_devices[t])
                device_index = device_index_search(sorted_devices[t],
                                                   mec[m]._having_devices[t])
                # print(mec[m]._having_devices[t], device_index)
                having_device_resource_sum = having_device_resource_sum + device_resource_calc(
                    sorted_devices[t], device_index)
        check_allocation(t, mec_num, MEC_resource, having_device_resource_sum,
                         mec_sum)
        print((mec_num * MEC_resource - having_device_resource_sum), mec_sum)
        having_device_resource_sum = 0
        sum = 0
        mec_sum = 0
    # print(sum, (150*100-sum), mec_sum)
    # print("resource",resource_sum)

    print("system_time: ", system_end_time)
    print("MEC_num: ", mec_num)
    print("device_num: ", num)

    sorted_devices = sorted_devices[0:system_end_time]
    maximum = max_hop_search(sorted_devices[-1])
    print("max_hop: ", maximum)
    minimum = min_hop_search(sorted_devices[-1])
    print("min_hop: ", minimum)
    average_hop = average_hop_calc(sorted_devices[-1])
    print("average_hop: ", average_hop)
    reboot_rate = application_reboot_rate(mec, system_end_time)
    print("AP reboot rate:", reboot_rate)
    max_distance = max_distance_search(sorted_devices[-1])
    print("max_distance:", max_distance)
    min_distance = min_distance_search(sorted_devices[-1])
    print("min_distance:", min_distance)
    average_distance = average_distance_calc(sorted_devices[-1])
    print("average_distance: ", average_distance)

    # for d in range(device_num):
    # print(devices[d].hop)

    result = [system_end_time]
    result.append(mec_num)
    result.append(MEC_resource)
    result.append(num)
    result.append(maximum)
    result.append(minimum)
    result.append(average_hop)
    result.append(reboot_rate)
    result.append(max_distance)
    result.append(min_distance)
    result.append(average_distance)

    # 結果をcsvへ書き込み
    write_csv(path_w, result)
    return average_hop, reboot_rate
def continue_priority_simulation(system_end_time, MEC_resource, device_num,
                                 continue_distance, f_time,
                                 device_allocation_method, path_w):

    df = pd.read_csv(
        "/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/base_station/kddi_okayama_city2.csv",
        dtype={
            'lon': 'float',
            'lat': 'float'
        })
    server_type = "LTE"
    cover_range = 500
    n = len(df)
    print("Number of MEC server:", n)
    mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n
    for index, series in df.iterrows():
        mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                                series["lon"], series["lat"], cover_range,
                                system_end_time)
    mec_num = len(df)

    # 集約局を対応するMECに設定する
    set_aggregation_station(mec)

    # 到着順
    if device_allocation_method == 0:
        d = open(
            '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.clone_binaryfile',
            'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
            devices[i]._allocation_plan = [None] * system_end_time
        # 順序をシャッフル
        random.shuffle(devices)
        sorted_devices = [devices] * system_end_time
        for t in range(system_end_time):
            random.shuffle(devices)
            sorted_devices[t] = devices
    # リソース順
    elif device_allocation_method == 1:
        d = open(
            '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/device.congestion_binaryfile',
            'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        devices = reverse_resource_sort(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
        sorted_devices = [devices] * system_end_time
    # 混雑度順
    else:
        # 混雑度計算
        # traffic_congestion(mec, devices, system_end_time, 1000)
        cd = open(
            '/Users/sugimurayuuki/Desktop/mecsimulator/CloudletSimulator/dataset/congestion_checked_devices.binaryfile',
            'rb')
        cd = pickle.load(cd)
        devices = cd
        num = len(devices)
        print("device_num", num)

        # 混雑度順で毎秒ごとのdevicesをソートする
        sorted_devices = devices_congestion_sort(devices, system_end_time)

    keep_count = 0
    # save_devices = [] * data_length
    # ---
    # ここからメインの処理
    for t in range(system_end_time):
        print("[TIME:", t, "]")
        # ある時刻tのMECに割り当てらえたデバイスを一時的に保存する用の変数
        save_devices = [None] * mec_num
        for i in range(num):
            print("---new device---", sorted_devices[t][i].name)
            # plan_indexがデバイスの稼働時間外なら処理をスキップ
            if (check_plan_index(sorted_devices[t][i].plan_index,
                                 len(sorted_devices[t][i].plan)) == False):
                print("skip")
                continue
            # plan_indexが稼働時間内なら処理開始
            if check_between_time(sorted_devices[t][i], t) == True:
                print(sorted_devices[t][i].plan_index)
                # 継続割り当て
                continue_flag, allocation_MEC_name = continue_search(
                    sorted_devices[t][i], mec, sorted_devices[t][i].plan_index,
                    cover_range, t, continue_distance)
                if continue_flag == True:
                    keep_count = keep_count + 1
                if continue_flag == False:
                    print("移動経路優先度選択")
                    loop_count = 0
                    # 移動経路優先で使う探索範囲の初期化
                    search_distance = continue_distance
                    # 移動経路優先で使う未来の時刻の初期化
                    ftime = f_time
                    # 優先度割り当て用のFLAGの初期化
                    property_flag = False
                    # 優先度を割り当てられるまで完了するまでループ(探索範囲内にMECがなければ、距離を500つずつ増やす)
                    # 車の平均速度を50km/hと仮定すると13m/s
                    while (property_flag == False):
                        # 予測時間の時にデバイスが稼働時間内の場合
                        if sorted_devices[t][i].plan_index + ftime < len(
                                sorted_devices[t][i].plan):
                            print("if")
                            # 優先度ソート用のFLAGの初期化
                            sort_flag = False
                            # 移動経路優先度計算が完了するまで繰り返す
                            calc_count = 0
                            while (sort_flag == False):
                                print("calc")
                                calc_count = calc_count + 1
                                print("ソート直前ののMECの長さ", len(mec))
                                # 移動経路優先度にMECをソート
                                sort_flag, sorted_mecs, sort_finish_index = move_plan_priority_calc(
                                    mec, sorted_devices[t][i],
                                    sorted_devices[t][i].plan_index, t, ftime,
                                    search_distance)
                                print("ソート直後ののMECの長さ", len(sorted_mecs))
                                # 探索範囲の加算
                                search_distance = search_distance + 500
                            print(sort_flag, search_distance,
                                  sorted_devices[t][i].plan_index + ftime,
                                  len(sorted_devices[t][i].plan))
                            # 優先度順にソートしたMECを選択
                            property_flag, allocation_MEC_name = priority_allocation(
                                sorted_mecs, sorted_devices[t][i],
                                sorted_devices[t][i].plan_index, t,
                                sort_finish_index)
                            # MECを更新
                            if property_flag == True:
                                mec = sorted_mecs

                        # 予測時間がデバイスの稼働時間を超えてしまった場合
                        else:
                            print("else")
                            # デバイスの終了時間のインデックスを調べる
                            shutdown_index = sorted_devices[t][
                                i].shutdown_time - sorted_devices[t][
                                    i].startup_time
                            # デバイスの終了時間のインデックスを予測時間に代入
                            ftime = shutdown_index - sorted_devices[t][
                                i].plan_index

                # 継続割り当て or 移動経路優先割り当てに成功した場合
                # 割り当てたときのMECとデバイスの情報を表示
                if continue_flag == True or property_flag == True:

                    # 移動経路優先割り当てでソートした場合
                    # MECを更新
                    # if property_flag == True:
                    # mec = sorted_mecs

                    # ID順に昇順ソート
                    mec = sorted(mec, key=lambda m: m.name, reverse=False)

                    # deviceが直前で割り当てたMECを取得
                    mec_index = search_mec_index(mec, allocation_MEC_name)

                    print(mec_index, mec[mec_index].name)
                    print("device:", sorted_devices[t][i].name,
                          ", use_resource:", sorted_devices[t][i].use_resource,
                          "--->", "MEC_ID:", mec[mec_index].name, ", index:",
                          i)
                    print("割り振られたMEC:", sorted_devices[t][i].mec_name,
                          ", MEC残量リソース:", mec[mec_index].resource)
                    print(mec_index, len(save_devices))

                    # ---
                    # 毎秒ごとの割り当てたデバイスを保存
                    # なぜindexがmec_indexなの? <- mec用のリストだから
                    if save_devices[mec_index] == None:
                        save_devices[mec_index] = [sorted_devices[t][i].name]
                    else:
                        save_devices[mec_index].append(
                            sorted_devices[t][i].name)
                    # ---
                    # print(t, mec_index, index)
                    allocation_MEC_name = 0
                else:
                    # デバイスが割り振れなかった時
                    # ここが実行されるのは本来ありえない
                    print("NOT FIND")
                    print("not find MEC error")
                    sys.exit()

                # plan_indexをインクリメント(planを読み込むため)
                sorted_devices[t][
                    i]._plan_index = sorted_devices[t][i]._plan_index + 1

            else:
                # デバイスの稼働時間を超えた時の処理
                if sorted_devices[t][i].mec_name != [] and sorted_devices[t][
                        i]._lost_flag == False:
                    mec = sorted(mec, key=lambda m: m.name, reverse=False)
                    print("device", sorted_devices[t][i].mec_name,
                          ": shutdown")
                    print("DECREASE")
                    sorted_devices[t][i].set_mode = "decrease"
                    print(sorted_devices[t][i].mec_name)
                    mec[sorted_devices[t][i].mec_name -
                        1].custom_resource_adjustment(sorted_devices[t][i], t)
                    mec[sorted_devices[t][i].mec_name - 1].save_resource(t)
                    sorted_devices[t][i].set_mode = "add"
                    sorted_devices[t][i]._lost_flag = True

        # ある時刻tのMECに一時的に保存していた割り当てたデバイスをコピーする。
        copy_to_mec(mec, save_devices, t)

    # MECを昇順に直す
    mec = sorted(mec, key=lambda m: m.name, reverse=False)

    sum = 0
    mec_sum = 0
    having_device_resource_sum = 0
    """
    for t in range(system_end_time):
        # print("time:", t)
        for m in range(mec_num):
            #if t == 95:
                # if mec[m]._having_devices_count[t] != (MEC_resource- mec[m]._resource_per_second[t]):
                # if mec[m].name == 11:
                #print("MEC_ID:", mec[m].name, ", having devices:", mec[m]._having_devices[t],
                      #mec[m]._having_devices_count[t],
                      #", mec_resouce:", mec[m]._resource_per_second[t], ", current time:", t, mec[m]._test)
                # sum = sum + mec[m]._having_devices_count[t]
            # mec_sum = mec_sum + mec[m]._resource_per_second[t]
            # sum = sum + mec[m]._having_devices_count[t]
            mec_sum = mec_sum + mec[m]._resource_per_second[t]
            if mec[m]._having_devices[t] is not None:
                # print("check", mec[m]._having_devices[t])
                device_index = device_index_search(sorted_devices[t], mec[m]._having_devices[t])
                # print(mec[m]._having_devices[t], device_index)
                having_device_resource_sum = having_device_resource_sum + device_resource_calc(sorted_devices[t],
                                                                                               device_index)
        check_allocation(t, mec_num, MEC_resource, having_device_resource_sum, mec_sum)
        print((mec_num * MEC_resource - having_device_resource_sum), mec_sum)
        having_device_resource_sum = 0
        sum = 0
        mec_sum = 0
    # print(sum, (150*100-sum), mec_sum)
    """
    num = len(devices)

    print("system_time: ", system_end_time)
    print("MEC_num: ", mec_num)
    print("device_num: ", num)

    sorted_devices = sorted_devices[0:system_end_time]
    maximum = max_hop_search(sorted_devices[-1])
    print("max_hop: ", maximum)
    minimum = min_hop_search(sorted_devices[-1])
    print("min_hop: ", minimum)
    average_hop = average_hop_calc(sorted_devices[-1])
    print("average_hop: ", average_hop)
    reboot_rate = application_reboot_rate(mec, system_end_time)
    print("AP reboot rate:", reboot_rate)
    print("continue_count", keep_count)
    max_distance = max_distance_search(sorted_devices[-1])
    print("max_distance:", max_distance)
    min_distance = min_distance_search(sorted_devices[-1])
    print("min_distance:", min_distance)
    average_distance = average_distance_calc(sorted_devices[-1])
    print("average_distance: ", average_distance)

    result = [system_end_time]
    result.append(mec_num)
    result.append(MEC_resource)
    result.append(num)
    result.append(maximum)
    result.append(minimum)
    result.append(average_hop)
    result.append(reboot_rate)
    result.append(max_distance)
    result.append(min_distance)
    result.append(average_distance)

    # pathを動的に変えることで毎回新しいファイルを作成することができる
    write_csv(path_w, result)
    print("finish")

    return average_hop, reboot_rate
def continue_nearest_simulation(system_end_time, MEC_resource, device_num,
                                continue_distance, device_allocation_method,
                                path_w, how_compare):
    df = pd.read_csv(
        "/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/base_station/okayama_kddi.csv",
        dtype={
            'lon': 'float',
            'lat': 'float'
        })
    server_type = "LTE"
    cover_range = 500
    n = len(df)
    print("Number of MEC server:", n)
    mec = [MEC_server(0, 00, " ", 00.00, 00.00, 0, 0)] * n

    #MECインスタンスをCSVを元に生成
    data_length = len(df)

    for index, series in df.iterrows():
        mec[index] = MEC_server(MEC_resource, index + 1, server_type,
                                series["lon"], series["lat"], cover_range,
                                system_end_time)
    #mec = delete_mec(mec)

#MECサーバにAPの情報を付与(乱数を取得し実行可能なAPを設定する)
    count = 1
    for t in range(data_length):
        if count == 1:
            mec[t]._app_ver = [1, 2]
            count = 2
        elif count == 2:
            mec[t]._app_ver = [1, 3]
            count = 3
        else:
            mec[t]._app_ver = [2, 3]
            count = 1

    mec_num = len(df)

    # 集約局を対応するMECに設定する
    set_aggregation_station(mec)

    # 到着順
    if device_allocation_method == 0:

        if how_compare == "hop":
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.ns_clone_binaryfile2',
                'rb')
        else:
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.ns_clone_binaryfile',
                'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
            devices[i]._allocation_plan = [None] * system_end_time
        # 順序をシャッフル(各時間ごとに到着順をランダムで決める)
        random.shuffle(devices)
        sorted_devices = [devices] * system_end_time
        for t in range(system_end_time):
            random.shuffle(devices)
            sorted_devices[t] = devices
    # リソース順
    elif device_allocation_method == 1:

        if how_compare == "hop":
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.clone_binaryfile2',
                'rb')
        else:
            d = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/dataset/device.clone_binaryfile',
                'rb')
        devices = pickle.load(d)
        devices = devices[0:device_num]
        num = len(devices)
        devices = reverse_resource_sort(devices)
        for i in range(num):
            devices[i].startup_time = float(
                devices[i].plan[0].time)  # 各デバイスの起動時間を設定する
            devices[i].set_congestion_status(system_end_time)
            devices[i].set_MEC_distance(len(df))
            devices[i]._first_flag = True
        sorted_devices = [devices] * system_end_time  #デバイスをリソース順にソートする

    # 混雑度順
    else:
        # 混雑度計算
        # traffic_congestion(mec, devices, system_end_time, 1000)

        if how_compare == "hop":
            cd = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/script/normal/device_compare/congestion_checked_devices2.binaryfile',
                'rb')
        else:
            cd = open(
                '/home/tomokishiraga/PycharmProjects/simulation/CloudletSimulator/script/normal/device_compare/congestion_checked_devices1.binaryfile',
                'rb')
        cd = pickle.load(cd)
        devices = cd
        num = len(devices)
        print("device_num", num)

        # 混雑度順で毎秒ごとのdevicesをソートする
        sorted_devices = devices_ap_congestion_sort(devices, system_end_time)

    # save_devices = [] * data_length

    # ここからメインの処理----------------------------------------------------------------------------------------

    keep_count = 0

    for t in range(system_end_time):
        #print("[TIME:", t, "]")
        # ある時刻tのMECに割り当てらえたデバイスを一時的に保存する用の変数
        save_devices = [None] * mec_num

        for i in range(num):
            #print("---new device---", sorted_devices[t][i].name)
            # plan_indexがデバイスの稼働時間外なら処理をスキップ
            if (check_plan_index(sorted_devices[t][i].plan_index,
                                 len(sorted_devices[t][i].plan)) == False):
                #print("skip")
                continue

            # plan_indexが稼働時間内なら処理開始
            if check_between_time(sorted_devices[t][i], t) == True:
                #print("plan_index", sorted_devices[t][i].plan_index, "max_index", len(sorted_devices[t][i].plan))

                # 継続割り当て
                device_flag, allocation_MEC_name = continue_search(
                    sorted_devices[t][i], mec, sorted_devices[t][i].plan_index,
                    cover_range, t, continue_distance)

                if device_flag == True:
                    # 継続回数
                    keep_count = keep_count + 1

                    # 最近傍選択
                if device_flag == False:
                    device_flag, allocation_MEC_name = nearest_search(
                        sorted_devices[t][i], mec,
                        sorted_devices[t][i].plan_index, cover_range, t)
                # 割り当てが成功したら表示する
                if device_flag == True:
                    # deviceが直前で割り当てたMECのインデックスを取得
                    mec_index = search_mec_index(mec, allocation_MEC_name)

                    # print("device:", sorted_devices[t][i].name, ", use_resource:", sorted_devices[t][i].use_resource, "--->", "MEC_ID:", mec[mec_index].name, ", index:", i)
                    # print(sorted_devices[t][i].mec_name, mec[mec_index].resource)
                    # print(mec_index, len(save_devices))
                    # ---

                    # なぜindexがmec_indexなの? <- mec用のリストだから
                    if save_devices[mec_index] == None:
                        save_devices[mec_index] = [sorted_devices[t][i].name
                                                   ]  #ある時刻tにMECに割り当てたデバイス名を保存
                    else:
                        save_devices[mec_index].append(
                            sorted_devices[t][i].name)  #デバイス名を追加

                    mec_index = 0  #初期化
                #else:
                #print("NOT FIND")
                # plan_indexをインクリメント

                sorted_devices[t][i]._plan_index = sorted_devices[t][
                    i]._plan_index + 1  #sorted_devicesのインスタンスのplan_indexをインクリメント

            # デバイスの稼働時間を超えた時の処理
            else:
                # もしデバイスの終了時間を超えた時のみ(1回だけ)、デバイスに直前に割り当てたMECのリソースをリカバリーする。
                if sorted_devices[t][i].mec_name != [] and sorted_devices[t][
                        i]._lost_flag == False:
                    #print("DECREASE")
                    sorted_devices[t][
                        i].set_mode = "decrease"  #移動し終わったデバイスのmodeを変更
                    #print(sorted_devices[t][i].mec_name)
                    mec[sorted_devices[t][i].mec_name -
                        1].custom_resource_adjustment(sorted_devices[t][i],
                                                      t)  #MECのリソースを調整(増やす)
                    mec[sorted_devices[t][i].mec_name - 1].save_resource(
                        t
                    )  #時刻tにおけるリソースの状態を保存するメソッド:resource_per_second[time]に保存
                    sorted_devices[t][i].set_mode = "add"  #初期値に更新
                    sorted_devices[t][i]._lost_flag = True  #初期値に更新

        # ある時刻tのMECに一時的に保存していた割り当てたデバイスをコピーする。
        copy_to_mec(mec, save_devices, t)

    #-----
    # リソース消費量がそれぞれで違う時のテスト用関数を作成する
    # 各秒でMECが持っているデバイスのインデックスと数がわかるものとする

    #sum = 0
    #mec_sum = 0
    #having_device_resource_sum = 0
    """
    for t in range(system_end_time):
        # print("time:", t)
        for m in range(mec_num):
            # if t == 16:
            # print("MEC_ID:", mec[m].name, ", having devices:", mec[m]._having_devices[t], mec[m]._having_devices_count[t],
            # ", mec_resouce:", mec[m]._resource_per_second[t], ", current time:", t)
            # sum = sum + mec[m]._having_devices_count[t]
            # mec_sum = mec_sum + mec[m]._resource_per_second[t]
            # sum = sum + mec[m]._having_devices_count[t]
            mec_sum = mec_sum + mec[m]._resource_per_second[t]
            if mec[m]._having_devices[t] is not None:
                # print("check", mec[m]._having_devices[t])
                device_index = device_index_search(sorted_devices[t], mec[m]._having_devices[t])
                # print(mec[m]._having_devices[t], device_index)
                having_device_resource_sum = having_device_resource_sum + device_resource_calc(sorted_devices[t],
                                                                                               device_index)
        check_allocation(t, 150, MEC_resource, having_device_resource_sum, mec_sum)
        print((150 * MEC_resource - having_device_resource_sum), mec_sum)
        having_device_resource_sum = 0
        sum = 0
        mec_sum = 0
    """
    # print(sum, (150*100-sum), mec_sum)

    num = len(sorted_devices[-1])

    print("system_time: ", system_end_time)
    print("MEC_num: ", mec_num)
    print("device_num: ", num)

    sorted_devices = sorted_devices[0:system_end_time]

    maximum = max_hop_search(sorted_devices[-1])
    print("max_hop: ", maximum)

    minimum = min_hop_search(sorted_devices[-1])
    print("min_hop: ", minimum)

    average_hop = average_hop_calc(sorted_devices[-1])
    print("average_hop: ", average_hop)

    reboot_rate = application_reboot_rate(mec, system_end_time)
    print("AP reboot rate:", reboot_rate)

    max_distance = max_distance_search(sorted_devices[-1])
    print("max_distance:", max_distance)

    min_distance = min_distance_search(sorted_devices[-1])
    print("min_distance:", min_distance)

    average_distance = average_distance_calc(sorted_devices[-1])
    print("average_distance: ", average_distance)

    result = [system_end_time]
    result.append(mec_num)
    result.append(MEC_resource)
    result.append(num)
    result.append(maximum)
    result.append(minimum)
    result.append(average_hop)
    result.append(reboot_rate)
    result.append(max_distance)
    result.append(min_distance)
    result.append(average_distance)

    # pathを動的に変えることで毎回新しいファイルを作成することができる
    write_csv(path_w, result)
    print("finish")

    return average_hop, reboot_rate