Skip to content

Commit

Permalink
Plants removed (#41)
Browse files Browse the repository at this point in the history
* Plotting scripts

* Tests cleared

* Player tests

* Plant price change

* Add lock

* Lock test fixes

* More tests

* Add rate limiting.
  • Loading branch information
nitko12 authored Feb 24, 2024
1 parent b4177dd commit 6f40a3c
Show file tree
Hide file tree
Showing 31 changed files with 471 additions and 653 deletions.
3 changes: 2 additions & 1 deletion backend/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ max_energy_per_player: 0.2

power_plant:
resources_per_tick: 1
sell_coeff: 0.5
price_coeff: 0.5
sell_coeff: 0.7

base_prices:
coal: 3000
Expand Down
89 changes: 48 additions & 41 deletions backend/db/migration.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import pandas as pd
from db.db import database
from model import Team, Player, PowerPlant, PowerPlantType, Game, Datasets, DatasetData
from model import Team, Player, Game, Datasets, DatasetData
from datetime import datetime
from config import config
from logger import logger
Expand All @@ -17,38 +17,36 @@ async def fill_tables():
dataset_id = datasets[0].dataset_id

not_nat_game_id = await Game.create(
game_name="Stalna igra",
is_contest=False,
bots="dummy:3;resource_bot:1",
dataset_id=dataset_id,
game_name="Stalna igra",
is_contest=False,
bots="dummy:3;resource_bot:1",
dataset_id=dataset_id,
start_time=datetime.now(),
total_ticks=2300,
tick_time=3000)
nat_game_id = await Game.create(
game_name="Natjecanje",
is_contest=True,
bots="dummy:2;resource_bot:1",
dataset_id=dataset_id,
start_time=datetime.now(),
total_ticks=100,
game_name="Natjecanje",
is_contest=True,
bots="dummy:2;resource_bot:1",
dataset_id=dataset_id,
start_time=datetime.now(),
total_ticks=100,
tick_time=1000)

for game_id in [not_nat_game_id, nat_game_id]:
await Player.create(player_name="Goran", is_active=True, is_bot=False, game_id=game_id, team_id=g_team_id, money=15000, coal=1000)
await Player.create(player_name="Kruno", is_active=True, is_bot=False, game_id=game_id, team_id=k_team_id)
await Player.create(player_name="Zvone", is_active=True, is_bot=False, game_id=game_id, team_id=z_team_id)

await PowerPlant.create(type=PowerPlantType.COAL, player_id=1, price=1, powered_on=True)

logger.info("Filled database with dummy data")


async def delete_tables():
await database.execute('TRUNCATE power_plants, orders, players, games, teams, market, datasets, dataset_data CASCADE')
await database.execute('TRUNCATE orders, players, games, teams, market, datasets, dataset_data CASCADE')


async def drop_tables():
for table_name in ["power_plants", "orders", "players", "games", "teams", "market", "datasets", "dataset_data"]:
for table_name in ["orders", "players", "games", "teams", "market", "datasets", "dataset_data"]:
await database.execute(f'DROP TABLE IF EXISTS {table_name} CASCADE')


Expand Down Expand Up @@ -101,22 +99,31 @@ async def run_migrations():
biomass INT NOT NULL DEFAULT 0,
gas INT NOT NULL DEFAULT 0,
oil INT NOT NULL DEFAULT 0,
coal_plants_owned INT NOT NULL DEFAULT 0,
uranium_plants_owned INT NOT NULL DEFAULT 0,
biomass_plants_owned INT NOT NULL DEFAULT 0,
gas_plants_owned INT NOT NULL DEFAULT 0,
oil_plants_owned INT NOT NULL DEFAULT 0,
geothermal_plants_owned INT NOT NULL DEFAULT 0,
wind_plants_owned INT NOT NULL DEFAULT 0,
solar_plants_owned INT NOT NULL DEFAULT 0,
hydro_plants_owned INT NOT NULL DEFAULT 0,
coal_plants_powered INT NOT NULL DEFAULT 0,
uranium_plants_powered INT NOT NULL DEFAULT 0,
biomass_plants_powered INT NOT NULL DEFAULT 0,
gas_plants_powered INT NOT NULL DEFAULT 0,
oil_plants_powered INT NOT NULL DEFAULT 0,
geothermal_plants_powered INT NOT NULL DEFAULT 0,
wind_plants_powered INT NOT NULL DEFAULT 0,
solar_plants_powered INT NOT NULL DEFAULT 0,
hydro_plants_powered INT NOT NULL DEFAULT 0,
FOREIGN KEY (game_id) REFERENCES games(game_id),
FOREIGN KEY (team_id) REFERENCES teams(team_id)
)''')

await database.execute('''
CREATE TABLE IF NOT EXISTS power_plants (
power_plant_id SERIAL PRIMARY KEY,
type INT NOT NULL,
player_id INT NOT NULL,
price INT NOT NULL,
powered_on BOOLEAN NOT NULL DEFAULT false,
temperature REAL NOT NULL DEFAULT 0,
FOREIGN KEY (player_id) REFERENCES players(player_id)
)''')

await database.execute('''
CREATE TABLE IF NOT EXISTS orders (
order_id SERIAL PRIMARY KEY,
Expand Down Expand Up @@ -208,21 +215,21 @@ async def run_migrations():
i = 0
for index, row in df.iterrows():
await DatasetData.create(dataset_id=dataset_id,
tick=i,
date=datetime.strptime(
row["date"], "%Y-%m-%d %H:%M:%S"),
coal=row["COAL"],
uranium=row["URANIUM"],
biomass=row["BIOMASS"],
gas=row["GAS"],
oil=row["OIL"],
geothermal=row["GEOTHERMAL"],
wind=row["WIND"],
solar=row["SOLAR"],
hydro=row["HYDRO"],
energy_demand=row["ENERGY_DEMAND"],
max_energy_price=row["MAX_ENERGY_PRICE"]
)
tick=i,
date=datetime.strptime(
row["date"], "%Y-%m-%d %H:%M:%S"),
coal=row["COAL"],
uranium=row["URANIUM"],
biomass=row["BIOMASS"],
gas=row["GAS"],
oil=row["OIL"],
geothermal=row["GEOTHERMAL"],
wind=row["WIND"],
solar=row["SOLAR"],
hydro=row["HYDRO"],
energy_demand=row["ENERGY_DEMAND"],
max_energy_price=row["MAX_ENERGY_PRICE"]
)
i += 1
logger.info(f"Added dataset {x}")
logger.info("Migrated database")
25 changes: 2 additions & 23 deletions backend/game/fixtures/fixtures.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from pprint import pprint
import pandas as pd
from game.tick import TickData, Ticker
from game.tick.ticker import GameData
from model import Order, Player, Resource, Game, PowerPlant, PowerPlantType, OrderSide
from model import Order, Player, Resource, Game, PowerPlantType, OrderSide
from game.market import ResourceMarket, EnergyMarket
import pytest
from model.dataset_data import DatasetData
Expand Down Expand Up @@ -73,7 +72,7 @@ def get_ticker(players) -> Ticker:

