В ситуациях стихийных бедствий/явлений могут возникнуть отключения. Чтобы бороться с этим, водители EV (электромобили) могут использовать свои транспортные средства в качестве батареи для клиентов/ клиентов. Чтобы смоделировать сложность этой проблемы, добравшись до как можно большего количества клиентов до тех пор, пока не закончится период отключения, была создана среда RL. В этой среде представлены случайные сценарии, основанные на размере сети узлов, количестве домов (не могут быть больше, чем размер узлов), данные затемнения и модели корпуса для моделирования отклика отключения ответа в веществе высокого уровня.

Пример случайного агента в действии.
Нагрузка представляет мощность, необходимую в данный момент от узла.
Текущий заряд представляет мощность, которую обладает агентом (или автомобилем).
Значения по краям представляют собой мили края, чтобы пройти.
Синий узел представляет буферы. Зеленый узел представляет дома. Серый узел представляет узел Blackout Out.
Более подробную информацию можно найти в разделе «Действие и пространство состояний».
Клонировать проект
git clone https://github.com/Natemen96/ECEMasterProject.gitПерейти в каталог проекта
cd ECEMasterProject/RL python main.py Предупреждение: это большая установка (~ 2 ГБ), и она займет около 30 минут в зависимости от скорости в Интернете. В зависимости от вашей настройки, вам может быть проще установить пакет самостоятельно. Список можно найти в папке conda_env . См. 'Conda_env/rl_window.yml' для самого современного списка пакетов. Работает лучше всего на Windows.
Для легкой установки, используя Conda First, убедитесь, что у вас установлена Conda.
После установки Conda выполните следующее, чтобы настроить среду
conda env create -f conda_env/rl_window.yml --name rl_env # or any name you prefer
conda activate rl_env # verify it work Обязательно запустите программу в рамках Conda Env.
Данные жилья могут быть загружены с Pecan Street/DataPort
Начните с «Дома» (узел). Путешествие в каждое место в обмен на питание (основной ресурс для EV), разгрузить питание в обмен на вознаграждение, отправляйтесь обратно домой в обмен на питание. Агент может восстановить власть в «доме» и получить больше вознаграждения в зависимости от того, сколько энергии он получил. Чем больше власти он восстанавливает для себя, тем больше он вознагражден.
После восстановления питания в узле с зарядной станцией питания, агент также может восстановить энергию там. Некоторые узлы будут пустыми в зависимости от параметров.
graph_env: Randomly generated a fully connected graph n nodes
Args:
n (int, optional): [number of nodes]. Defaults to 5.
numofhome (int, optional): [number of homes for agent starting
point]. Defaults to 1.
numofblackout (int, optional): [number of houses with blackout].
Defaults to 1.
numofblackoutws (int, optional): [number of blackout houses with
solarpower]. Defaults to 0.
numofchargingstation (int, optional): [number of charging
station]. Defaults to 0.
max_actions (int, optional): [max number of action can be done
times 7. By default 3 (7) = 21]. Defaults to 3.
blackout_str (str, optional): [Reads Blackout data from npy
file. Blackout data from the 2021 Texas Power Crisis, a file for
each country]. Defaults to 'Brazoria'.
agents (list, optional): [Agent objects]. Defaults to [None].
nonsolarhouse_data_paths (list, optional): [Path for npy file
with nonsolar data info. Added to a node per path.]. Defaults to
[None].
solarhouse_data_paths (list, optional): [Path for npy file with
solarhouse data info. Added to a node per path.]. Defaults to
[None].
data_sample (int, optional): [how many data sample it take from
data in paths, samples taken evenly throughout data. By default
(0/6. 1/6 ... 6/6 0/6 ...) sample]. Defaults to 6.BasicAgent: Basic Agent that act as skeleton for other agent. Won't work by itself.
Args:
car ([dict]): [car information in the form of a python
dictionary. Required dict information: model, make, year,
avg_energy_consumption(kWh/mile), battery_capacity(kWh)]SmartQLAgent: Smart Agent that uses Qtable to make decisions
Args:
car ([dict]): [car information in the form of a python
dictionary. Required dict information: model, make, year,
avg_energy_consumption(kWh/mile), battery_capacity(kWh)]
sample_rate (int, optional): [decides how often a sample of the
qtable is taken. If left to default it's every 1/100 of total ep]
. Defaults to 100.
qtabletraining (bool, optional): [Flag for turning qtable
training on]. Defaults to True.
quiet (bool, optional): [Flag for turning data collection on].
Defaults to True.RandomDataAgent: Used for data collection of random agent. Doesn't
use Observation.
Args:
car ([dict]): [car information in the form of a python
dictionary. Required dict information: model, make, year,
avg_energy_consumption(kWh/mile), battery_capacity(kWh)]Награда, предоставленная за разгрузку, перезарядка. Разнообразие восстановления власти приведет к большей награде. Награда потеряна за то, что заканчивается энергией. Эпизод закончился, когда EV не является энергией, или сеть полностью питается.
Each Agent will have 24 actions per ep by default.
e+2 Actions:
e - Move (at cost) to Node if possible
1 - Unload (at cost)
1 - Recharge (no cost, expect an action)
2 * n + 6 * n + 300 * n + c States:
n - Statuses of Each Node
Key - Assignment
0 - Buffer (Blue)
1 - Blackout (Darkgrey)
2 - Blackout with Solar (Lightgrey)
3 - Powered (Blue)
4 - Charging Station (Yellow)
5 - Home (Green)
n - Cost of each edge
n - Is the path reachable or not?
0 - No
1 - Yes
c - Charge State (400 possible values by default)
where n is the number of nodes states, e is the number of edges, and c number of is Charge states Каждое узлы были разработаны, чтобы основываться на наборе данных дома. В некоторых домах солнечные батареи будут потребоваться меньше энергии от электромобилей по сравнению с несолярными домами. Стоимость домашнего узла может быть получена из данных жилья.
Процент затемнения на основе данных Blackout Texas, а также изменения в день.
Как минимум, Q-обучение использовалось для поиска лучших решений.
Может быть масштабирован до нескольких EV (MARL понадобится) и более крупную сеть. Marl не был полностью протестирован и, вероятно, очень глюка.
Во время тестового прогона 50K EPS смарт -агент, который поддерживал QTables, имел улучшение 263,13% по сравнению со случайным агентом (который выполняет случайные действия).
scripts/Data/TexasBlackout.csv
-csv file of data collected from https://poweroutage.us/area/state/texas during the 2021 Texas Power Crisis with the following
- Metrics: ID,County,Customers Tracked,Customers Out,Outage %,DateTime
ECEMasterProject/RL/Data/
Avg_House_0/
- npy files of average daily power per every 15 mins of various houses provide by Dataport
Avg_House_1/
- npy files of next day regression of Avg_House_0 per house
Avg_House_n/
- npy files of concatenation of Avg_House_0 adn Avg_House_1 per houses
County/
- npy files of Texas County that were effect the most during the 2021 Texas Power Crisis
RL/agent/Sim_Data
- csv file result from various RL training, only stored reward.
RL/agent/agent_jsons/
-various json file of EV information
-Metrics: model, make, year, avg_energy_consumption(kWh/mile), battery_capacity(kWh), source
models/
KM/
-Classifier models trained using Time Series K Means stored in h5
LSTM/
-Old LSTM regression model trained on one house stored in h5
LSTM_nonsolar/
-LSTM regression model trained on non solar data stored in h5
LSTM_solar/
-LSTM regression model trained on solar data stored in h5
Qtables/
-Qtables from RL training stored in h5
notebooks/
analysis_c0.ipynb
-Analysis of classifier and regression model on solar houses data
analysis_c1.ipynb
-Analysis of classifier and regression model on nonsolar houses data
cluster.ipynb
-Creation and Analysis of classifier that can distinguish between solar and nonsolar data
compare_qtable_analyis.ipynb
-Comparing Qtable Smart Agent with Random Agent Baseline
D_LSTM_HousingData.ipynb
-Creation and analysis of regression on avg housing data where the original data sample occurs every 15 mins -> 98 sample per day
Dp1_analysis.ipynb
-Creation and analysis of regression on one house
EveryNyHouseAvg.ipynb
-Creation and analysis of regression on all house samples with model trained on one house (house 1)
LSTM_cluster0.ipynb
-Creation and analysis of regression on one house using most of the solar housing data
LSTM_cluster1.ipynb
-Creation and analysis of regression on one house using most of the nonsolar housing data
qtable_analyis_4_19.ipynb
-Analysis of Smart Agents performance
qtable_analyis_4_22.ipynb
-Analysis of Smart Agents performance
qtable_analyis.ipynb
-Analysis of Smart Agents performance
random_agent_analyis.ipynb
-Analysis of Random Agents performance
Texas_Blackout.ipynb
-Analysis of recorded Blackout DataНекоторые края могут быть заблокированы и восстановлены позже, как пропущенные дни (симулировать для стихийных бедствий)
Добавить тестирование
DRL и классические методы оптимизации
Отладка для Marl
Преобразовать в Environment
Узнал больше о создании моделей DL/ML.
Узнал больше об анализе данных из изучения данных и результатов обучения DL/ML.
Узнал о NetworkX и его возможностях для теории графиков, связанной с проектами.
Узнал больше о создании подкрепления среды обучения и агентов.
Узнал больше о скребке данных, так как мне нужно было отказаться от Blapout Data во время кризиса в Техасе 2021 года.
Научился сделать GIF, используя изображения в Python.
Спасибо профессору Цинь из моей Alma Mater, Университета Пердью за его удивительную поддержку и поделился своим опытом для этого проекта.
Спасибо DataPort и Pecan Street за предоставление данных жилья для создания моделей.
Спасибо Мэтту Ликоку, создателю настольной игры, пандемии за вдохновляющую эту среду обучения подкрепления.