Проблемы в пересчете дистрибутивов для использования в файле main.py - PullRequest
0 голосов
/ 19 января 2019

Прежде всего, у меня был старый, который отлично работал, я называю это для Distribution_v1.py. Этот файл генерирует случайные распределения с использованием вероятностей.

В чем была проблема с этим файлом? Проблема заключалась в том, что это был плохой код, и он генерировал дистрибутивы только один раз! поэтому, когда я запускаю симуляции в main.py, симуляция использует одни и те же дистрибутивы каждый день вместо того, чтобы вычислять новые для каждого дня.

Итак, что я пытался сделать, я попытался перезагрузить модуль (вызывая файл), но это не работает из-за этого метода:

def distribute_faster(cars, totals):
    counts = {total: 0 for total in range(totals)}
    while cars > 0:
        adjust = cars > 5000  # totally arbitrary
        change = 1
        if adjust:
            change = 5
        choice = randint(0, totals - 1)
        counts[choice] += change
        cars -= change
    return counts

Так что после того, как это не сработало, я попытался переформатировать код, который я назвал по имени Distribution_v2.py. Я добавил функции и т.д., но из-за изменений я получаю ошибку в файле main.py являются: для горячей точки в hotspot_districts: Ошибка типа: объект 'int' не повторяется

PS: вот старый код (Distribution_v1.py):

from random import randint

total_amount_of_cars_that_are_driving_to_work_districts =  26904
total_amount_of_cars_that_are_driving_to_main_districts = 21528
total_amount_of_cars_that_are_driving_to_hotspot_districts = 5376


"----Work districts setup----"
distributed_cars_to_work = []
cars_per_hour_to_work_districts = []

total_work_districts = []
all_working_districts_used = []
for amount_of_working_districts in range(0,7):
    all_working_districts_used.append(amount_of_working_districts)

for work_districts in all_working_districts_used:
    total_work_districts.append(work_districts)

"----Main districts setup----"
distributed_cars_to_main = []
cars_per_hour_to_main_districts = []

total_main_districts = []
all_the_main_districts = []
for amount_of_main_districts in range (0,45):
    all_the_main_districts.append(amount_of_main_districts)
for main_districts in all_the_main_districts:
    total_main_districts.append(main_districts)

"----Hotspot district setup----"
distributed_cars_to_hotspot = []
cars_per_hour_to_hotspot_districts = []

total_hotspot_districts = []
all_the_hotspot_districts = []
for amount_of_hotspot_districts in range(0,4):
    all_the_hotspot_districts.append(amount_of_hotspot_districts)

for hotspot_districts in all_the_hotspot_districts:
    total_hotspot_districts.append(hotspot_districts)






class CarsDistribution:
    all_probabilities = {
        "work":
#Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
    (0.0,   0.0,   0.0,  0.0,   0.01, 0.05,  0.11,  0.19,  0.23,  0.2,  0.14,  0.05, 0.0,  0.0,    0.0,  0.0,   0.0, 0.0,  0.0,   0.0,  0.0,   0.0,    0.0,   0.0,   0.0),
        "main":
#Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
    (0.0,   0.0,   0.0,  0.0,   0.0,  0.0,   0.0,   0.01,  0.01,  0.02, 0.02,  0.03, 0.04, 0.05,  0.06,  0.07, 0.08, 0.08, 0.08,  0.08, 0.07,  0.06,   0.06,  0.05,  0.04),
        "hotspot":
#Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
    (0.0,   0.0,   0.0,  0.0,   0.0,  0.0,   0.0,   0.0,   0.0,  0.01,  0.02,  0.03, 0.04, 0.08,   0.1,  0.12, 0.13, 0.13, 0.11,  0.07, 0.05,  0.04,   0.03,  0.02,   0.01)

    }

    def __init__(self, type, cars):
        total_length = len(cars)
        self.cars_per_hour = {}
        for hour, p in enumerate(self.all_probabilities[type]):
            try:
                self.cars_per_hour[hour] = [cars.pop() for i in range(int(p * total_length))]
            except IndexError:
                print('cars already exhausted at hour {}'.format(hour))
        if cars:
            print('{} left after distributing is finished'.format(len(cars)))

def distribute_faster(cars, totals):
    counts = {total: 0 for total in range(totals)}
    while cars > 0:
        adjust = cars > 5000  # totally arbitrary
        change = 1
        if adjust:
            change = 5
        choice = randint(0, totals - 1)
        counts[choice] += change
        cars -= change
    return counts




