Skip to content

Commit

Permalink
adding experimental support for environment with other type of file
Browse files Browse the repository at this point in the history
  • Loading branch information
BDonnot committed Oct 20, 2023
1 parent 655cb06 commit dddd4c4
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 29 deletions.
5 changes: 3 additions & 2 deletions lightsim2grid/gridmodel/from_pypowsybl.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ def init(net : pypo.network,
df_gen = net.get_generators().sort_index()
else:
df_gen = net.get_generators()

# to handle encoding in 32 bits and overflow when "splitting" the Q values among
min_q = df_gen["min_q"].values.astype(np.float32)
max_q = df_gen["max_q"].values.astype(np.float32)
min_q[~np.isfinite(min_q)] = np.finfo(np.float32).min / 2. + 1.
max_q[~np.isfinite(max_q)] = np.finfo(np.float32).max / 2. - 1.
min_q[~np.isfinite(min_q)] = np.finfo(np.float32).min * 0.5 + 1.
max_q[~np.isfinite(max_q)] = np.finfo(np.float32).max * 0.5 - 1.
model.init_generators(df_gen["target_p"].values,
df_gen["target_v"].values / voltage_levels.loc[df_gen["voltage_level_id"].values]["nominal_v"].values,
min_q,
Expand Down
31 changes: 22 additions & 9 deletions lightsim2grid/lightSimBackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ def __init__(self,
self._loader_method = loader_method
self._loader_kwargs = loader_kwargs

if loader_method == "pandapower":
self.supported_grid_format = ("json", ) # new in 1.9.6
elif loader_method == "pypowsybl":
self.supported_grid_format = ("xiidm", ) # new in 1.9.6
else:
raise BackendError(f"Uknown loader_metho : '{loader_method}'")

self.shunts_data_available = True # needs to be self and not type(self) here

self.nb_bus_total = None
Expand Down Expand Up @@ -444,7 +451,7 @@ def make_complete_path(path, filename):
gen_slack_id = None
if "gen_slack_id" in loader_kwargs:
gen_slack_id = int(loader_kwargs["gen_slack_id"])
self._grid = init_pypow(grid_tmp, gen_slack_id=None) # TODO gen_slack_id !
self._grid = init_pypow(grid_tmp, gen_slack_id=None) # TODO gen_slack_id, make things crash !
self._aux_setup_right_after_grid_init()

# mandatory for the backend
Expand All @@ -458,10 +465,10 @@ def make_complete_path(path, filename):
from_sub = True

if "use_buses_for_sub" in loader_kwargs and loader_kwargs["use_buses_for_sub"]:
df = grid_tmp.get_buses()
from_sub = False
df = grid_tmp.get_buses()
from_sub = False
self.n_sub = df.shape[0]
self.name_sub = ["sub_{}".format(i) for i, _ in df.iterrows()]
self.name_sub = ["sub_{}".format(i) for i, _ in enumerate(df.iterrows())]

if not from_sub:
self.load_to_subid = np.array([el.bus_id for el in self._grid.get_loads()], dtype=dt_int)
Expand Down Expand Up @@ -510,7 +517,14 @@ def make_complete_path(path, filename):
self._big_topo_to_obj = [(None, None) for _ in range(type(self).dim_topo)]
self._aux_finish_setup_after_reading()
self.prod_pu_to_kv = 1.0 * self._grid.get_buses()[[el.bus_id for el in self._grid.get_generators()]]
self.prod_pu_to_kv = self.prod_pu_to_kv.astype(dt_float)
self.prod_pu_to_kv = self.prod_pu_to_kv.astype(dt_float)

# TODO
max_not_too_max = (np.finfo(dt_float).max * 0.5 - 1.)
self.thermal_limit_a = max_not_too_max * np.ones(self.n_line, dtype=dt_float)
bus_vn_kv = np.array(self._grid.get_buses())
shunt_bus_id = np.array([el.bus_id for el in self._grid.get_shunts()])
self._sh_vnkv = bus_vn_kv[shunt_bus_id]

def _aux_setup_right_after_grid_init(self):
self._handle_turnedoff_pv()
Expand Down Expand Up @@ -738,7 +752,7 @@ def assert_grid_correct_after_powerflow(self):
try:
# feature added in grid2op 1.4 or 1.5
_init_action_to_set = self.get_action_to_set()
except TypeError:
except TypeError as exc_:
_init_action_to_set = self._get_action_to_set_deprecated()
self._init_action_to_set += _init_action_to_set

Expand Down Expand Up @@ -817,12 +831,12 @@ def apply_action(self, backendAction):
backendAction.load_q.values)
except RuntimeError as exc_:
# see https://github.com/BDonnot/lightsim2grid/issues/66 (even though it's not a "bug" and has not been replicated)
raise BackendError(f"{exc_}")
raise BackendError(f"{exc_}") from exc_

if self.__has_storage:
try:
self._grid.update_storages_p(backendAction.storage_power.changed,
backendAction.storage_power.values)
backendAction.storage_power.values)
except RuntimeError as exc_:
# modification of power of disconnected storage has no effect in lightsim2grid
pass
Expand Down Expand Up @@ -872,7 +886,6 @@ def runpf(self, is_dc=False):
if (self.V is None) or (self.V.shape[0] == 0):
# create the vector V as it is not created
self.V = np.ones(self.nb_bus_total, dtype=np.complex_) * self._grid.get_init_vm_pu()

if self.initdc:
self._grid.deactivate_result_computation()
# if I init with dc values, it should depends on previous state
Expand Down
43 changes: 27 additions & 16 deletions lightsim2grid/tests/test_backend_pypowsybl.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@
CAN_DO_TEST_SUITE = False


def _aux_get_loader_kwargs():
def _aux_get_loader_kwargs_storage():
return {"use_buses_for_sub": True, "double_bus_per_sub": True, "gen_slack_id": 6}

def _aux_get_loader_kwargs():
return {"use_buses_for_sub": True, "double_bus_per_sub": True, "gen_slack_id": 5}


class BackendTester(unittest.TestCase):
Expand Down Expand Up @@ -79,31 +82,39 @@ def get_casefile(self):

def make_backend(self, detailed_infos_for_cascading_failures=False):
return LightSimBackend(loader_method="pypowsybl",
loader_kwargs=_aux_get_loader_kwargs(),
loader_kwargs=_aux_get_loader_kwargs_storage(),
detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures)

# # add test of grid2op for the backend based on pypowsybl
# def this_make_backend(self, detailed_infos_for_cascading_failures=False):
# return LightSimBackend(
# loader_method="pypowsybl",
# loader_kwargs=_aux_get_loader_kwargs(),
# loader_kwargs=_aux_get_loader_kwargs_storage(),
# detailed_infos_for_cascading_failures=detailed_infos_for_cascading_failures
# )
# add_name_cls = "test_LightSimBackend_pypowsybl"

# def get_path_test_api(self):
# return path

# def get_casefile(self):
# return "grid.xiidm"

# res = create_test_suite(make_backend_fun=this_make_backend,
# add_name_cls=add_name_cls,
# add_to_module=__name__,
# extended_test=False, # for now keep `extended_test=False` until all problems are solved
# get_paths={"AAATestBackendAPI": get_path_test_api},
# get_casefiles={"AAATestBackendAPI": get_casefile}
# )
if CAN_DO_TEST_SUITE:
# requires grid2Op 1.9.6 at least
class EnvTester(unittest.TestCase):
def setUp(self) -> None:
dir_path = os.path.dirname(os.path.realpath(__file__))
path_case_14_storage_iidm = os.path.join(dir_path, "case_14_storage_iidm")
self.env = grid2op.make(path_case_14_storage_iidm,
backend=LightSimBackend(loader_method="pypowsybl",
loader_kwargs=_aux_get_loader_kwargs_storage(),
)
)
super().setUp()

def tearDown(self) -> None:
self.env.close()
return super().tearDown()

def test_can_make(self):
self.env.reset()
1 + 1

# TODO env tester
if __name__ == "__main__":
unittest.main()
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from pybind11.setup_helpers import Pybind11Extension, build_ext


__version__ = "0.7.5"
__version__ = "0.7.6.dev0"
KLU_SOLVER_AVAILABLE = False

# Try to link against SuiteSparse (if available)
Expand Down Expand Up @@ -386,6 +386,7 @@
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Intended Audience :: Developers",
"Intended Audience :: Education",
Expand Down
2 changes: 1 addition & 1 deletion src/SparseLUSolver.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
#include "Eigen/SparseLU"

/**
class to handle the solver using newton-raphson method, using a "SparseLU" algorithm from Eigein
class to handle the solver using newton-raphson method, using a "SparseLU" algorithm from Eigen
and sparse matrices.
As long as the admittance matrix of the sytem does not change, you can reuse the same solver.
Expand Down

0 comments on commit dddd4c4

Please sign in to comment.