Skip to content

Commit

Permalink
minor bugs corrections
Browse files Browse the repository at this point in the history
  • Loading branch information
Yassir Akram committed Nov 25, 2024
1 parent 0d5e957 commit f139d32
Show file tree
Hide file tree
Showing 14 changed files with 81 additions and 87 deletions.
12 changes: 6 additions & 6 deletions website/api/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,18 +203,18 @@ def concat_slices(dict1, dict2):
if current_user.tile is None:
return "", 404
total_t = g.engine.data["total_t"]
history = current_user.history.get_data(t=total_t % 216 + 1)
rolling_history = current_user.data.rolling_history.get_data(t=total_t % 216 + 1)
filename = f"instance/player_data/player_{current_user.id}.pck"
with open(filename, "rb") as file:
data = pickle.load(file)
concat_slices(data, history)
concat_slices(data, rolling_history)

network_data = None
if current_user.network is not None:
filename = f"instance/network_data/{current_user.network.id}/time_series.pck"
with open(filename, "rb") as file:
network_data = pickle.load(file)
concat_slices(network_data, current_user.network.history.get_data(t=total_t % 216 + 1))
concat_slices(network_data, current_user.network.data.rolling_history.get_data(t=total_t % 216 + 1))

current_climate_data = g.engine.data["current_climate_data"].get_data(t=total_t % 216 + 1)
with open("instance/server_data/climate_data.pck", "rb") as file:
Expand All @@ -227,7 +227,7 @@ def concat_slices(dict1, dict2):
"data": data,
"network_data": network_data,
"climate_data": climate_data,
"cumulative_emissions": current_user.cumul_emissions.get_all(),
"cumulative_emissions": current_user.data.cumul_emissions.get_all(),
}
)

Expand All @@ -243,7 +243,7 @@ def get_network_capacities():
"""gets the network capacities for the current player"""
if current_user.network is None:
return "", 404
return jsonify(current_user.network.capacities.get_all())
return jsonify(current_user.network.data.capacities.get_all())