random_distribution_to_work = distribute_faster(total_amount_of_cars_that_are_driving_to_work_districts, 8)
print("Amount of cars distributed to work stations: {}".format(random_distribution_to_work))
print(".............................................................................................................")


for key, value in random_distribution_to_work.items():
    distributed_cars_to_work.append(value)


(work_districts) = (CarsDistribution('work', [distributed_cars_to_work for x in range(num_cars)]) for num_cars in distributed_cars_to_work)



for randomWork in work_districts:
    cars_per_hour_to_work_districts.append([len(c) for c in randomWork.cars_per_hour.values()])

for if_i_want_to_see_cars_per_hour_in_24_hours_to_work in cars_per_hour_to_work_districts:
    print(if_i_want_to_see_cars_per_hour_in_24_hours_to_work)

    print("Total amount of car that got distributed to this work station: {}".format(
        sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_work)))
    print("--------------------------------------------------------------------------------------------------")

print("===============================WORK DISTRIBUTION FINISHED=========================================")





random_distribution_to_main = distribute_faster(total_amount_of_cars_that_are_driving_to_main_districts, 46) #46!!

print("Amount of cars distributed to main stations: {}".format(random_distribution_to_main))
print(".............................................................................................................")


for key, value in random_distribution_to_main.items():
    distributed_cars_to_main.append(value)


(main_districts) = (CarsDistribution('main', [distributed_cars_to_main for x in range(num_cars)]) for num_cars in
                    distributed_cars_to_main)

for randomMain in main_districts:
    cars_per_hour_to_main_districts.append([len(c) for c in randomMain.cars_per_hour.values()])

for if_i_want_to_see_cars_per_hour_in_24_hours_to_main in cars_per_hour_to_main_districts:
    print(if_i_want_to_see_cars_per_hour_in_24_hours_to_main)

    print("Total amount of car that got distributed to this main station: {}".format(
        sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_main)))
    print("--------------------------------------------------------------------------------------------------")

print("===============================MAIN DISTRIBUTION FINISHED=========================================")




random_distribution_to_hotspot = distribute_faster(total_amount_of_cars_that_are_driving_to_hotspot_districts, 5)

print("Amount of cars distributed to hotspot stations: {}".format(random_distribution_to_hotspot))
print(".............................................................................................................")



for key, value in random_distribution_to_hotspot.items():
    distributed_cars_to_hotspot.append(value)


(hotspot_districts) = (CarsDistribution('hotspot', [distributed_cars_to_hotspot for x in range(num_cars)]) for num_cars in
                    distributed_cars_to_hotspot)

for randomHotspot in hotspot_districts:
    cars_per_hour_to_hotspot_districts.append([len(c) for c in randomHotspot.cars_per_hour.values()])

for if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot in cars_per_hour_to_hotspot_districts:
    print(if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot)

    print("Total amount of car that got distributed to this hotspot station: {}".format(
        sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot)))
    print("--------------------------------------------------------------------------------------------------")

print("============================HOTSPOT DISTRIBUTION FINISHED=========================================")

и вот переформатированный код с функциями (distribtions_v2.py):

from random import randint

total_amount_of_cars_that_are_driving_to_work_districts =  26904
total_amount_of_cars_that_are_driving_to_main_districts = 21528
total_amount_of_cars_that_are_driving_to_hotspot_districts = 5376


"----Work districts setup----"
distributed_cars_to_work = []
cars_per_hour_to_work_districts = []

total_work_districts = []
all_working_districts_used = []
for amount_of_working_districts in range(0,7):
    all_working_districts_used.append(amount_of_working_districts)

for work_districts in all_working_districts_used:
    total_work_districts.append(work_districts)

"----Main districts setup----"
distributed_cars_to_main = []
cars_per_hour_to_main_districts = []

total_main_districts = []
all_the_main_districts = []
for amount_of_main_districts in range (0,45):
    all_the_main_districts.append(amount_of_main_districts)
for main_districts in all_the_main_districts:
    total_main_districts.append(main_districts)

"----Hotspot district setup----"
distributed_cars_to_hotspot = []
cars_per_hour_to_hotspot_districts = []

