def test_json(net_in, tempdir): filename = os.path.join(tempdir, "testfile.json") try: net_geo = copy.deepcopy(net_in) # make GeodataFrame from shapely.geometry import Point, LineString from fiona.crs import from_epsg import geopandas as gpd for tab in ('bus_geodata', 'line_geodata'): net_geo[tab]['geometry'] = None net_geo[tab] = gpd.GeoDataFrame(net_geo[tab], geometry='geometry', crs=from_epsg(4326)) for idx, row in net_geo.bus_geodata.iterrows(): net_geo.bus_geodata.at[idx, 'geometry'] = Point(row.x, row.y) for idx, row in net_geo.line_geodata.iterrows(): net_geo.line_geodata.at[idx, 'geometry'] = LineString(row.coords) pp.to_json(net_geo, filename) net_out = pp.from_json(filename) assert_net_equal(net_geo, net_out) except (NameError, ImportError): pass # check if restore_all_dtypes works properly: net_in.line['test'] = 123 # this will not work: # net_in.res_line['test'] = 123 pp.to_json(net_in, filename) net_out = pp.from_json(filename) assert_net_equal(net_in, net_out)
def test_json(net_in, tmp_path): filename = os.path.join(os.path.abspath(str(tmp_path)), "testfile.json") try: net_geo = copy.deepcopy(net_in) # make GeodataFrame from shapely.geometry import Point, LineString from fiona.crs import from_epsg import geopandas as gpd for tab in ('bus_geodata', 'line_geodata'): if tab == 'bus_geodata': geometry = net_geo[tab].apply(lambda x: Point(x.x, x.y), axis=1) else: geometry = net_geo[tab].coords.apply(LineString) net_geo[tab] = gpd.GeoDataFrame(net_geo[tab], geometry=geometry, crs=from_epsg(4326)) pp.to_json(net_geo, filename) net_out = pp.from_json(filename) assert_net_equal(net_geo, net_out) # assert isinstance(net_out.line_geodata, gpd.GeoDataFrame) # assert isinstance(net_out.bus_geodata, gpd.GeoDataFrame) assert isinstance(net_out.bus_geodata.geometry.iat[0], Point) assert isinstance(net_out.line_geodata.geometry.iat[0], LineString) except (NameError, ImportError): pass # check if restore_all_dtypes works properly: net_in.line['test'] = 123 net_in.res_line['test'] = 123 pp.to_json(net_in, filename) net_out = pp.from_json(filename) assert_net_equal(net_in, net_out)
def test_json_controller_none(): try: pp.from_json(os.path.join(pp_dir, 'test', 'test_files', 'controller_containing_NoneNan.json'), convert=False) except: raise (UserWarning( "empty net with controller containing Nan/None can't be loaded"))
def mv_oberrhein(scenario="load", cosphi_load=0.98, cosphi_pv=1.0, include_substations=False): """ Loads the Oberrhein network, a generic 20 kV network serviced by two 25 MVA HV/MV transformer stations. The network supplies 141 HV/MV substations and 6 MV loads through four MV feeders. The network layout is meshed, but the network is operated as a radial network with 6 open sectioning points. The network can be loaded with two different worst case scenarios for load and generation, which are defined by scaling factors for loads / generators as well as tap positions of the HV/MV transformers. These worst case scenarios are a good starting point for working with this network, but you are of course free to parametrize the network for your use case. The network also includes geographical information of lines and buses for plotting. OPTIONAL: **scenario** - (str, "load"): defines the scaling for load and generation - "load": high load scenario, load = 0.6 / sgen = 0, trafo taps [-2, -3] - "generation": high feed-in scenario: load = 0.1, generation = 0.8, trafo taps [0, 0] **cosphi_load** - (str, 0.98): cosine(phi) of the loads **cosphi_sgen** - (str, 1.0): cosine(phi) of the static generators **include_substations** - (bool, False): if True, the transformers of the MV/LV level are modelled, otherwise the loads representing the LV networks are connected directly to the MV node OUTPUT: **net** - pandapower network EXAMPLE: import pandapower.networks net = pandapower.networks.mv_oberrhein("generation") """ if include_substations: net = pp.from_json(os.path.join(get_pp_networks_path(), "mv_oberrhein_substations.json")) else: net = pp.from_json(os.path.join(get_pp_networks_path(), "mv_oberrhein.json")) net.load.q_kvar = np.tan(np.arccos(cosphi_load)) * net.load.p_kw net.sgen.q_kvar = np.tan(np.arccos(cosphi_pv)) * net.sgen.p_kw hv_trafos = net.trafo[net.trafo.sn_kva > 1e3].index if scenario == "load": net.load.scaling = 0.6 net.sgen.scaling = 0.0 net.trafo.tp_pos.loc[hv_trafos] = [-2, -3] elif scenario == "generation": net.load.scaling = 0.1 net.sgen.scaling = 0.8 net.trafo.tp_pos.loc[hv_trafos] = [0, 0] else: raise ValueError("Unknown scenario %s - chose 'load' or 'generation'" % scenario) pp.runpp(net) return net
def test_encrypted_json(net_in, tmp_path): import cryptography.fernet filename = os.path.abspath(str(tmp_path)) + "testfile.json" pp.to_json(net_in, filename, encryption_key="verysecret") with pytest.raises(json.JSONDecodeError): pp.from_json(filename) with pytest.raises(cryptography.fernet.InvalidToken): pp.from_json(filename, encryption_key="wrong") net_out = pp.from_json(filename, encryption_key="verysecret") assert_net_equal(net_in, net_out)
def test_store_and_load(simple_test_net): net = simple_test_net n_timesteps = 2 profiles, ds = create_data_source(n_timesteps) ConstControl(net, element='load', variable='p_mw', element_index=[0, 1, 2], data_source=ds, profile_name=["load1", "load2_mv_p", "load3_hv_p"]) dirname = tempfile.gettempdir() ow = OutputWriter(net, output_path=dirname, output_file_type=".json") ow.remove_log_variable("res_bus") tmp_file = os.path.join(dirname, "net.json") pp.to_json(net, tmp_file) del net del ow res_line_file = os.path.join(dirname, "res_line", "loading_percent.json") # del result file is one is present if os.path.isfile(res_line_file): os.remove(res_line_file) net = pp.from_json(tmp_file) ow = net.output_writer.iat[0, 0] assert len(ow.log_variables) == 1 assert ow.output_path == dirname time_steps = range(0, n_timesteps) run_timeseries(net, time_steps=time_steps, verbose=False) # check if results were written assert os.path.isfile(res_line_file)
def case6515rte(ref_bus_idx=6171): """ This case accurately represents the size and complexity of French very high voltage and high \ voltage transmission network. The data is provided by `MATPOWER \ <http://www.pserc.cornell.edu/matpower/>`_. The data origin is the paper `C. Josz, S. Fliscounakis, J. Maenght, P. Panciatici, AC power \ flow data in MATPOWER and QCQP format: iTesla, RTE snapshots, and PEGASE \ <https://arxiv.org/abs/1603.01533>`_, 2016. OPTIONAL: **ref_bus_idx** - Since the MATPOWER case provides a reference bus without connected \ generator, because a distributed slack is assumed, to convert the data to pandapower, \ another bus has been assumed as reference bus. Via 'ref_bus_idx' the User can choose a \ reference bus, which should have a generator connected to. Please be aware that by \ changing the reference bus to another bus than the proposed default value, maybe a \ powerflow does not converge anymore! OUTPUT: **net** - Returns the required ieee network case6515rte EXAMPLE: import pandapower.networks as pn net = pn.case6515rte() """ case6515rte = pp.from_json(_get_cases_path("case6515rte.json")) if ref_bus_idx != 6171: # change reference bus _change_ref_bus(case6515rte, ref_bus_idx, ext_grid_p=-2850.78e3) return case6515rte
def count_obs_tar(self): assert len(self.observer) == len(self.observe_attribute), '数量应相等' net_buffer = pp.from_json(self.folder + '/' + os.listdir(self.folder)[0]) pp.runpp(net_buffer) num_obs = sum([net_buffer[ele].shape[0] for ele in self.observer]) num_tar = sum([net_buffer[ele].shape[0] for ele in self.target]) return num_obs, num_tar
def load_network(self, num): self.net = pp.from_json(self.folder + '/' + os.listdir(self.folder)[num]) self.is_diverged = False # 从1开始方便计算 self.step = 1 self.run_network()
def ieee_european_lv_asymmetric(scenario="on_peak_566"): """ Loads the IEEE European LV network, a generic 0.416 kV network serviced by one 0.8 MVA MV/LV transformer station. The network supplies 906 LV buses and 55 1-PH loads The network layout is mostly radial. The data source can be found at https://cmte.ieee.org/pes-testfeeders/resources/ The network can be loaded with three different scenarios for On-Peak and Off-Peak load which are defined by scaling factors for loads / generators. These scenarios are a good starting point for working with this network, but you are of course free to parametrize the network for your use case. The network also includes geographical information of lines and buses for plotting. OPTIONAL: **scenario** - (str, "on_mid"): defines the scaling for load and generation - "on_mid": high load scenario - "off_start": low load scenario at 12:01 AM - "off_end": low load scenario at mignight OUTPUT: **net** - pandapower network EXAMPLE: import pandapower.networks net = pandapower.networks.ieee_european_lv_asymmetric("off_start") """ if scenario == "off_peak_1": net = pp.from_json( os.path.join(pp_dir, "networks", "IEEE_European_LV_Off_Peak_1.json")) elif scenario == "on_peak_566": net = pp.from_json( os.path.join(pp_dir, "networks", "IEEE_European_LV_On_Peak_566.json")) elif scenario == "off_peak_1440": net = pp.from_json( os.path.join(pp_dir, "networks", "IEEE_European_LV_Off_Peak_1440.json")) else: raise ValueError("Unknown scenario %s - chose 'on_peak_566' or " % scenario + "'off_peak_1' or 'off_peak_1440'") return net
def __get_net_from_config(self, config): if config['PP_NET']['pp_name'] == '': print('Grab net from file ...') net = pp.from_json(config['PP_NET']['file_path']) else: print('Grab net from pandapower lib ...') net = pn.__dict__[config['PP_NET']['pp_name']]() return net
def test_trafo_asym(): nw_dir = os.path.abspath(os.path.join(pp.pp_dir, "test/loadflow")) for trafo_vector_group in ["YNyn", "Dyn", "Yzn"]: net = pp.from_json(nw_dir + '/runpp_3ph Validation.json') net['trafo'].vector_group = trafo_vector_group runpp_3ph_with_consistency_checks(net) assert net['converged'] check_results(net, trafo_vector_group, get_PF_Results(trafo_vector_group))
def test_json(): net_in = create_test_network() net_in.line_geodata.loc[0, "coords"] = [(1.1, 2.2), (3.3, 4.4)] net_in.line_geodata.loc[1, "coords"] = [(5.5, 5.5), (6.6, 6.6), (7.7, 7.7)] pp.to_json(net_in, "testfile.json") net_out = pp.from_json("testfile.json") assert_net_equal(net_in, net_out, reindex=True) os.remove('testfile.json')
def meshed_grid(): net = pp.from_json( os.path.join(pp.pp_dir, "test", "shortcircuit", "sc_test_meshed_grid.json")) bid = pp.create_bus(net, vn_kv=10.) pp.create_switch(net, net.ext_grid.bus.iloc[0], bid, et="b") net.ext_grid.bus.iloc[0] = bid pp.create_bus(net, vn_kv=0.4, in_service=False) return net
def test_convert_format_pq_bus_meas(): net = pp.from_json(os.path.join(folder, "example_2.3.1.json"), convert=False) net = pp.convert_format(net) pp.runpp(net) bus_p_meas = net.measurement.query( "element_type=='bus' and measurement_type=='p'").set_index("element", drop=True) assert np.allclose(net.res_bus.p_mw, bus_p_meas["value"])
def test_iec60909_example_4(): file = os.path.join(pp.pp_dir, "test", "test_files", "IEC60909-4_example.json") net = pp.from_json(file) sc.calc_sc(net, fault="1ph") assert np.isclose(net.res_bus_sc[net.bus.name=="Q"].ikss_ka.values[0], 10.05957231) assert np.isclose(net.res_bus_sc[net.bus.name=="T2LV"].ikss_ka.values[0], 34.467353142) assert np.isclose(net.res_bus_sc[net.bus.name=="F1"].ikss_ka.values[0], 35.53066312) assert np.isclose(net.res_bus_sc[net.bus.name=="F2"].ikss_ka.values[0], 34.89135137) assert np.isclose(net.res_bus_sc[net.bus.name=="F3"].ikss_ka.values[0], 5.0321033105) assert np.isclose(net.res_bus_sc[net.bus.name=="Cable/Line IC"].ikss_ka.values[0], 16.362586813)
def test_fluc(self): net = pp.from_json(base_grid) obj, attr, area = obj2change[0], attr2change[0], fluc_area[0] new_net = fluc_value(net, obj, attr, area) base_value = net[obj][attr].values bottom_value = base_value * area[0] top_value = base_value * area[1] new_value = new_net[obj][attr].values self.assertTrue((top_value > new_value).all()) self.assertTrue((bottom_value < new_value).all())
def test_json_io_same_net(net_in, tempdir): pp.control.ConstControl(net_in, 'load', 'p_mw', 0) s = pp.to_json(net_in) net1 = pp.from_json_string(s) assert net1.controller.object.at[0].net is net1 filename = os.path.join(tempdir, "testfile.json") pp.to_json(net_in, filename) net2 = pp.from_json(filename) assert net2.controller.object.at[0].net is net2
def test_json_io_same_net(net_in, tmp_path): control.ConstControl(net_in, 'load', 'p_mw', 0) s = pp.to_json(net_in) net1 = pp.from_json_string(s) assert isinstance(net1.controller.object.at[0], control.ConstControl) filename = os.path.abspath(str(tmp_path)) + "testfile.json" pp.to_json(net_in, filename) net2 = pp.from_json(filename) assert isinstance(net2.controller.object.at[0], control.ConstControl)
def test_to_json_dtypes(tempdir): filename = os.path.join(tempdir, "testfile.json") net = create_test_network() pp.runpp(net) net['res_test'] = pd.DataFrame(columns=['test'], data=[1, 2, 3]) net['test'] = pd.DataFrame(columns=['test'], data=[1, 2, 3]) net.line['test'] = 123 net.res_line['test'] = 123 net.bus['test'] = 123 net.res_bus['test'] = 123 net.res_load['test'] = 123 pp.to_json(net, filename) net1 = pp.from_json(filename)
def test_to_json_dtypes(tmp_path): filename = os.path.abspath(str(tmp_path)) + "testfile.json" net = create_test_network() pp.runpp(net) net['res_test'] = pd.DataFrame(columns=['test'], data=[1, 2, 3]) net['test'] = pd.DataFrame(columns=['test'], data=[1, 2, 3]) net.line['test'] = 123 net.res_line['test'] = 123 net.bus['test'] = 123 net.res_bus['test'] = 123 net.res_load['test'] = 123 pp.to_json(net, filename) net1 = pp.from_json(filename) assert_net_equal(net, net1)
def test_convert_format(version): filename = os.path.join(folder, "example_%s.json" % version) if not os.path.isfile(filename): raise ValueError("File for version %s does not exist" % version) try: net = pp.from_json(filename, convert=False) if ('version' in net) and (vs.parse(str(net.version)) > vs.parse('2.0.1')): _ = pp.from_json(filename, elements_to_deserialize=['bus', 'load']) except: raise UserWarning( "Can not load network saved in pandapower version %s" % version) vm_pu_old = net.res_bus.vm_pu.copy() pp.convert_format(net) try: pp.runpp(net, run_control="controller" in net and len(net.controller) > 0) except: raise UserWarning("Can not run power flow in network " "saved with pandapower version %s" % version) if not np.allclose(vm_pu_old.values, net.res_bus.vm_pu.values): raise UserWarning("Power flow results mismatch " "with pandapower version %s" % version)
def test_from_ppc(): ppc = get_testgrids('case2_2', 'ppc_testgrids.p') net_by_ppc = from_ppc(ppc) net_by_code = pp.from_json(os.path.join(os.path.split(pp.__file__)[0], 'test', 'converter', 'case2_2_by_code.json')) pp.set_user_pf_options(net_by_code) # for assertion of nets_equal pp.runpp(net_by_ppc, trafo_model="pi") pp.runpp(net_by_code, trafo_model="pi") assert type(net_by_ppc) == type(net_by_code) assert net_by_ppc.converged assert len(net_by_ppc.bus) == len(net_by_code.bus) assert len(net_by_ppc.trafo) == len(net_by_code.trafo) assert len(net_by_ppc.ext_grid) == len(net_by_code.ext_grid) assert pp.nets_equal(net_by_ppc, net_by_code, check_only_results=True, tol=1.e-9)
def test_iec60909_example_4_bus_selection(): file = os.path.join(pp.pp_dir, "test", "test_files", "IEC60909-4_example.json") net = pp.from_json(file) for inv_y in (False, True): sc.calc_sc(net, fault="1ph", inverse_y=inv_y, bus=net.bus[net.bus.name.isin(("F1", "F2"))].index) assert np.isclose( net.res_bus_sc.at[net.bus[net.bus.name == "F1"].index[0], "ikss_ka"], 35.53066312) assert np.isclose( net.res_bus_sc.at[net.bus[net.bus.name == "F2"].index[0], "ikss_ka"], 34.89135137)
def case5(): """ This is the 5 bus example from F.Li and R.Bo, "Small Test Systems for Power System Economic \ Studies" Its data origin is `MATPOWER <http://www.pserc.cornell.edu/matpower/>`_. OUTPUT: **net** - Returns the required ieee network case4gs EXAMPLE: import pandapower.networks as pn net = pn.case5() """ case5 = pp.from_json(_get_cases_path("case5.json")) return case5
def load_case(case_name, data_dir, reindex=True): custom_cases = ['denmark'] if hasattr(pp.networks, case_name): net = getattr(pp.networks, case_name)() if case_name == 'iceland': net['line']['x_ohm_per_km'][80] = -net['line']['x_ohm_per_km'][80] elif case_name in custom_cases: net = pp.from_json(os.path.join(data_dir, case_name, "train.json")) else: raise ValueError("Network name {} is undefined.".format(case_name)) if not os.path.exists(os.path.join(data_dir, case_name)): os.mkdir(os.path.join(data_dir, case_name)) if reindex: net = pp.create_continuous_bus_index(net, start=0) return net
def __init__(self, path_to_network): print 'ingesting network info' self.network = pp.from_json(path_to_network) self.bus_index = self.bus_names_to_numbers() self.loads = self.map_loads_to_busses() # calculating cost functions (by bus) groups = self.loads.groupby('bus') self.bus_outages = pd.DataFrame(columns=['customers','load','cost'], index=groups.groups.keys()) self.bus_outages['customers'] = groups['zone'].count() self.bus_outages['load'] = groups['kW'].sum() # read in cost functions (by line) self.affected_busses = self.get_affected_busses() self.line_outages = pd.read_csv(os.path.join('inputs','line_outage_consequences.csv'), index_col='line')
def case4gs(): """ This is the 4 bus example from J. J. Grainger and W. D. Stevenson, Power system analysis. \ McGraw-Hill, 1994. pp. 337-338. Its data origin is \ `PYPOWER <https:/pypi.python.org/pypi/PYPOWER>`_. OUTPUT: **net** - Returns the required ieee network case4gs EXAMPLE: import pandapower.networks as pn net = pn.case4gs() """ case4gs = pp.from_json(_get_cases_path("case4gs.json")) return case4gs
def case3120sp(): """ This case represents the Polish 400, 220 and 110 kV networks during summer 2008 morning peak \ conditions. The data was provided by Roman Korab <*****@*****.**> and to pandapower \ converted from `MATPOWER <http://www.pserc.cornell.edu/matpower/>`_. OUTPUT: **net** - Returns the required ieee network case3120sp EXAMPLE: import pandapower.networks as pn net = pn.case3120sp() """ case3120sp = pp.from_json(_get_cases_path("case3120sp.json")) return case3120sp
def case145(): """ Calls the json file case145.json which data origin is \ `MATPOWER <http://www.pserc.cornell.edu/matpower/>`_. This data is converted by MATPOWER 5.1 using CDF2MPC on 18-May-2016 from 'dd50cdf.txt'. OUTPUT: **net** - Returns the required ieee network case145 EXAMPLE: import pandapower.networks as pn net = pn.case145() """ case145 = pp.from_json(_get_cases_path("case145.json")) return case145