@http.route("/get_market_data", methods=["GET"])
Expand All @@ -270,7 +270,7 @@ def get_player_data():
if current_user.tile is None:
return "", 404
levels = current_user.get_lvls()
capacities = current_user.capacities.get_all()
capacities = current_user.data.capacities.get_all()
return jsonify(
{
"levels": levels,
Expand Down
2 changes: 1 addition & 1 deletion website/api/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def combine_file_data_and_engine_data(file_data, engine_data):
def industry_data_for(category, subcategory):
return combine_file_data_and_engine_data(
file_data[category][subcategory],
g.player.data.history[category][subcategory],
g.player.data.rolling_history[category][subcategory],
)

subcategories = {
Expand Down
2 changes: 1 addition & 1 deletion website/database/engine_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def update(self, player, facility):
effective_values["pollution"] += base_data["base_pollution"] * facility.multiplier_3

if player.network is not None:
player.network.capacities.update_network(player.network)
player.network.data.capacities.update_network(player.network)

def update_network(self, network):
"""This function updates the capacity data of the network"""
Expand Down
42 changes: 19 additions & 23 deletions website/database/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@

@dataclass
class PlayerData(object):
history: CircularBufferPlayer
rolling_history: CircularBufferPlayer
capacities: CapacityData
cumul_emissions: CumulativeEmissionsData

Expand Down Expand Up @@ -207,6 +207,8 @@ def data(self) -> PlayerData:

@cached_property
def cache(self) -> PlayerCache:
if self.id not in current_app.config["engine"].buffered["by_player"]:
current_app.config["engine"].buffered["by_player"][self.id] = PlayerCache(self.id)
return current_app.config["engine"].buffered["by_player"][self.id]

@property
Expand Down Expand Up @@ -398,7 +400,7 @@ def send_new_data(self, new_values):
"total_t": engine.data["total_t"],
"chart_values": new_values,
"climate_values": engine.data["current_climate_data"].get_last_data(),
"cumulative_emissions": self.cumul_emissions.get_all(),
"cumulative_emissions": self.data.cumul_emissions.get_all(),
"money": self.money,
},
)
Expand Down Expand Up @@ -445,7 +447,7 @@ def notify(self, title, message):

def calculate_net_emissions(self):
"""Calculates the net emissions of the player"""
cumulative_emissions = self.cumul_emissions.get_all()
cumulative_emissions = self.data.cumul_emissions.get_all()
net_emissions = 0
for value in cumulative_emissions.values():
net_emissions += value
Expand Down Expand Up @@ -677,15 +679,15 @@ def invalidate_recompute_and_dispatch_data_for_pages(
Signal to all instances of clients for this player that there is possibly new data for the specified page.
This function will invalidate the data for all corresponding arguments that are set to True.
"""
if power_facilities:
if power_facilities and "power_facilities_data" in self.cache.__dict__:
del self.cache.power_facilities_data
if storage_facilities:
if storage_facilities and "storage_facilities_data" in self.cache.__dict__:
del self.cache.storage_facilities_data
if extraction_facilities:
if extraction_facilities and "extraction_facility_data" in self.cache.__dict__:
del self.cache.extraction_facility_data
if functional_facilities:
if functional_facilities and "functional_facilities_data" in self.cache.__dict__:
del self.cache.functional_facilities_data
if technologies:
if technologies and "technologies_data" in self.cache.__dict__:
del self.cache.technologies_data
# if resource_market:
# self._buffered_data_for_resource_market_page = None
Expand All @@ -708,28 +710,22 @@ def invalidate_recompute_and_dispatch_data_for_pages(
# TODO: update clients over websocket


@dataclass
class NetworkData(object):
rolling_history: CircularBufferNetwork
capacities: CapacityData


class Network(db.Model):
"""class that stores the networks of players"""

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
members = db.relationship("Player", backref="network")

@property
def history(self) -> CircularBufferNetwork:
return current_app.config["engine"].data["by_network"][self.id]["history"]

@history.setter
def history(self, value):
current_app.config["engine"].data["by_network"][self.id]["history"] = value

@property
def capacities(self) -> CapacityData:
return current_app.config["engine"].data[type(self).__name__][self.id]["capacities"]

@capacities.setter
def capacities(self, value):
current_app.config["engine"].data[type(self).__name__][self.id]["capacities"] = value
@cached_property
def data(self) -> NetworkData:
return current_app.config["engine"].data["by_network"][self.id]


class PlayerUnreadMessages(db.Model):
Expand Down
8 changes: 4 additions & 4 deletions website/game_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@

from gevent.lock import RLock

from website.database.player import PlayerCache, PlayerData
from website.database.player import NetworkData, PlayerData
from website.database.player_assets import OngoingConstructionCache

from .config.assets import config, const_config
from .database.engine_data import CircularBufferNetwork, EmissionData
from .database.engine_data import EmissionData


# This is the engine object
Expand Down Expand Up @@ -152,9 +152,9 @@ def __init__(self, clock_time, in_game_seconds_per_tick, random_seed, start_date
self.lock = RLock()
self.data = {}
self.data["by_player"] = defaultdict(PlayerData)
self.data["by_network"] = defaultdict(CircularBufferNetwork)
self.data["by_network"] = defaultdict(NetworkData)
self.buffered = {} # stores buffered values for mixed_database
self.buffered["by_player"] = defaultdict(PlayerCache)
self.buffered["by_player"] = {}
self.buffered["by_ongoing_construction"] = defaultdict(OngoingConstructionCache)
self.data["random_seed"] = random_seed
self.data["total_t"] = 0 # Number of simulated game ticks since server start
Expand Down
20 changes: 10 additions & 10 deletions website/production_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def update_electricity(engine):
for player in players:
if player.tile is None:
continue
new_values[player.id] = player.data.history.init_new_data()
new_values[player.id] = player.data.rolling_history.init_new_data()

for network in networks:
market = init_market()
Expand All @@ -56,7 +56,7 @@ def update_electricity(engine):
"generation": market["generation"],
"consumption": market["consumption"],
}
network.history.append_value(new_network_values)
network.data.rolling_history.append_value(new_network_values)
for player in network.members:
player.emit(
"new_network_values",
Expand All @@ -82,7 +82,7 @@ def update_electricity(engine):
calculate_net_import(new_values[player.id])
update_storage_lvls(engine, new_values[player.id], player)
resources_and_pollution(engine, new_values[player.id], player)
player.data.history.append_value(new_values[player.id])
player.data.rolling_history.append_value(new_values[player.id])
# add industry revenues to player money
player.money += new_values[player.id]["revenues"]["industry"]
update_player_progress_values(engine, player, new_values)
Expand Down Expand Up @@ -386,7 +386,7 @@ def calculate_generation_with_market(engine, new_values, market, player):
price = getattr(player, "price_buy_" + demand_type)
market = bid(market, player.id, bid_q, price, demand_type)
else:
reduce_demand(engine, new_values, player.data.history, demand_type, player.id, 0.0)
reduce_demand(engine, new_values, player.data.rolling_history, demand_type, player.id, 0.0)

resource_reservations = reset_resource_reservations()
# Sell capacities of remaining facilities on the market
Expand Down Expand Up @@ -662,7 +662,7 @@ def reserve_resources(power):
max(
0.0,
player.data.capacities[facility]["capacity"]
- player.data.history.get_last_data("storage", facility),
- player.data.rolling_history.get_last_data("storage", facility),
)
* 3600
/ engine.in_game_seconds_per_tick
Expand All @@ -671,7 +671,7 @@ def reserve_resources(power):
else:
energy_capacity = max(
0.0,
player.data.history.get_last_data("storage", facility)
player.data.rolling_history.get_last_data("storage", facility)
* 3600
/ engine.in_game_seconds_per_tick
* (player.data.capacities[facility]["efficiency"] ** 0.5),
Expand All @@ -681,14 +681,14 @@ def reserve_resources(power):
) # ramping down
if minmax == "max":
if filling:
max_ramping = player.data.history.get_last_data("demand", facility) + ramping_speed
max_ramping = player.data.rolling_history.get_last_data("demand", facility) + ramping_speed
else:
max_ramping = player.data.history.get_last_data("generation", facility) + ramping_speed
max_ramping = player.data.rolling_history.get_last_data("generation", facility) + ramping_speed
max_generation = min(max_resources, max_ramping, player.data.capacities[facility]["power"])
reserve_resources(max_generation)
return max_generation
else:
min_ramping = player.data.history.get_last_data("generation", facility) - ramping_speed
min_ramping = player.data.rolling_history.get_last_data("generation", facility) - ramping_speed
min_generation = max(0.0, min(max_resources, min_ramping, player.data.capacities[facility]["power"]))
reserve_resources(min_generation)
return min_generation
Expand Down Expand Up @@ -849,7 +849,7 @@ def reduce_demand(engine, new_values, demand_type, player_id, satisfaction):
demand[demand_type] = satisfaction
if demand_type in engine.extraction_facilities + engine.storage_facilities + ["carbon_capture"]:
return
if satisfaction > (1 + 0.0008 * engine.in_game_seconds_per_tick) * player.data.history.get_last_data(
if satisfaction > (1 + 0.0008 * engine.in_game_seconds_per_tick) * player.data.rolling_history.get_last_data(
"demand", demand_type
):
return
Expand Down
1 change: 0 additions & 1 deletion website/simulate.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ def _simulate(
if stop_on_mismatch:
break
if response.status_code != action["response"]["status_code"]:
print(response.history)
print(
f"""\033[31mStatus code {response.status_code} does not match expected status code """
f"""{action["response"]["status_code"]}.\033[0m"""
Expand Down
38 changes: 19 additions & 19 deletions website/static/charts/electricity.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,27 +78,27 @@ function graph_sketch(s) {
s.push();
let sum = s.upper_bound;
if (s.percent == "percent") {
const groups = Object.keys(s.history);
const groups = Object.keys(s.current_data);
sum = groups.reduce((acc, group) => {
if (s.keys[group] === false) {
return acc;
}
return acc + s.history[group][res_id][t_view];
return acc + s.current_data[group][res_id][t_view];
}, 0);
}
for (const group in s.keys) {
if (group in s.history) {
if (s.history[group][res_id][t_view] > 1 && s.keys[group]) {
let h = -s.history[group][res_id][t_view] * s.graph_h / sum;
if (group in s.current_data) {
if (s.current_data[group][res_id][t_view] > 1 && s.keys[group]) {
let h = -s.current_data[group][res_id][t_view] * s.graph_h / sum;
s.ellipse(0, h, 8, 8);
s.translate(0, h);
}
}
}
s.pop();

for (const group in s.history) {
if (s.history[group][res_id][t_view] > 1 && s.keys[group]) {
for (const group in s.current_data) {
if (s.current_data[group][res_id][t_view] > 1 && s.keys[group]) {
count += 1;
}
}
Expand All @@ -123,9 +123,9 @@ function graph_sketch(s) {

let cumsum = 0;
for (const group of Object.keys(s.keys).reverse()) {
if (group in s.history) {
if (s.history[group][res_id][t_view] > 1 && s.keys[group]) {
cumsum += s.history[group][res_id][t_view];
if (group in s.current_data) {
if (s.current_data[group][res_id][t_view] > 1 && s.keys[group]) {
cumsum += s.current_data[group][res_id][t_view];
alternate_fill(s);
s.rect(0, 0, 160, 17);
s.push();
Expand All @@ -136,7 +136,7 @@ function graph_sketch(s) {
s.textAlign(LEFT, CENTER);
s.text(cols_and_names[group][1], 20, 5);
s.textAlign(CENTER, CENTER);
s.text(format_power(s.history[group][res_id][t_view]), 132, 5);
s.text(format_power(s.current_data[group][res_id][t_view]), 132, 5);
s.translate(0, 16);
}
}
Expand Down Expand Up @@ -211,10 +211,10 @@ function graph_sketch(s) {
};

s.render_graph = function (regen_table = true) {
s.history = data.generation;
s.current_data = data.generation;
s.keys = keys_generation;
if (s.view == "consumption") {
s.history = data.demand;
s.current_data = data.demand;
s.keys = keys_demand;
}
s.graph_h = s.height - margin;
Expand All @@ -228,7 +228,7 @@ function graph_sketch(s) {
s.t0 = 300;
}

const sumArray = Object.entries(s.history).reduce((acc, [key, arr]) => {
const sumArray = Object.entries(s.current_data).reduce((acc, [key, arr]) => {
// Skip summing if not displayed
if (s.keys[key] === false) {
return acc;
Expand All @@ -254,19 +254,19 @@ function graph_sketch(s) {
s.graphics.push();
let sum = s.upper_bound;
if (s.percent == "percent") {
const goups = Object.keys(s.history);
const goups = Object.keys(s.current_data);
sum = goups.reduce((acc, group) => {
if (s.keys[group] === false) {
return acc;
}
return acc + s.history[group][res_id][t];
return acc + s.current_data[group][res_id][t];
}, 0);
}
for (const group in s.keys) {
if (group in s.history) {
if (s.history[group][res_id][t] > 1 && s.keys[group]) {
if (group in s.current_data) {
if (s.current_data[group][res_id][t] > 1 && s.keys[group]) {
s.graphics.fill(cols_and_names[group][0]);
let h = s.history[group][res_id][t] * s.graph_h / sum;
let h = s.current_data[group][res_id][t] * s.graph_h / sum;
s.graphics.rect(0, 0, s.graph_w / data_len + 1, -h - 1);
s.graphics.translate(0, -h);
}
Expand Down
2 changes: 1 addition & 1 deletion website/templates/network.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
<p class="txt_center medium">To have a better understanding how this priority list works, please refer to the <a href="{{ url_for('wiki.render_template_wiki', template_name='power_management') }}">Power Management</a> section of the wiki.</p>
<br><br><br><br>
{% else %}
{% set caps = user.capacities %}
{% set caps = user.data.capacities %}

<div class="flex-center margin">
<button id="page_view_button_basic" class="graph_button graph_button_views left {% if user.graph_view == 'basic'%}selected{% endif %}" onclick="change_page_view('basic')">Basic view</button>
Expand Down
2 changes: 1 addition & 1 deletion website/templates/profile.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
</div>

<div id="facilities_list" class="flex-col medium margin">
{% set caps = user.capacities %}
{% set caps = user.data.capacities %}
{% if caps["steam_engine"] or caps["windmill"] or caps["watermill"] or caps["coal_burner"] or caps["gas_burner"] or caps["small_water_dam"] or caps["onshore_wind_turbine"] or caps["combined_cycle"] or caps["nuclear_reactor"] or caps["large_water_dam"] or caps["CSP_solar"] or caps["PV_solar"] or caps["offshore_wind_turbine"] or caps["nuclear_reactor_gen4"] %}
<b class="large">Power facilities</b>
<div class="table_container">
Expand Down
Loading

0 comments on commit f139d32

Please sign in to comment.