total_hotspot_districts = []
all_the_hotspot_districts = []
for amount_of_hotspot_districts in range(0,4):
    all_the_hotspot_districts.append(amount_of_hotspot_districts)

for hotspot_districts in all_the_hotspot_districts:
    total_hotspot_districts.append(hotspot_districts)



def distribute_faster(cars, totals):
    counts = {total: 0 for total in range(totals)}
    while cars > 0:
        adjust = cars > 5000  # totally arbitrary
        change = 1
        if adjust:
            change = 5
        choice = randint(0, totals - 1)
        counts[choice] += change
        cars -= change
    return counts





class CarsDistribution:
    all_probabilities = {
        "work":
#Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
    (0.0,   0.0,   0.0,  0.0,   0.01, 0.05,  0.11,  0.19,  0.23,  0.2,  0.14,  0.05, 0.0,  0.0,    0.0,  0.0,   0.0, 0.0,  0.0,   0.0,  0.0,   0.0,    0.0,   0.0,   0.0),
        "main":
#Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
    (0.0,   0.0,   0.0,  0.0,   0.0,  0.0,   0.0,   0.01,  0.01,  0.02, 0.02,  0.03, 0.04, 0.05,  0.06,  0.07, 0.08, 0.08, 0.08,  0.08, 0.07,  0.06,   0.06,  0.05,  0.04),
        "hotspot":
#Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
    (0.0,   0.0,   0.0,  0.0,   0.0,  0.0,   0.0,   0.0,   0.0,  0.01,  0.02,  0.03, 0.04, 0.08,   0.1,  0.12, 0.13, 0.13, 0.11,  0.07, 0.05,  0.04,   0.03,  0.02,   0.01)

    }

    def __init__(self, type, cars):
        total_length = len(cars)
        self.cars_per_hour = {}
        for hour, p in enumerate(self.all_probabilities[type]):
            try:
                self.cars_per_hour[hour] = [cars.pop() for i in range(int(p * total_length))]
            except IndexError:
                print('cars already exhausted at hour {}'.format(hour))
        if cars:
            print('{} left after distributing is finished'.format(len(cars)))





def generate_work_districts_distribution():
    random_distribution_to_work = distribute_faster(total_amount_of_cars_that_are_driving_to_work_districts, 8)
    print("Amount of cars distributed to work stations: {}".format(random_distribution_to_work))
    print(
        ".............................................................................................................")

    for key, value in random_distribution_to_work.items():
        distributed_cars_to_work.append(value)

    (work_districts) = (CarsDistribution('work', [distributed_cars_to_work for x in range(num_cars)]) for num_cars in
                        distributed_cars_to_work)

    for randomWork in work_districts:
        cars_per_hour_to_work_districts.append([len(c) for c in randomWork.cars_per_hour.values()])

    for if_i_want_to_see_cars_per_hour_in_24_hours_to_work in cars_per_hour_to_work_districts:
        print(if_i_want_to_see_cars_per_hour_in_24_hours_to_work)

        print("Total amount of car that got distributed to this work station: {}".format(
            sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_work)))
        print("--------------------------------------------------------------------------------------------------")

    print("===============================WORK DISTRIBUTION FINISHED=========================================")



def generate_distributions_to_main():
    random_distribution_to_main = distribute_faster(total_amount_of_cars_that_are_driving_to_main_districts, 46)  # 46!!

    print("Amount of cars distributed to main stations: {}".format(random_distribution_to_main))
    print(
        ".............................................................................................................")

    for key, value in random_distribution_to_main.items():
        distributed_cars_to_main.append(value)

    (main_districts) = (CarsDistribution('main', [distributed_cars_to_main for x in range(num_cars)]) for num_cars in
                        distributed_cars_to_main)

    for randomMain in main_districts:
        cars_per_hour_to_main_districts.append([len(c) for c in randomMain.cars_per_hour.values()])

    for if_i_want_to_see_cars_per_hour_in_24_hours_to_main in cars_per_hour_to_main_districts:
        print(if_i_want_to_see_cars_per_hour_in_24_hours_to_main)

        print("Total amount of car that got distributed to this main station: {}".format(
            sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_main)))
        print("--------------------------------------------------------------------------------------------------")

    print("===============================MAIN DISTRIBUTION FINISHED=========================================")




