1+ import grid2op
2+ from PandaModelsBackend import PandaModelsBackend
3+ import pandapower as pp
4+ import pandapower .converter as pp_converter
5+ import os
6+ import numpy as np
7+
8+ def test_grid2op_pandapower ():
9+ """
10+ Full test for Grid2Op with PandaPower backend.
11+ - Lists available Grid2Op test environments.
12+ - Loads an environment and converts its network to PandaPower.
13+ - Runs a basic simulation with a dummy action.
14+ - Ensures the backend works without errors.
15+ """
16+
17+ # Step 1: List available test environments
18+ available_envs = grid2op .list_available_test_env ()
19+ if not available_envs :
20+ print ("❌ No available Grid2Op test environments found!" )
21+ return
22+ print (f"✅ Found { len (available_envs )} available Grid2Op test environments." )
23+
24+ # Step 2: Pick the first available test environment
25+ env_name = available_envs [2 ]
26+ print (f"✅ Running test on Grid2Op environment: { env_name } " )
27+
28+ # Step 3: Construct the test environment path
29+ path_grid2op = os .path .dirname (grid2op .__file__ )
30+ path_data_test = os .path .join (path_grid2op , "data" , env_name )
31+
32+ # Step 4: Find a valid grid file
33+ possible_files = ["grid.json" , "case.m" , "grid.m" ]
34+ network_file = None
35+
36+ for file in possible_files :
37+ full_path = os .path .join (path_data_test , file )
38+ if os .path .exists (full_path ):
39+ network_file = full_path
40+ break
41+
42+ if not network_file :
43+ print (f"❌ No valid grid file found in { path_data_test } " )
44+ return
45+
46+ print (f"✅ Found network file: { network_file } " )
47+
48+ # Step 5: Convert the environment grid to a PandaPower network
49+ try :
50+ if network_file .endswith (".json" ):
51+ pp_net = pp .from_json (network_file ) # Load PandaPower JSON
52+ print ("✅ Loaded grid from JSON" )
53+ else :
54+ pp_net = pp_converter .from_mpc (network_file , f_hz = 50 ) # Convert MATPOWER to PandaPower
55+ print ("✅ Converted MATPOWER to PandaPower network" )
56+ except Exception as e :
57+ print (f"❌ Error loading grid file: { e } " )
58+ return
59+
60+ # Step 6: Initialize Grid2Op with the PandaPower backend
61+ backend = PandaModelsBackend (pp_net )
62+ env = grid2op .make (env_name , backend = backend ) # Fix missing dataset argument
63+
64+ # Step 7: Reset the environment
65+ obs = env .reset ()
66+
67+ # Step 8: Take a simple action (do nothing)
68+ action = env .action_space ()
69+ obs , reward , done , info = env .step (action )
70+
71+ # Step 9: Validate results
72+ assert not done , "❌ Simulation ended too early!"
73+ assert not np .isnan (obs .rho .max ()), "❌ Invalid line loading (NaN detected)!"
74+ assert not np .isnan (obs .prod_p .max ()), "❌ Invalid generator production (NaN detected)!"
75+
76+ print ("✅ Grid2Op PandaPower Backend Test Passed: Environment runs successfully!" )
77+
78+ # Run the test
79+ if __name__ == "__main__" :
80+ test_grid2op_pandapower ()
0 commit comments