Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reset records #40

Merged
merged 3 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions boario/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
else:
_has_coloredlogs = True

try:
import pygit2
except:
pass

import pathlib
import logging
from functools import lru_cache

Expand All @@ -44,6 +50,14 @@
)


try:
__git_branch__ = pygit2.Repository(__file__).head.name
except Exception:
pass
else:
logger.info(f"You are using boario from branch {__git_branch__}")


@lru_cache(10)
def warn_once(logger, msg: str):
logger.warning(msg)
Expand Down
137 changes: 13 additions & 124 deletions boario/model_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,19 +411,6 @@ def __init__(
self._prod_cap_delta_kapital = None
self._prod_cap_delta_arbitrary = None
self._prod_cap_delta_tot = None
self.prod_max_toward_rebuilding = None
self.records_storage = None
self.production_evolution = None
self.production_cap_evolution = None
self.io_demand_evolution = None
self.final_demand_evolution = None
self.rebuild_demand_evolution = None
self.overproduction_evolution = None
self.final_demand_unmet_evolution = None
self.rebuild_production_evolution = None
self.stocks_evolution = None
self.limiting_stocks_evolution = None
self.regional_sectoral_kapital_destroyed_evol = None

## Properties

Expand Down Expand Up @@ -1478,35 +1465,34 @@ def calc_overproduction(self) -> None:

def reset_module(
self,
simulation_params: dict,
) -> None:
"""Resets the model to initial state [Deprecated]

This method is currently not functioning.
"""

logger.warning("This method is quite probably deprecated")
self.reset_record_files(
simulation_params["n_temporal_units_to_sim"],
simulation_params["register_stocks"],
)
# Reset variable attributes
self.kapital_lost = np.zeros(self.production.shape)
self.overprod = np.full(
(self.n_regions * self.n_sectors), self.overprod_base, dtype=np.float64
)
with np.errstate(divide="ignore", invalid="ignore"):
self.matrix_stock = (
np.tile(self.X_0, (self.n_sectors, 1)) * self.tech_mat
) * self.inv_duration[:, np.newaxis]
self.matrix_stock = np.nan_to_num(self.matrix_stock, nan=np.inf, posinf=np.inf)
self.matrix_stock_0 = self.matrix_stock.copy()
self.matrix_stock = self.matrix_stock_0.copy()
self.matrix_orders = self.Z_0.copy()
self.production = self.X_0.copy()
self.intmd_demand = self.Z_0.copy()
self.final_demand = self.Y_0.copy()
self.final_demand_not_met = np.zeros(self.Y_0.shape)
self.rebuilding_demand = None
self.prod_max_toward_rebuilding = None
self.in_shortage = False
self.had_shortage = False
self._prod_delta_type = None
self._indus_rebuild_demand_tot = None
self._house_rebuild_demand_tot = None
self._indus_rebuild_demand = None
self._house_rebuild_demand = None
self._tot_rebuild_demand = None
self._prod_cap_delta_kapital = None
self._prod_cap_delta_arbitrary = None
self._prod_cap_delta_tot = None

def update_params(self, new_params: dict) -> None:
"""Update the parameters of the model.
Expand Down Expand Up @@ -1541,103 +1527,6 @@ def update_params(self, new_params: dict) -> None:
new_params["n_temporal_units_to_sim"], new_params["register_stocks"]
)

def reset_record_files(self, n_temporal_units: int, reg_stocks: bool) -> None:
"""Reset results memmaps

This method creates/resets the :class:`memmaps <numpy.memmap>` arrays used to track
production, demand, overproduction, etc.

Parameters
----------
n_steps : int
number of steps of the simulation (memmaps size are predefined)
reg_stocks : bool
If true, create/reset the stock memmap (which can be huge)

"""
self.production_evolution = np.memmap(
self.records_storage / "iotable_XVA_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.production_evolution.fill(np.nan)
self.production_cap_evolution = np.memmap(
self.records_storage / "iotable_X_max_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.production_cap_evolution.fill(np.nan)
self.io_demand_evolution = np.memmap(
self.records_storage / "io_demand_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.io_demand_evolution.fill(np.nan)
self.final_demand_evolution = np.memmap(
self.records_storage / "final_demand_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.final_demand_evolution.fill(np.nan)
self.rebuild_demand_evolution = np.memmap(
self.records_storage / "rebuild_demand_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.rebuild_demand_evolution.fill(np.nan)
self.overproduction_evolution = np.memmap(
self.records_storage / "overprodvector_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.overproduction_evolution.fill(np.nan)
self.final_demand_unmet_evolution = np.memmap(
self.records_storage / "final_demand_unmet_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.final_demand_unmet_evolution.fill(np.nan)
self.rebuild_production_evolution = np.memmap(
self.records_storage / "rebuild_prod_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.rebuild_production_evolution.fill(np.nan)
if reg_stocks:
self.stocks_evolution = np.memmap(
self.records_storage / "stocks_record",
dtype="float64",
mode="w+",
shape=(
n_temporal_units,
self.n_sectors,
self.n_sectors * self.n_regions,
),
)
self.stocks_evolution.fill(np.nan)
self.limiting_stocks_evolution = np.memmap(
self.records_storage / "limiting_stocks_record",
dtype="byte",
mode="w+",
shape=(n_temporal_units, self.n_sectors, self.n_sectors * self.n_regions),
)
self.limiting_stocks_evolution.fill(-1)
self.regional_sectoral_kapital_destroyed_evol = np.memmap(
self.records_storage / "iotable_kapital_destroyed_record",
dtype="float64",
mode="w+",
shape=(n_temporal_units, self.n_sectors * self.n_regions),
)
self.regional_sectoral_kapital_destroyed_evol.fill(np.nan)

def write_index(self, index_file: str | pathlib.Path) -> None:
"""Write the indexes of the different dataframes of the model in a json file.

Expand Down
86 changes: 52 additions & 34 deletions boario/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ def __init__(
self._save_events = save_events
self._save_params = save_params
self._save_index = save_index
self._register_stocks = register_stocks
self.output_dir = pathlib.Path(boario_output_dir)
"""pathlib.Path, optional: Optional path to the directory where output are stored."""

Expand Down Expand Up @@ -183,7 +184,6 @@ def __init__(
"""list[Event]: A list containing all events that are happening at the current timestep of the simulation."""

self.events_timings = set()
self._files_to_record = []
self.n_temporal_units_to_sim = n_temporal_units_to_sim
"""int: The total number of `temporal_units` to simulate."""

Expand All @@ -208,6 +208,8 @@ def __init__(
self.records_storage: pathlib.Path = self.results_storage / "records"
"""Place where records are stored if stored"""

self._files_to_record = []

if save_records != []:
if isinstance(save_records, str):
if save_records == "all":
Expand All @@ -231,36 +233,7 @@ def __init__(
self._save_events = True
self._save_params = True

for rec in self.__possible_records:
if rec == "inputs_stocks" and not register_stocks:
pass
else:
save = rec in save_records
filename = rec
dtype, attr_name, shapev, fillv = self.__file_save_array_specs[rec]
if shapev == "industries":
shape = (
self.n_temporal_units_to_sim,
self.model.n_sectors * self.model.n_regions,
)
elif shapev == "stocks":
shape = (
self.n_temporal_units_to_sim,
self.model.n_sectors,
self.model.n_sectors * self.model.n_regions,
)
else:
raise RuntimeError(f"shapev {shapev} unrecognised")
memmap_array = TempMemmap(
filename=(self.records_storage / filename),
dtype=dtype,
mode="w+",
shape=shape,
save=save,
)
memmap_array.fill(fillv)
self._files_to_record.append(attr_name)
setattr(self, attr_name, memmap_array)
self.init_records(save_records, register_stocks)

Event.temporal_unit_range = self.n_temporal_units_to_sim
self.params_dict = {
Expand Down Expand Up @@ -624,21 +597,22 @@ def add_event(self, ev: Event):

def reset_sim_with_same_events(self):
"""Resets the model to its initial status (without removing the events). [WIP]"""
raise NotImplementedError("To fix")
logger.info("Resetting model to initial status (with same events)")
self.current_temporal_unit = 0
self._monotony_checker = 0
self._n_checks = 0
self.n_temporal_units_simulated = 0
self.has_crashed = False
self.model.reset_module(self.params_dict)
self.reset_records()
self.model.reset_module()

def reset_sim_full(self):
"""Resets the model to its initial status and remove all events."""

raise NotImplementedError("To fix")
self.reset_sim_with_same_events()
logger.info("Resetting events")
self.all_events = []
self.currently_happening_events = []
self.events_timings = set()

def update_params(self, new_params: dict):
Expand Down Expand Up @@ -817,3 +791,47 @@ def flush_memmaps(self) -> None:
)
else:
getattr(self, at).flush()

def init_records(self, save_records, register_stocks):
for rec in self.__possible_records:
if rec == "input_stocks" and not register_stocks:
pass
else:
save = rec in save_records
filename = rec
dtype, attr_name, shapev, fillv = self.__file_save_array_specs[rec]
if shapev == "industries":
shape = (
self.n_temporal_units_to_sim,
self.model.n_sectors * self.model.n_regions,
)
elif shapev == "stocks":
shape = (
self.n_temporal_units_to_sim,
self.model.n_sectors,
self.model.n_sectors * self.model.n_regions,
)
else:
raise RuntimeError(f"shapev {shapev} unrecognised")
memmap_array = TempMemmap(
filename=(self.records_storage / filename),
dtype=dtype,
mode="w+",
shape=shape,
save=save,
)
memmap_array.fill(fillv)
self._files_to_record.append(attr_name)
setattr(self, attr_name, memmap_array)

def reset_records(
self,
):
for rec in self.__possible_records:
dtype, attr_name, shapev, fillv = self.__file_save_array_specs[rec]
if rec == "input_stocks" and not self._register_stocks:
pass
else:
memmap_array = getattr(self, attr_name)
memmap_array.fill(fillv)
setattr(self, attr_name, memmap_array)