def generate_hotspot_distributions():
    random_distribution_to_hotspot = distribute_faster(total_amount_of_cars_that_are_driving_to_hotspot_districts, 5)
    print("Amount of cars distributed to hotspot stations: {}".format(random_distribution_to_hotspot))
    print(
        ".............................................................................................................")

    for key, value in random_distribution_to_hotspot.items():
        distributed_cars_to_hotspot.append(value)

    (hotspot_districts) = (CarsDistribution('hotspot', [distributed_cars_to_hotspot for x in range(num_cars)]) for
                           num_cars in
                           distributed_cars_to_hotspot)

    for randomHotspot in hotspot_districts:
        cars_per_hour_to_hotspot_districts.append([len(c) for c in randomHotspot.cars_per_hour.values()])


for if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot in cars_per_hour_to_hotspot_districts:
    print(if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot)

    print("Total amount of car that got distributed to this hotspot station: {}".format(
        sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot)))
    print("--------------------------------------------------------------------------------------------------")

    print("============================HOTSPOT DISTRIBUTION FINISHED=========================================")




"---Reset the lists after used ---"
distributed_cars_to_work = []
cars_per_hour_to_work_districts = []

total_work_districts = []
all_working_districts_used = []


distributed_cars_to_main = []
cars_per_hour_to_main_districts = []

total_main_districts = []
all_the_main_districts = []


distributed_cars_to_hotspot = []
cars_per_hour_to_hotspot_districts = []

total_hotspot_districts = []
all_the_hotspot_districts = []

Может кто-нибудь помочь мне, пожалуйста? новый код выглядит великолепно, но теперь в файле main.py я получаю Typerror "объект int не повторяется"

Если я не вижу никакого решения, я, возможно, просто перенесу все в main.py, но, поскольку я хочу иметь хорошую структуру, я хочу сохранить файл Distribution.py.

Спасибо.

1 Ответ

0 голосов
/ 19 января 2019

Решено, у меня есть функция, которая вызывает все остальные функции!

вот мой код:

from random import randint

total_amount_of_cars_that_are_driving_to_work_districts = 26904
total_amount_of_cars_that_are_driving_to_main_districts = 21528
total_amount_of_cars_that_are_driving_to_hotspot_districts = 5376

cars_per_hour_to_hotspot_districts = None
cars_per_hour_to_work_districts = None
cars_per_hour_to_main_districts = None


def generate_new_data():
    create_days()
    generate_work_districts_distribution()
    generate_hotspot_distributions()
    generate_distributions_to_main()


def distribute_faster(cars, totals):
    counts = {total: 0 for total in range(totals)}
    while cars > 0:
        adjust = cars > 5000  # totally arbitrary
        change = 1
        if adjust:
            change = 5
        choice = randint(0, totals - 1)
        counts[choice] += change
        cars -= change
    return counts


def create_days():
    "----Work districts setup----"
    global distributed_cars_to_work
    distributed_cars_to_work = []
    global cars_per_hour_to_work_districts
    cars_per_hour_to_work_districts = []

    total_work_districts = []
    all_working_districts_used = []
    for amount_of_working_districts in range(0, 7):
        all_working_districts_used.append(amount_of_working_districts)

    for work_districts in all_working_districts_used:
        total_work_districts.append(work_districts)

    "----Main districts setup----"
    global distributed_cars_to_main
    distributed_cars_to_main = []
    global cars_per_hour_to_main_districts
    cars_per_hour_to_main_districts = []

    total_main_districts = []
    all_the_main_districts = []
    for amount_of_main_districts in range(0, 45):
        all_the_main_districts.append(amount_of_main_districts)
    for main_districts in all_the_main_districts:
        total_main_districts.append(main_districts)

    "----Hotspot district setup----"
    global distributed_cars_to_hotspot
    distributed_cars_to_hotspot = []
    global cars_per_hour_to_hotspot_districts
    cars_per_hour_to_hotspot_districts = []

    total_hotspot_districts = []
    all_the_hotspot_districts = []
    for amount_of_hotspot_districts in range(0, 4):
        all_the_hotspot_districts.append(amount_of_hotspot_districts)

    for hotspot_districts in all_the_hotspot_districts:
        total_hotspot_districts.append(hotspot_districts)