@pytest.fixture
def get_tick_data(game_id):
def get_tick_data(power_plants, markets, players, user_cancelled_orders=[], pending_orders=[], updated_orders=[], coal=100, energy_demand=100, max_energy_price=100) -> TickData:
def get_tick_data(markets, players, user_cancelled_orders=[], pending_orders=[], updated_orders=[], coal=100, energy_demand=100, max_energy_price=100) -> TickData:
tick_data = TickData(
game=Game(
game_id=game_id,
Expand Down Expand Up @@ -103,7 +102,6 @@ def get_tick_data(power_plants, markets, players, user_cancelled_orders=[], pend
energy_demand=energy_demand,
max_energy_price=max_energy_price
),
power_plants=power_plants,
markets=markets,
players=players,
user_cancelled_orders=user_cancelled_orders,
Expand Down Expand Up @@ -190,25 +188,6 @@ def energy_market():
return EnergyMarket()


@pytest.fixture
def get_power_plant():
plant_id = 0

def get_power_plant(player_id: int, type: PowerPlantType, powered_on: int = True, **kwargs):
nonlocal plant_id
power_plant = PowerPlant(
power_plant_id=plant_id,
player_id=player_id,
type=type,
price=100,
powered_on=powered_on,
**kwargs
)
plant_id += 1
return power_plant
return get_power_plant


@pytest.fixture
def get_energy_market():
def get_energy_market() -> EnergyMarket:
Expand Down
1 change: 0 additions & 1 deletion backend/game/market/energy_market.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from model.order import Order
from config import config
from model.player import Player
from model.power_plant import PowerPlant


class EnergyMarket:
Expand Down
1 change: 0 additions & 1 deletion backend/game/market/resource_market.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from pprint import pprint
from game.orderbook.orderbook import OrderBook
from game.price_tracker.price_tracker import PriceTracker
from model import Resource, Trade, Order
Expand Down
1 change: 0 additions & 1 deletion backend/game/market/test_resource_market.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from pprint import pprint
from model import Order, Player, OrderSide, OrderStatus
from . import ResourceMarket, EnergyMarket
from game.fixtures.fixtures import *
Expand Down
25 changes: 4 additions & 21 deletions backend/game/tick/test_tick_fixtures.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import datetime
import pytest
from game.tick import TickData, Ticker, GameData
from model import Game, Player, PowerPlant, Order, OrderStatus, Resource
from model import Game, Player, Order, OrderStatus, Resource


@pytest.fixture
Expand All @@ -23,8 +23,8 @@ def sample_game():
@pytest.fixture
def sample_players():
return {
1: Player(player_id=1, game_id=1, player_name="Player 1", energy=0, team_id=1),
2: Player(player_id=2, game_id=1, player_name="Player 2", energy=0, team_id=1)
1: Player(player_id=1, game_id=1, player_name="Player 1", energy=0, team_id=1, wind_plants_owned=2, wind_plants_powered=2),
2: Player(player_id=2, game_id=1, player_name="Player 2", energy=0, team_id=1, coal=100, coal_plants_powered=2, coal_plants_owned=2)
}


Expand All @@ -36,22 +36,6 @@ def ticker(sample_game, sample_players):
return t


@pytest.fixture
def sample_power_plants():
return {
1: [
PowerPlant(power_plant_id=1, player_id=1, type=1, price=100,
temperature=0.5, powered_on=True),
PowerPlant(power_plant_id=2, player_id=1, type=2, price=100,
temperature=0.6, powered_on=True)
],
2: [
PowerPlant(power_plant_id=3, player_id=2, type=1, price=100,
temperature=0.7, powered_on=True)
]
}


@pytest.fixture
def sample_pending_orders():
return [
Expand All @@ -74,15 +58,14 @@ def sample_user_cancelled_orders():

@pytest.fixture
def sample_dataset_row():
return {"energy_demand": 100, "max_energy_price": 50}
return {"energy_demand": 100, "max_energy_price": 50, "coal": 100, "oil": 100, "uranium": 100, 'biomass': 100, 'gas': 100, 'geothermal': 100, 'solar': 100, 'wind': 100, 'hydro': 100}


@pytest.fixture
def tick_data(sample_game, sample_players):
return TickData(
game=sample_game,
players=sample_players,
power_plants={},
markets={},
bots=[],
dataset_row={},
Expand Down
5 changes: 3 additions & 2 deletions backend/game/tick/test_ticker_bots.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ async def test_run_bots(get_tick_data):

# Set the bots for the game
ticker.game_data[game.game_id] = GameData(game, players)
tick_data = get_tick_data(power_plants={}, markets={}, players={})
tick_data = get_tick_data(markets={}, players={})

# Run the method being tested
await ticker.run_bots(tick_data)

# Assertions
# Ensure Bot.run is called once for each bot
assert mock_run.call_count == len(bots)
mock_run.assert_called_with(tick_data) # Ensure Bot.run is called with no arguments
# Ensure Bot.run is called with no arguments
mock_run.assert_called_with(tick_data)
54 changes: 32 additions & 22 deletions backend/game/tick/test_ticker_db_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,45 @@
from unittest.mock import patch
from datetime import datetime
from model import Order, OrderStatus, Resource
from model.dataset_data import DatasetData
from model.order_types import OrderSide, OrderType
from game.tick import Ticker, TickData
from tick.test_tick_fixtures import *


@patch('model.Player.list')
@patch('model.PowerPlant.list')
@patch('model.Order.list')
@patch('model.DatasetData.get')
@pytest.mark.asyncio
async def test_get_tick_data(mock_dataset_get, mock_order_list, mock_powerplant_list, mock_player_list, ticker, sample_game, sample_players, sample_power_plants, sample_pending_orders, sample_user_cancelled_orders, sample_dataset_row):
mock_player_list.return_value = sample_players.values()
mock_powerplant_list.side_effect = lambda player_id: sample_power_plants[player_id]
mock_order_list.side_effect = lambda **kwargs: sample_pending_orders if kwargs.get(
"order_status") == OrderStatus.PENDING else sample_user_cancelled_orders
mock_dataset_get.return_value = sample_dataset_row
async def test_get_tick_data(sample_game, sample_players, sample_pending_orders, sample_user_cancelled_orders, sample_dataset_row):
# Setup ticker
ticker = Ticker()
ticker.game_data[sample_game.game_id] = GameData(
sample_game, sample_players)

tick_data = await ticker.get_tick_data(sample_game)
# Mocking database interaction
async def mock_list_players(*args, **kwargs):
return [sample_players[1], sample_players[2]]

assert len(tick_data.players) == len(sample_players)
assert len(tick_data.power_plants) == len(sample_power_plants)
assert len(tick_data.pending_orders) == len(sample_pending_orders)
assert len(tick_data.user_cancelled_orders) == len(
sample_user_cancelled_orders)
assert tick_data.dataset_row == sample_dataset_row
async def mock_list_orders(*args, **kwargs):
if kwargs.get('order_status') == OrderStatus.PENDING:
return sample_pending_orders
elif kwargs.get('order_status') == OrderStatus.USER_CANCELLED:
return sample_user_cancelled_orders

async def mock_get_dataset_data(*args, **kwargs):
return sample_dataset_row

with patch('model.Player.list', new=mock_list_players), patch('model.Order.list', new=mock_list_orders), patch('model.DatasetData.get', new=mock_get_dataset_data):
# Execute get_tick_data method
tick_data = await ticker.get_tick_data(sample_game)

# Assertions
assert len(tick_data.players) == 2
# Assuming 2 pending orders in sample_pending_orders fixture
assert len(tick_data.pending_orders) == 2
# Assuming 2 user cancelled orders in sample_user_cancelled_orders fixture
assert len(tick_data.user_cancelled_orders) == 2
assert tick_data.dataset_row == sample_dataset_row
# Assuming all resources have markets created
assert len(tick_data.markets) == len(Resource)


@pytest.fixture
Expand All @@ -41,14 +55,12 @@ def sample_update_orders():


@patch('model.Player.update')
@patch('model.PowerPlant.update')
@patch('model.Order.update')
@pytest.mark.asyncio
async def test_save_tick_data(mock_order_update, mock_powerplant_update, mock_player_update, ticker, sample_game, sample_players, sample_power_plants, sample_pending_orders, sample_user_cancelled_orders, sample_dataset_row, sample_update_orders):
async def test_save_tick_data(mock_order_update, mock_player_update, ticker, sample_game, sample_players, sample_pending_orders, sample_user_cancelled_orders, sample_dataset_row, sample_update_orders):
tick_data = TickData(
game=sample_game,
players=sample_players,
power_plants=sample_power_plants,
pending_orders=sample_pending_orders,
user_cancelled_orders=sample_user_cancelled_orders,
dataset_row=sample_dataset_row,
Expand All @@ -60,8 +72,6 @@ async def test_save_tick_data(mock_order_update, mock_powerplant_update, mock_pl
await ticker.save_tick_data(tick_data)

assert mock_player_update.call_count == len(sample_players)
assert mock_powerplant_update.call_count == len(sample_power_plants[1]) + len(
sample_power_plants[2])
assert mock_order_update.call_count == len(sample_update_orders)


Expand Down
Loading

0 comments on commit 6f40a3c

Please sign in to comment.