def setUp(self): params = Parameters() params.NB_TIMESTEP_COOLDOWN_LINE = 5 params.NB_TIMESTEP_COOLDOWN_SUB = 15 with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env = make("rte_case5_example", test=True, gamerules_class=DefaultRules, param=params)
def test_donothing_noov_80(self): """test that do nothing has a score of 80.0 if it is run with "no overflow disconnection" """ with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make("rte_case5_example", test=True) as env: # I cannot decrease the max step: it must be above the number of steps the do nothing does scores = ScoreL2RPN2020(env, nb_scenario=2, verbose=0, max_step=130) assert scores._recomputed_dn assert scores._recomputed_no_ov # the statistics have been properly computed assert os.path.exists( os.path.join( env.get_path_env(), EpisodeStatistics.get_name_dir( ScoreL2RPN2020.NAME_DN))) assert os.path.exists( os.path.join( env.get_path_env(), EpisodeStatistics.get_name_dir( ScoreL2RPN2020.NAME_DN_NO_OVERWLOW))) my_agent = DoNothingAgent(env.action_space) my_scores, *_ = scores.get(my_agent) assert np.max( np.abs(my_scores )) <= self.tol_one, "error for the first do nothing" param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True with make("rte_case5_example", test=True, param=param) as env: scores2 = ScoreL2RPN2020(env, nb_scenario=2, verbose=0, max_step=130) assert not scores2._recomputed_dn assert not scores2._recomputed_no_ov my_agent = DoNothingAgent(env.action_space) my_scores, *_ = scores2.get(my_agent) assert np.max( np.abs(np.array(my_scores) - 80.0)) <= self.tol_one # delete them stats_0 = EpisodeStatistics(env, ScoreL2RPN2020.NAME_DN) stats_1 = EpisodeStatistics(env, ScoreL2RPN2020.NAME_DN_NO_OVERWLOW) stats_0.clear_all() stats_1.clear_all() assert not os.path.exists( os.path.join( env.get_path_env(), EpisodeStatistics.get_name_dir(ScoreL2RPN2020.NAME_DN))) assert not os.path.exists( os.path.join( env.get_path_env(), EpisodeStatistics.get_name_dir( ScoreL2RPN2020.NAME_DN_NO_OVERWLOW)))
def set_environement(start_id, env_name, profiles_chronics): param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True env = make(env_name, chronics_path=profiles_chronics, reward_class=CombinedReward, param=param) # Register custom reward for training cr = env.reward_helper.template_reward cr.addReward("overflow", CloseToOverflowReward(), 50.0) cr.addReward("game", GameplayReward(), 100.0) cr.initialize(env) # Debug prints print("Debug prints --->:") print("Chronics location that being used:", env.chronics_handler.path) print("Grid location being used:", env.init_grid_path) print("Reward class that is being used:", env.rewardClass) print("Action type class being used:", env.actionClass) print("Observation type class being used:", env.observationClass) print("Backend CSV file key names:", env.names_chronics_to_backend) print("Legal action class being used:", env.legalActClass) print("Voltage controller class being used:", env.voltagecontrolerClass) if start_id != None: env.chronics_handler.tell_id(start_id) print("Thread number:", start_id, ", ID of chronic current folder:", env.chronics_handler.real_data.id_chron_folder_current) return env
def test_activate_storage_loss(self): """ test that the parameters param.ACTIVATE_STORAGE_LOSS properly deactivate the loss in the storage units """ # first test the storage loss act = self.env.action_space() loss = 1.0 * self.env.storage_loss loss /= 12. # i have 12 steps per hour (ts = (mins), losses are given in MW and capacity in MWh for nb_ts in range(5): obs, reward, done, info = self.env.step(act) assert np.all(np.abs(obs.storage_charge - (0.5 * obs.storage_Emax - (nb_ts + 1) * loss)) <= self.tol_one), \ f"wrong value computed for time step {nb_ts}" param = Parameters() param.ACTIVATE_STORAGE_LOSS = False with warnings.catch_warnings(): warnings.filterwarnings("ignore") env = grid2op.make("educ_case14_storage", test=True, param=param) obs = env.get_obs() assert np.all( np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) <= self.tol_one ), "wrong initial capacity" for nb_ts in range(5): obs, reward, done, info = env.step(act) assert np.all(np.abs(obs.storage_charge - 0.5 * obs.storage_Emax) <= self.tol_one), \ f"wrong value computed for time step {nb_ts} (no loss in storage)"
def main(max_ts, name, test=True): backend = LightSimBackend() param = Parameters() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) env_klu = make(name, backend=backend, test=test, param=param, gamerules_class=AlwaysLegal, data_feeding_kwargs={ "chunk_size": 128, "max_iter": max_ts, "gridvalueClass": GridStateFromFile }) agent = TestAgent(action_space=env_klu.action_space, env_name=name) nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu = run_env( env_klu, max_ts, agent, chron_id=0, keep_forecast=False) env_pp = make(name, param=param, gamerules_class=AlwaysLegal, test=test, data_feeding_kwargs={ "chunk_size": 128, "max_iter": max_ts, "gridvalueClass": GridStateFromFile }) agent = TestAgent(action_space=env_pp.action_space, env_name=name) nb_ts_pp, time_pp, aor_pp, gen_p_pp, gen_q_pp = run_env( env_pp, max_ts, agent, chron_id=0, keep_forecast=False) print_res(env_klu, env_pp, nb_ts_klu, nb_ts_pp, time_klu, time_pp, aor_klu, aor_pp, gen_p_klu, gen_p_pp, gen_q_klu, gen_q_pp)
def test_reconnect_disconnected(self): with warnings.catch_warnings(): warnings.filterwarnings("ignore") params = Parameters() params.MAX_SUB_CHANGED = 0 params.NO_OVERFLOW_DISCONNECTION = True env_case2 = make("rte_case5_example", test=True, param=params) obs = env_case2.reset() # reset is good line_id = 5 # Disconnect the line disco_act = env_case2.action_space.disconnect_powerline( line_id=line_id) obs, reward, done, info = env_case2.step(disco_act) # Line has been disconnected assert info["is_illegal"] == False assert done == False assert np.sum(obs.line_status) == (env_case2.n_line - 1) # Reconnect the line reco_act = env_case2.action_space.reconnect_powerline(line_id=line_id, bus_or=1, bus_ex=2) obs, reward, done, info = env_case2.step(reco_act) # Check reconnecting is legal assert info["is_illegal"] == False assert done == False # Check line has been reconnected assert np.sum(obs.line_status) == (env_case2.n_line)
def main(max_ts, name, use_lightsim=False): param = Parameters() if use_lightsim: if light_sim_avail: backend = LightSimBackend() else: raise RuntimeError("LightSimBackend not available") else: backend = PandaPowerBackend() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) env_klu = make(name, backend=backend, param=param, gamerules_class=AlwaysLegal, test=True) agent = TestAgent(action_space=env_klu.action_space, env_name=name) cp = cProfile.Profile() cp.enable() nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu = run_env( env_klu, max_ts, agent) cp.disable() nm_f, ext = os.path.splitext(__file__) nm_out = "{}_{}_{}.prof".format(nm_f, "lightsim" if use_ls else "pp", name) cp.dump_stats(nm_out) print("You can view profiling results with:\n\tsnakeviz {}".format(nm_out))
def test_load_fake_january(self): param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make(os.path.join( PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance_3"), param=param) as env: env.seed(0) # get input data, to check they were correctly applied in linesPossiblyInMaintenance = env.chronics_handler.real_data.data.line_to_maintenance assert np.all( np.array(sorted(linesPossiblyInMaintenance)) == [ '11_12_13', '12_13_14', '16_18_23', '16_21_27', '22_26_39', '26_30_56', '2_3_0', '30_31_45', '7_9_9', '9_16_18' ]) ChronicMonth = env.chronics_handler.real_data.data.start_datetime.month assert ChronicMonth == 1 maxMaintenancePerDay = env.chronics_handler.real_data.data.max_daily_number_per_month_maintenance[ (ChronicMonth - 1)] assert maxMaintenancePerDay == 0 assert np.sum( env.chronics_handler.real_data.data.maintenance) == 0
def test_seed(self): param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make(os.path.join(PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance"), param=param) as env: nb_scenario = 10 nb_maintenance = np.zeros((nb_scenario, env.n_line), dtype=dt_float) nb_maintenance1 = np.zeros((nb_scenario, env.n_line), dtype=dt_float) env.seed(0) for i in range(nb_scenario): obs = env.reset() nb_maintenance[i, :] = np.sum( env.chronics_handler.real_data.data.maintenance, axis=0) env.seed(0) for i in range(nb_scenario): obs = env.reset() nb_maintenance1[i, :] = np.sum( env.chronics_handler.real_data.data.maintenance, axis=0) assert np.all(nb_maintenance == nb_maintenance)
def main(max_ts, name): backend = LightSimBackend() param = Parameters() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) env_klu = make( name, backend=backend, param=param, gamerules_class=AlwaysLegal, test=True, data_feeding_kwargs={"gridvalueClass": GridStateFromFileWithForecasts}) agent = PowerLineSwitch(action_space=env_klu.action_space) nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu = run_env( env_klu, max_ts, agent, chron_id=0, keep_forecast=True) env_pp = make( name, param=param, gamerules_class=AlwaysLegal, test=True, data_feeding_kwargs={"gridvalueClass": GridStateFromFileWithForecasts}) agent = PowerLineSwitch(action_space=env_pp.action_space) nb_ts_pp, time_pp, aor_pp, gen_p_pp, gen_q_pp = run_env(env_pp, max_ts, agent, chron_id=0, keep_forecast=True) print_res(env_klu, env_pp, nb_ts_klu, nb_ts_pp, time_klu, time_pp, aor_klu, aor_pp, gen_p_klu, gen_p_pp, gen_q_klu, gen_q_pp)
def test_issue_153(self): """ The rule "Prevent Reconnection" was not properly applied, this was because the observation of the _ObsEnv was not properly updated. """ param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True param.NB_TIMESTEP_COOLDOWN_SUB = 3 with warnings.catch_warnings(): warnings.filterwarnings("ignore") env = grid2op.make("rte_case14_realistic", test=True, _add_to_name="test_issue_153") env.gen_max_ramp_up[:] = env.gen_pmax env.gen_max_ramp_down[:] = env.gen_pmax env.action_space.gen_max_ramp_up[:] = env.gen_pmax env.action_space.gen_max_ramp_down[:] = env.gen_pmax env.action_space.actionClass.gen_max_ramp_up[:] = env.gen_pmax env.action_space.actionClass.gen_max_ramp_down[:] = env.gen_pmax obs = env.reset() # prod 1 do [74.8, 77. , 75.1, 76.4, 76.3, 75. , 74.5, 74.2, 73. , 72.6] for i in range(3): obs, reward, done, info = env.step(env.action_space()) # now generator 1 decreases: 76.3, 75. , 74.5, 74.2, 73. , 72.6 action = env.action_space({"redispatch": [(0, -76)]}) obs, reward, done, info = env.step(action) # should be at 0.3 assert np.abs(obs.prod_p[0] - 0.3) <= 1e-2, "wrong data" # I do an illegal action obs, reward, done, info = env.step(action) # and the redispatching was negative (this was the issue) assert obs.prod_p[0] >= -env._tol_poly, "generator should be positive"
def test_reco_simple(self): param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True param.NB_TIMESTEP_COOLDOWN_LINE = 1 with warnings.catch_warnings(): warnings.filterwarnings("ignore") with grid2op.make("rte_case5_example", test=True, param=param) as env: my_agent = RecoPowerlineAgent(env.action_space) obs = env.reset() obs, reward, done, info = env.step( env.action_space({'set_line_status': [(1, -1)]})) assert np.sum(obs.time_before_cooldown_line) == 1 # the agent should do nothing, as the line is still in cooldown act = my_agent.act(obs, reward, done) assert not act.as_dict() obs, reward, done, info = env.step(act) # now cooldown is over assert np.sum(obs.time_before_cooldown_line) == 0 act2 = my_agent.act(obs, reward, done) ddict = act2.as_dict() assert "set_line_status" in ddict assert "nb_connected" in ddict["set_line_status"] assert "connected_id" in ddict["set_line_status"] assert ddict["set_line_status"]["nb_connected"] == 1 assert ddict["set_line_status"]["connected_id"][0] == 1
def setUp(self): with warnings.catch_warnings(): warnings.filterwarnings("ignore") params = Parameters() params.MAX_SUB_CHANGED = 2 self.env = make("rte_case14_test", test=True, chronics_class=ChangeNothing, param=params, backend=self.make_backend())
def test_proba(self): param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make(os.path.join( PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance_2"), param=param) as env: env.seed(0) # input data nb_scenario = 30 # if too low then i don't have 1e-3 beteween theory and practice nb_line_in_maintenance = 10 assert len(env.chronics_handler.real_data.data. line_to_maintenance) == nb_line_in_maintenance proba = 0.06 nb_th = proba * 5 / 7 # for day of week nb_th *= 8 / 24 # maintenance only between 9 and 17 nb_maintenance = np.zeros(env.n_line, dtype=dt_float) nb_ts_ = 0 for i in range(nb_scenario): obs = env.reset() nb_maintenance += np.sum( env.chronics_handler.real_data.data.maintenance, axis=0) nb_ts_ += env.chronics_handler.real_data.data.maintenance.shape[ 0] total_maintenance = np.sum(nb_maintenance) total_maintenance /= nb_ts_ * nb_line_in_maintenance assert np.abs(total_maintenance - nb_th) <= 1e-3
def setUp(self): self.param = Parameters() self.param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) self.max_ts = MAX_TS self.tol = 1e-9 self.tol_q = 2e-5 self.agent_class = TestAgent
def test_change_parameters_forecast_fromissue_128(self): """ this is basic test of the env.change_forecast_parameters() function It only checks the right parameters are used for the environment (or obs_env) but it do not currently check the observation (with the cooldown for example) This is the example taken from https://github.com/rte-france/Grid2Op/issues/128 (first remak) """ # modify the parmeters for simulate param = Parameters() param.MAX_SUB_CHANGED = 9999 param.MAX_LINE_STATUS_CHANGED = 9999 self.env1.change_forecast_parameters(param) self.env1.reset() obs, *_ = self.env1.step(self.env1.action_space()) # and you can simulate the impact of action modifying as many substation as you want, for example act = self.env1.action_space( {"set_bus": { "lines_or_id": [(0, 2), (10, 2)] }}) # this action modfies both substation 0 and substation 8 sim_o, sim_r, sim_d, sim_info = obs.simulate(act) assert sim_info["is_illegal"] is False
def test_creation_with_params(self): p = Parameters() p.MAX_SUB_CHANGED = 666 mme = MultiMixEnvironment(PATH_DATA_MULTIMIX, param=p) assert mme.current_obs is not None assert mme.current_env is not None assert mme.parameters.MAX_SUB_CHANGED == 666
def main(max_ts, ENV_NAME, test=True): backend = LightSimBackend() param = Parameters() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) env_klu = make(ENV_NAME, backend=backend, param=param, test=test, data_feeding_kwargs={"gridvalueClass": GridStateFromFile}) agent = DoNothingAgent(action_space=env_klu.action_space) nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu = run_env(env_klu, max_ts, agent, chron_id=0) env_pp = make(ENV_NAME, param=param, test=test, data_feeding_kwargs={"gridvalueClass": GridStateFromFile}) agent = DoNothingAgent(action_space=env_pp.action_space) nb_ts_pp, time_pp, aor_pp, gen_p_pp, gen_q_pp = run_env(env_pp, max_ts, agent, chron_id=0) print_res(env_klu, env_pp, nb_ts_klu, nb_ts_pp, time_klu, time_pp, aor_klu, aor_pp, gen_p_klu, gen_p_pp, gen_q_klu, gen_q_pp)
def setUp(self): parser = configparser.ConfigParser() parser.read(config_file_path) self.agents_path = parser.get("DEFAULT", "agents_dir") self.cache_dir = os.path.join(self.agents_path, "_cache") if not os.path.isdir(self.cache_dir): from tests.test_make_cache import TestMakeCache test_make_cache = TestMakeCache() test_make_cache.setUp() test_make_cache.test_make_cache() self.agent_name = "do-nothing-baseline" self.scenario_name = "000" self.env_path = parser.get("DEFAULT", "env_dir") p = Parameters() p.NO_OVERFLOW_DISCONNECTION = False self.env = make( self.env_path, backend=PandaPowerBackend(), test=True, param=p, ) self.env.seed(0) params_for_runner = self.env.get_params_for_runner() params_to_fetch = ["init_grid_path"] self.params_for_reboot = { key: value for key, value in params_for_runner.items() if key in params_to_fetch } self.params_for_reboot["parameters"] = p cache_file = os.path.join(self.cache_dir, self.scenario_name, self.agent_name + ".dill") try: with open(cache_file, "rb") as f: episode_analytics = dill.load(f) except: episode_analytics = EpisodeAnalytics(self.episode_data, self.scenario_name, self.agent_name) self.episode_data = EpisodeData.from_disk( os.path.join(self.agents_path, self.agent_name), self.scenario_name) episode_analytics.decorate(self.episode_data) self.episode = episode_analytics self.act = self.env.action_space() self.expert_config = { "totalnumberofsimulatedtopos": 25, "numberofsimulatedtopospernode": 5, "maxUnusedLines": 2, "ratioToReconsiderFlowDirection": 0.75, "ratioToKeepLoop": 0.25, "ThersholdMinPowerOfLoop": 0.1, "ThresholdReportOfLine": 0.2, } self.obs_reboot = None self.reward_type = "MinMargin_reward"
def test_load(self): param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make(os.path.join(PATH_DATA_TEST, "ieee118_R2subgrid_wcci_test_maintenance"), param=param) as env: env.seed(123456) # for reproducible tests ! obs = env.reset() #get input data, to check they were correctly applied in linesPossiblyInMaintenance = env.chronics_handler.real_data.data.line_to_maintenance assert np.all( np.array(sorted(linesPossiblyInMaintenance)) == [ '11_12_13', '12_13_14', '16_18_23', '16_21_27', '22_26_39', '26_30_56', '2_3_0', '30_31_45', '7_9_9', '9_16_18' ]) ChronicMonth = env.chronics_handler.real_data.data.start_datetime.month assert ChronicMonth == 8 maxMaintenancePerDay = env.chronics_handler.real_data.data.max_daily_number_per_month_maintenance[ (ChronicMonth - 1)] assert maxMaintenancePerDay == 2 envLines = env.name_line idx_linesPossiblyInMaintenance = [ i for i in range(len(envLines)) if envLines[i] in linesPossiblyInMaintenance ] idx_linesNotInMaintenance = [ i for i in range(len(envLines)) if envLines[i] not in linesPossiblyInMaintenance ] #maintenance dataFrame maintenanceChronic = maintenances_df = pd.DataFrame( env.chronics_handler.real_data.data.maintenance, columns=envLines) nb_timesteps = maintenanceChronic.shape[0] # identify the timestamps of the chronics to find out the month and day of the week freq = str( int(env.chronics_handler.real_data.data.time_interval. total_seconds()) ) + "s" # should be in the timedelta frequency format in pandas datelist = pd.date_range( env.chronics_handler.real_data.data.start_datetime, periods=nb_timesteps, freq=freq) maintenances_df.index = datelist assert (maintenanceChronic[ envLines[idx_linesNotInMaintenance]].sum().sum() == 0) assert ( maintenanceChronic[linesPossiblyInMaintenance].sum().sum() >= 1) nb_mainteance_timestep = maintenanceChronic.sum(axis=1) assert np.all(nb_mainteance_timestep <= maxMaintenancePerDay)
def test_issue_148(self): """ The rule "Prevent Reconnection" was not properly applied, this was because the observation of the _ObsEnv was not properly updated. """ param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True param.NB_TIMESTEP_COOLDOWN_SUB = 3 with warnings.catch_warnings(): warnings.filterwarnings("ignore") env = grid2op.make(os.path.join(PATH_CHRONICS, "env_14_test_maintenance"), param=param) ID_MAINT = 11 # in maintenance at the second time step obs = env.reset() # check i can "simulate" properly if a maintenance happens next sim_o, sim_r, sim_d, sim_i = obs.simulate(env.action_space()) assert not sim_d assert sim_o.time_next_maintenance[ ID_MAINT] == 0 # the stuff have been properly updated assert not sim_o.line_status[ID_MAINT] oo_, rr_, dd_, ii_ = env.step(env.action_space()) assert not dd_ assert oo_.time_next_maintenance[ID_MAINT] == 0 assert not oo_.line_status[ID_MAINT] # check once the maintenance is performed, it stays this way sim_o, sim_r, sim_d, sim_i = oo_.simulate(env.action_space()) assert not sim_d assert sim_o.time_next_maintenance[ ID_MAINT] == 0 # the stuff have been properly updated assert not sim_o.line_status[ID_MAINT] oo_, rr_, dd_, ii_ = env.step(env.action_space()) assert not dd_ assert oo_.time_next_maintenance[ID_MAINT] == 0 assert not oo_.line_status[ID_MAINT] # now test the cooldown action = env.action_space( {"set_bus": { "substations_id": [(1, [1, 1, 1, 1, 1, 1])] }}) oo_, rr_, dd_, ii_ = env.step(action) assert oo_.time_before_cooldown_sub[1] == 3 oo_, rr_, dd_, ii_ = env.step(env.action_space()) oo_, rr_, dd_, ii_ = env.step(action) assert oo_.time_before_cooldown_sub[1] == 1 assert ii_["is_illegal"] oo_, rr_, dd_, ii_ = oo_.simulate(action) assert not dd_ assert oo_.time_before_cooldown_sub[ID_MAINT] == 0 assert not ii_["is_illegal"] oo_, rr_, dd_, ii_ = env.step(env.action_space()) assert not dd_ assert oo_.time_before_cooldown_sub[ID_MAINT] == 0
def setUp(self): with warnings.catch_warnings(): warnings.filterwarnings("ignore") params = Parameters() params.MAX_SUB_CHANGED = 2 self.env = make("case14_test", chronics_class=ChangeNothing, param=params)
def test_case5_changedparameters(self): param = Parameters() param.NB_TIMESTEP_RECONNECTION = 128 dataset_path = os.path.join(PATH_DATA_TEST, "5bus_example_with_params") with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make_from_dataset_path(dataset_path, param=param) as env: assert env.parameters.NB_TIMESTEP_RECONNECTION == 128
def test_init_from_dict(self): p = Parameters() p_dict = p.to_dict() p_dict["NB_TIMESTEP_POWERFLOW_ALLOWED"] = 42 p.init_from_dict(p_dict) assert p.NB_TIMESTEP_POWERFLOW_ALLOWED == 42
def setUp(self): parser = configparser.ConfigParser() parser.read(config_file_path) self.agents_path = parser.get("DEFAULT", "agents_dir") self.cache_dir = os.path.join(self.agents_path, "_cache") if not os.path.isdir(self.cache_dir): from tests.test_make_cache import TestMakeCache test_make_cache = TestMakeCache() test_make_cache.setUp() test_make_cache.test_make_cache() self.agent_name = "do-nothing-baseline" self.scenario_name = "000" self.env_path = parser.get("DEFAULT", "env_dir") p = Parameters() p.NO_OVERFLOW_DISCONNECTION = False self.env = make( self.env_path, backend=PandaPowerBackend(), test=True, param=p, ) self.env.seed(0) params_for_runner = self.env.get_params_for_runner() params_to_fetch = ["init_grid_path"] self.params_for_reboot = { key: value for key, value in params_for_runner.items() if key in params_to_fetch } self.params_for_reboot["parameters"] = p cache_file = os.path.join(self.cache_dir, self.scenario_name, self.agent_name + ".dill") try: with open(cache_file, "rb") as f: episode_analytics = dill.load(f) except: episode_analytics = EpisodeAnalytics(self.episode_data, self.scenario_name, self.agent_name) self.episode_data = EpisodeData.from_disk( os.path.join(self.agents_path, self.agent_name), self.scenario_name) episode_analytics.decorate(self.episode_data) self.episode = episode_analytics self.episode_reboot = EpisodeReboot.EpisodeReboot() self.episode_reboot.load( self.env.backend, data=self.episode, agent_path=os.path.join(self.agents_path, self.agent_name), name=self.episode.episode_name, env_kwargs=self.params_for_reboot, ) self.obs, *_ = self.episode_reboot.go_to(1895) self.act = self.env.action_space()
def __init__(self, case_name, env_dc=False): Parameters.__init__(self, parameters_path=None) param_dict = self._get_param_dict(case_name=case_name) self.init_from_dict(dict_=param_dict) if env_dc: self.ENV_DC = env_dc self.FORECAST_DC = env_dc
def setUp(self) -> None: with warnings.catch_warnings(): warnings.filterwarnings("ignore") param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True self.env1 = grid2op.make("educ_case14_storage", test=True, action_class=PlayableAction, param=param) self.env2 = self.env1.copy()
def setUp(self): """ The case file is a representation of the case14 as found in the ieee14 powergrid. :return: """ param = Parameters() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env = make("rte_case14_redisp", test=True, param=param)
def setUp(self): with warnings.catch_warnings(): warnings.filterwarnings("ignore") params = Parameters() params.MAX_SUB_CHANGED = 0 params.NB_TIMESTEP_POWERFLOW_ALLOWED = 2 rules = DefaultRules self.env = make("rte_case14_test", test=True, chronics_class=ChangeNothing, param=params, gamerules_class=rules)
def test_reco_more_difficult(self): param = Parameters() param.NO_OVERFLOW_DISCONNECTION = True param.NB_TIMESTEP_COOLDOWN_LINE = 3 with warnings.catch_warnings(): warnings.filterwarnings("ignore") with grid2op.make("rte_case5_example", test=True, param=param) as env: my_agent = RecoPowerlineAgent(env.action_space) obs = env.reset() obs, reward, done, info = env.step( env.action_space({'set_line_status': [(1, -1)]})) obs, reward, done, info = env.step( env.action_space({'set_line_status': [(2, -1)]})) # the agent should do nothing, as the line is still in cooldown act = my_agent.act(obs, reward, done) assert not act.as_dict() obs, reward, done, info = env.step(act) act = my_agent.act(obs, reward, done) assert not act.as_dict() obs, reward, done, info = env.step(act) # now in theory i can reconnect the first one act2 = my_agent.act(obs, reward, done) ddict = act2.as_dict() assert "set_line_status" in ddict assert "nb_connected" in ddict["set_line_status"] assert "connected_id" in ddict["set_line_status"] assert ddict["set_line_status"]["nb_connected"] == 1 assert ddict["set_line_status"]["connected_id"][0] == 1 # but i will not implement it on the grid obs, reward, done, info = env.step(env.action_space()) act3 = my_agent.act(obs, reward, done) ddict3 = act3.as_dict() assert len(my_agent.tested_action) == 2 # and it turns out i need to reconnect the first one first assert "set_line_status" in ddict3 assert "nb_connected" in ddict3["set_line_status"] assert "connected_id" in ddict3["set_line_status"] assert ddict3["set_line_status"]["nb_connected"] == 1 assert ddict3["set_line_status"]["connected_id"][0] == 1 obs, reward, done, info = env.step(act3) act4 = my_agent.act(obs, reward, done) ddict4 = act4.as_dict() assert len(my_agent.tested_action) == 1 # and it turns out i need to reconnect the first one first assert "set_line_status" in ddict4 assert "nb_connected" in ddict4["set_line_status"] assert "connected_id" in ddict4["set_line_status"] assert ddict4["set_line_status"]["nb_connected"] == 1 assert ddict4["set_line_status"]["connected_id"][0] == 2