def generate_work_districts_distribution():
    random_distribution_to_work = distribute_faster(total_amount_of_cars_that_are_driving_to_work_districts, 8)
    print("Amount of cars distributed to work stations: {}".format(random_distribution_to_work))
    print(
        ".............................................................................................................")

    for key, value in random_distribution_to_work.items():
        distributed_cars_to_work.append(value)

    (work_districts) = (CarsDistribution('work', [distributed_cars_to_work for x in range(num_cars)]) for num_cars in
                        distributed_cars_to_work)

    for randomWork in work_districts:
        cars_per_hour_to_work_districts.append([len(c) for c in randomWork.cars_per_hour.values()])

    for if_i_want_to_see_cars_per_hour_in_24_hours_to_work in cars_per_hour_to_work_districts:
        print(if_i_want_to_see_cars_per_hour_in_24_hours_to_work)

        print("Total amount of car that got distributed to this work station: {}".format(
            sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_work)))
        print("--------------------------------------------------------------------------------------------------")

    print("===============================WORK DISTRIBUTION FINISHED=========================================")


def generate_distributions_to_main():
    random_distribution_to_main = distribute_faster(total_amount_of_cars_that_are_driving_to_main_districts, 46)  # 46!!

    print("Amount of cars distributed to main stations: {}".format(random_distribution_to_main))
    print(
        ".............................................................................................................")

    for key, value in random_distribution_to_main.items():
        distributed_cars_to_main.append(value)

    (main_districts) = (CarsDistribution('main', [distributed_cars_to_main for x in range(num_cars)]) for num_cars in
                        distributed_cars_to_main)

    for randomMain in main_districts:
        cars_per_hour_to_main_districts.append([len(c) for c in randomMain.cars_per_hour.values()])

    for if_i_want_to_see_cars_per_hour_in_24_hours_to_main in cars_per_hour_to_main_districts:
        print(if_i_want_to_see_cars_per_hour_in_24_hours_to_main)

        print("Total amount of car that got distributed to this main station: {}".format(
            sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_main)))
        print("--------------------------------------------------------------------------------------------------")

    print("===============================MAIN DISTRIBUTION FINISHED=========================================")


def generate_hotspot_distributions():
    random_distribution_to_hotspot = distribute_faster(total_amount_of_cars_that_are_driving_to_hotspot_districts, 5)
    print("Amount of cars distributed to hotspot stations: {}".format(random_distribution_to_hotspot))
    print(
        ".............................................................................................................")

    for key, value in random_distribution_to_hotspot.items():
        distributed_cars_to_hotspot.append(value)

    (hotspot_districts) = (CarsDistribution('hotspot', [distributed_cars_to_hotspot for x in range(num_cars)]) for
                           num_cars in distributed_cars_to_hotspot)

    for randomHotspot in hotspot_districts:
        cars_per_hour_to_hotspot_districts.append([len(c) for c in randomHotspot.cars_per_hour.values()])

    for if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot in cars_per_hour_to_hotspot_districts:
        print(if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot)

        print("Total amount of car that got distributed to this hotspot station: {}".format(
            sum(if_i_want_to_see_cars_per_hour_in_24_hours_to_hotspot)))
        print("--------------------------------------------------------------------------------------------------")

    print("============================HOTSPOT DISTRIBUTION FINISHED=========================================")


class CarsDistribution:
    all_probabilities = {
        "work":
        # Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
            (0.0, 0.0, 0.0, 0.0, 0.01, 0.05, 0.11, 0.19, 0.23, 0.2, 0.14, 0.05, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
             0.0, 0.0, 0.0, 0.0, 0.0),
        "main":
        # Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
            (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.01, 0.01, 0.02, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.08, 0.08,
             0.08, 0.07, 0.06, 0.06, 0.05, 0.04),
        "hotspot":
        # Hour:0      1      2     3      4     5      6      7      8      9     10     11    12    13     14     15    16    17    18     19    20     21      22     23      24
            (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.01, 0.02, 0.03, 0.04, 0.08, 0.1, 0.12, 0.13, 0.13, 0.11,
             0.07, 0.05, 0.04, 0.03, 0.02, 0.01)

    }

    def __init__(self, type, cars):
        total_length = len(cars)
        self.cars_per_hour = {}
        for hour, p in enumerate(self.all_probabilities[type]):
            try:
                self.cars_per_hour[hour] = [cars.pop() for i in range(int(p * total_length))]
            except IndexError:
                print('cars already exhausted at hour {}'.format(hour))
        if cars:
            print('{} left after distributing is finished'.format(len(cars)))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...