def test_do_nothing(self): backend = LightSimBackend() env_name = self._get_env_name() with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make(env_name, test=True, param=self.param, backend=backend, gamerules_class=AlwaysLegal, data_feeding_kwargs={"chunk_size": 128, "max_iter": MAX_TS}) as env: nb_ts_klu, aor_klu, gen_p_klu, gen_q_klu = self._run_env(env) with make(env_name, test=True, param=self.param, gamerules_class=AlwaysLegal, data_feeding_kwargs={"chunk_size": 128, "max_iter": MAX_TS}) as env: nb_ts_pp, aor_pp, gen_p_pp, gen_q_pp = self._run_env(env) assert nb_ts_klu == nb_ts_pp, "not same number of timesteps for {}: lightsim: {}, pp: {}" \ "".format(env_name, nb_ts_klu, nb_ts_pp) assert np.max(np.abs(aor_klu - aor_pp)) <= self.tol, "aor l inf different for {}: {}" \ "".format(env_name, np.max(np.abs(aor_klu - aor_pp))) assert np.mean(np.abs(aor_klu - aor_pp)) <= self.tol, "aor l1 different for {}: {}" \ "".format(env_name, np.mean(np.abs(aor_klu - aor_pp))) assert np.max(np.abs(gen_p_klu - gen_p_pp)) <= self.tol, "gen_p l inf different for {}: {}" \ "".format(env_name, np.max(np.abs(gen_p_klu - gen_p_pp))) assert np.mean(np.abs(gen_p_klu - gen_p_pp)) <= self.tol, "gen_p l1 different for {}: {}" \ "".format(env_name, np.mean(np.abs(gen_p_klu - gen_p_pp))) # a slightly different algorithm compare to pandapower (see DataGen.cpp, set_q) assert np.max(np.abs(gen_q_klu - gen_q_pp)) <= self.tol_q, "l inf different for {} gen_q: {}" \ "".format(env_name, np.max(np.abs(gen_q_klu - gen_q_pp))) assert np.mean(np.abs(gen_q_klu - gen_q_pp)) <= self.tol_q, "l1 different for {} gen_q".format(env_name)
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 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 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 setUp(self) -> None: with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env_pp = grid2op.make("l2rpn_case14_sandbox", test=True) self.env_ls = grid2op.make("l2rpn_case14_sandbox", test=True, backend=LightSimBackend())
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 setUp(self): super().setUp() with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env = grid2op.make("l2rpn_case14_sandbox", test=True, backend=LightSimBackend()) self.runner = Runner(**self.env.get_params_for_runner())
def setUp(self) -> None: self.backend = LightSimBackend() with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env = make("case14_redisp", backend=self.backend, test=True) # i don't want to be bother by ramps in these test (note that is NOT recommended to change that) self.env.gen_max_ramp_down[:] = 5000 self.env.gen_max_ramp_up[:] = 5000 self.msg_ = 'Grid2OpException AmbiguousAction InvalidRedispatching NotEnoughGenerators "Attempt to use a ' \ 'redispatch action that does not sum to 0., but a'
def setUp(self): self.param = Parameters() self.param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) self.max_ts = 100 self.tol = 1e-5 self.env_name = "case5_example" backend = LightSimBackend() env_name = self.env_name with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env = make(self.env_name, param=self.param, backend=backend, gamerules_class=AlwaysLegal, chronics_class=ChangeNothing, test=True)
def main(max_ts, ENV_NAME): backend = LightSimBackend() param = Parameters() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) env_klu = make(ENV_NAME, backend=backend, param=param, test=True) 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) env_pp = make(ENV_NAME, param=param, test=True) 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) 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 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) 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) env_pp = make(name, param=param, gamerules_class=AlwaysLegal, test=True) 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) 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 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, data_feeding_kwargs={ "chunk_size": 128, "max_iter": max_ts, "gridvalueClass": GridStateFromFile }) agent = TestAgent(action_space=env_klu.action_space, env_name=name, nb_quiet=2) agent.seed(42) # nb_quiet = 2 : do a random action once every 2 timesteps agent.seed(42) cp = cProfile.Profile() cp.enable() nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu, reset_count = run_env_with_reset( env_klu, max_ts, agent, seed=69) 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)) print("There were {} resets".format(reset_count))
def test_save_load(self): with warnings.catch_warnings(): warnings.filterwarnings("ignore") with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env = make("rte_case5_example", test=True, backend=LightSimBackend()) with tempfile.TemporaryDirectory() as tmpdir: with open(os.path.join(tmpdir, "test_pickle.pickle"), "wb") as f: pickle.dump(self.env.backend, f) with open(os.path.join(tmpdir, "test_pickle.pickle"), "rb") as f: backend_1 = pickle.load(f) nb_bus_total = self.env.n_sub * 2 max_it = 10 tol = 1e-8 # TODO test in case the pickle file is corrupted... # test dc_pf V_0 = np.ones(nb_bus_total, dtype=np.complex_) V_0 = self.env.backend._grid.dc_pf(V_0, max_it, tol) V_1 = np.ones(nb_bus_total, dtype=np.complex_) V_1 = backend_1._grid.dc_pf(V_1, max_it, tol) assert np.all( np.abs(V_0 - V_1) <= 1e-7), "dc pf does not lead to same results" # test ac_pf V_0 = self.env.backend._grid.ac_pf(V_0, max_it, tol) V_1 = backend_1._grid.ac_pf(V_1, max_it, tol) assert np.all( np.abs(V_0 - V_1) <= 1e-7), "ac pf does not lead to same results"
def test_do_nothing(self): backend = LightSimBackend() env_name = self._get_env_name() with warnings.catch_warnings(): warnings.filterwarnings("ignore") with make(env_name, test=True, param=self.param, backend=backend, gamerules_class=AlwaysLegal) as env: nb_ts_klu, aor_klu, gen_p_klu, gen_q_klu = self._run_env(env) with make(env_name, test=True, param=self.param, gamerules_class=AlwaysLegal) as env: nb_ts_pp, aor_pp, gen_p_pp, gen_q_pp = self._run_env(env) assert nb_ts_klu == nb_ts_pp, "not same number of timesteps for {}".format( env_name) assert np.max(np.abs(aor_klu - aor_pp) ) <= self.tol, "l inf different for {}".format(env_name) assert np.mean(np.abs( aor_klu - aor_pp)) <= self.tol, "l1 different for {} aor".format(env_name) assert np.max( np.abs(gen_p_klu - gen_p_pp) ) <= self.tol, "l inf different for {} gen_p".format(env_name) assert np.mean( np.abs(gen_p_klu - gen_p_pp)) <= self.tol, "l1 different for {} gen_p".format( env_name) assert np.max( np.abs(gen_q_klu - gen_q_pp) ) <= self.tol, "l inf different for {} gen_q".format(env_name) assert np.mean( np.abs(gen_q_klu - gen_q_pp)) <= self.tol, "l1 different for {} gen_q".format( env_name)
def main(): args = cli() # read arguments input_dir = args.input_path output_dir = args.output_path program_dir = args.program_path submission_dir = args.submission_path config_file = args.config_in with open(config_file, "r") as f: config = json.load(f) # Generate seeds once np.random.seed(int(config["score_config"]["seed"])) max_int = np.iinfo(dt_int).max env_seeds = list(np.random.randint(max_int, size=args.nb_episode)) agent_seeds = list(np.random.randint(max_int, size=args.nb_episode)) # create output dir if not existing if not os.path.exists(output_dir): os.makedirs(output_dir) if DEBUG: print("input dir: {}".format(input_dir)) print("output dir: {}".format(output_dir)) print("program dir: {}".format(program_dir)) print("submission dir: {}".format(submission_dir)) print("input content", os.listdir(input_dir)) print("output content", os.listdir(output_dir)) print("program content", os.listdir(program_dir)) print("Content received by codalab: {}".format( sorted(os.listdir(submission_dir)))) submission_location = os.path.join(submission_dir, "submission") if not os.path.exists(submission_location): print(SUBMISSION_DIR_ERR) raise RuntimeError(SUBMISSION_DIR_ERR) # add proper directories to path sys.path.append(program_dir) sys.path.append(submission_dir) try: from submission import make_agent except Exception as e: print(e) raise RuntimeError(MAKE_AGENT_ERR) from None try: from submission import reward except: print(INFO_CUSTOM_REWARD) reward = RedispReward if not isinstance(reward, type): raise RuntimeError(REWARD_ERR) if not issubclass(reward, BaseReward): raise RuntimeError(REWARD_ERR2) try: from submission import other_rewards except: print(INFO_CUSTOM_OTHER) other_rewards = {} if args.key_score in other_rewards: print(KEY_OVERLOAD_WARN.format(args.key_score)) other_rewards[args.key_score] = L2RPNSandBoxScore # Loop over env dirs for env_dir in os.listdir(input_dir): env_path = os.path.join(input_dir, env_dir) if not os.path.isdir(env_path): continue try: with warnings.catch_warnings(): warnings.filterwarnings("ignore") env_template = grid2op.make( env_path, chronics_class=ChangeNothing, action_class=TopologyAndDispatchAction) except Exception as e: raise RuntimeError(ENV_TEMPLATE_ERR) try: submitted_agent = make_agent(env_template, submission_location) except Exception as e: raise RuntimeError(MAKE_AGENT_ERR2) if not isinstance(submitted_agent, BaseAgent): raise RuntimeError(BASEAGENT_ERR) try: from lightsim2grid.LightSimBackend import LightSimBackend backend = LightSimBackend() except: print(BACKEND_WARN) from grid2op.Backend import PandaPowerBackend backend = PandaPowerBackend() real_env = grid2op.make(env_path, backend=backend, reward_class=reward, other_rewards=other_rewards) runner = Runner(**real_env.get_params_for_runner(), agentClass=None, agentInstance=submitted_agent) path_save = os.path.abspath(os.path.join(output_dir, env_dir)) runner.run(nb_episode=args.nb_episode, path_save=path_save, max_iter=-1, env_seeds=env_seeds, agent_seeds=agent_seeds) print(INFO_ENV_INGESTION_OK.format(env_dir, path_save)) real_env.close() env_template.close() # Generate a gif if enabled if args.gif_env is not None and args.gif_episode is not None: gif_input = os.path.join(output_dir, args.gif_env) write_gif(output_dir, gif_input, args.gif_episode, args.gif_start, args.gif_end) if args.cleanup: cmds = [ "find {} -name '*.npz' | xargs -i rm -rf {}", "find {} -name 'dict_*.json' | xargs -i rm -rf {}", "find {} -name '_parameters.json' | xargs -i rm -rf {}" ] for cmd in cmds: os.system(cmd.format(output_dir, "{}"))
# it is not necessary to save it again here. But if you chose not to follow these advice, it is more than # recommended to save the "baseline" at the end of this function with: # baseline.save(path_save) if __name__ == "__main__": # import grid2op import numpy as np from grid2op.Parameters import Parameters from grid2op import make from grid2op.Reward import BaseReward from grid2op.dtypes import dt_float import re try: from lightsim2grid.LightSimBackend import LightSimBackend backend = LightSimBackend() except: from grid2op.Backend import PandaPowerBackend backend = PandaPowerBackend() args = cli_train().parse_args() # is it highly recommended to modify the reward depening on the algorithm. # for example here i will push my algorithm to learn that plyaing illegal or ambiguous action is bad class MyReward(BaseReward): power_rho = int(4) # to which "power" is put the rho values penalty_powerline_disco = 1.0 # how to penalize the powerline disconnected that can be reconnected # how to penalize the fact that a powerline will be disconnected next time steps, because it's close to # an overflow
def make_backend(self, detailed_infos_for_cascading_failures=False): with warnings.catch_warnings(): warnings.filterwarnings("ignore") bk = LightSimBackend(detailed_infos_for_cascading_failures= detailed_infos_for_cascading_failures) return bk
def setUp(self): # powergrid self.backend = LightSimBackend() self.path_matpower = PATH_DATA_TEST_PP self.case_file = "test_case14.json" # chronics self.path_chron = os.path.join(PATH_CHRONICS, "chronics") self.chronics_handler = ChronicsHandler(chronicsClass=ChangeNothing) self.id_chron_to_back_load = np.array( [0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]) # force the verbose backend self.backend.detailed_infos_for_cascading_failures = True self.names_chronics_to_backend = { "loads": { "2_C-10.61": 'load_1_0', "3_C151.15": 'load_2_1', "14_C63.6": 'load_13_2', "4_C-9.47": 'load_3_3', "5_C201.84": 'load_4_4', "6_C-6.27": 'load_5_5', "9_C130.49": 'load_8_6', "10_C228.66": 'load_9_7', "11_C-138.89": 'load_10_8', "12_C-27.88": 'load_11_9', "13_C-13.33": 'load_12_10' }, "lines": { '1_2_1': '0_1_0', '1_5_2': '0_4_1', '9_10_16': '8_9_2', '9_14_17': '8_13_3', '10_11_18': '9_10_4', '12_13_19': '11_12_5', '13_14_20': '12_13_6', '2_3_3': '1_2_7', '2_4_4': '1_3_8', '2_5_5': '1_4_9', '3_4_6': '2_3_10', '4_5_7': '3_4_11', '6_11_11': '5_10_12', '6_12_12': '5_11_13', '6_13_13': '5_12_14', '4_7_8': '3_6_15', '4_9_9': '3_8_16', '5_6_10': '4_5_17', '7_8_14': '6_7_18', '7_9_15': '6_8_19' }, "prods": { "1_G137.1": 'gen_0_4', "3_G36.31": "gen_2_1", "6_G63.29": "gen_5_2", "2_G-56.47": "gen_1_0", "8_G40.43": "gen_7_3" }, } # _parameters for the environment self.env_params = Parameters() self.env = Environment( init_grid_path=os.path.join(self.path_matpower, self.case_file), backend=self.backend, chronics_handler=self.chronics_handler, parameters=self.env_params, names_chronics_to_backend=self.names_chronics_to_backend, actionClass=BaseAction)
def make_backend(self, detailed_infos_for_cascading_failures=False): return LightSimBackend(detailed_infos_for_cascading_failures= detailed_infos_for_cascading_failures)
def setUp(self): self.backend = LightSimBackend() # powergrid with warnings.catch_warnings(): warnings.filterwarnings("ignore") self.env = make("case14_test", backend=self.backend, test=True)
def main(max_ts, ENV_NAME, test=True): param = Parameters() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) 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, env_seed=0) pp_time_pf = env_pp._time_powerflow wst = False # print extra info in the run_env function env_lightsim = make( ENV_NAME, backend=LightSimBackend(), param=param, test=test, data_feeding_kwargs={"gridvalueClass": GridStateFromFile}) li_tols = [10., 1., 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9] nb_ts = [] time = [] aor = [] gen_p = [] gen_q = [] comp_time = [] time_pf = [] for tol in li_tols: env_lightsim.backend.set_tol(tol) nb_ts_, time_, aor_, gen_p_, gen_q_ = run_env(env_lightsim, max_ts, agent, chron_id=0, with_type_solver=wst, env_seed=0) comp_time_ = env_lightsim.backend.comp_time time_pf_ = env_lightsim._time_powerflow nb_ts.append(nb_ts_) time.append(time_) aor.append(aor_) gen_p.append(gen_p_) gen_q.append(gen_q_) comp_time.append(comp_time_) time_pf.append(time_pf_) # NOW PRINT THE RESULTS env_name = get_env_name_displayed(ENV_NAME) hds = [ f"{env_name} ({nb_ts_pp} iter)", f"speed (it/s)", f"Δ aor (amps)", f"Δ gen_p (MW)", f"Δ gen_q (MVAr)" ] tab = [["PP", int(nb_ts_pp / time_pp), "0.00", "0.00", "0.00"]] for i, tol in enumerate(li_tols): if lightsim2grid.SolverType.GaussSeidel: tab.append([ f"{tol:.2e}", f"{int(nb_ts[i] / time[i])}", f"{np.max(np.abs(aor[i] - aor_pp)):.2e}", f"{np.max(np.abs(gen_p[i] - gen_p_pp)):.2e}", f"{np.max(np.abs(gen_q[i] - gen_q_pp)):.2e}" ]) res_tol = tabulate(tab, headers=hds, tablefmt="rst") print(res_tol)
import json import os import numpy as np import grid2op from grid2op.Converter import IdToAct from lightsim2grid.LightSimBackend import LightSimBackend from utils import create_action_mappings, create_action_line_mappings, filter_action if __name__ == '__main__': with open("data/config.json", 'r') as f: config = json.load(f) env = grid2op.make(config["env"], backend=LightSimBackend()) env.seed(config["seed"]) selected_action_types = config["selected_action_types"] if os.path.exists(os.path.join("data", f"{config['env']}_action_space.npz")): action_space = IdToAct(env.action_space) action_space.init_converter(all_actions=os.path.join( "data", f"{config['env']}_action_space.npz")) else: action_space = IdToAct(env.action_space) action_space.init_converter( set_line_status=(selected_action_types["force_line_reconnect"] or selected_action_types["force_line_disconnect"]), change_line_status=selected_action_types["switch_line"], set_topo_vect=selected_action_types["set_bus"], change_bus_vect=selected_action_types["switch_bus"], redispatch=selected_action_types["redispatch"])
def get_backend(self): return LightSimBackend()
def __init__(self): backend = LightSimBackend() env = grid2op.make("l2rpn_neurips_2020_track1_small", backend=backend) self.agent = Track1PowerNetAgent(env.action_space) self.env = env
def main(max_ts, ENV_NAME, test=True): param = Parameters() param.init_from_dict({"NO_OVERFLOW_DISCONNECTION": True}) 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, env_seed=0) pp_time_pf = env_pp._time_powerflow wst = True # print extra info in the run_env function env_lightsim = make( ENV_NAME, backend=LightSimBackend(), param=param, test=test, data_feeding_kwargs={"gridvalueClass": GridStateFromFile}) solver_types = env_lightsim.backend.available_solvers if lightsim2grid.SolverType.KLU in solver_types: env_lightsim.backend.set_solver_type(lightsim2grid.SolverType.KLU) env_lightsim.backend.set_solver_max_iter(10) nb_ts_klu, time_klu, aor_klu, gen_p_klu, gen_q_klu = run_env( env_lightsim, max_ts, agent, chron_id=0, with_type_solver=wst, env_seed=0) klu_comp_time = env_lightsim.backend.comp_time klu_time_pf = env_lightsim._time_powerflow if lightsim2grid.SolverType.SparseLU in solver_types: env_lightsim.backend.set_solver_type(lightsim2grid.SolverType.SparseLU) env_lightsim.backend.set_solver_max_iter(10) nb_ts_slu, time_slu, aor_slu, gen_p_slu, gen_q_slu = run_env( env_lightsim, max_ts, agent, chron_id=0, with_type_solver=wst, env_seed=0) slu_comp_time = env_lightsim.backend.comp_time slu_time_pf = env_lightsim._time_powerflow if lightsim2grid.SolverType.GaussSeidel in solver_types: env_lightsim.backend.set_solver_type( lightsim2grid.SolverType.GaussSeidel) env_lightsim.backend.set_solver_max_iter(10000) nb_ts_gs, time_gs, aor_gs, gen_p_gs, gen_q_gs = run_env( env_lightsim, max_ts, agent, chron_id=0, with_type_solver=wst, env_seed=0) gs_comp_time = env_lightsim.backend.comp_time gs_time_pf = env_lightsim._time_powerflow # NOW PRINT THE RESULTS env_name = get_env_name_displayed(ENV_NAME) hds = [ f"{env_name}", f"grid2op speed (it/s)", f"grid2op powerflow time (ms)", f"solver powerflow time (ms)" ] tab = [[ "PP", int(nb_ts_pp / time_pp), f"{1000.*pp_time_pf/nb_ts_pp:.2e}", f"{1000.*pp_time_pf/nb_ts_pp:.2e}" ]] if lightsim2grid.SolverType.GaussSeidel: tab.append([ "LS+GS", int(nb_ts_gs / time_gs), f"{1000.*gs_time_pf/nb_ts_gs:.2e}", f"{1000.*gs_comp_time/nb_ts_gs:.2e}" ]) if lightsim2grid.SolverType.SparseLU: tab.append([ "LS+SLU", int(nb_ts_slu / time_slu), f"{1000.*slu_time_pf/nb_ts_slu:.2e}", f"{1000.*slu_comp_time/nb_ts_slu:.2e}" ]) if lightsim2grid.SolverType.KLU: tab.append([ "LS+KLU", int(nb_ts_klu / time_klu), f"{1000.*klu_time_pf/nb_ts_klu:.2e}", f"{1000.*klu_comp_time/nb_ts_klu:.2e}" ]) res_use_with_grid2op_1 = tabulate(tab, headers=hds, tablefmt="rst") print(res_use_with_grid2op_1) print() res_github_readme = tabulate(tab, headers=hds, tablefmt="github") print(res_github_readme) print() hds = [ f"{env_name} ({nb_ts_pp} iter)", f"Δ aor (amps)", f"Δ gen_p (MW)", f"Δ gen_q (MVAr)" ] tab = [["PP", "0.00", "0.00", "0.00"]] if lightsim2grid.SolverType.GaussSeidel: tab.append([ "LS+GS", f"{np.max(np.abs(aor_gs - aor_pp)):.2e}", f"{np.max(np.abs(gen_p_gs - gen_p_pp)):.2e}", f"{np.max(np.abs(gen_q_gs - gen_q_pp)):.2e}" ]) if lightsim2grid.SolverType.SparseLU: tab.append([ "LS+SLU", f"{np.max(np.abs(aor_slu - aor_pp)):.2e}", f"{np.max(np.abs(gen_p_slu - gen_p_pp)):.2e}", f"{np.max(np.abs(gen_q_slu - gen_q_pp)):.2e}" ]) if lightsim2grid.SolverType.KLU: tab.append([ "LS+KLU", f"{np.max(np.abs(aor_klu - aor_pp)):.2e}", f"{np.max(np.abs(gen_p_klu - gen_p_pp)):.2e}", f"{np.max(np.abs(gen_q_klu - gen_q_pp)):.2e}" ]) res_use_with_grid2op_2 = tabulate(tab, headers=hds, tablefmt="rst") print(res_use_with_grid2op_2)