From 7d7e2c91ba6ec53b76cbd78629be55bb87449f22 Mon Sep 17 00:00:00 2001 From: Steffen Meinecke Date: Mon, 25 Mar 2024 11:14:43 +0100 Subject: [PATCH 01/17] df.col.loc[idx] = -> df.loc[idx, col] --- pandapower/converter/pypower/from_ppc.py | 12 ++--- pandapower/diagnostic.py | 2 +- pandapower/estimation/util.py | 14 ++--- pandapower/grid_equivalents/auxiliary.py | 10 ++-- pandapower/grid_equivalents/get_equivalent.py | 2 +- pandapower/grid_equivalents/rei_generation.py | 4 +- pandapower/grid_equivalents/toolbox.py | 2 +- pandapower/groups.py | 2 +- pandapower/networks/create_examples.py | 2 +- pandapower/networks/mv_oberrhein.py | 4 +- .../networks/power_system_test_cases.py | 12 ++--- pandapower/results_bus.py | 8 +-- .../grid_equivalents/test_get_equivalent.py | 2 +- pandapower/test/loadflow/test_results.py | 2 +- .../test/networks/test_kerber_networks.py | 4 +- pandapower/test/opf/test_cost_consistency.py | 2 +- pandapower/test/opf/test_pandamodels_runpm.py | 54 +++++++++---------- .../test/shortcircuit/test_all_currents.py | 4 +- .../test/toolbox/test_grid_modification.py | 2 +- pandapower/toolbox/grid_modification.py | 22 ++++---- 20 files changed, 83 insertions(+), 83 deletions(-) diff --git a/pandapower/converter/pypower/from_ppc.py b/pandapower/converter/pypower/from_ppc.py index 249427e36..6356909fc 100644 --- a/pandapower/converter/pypower/from_ppc.py +++ b/pandapower/converter/pypower/from_ppc.py @@ -171,8 +171,8 @@ def _from_ppc_gen(net, ppc): for is_, idx, et in zip([is_ext_grid, is_gen, is_sgen], [idx_eg, idx_gen, idx_sgen], ["ext_grid", "gen", "sgen"]): - gen_lookup["element"].loc[is_] = idx - gen_lookup["element_type"].loc[is_] = et + gen_lookup.loc[is_, "element"] = idx + gen_lookup.loc[is_, "element_type"] = et return gen_lookup @@ -272,10 +272,10 @@ def _from_ppc_branch(net, ppc, f_hz, **kwargs): # branch_lookup: which branches are lines, and which ones are transformers branch_lookup = pd.DataFrame({"element": [-1] * n_bra, "element_type": [""] * n_bra}) - branch_lookup["element"].loc[is_line] = idx_line - branch_lookup["element_type"].loc[is_line] = "line" - branch_lookup["element"].loc[~is_line] = idx_trafo - branch_lookup["element_type"].loc[~is_line] = "trafo" + branch_lookup.loc[is_line, "element"] = idx_line + branch_lookup.loc[is_line, "element_type"] = "line" + branch_lookup.loc[~is_line, "element"] = idx_trafo + branch_lookup.loc[~is_line, "element_type"] = "trafo" return branch_lookup diff --git a/pandapower/diagnostic.py b/pandapower/diagnostic.py index 534e45e96..95a03b6b1 100644 --- a/pandapower/diagnostic.py +++ b/pandapower/diagnostic.py @@ -549,7 +549,7 @@ def impedance_values_close_to_zero(net, min_r_ohm, min_x_ohm, min_r_pu, min_x_pu if key == 'xward': continue implausible_idx = implausible_elements[key] - net[key].in_service.loc[implausible_idx] = False + net[key].loc[implausible_idx, "in_service"] = False for idx in implausible_idx: pp.create_switch(net, net[key].from_bus.at[idx], net[key].to_bus.at[idx], et="b") runpp(net) diff --git a/pandapower/estimation/util.py b/pandapower/estimation/util.py index cce3f5420..a43f39b56 100644 --- a/pandapower/estimation/util.py +++ b/pandapower/estimation/util.py @@ -22,8 +22,8 @@ def estimate_voltage_vector(net): net_graph = create_nxgraph(net, include_trafos=False) for _, ext_grid in net.ext_grid.iterrows(): area = list(connected_component(net_graph, ext_grid.bus)) - res_bus.vm_pu.loc[area] = ext_grid.vm_pu - res_bus.va_degree.loc[area] = ext_grid.va_degree + res_bus.loc[area, "vm_pu"] = ext_grid.vm_pu + res_bus.loc[area, "va_degree"] = ext_grid.va_degree trafos = net.trafo[net.trafo.in_service == 1] trafo_index = trafos.index.tolist() while len(trafo_index): @@ -35,8 +35,8 @@ def estimate_voltage_vector(net): shift = trafo.shift_degree if "shift_degree" in trafo else 0 ratio = (trafo.vn_hv_kv / trafo.vn_lv_kv) / (net.bus.vn_kv.at[trafo.hv_bus] / net.bus.vn_kv.at[trafo.lv_bus]) - res_bus.vm_pu.loc[area] = res_bus.vm_pu.at[trafo.hv_bus] * ratio - res_bus.va_degree.loc[area] = res_bus.va_degree.at[trafo.hv_bus] - shift + res_bus.loc[area, "vm_pu"] = res_bus.vm_pu.at[trafo.hv_bus] * ratio + res_bus.loc[area, "va_degree"] = res_bus.va_degree.at[trafo.hv_bus] - shift except KeyError: raise UserWarning("An out-of-service bus is connected to an in-service " "transformer. Please set the transformer out of service or" @@ -48,8 +48,8 @@ def estimate_voltage_vector(net): if len(trafo_index) == len(trafos): # after the initial run we could not identify any areas correctly, it's probably a transmission grid # with slack on the LV bus and multiple transformers/gens. do flat init and return - res_bus.vm_pu.loc[res_bus.vm_pu.isnull()] = 1. - res_bus.va_degree.loc[res_bus.va_degree.isnull()] = 0. + res_bus.loc[res_bus.vm_pu.isnull(), "vm_pu"] = 1. + res_bus.loc[res_bus.va_degree.isnull(), "va_degree"] = 0. return res_bus return res_bus @@ -61,7 +61,7 @@ def _get_bus_ppc_mapping(net, bus_to_be_fused): set(net.xward.bus)) # Run dc pp to get the ppc we need #pp.rundcpp(net) - + pp.runpp(net, calculate_voltage_angles=True) bus_ppci = pd.DataFrame(data=net._pd2ppc_lookups['bus'], columns=["bus_ppci"]) diff --git a/pandapower/grid_equivalents/auxiliary.py b/pandapower/grid_equivalents/auxiliary.py index 4fc6cc936..19053a2b9 100644 --- a/pandapower/grid_equivalents/auxiliary.py +++ b/pandapower/grid_equivalents/auxiliary.py @@ -392,7 +392,7 @@ def ensure_origin_id(net, no_start=0, elms=None): if "origin_id" not in net[elm].columns: net[elm]["origin_id"] = pd.Series([None]*net[elm].shape[0], dtype=object) idxs = net[elm].index[net[elm].origin_id.isnull()] - net[elm].origin_id.loc[idxs] = ["%s_%i_%s" % (elm, idx, str(uuid.uuid4())) for idx in idxs] + net[elm].loc[idxs, "origin_id"] = ["%s_%i_%s" % (elm, idx, str(uuid.uuid4())) for idx in idxs] def drop_and_edit_cost_functions(net, buses, drop_cost, add_origin_id, @@ -410,7 +410,7 @@ def drop_and_edit_cost_functions(net, buses, drop_cost, add_origin_id, for elm in set(net[cost_elm].et.values): idx = net[cost_elm].element.index[(net[cost_elm].et == elm) & (net[cost_elm].element.isin(net[elm].index))] - net[cost_elm]["bus"].loc[idx] = net[elm].bus.loc[net[cost_elm].element.loc[ + net[cost_elm].loc[idx, "bus"] = net[elm].bus.loc[net[cost_elm].element.loc[ idx]].values to_drop = net[cost_elm].index[net[cost_elm].bus.isin(buses) | net[cost_elm].bus.isnull()] @@ -425,10 +425,10 @@ def drop_and_edit_cost_functions(net, buses, drop_cost, add_origin_id, net[cost_elm]["origin_seq"] = None for elm in set(net[cost_elm].et.values): idx = net[cost_elm].index[net[cost_elm].et == elm] - net[cost_elm]["et_origin_id"].loc[idx] = net[elm].origin_id.loc[net[ + net[cost_elm].loc[idx, "et_origin_id"] = net[elm].origin_id.loc[net[ cost_elm].element.loc[idx]].values - net[cost_elm]["origin_idx"].loc[idx] = idx - net[cost_elm]["origin_seq"].loc[idx] = [cost_backup.index.tolist().index(t) for t in idx] + net[cost_elm].loc[idx, "origin_idx"] = idx + net[cost_elm].loc[idx, "origin_seq"] = [cost_backup.index.tolist().index(t) for t in idx] def match_cost_functions_and_eq_net(net, boundary_buses, eq_type): diff --git a/pandapower/grid_equivalents/get_equivalent.py b/pandapower/grid_equivalents/get_equivalent.py index 099e7c9e3..85cd7a68b 100644 --- a/pandapower/grid_equivalents/get_equivalent.py +++ b/pandapower/grid_equivalents/get_equivalent.py @@ -267,7 +267,7 @@ def get_equivalent(net, eq_type, boundary_buses, internal_buses, net_eq, net_internal, show_computing_time=show_computing_time, calc_volt_angles=calculate_voltage_angles) if len(orig_slack_gens): - net_eq.gen.slack.loc[net_eq.gen.index.intersection(orig_slack_gens)] = True + net_eq.gen.loc[net_eq.gen.index.intersection(orig_slack_gens), "slack"] = True # run final power flow calculation net_eq = runpp_fct(net_eq, calculate_voltage_angles=calculate_voltage_angles) else: diff --git a/pandapower/grid_equivalents/rei_generation.py b/pandapower/grid_equivalents/rei_generation.py index 53ccc1fd4..5e5f4c3b6 100644 --- a/pandapower/grid_equivalents/rei_generation.py +++ b/pandapower/grid_equivalents/rei_generation.py @@ -592,8 +592,8 @@ def _calclate_equivalent_element_params(net_zpbn, Ybus_eq, bus_lookups, non_zero_cr = np.abs(params[cols, rows]) > 1/max_allowed_impedance impedance_params["rtf_pu"] = 1e5 impedance_params["xtf_pu"] = 1e5 - impedance_params["rtf_pu"].loc[non_zero_cr] = (-1 / params[cols, rows]).real[non_zero_cr] - impedance_params["xtf_pu"].loc[non_zero_cr] = (-1 / params[cols, rows]).imag[non_zero_cr] + impedance_params.loc[non_zero_cr, "rtf_pu"] = (-1 / params[cols, rows]).real[non_zero_cr] + impedance_params.loc[non_zero_cr, "xtf_pu"] = (-1 / params[cols, rows]).imag[non_zero_cr] t_end = time.perf_counter() if show_computing_time: diff --git a/pandapower/grid_equivalents/toolbox.py b/pandapower/grid_equivalents/toolbox.py index 419b1ca49..b365d7117 100644 --- a/pandapower/grid_equivalents/toolbox.py +++ b/pandapower/grid_equivalents/toolbox.py @@ -105,7 +105,7 @@ def set_bus_zone_by_boundary_branches(net, all_boundary_branches): areas[-1] |= ccl.pop(i) for i, area in enumerate(areas): - net.bus.zone.loc[list(area)] = i + net.bus.loc[list(area), "zone"] = i def get_boundaries_by_bus_zone_with_boundary_branches(net): diff --git a/pandapower/groups.py b/pandapower/groups.py index 20f636ba2..c81970168 100644 --- a/pandapower/groups.py +++ b/pandapower/groups.py @@ -169,7 +169,7 @@ def attach_to_group(net, index, element_types, elements, reference_columns=None, prev_elm = net.group.element.loc[group_et].at[index] prev_elm = [prev_elm] if isinstance(prev_elm, str) or not hasattr( prev_elm, "__iter__") else list(prev_elm) - net.group.element.loc[group_et] = [prev_elm + list(pd.Index(elm).difference( + net.group.loc[group_et, "element"] = [prev_elm + list(pd.Index(elm).difference( pd.Index(prev_elm)))] # --- prepare adding new rows to net.group (because no other elements of element type et diff --git a/pandapower/networks/create_examples.py b/pandapower/networks/create_examples.py index 9d40eb80c..f0330d0c8 100644 --- a/pandapower/networks/create_examples.py +++ b/pandapower/networks/create_examples.py @@ -371,7 +371,7 @@ def example_multivoltage(): name='Switch %s - %s' % (net.bus.name.at[bus], line['name'])) open_switch_id = net.switch[(net.switch.name == 'Switch Bus MV5 - MV Line5')].index - net.switch.closed.loc[open_switch_id] = False + net.switch.loc[open_switch_id, "closed"] = False # LV # Bus-line switches diff --git a/pandapower/networks/mv_oberrhein.py b/pandapower/networks/mv_oberrhein.py index 4a15419ff..31efb94c5 100644 --- a/pandapower/networks/mv_oberrhein.py +++ b/pandapower/networks/mv_oberrhein.py @@ -72,11 +72,11 @@ def mv_oberrhein(scenario="load", cosphi_load=0.98, cosphi_pv=1.0, include_subst if scenario == "load": net.load.scaling = 0.6 net.sgen.scaling = 0.0 - net.trafo.tap_pos.loc[hv_trafos] = [-2, -3] + net.trafo.loc[hv_trafos, "tap_pos"] = [-2, -3] elif scenario == "generation": net.load.scaling = 0.1 net.sgen.scaling = 0.8 - net.trafo.tap_pos.loc[hv_trafos] = [0, 0] + net.trafo.loc[hv_trafos, "tap_pos"] = [0, 0] else: raise ValueError("Unknown scenario %s - chose 'load' or 'generation'" % scenario) diff --git a/pandapower/networks/power_system_test_cases.py b/pandapower/networks/power_system_test_cases.py index 324b53d06..60611a652 100644 --- a/pandapower/networks/power_system_test_cases.py +++ b/pandapower/networks/power_system_test_cases.py @@ -318,12 +318,12 @@ def case57(vn_kv_area1=115, vn_kv_area2=500, vn_kv_area3=138, vn_kv_area4=345, v Idx_area4 = case57.bus[case57.bus.vn_kv == 130].index Idx_area5 = case57.bus[case57.bus.vn_kv == 140].index Idx_area6 = case57.bus[case57.bus.vn_kv == 150].index - case57.bus.vn_kv.loc[Idx_area1] = vn_kv_area1 # default 115 - case57.bus.vn_kv.loc[Idx_area2] = vn_kv_area2 # default 500 - case57.bus.vn_kv.loc[Idx_area3] = vn_kv_area3 # default 138 - case57.bus.vn_kv.loc[Idx_area4] = vn_kv_area4 # default 345 - case57.bus.vn_kv.loc[Idx_area5] = vn_kv_area5 # default 230 - case57.bus.vn_kv.loc[Idx_area6] = vn_kv_area6 # default 161 + case57.bus.loc[Idx_area1, "vn_kv"] = vn_kv_area1 # default 115 + case57.bus.loc[Idx_area2, "vn_kv"] = vn_kv_area2 # default 500 + case57.bus.loc[Idx_area3, "vn_kv"] = vn_kv_area3 # default 138 + case57.bus.loc[Idx_area4, "vn_kv"] = vn_kv_area4 # default 345 + case57.bus.loc[Idx_area5, "vn_kv"] = vn_kv_area5 # default 230 + case57.bus.loc[Idx_area6, "vn_kv"] = vn_kv_area6 # default 161 return case57 diff --git a/pandapower/results_bus.py b/pandapower/results_bus.py index 0980a5332..479221ee4 100644 --- a/pandapower/results_bus.py +++ b/pandapower/results_bus.py @@ -211,7 +211,7 @@ def write_pq_results_to_element(net, ppc, element, suffix=None): # P result in mw to element net[res_]["p_mw"].values[:] = el_data[p_mw].values * scaling * element_in_service if is_controllable: - net[res_]["p_mw"].loc[controlled_elements] = ppc["gen"][gen_idx, PG] * gen_sign + net[res_].loc[controlled_elements, "p_mw"] = ppc["gen"][gen_idx, PG] * gen_sign # add results from distributed slack calculation for xwards from ppc instead of the element table if net._options['distributed_slack'] and element == "xward" and np.any(net.xward.loc[element_in_service, 'slack_weight'].values != 0): @@ -221,7 +221,7 @@ def write_pq_results_to_element(net, ppc, element, suffix=None): # Q result in mvar to element net[res_]["q_mvar"].values[:] = el_data[q_mvar].values * scaling * element_in_service if is_controllable: - net[res_]["q_mvar"].loc[controlled_elements] = ppc["gen"][gen_idx, QG] * gen_sign + net[res_].loc[controlled_elements, "q_mvar"] = ppc["gen"][gen_idx, QG] * gen_sign return net @@ -489,8 +489,8 @@ def _get_shunt_results(net, ppc, bus_lookup_aranged, bus_pq): net["res_svc"].loc[:, "q_mvar"] = q_svc # write all because of zeros net["res_svc"].loc[svc_is, "x_ohm"] = ppc["svc"][svc_is, SVC_X_PU] * baseZ[svcidx[svc_is]] q = np.hstack([q, q_svc]) - b = np.hstack([b, svc["bus"].values]) - + b = np.hstack([b, svc["bus"].values]) + # ssc = net["ssc"] # todo: uncomment this after PandaModels net also has this key ssc = net.get("ssc", np.array([])) if len(ssc): diff --git a/pandapower/test/grid_equivalents/test_get_equivalent.py b/pandapower/test/grid_equivalents/test_get_equivalent.py index f17b27d02..96d544938 100644 --- a/pandapower/test/grid_equivalents/test_get_equivalent.py +++ b/pandapower/test/grid_equivalents/test_get_equivalent.py @@ -245,7 +245,7 @@ def test_basic_usecases(): def test_case9_with_slack_generator_in_external_net(): net = pp.networks.case9() idx = pp.replace_ext_grid_by_gen(net) - net.gen.slack.loc[idx] = True + net.gen.loc[idx, "slack"] = True net.bus_geodata.drop(net.bus_geodata.index, inplace=True) pp.runpp(net) diff --git a/pandapower/test/loadflow/test_results.py b/pandapower/test/loadflow/test_results.py index 1f5058ed0..9d7112d79 100644 --- a/pandapower/test/loadflow/test_results.py +++ b/pandapower/test/loadflow/test_results.py @@ -213,7 +213,7 @@ def test_trafo(result_test_network, v_tol=1e-6, i_tol=1e-6, s_tol=1e-2, l_tol=1e assert abs(net.res_bus.va_degree.at[b3] - va3) < va_tol # sincal results to check pi-equivalent circuit model - net.trafo.parallel.loc[trafos] = 1 # sincal is tested without parallel transformers + net.trafo.loc[trafos, "parallel"] = 1 # sincal is tested without parallel transformers runpp_with_consistency_checks(net, trafo_model="pi", trafo_loading="current") load1 = 57.637 diff --git a/pandapower/test/networks/test_kerber_networks.py b/pandapower/test/networks/test_kerber_networks.py index bf368906f..e6068667e 100644 --- a/pandapower/test/networks/test_kerber_networks.py +++ b/pandapower/test/networks/test_kerber_networks.py @@ -25,8 +25,8 @@ def test_create_empty_network_with_transformer(): assert len(net.bus.index) == 2 assert len(net.trafo.index) == 1 assert len(net.ext_grid.index) == 1 - assert net.bus.vn_kv.loc[0] == v_os - assert net.bus.vn_kv.loc[1] == v_us + assert net.bus.loc[0, "vn_kv"] == v_os + assert net.bus.loc[1, "vn_kv"] == v_us def test_add_lines_and_loads(): diff --git a/pandapower/test/opf/test_cost_consistency.py b/pandapower/test/opf/test_cost_consistency.py index 918c5eab2..d8ebf11c4 100644 --- a/pandapower/test/opf/test_cost_consistency.py +++ b/pandapower/test/opf/test_cost_consistency.py @@ -47,7 +47,7 @@ def test_contingency_sgen(base_net): # p_min_mw |\ # | \ # | \ - net.pwl_cost.points.loc[pwl] = [(0, net.sgen.max_p_mw.at[0], -1)] + net.pwl_cost.loc[pwl, "points"] = [(0, net.sgen.max_p_mw.at[0], -1)] pp.runopp(net) assert isclose(net.res_cost, -net.res_sgen.p_mw.at[0], atol=1e-4) diff --git a/pandapower/test/opf/test_pandamodels_runpm.py b/pandapower/test/opf/test_pandamodels_runpm.py index 7d42deb5b..dcd1ad195 100644 --- a/pandapower/test/opf/test_pandamodels_runpm.py +++ b/pandapower/test/opf/test_pandamodels_runpm.py @@ -40,16 +40,16 @@ def create_cigre_grid_with_time_series(json_path, net=None, add_ts_constaints=Fa net = nw.create_cigre_network_mv("pv_wind") min_vm_pu = 0.95 max_vm_pu = 1.05 - + net["bus"].loc[:, "min_vm_pu"] = min_vm_pu net["bus"].loc[:, "max_vm_pu"] = max_vm_pu net["line"].loc[:, "max_loading_percent"] = 100. - + # close all switches net.switch.loc[:, "closed"] = True # add storage to bus 10 pp.create_storage(net, 10, p_mw=0.5, max_e_mwh=.2, soc_percent=0., q_mvar=0., controllable=True) - + # set the load type in the cigre grid, since it is not specified net["load"].loc[:, "type"] = "residential" @@ -76,7 +76,7 @@ def create_cigre_grid_with_time_series(json_path, net=None, add_ts_constaints=Fa sgen_ts.loc[t][:8] = sgen_p * time_series.at[t, "pv"] sgen_ts.loc[t][8] = wind_p * time_series.at[t, "wind"] - # create time series controller for load and sgen + # create time series controller for load and sgen ConstControl(net, element="load", variable="p_mw", element_index=net.load.index.tolist(), profile_name=net.load.index.tolist(), data_source=DFData(load_ts)) @@ -591,41 +591,41 @@ def test_storage_opt(): assert net._pm["pm_solver"] == "juniper" assert net._pm["pm_mip_solver"] == "cbc" assert len(net.res_ts_opt) == 5 - + net2 = create_cigre_grid_with_time_series(json_path) net2.sn_mva = 100.0 pp.runpm_storage_opf(net2, from_time_step=0, to_time_step=5) storage_results_100 = read_pm_storage_results(net2) - - assert abs(storage_results_100[0].values - storage_results_1[0].values).max() < 1e-6 + + assert abs(storage_results_100[0].values - storage_results_1[0].values).max() < 1e-6 @pytest.mark.slow @pytest.mark.skipif(julia_installed == False, reason="requires julia installation") def test_runpm_multi_vstab(): - net = nw.create_cigre_network_mv(with_der="pv_wind") + net = nw.create_cigre_network_mv(with_der="pv_wind") net.load['controllable'] = False net.sgen['controllable'] = True # lower and upper bounds for buses net.bus["max_vm_pu"] = 1.1 net.bus["min_vm_pu"] = 0.9 - + # lower and upper bounds for external grid net.ext_grid["max_q_mvar"] = 10000.0 net.ext_grid["min_q_mvar"] = -10000.0 net.ext_grid["max_p_mw"] = 10000.0 net.ext_grid["min_p_mw"] = -10000.0 - + # lower and upper bounds for DERs net.sgen["max_p_mw"] = net.sgen.p_mw.values net.sgen["min_p_mw"] = net.sgen.p_mw.values net.sgen["max_q_mvar"] = net.sgen.p_mw.values * 0.328 net.sgen["min_q_mvar"] = -net.sgen.p_mw.values * 0.328 - + net.trafo["max_loading_percent"] = 100.0 net.line["max_loading_percent"] = 100.0 - + net.bus["pm_param/setpoint_v"] = None # add extra column net.bus["pm_param/setpoint_v"].loc[net.sgen.bus] = 0.96 @@ -633,15 +633,15 @@ def test_runpm_multi_vstab(): json_path = os.path.join(pp_dir, "test", "opf", "cigre_timeseries_15min.json") create_cigre_grid_with_time_series(json_path, net, True) - # run time series opf + # run time series opf pp.runpm_multi_vstab(net, from_time_step=0, to_time_step=96) assert len(net.res_ts_opt) == 96 - - # get opf-results + + # get opf-results y_multi = [] for t in range(96): y_multi.append(net.res_ts_opt[str(t)].res_bus.vm_pu[net.sgen.bus].values.mean() - 0.96) - + assert np.array(y_multi).max() < 0.018 assert np.array(y_multi).min() > -0.002 @@ -649,50 +649,50 @@ def test_runpm_multi_vstab(): @pytest.mark.slow @pytest.mark.skipif(julia_installed == False, reason="requires julia installation") def test_runpm_qflex_and_multi_qflex(): - - net = nw.create_cigre_network_mv(with_der="pv_wind") + + net = nw.create_cigre_network_mv(with_der="pv_wind") pp.runpp(net) - + net.load['controllable'] = False net.sgen['controllable'] = True # lower and upper bounds for buses net.bus["max_vm_pu"] = 1.1 net.bus["min_vm_pu"] = 0.9 - + # lower and upper bounds for external grid net.ext_grid["max_q_mvar"] = 10000.0 net.ext_grid["min_q_mvar"] = -10000.0 net.ext_grid["max_p_mw"] = 10000.0 net.ext_grid["min_p_mw"] = -10000.0 - + # lower and upper bounds for DERs net.sgen["max_p_mw"] = net.sgen.p_mw.values net.sgen["min_p_mw"] = net.sgen.p_mw.values net.sgen["max_q_mvar"] = net.sgen.p_mw.values * 0.828 net.sgen["min_q_mvar"] = -net.sgen.p_mw.values * 0.828 - + net.trafo["max_loading_percent"] = 100.0 net.line["max_loading_percent"] = 100.0 - + net.trafo["pm_param/setpoint_q"] = None # add extra column net.trafo["pm_param/setpoint_q"].loc[0] = -5 net.trafo["pm_param/side"] = None net.trafo["pm_param/side"][0] = "lv" - + # run opf pp.runpm_qflex(net) opt_q = net.res_trafo.q_lv_mvar[0] assert abs(opt_q + 5) < 1e-6 - + # test for multi_qflex # load time series data for 96 time steps json_path = os.path.join(pp_dir, "test", "opf", "cigre_timeseries_15min.json") create_cigre_grid_with_time_series(json_path, net, True) pp.runpm_multi_qflex(net, from_time_step=0, to_time_step=96) - # get opf-results + # get opf-results y_multi = [] for t in range(96): - y_multi.append(abs(abs(net.res_ts_opt[str(t)].res_trafo.q_lv_mvar[0])-5)) + y_multi.append(abs(abs(net.res_ts_opt[str(t)].res_trafo.q_lv_mvar[0])-5)) assert np.array(y_multi).max() < 1e-6 diff --git a/pandapower/test/shortcircuit/test_all_currents.py b/pandapower/test/shortcircuit/test_all_currents.py index b9937a16f..e71cd4176 100644 --- a/pandapower/test/shortcircuit/test_all_currents.py +++ b/pandapower/test/shortcircuit/test_all_currents.py @@ -258,8 +258,8 @@ def test_with_permuted_index(): def test_all_currents_with_oos_elements(): net = three_bus_example() - net.bus.in_service.loc[2] = False - net.line.in_service.loc[1] = False + net.bus.loc[2, "in_service"] = False + net.line.loc[1, "in_service"] = False sc.calc_sc(net, case="max", branch_results=True, return_all_currents=True) assert np.allclose(net.res_line_sc.ikss_ka.loc[[(0, 0), (0, 1)]].values, diff --git a/pandapower/test/toolbox/test_grid_modification.py b/pandapower/test/toolbox/test_grid_modification.py index 8c27fbf72..ed73f0d83 100644 --- a/pandapower/test/toolbox/test_grid_modification.py +++ b/pandapower/test/toolbox/test_grid_modification.py @@ -579,7 +579,7 @@ def test_replace_ext_grid_gen(): assert np.allclose(net.gen.vm_pu.values, [1.03, 1.02]) assert net.res_gen.p_mw.dropna().shape[0] == 2 assert np.allclose(net.gen.index.values, [0, 4]) - assert net.gen.uuid.loc[4] == "test" + assert net.gen.loc[4, "uuid"] == "test" assert net.group.element_type.tolist() == ["line", "gen"] assert net.group.element.iat[1] == [4] diff --git a/pandapower/toolbox/grid_modification.py b/pandapower/toolbox/grid_modification.py index a03262d19..13f04501f 100644 --- a/pandapower/toolbox/grid_modification.py +++ b/pandapower/toolbox/grid_modification.py @@ -1193,7 +1193,7 @@ def replace_ext_grid_by_gen(net, ext_grids=None, gen_indices=None, slack=False, idx = create_gen(net, ext_grid.bus, vm_pu=ext_grid.vm_pu, p_mw=p_mw, name=ext_grid.name, in_service=ext_grid.in_service, controllable=True, index=index) new_idx.append(idx) - net.gen.slack.loc[new_idx] = slack + net.gen.loc[new_idx, "slack"] = slack net.gen.loc[new_idx, existing_cols_to_keep] = net.ext_grid.loc[ ext_grids, existing_cols_to_keep].values @@ -1208,8 +1208,8 @@ def replace_ext_grid_by_gen(net, ext_grids=None, gen_indices=None, slack=False, to_change = net[table].index[(net[table].et == "ext_grid") & (net[table].element.isin(ext_grids))] if len(to_change): - net[table].et.loc[to_change] = "gen" - net[table].element.loc[to_change] = new_idx + net[table].loc[to_change, "et"] = "gen" + net[table].loc[to_change, "element"] = new_idx # --- result data if net.res_ext_grid.shape[0]: @@ -1290,8 +1290,8 @@ def replace_gen_by_ext_grid(net, gens=None, ext_grid_indices=None, cols_to_keep= if net[table].shape[0]: to_change = net[table].index[(net[table].et == "gen") & (net[table].element.isin(gens))] if len(to_change): - net[table].et.loc[to_change] = "ext_grid" - net[table].element.loc[to_change] = new_idx + net[table].loc[to_change, "et"] = "ext_grid" + net[table].loc[to_change, "element"] = new_idx # --- result data if net.res_gen.shape[0]: @@ -1374,8 +1374,8 @@ def replace_gen_by_sgen(net, gens=None, sgen_indices=None, cols_to_keep=None, if net[table].shape[0]: to_change = net[table].index[(net[table].et == "gen") & (net[table].element.isin(gens))] if len(to_change): - net[table].et.loc[to_change] = "sgen" - net[table].element.loc[to_change] = new_idx + net[table].loc[to_change, "et"] = "sgen" + net[table].loc[to_change, "element"] = new_idx # --- result data if net.res_gen.shape[0]: @@ -1474,8 +1474,8 @@ def replace_sgen_by_gen(net, sgens=None, gen_indices=None, cols_to_keep=None, to_change = net[table].index[(net[table].et == "sgen") & (net[table].element.isin(sgens))] if len(to_change): - net[table].et.loc[to_change] = "gen" - net[table].element.loc[to_change] = new_idx + net[table].loc[to_change, "et"] = "gen" + net[table].loc[to_change, "element"] = new_idx # --- result data if net.res_sgen.shape[0]: @@ -1594,8 +1594,8 @@ def replace_pq_elmtype(net, old_element_type, new_element_type, old_indices=None to_change = net[table].index[(net[table].et == old_element_type) & (net[table].element.isin(old_indices))] if len(to_change): - net[table].et.loc[to_change] = new_element_type - net[table].element.loc[to_change] = new_idx + net[table].loc[to_change, "et"] = new_element_type + net[table].loc[to_change, "element"] = new_idx # --- result data if net["res_" + old_element_type].shape[0]: From e9136d7e62bcd644c0040a539783d56e0fee8ed9 Mon Sep 17 00:00:00 2001 From: Steffen Meinecke Date: Mon, 25 Mar 2024 11:22:36 +0100 Subject: [PATCH 02/17] df.col.loc[idx] = -> df.loc[idx, col] --- pandapower/grid_equivalents/auxiliary.py | 4 ++-- pandapower/test/api/test_diagnostic.py | 4 ++-- pandapower/toolbox/data_modification.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pandapower/grid_equivalents/auxiliary.py b/pandapower/grid_equivalents/auxiliary.py index 19053a2b9..2b2877c8d 100644 --- a/pandapower/grid_equivalents/auxiliary.py +++ b/pandapower/grid_equivalents/auxiliary.py @@ -272,8 +272,8 @@ def _ensure_unique_boundary_bus_names(net, boundary_buses): """ assert "name_equivalent" not in net.bus.columns.tolist() net.bus["name_equivalent"] = "uuid" - net.bus.name_equivalent.loc[boundary_buses] = ["Boundary bus " + str(uuid.uuid1()) for _ in - boundary_buses] + net.bus.loc[boundary_buses, "name_equivalent"] = ["Boundary bus " + str(uuid.uuid1()) for _ in + boundary_buses] def drop_assist_elms_by_creating_ext_net(net, elms=None): diff --git a/pandapower/test/api/test_diagnostic.py b/pandapower/test/api/test_diagnostic.py index dcc3c33f0..128f6df89 100644 --- a/pandapower/test/api/test_diagnostic.py +++ b/pandapower/test/api/test_diagnostic.py @@ -528,7 +528,7 @@ def test_different_voltage_levels_connected(test_net, diag_params, diag_errors, diag_params = copy.deepcopy(diag_params) report_methods = copy.deepcopy(report_methods) pp.create_switch(net, 41, 45, et = 'b') - net.bus.vn_kv.loc[38] = 30 + net.bus.loc[38, "vn_kv"] = 30 check_result = pp.different_voltage_levels_connected(net) if check_result: diag_results = {check_function: check_result} @@ -967,7 +967,7 @@ def test_deviation_from_std_type(test_net, diag_params, diag_errors, report_meth net.line.r_ohm_per_km.loc[0] += 1 net.line.x_ohm_per_km.loc[6] -= 1 net.line.c_nf_per_km.loc[14] *= -1 - net.line.max_i_ka.loc[21] = '5' + net.line.loc[21, "max_i_ka"] = '5' pp.change_std_type(net, 0, element='trafo', name='160 MVA 380/110 kV') net.trafo.vk_percent.loc[0] *= 2 check_result = pp.deviation_from_std_type(net) diff --git a/pandapower/toolbox/data_modification.py b/pandapower/toolbox/data_modification.py index d68262b8f..f3897736e 100644 --- a/pandapower/toolbox/data_modification.py +++ b/pandapower/toolbox/data_modification.py @@ -325,7 +325,7 @@ def reindex_elements(net, element_type, new_indices=None, old_indices=None, look for cost_df in ["pwl_cost", "poly_cost"]: element_in_cost_df = (net[cost_df].et == element_type) & net[cost_df].element.isin(old_indices) if sum(element_in_cost_df): - net[cost_df].element.loc[element_in_cost_df] = get_indices(net[cost_df].element[ + net[cost_df].loc[element_in_cost_df, "element"] = get_indices(net[cost_df].element[ element_in_cost_df], lookup) From a1928a459e29ee88e2ca34e148005791a3e0107f Mon Sep 17 00:00:00 2001 From: Steffen Meinecke Date: Mon, 25 Mar 2024 11:30:40 +0100 Subject: [PATCH 03/17] df.col.at[idx] = -> df.at[idx, col] --- .../protection/protection_devices/fuse.py | 2 +- .../protection/protection_devices/ocrelay.py | 2 +- pandapower/protection/utility_functions.py | 6 +-- pandapower/test/api/test_diagnostic.py | 36 +++++++-------- pandapower/test/api/test_group.py | 4 +- pandapower/test/api/test_std_types.py | 2 +- .../control/test_continuous_tap_control.py | 8 ++-- .../test/control/test_discrete_tap_control.py | 16 +++---- .../test/control/test_vm_set_tap_control.py | 20 ++++---- .../loadflow/result_test_network_generator.py | 6 +-- pandapower/test/loadflow/test_dist_slack.py | 10 ++-- pandapower/test/loadflow/test_facts.py | 10 ++-- pandapower/test/loadflow/test_results.py | 12 ++--- pandapower/test/loadflow/test_rundcpp.py | 4 +- pandapower/test/loadflow/test_runpp.py | 46 +++++++++---------- pandapower/test/loadflow/test_scenarios.py | 40 ++++++++-------- pandapower/test/opf/test_basic.py | 6 +-- pandapower/test/opf/test_costs_mixed.py | 4 +- pandapower/test/opf/test_costs_pol.py | 2 +- pandapower/test/opf/test_pandamodels_runpm.py | 4 +- pandapower/test/protection/test_fuse.py | 2 +- pandapower/test/protection/test_oc_relay.py | 8 ++-- .../test/shortcircuit/test_all_currents.py | 28 +++++------ pandapower/test/shortcircuit/test_gen.py | 12 ++--- .../test/toolbox/test_element_selection.py | 14 +++--- .../test/toolbox/test_grid_modification.py | 12 ++--- pandapower/test/topology/test_create_graph.py | 8 ++-- 27 files changed, 162 insertions(+), 162 deletions(-) diff --git a/pandapower/protection/protection_devices/fuse.py b/pandapower/protection/protection_devices/fuse.py index 04f38c742..48012c483 100644 --- a/pandapower/protection/protection_devices/fuse.py +++ b/pandapower/protection/protection_devices/fuse.py @@ -96,7 +96,7 @@ def has_tripped(self): def status_to_net(self, net): # update self.tripped status to net - net.switch.closed.at[self.switch_index] = not self.tripped + net.switch.at[self.switch_index, "closed"] = not self.tripped def protection_function(self, net, scenario="sc"): # compute protection time in net under short-circuit or operating conditions diff --git a/pandapower/protection/protection_devices/ocrelay.py b/pandapower/protection/protection_devices/ocrelay.py index cb7fe3a13..6a61307c2 100644 --- a/pandapower/protection/protection_devices/ocrelay.py +++ b/pandapower/protection/protection_devices/ocrelay.py @@ -193,7 +193,7 @@ def has_tripped(self): def status_to_net(self, net): # update self.tripped status to net - net.switch.closed.at[self.switch_index] = not self.tripped + net.switch.at[self.switch_index, "closed"] = not self.tripped def protection_function(self, net, scenario): # compute protection time in net under short-circuit or operating conditions diff --git a/pandapower/protection/utility_functions.py b/pandapower/protection/utility_functions.py index f4a8d3ffb..d43b47cf6 100644 --- a/pandapower/protection/utility_functions.py +++ b/pandapower/protection/utility_functions.py @@ -70,7 +70,7 @@ def create_sc_bus(net_copy, sc_line_id, sc_fraction): index = max_idx_line+1, r_ohm_per_km = aux_line.r_ohm_per_km, x_ohm_per_km = aux_line.x_ohm_per_km, c_nf_per_km = aux_line.c_nf_per_km, max_i_ka = aux_line.max_i_ka) if 'endtemp_degree' in net.line.columns: - net.line.endtemp_degree.at[sc_line2] = net.line.endtemp_degree.at[sc_line1] + net.line.at[sc_line2, "endtemp_degree"] = net.line.endtemp_degree.at[sc_line1] net.line = net.line.sort_index() @@ -89,8 +89,8 @@ def create_sc_bus(net_copy, sc_line_id, sc_fraction): y1 = net.bus_geodata.y.at[aux_line.from_bus] y2 = net.bus_geodata.y.at[aux_line.to_bus] - net.bus_geodata.x.at[max_idx_bus+1] = sc_fraction*(x2-x1) + x1 - net.bus_geodata.y.at[max_idx_bus+1] = sc_fraction*(y2-y1) + y1 + net.bus_geodata.at[max_idx_bus+1, "x"] = sc_fraction*(x2-x1) + x1 + net.bus_geodata.at[max_idx_bus+1, "y"] = sc_fraction*(y2-y1) + y1 return net diff --git a/pandapower/test/api/test_diagnostic.py b/pandapower/test/api/test_diagnostic.py index 128f6df89..76f60216b 100644 --- a/pandapower/test/api/test_diagnostic.py +++ b/pandapower/test/api/test_diagnostic.py @@ -385,9 +385,9 @@ def test_multiple_voltage_controlling_elements_per_bus(test_net, diag_params, di check_function = 'multiple_voltage_controlling_elements_per_bus' diag_params = copy.deepcopy(diag_params) report_methods = copy.deepcopy(report_methods) - net.gen.bus.at[0] = 0 + net.gen.at[0, "bus"] = 0 pp.create_ext_grid(net, 1) - net.ext_grid.bus.at[1] = 0 + net.ext_grid.at[1, "bus"] = 0 check_result = pp.multiple_voltage_controlling_elements_per_bus(net) if check_result: @@ -553,14 +553,14 @@ def test_impedance_values_close_to_zero(test_net, diag_params, diag_errors, repo # line test net = copy.deepcopy(test_net) check_function = 'impedance_values_close_to_zero' - net.line.length_km.at[0] = 0 - net.line.r_ohm_per_km.at[1] = 0 - net.line.x_ohm_per_km.at[1] = 0 - net.line.r_ohm_per_km.at[2] = 0 - net.line.x_ohm_per_km.at[3] = 0 - net.line.length_km.at[4] = 0 - net.line.r_ohm_per_km.at[4] = 0 - net.line.x_ohm_per_km.at[4] = 0 + net.line.at[0, "length_km"] = 0 + net.line.at[1, "r_ohm_per_km"] = 0 + net.line.at[1, "x_ohm_per_km"] = 0 + net.line.at[2, "r_ohm_per_km"] = 0 + net.line.at[3, "x_ohm_per_km"] = 0 + net.line.at[4, "length_km"] = 0 + net.line.at[4, "r_ohm_per_km"] = 0 + net.line.at[4, "x_ohm_per_km"] = 0 net.xward.drop(net.xward.index, inplace=True) check_result = pp.impedance_values_close_to_zero(net, diag_params['min_r_ohm'], diag_params['min_x_ohm'], diag_params['min_r_pu'], diag_params['min_x_pu']) @@ -680,8 +680,8 @@ def test_nominal_voltages_dont_match(test_net, diag_params, diag_errors, report_ report_methods = copy.deepcopy(report_methods) trafo_copy = copy.deepcopy(net.trafo) trafo3w_copy = copy.deepcopy(net.trafo3w) - net.trafo.hv_bus.at[0] = trafo_copy.lv_bus.at[0] - net.trafo.lv_bus.at[0] = trafo_copy.hv_bus.at[0] + net.trafo.at[0, "hv_bus"] = trafo_copy.lv_bus.at[0] + net.trafo.at[0, "lv_bus"] = trafo_copy.hv_bus.at[0] check_result = pp.nominal_voltages_dont_match(net, diag_params['nom_voltage_tolerance']) if check_result: diag_results = {check_function: check_result} @@ -784,9 +784,9 @@ def test_nominal_voltages_dont_match(test_net, diag_params, diag_errors, report_ net.trafo = copy.deepcopy(trafo_copy) - net.trafo3w.hv_bus.at[0] = trafo3w_copy.mv_bus.at[0] - net.trafo3w.mv_bus.at[0] = trafo3w_copy.lv_bus.at[0] - net.trafo3w.lv_bus.at[0] = trafo3w_copy.hv_bus.at[0] + net.trafo3w.at[0, "hv_bus"] = trafo3w_copy.mv_bus.at[0] + net.trafo3w.at[0, "mv_bus"] = trafo3w_copy.lv_bus.at[0] + net.trafo3w.at[0, "lv_bus"] = trafo3w_copy.hv_bus.at[0] check_result = pp.nominal_voltages_dont_match(net, diag_params['nom_voltage_tolerance']) if check_result: diag_results = {check_function: check_result} @@ -899,9 +899,9 @@ def test_wrong_reference_system(test_net, diag_params, diag_errors, report_metho check_function = 'wrong_reference_system' diag_params = copy.deepcopy(diag_params) report_methods = copy.deepcopy(report_methods) - net.load.p_mw.at[0] = -1 - net.gen.p_mw.at[0] = -1 - net.sgen.p_mw.at[0] = -1 + net.load.at[0, "p_mw"] = -1 + net.gen.at[0, "p_mw"] = -1 + net.sgen.at[0, "p_mw"] = -1 check_result = pp.wrong_reference_system(net) if check_result: diag_results = {check_function: check_result} diff --git a/pandapower/test/api/test_group.py b/pandapower/test/api/test_group.py index 45e8c5db6..1037e9446 100644 --- a/pandapower/test/api/test_group.py +++ b/pandapower/test/api/test_group.py @@ -426,8 +426,8 @@ def test_elements_connected_to_group(): pp.create_switches(net, [0, 0, 6], [0, 1, net.line.index[-1]], "l", closed=[True, False, False]) pp.create_switches(net, [0]*3, [7, 8, 9], "b", closed=[True, False, True]) pp.create_switches(net, [0]*2, [10, 11], "b", closed=[True, False]) - net.load.in_service.at[0] = False - net.line.in_service.at[4] = False + net.load.at[0, "in_service"] = False + net.line.at[4, "in_service"] = False net.bus.in_service.loc[[3, 9]] = False # create group diff --git a/pandapower/test/api/test_std_types.py b/pandapower/test/api/test_std_types.py index ff4f60940..a99de171b 100644 --- a/pandapower/test/api/test_std_types.py +++ b/pandapower/test/api/test_std_types.py @@ -328,7 +328,7 @@ def test_parameter_from_std_type_line(): assert net.line.endtemp_degree.at[lid2] == endtemp2 #type2 has specified endtemp assert net.line.endtemp_degree.at[lid3] == endtemp_fill #line3 has no standard type - net.line.endtemp_degree.at[lid3] = 10 + net.line.at[lid3, "endtemp_degree"] = 10 pp.parameter_from_std_type(net, "endtemp_degree", fill=endtemp_fill) assert net.line.endtemp_degree.at[lid3] == 10 #check that existing values arent overwritten diff --git a/pandapower/test/control/test_continuous_tap_control.py b/pandapower/test/control/test_continuous_tap_control.py index 62ce4732d..674c5c80e 100644 --- a/pandapower/test/control/test_continuous_tap_control.py +++ b/pandapower/test/control/test_continuous_tap_control.py @@ -48,7 +48,7 @@ def test_continuous_tap_control_lv(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 1.03 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -66,7 +66,7 @@ def test_continuous_tap_control_lv(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 0.98 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -116,7 +116,7 @@ def test_continuous_tap_control_hv(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 1.03 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -134,7 +134,7 @@ def test_continuous_tap_control_hv(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 0.98 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") diff --git a/pandapower/test/control/test_discrete_tap_control.py b/pandapower/test/control/test_discrete_tap_control.py index 28e91c932..c2126255f 100644 --- a/pandapower/test/control/test_discrete_tap_control.py +++ b/pandapower/test/control/test_discrete_tap_control.py @@ -50,7 +50,7 @@ def test_discrete_tap_control_lv(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 1.03 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -66,7 +66,7 @@ def test_discrete_tap_control_lv(): # reduce voltage from 1.03 pu to 0.949 pu net.ext_grid.vm_pu = 0.949 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -110,7 +110,7 @@ def test_discrete_tap_control_hv(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 1.03 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -126,7 +126,7 @@ def test_discrete_tap_control_hv(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 0.949 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -181,7 +181,7 @@ def test_discrete_tap_control_lv_from_tap_step_percent(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 1.03 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -197,7 +197,7 @@ def test_discrete_tap_control_lv_from_tap_step_percent(): # reduce voltage from 1.03 pu to 0.969 pu net.ext_grid.vm_pu = 0.969 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -252,7 +252,7 @@ def test_discrete_tap_control_hv_from_tap_step_percent(): # increase voltage from 1.0 pu to 1.03 pu net.ext_grid.vm_pu = 1.03 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") @@ -268,7 +268,7 @@ def test_discrete_tap_control_hv_from_tap_step_percent(): # reduce voltage from 1.03 pu to 0.969 pu net.ext_grid.vm_pu = 0.969 # switch back tap position - net.trafo.tap_pos.at[0] = 0 + net.trafo.at[0, "tap_pos"] = 0 pp.runpp(net) logger.info("case2: high voltage") diff --git a/pandapower/test/control/test_vm_set_tap_control.py b/pandapower/test/control/test_vm_set_tap_control.py index 0e8b6774a..6ad23d19e 100644 --- a/pandapower/test/control/test_vm_set_tap_control.py +++ b/pandapower/test/control/test_vm_set_tap_control.py @@ -31,14 +31,14 @@ def test_continuous_p(): assert abs(net.res_bus.vm_pu.at[c.controlled_bus] - 1.05) < eps # power sums up to 15kW - net.sgen.p_mw.at[gid] = 5 + net.sgen.at[gid, "p_mw"] = 5 pp.runpp(net, run_control=True) # we expect the tap to converge at 1.0 pu assert abs(net.res_bus.vm_pu.at[c.controlled_bus] - 1.) < eps # generation now cancels load - net.sgen.p_mw.at[gid] = 10 + net.sgen.at[gid, "p_mw"] = 10 pp.runpp(net, run_control=True) # we expect the tap to converge at lower voltage limit @@ -46,15 +46,15 @@ def test_continuous_p(): # testing limits # power flowing back - net.sgen.p_mw.at[gid] = 30 + net.sgen.at[gid, "p_mw"] = 30 pp.runpp(net, run_control=True) # we expect the tap to converge at lower voltage limit and not drop even lower assert abs(net.res_bus.vm_pu.at[c.controlled_bus] - 0.95) < eps # excessive load - net.sgen.p_mw.at[gid] = 0 - net.load.p_mw.at[lid] = 30 + net.sgen.at[gid, "p_mw"] = 0 + net.load.at[lid, "p_mw"] = 30 pp.runpp(net, run_control=True) # we expect the tap to converge at upper voltage limit and not to go beyond @@ -84,14 +84,14 @@ def test_continuous_i(): assert abs(net.res_bus.vm_pu.at[c.controlled_bus] - 1.05) < eps # power sums up to 15kW - net.sgen.p_mw.at[gid] = 5 + net.sgen.at[gid, "p_mw"] = 5 pp.runpp(net, run_control=True) # we expect the tap to converge at 1.0 pu assert abs(net.res_bus.vm_pu.at[c.controlled_bus] - 1.) < eps # generation now cancels load - net.sgen.p_mw.at[gid] = 10 + net.sgen.at[gid, "p_mw"] = 10 pp.runpp(net, run_control=True) # we expect the tap to converge at lower voltage limit @@ -99,15 +99,15 @@ def test_continuous_i(): # testing limits # power flowing back - net.sgen.p_mw.at[gid] = 30 + net.sgen.at[gid, "p_mw"] = 30 pp.runpp(net, run_control=True) # we expect the tap to converge at lower voltage limit and not drop even lower assert abs(net.res_bus.vm_pu.at[c.controlled_bus] - 0.95) < eps # excessive load - net.sgen.p_mw.at[gid] = 0 - net.load.p_mw.at[lid] = 30 + net.sgen.at[gid, "p_mw"] = 0 + net.load.at[lid, "p_mw"] = 30 pp.runpp(net, run_control=True) # we expect the tap to converge at upper voltage limit and not to go beyond diff --git a/pandapower/test/loadflow/result_test_network_generator.py b/pandapower/test/loadflow/result_test_network_generator.py index a002a24d6..62be8d87e 100644 --- a/pandapower/test/loadflow/result_test_network_generator.py +++ b/pandapower/test/loadflow/result_test_network_generator.py @@ -99,11 +99,11 @@ def result_test_network_generator_dcpp(sn_mva=1): def add_test_line(net): b1, b2, l1 = add_grid_connection(net, zone="test_line") - net.line.parallel.at[l1] = 2 - net.line.g_us_per_km.at[l1] = 1 + net.line.at[l1, "parallel"] = 2 + net.line.at[l1, "g_us_per_km"] = 1 pp.create_load(net, b2, p_mw=1.2, q_mvar=1.1) l2 = create_test_line(net, b1, b2) - net.line.g_us_per_km.at[l2] = 1 + net.line.at[l2, "g_us_per_km"] = 1 pp.create_switch(net, b2, l2, et="l", closed=False) create_test_line(net, b1, b2, in_service=False) net.last_added_case = "test_line" diff --git a/pandapower/test/loadflow/test_dist_slack.py b/pandapower/test/loadflow/test_dist_slack.py index bab1c63fe..52af450ac 100644 --- a/pandapower/test/loadflow/test_dist_slack.py +++ b/pandapower/test/loadflow/test_dist_slack.py @@ -436,11 +436,11 @@ def test_multivoltage_example_with_controller(): net = networks.example_multivoltage() gen_p_disp = 10 - net.gen.p_mw.at[0] = gen_p_disp - net.gen.slack_weight.at[0] = 1 - net.ext_grid.slack_weight.at[0] = 1 - net.trafo.tap_max.at[1] = 5 - net.trafo.tap_min.at[1] = -5 + net.gen.at[0, "p_mw"] = gen_p_disp + net.gen.at[0, "slack_weight"] = 1 + net.ext_grid.at[0, "slack_weight"] = 1 + net.trafo.at[1, "tap_max"] = 5 + net.trafo.at[1, "tap_min"] = -5 ContinuousTapControl(net, tid=1, vm_set_pu=1.05) gen_disp = sum([net[elm].p_mw.sum() for elm in ["gen", "sgen"]]) diff --git a/pandapower/test/loadflow/test_facts.py b/pandapower/test/loadflow/test_facts.py index a2961b9c3..39ef8b237 100644 --- a/pandapower/test/loadflow/test_facts.py +++ b/pandapower/test/loadflow/test_facts.py @@ -222,8 +222,8 @@ def test_svc(vm_set_pu): assert np.isclose(net3.res_bus.at[3, 'va_degree'], net.res_svc.at[0, 'va_degree'], rtol=0, atol=1e-6) assert np.isclose(net3.res_bus.at[3, 'q_mvar'], net.res_bus.at[3, 'q_mvar'], rtol=0, atol=1e-6) - net2.svc.thyristor_firing_angle_degree.at[0] = net.res_svc.thyristor_firing_angle_degree.at[0] - net2.svc.controllable.at[0] = False + net2.svc.at[0, "thyristor_firing_angle_degree"] = net.res_svc.thyristor_firing_angle_degree.at[0] + net2.svc.at[0, "controllable"] = False pp.runpp(net2) assert np.isclose(net2.res_bus.at[3, 'vm_pu'], net.svc.at[0, 'set_vm_pu'], rtol=0, atol=1e-6) assert np.isclose(net2.res_bus.at[3, 'q_mvar'], net.res_bus.at[3, 'q_mvar'], rtol=0, atol=1e-6) @@ -350,13 +350,13 @@ def test_tcsc_simple2(): pp.runpp(net_ref) compare_tcsc_impedance(net, net_ref, net.tcsc.index, net_ref.impedance.index) - net.tcsc.controllable.at[0] = True + net.tcsc.at[0, "controllable"] = True runpp_with_consistency_checks(net) net_ref = copy_with_impedance(net) pp.runpp(net_ref) compare_tcsc_impedance(net, net_ref, net.tcsc.index, net_ref.impedance.index) - net.tcsc.controllable.at[1] = True + net.tcsc.at[1, "controllable"] = True runpp_with_consistency_checks(net) net_ref = copy_with_impedance(net) pp.runpp(net_ref) @@ -514,7 +514,7 @@ def test_multiple_facts(): pp.create_svc(net, 3, 1, -10, 1.01, 90) runpp_with_consistency_checks(net) - net.svc.thyristor_firing_angle_degree.at[0] = net.res_svc.loc[0, "thyristor_firing_angle_degree"] + net.svc.at[0, "thyristor_firing_angle_degree"] = net.res_svc.loc[0, "thyristor_firing_angle_degree"] net.svc.controllable = False runpp_with_consistency_checks(net) net_ref = copy_with_impedance(net) diff --git a/pandapower/test/loadflow/test_results.py b/pandapower/test/loadflow/test_results.py index 9d7112d79..22175a352 100644 --- a/pandapower/test/loadflow/test_results.py +++ b/pandapower/test/loadflow/test_results.py @@ -278,8 +278,8 @@ def test_tap_dependent_impedance(result_test_network): net.trafo.loc[0, ['vk_percent_characteristic', 'vkr_percent_characteristic']] = idx_vk, idx_vkr # first, make sure there is no change for neutral - net.trafo.tap_pos.at[0] = net.trafo.tap_neutral.at[0] - net0.trafo.tap_pos.at[0] = net.trafo.tap_neutral.at[0] + net.trafo.at[0, "tap_pos"] = net.trafo.tap_neutral.at[0] + net0.trafo.at[0, "tap_pos"] = net.trafo.tap_neutral.at[0] pp.runpp(net) pp.runpp(net0) assert_res_equal(net, net0) @@ -289,11 +289,11 @@ def test_tap_dependent_impedance(result_test_network): for pos, factor in (("tap_min", 0.9), ("tap_max", 1.1)): assert isclose(characteristic_vk(net.trafo[pos].at[0]), net.trafo.vk_percent.at[0]*factor, rtol=0, atol=1e-12) assert isclose(characteristic_vkr(net.trafo[pos].at[0]), net.trafo.vkr_percent.at[0]*factor, rtol=0, atol=1e-12) - net0.trafo.vk_percent.at[0] = net.trafo.vk_percent.at[0]*factor - net0.trafo.vkr_percent.at[0] = net.trafo.vkr_percent.at[0]*factor - net0.trafo.tap_pos.at[0] = net.trafo[pos].at[0] + net0.trafo.at[0, "vk_percent"] = net.trafo.vk_percent.at[0]*factor + net0.trafo.at[0, "vkr_percent"] = net.trafo.vkr_percent.at[0]*factor + net0.trafo.at[0, "tap_pos"] = net.trafo[pos].at[0] pp.runpp(net0) - net.trafo.tap_pos.at[0] = net.trafo[pos].at[0] + net.trafo.at[0, "tap_pos"] = net.trafo[pos].at[0] pp.runpp(net) assert_res_equal(net, net0) diff --git a/pandapower/test/loadflow/test_rundcpp.py b/pandapower/test/loadflow/test_rundcpp.py index e3ac54fad..0fdba10ae 100644 --- a/pandapower/test/loadflow/test_rundcpp.py +++ b/pandapower/test/loadflow/test_rundcpp.py @@ -34,8 +34,8 @@ def test_rundcpp_init_auxiliary_buses(): pp.create_load(net, b3, p_mw=5) pp.create_load(net, b4, p_mw=5) pp.create_xward(net, b4, 1, 1, 1, 1, 0.1, 0.1, 1.0) - net.trafo3w.shift_lv_degree.at[tidx] = 120 - net.trafo3w.shift_mv_degree.at[tidx] = 80 + net.trafo3w.at[tidx, "shift_lv_degree"] = 120 + net.trafo3w.at[tidx, "shift_mv_degree"] = 80 pp.rundcpp(net) va = net.res_bus.va_degree.at[b2] pp.rundcpp(net) diff --git a/pandapower/test/loadflow/test_runpp.py b/pandapower/test/loadflow/test_runpp.py index 0239a58e6..9e1b7e042 100644 --- a/pandapower/test/loadflow/test_runpp.py +++ b/pandapower/test/loadflow/test_runpp.py @@ -123,7 +123,7 @@ def test_runpp_init(): b1, b2, l1 = add_grid_connection(net) b3 = pp.create_bus(net, vn_kv=0.4) tidx = pp.create_transformer(net, hv_bus=b2, lv_bus=b3, std_type="0.25 MVA 20/0.4 kV") - net.trafo.shift_degree.at[tidx] = 70 + net.trafo.at[tidx, "shift_degree"] = 70 pp.runpp(net, calculate_voltage_angles="auto") va = net.res_bus.va_degree.at[4] pp.runpp(net, calculate_voltage_angles=True, init_va_degree="dc") @@ -142,8 +142,8 @@ def test_runpp_init_auxiliary_buses(): pp.create_load(net, b4, p_mw=5) pp.create_xward(net, b4, ps_mw=1, qs_mvar=1, pz_mw=1, qz_mvar=1, r_ohm=0.1, x_ohm=0.1, vm_pu=1.0) - net.trafo3w.shift_lv_degree.at[tidx] = 120 - net.trafo3w.shift_mv_degree.at[tidx] = 80 + net.trafo3w.at[tidx, "shift_lv_degree"] = 120 + net.trafo3w.at[tidx, "shift_mv_degree"] = 80 pp.runpp(net) va = net.res_bus.va_degree.at[b2] pp.runpp(net, calculate_voltage_angles=True, init_va_degree="dc") @@ -191,7 +191,7 @@ def test_bus_bus_switches(bus_bus_net): net.res_bus.vm_pu.at[6] assert net.res_bus.vm_pu.at[0] == net.res_bus.vm_pu.at[7] - net.bus.in_service.at[5] = False + net.bus.at[5, "in_service"] = False pp.runpp(net) assert net.res_bus.vm_pu.at[3] == net.res_bus.vm_pu.at[6] assert net.res_bus.vm_pu.at[0] == net.res_bus.vm_pu.at[7] @@ -202,10 +202,10 @@ def test_bus_bus_switches(bus_bus_net): def test_bus_bus_switches_merges_two_gens(bus_bus_net): "buses should not be fused if two gens are connected" net = bus_bus_net - net.bus.in_service.at[5] = False + net.bus.at[5, "in_service"] = False pp.create_gen(net, 6, 10) pp.create_gen(net, 4, 10) - net.bus.in_service.at[5] = True + net.bus.at[5, "in_service"] = True pp.runpp(net) assert net.converged @@ -1063,14 +1063,14 @@ def two_ext_grids_at_one_bus(): assert net.converged # error is raised after eg2 is set in service - net.ext_grid.in_service.at[eg2] = True + net.ext_grid.at[eg2, "in_service"] = True with pytest.raises(UserWarning): pp.runpp(net) # error is also raised when eg2 is connected to first ext_grid through bus-bus switch b3 = pp.create_bus(net, vn_kv=110) pp.create_switch(net, b1, b3, et="b") - net.ext_grid.bus.at[eg2] = b3 + net.ext_grid.at[eg2, "bus"] = b3 with pytest.raises(UserWarning): pp.runpp(net) @@ -1079,8 +1079,8 @@ def two_ext_grids_at_one_bus(): assert net.converged # same angle but different voltage magnitude also raises an error - net.ext_grid.vm_pu.at[eg2] = 1.02 - net.ext_grid.va_degree.at[eg2] = 0 + net.ext_grid.at[eg2, "vm_pu"] = 1.02 + net.ext_grid.at[eg2, "va_degree"] = 0 with pytest.raises(UserWarning): pp.runpp(net) @@ -1132,7 +1132,7 @@ def test_only_ref_buses(): assert np.all(net.res_ext_grid.p_mw == 0.) assert np.all(net.res_ext_grid.q_mvar == 0.) - net.ext_grid.vm_pu.at[1] = 0.5 + net.ext_grid.at[1, "vm_pu"] = 0.5 pp.runpp(net) assert np.allclose(net.res_ext_grid.p_mw.values, np.array([0.25, -0.125]), rtol=0, atol=1e-12) assert np.allclose(net.res_ext_grid.q_mvar.values, np.array([0.25, -0.125]), rtol=0, atol=1e-12) @@ -1180,9 +1180,9 @@ def test_init_results(): t3_switch = pp.create_switch(net, bus=net.trafo3w.hv_bus.at[t3idx], element=t3idx, et="t3", closed=False) # trafo3w switch at hv side assert_init_results(net) - net.switch.bus.at[t3_switch] = net.trafo3w.mv_bus.at[t3idx] # trafo3w switch at mv side + net.switch.at[t3_switch, "bus"] = net.trafo3w.mv_bus.at[t3idx] # trafo3w switch at mv side assert_init_results(net) - net.switch.bus.at[t3_switch] = net.trafo3w.lv_bus.at[t3idx] # trafo3w switch at lv side + net.switch.at[t3_switch, "bus"] = net.trafo3w.lv_bus.at[t3idx] # trafo3w switch at lv side assert_init_results(net) @@ -1333,26 +1333,26 @@ def test_tap_dependent_impedance(): pp.runpp(net_backup) assert_res_equal(net, net_backup) - net.trafo.tap_pos.at[0] = 2 - net_backup.trafo.tap_pos.at[0] = 2 - net_backup.trafo.vk_percent.at[0] = 6.5 - net_backup.trafo.vkr_percent.at[0] = 1.48 + net.trafo.at[0, "tap_pos"] = 2 + net_backup.trafo.at[0, "tap_pos"] = 2 + net_backup.trafo.at[0, "vk_percent"] = 6.5 + net_backup.trafo.at[0, "vkr_percent"] = 1.48 pp.runpp(net) pp.runpp(net_backup) assert_res_equal(net, net_backup) - net.trafo.tap_pos.at[1] = -2 - net_backup.trafo.tap_pos.at[1] = -2 - net_backup.trafo.vk_percent.at[1] = 5.4 + net.trafo.at[1, "tap_pos"] = -2 + net_backup.trafo.at[1, "tap_pos"] = -2 + net_backup.trafo.at[1, "vk_percent"] = 5.4 pp.runpp(net) pp.runpp(net_backup) assert_res_equal(net, net_backup) - net.trafo3w.tap_pos.at[0] = 2 - net_backup.trafo3w.tap_pos.at[0] = 2 - net_backup.trafo3w.vk_hv_percent.at[0] = 1.05 + net.trafo3w.at[0, "tap_pos"] = 2 + net_backup.trafo3w.at[0, "tap_pos"] = 2 + net_backup.trafo3w.at[0, "vk_hv_percent"] = 1.05 pp.runpp(net) pp.runpp(net_backup) diff --git a/pandapower/test/loadflow/test_scenarios.py b/pandapower/test/loadflow/test_scenarios.py index 7f65cf46a..ec4192814 100644 --- a/pandapower/test/loadflow/test_scenarios.py +++ b/pandapower/test/loadflow/test_scenarios.py @@ -47,7 +47,7 @@ def test_0gen_2ext_grid(): pp.create_ext_grid(net, 1) net.gen = net.gen.drop(0) net.trafo.shift_degree = 150 - net.ext_grid.in_service.at[1] = False + net.ext_grid.at[1, "in_service"] = False pp.create_ext_grid(net, 3) pp.runpp(net, init='dc', calculate_voltage_angles=True) @@ -68,9 +68,9 @@ def test_0gen_2ext_grid_decoupled(): net.gen = net.gen.drop(0) net.shunt.q_mvar *= -1 pp.create_ext_grid(net, 1) - net.ext_grid.in_service.at[1] = False + net.ext_grid.at[1, "in_service"] = False pp.create_ext_grid(net, 3) - net.ext_grid.in_service.at[2] = False + net.ext_grid.at[2, "in_service"] = False auxbus = pp.create_bus(net, name="bus1", vn_kv=10.) net.trafo.shift_degree = 150 pp.create_std_type(net, {"type": "cs", "r_ohm_per_km": 0.876, "q_mm2": 35.0, @@ -225,8 +225,8 @@ def test_transformer_phase_shift(): b2b_angle = net.res_bus.va_degree.at[4] b3b_angle = net.res_bus.va_degree.at[5] - net.trafo.tap_pos.at[0] = 1 - net.trafo.tap_pos.at[2] = 1 + net.trafo.at[0, "tap_pos"] = 1 + net.trafo.at[2, "tap_pos"] = 1 pp.runpp(net, init="dc", calculate_voltage_angles=True) assert np.isclose(b2a_angle - net.res_bus.va_degree.at[1], 10) assert np.isclose(b3a_angle - net.res_bus.va_degree.at[2], 10) @@ -259,12 +259,12 @@ def test_transformer_phase_shift_complex(): assert np.isclose(net.res_bus.vm_pu.at[b2], test_ref[0], rtol=1e-4) assert np.isclose(net.res_bus.va_degree.at[b2], test_ref[1], rtol=1e-4) - net.trafo.tap_pos.at[0] = 2 + net.trafo.at[0, "tap_pos"] = 2 pp.runpp(net, init="dc", calculate_voltage_angles=True) assert np.isclose(net.res_bus.vm_pu.at[b2], test_tap_pos[side][0], rtol=1e-4) assert np.isclose(net.res_bus.va_degree.at[b2], test_tap_pos[side][1], rtol=1e-4) - net.trafo.tap_pos.at[0] = -2 + net.trafo.at[0, "tap_pos"] = -2 pp.runpp(net, init="dc", calculate_voltage_angles=True) assert np.isclose(net.res_bus.vm_pu.at[b2], test_tap_neg[side][0], rtol=1e-4) assert np.isclose(net.res_bus.va_degree.at[b2], test_tap_neg[side][1], rtol=1e-4) @@ -307,14 +307,14 @@ def test_transformer3w_phase_shift(): assert np.isclose(net.res_bus.vm_pu.at[b3], test_ref[1][0], rtol=1e-4) assert np.isclose(net.res_bus.va_degree.at[b3], test_ref[1][1], rtol=1e-4) - net.trafo3w.tap_pos.at[0] = 2 + net.trafo3w.at[0, "tap_pos"] = 2 pp.runpp(net, init="dc", calculate_voltage_angles=True) assert np.isclose(net.res_bus.vm_pu.at[b2], test_tap_pos[side][0][0], rtol=1e-4) assert np.isclose(net.res_bus.va_degree.at[b2], test_tap_pos[side][0][1], rtol=1e-4) assert np.isclose(net.res_bus.vm_pu.at[b3], test_tap_pos[side][1][0], rtol=1e-4) assert np.isclose(net.res_bus.va_degree.at[b3], test_tap_pos[side][1][1], rtol=1e-4) - net.trafo3w.tap_pos.at[0] = -2 + net.trafo3w.at[0, "tap_pos"] = -2 pp.runpp(net, init="dc", calculate_voltage_angles=True) assert np.isclose(net.res_bus.vm_pu.at[b2], test_tap_neg[side][0][0], rtol=1e-4) assert np.isclose(net.res_bus.va_degree.at[b2], test_tap_neg[side][0][1], rtol=1e-4) @@ -434,7 +434,7 @@ def test_trafo3w_switches(network_with_trafo3ws): assert np.isnan(net.res_trafo3w.p_hv_mw.at[t3]) == 0 # open switch at mv side - mv is disconnected, lv is connected - net.switch.bus.at[s1] = mv + net.switch.at[s1, "bus"] = mv runpp_with_consistency_checks(net) assert np.isnan(net.res_bus.vm_pu.at[mv]) @@ -444,7 +444,7 @@ def test_trafo3w_switches(network_with_trafo3ws): assert 0.490 < net.res_trafo3w.p_hv_mw.at[t3] < 0.510 # open switch at lv side - lv is disconnected, mv is connected - net.switch.bus.at[s1] = lv + net.switch.at[s1, "bus"] = lv runpp_with_consistency_checks(net) assert np.isnan(net.res_bus.vm_pu.at[lv]) @@ -541,8 +541,8 @@ def test_switch_results(): net = nw.simple_mv_open_ring_net() net.ext_grid["s_sc_max_mva"] = 1000 net.ext_grid['rx_max'] = 0.1 - - switch_trafo_hv = pp.create_switch(net, bus=0, element=0, et="t") + + switch_trafo_hv = pp.create_switch(net, bus=0, element=0, et="t") switch_trafo_lv = pp.create_switch(net, bus=1, element=0, et="t") closed_line_switch = 1 @@ -556,17 +556,17 @@ def test_switch_results(): in_ka = 0.1 pp.create_load(net, new_bus, p_mw=1.5) closed_bb_switch_impedance = pp.create_switch(net, bus=new_bus, element=4, et="b", z_ohm=0.1, in_ka=in_ka) - + new_bus = pp.create_bus(net, vn_kv=20.0) pp.create_load(net, new_bus, p_mw=1.5) open_bb_switch = pp.create_switch(net, bus=new_bus, element=6, et="b", closed=False) - + pp.runpp(net) - + assert np.isclose(net.res_switch.i_ka.at[open_line_switch], 0) assert np.isclose(net.res_switch.i_ka.at[open_bb_switch], 0) - + assert np.isnan(net.res_switch.i_ka.at[closed_bb_switch]) assert np.isclose(net.res_switch.i_ka.at[closed_bb_switch_impedance], 0.04378035814760788) loading = net.res_switch.i_ka.at[closed_bb_switch_impedance] / in_ka * 100 @@ -574,7 +574,7 @@ def test_switch_results(): line = net.switch.element.at[closed_line_switch] assert np.isclose(net.res_switch.i_ka.at[closed_line_switch], net.res_line.i_ka.at[line]) - + trafo = net.switch.element.at[switch_trafo_hv] assert np.isclose(net.res_switch.i_ka.at[switch_trafo_hv], abs(net.res_trafo.i_hv_ka.at[trafo])) assert np.isclose(net.res_switch.i_ka.at[switch_trafo_lv], abs(net.res_trafo.i_lv_ka.at[trafo])) @@ -584,12 +584,12 @@ def test_switch_results(): assert np.isclose(net.res_switch_sc.ikss_ka.at[open_line_switch], 0) assert np.isclose(net.res_switch_sc.ikss_ka.at[open_bb_switch], 0) - + assert np.isnan(net.res_switch_sc.ikss_ka.at[closed_bb_switch]) assert np.isclose(net.res_switch_sc.ikss_ka.at[closed_bb_switch_impedance], 4.555211220391998) assert np.isclose(net.res_switch_sc.ikss_ka.at[closed_line_switch], net.res_line_sc.ikss_ka.at[line]) - + assert np.isclose(net.res_switch_sc.ikss_ka.at[switch_trafo_hv], abs(net.res_trafo_sc.ikss_hv_ka.at[trafo])) assert np.isclose(net.res_switch_sc.ikss_ka.at[switch_trafo_lv], abs(net.res_trafo_sc.ikss_lv_ka.at[trafo])) diff --git a/pandapower/test/opf/test_basic.py b/pandapower/test/opf/test_basic.py index f0dcbb041..19964fce4 100644 --- a/pandapower/test/opf/test_basic.py +++ b/pandapower/test/opf/test_basic.py @@ -39,7 +39,7 @@ def simplest_grid(): pp.create_poly_cost(net, 0, "gen", cp1_eur_per_mw=0.1) return net - + @pytest.fixture def net_3w_trafo_opf(): @@ -475,8 +475,8 @@ def test_trafo3w_loading(): min_q_mvar=-1e6, max_q_mvar=1e6) pp.create_poly_cost(net, load_id, "load", cp1_eur_per_mw=-1000) # pp.create_xward(net, b4, 1000, 1000, 1000, 1000, 0.1, 0.1, 1.0) - net.trafo3w.shift_lv_degree.at[tidx] = 120 - net.trafo3w.shift_mv_degree.at[tidx] = 80 + net.trafo3w.at[tidx, "shift_lv_degree"] = 120 + net.trafo3w.at[tidx, "shift_mv_degree"] = 80 # pp.runopp(net, calculate_voltage_angles = True) >> Doesn't converge for init in ["pf", "flat"]: diff --git a/pandapower/test/opf/test_costs_mixed.py b/pandapower/test/opf/test_costs_mixed.py index 8a778e730..ae2ff549e 100644 --- a/pandapower/test/opf/test_costs_mixed.py +++ b/pandapower/test/opf/test_costs_mixed.py @@ -51,11 +51,11 @@ def test_cost_mixed(): assert net["OPF_converged"] assert np.isclose(net.res_cost, net.res_gen.p_mw.values**2 + 1) - net.load.controllable.at[0] = True + net.load.at[0, "controllable"] = True pp.runopp(net) assert np.isclose(net.res_cost, net.res_gen.p_mw.values ** 2 + 1) - net.load.controllable.at[0] = False + net.load.at[0, "controllable"] = False net.pwl_cost.drop(net.pwl_cost.index, inplace=True) pp.create_pwl_cost(net, 0, "ext_grid", [[-1000, 0, -2000], [0, 1000, 2000]], power_type="p") diff --git a/pandapower/test/opf/test_costs_pol.py b/pandapower/test/opf/test_costs_pol.py index f98b6a016..2826a0f6f 100644 --- a/pandapower/test/opf/test_costs_pol.py +++ b/pandapower/test/opf/test_costs_pol.py @@ -115,7 +115,7 @@ def test_cost_pol_q(): net.poly_cost.cq1_eur_per_mvar.at[0] = 0 net.poly_cost.cq2_eur_per_mvar2.at[0] = 1 -# net.poly_cost.c.at[0] = np.array([[1, 0, 0]]) +# net.poly_cost.at[0, "c"] = np.array([[1, 0, 0]]) # run OPF pp.runopp(net) diff --git a/pandapower/test/opf/test_pandamodels_runpm.py b/pandapower/test/opf/test_pandamodels_runpm.py index dcd1ad195..536c4de96 100644 --- a/pandapower/test/opf/test_pandamodels_runpm.py +++ b/pandapower/test/opf/test_pandamodels_runpm.py @@ -393,8 +393,8 @@ def test_voltage_angles(): max_q_mvar=1e-6) pp.create_poly_cost(net, 0, "ext_grid", cp1_eur_per_mw=1) pp.create_poly_cost(net, load_id, "load", cp1_eur_per_mw=1000) - net.trafo3w.shift_lv_degree.at[tidx] = 10 - net.trafo3w.shift_mv_degree.at[tidx] = 30 + net.trafo3w.at[tidx, "shift_lv_degree"] = 10 + net.trafo3w.at[tidx, "shift_mv_degree"] = 30 net.bus.loc[:, "max_vm_pu"] = 1.1 net.bus.loc[:, "min_vm_pu"] = .9 diff --git a/pandapower/test/protection/test_fuse.py b/pandapower/test/protection/test_fuse.py index 459936a74..1763005a1 100644 --- a/pandapower/test/protection/test_fuse.py +++ b/pandapower/test/protection/test_fuse.py @@ -313,7 +313,7 @@ def test_fuse_fault_oc_scenario(): assert net.switch.closed.at[3] == False, 'Fuse 3 should melt, switch 3 should be open' # after fault is cleared, close the CB at bus 6 so that Load 0 continues to get power - net.switch.closed.at[9] = True + net.switch.at[9, "closed"] = True # perform power flow calculation pp.runpp(net) diff --git a/pandapower/test/protection/test_oc_relay.py b/pandapower/test/protection/test_oc_relay.py index f123de633..224d48e6d 100644 --- a/pandapower/test/protection/test_oc_relay.py +++ b/pandapower/test/protection/test_oc_relay.py @@ -59,10 +59,10 @@ def test_oc_relay_idtoc(): def test_oc_relay_plots(): net = oc_relay_net() - net.switch.type.at[2] = 'CB_IDMT' - net.switch.type.at[3] = 'CB_IDMT' - net.switch.type.at[4] = 'CB_IDTOC' - net.switch.type.at[5] = 'CB_IDTOC' + net.switch.at[2, "type"] = 'CB_IDMT' + net.switch.at[3, "type"] = 'CB_IDMT' + net.switch.at[4, "type"] = 'CB_IDTOC' + net.switch.at[5, "type"] = 'CB_IDTOC' oc_relay_type_list = ['DTOC', 'DTOC', 'IDMT', 'IDMT', 'IDTOC', 'IDTOC'] time_settings_list = [[0.07, 0.5, 0.3], diff --git a/pandapower/test/shortcircuit/test_all_currents.py b/pandapower/test/shortcircuit/test_all_currents.py index e71cd4176..78e783813 100644 --- a/pandapower/test/shortcircuit/test_all_currents.py +++ b/pandapower/test/shortcircuit/test_all_currents.py @@ -325,8 +325,8 @@ def add_aux_trafo(net, trafo_idx): @pytest.mark.parametrize("inverse_y", (True, False), ids=("Inverse Y", "LU factorization")) def test_branch_all_currents_trafo_simple_other_voltage3(inverse_y): net = net_transformer_simple_3() - net.trafo.vn_hv_kv.at[1] = 31 - net.trafo.vn_hv_kv.at[2] = 11 + net.trafo.at[1, "vn_hv_kv"] = 31 + net.trafo.at[2, "vn_hv_kv"] = 11 sc.calc_sc(net, case='max', lv_tol_percent=6., branch_results=True, bus=6, inverse_y=inverse_y) @@ -350,8 +350,8 @@ def test_branch_all_currents_trafo_simple_other_voltage3(inverse_y): relevant = [i for i, c in enumerate(net.res_trafo_sc.columns) if not np.all(np.isnan(net.res_trafo_sc[c]))] assert np.allclose(net.res_trafo_sc.iloc[:, relevant].values, res_trafo_sc[:, relevant], rtol=0, atol=1e-6) - net.trafo.vn_hv_kv.at[1] = 29 - net.trafo.vn_hv_kv.at[2] = 9 + net.trafo.at[1, "vn_hv_kv"] = 29 + net.trafo.at[2, "vn_hv_kv"] = 9 sc.calc_sc(net, case='max', lv_tol_percent=6., branch_results=True, bus=6, inverse_y=inverse_y) @@ -375,8 +375,8 @@ def test_branch_all_currents_trafo_simple_other_voltage3(inverse_y): relevant = [i for i, c in enumerate(net.res_trafo_sc.columns) if not np.all(np.isnan(net.res_trafo_sc[c]))] assert np.allclose(net.res_trafo_sc.iloc[:, relevant].values, res_trafo_sc[:, relevant], rtol=0, atol=1e-6) - net.trafo.vn_hv_kv.at[1] = 31 - net.trafo.vn_hv_kv.at[2] = 11 + net.trafo.at[1, "vn_hv_kv"] = 31 + net.trafo.at[2, "vn_hv_kv"] = 11 sc.calc_sc(net, case='max', lv_tol_percent=6., branch_results=True, bus=4, inverse_y=inverse_y) assert np.allclose(net.res_bus_sc.loc[4].values, @@ -395,10 +395,10 @@ def test_branch_all_currents_trafo_simple_other_voltage3(inverse_y): relevant = [i for i, c in enumerate(net.res_trafo_sc.columns) if not np.all(np.isnan(net.res_trafo_sc[c]))] assert np.allclose(net.res_trafo_sc.iloc[:, relevant].values, res_trafo_sc[:, relevant], rtol=0, atol=1e-6) - net.trafo.vn_hv_kv.at[1] = 30 - net.trafo.vn_hv_kv.at[2] = 10 - net.trafo.vn_lv_kv.at[1] = 9 - net.trafo.vn_lv_kv.at[2] = 0.42 + net.trafo.at[1, "vn_hv_kv"] = 30 + net.trafo.at[2, "vn_hv_kv"] = 10 + net.trafo.at[1, "vn_lv_kv"] = 9 + net.trafo.at[2, "vn_lv_kv"] = 0.42 sc.calc_sc(net, case='max', lv_tol_percent=6., branch_results=True, bus=6, inverse_y=inverse_y) @@ -427,8 +427,8 @@ def test_type_c_trafo_simple_other_voltage4(inverse_y): net = net_transformer_simple_4() net.sgen.in_service = False - # net.trafo.vn_hv_kv.at[1] = 31 - net.trafo.vn_hv_kv.at[2] = 11 + # net.trafo.at[1, "vn_hv_kv"] = 31 + net.trafo.at[2, "vn_hv_kv"] = 11 pp.runpp(net) sc.calc_sc(net, case='max', lv_tol_percent=6., branch_results=True, bus=6, use_pre_fault_voltage=True, inverse_y=inverse_y) @@ -483,8 +483,8 @@ def test_type_c_trafo_simple_other_voltage4_sgen(inverse_y): pp.create_load(net, 7, 10, 3) pp.create_switch(net, 6, 4, 'l', False) - net.trafo.vn_hv_kv.at[1] = 31 - net.trafo.vn_lv_kv.at[2] = 0.42 + net.trafo.at[1, "vn_hv_kv"] = 31 + net.trafo.at[2, "vn_lv_kv"] = 0.42 pp.runpp(net) sc.calc_sc(net, case='max', lv_tol_percent=6., branch_results=True, bus=6, use_pre_fault_voltage=True, diff --git a/pandapower/test/shortcircuit/test_gen.py b/pandapower/test/shortcircuit/test_gen.py index eea38b730..a21a12a91 100644 --- a/pandapower/test/shortcircuit/test_gen.py +++ b/pandapower/test/shortcircuit/test_gen.py @@ -110,22 +110,22 @@ def test_gen_ext_grid_same_bus(): # g2 = pp.create_gen(net, b2, vn_kv=21., xdss_pu=0.2, cos_phi=0.85, p_mw=0.1, sn_mva=2.5) # b3 = pp.create_bus(net, vn_kv=20.) # g3 = pp.create_gen(net, b3, vn_kv=30., xdss_pu=0.25, cos_phi=0.9, p_mw=0.1, sn_mva=150) - + # sc.calc_sc(net, case="max") # assert np.isclose(net.res_bus_sc.ikss_ka.at[b1], 1.5130509845) -# net.gen.rdss_pu.at[g1] = net.gen.xdss_pu.at[g1] * 0.15 +# net.gen.at[g1, "rdss_pu"] = net.gen.xdss_pu.at[g1] * 0.15 # sc.calc_sc(net, case="max") # assert np.isclose(net.res_bus_sc.ikss_ka.at[b1], 1.5130509845) - + # sc.calc_sc(net, case="max") # assert np.isclose(net.res_bus_sc.ikss_ka.at[b2], 0.37894052506) -# net.gen.rdss_pu.at[g2] = net.gen.xdss_pu.at[g2] * 0.07 +# net.gen.at[g2, "rdss_pu"] = net.gen.xdss_pu.at[g2] * 0.07 # sc.calc_sc(net, case="max") # assert np.isclose(net.res_bus_sc.ikss_ka.at[b2], 0.37894052506) - + # sc.calc_sc(net, case="max") # assert np.isclose(net.res_bus_sc.ikss_ka.at[b3], 12.789334853) -# net.gen.rdss_pu.at[g3] = net.gen.xdss_pu.at[g3] * 0.05 +# net.gen.at[g3, "rdss_pu"] = net.gen.xdss_pu.at[g3] * 0.05 # sc.calc_sc(net, case="max") # assert np.isclose(net.res_bus_sc.ikss_ka.at[b3], 12.789334853) diff --git a/pandapower/test/toolbox/test_element_selection.py b/pandapower/test/toolbox/test_element_selection.py index a355c056d..23c32ba91 100644 --- a/pandapower/test/toolbox/test_element_selection.py +++ b/pandapower/test/toolbox/test_element_selection.py @@ -130,7 +130,7 @@ def test_get_false_links(): # --- gens pp.create_gens(net, [0, 1, 3], 5) # manipulate to not existing - net.gen.bus.at[1] = 999 + net.gen.at[1, "bus"] = 999 # --- sgens pp.create_sgens(net, [0, 1, 3], 5) @@ -139,8 +139,8 @@ def test_get_false_links(): for fbus, tbus in zip([0, 1, 4, 6, 7], [1, 4, 6, 7, 3]): pp.create_line(net, fbus, tbus, 2., "NA2XS2Y 1x185 RM/25 6/10 kV") # manipulate to not existing - net.line.from_bus.at[1] = 2 - net.line.to_bus.at[4] = 999 + net.line.at[1, "from_bus"] = 2 + net.line.at[4, "to_bus"] = 999 # --- measurements pp.create_measurement(net, "v", "bus", 1.01, 5, 1) @@ -149,8 +149,8 @@ def test_get_false_links(): pp.create_measurement(net, "v", "bus", 1.01, 5, 6) pp.create_measurement(net, "i", "line", 0.41, 1, 1, side="from") # manipulate to not existing - net.measurement.element.at[1] = 999 - net.measurement.element.at[3] = 999 + net.measurement.at[1, "element"] = 999 + net.measurement.at[3, "element"] = 999 # --- poly_cost pp.create_poly_cost(net, 0, "gen", 5) @@ -158,8 +158,8 @@ def test_get_false_links(): pp.create_poly_cost(net, 0, "sgen", 5) pp.create_poly_cost(net, 1, "sgen", 5) # manipulate to not existing - net.poly_cost.element.at[1] = 999 - net.poly_cost.element.at[2] = 999 + net.poly_cost.at[1, "element"] = 999 + net.poly_cost.at[2, "element"] = 999 expected = {"gen": {1}, "line": {1, 4}, diff --git a/pandapower/test/toolbox/test_grid_modification.py b/pandapower/test/toolbox/test_grid_modification.py index ed73f0d83..6a9bf240b 100644 --- a/pandapower/test/toolbox/test_grid_modification.py +++ b/pandapower/test/toolbox/test_grid_modification.py @@ -383,8 +383,8 @@ def test_create_replacement_switch_for_branch(): # look that the switch is created properly pp.create_replacement_switch_for_branch(net, 'line', line0) pp.create_replacement_switch_for_branch(net, 'impedance', impedance0) - net.line.in_service.at[line0] = False - net.impedance.in_service.at[impedance0] = False + net.line.at[line0, "in_service"] = False + net.impedance.at[impedance0, "in_service"] = False assert 'REPLACEMENT_line_0' in net.switch.name.values assert 'REPLACEMENT_impedance_0' in net.switch.name.values @@ -393,8 +393,8 @@ def test_create_replacement_switch_for_branch(): pp.runpp(net) # look that the switch is created with the correct closed status - net.line.in_service.at[line1] = False - net.impedance.in_service.at[impedance1] = False + net.line.at[line1, "in_service"] = False + net.impedance.at[impedance1, "in_service"] = False pp.create_replacement_switch_for_branch(net, 'line', line1) pp.create_replacement_switch_for_branch(net, 'impedance', impedance1) @@ -710,7 +710,7 @@ def test_get_connected_elements_empty_in_service(): # - element_table was unbound for the element table measurement # see #1592 net = nw.example_simple() - net.bus.in_service.at[6] = False + net.bus.at[6, "in_service"] = False conn = pp.get_connected_elements_dict(net, [0], respect_switches=False, respect_in_service=True) assert conn == {"line": [0], 'ext_grid': [0], 'bus': [1]} conn = pp.get_connected_elements_dict(net, [3, 4], respect_switches=False, respect_in_service=True) @@ -938,7 +938,7 @@ def test_merge_same_bus_generation_plants(): # 2) remove limit columns or values to check whether merge_same_bus_generation_plants() can # handle that del net.sgen["max_q_mvar"] - net.sgen.min_p_mw.at[1] = np.nan + net.sgen.at[1, "min_p_mw"] = np.nan # prepare expatation values dupl_buses = [0, 1, 6, 12, 14, 21, 22] diff --git a/pandapower/test/topology/test_create_graph.py b/pandapower/test/topology/test_create_graph.py index 1f618baa6..e4158ca18 100644 --- a/pandapower/test/topology/test_create_graph.py +++ b/pandapower/test/topology/test_create_graph.py @@ -127,7 +127,7 @@ def test_trafo3w(): assert set(mg.get_edge_data(f, t).keys()) == {("trafo3w", t1)} assert set(mg.nodes()) == set(net.bus.index) - net.trafo3w.in_service.at[t2] = True + net.trafo3w.at[t2, "in_service"] = True mg = create_nxgraph(net, library=library) for f, t in combinations([hv, mv, lv], 2): assert set(mg.get_edge_data(f, t).keys()) == {("trafo3w", t1), ("trafo3w", t2)} @@ -142,7 +142,7 @@ def test_trafo3w(): else: assert set(mg.get_edge_data(f, t).keys()) == {("trafo3w", t1), ("trafo3w", t2)} assert set(mg.nodes()) == set(net.bus.index) - net.switch.closed.at[sw] = True + net.switch.at[sw, "closed"] = True def test_trafo3w_impedances(network_with_trafo3ws): @@ -215,12 +215,12 @@ def test_bus_bus_switches(): s = net.switch.index[0] f, t = net.switch.bus.iloc[0], net.switch.element.iloc[0] - net.switch.closed.at[s] = True + net.switch.at[s, "closed"] = True mg = create_nxgraph(net, library=library) assert set(mg.get_edge_data(f, t)) == {("switch", s)} assert set(mg.nodes()) == set(net.bus.index) - net.switch.closed.at[s] = False + net.switch.at[s, "closed"] = False mg = create_nxgraph(net, library=library) assert mg.get_edge_data(f, t) is None assert set(mg.nodes()) == set(net.bus.index) From 2b029611236c6224a12b7ad9db0826f17d46a4cc Mon Sep 17 00:00:00 2001 From: Steffen Meinecke Date: Mon, 25 Mar 2024 11:48:09 +0100 Subject: [PATCH 04/17] remove all inplace usage --- pandapower/auxiliary.py | 4 +- pandapower/control/util/auxiliary.py | 2 +- pandapower/convert_format.py | 14 +- .../converter/cim/cim2pp/build_pp_net.py | 2 +- .../cim/cim2pp/convert_measurements.py | 26 +- .../connectivityNodesCim16.py | 62 ++--- .../coordinates/coordinatesFromDLCim16.py | 24 +- .../coordinates/geoCoordinatesFromGLCim16.py | 26 +- .../externalNetworkInjectionsCim16.py | 2 +- .../generators/asynchronousMachinesCim16.py | 8 +- .../generators/energySourcesCim16.py | 8 +- .../generators/synchronousMachinesCim16.py | 20 +- .../impedance/equivalentBranchesCim16.py | 8 +- .../impedance/seriesCompensatorsCim16.py | 8 +- .../lines/acLineSegmentsCim16.py | 22 +- .../lines/dcLineSegmentsCim16.py | 18 +- .../loads/conformLoadsCim16.py | 4 +- .../loads/energyConcumersCim16.py | 4 +- .../loads/nonConformLoadsCim16.py | 4 +- .../loads/stationSuppliesCim16.py | 4 +- .../shunts/linearShuntCompensatorCim16.py | 4 +- .../shunts/nonLinearShuntCompensatorCim16.py | 4 +- .../shunts/staticVarCompensatorCim16.py | 2 +- .../switches/switchesCim16.py | 10 +- .../transformers/powerTransformersCim16.py | 82 +++--- .../wards/equivalentInjectionsCim16.py | 6 +- pandapower/converter/cim/cim_classes.py | 4 +- .../powerfactory/pp_import_functions.py | 6 +- pandapower/converter/powerfactory/validate.py | 2 +- pandapower/create.py | 2 +- pandapower/estimation/state_estimation.py | 12 +- pandapower/estimation/util.py | 2 +- pandapower/grid_equivalents/auxiliary.py | 20 +- pandapower/grid_equivalents/get_equivalent.py | 6 +- pandapower/grid_equivalents/rei_generation.py | 14 +- .../grid_equivalents/ward_generation.py | 10 +- pandapower/groups.py | 8 +- pandapower/io_utils.py | 6 +- .../networks/power_system_test_cases.py | 4 +- pandapower/opf/validate_opf_input.py | 4 +- pandapower/plotting/generic_geodata.py | 2 +- pandapower/protection/oc_relay_model.py | 250 +++++++++--------- pandapower/sql_io.py | 4 +- pandapower/test/api/test_diagnostic.py | 6 +- pandapower/test/api/test_file_io.py | 4 +- .../test/contingency/test_contingency.py | 2 +- .../test/estimation/test_wls_estimation.py | 44 +-- .../grid_equivalents/test_get_equivalent.py | 14 +- pandapower/test/loadflow/test_runpp.py | 2 +- pandapower/test/loadflow/test_scenarios.py | 2 +- pandapower/test/loadflow/test_tdpf.py | 10 +- pandapower/test/opf/test_basic.py | 6 +- pandapower/test/opf/test_cost_consistency.py | 6 +- pandapower/test/opf/test_costs_mixed.py | 2 +- pandapower/test/opf/test_pandamodels_runpm.py | 6 +- .../test/plotting/test_generic_coordinates.py | 6 +- .../timeseries/test_timeseries_recycle.py | 8 +- pandapower/test/toolbox/test_comparison.py | 4 +- .../test/toolbox/test_data_modification.py | 8 +- .../test/toolbox/test_grid_modification.py | 2 +- pandapower/toolbox/data_modification.py | 2 +- pandapower/toolbox/grid_modification.py | 50 ++-- pandapower/toolbox/result_info.py | 2 +- 63 files changed, 460 insertions(+), 460 deletions(-) diff --git a/pandapower/auxiliary.py b/pandapower/auxiliary.py index d3f1347aa..474a8faac 100644 --- a/pandapower/auxiliary.py +++ b/pandapower/auxiliary.py @@ -938,9 +938,9 @@ def _clean_up(net, res=True): # res_bus.drop(xward_buses, inplace=True) if len(net["dcline"]) > 0: dc_gens = net.gen.index[(len(net.gen) - len(net.dcline) * 2):] - net.gen.drop(dc_gens, inplace=True) + net.gen = net.gen.drop(dc_gens) if res: - net.res_gen.drop(dc_gens, inplace=True) + net.res_gen = net.res_gen.drop(dc_gens) def _set_isolated_buses_out_of_service(net, ppc): diff --git a/pandapower/control/util/auxiliary.py b/pandapower/control/util/auxiliary.py index c338e61be..9d0afe311 100644 --- a/pandapower/control/util/auxiliary.py +++ b/pandapower/control/util/auxiliary.py @@ -188,7 +188,7 @@ def drop_same_type_existing_controllers(net, this_ctrl_type, index=None, matchin same_type_existing_ctrl = get_controller_index(net, ctrl_type=this_ctrl_type, parameters=matching_params) if len(same_type_existing_ctrl): - net.controller.drop(same_type_existing_ctrl, inplace=True) + net.controller = net.controller.drop(same_type_existing_ctrl) logger.debug("Controllers " + str(['%i' % idx for idx in same_type_existing_ctrl]) + "got removed because of same type and matching parameters as new " + "controller " + index + ".") diff --git a/pandapower/convert_format.py b/pandapower/convert_format.py index 798acdf88..8e7e489ed 100644 --- a/pandapower/convert_format.py +++ b/pandapower/convert_format.py @@ -216,9 +216,9 @@ def _create_seperate_cost_tables(net, elements_to_deserialize): def _rename_columns(net, elements_to_deserialize): if _check_elements_to_deserialize('line', elements_to_deserialize): - net.line.rename(columns={'imax_ka': 'max_i_ka'}, inplace=True) + net.line = net.line.rename(columns={'imax_ka': 'max_i_ka'}) if _check_elements_to_deserialize('gen', elements_to_deserialize): - net.gen.rename(columns={"qmin_mvar": "min_q_mvar", "qmax_mvar": "max_q_mvar"}, inplace=True) + net.gen = net.gen.rename(columns={"qmin_mvar": "min_q_mvar", "qmax_mvar": "max_q_mvar"}) for typ, data in net.std_types["line"].items(): if "imax_ka" in data: net.std_types["line"][typ]["max_i_ka"] = net.std_types["line"][typ].pop("imax_ka") @@ -235,11 +235,11 @@ def _rename_columns(net, elements_to_deserialize): net.measurement.loc[bus_measurements, "bus"].values net.measurement.loc[~bus_measurements, "side"] = \ net.measurement.loc[~bus_measurements, "bus"].values - net.measurement.rename(columns={'type': 'measurement_type'}, inplace=True) - net.measurement.drop(["bus"], axis=1, inplace=True) + net.measurement = net.measurement.rename(columns={'type': 'measurement_type'}) + net.measurement = net.measurement.drop(["bus"], axis=1) if _check_elements_to_deserialize('controller', elements_to_deserialize): if "controller" in net: - net["controller"].rename(columns={"controller": "object"}, inplace=True) + net["controller"] = net["controller"].rename(columns={"controller": "object"}) if "options" in net: if "recycle" in net["options"]: if "Ybus" in net["options"]["recycle"]: @@ -371,7 +371,7 @@ def _update_trafo_parameter_names(net, elements_to_deserialize): for element in update_data: replace_cols = {col: _update_column(col) for col in net[element].columns if col.startswith("tp") or col.startswith("vsc")} - net[element].rename(columns=replace_cols, inplace=True) + net[element] = net[element].rename(columns=replace_cols) _update_trafo_type_parameter_names(net) @@ -404,7 +404,7 @@ def _convert_to_mw(net): for old, new in replace: diff = {column: column.replace(old, new) for column in tab.columns if old in column and column != "pfe_kw"} - tab.rename(columns=diff, inplace=True) + tab = tab.rename(columns=diff) if len(tab) == 0: continue for old, new in diff.items(): diff --git a/pandapower/converter/cim/cim2pp/build_pp_net.py b/pandapower/converter/cim/cim2pp/build_pp_net.py index dda63d643..5c8345a40 100644 --- a/pandapower/converter/cim/cim2pp/build_pp_net.py +++ b/pandapower/converter/cim/cim2pp/build_pp_net.py @@ -219,7 +219,7 @@ def convert_to_pp(self, convert_line_to_switch: bool = False, line_r_limit: floa # fuse boundary ConnectivityNodes with their TopologicalNodes bus_t = self.net.bus.reset_index(level=0, drop=False) bus_drop = bus_t.loc[bus_t[sc['o_prf']] == 'eq_bd', ['index', sc['o_id'], 'cim_topnode']] - bus_drop.rename(columns={'index': 'b1'}, inplace=True) + bus_drop = bus_drop.rename(columns={'index': 'b1'}) bus_drop = pd.merge(bus_drop, bus_t[['index', sc['o_id']]].rename(columns={'index': 'b2', sc['o_id']: 'o_id2'}), how='inner', left_on='cim_topnode', right_on='o_id2') if bus_drop.index.size > 0: diff --git a/pandapower/converter/cim/cim2pp/convert_measurements.py b/pandapower/converter/cim/cim2pp/convert_measurements.py index ab0e242f0..87e2f2644 100644 --- a/pandapower/converter/cim/cim2pp/convert_measurements.py +++ b/pandapower/converter/cim/cim2pp/convert_measurements.py @@ -44,11 +44,11 @@ def create_measurements_from_analog(self): 'PowerSystemResource', 'positiveFlowIn']], self.cim['eq']['AnalogValue'][['sensorAccuracy', 'MeasurementValueSource', 'Analog', 'value']], how='inner', left_on='rdfId', right_on='Analog') - analogs.drop(columns=['rdfId', 'Analog'], inplace=True) + analogs = analogs.drop(columns=['rdfId', 'Analog']) analogs = pd.merge(analogs, self.cim['eq']['MeasurementValueSource'], how='left', left_on='MeasurementValueSource', right_on='rdfId') - analogs.drop(columns=['rdfId', 'MeasurementValueSource'], inplace=True) + analogs = analogs.drop(columns=['rdfId', 'MeasurementValueSource']) # collect all the assets (line, trafo, trafo3w) and its connections assets = pd.DataFrame(None, columns=['element_type', 'side']) append_dict = dict({'line': {'from_bus': 'from', 'to_bus': 'to'}, @@ -61,7 +61,7 @@ def create_measurements_from_analog(self): temp['element_type'] = element_type temp['side'] = side assets = pd.concat([assets, temp], sort=False) - assets.rename(columns={'index': 'element'}, inplace=True) + assets = assets.rename(columns={'index': 'element'}) # now join the analogs with the assets psr = pd.merge(analogs, assets, how='inner', left_on='PowerSystemResource', right_on=sc['o_id']) # keep only entries which are associated to the terminal from the asset @@ -96,24 +96,24 @@ def create_measurements_from_sv(self): sc = cim_tools.get_pp_net_special_columns_dict() # get the measurements from the sv profile and set the Terminal as index sv_powerflow = self.cim['sv']['SvPowerFlow'][['Terminal', 'p', 'q']] - sv_powerflow.set_index('Terminal', inplace=True) + sv_powerflow = sv_powerflow.set_index('Terminal') # ---------------------------------------measure: bus v--------------------------------------------------- busses_temp = self.net.bus[['name', 'vn_kv', sc['ct']]].copy() - busses_temp.reset_index(level=0, inplace=True) - busses_temp.rename(columns={'index': 'element', sc['ct']: 'TopologicalNode'}, inplace=True) + busses_temp = busses_temp.reset_index(level=0) + busses_temp = busses_temp.rename(columns={'index': 'element', sc['ct']: 'TopologicalNode'}) sv_sv_voltages = pd.merge(self.cim['sv']['SvVoltage'][['TopologicalNode', 'v']], busses_temp, how='left', on='TopologicalNode') # drop all the rows mit vn_kv == np.NaN (no measurements available for that bus) - sv_sv_voltages.dropna(subset=['vn_kv'], inplace=True) + sv_sv_voltages = sv_sv_voltages.dropna(subset=['vn_kv']) sv_sv_voltages.reset_index(inplace=True) if 'index' in sv_sv_voltages.columns: - sv_sv_voltages.drop(['index'], inplace=True, axis=1) + sv_sv_voltages = sv_sv_voltages.drop(['index'], axis=1) # value -> voltage () sv_sv_voltages['value'] = sv_sv_voltages.v / sv_sv_voltages.vn_kv sv_sv_voltages['value'].replace(0, np.nan, inplace=True) # drop all the rows mit value == np.NaN - sv_sv_voltages.dropna(subset=['value'], inplace=True) + sv_sv_voltages = sv_sv_voltages.dropna(subset=['value']) sv_sv_voltages.reset_index(inplace=True) sv_sv_voltages['value_stddev'] = sv_sv_voltages.value * 0.001 sv_sv_voltages['vn_kv_stddev'] = 0.1 / sv_sv_voltages.vn_kv @@ -136,7 +136,7 @@ def create_measurements_from_sv(self): line_temp['q_to'] = \ pd.merge(line_temp[sc['t_to']], sv_powerflow['q'], left_on=sc['t_to'], right_index=True)['q'] - line_temp.dropna(subset=['p_from', 'p_to', 'q_from', 'q_to'], thresh=4, inplace=True) + line_temp = line_temp.dropna(subset=['p_from', 'p_to', 'q_from', 'q_to'], thresh=4) line_temp['stddev_line_from_p'] = abs(line_temp.p_from) * sigma_line + 1. line_temp['stddev_line_to_p'] = abs(line_temp.p_to) * sigma_line + 1. @@ -181,7 +181,7 @@ def create_measurements_from_sv(self): trafo_temp['q_lv'] = \ pd.merge(trafo_temp[sc['t_lv']], sv_powerflow['q'], left_on=sc['t_lv'], right_index=True)['q'] - trafo_temp.dropna(subset=['p_hv', 'p_lv', 'q_hv', 'q_lv'], thresh=4, inplace=True) + trafo_temp = trafo_temp.dropna(subset=['p_hv', 'p_lv', 'q_hv', 'q_lv'], thresh=4) trafo_temp['stddev_trafo_hv_p'] = abs(trafo_temp.p_hv) * sigma_trafo + 1. trafo_temp['stddev_trafo_lv_p'] = abs(trafo_temp.p_lv) * sigma_trafo + 1. @@ -230,7 +230,7 @@ def create_measurements_from_sv(self): trafo3w_temp['q_lv'] = \ pd.merge(trafo3w_temp[sc['t_lv']], sv_powerflow['q'], left_on=sc['t_lv'], right_index=True)['q'] - trafo3w_temp.dropna(subset=['p_hv', 'p_mv', 'p_lv', 'q_hv', 'q_mv', 'q_lv'], thresh=6, inplace=True) + trafo3w_temp = trafo3w_temp.dropna(subset=['p_hv', 'p_mv', 'p_lv', 'q_hv', 'q_mv', 'q_lv'], thresh=6) trafo3w_temp['stddev_trafo_hv_p'] = abs(trafo3w_temp.p_hv) * sigma_trafo3w + 1. trafo3w_temp['stddev_trafo_mv_p'] = abs(trafo3w_temp.p_mv) * sigma_trafo3w + 1. @@ -275,7 +275,7 @@ def create_measurements_from_sv(self): self._copy_to_measurement(trafo3w_temp) # remove NaN values - self.net.measurement.dropna(subset=['value'], inplace=True) + self.net.measurement = self.net.measurement.dropna(subset=['value']) # set the element from float to default uint32 self._set_measurement_element_datatype() diff --git a/pandapower/converter/cim/cim2pp/converter_classes/connectivitynodes/connectivityNodesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/connectivitynodes/connectivityNodesCim16.py index 3d3ce5100..aa535f586 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/connectivitynodes/connectivityNodesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/connectivitynodes/connectivityNodesCim16.py @@ -29,13 +29,13 @@ def convert_connectivity_nodes_cim16(self): # a prepared and modified copy of eqssh_terminals to use for lines, switches, loads, sgens and so on eqssh_terminals = eqssh_terminals[ ['rdfId', 'ConductingEquipment', 'ConnectivityNode', 'sequenceNumber', 'connected']].copy() - eqssh_terminals.rename(columns={'rdfId': 'rdfId_Terminal'}, inplace=True) - eqssh_terminals.rename(columns={'ConductingEquipment': 'rdfId'}, inplace=True) + eqssh_terminals = eqssh_terminals.rename(columns={'rdfId': 'rdfId_Terminal'}) + eqssh_terminals = eqssh_terminals.rename(columns={'ConductingEquipment': 'rdfId'}) # buses for merging with assets: bus_merge = pd.DataFrame(data=self.cimConverter.net['bus'].loc[:, [sc['o_id'], 'vn_kv']]) - bus_merge.rename(columns={'vn_kv': 'base_voltage_bus'}, inplace=True) - bus_merge.reset_index(level=0, inplace=True) - bus_merge.rename(columns={'index': 'index_bus', sc['o_id']: 'ConnectivityNode'}, inplace=True) + bus_merge = bus_merge.rename(columns={'vn_kv': 'base_voltage_bus'}) + bus_merge = bus_merge.reset_index(level=0) + bus_merge = bus_merge.rename(columns={'index': 'index_bus', sc['o_id']: 'ConnectivityNode'}) bus_merge = pd.merge(eqssh_terminals, bus_merge, how='left', on='ConnectivityNode') self.cimConverter.bus_merge = bus_merge @@ -69,15 +69,15 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] # The idea is to add the Bays and Substations to the VoltageLevels to handle them similar to (1) # prepare the bays (2) eq_bay = self.cimConverter.cim['eq']['Bay'].copy() - eq_bay.rename(columns={'rdfId': 'ConnectivityNodeContainer'}, inplace=True) + eq_bay = eq_bay.rename(columns={'rdfId': 'ConnectivityNodeContainer'}) eq_bay = pd.merge(self.cimConverter.cim['eq']['ConnectivityNode'][['ConnectivityNodeContainer']], eq_bay, how='inner', on='ConnectivityNodeContainer') - eq_bay.dropna(subset=['VoltageLevel'], inplace=True) + eq_bay = eq_bay.dropna(subset=['VoltageLevel']) eq_bay = pd.merge(eq_bay, self.cimConverter.cim['eq']['VoltageLevel'][['rdfId', 'BaseVoltage', 'Substation']], how='left', left_on='VoltageLevel', right_on='rdfId') - eq_bay.drop(columns=['VoltageLevel', 'rdfId'], inplace=True) - eq_bay.rename(columns={'ConnectivityNodeContainer': 'rdfId'}, inplace=True) + eq_bay = eq_bay.drop(columns=['VoltageLevel', 'rdfId']) + eq_bay = eq_bay.rename(columns={'ConnectivityNodeContainer': 'rdfId'}) # now prepare the substations (3) # first get only the needed substation used as ConnectivityNodeContainer in ConnectivityNode eq_subs = pd.merge(self.cimConverter.cim['eq']['ConnectivityNode'][['ConnectivityNodeContainer']].rename( @@ -98,18 +98,18 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] level=LogLevel.WARNING, code=ReportCode.WARNING_CONVERTING, message="More than one VoltageLevel refers to one Substation, maybe the voltages from some buses " "are incorrect, the problematic VoltageLevels and Substations:\n%s" % eq_subs_duplicates)) - eq_subs.drop_duplicates(['rdfId'], keep='first', inplace=True) + eq_subs = eq_subs.drop_duplicates(['rdfId'], keep='first') # now merge the VoltageLevel with the ConnectivityNode eq_voltage_levels = self.cimConverter.cim['eq']['VoltageLevel'][['rdfId', 'BaseVoltage', 'Substation']] eq_voltage_levels = pd.concat([eq_voltage_levels, eq_bay], ignore_index=True, sort=False) eq_voltage_levels = pd.concat([eq_voltage_levels, eq_subs], ignore_index=True, sort=False) - eq_voltage_levels.drop_duplicates(['rdfId'], keep='first', inplace=True) + eq_voltage_levels = eq_voltage_levels.drop_duplicates(['rdfId'], keep='first') del eq_bay, eq_subs, eq_subs_duplicates eq_substations = self.cimConverter.cim['eq']['Substation'][['rdfId', 'name']] - eq_substations.rename(columns={'rdfId': 'Substation', 'name': 'name_substation'}, inplace=True) + eq_substations = eq_substations.rename(columns={'rdfId': 'Substation', 'name': 'name_substation'}) eq_voltage_levels = pd.merge(eq_voltage_levels, eq_substations, how='left', on='Substation') - eq_voltage_levels.drop_duplicates(subset=['rdfId'], inplace=True) - eq_voltage_levels.rename(columns={'rdfId': 'ConnectivityNodeContainer'}, inplace=True) + eq_voltage_levels = eq_voltage_levels.drop_duplicates(subset=['rdfId']) + eq_voltage_levels = eq_voltage_levels.rename(columns={'rdfId': 'ConnectivityNodeContainer'}) connectivity_nodes = pd.merge(connectivity_nodes, eq_voltage_levels, how='left', on='ConnectivityNodeContainer') @@ -128,7 +128,7 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] inplace=True) connectivity_nodes = pd.merge(connectivity_nodes, eq_bd_cns, how='left', on='rdfId') connectivity_nodes['BaseVoltage'].fillna(connectivity_nodes['BaseVoltage_2'], inplace=True) - connectivity_nodes.drop(columns=['BaseVoltage_2'], inplace=True) + connectivity_nodes = connectivity_nodes.drop(columns=['BaseVoltage_2']) # check if there is a mix between BB and NB models terminals_temp = \ self.cimConverter.cim['eq']['Terminal'].loc[ @@ -137,9 +137,9 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] terminals_temp = pd.merge(terminals_temp, self.cimConverter.cim['tp']['Terminal'][['rdfId', 'TopologicalNode']], how='left', on='rdfId') - terminals_temp.drop(columns=['rdfId'], inplace=True) - terminals_temp.rename(columns={'TopologicalNode': 'rdfId'}, inplace=True) - terminals_temp.drop_duplicates(subset=['rdfId'], inplace=True) + terminals_temp = terminals_temp.drop(columns=['rdfId']) + terminals_temp = terminals_temp.rename(columns={'TopologicalNode': 'rdfId'}) + terminals_temp = terminals_temp.drop_duplicates(subset=['rdfId']) tp_temp = self.cimConverter.cim['tp']['TopologicalNode'][ ['rdfId', 'name', 'description', 'BaseVoltage']] tp_temp[sc['o_prf']] = 'tp' @@ -164,12 +164,12 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] eq_base_voltages = pd.concat([self.cimConverter.cim['eq']['BaseVoltage'][['rdfId', 'nominalVoltage']], self.cimConverter.cim['eq_bd']['BaseVoltage'][['rdfId', 'nominalVoltage']]], ignore_index=True, sort=False) - eq_base_voltages.drop_duplicates(subset=['rdfId'], inplace=True) - eq_base_voltages.rename(columns={'rdfId': 'BaseVoltage'}, inplace=True) + eq_base_voltages = eq_base_voltages.drop_duplicates(subset=['rdfId']) + eq_base_voltages = eq_base_voltages.rename(columns={'rdfId': 'BaseVoltage'}) # make sure that the BaseVoltage has string datatype connectivity_nodes['BaseVoltage'] = connectivity_nodes['BaseVoltage'].astype(str) connectivity_nodes = pd.merge(connectivity_nodes, eq_base_voltages, how='left', on='BaseVoltage') - connectivity_nodes.drop(columns=['BaseVoltage'], inplace=True) + connectivity_nodes = connectivity_nodes.drop(columns=['BaseVoltage']) eqssh_terminals = self.cimConverter.cim['eq']['Terminal'][['rdfId', 'ConnectivityNode', 'ConductingEquipment', 'sequenceNumber']] eqssh_terminals = \ @@ -191,13 +191,13 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] pd.concat([self.cimConverter.cim['tp']['DCTerminal'], self.cimConverter.cim['tp']['ACDCConverterDCTerminal']], ignore_index=True, sort=False), how='left', on='rdfId') - dc_terminals.rename(columns={'DCNode': 'ConnectivityNode', 'DCConductingEquipment': 'ConductingEquipment', - 'DCTopologicalNode': 'TopologicalNode'}, inplace=True) + dc_terminals = dc_terminals.rename(columns={'DCNode': 'ConnectivityNode', 'DCConductingEquipment': 'ConductingEquipment', + 'DCTopologicalNode': 'TopologicalNode'}) eqssh_terminals = pd.concat([eqssh_terminals, dc_terminals], ignore_index=True, sort=False) # special fix for concat tp profiles - eqssh_terminals.drop_duplicates(subset=['rdfId', 'TopologicalNode'], inplace=True) + eqssh_terminals = eqssh_terminals.drop_duplicates(subset=['rdfId', 'TopologicalNode']) eqssh_terminals_temp = eqssh_terminals[['ConnectivityNode', 'TopologicalNode']] - eqssh_terminals_temp.dropna(subset=['TopologicalNode'], inplace=True) + eqssh_terminals_temp = eqssh_terminals_temp.dropna(subset=['TopologicalNode']) eqssh_terminals_temp.drop_duplicates(inplace=True) connectivity_nodes_size = connectivity_nodes.index.size if node_breaker: @@ -210,7 +210,7 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] # fill the column TopologicalNode for the ConnectivityNodes from the eq_bd profile if exists if 'TopologicalNode_2' in connectivity_nodes.columns: connectivity_nodes['TopologicalNode'].fillna(connectivity_nodes['TopologicalNode_2'], inplace=True) - connectivity_nodes.drop(columns=['TopologicalNode_2'], inplace=True) + connectivity_nodes = connectivity_nodes.drop(columns=['TopologicalNode_2']) if connectivity_nodes.index.size != connectivity_nodes_size: self.logger.warning("There is a problem at the busses!") self.cimConverter.report_container.add_log(Report( @@ -228,17 +228,17 @@ def _prepare_connectivity_nodes_cim16(self) -> Tuple[pd.DataFrame, pd.DataFrame] # raise ValueError("The number of ConnectivityNodes increased after merging with Terminals, number of " # "ConnectivityNodes before merge: %s, number of ConnectivityNodes after merge: %s" % # (connectivity_nodes_size, connectivity_nodes.index.size)) - connectivity_nodes.drop_duplicates(subset=['rdfId'], keep='first', inplace=True) + connectivity_nodes = connectivity_nodes.drop_duplicates(subset=['rdfId'], keep='first') # add the busbars bb = self.cimConverter.cim['eq']['BusbarSection'][['rdfId', 'name']] - bb.rename(columns={'rdfId': 'busbar_id', 'name': 'busbar_name'}, inplace=True) + bb = bb.rename(columns={'rdfId': 'busbar_id', 'name': 'busbar_name'}) bb = pd.merge(bb, self.cimConverter.cim['eq']['Terminal'][['ConnectivityNode', 'ConductingEquipment']].rename( columns={'ConnectivityNode': 'rdfId', 'ConductingEquipment': 'busbar_id'}), how='left', on='busbar_id') - bb.drop_duplicates(subset=['rdfId'], keep='first', inplace=True) + bb = bb.drop_duplicates(subset=['rdfId'], keep='first') connectivity_nodes = pd.merge(connectivity_nodes, bb, how='left', on='rdfId') - connectivity_nodes.rename(columns={'rdfId': sc['o_id'], 'TopologicalNode': sc['ct'], 'nominalVoltage': 'vn_kv', - 'name_substation': 'zone'}, inplace=True) + connectivity_nodes = connectivity_nodes.rename(columns={'rdfId': sc['o_id'], 'TopologicalNode': sc['ct'], 'nominalVoltage': 'vn_kv', + 'name_substation': 'zone'}) connectivity_nodes['in_service'] = True connectivity_nodes['type'] = 'b' return connectivity_nodes, eqssh_terminals diff --git a/pandapower/converter/cim/cim2pp/converter_classes/coordinates/coordinatesFromDLCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/coordinates/coordinatesFromDLCim16.py index 2ab8c926f..ac3a30b44 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/coordinates/coordinatesFromDLCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/coordinates/coordinatesFromDLCim16.py @@ -32,12 +32,12 @@ def add_coordinates_from_dl_cim16(self, diagram_name: str = None): self.cimConverter.cim['dl']['Diagram']['name'] == diagram_name].values[0] dl_do = self.cimConverter.cim['dl']['DiagramObject'][ self.cimConverter.cim['dl']['DiagramObject']['Diagram'] == diagram_rdf_id] - dl_do.rename(columns={'rdfId': 'DiagramObject'}, inplace=True) + dl_do = dl_do.rename(columns={'rdfId': 'DiagramObject'}) else: dl_do = self.cimConverter.cim['dl']['DiagramObject'].copy() - dl_do.rename(columns={'rdfId': 'DiagramObject'}, inplace=True) + dl_do = dl_do.rename(columns={'rdfId': 'DiagramObject'}) dl_data = pd.merge(dl_do, self.cimConverter.cim['dl']['DiagramObjectPoint'], how='left', on='DiagramObject') - dl_data.drop(columns=['rdfId', 'Diagram', 'DiagramObject'], inplace=True) + dl_data = dl_data.drop(columns=['rdfId', 'Diagram', 'DiagramObject']) # make sure that the columns 'xPosition' and 'yPosition' are floats dl_data['xPosition'] = dl_data['xPosition'].astype(float) dl_data['yPosition'] = dl_data['yPosition'].astype(float) @@ -45,7 +45,7 @@ def add_coordinates_from_dl_cim16(self, diagram_name: str = None): buses = self.cimConverter.net.bus.reset_index() buses = buses[['index', sc['o_id']]] bus_geo = pd.merge(dl_data, buses, how='inner', left_on='IdentifiedObject', right_on=sc['o_id']) - bus_geo.sort_values(by=[sc['o_id'], 'sequenceNumber'], inplace=True) + bus_geo = bus_geo.sort_values(by=[sc['o_id'], 'sequenceNumber']) bus_geo['coords'] = bus_geo[['xPosition', 'yPosition']].values.tolist() bus_geo['coords'] = bus_geo[['coords']].values.tolist() # for the buses which have more than one coordinate @@ -53,8 +53,8 @@ def add_coordinates_from_dl_cim16(self, diagram_name: str = None): # now deal with the buses which have more than one coordinate for _, df_group in bus_geo_mult.groupby(by=sc['o_id'], sort=False): bus_geo['coords'][df_group.index.values[0]] = df_group[['xPosition', 'yPosition']].values.tolist() - bus_geo.drop_duplicates([sc['o_id']], keep='first', inplace=True) - bus_geo.sort_values(by='index', inplace=True) + bus_geo = bus_geo.drop_duplicates([sc['o_id']], keep='first') + bus_geo = bus_geo.sort_values(by='index') start_index_pp_net = self.cimConverter.net.bus_geodata.index.size self.cimConverter.net.bus_geodata = pd.concat( [self.cimConverter.net.bus_geodata, pd.DataFrame(None, index=bus_geo['index'].values)], @@ -69,19 +69,19 @@ def add_coordinates_from_dl_cim16(self, diagram_name: str = None): self.cimConverter.net.bus_geodata['coords'] = self.cimConverter.net.bus_geodata.apply( lambda row: [row['coords'][0], row['coords'][-1]] if row['coords_length'] > 2 else row['coords'], axis=1) if 'coords_length' in self.cimConverter.net.bus_geodata.columns: - self.cimConverter.net.bus_geodata.drop(columns=['coords_length'], inplace=True) + self.cimConverter.net.bus_geodata = self.cimConverter.net.bus_geodata.drop(columns=['coords_length']) # the coordinates for the lines lines = self.cimConverter.net.line.reset_index() lines = lines[['index', sc['o_id']]] line_geo = pd.merge(dl_data, lines, how='inner', left_on='IdentifiedObject', right_on=sc['o_id']) - line_geo.sort_values(by=[sc['o_id'], 'sequenceNumber'], inplace=True) + line_geo = line_geo.sort_values(by=[sc['o_id'], 'sequenceNumber']) line_geo['coords'] = line_geo[['xPosition', 'yPosition']].values.tolist() line_geo['coords'] = line_geo[['coords']].values.tolist() for _, df_group in line_geo.groupby(by=sc['o_id']): line_geo['coords'][df_group.index.values[0]] = df_group[['xPosition', 'yPosition']].values.tolist() - line_geo.drop_duplicates([sc['o_id']], keep='first', inplace=True) - line_geo.sort_values(by='index', inplace=True) + line_geo = line_geo.drop_duplicates([sc['o_id']], keep='first') + line_geo = line_geo.sort_values(by='index') # now add the line coordinates # if there are no bus geodata in the GL profile the line geodata from DL has higher priority if self.cimConverter.net.line_geodata.index.size > 0 and line_geo.index.size > 0: @@ -95,12 +95,12 @@ def add_coordinates_from_dl_cim16(self, diagram_name: str = None): 'storage', 'ward', 'xward']: one_ele_df = self.cimConverter.net[one_ele][[sc['o_id']]] one_ele_df = pd.merge(dl_data, one_ele_df, how='inner', left_on='IdentifiedObject', right_on=sc['o_id']) - one_ele_df.sort_values(by=[sc['o_id'], 'sequenceNumber'], inplace=True) + one_ele_df = one_ele_df.sort_values(by=[sc['o_id'], 'sequenceNumber']) one_ele_df['coords'] = one_ele_df[['xPosition', 'yPosition']].values.tolist() one_ele_df['coords'] = one_ele_df[['coords']].values.tolist() for _, df_group in one_ele_df.groupby(by=sc['o_id']): one_ele_df['coords'][df_group.index.values[0]] = df_group[['xPosition', 'yPosition']].values.tolist() - one_ele_df.drop_duplicates([sc['o_id']], keep='first', inplace=True) + one_ele_df = one_ele_df.drop_duplicates([sc['o_id']], keep='first') # now add the coordinates self.cimConverter.net[one_ele]['coords'] = self.cimConverter.net[one_ele][sc['o_id']].map( one_ele_df.set_index(sc['o_id']).to_dict(orient='dict').get('coords')) diff --git a/pandapower/converter/cim/cim2pp/converter_classes/coordinates/geoCoordinatesFromGLCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/coordinates/geoCoordinatesFromGLCim16.py index e0360856c..b56537915 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/coordinates/geoCoordinatesFromGLCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/coordinates/geoCoordinatesFromGLCim16.py @@ -25,7 +25,7 @@ def add_geo_coordinates_from_gl_cim16(self): self.cimConverter.cim['gl']['PositionPoint'][['Location', 'xPosition', 'yPosition', 'sequenceNumber']], self.cimConverter.cim['gl']['Location'][['rdfId', 'PowerSystemResources']], how='left', left_on='Location', right_on='rdfId') - gl_data.drop(columns=['Location', 'rdfId'], inplace=True) + gl_data = gl_data.drop(columns=['Location', 'rdfId']) # make sure that the columns 'xPosition' and 'yPosition' are floats gl_data['xPosition'] = gl_data['xPosition'].astype(float) gl_data['yPosition'] = gl_data['yPosition'].astype(float) @@ -34,15 +34,15 @@ def add_geo_coordinates_from_gl_cim16(self): cn = pd.concat([cn, self.cimConverter.cim['eq_bd']['ConnectivityNode'][['rdfId', 'ConnectivityNodeContainer']]]) cn = pd.concat([cn, self.cimConverter.cim['tp']['TopologicalNode'][['rdfId', 'ConnectivityNodeContainer']]]) cn = pd.concat([cn, self.cimConverter.cim['tp_bd']['TopologicalNode'][['rdfId', 'ConnectivityNodeContainer']]]) - cn.rename(columns={'rdfId': sc['o_id'], 'ConnectivityNodeContainer': 'rdfId'}, inplace=True) + cn = cn.rename(columns={'rdfId': sc['o_id'], 'ConnectivityNodeContainer': 'rdfId'}) cn = pd.merge(cn, self.cimConverter.cim['eq']['VoltageLevel'][['rdfId', 'Substation']], how='left', on='rdfId') - cn.drop(columns=['rdfId'], inplace=True) + cn = cn.drop(columns=['rdfId']) buses = self.cimConverter.net.bus.reset_index() buses = buses[['index', sc['o_id']]] buses = pd.merge(buses, cn, how='left', on=sc['o_id']) bus_geo = pd.merge(bus_geo, buses, how='inner', on='Substation') - bus_geo.drop(columns=['Substation'], inplace=True) - bus_geo.sort_values(by=[sc['o_id'], 'sequenceNumber'], inplace=True) + bus_geo = bus_geo.drop(columns=['Substation']) + bus_geo = bus_geo.sort_values(by=[sc['o_id'], 'sequenceNumber']) bus_geo['coords'] = bus_geo[['xPosition', 'yPosition']].values.tolist() bus_geo['coords'] = bus_geo[['coords']].values.tolist() # for the buses which have more than one coordinate @@ -50,8 +50,8 @@ def add_geo_coordinates_from_gl_cim16(self): # now deal with the buses which have more than one coordinate for _, df_group in bus_geo_mult.groupby(by=sc['o_id'], sort=False): bus_geo['coords'][df_group.index.values[0]] = df_group[['xPosition', 'yPosition']].values.tolist() - bus_geo.drop_duplicates([sc['o_id']], keep='first', inplace=True) - bus_geo.sort_values(by='index', inplace=True) + bus_geo = bus_geo.drop_duplicates([sc['o_id']], keep='first') + bus_geo = bus_geo.sort_values(by='index') start_index_pp_net = self.cimConverter.net.bus_geodata.index.size self.cimConverter.net.bus_geodata = pd.concat( [self.cimConverter.net.bus_geodata, pd.DataFrame(None, index=bus_geo['index'].values)], @@ -66,20 +66,20 @@ def add_geo_coordinates_from_gl_cim16(self): self.cimConverter.net.bus_geodata['coords'] = self.cimConverter.net.bus_geodata.apply( lambda row: [row['coords'][0], row['coords'][-1]] if row['coords_length'] > 2 else row['coords'], axis=1) if 'coords_length' in self.cimConverter.net.bus_geodata.columns: - self.cimConverter.net.bus_geodata.drop(columns=['coords_length'], inplace=True) + self.cimConverter.net.bus_geodata = self.cimConverter.net.bus_geodata.drop(columns=['coords_length']) # the geo coordinates for the lines lines = self.cimConverter.net.line.reset_index() lines = lines[['index', sc['o_id']]] line_geo = gl_data.rename(columns={'PowerSystemResources': sc['o_id']}) line_geo = pd.merge(line_geo, lines, how='inner', on=sc['o_id']) - line_geo.sort_values(by=[sc['o_id'], 'sequenceNumber'], inplace=True) + line_geo = line_geo.sort_values(by=[sc['o_id'], 'sequenceNumber']) line_geo['coords'] = line_geo[['xPosition', 'yPosition']].values.tolist() line_geo['coords'] = line_geo[['coords']].values.tolist() for _, df_group in line_geo.groupby(by=sc['o_id']): line_geo['coords'][df_group.index.values[0]] = df_group[['xPosition', 'yPosition']].values.tolist() - line_geo.drop_duplicates([sc['o_id']], keep='first', inplace=True) - line_geo.sort_values(by='index', inplace=True) + line_geo = line_geo.drop_duplicates([sc['o_id']], keep='first') + line_geo = line_geo.sort_values(by='index') # now add the line coordinates start_index_pp_net = self.cimConverter.net.line_geodata.index.size self.cimConverter.net.line_geodata = pd.concat( @@ -93,12 +93,12 @@ def add_geo_coordinates_from_gl_cim16(self): one_ele_df = self.cimConverter.net[one_ele][[sc['o_id']]] one_ele_df = pd.merge(gl_data.rename(columns={'PowerSystemResources': sc['o_id']}), one_ele_df, how='inner', on=sc['o_id']) - one_ele_df.sort_values(by=[sc['o_id'], 'sequenceNumber'], inplace=True) + one_ele_df = one_ele_df.sort_values(by=[sc['o_id'], 'sequenceNumber']) one_ele_df['coords'] = one_ele_df[['xPosition', 'yPosition']].values.tolist() one_ele_df['coords'] = one_ele_df[['coords']].values.tolist() for _, df_group in one_ele_df.groupby(by=sc['o_id']): one_ele_df['coords'][df_group.index.values[0]] = df_group[['xPosition', 'yPosition']].values.tolist() - one_ele_df.drop_duplicates([sc['o_id']], keep='first', inplace=True) + one_ele_df = one_ele_df.drop_duplicates([sc['o_id']], keep='first') # now add the coordinates self.cimConverter.net[one_ele]['coords'] = self.cimConverter.net[one_ele][sc['o_id']].map( one_ele_df.set_index(sc['o_id']).to_dict(orient='dict').get('coords')) diff --git a/pandapower/converter/cim/cim2pp/converter_classes/externalnetworks/externalNetworkInjectionsCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/externalnetworks/externalNetworkInjectionsCim16.py index a3293aa4e..5950cd054 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/externalnetworks/externalNetworkInjectionsCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/externalnetworks/externalNetworkInjectionsCim16.py @@ -110,6 +110,6 @@ def get_volate_from_controllers(self, eqssh_eni): regulation_controllers = self.cimConverter.merge_eq_ssh_profile('RegulatingControl') regulation_controllers = regulation_controllers.loc[regulation_controllers['mode'] == 'voltage'] regulation_controllers = regulation_controllers[['rdfId', 'targetValue', 'enabled']] - regulation_controllers.rename(columns={'rdfId': 'RegulatingControl'}, inplace=True) + regulation_controllers = regulation_controllers.rename(columns={'rdfId': 'RegulatingControl'}) eqssh_eni = pd.merge(eqssh_eni, regulation_controllers, how='left', on='RegulatingControl') return eqssh_eni diff --git a/pandapower/converter/cim/cim2pp/converter_classes/generators/asynchronousMachinesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/generators/asynchronousMachinesCim16.py index 1f1a97d1e..2279b5896 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/generators/asynchronousMachinesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/generators/asynchronousMachinesCim16.py @@ -48,11 +48,11 @@ def _prepare_asynchronous_machines_cim16(self) -> pd.DataFrame: eq_generating_units = pd.concat([eq_generating_units, self.cimConverter.cim['eq']['NuclearGeneratingUnit']], sort=False) eq_generating_units['type'].fillna('Nuclear', inplace=True) - eq_generating_units.rename(columns={'rdfId': 'GeneratingUnit'}, inplace=True) + eq_generating_units = eq_generating_units.rename(columns={'rdfId': 'GeneratingUnit'}) eqssh_asynchronous_machines = self.cimConverter.merge_eq_ssh_profile('AsynchronousMachine', add_cim_type_column=True) # prevent conflict of merging two dataframes each containing column 'name' - eq_generating_units.drop('name', axis=1, inplace=True) + eq_generating_units = eq_generating_units.drop('name', axis=1) eqssh_asynchronous_machines = pd.merge(eqssh_asynchronous_machines, eq_generating_units, how='left', on='GeneratingUnit') eqssh_asynchronous_machines = pd.merge(eqssh_asynchronous_machines, self.cimConverter.bus_merge, how='left', @@ -66,12 +66,12 @@ def _prepare_asynchronous_machines_cim16(self) -> pd.DataFrame: eqssh_asynchronous_machines['generator_type'] = 'async' eqssh_asynchronous_machines['loading_percent'] = \ 100 * eqssh_asynchronous_machines['p_mw'] / eqssh_asynchronous_machines['ratedMechanicalPower'] - eqssh_asynchronous_machines.rename(columns={'rdfId_Terminal': sc['t'], 'rdfId': sc['o_id'], + eqssh_asynchronous_machines = eqssh_asynchronous_machines.rename(columns={'rdfId_Terminal': sc['t'], 'rdfId': sc['o_id'], 'connected': 'in_service', 'index_bus': 'bus', 'rxLockedRotorRatio': 'rx', 'iaIrRatio': 'lrc_pu', 'ratedPowerFactor': 'cos_phi', 'ratedU': 'vn_kv', 'efficiency': 'efficiency_n_percent', - 'ratedMechanicalPower': 'pn_mech_mw'}, inplace=True) + 'ratedMechanicalPower': 'pn_mech_mw'}) eqssh_asynchronous_machines['scaling'] = 1 eqssh_asynchronous_machines['efficiency_percent'] = 100 return eqssh_asynchronous_machines diff --git a/pandapower/converter/cim/cim2pp/converter_classes/generators/energySourcesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/generators/energySourcesCim16.py index b587f06c3..30c38e5ab 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/generators/energySourcesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/generators/energySourcesCim16.py @@ -38,12 +38,12 @@ def _prepare_energy_sources_cim16(self) -> pd.DataFrame: pd.concat([self.cimConverter.cim['eq']['EnergySchedulingType'], self.cimConverter.cim['eq_bd']['EnergySchedulingType']], sort=False) - eq_energy_scheduling_type.rename(columns={'rdfId': 'EnergySchedulingType', 'name': 'type'}, inplace=True) + eq_energy_scheduling_type = eq_energy_scheduling_type.rename(columns={'rdfId': 'EnergySchedulingType', 'name': 'type'}) eqssh_energy_sources = self.cimConverter.merge_eq_ssh_profile('EnergySource', add_cim_type_column=True) eqssh_energy_sources = pd.merge(eqssh_energy_sources, eq_energy_scheduling_type, how='left', on='EnergySchedulingType') eqssh_energy_sources = pd.merge(eqssh_energy_sources, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_energy_sources.drop_duplicates(['rdfId'], keep='first', inplace=True) + eqssh_energy_sources = eqssh_energy_sources.drop_duplicates(['rdfId'], keep='first') sgen_type = dict({'WP': 'WP', 'Wind': 'WP', 'PV': 'PV', 'SolarPV': 'PV', 'BioGas': 'BioGas', 'OtherRES': 'OtherRES', 'CHP': 'CHP'}) # todo move? eqssh_energy_sources['type'] = eqssh_energy_sources['type'].map(sgen_type) @@ -55,6 +55,6 @@ def _prepare_energy_sources_cim16(self) -> pd.DataFrame: eqssh_energy_sources['scaling'] = 1. eqssh_energy_sources['current_source'] = True eqssh_energy_sources['generator_type'] = 'current_source' - eqssh_energy_sources.rename(columns={'rdfId_Terminal': sc['t'], 'rdfId': sc['o_id'], 'connected': 'in_service', - 'index_bus': 'bus'}, inplace=True) + eqssh_energy_sources = eqssh_energy_sources.rename(columns={'rdfId_Terminal': sc['t'], 'rdfId': sc['o_id'], 'connected': 'in_service', + 'index_bus': 'bus'}) return eqssh_energy_sources diff --git a/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py index b7178c17b..37db5fc18 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py @@ -57,12 +57,12 @@ def _prepare_synchronous_machines_cim16(self) -> pd.DataFrame: eq_generating_units = pd.concat([eq_generating_units, self.cimConverter.cim['eq']['NuclearGeneratingUnit']], sort=False) eq_generating_units['type'].fillna('Nuclear', inplace=True) - eq_generating_units.rename(columns={'rdfId': 'GeneratingUnit'}, inplace=True) + eq_generating_units = eq_generating_units.rename(columns={'rdfId': 'GeneratingUnit'}) eqssh_synchronous_machines = self.cimConverter.merge_eq_ssh_profile('SynchronousMachine', add_cim_type_column=True) if 'type' in eqssh_synchronous_machines.columns: - eqssh_synchronous_machines.drop(columns=['type'], inplace=True) - if 'EquipmentContainer' in eqssh_synchronous_machines.columns: + eqssh_synchronous_machines = eqssh_synchronous_machines.drop(columns=['type']) + eqssh_synchronous_machines = eqssh_synchronous_machines.drop(columns=['type'] eqssh_synchronous_machines.drop(columns=['EquipmentContainer'], inplace=True) eqssh_synchronous_machines = pd.merge(eqssh_synchronous_machines, eq_generating_units, how='left', on='GeneratingUnit') @@ -71,11 +71,11 @@ def _prepare_synchronous_machines_cim16(self) -> pd.DataFrame: # if voltage is not on connectivity node, topological node will be used eqtp_terminals = pd.merge(self.cimConverter.cim['eq']['Terminal'], self.cimConverter.cim['tp']['Terminal'], how='left', on='rdfId') - eqtp_terminals.ConnectivityNode.fillna(eqtp_terminals.TopologicalNode, inplace=True) + eqtp_terminals.ConnectivityNode = eqtp_terminals.ConnectivityNode.fillna(eqtp_terminals.TopologicalNode) eqtp_terminals = eqtp_terminals[['rdfId', 'ConnectivityNode']].rename( columns={'rdfId': 'Terminal', 'ConnectivityNode': 'reg_control_cnode'}) eqssh_reg_control = pd.merge(eqssh_reg_control, eqtp_terminals, how='left', on='Terminal') - eqssh_reg_control.drop(columns=['Terminal'], inplace=True) + eqssh_reg_control = eqssh_reg_control.drop(columns=['Terminal']) # add the voltage from the bus eqssh_reg_control = pd.merge(eqssh_reg_control, self.cimConverter.net.bus[['vn_kv', sc['o_id']]].rename( columns={sc['o_id']: 'reg_control_cnode'}), how='left', on='reg_control_cnode') @@ -86,10 +86,10 @@ def _prepare_synchronous_machines_cim16(self) -> pd.DataFrame: how='left', on='RegulatingControl') eqssh_synchronous_machines = pd.merge(eqssh_synchronous_machines, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_synchronous_machines.drop_duplicates(['rdfId'], keep='first', inplace=True) + eqssh_synchronous_machines = eqssh_synchronous_machines.drop_duplicates(['rdfId'], keep='first') eqssh_synchronous_machines['vm_pu'] = eqssh_synchronous_machines.targetValue / eqssh_synchronous_machines.vn_kv eqssh_synchronous_machines['vm_pu'].fillna(1., inplace=True) - eqssh_synchronous_machines.rename(columns={'vn_kv': 'bus_voltage'}, inplace=True) + eqssh_synchronous_machines = eqssh_synchronous_machines.rename(columns={'vn_kv': 'bus_voltage'}) eqssh_synchronous_machines['slack'] = False # set the slack = True for gens with highest prio # get the highest prio from SynchronousMachines @@ -101,7 +101,7 @@ def _prepare_synchronous_machines_cim16(self) -> pd.DataFrame: regulation_controllers = self.cimConverter.merge_eq_ssh_profile('RegulatingControl') regulation_controllers = regulation_controllers.loc[regulation_controllers['mode'] == 'voltage'] regulation_controllers = regulation_controllers[['rdfId', 'targetValue', 'enabled']] - regulation_controllers.rename(columns={'rdfId': 'RegulatingControl'}, inplace=True) + regulation_controllers = regulation_controllers.rename(columns={'rdfId': 'RegulatingControl'}) enis = pd.merge(enis, regulation_controllers, how='left', on='RegulatingControl') eni_ref_prio_min = enis.loc[(enis['referencePriority'] > 0) & (enis['enabled']), 'referencePriority'].min() @@ -132,9 +132,9 @@ def _prepare_synchronous_machines_cim16(self) -> pd.DataFrame: eqssh_synchronous_machines['rx'] = eqssh_synchronous_machines['r2'] / eqssh_synchronous_machines['x2'] eqssh_synchronous_machines['scaling'] = 1. eqssh_synchronous_machines['generator_type'] = 'current_source' - eqssh_synchronous_machines.rename(columns={'rdfId_Terminal': sc['t'], 'rdfId': sc['o_id'], + eqssh_synchronous_machines = eqssh_synchronous_machines.rename(columns={'rdfId_Terminal': sc['t'], 'rdfId': sc['o_id'], 'connected': 'in_service', 'index_bus': 'bus', 'minOperatingP': 'min_p_mw', 'maxOperatingP': 'max_p_mw', 'minQ': 'min_q_mvar', 'maxQ': 'max_q_mvar', - 'ratedPowerFactor': 'cos_phi'}, inplace=True) + 'ratedPowerFactor': 'cos_phi'}) return eqssh_synchronous_machines diff --git a/pandapower/converter/cim/cim2pp/converter_classes/impedance/equivalentBranchesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/impedance/equivalentBranchesCim16.py index b644ce0f3..52a12c5f0 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/impedance/equivalentBranchesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/impedance/equivalentBranchesCim16.py @@ -77,7 +77,7 @@ def _prepare_equivalent_branches_cim16(self) -> pd.DataFrame: message="The EquivalentBranch with RDF ID %s has %s Terminals!" % (rdfId, count))) eq_eb = eq_eb[0:0] # sort by RDF ID and the sequenceNumber to make sure r12 and r21 are in the correct order - eq_eb.sort_values(by=['rdfId', 'sequenceNumber'], inplace=True) + eq_eb = eq_eb.sort_values(by=['rdfId', 'sequenceNumber']) # copy the columns which are needed to reduce the eq_eb to one row per equivalent branch eq_eb['rdfId_Terminal2'] = eq_eb['rdfId_Terminal'].copy() eq_eb['connected2'] = eq_eb['connected'].copy() @@ -88,7 +88,7 @@ def _prepare_equivalent_branches_cim16(self) -> pd.DataFrame: eq_eb.rdfId_Terminal2 = eq_eb.rdfId_Terminal2.iloc[1:].reset_index().rdfId_Terminal2 eq_eb.connected2 = eq_eb.connected2.iloc[1:].reset_index().connected2 eq_eb.index_bus2 = eq_eb.index_bus2.iloc[1:].reset_index().index_bus2 - eq_eb.drop_duplicates(['rdfId'], keep='first', inplace=True) + eq_eb = eq_eb.drop_duplicates(['rdfId'], keep='first') if hasattr(self.cimConverter.net, 'sn_mva'): eq_eb['sn_mva'] = self.cimConverter.net['sn_mva'] else: @@ -104,6 +104,6 @@ def _prepare_equivalent_branches_cim16(self) -> pd.DataFrame: eq_eb['rtf0_pu'] = eq_eb['zeroR21'] / eq_eb['z_base'] eq_eb['xtf0_pu'] = eq_eb['zeroX21'] / eq_eb['z_base'] eq_eb['in_service'] = eq_eb.connected & eq_eb.connected2 - eq_eb.rename(columns={'rdfId_Terminal': sc['t_from'], 'rdfId_Terminal2': sc['t_to'], 'rdfId': sc['o_id'], - 'index_bus': 'from_bus', 'index_bus2': 'to_bus'}, inplace=True) + eq_eb = eq_eb.rename(columns={'rdfId_Terminal': sc['t_from'], 'rdfId_Terminal2': sc['t_to'], 'rdfId': sc['o_id'], + 'index_bus': 'from_bus', 'index_bus2': 'to_bus'}) return eq_eb diff --git a/pandapower/converter/cim/cim2pp/converter_classes/impedance/seriesCompensatorsCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/impedance/seriesCompensatorsCim16.py index 16e5cb384..2ffc3778d 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/impedance/seriesCompensatorsCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/impedance/seriesCompensatorsCim16.py @@ -74,7 +74,7 @@ def _prepare_series_compensators_cim16(self) -> pd.DataFrame: message="The SeriesCompensator with RDF ID %s has %s Terminals!" % (rdfId, count))) eq_sc = eq_sc[0:0] # sort by RDF ID and the sequenceNumber to make sure r12 and r21 are in the correct order - eq_sc.sort_values(by=['rdfId', 'sequenceNumber'], inplace=True) + eq_sc = eq_sc.sort_values(by=['rdfId', 'sequenceNumber']) # copy the columns which are needed to reduce the eq_sc to one row per equivalent branch eq_sc['rdfId_Terminal2'] = eq_sc['rdfId_Terminal'].copy() eq_sc['connected2'] = eq_sc['connected'].copy() @@ -85,7 +85,7 @@ def _prepare_series_compensators_cim16(self) -> pd.DataFrame: eq_sc.rdfId_Terminal2 = eq_sc.rdfId_Terminal2.iloc[1:].reset_index().rdfId_Terminal2 eq_sc.connected2 = eq_sc.connected2.iloc[1:].reset_index().connected2 eq_sc.index_bus2 = eq_sc.index_bus2.iloc[1:].reset_index().index_bus2 - eq_sc.drop_duplicates(['rdfId'], keep='first', inplace=True) + eq_sc = eq_sc.drop_duplicates(['rdfId'], keep='first') if hasattr(self.cimConverter.net, 'sn_mva'): eq_sc['sn_mva'] = self.cimConverter.net['sn_mva'] else: @@ -101,6 +101,6 @@ def _prepare_series_compensators_cim16(self) -> pd.DataFrame: eq_sc['rtf0_pu'] = eq_sc['r0'] / eq_sc['z_base'] eq_sc['xtf0_pu'] = eq_sc['x0'] / eq_sc['z_base'] eq_sc['in_service'] = eq_sc.connected & eq_sc.connected2 - eq_sc.rename(columns={'rdfId_Terminal': sc['t_from'], 'rdfId_Terminal2': sc['t_to'], 'rdfId': sc['o_id'], - 'index_bus': 'from_bus', 'index_bus2': 'to_bus'}, inplace=True) + eq_sc = eq_sc.rename(columns={'rdfId_Terminal': sc['t_from'], 'rdfId_Terminal2': sc['t_to'], 'rdfId': sc['o_id'], + 'index_bus': 'from_bus', 'index_bus2': 'to_bus'}) return eq_sc diff --git a/pandapower/converter/cim/cim2pp/converter_classes/lines/acLineSegmentsCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/lines/acLineSegmentsCim16.py index 37161e043..2917fd92a 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/lines/acLineSegmentsCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/lines/acLineSegmentsCim16.py @@ -27,10 +27,10 @@ def convert_ac_line_segments_cim16(self, convert_line_to_switch, line_r_limit, l # -------- lines -------- if 'line' in eq_ac_line_segments['kindOfType'].values: line_df = eq_ac_line_segments.loc[eq_ac_line_segments['kindOfType'] == 'line'] - line_df.rename(columns={ + line_df = line_df.rename(columns={ 'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t_from'], 'rdfId_Terminal2': sc['t_to'], 'index_bus': 'from_bus', 'index_bus2': 'to_bus', 'length': 'length_km', - 'shortCircuitEndTemperature': 'endtemp_degree'}, inplace=True) + 'shortCircuitEndTemperature': 'endtemp_degree'}) line_df[sc['o_cl']] = 'ACLineSegment' line_df['in_service'] = line_df.connected & line_df.connected2 line_df['r_ohm_per_km'] = abs(line_df.r) / line_df.length_km @@ -52,9 +52,9 @@ def convert_ac_line_segments_cim16(self, convert_line_to_switch, line_r_limit, l if 'switch' in eq_ac_line_segments['kindOfType'].values: switch_df = eq_ac_line_segments.loc[eq_ac_line_segments['kindOfType'] == 'switch'] - switch_df.rename(columns={ + switch_df = switch_df.rename(columns={ 'rdfId': sc['o_id'], 'index_bus': 'bus', 'index_bus2': 'element', 'rdfId_Terminal': sc['t_bus'], - 'rdfId_Terminal2': sc['t_ele']}, inplace=True) + 'rdfId_Terminal2': sc['t_ele']}) switch_df['et'] = 'b' switch_df['type'] = None switch_df['z_ohm'] = 0 @@ -107,20 +107,20 @@ def _prepare_ac_line_segments_cim16(self, convert_line_to_switch, line_r_limit, eq_ac_line_segments.reset_index(inplace=True) # now merge with OperationalLimitSets and CurrentLimits eq_operational_limit_sets = self.cimConverter.cim['eq']['OperationalLimitSet'][['rdfId', 'Terminal']] - eq_operational_limit_sets.rename(columns={'rdfId': 'rdfId_OperationalLimitSet', - 'Terminal': 'rdfId_Terminal'}, inplace=True) + eq_operational_limit_sets = eq_operational_limit_sets.rename(columns={'rdfId': 'rdfId_OperationalLimitSet', + 'Terminal': 'rdfId_Terminal'}) eq_ac_line_segments = pd.merge(eq_ac_line_segments, eq_operational_limit_sets, how='left', on='rdfId_Terminal') eq_current_limits = self.cimConverter.cim['eq']['CurrentLimit'][['rdfId', 'OperationalLimitSet', 'value']] - eq_current_limits.rename(columns={'rdfId': 'rdfId_CurrentLimit', - 'OperationalLimitSet': 'rdfId_OperationalLimitSet'}, inplace=True) + eq_current_limits = eq_current_limits.rename(columns={'rdfId': 'rdfId_CurrentLimit', + 'OperationalLimitSet': 'rdfId_OperationalLimitSet'}) eq_ac_line_segments = pd.merge(eq_ac_line_segments, eq_current_limits, how='left', on='rdfId_OperationalLimitSet') eq_ac_line_segments.value = eq_ac_line_segments.value.astype(float) # sort by rdfId, sequenceNumber and value. value is max_i_ka, choose the lowest one if more than one is # given (A line may have more than one max_i_ka in CIM, different modes e.g. normal) - eq_ac_line_segments.sort_values(by=['rdfId', 'sequenceNumber', 'value'], inplace=True) - eq_ac_line_segments.drop_duplicates(['rdfId', 'rdfId_Terminal'], keep='first', inplace=True) + eq_ac_line_segments = eq_ac_line_segments.sort_values(by=['rdfId', 'sequenceNumber', 'value']) + eq_ac_line_segments = eq_ac_line_segments.drop_duplicates(['rdfId', 'rdfId_Terminal'], keep='first') # copy the columns which are needed to reduce the eq_ac_line_segments to one row per line eq_ac_line_segments['rdfId_Terminal2'] = eq_ac_line_segments['rdfId_Terminal'].copy() @@ -135,7 +135,7 @@ def _prepare_ac_line_segments_cim16(self, convert_line_to_switch, line_r_limit, eq_ac_line_segments.connected2 = eq_ac_line_segments.connected2.iloc[1:].reset_index().connected2 eq_ac_line_segments.index_bus2 = eq_ac_line_segments.index_bus2.iloc[1:].reset_index().index_bus2 eq_ac_line_segments.value2 = eq_ac_line_segments.value2.iloc[1:].reset_index().value2 - eq_ac_line_segments.drop_duplicates(['rdfId'], keep='first', inplace=True) + eq_ac_line_segments = eq_ac_line_segments.drop_duplicates(['rdfId'], keep='first') # get the max_i_ka eq_ac_line_segments['max_i_ka'] = eq_ac_line_segments['value'].fillna(eq_ac_line_segments['value2']) * 1e-3 diff --git a/pandapower/converter/cim/cim2pp/converter_classes/lines/dcLineSegmentsCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/lines/dcLineSegmentsCim16.py index ac3930701..11f5dee1d 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/lines/dcLineSegmentsCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/lines/dcLineSegmentsCim16.py @@ -66,11 +66,11 @@ def _prepare_dc_line_segments_cim16(self) -> pd.DataFrame: ignore_index=True, sort=False), how='left', on='rdfId') if 'name' in converters.columns: - converters.drop(columns=['name'], inplace=True) + converters = converters.drop(columns=['name']) # merge with the terminals converters = pd.merge(converters, self.cimConverter.bus_merge, how='left', on='rdfId') - converters.drop(columns=['sequenceNumber'], inplace=True) - converters.rename(columns={'rdfId': 'converters'}, inplace=True) + converters = converters.drop(columns=['sequenceNumber']) + converters = converters.rename(columns={'rdfId': 'converters'}) converter_terminals = pd.concat( [self.cimConverter.cim['eq']['Terminal'], self.cimConverter.cim['eq_bd']['Terminal']], ignore_index=True, sort=False) @@ -81,7 +81,7 @@ def _prepare_dc_line_segments_cim16(self) -> pd.DataFrame: how='left', on='ConnectivityNode') # get the missing converters (maybe there is a switch or something else between the line and the converter) t = self.cimConverter.cim['eq']['DCTerminal'][['DCNode', 'DCConductingEquipment', 'sequenceNumber']] - t.rename(columns={'DCNode': 'ConnectivityNode', 'DCConductingEquipment': 'ConductingEquipment'}, inplace=True) + t = t.rename(columns={'DCNode': 'ConnectivityNode', 'DCConductingEquipment': 'ConductingEquipment'}) def search_converter(cn_ids: Dict[str, str], visited_cns: List[str]) -> str: new_cn_dict = dict() @@ -116,12 +116,12 @@ def search_converter(cn_ids: Dict[str, str], visited_cns: List[str]) -> str: level=LogLevel.WARNING, code=ReportCode.WARNING_CONVERTING, message="Error processing the DCLineSegments, there is a problem with Terminals in the source " "data!")) - dc_line_segments.drop(columns=['ConnectivityNode'], inplace=True) + dc_line_segments = dc_line_segments.drop(columns=['ConnectivityNode']) dc_line_segments = pd.merge(dc_line_segments, converters_t, how='left', on='converters') dc_line_segments['targetUpcc'].fillna(dc_line_segments['base_voltage_bus'], inplace=True) # copy the columns which are needed to reduce the dc_line_segments to one row per line - dc_line_segments.sort_values(by=['rdfId', 'sequenceNumber'], inplace=True) + dc_line_segments = dc_line_segments.sort_values(by=['rdfId', 'sequenceNumber']) # a list of DC line parameters which are used for each DC line end dc_line_segments.reset_index(inplace=True) copy_list = ['index_bus', 'rdfId_Terminal', 'connected', 'p', 'ratedUdc', 'targetUpcc', 'base_voltage_bus'] @@ -131,7 +131,7 @@ def search_converter(cn_ids: Dict[str, str], visited_cns: List[str]) -> str: # cut the first element from the copied columns dc_line_segments[one_item + '2'] = dc_line_segments[one_item + '2'].iloc[1:].reset_index()[one_item + '2'] del copy_list, one_item - dc_line_segments.drop_duplicates(['rdfId'], keep='first', inplace=True) + dc_line_segments = dc_line_segments.drop_duplicates(['rdfId'], keep='first') dc_line_segments = pd.merge(dc_line_segments, pd.DataFrame(dc_line_segments.pivot_table(index=['converters'], aggfunc='size'), columns=['converter_dups']), how='left', on='converters') @@ -142,8 +142,8 @@ def search_converter(cn_ids: Dict[str, str], visited_cns: List[str]) -> str: dc_line_segments['vm_from_pu'] = dc_line_segments['targetUpcc'] / dc_line_segments['base_voltage_bus'] dc_line_segments['vm_to_pu'] = dc_line_segments['targetUpcc2'] / dc_line_segments['base_voltage_bus2'] dc_line_segments['in_service'] = dc_line_segments.connected & dc_line_segments.connected2 - dc_line_segments.rename(columns={ + dc_line_segments = dc_line_segments.rename(columns={ 'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t_from'], 'rdfId_Terminal2': sc['t_to'], 'index_bus': 'from_bus', - 'index_bus2': 'to_bus'}, inplace=True) + 'index_bus2': 'to_bus'}) return dc_line_segments diff --git a/pandapower/converter/cim/cim2pp/converter_classes/loads/conformLoadsCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/loads/conformLoadsCim16.py index 19909d362..c46c03914 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/loads/conformLoadsCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/loads/conformLoadsCim16.py @@ -31,8 +31,8 @@ def convert_conform_loads_cim16(self): def _prepare_conform_loads_cim16(self) -> pd.DataFrame: eqssh_conform_loads = self.cimConverter.merge_eq_ssh_profile('ConformLoad', add_cim_type_column=True) eqssh_conform_loads = pd.merge(eqssh_conform_loads, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_conform_loads.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', - 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}, inplace=True) + eqssh_conform_loads = eqssh_conform_loads.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', + 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}) eqssh_conform_loads['const_i_percent'] = 0. eqssh_conform_loads['const_z_percent'] = 0. eqssh_conform_loads['scaling'] = 1. diff --git a/pandapower/converter/cim/cim2pp/converter_classes/loads/energyConcumersCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/loads/energyConcumersCim16.py index 4e579235d..fbfb4d04a 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/loads/energyConcumersCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/loads/energyConcumersCim16.py @@ -31,8 +31,8 @@ def convert_energy_consumers_cim16(self): def _prepare_energy_consumers_cim16(self) -> pd.DataFrame: eqssh_energy_consumers = self.cimConverter.merge_eq_ssh_profile('EnergyConsumer', add_cim_type_column=True) eqssh_energy_consumers = pd.merge(eqssh_energy_consumers, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_energy_consumers.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', - 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}, inplace=True) + eqssh_energy_consumers = eqssh_energy_consumers.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', + 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}) eqssh_energy_consumers['const_i_percent'] = 0. eqssh_energy_consumers['const_z_percent'] = 0. eqssh_energy_consumers['scaling'] = 1. diff --git a/pandapower/converter/cim/cim2pp/converter_classes/loads/nonConformLoadsCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/loads/nonConformLoadsCim16.py index 88cda2ea2..59634e67b 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/loads/nonConformLoadsCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/loads/nonConformLoadsCim16.py @@ -31,8 +31,8 @@ def convert_non_conform_loads_cim16(self): def _prepare_non_conform_loads_cim16(self) -> pd.DataFrame: eqssh_non_conform_loads = self.cimConverter.merge_eq_ssh_profile('NonConformLoad', add_cim_type_column=True) eqssh_non_conform_loads = pd.merge(eqssh_non_conform_loads, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_non_conform_loads.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', - 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}, inplace=True) + eqssh_non_conform_loads = eqssh_non_conform_loads.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', + 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}) eqssh_non_conform_loads['const_i_percent'] = 0. eqssh_non_conform_loads['const_z_percent'] = 0. eqssh_non_conform_loads['scaling'] = 1. diff --git a/pandapower/converter/cim/cim2pp/converter_classes/loads/stationSuppliesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/loads/stationSuppliesCim16.py index 632125491..ecb54eeed 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/loads/stationSuppliesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/loads/stationSuppliesCim16.py @@ -31,8 +31,8 @@ def convert_station_supplies_cim16(self): def _prepare_station_supplies_cim16(self) -> pd.DataFrame: eqssh_station_supplies = self.cimConverter.merge_eq_ssh_profile('StationSupply', add_cim_type_column=True) eqssh_station_supplies = pd.merge(eqssh_station_supplies, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_station_supplies.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', - 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}, inplace=True) + eqssh_station_supplies = eqssh_station_supplies.rename(columns={'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'index_bus': 'bus', + 'connected': 'in_service', 'p': 'p_mw', 'q': 'q_mvar'}) eqssh_station_supplies['const_i_percent'] = 0. eqssh_station_supplies['const_z_percent'] = 0. eqssh_station_supplies['scaling'] = 1. diff --git a/pandapower/converter/cim/cim2pp/converter_classes/shunts/linearShuntCompensatorCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/shunts/linearShuntCompensatorCim16.py index ca2b1e6ca..be44ccdc1 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/shunts/linearShuntCompensatorCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/shunts/linearShuntCompensatorCim16.py @@ -32,9 +32,9 @@ def convert_linear_shunt_compensator_cim16(self): def _prepare_linear_shunt_compensator_cim16(self) -> pd.DataFrame: eqssh_shunts = self.cimConverter.merge_eq_ssh_profile('LinearShuntCompensator', add_cim_type_column=True) eqssh_shunts = pd.merge(eqssh_shunts, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_shunts.rename(columns={ + eqssh_shunts = eqssh_shunts.rename(columns={ 'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'connected': 'in_service', 'index_bus': 'bus', - 'nomU': 'vn_kv', 'sections': 'step', 'maximumSections': 'max_step'}, inplace=True) + 'nomU': 'vn_kv', 'sections': 'step', 'maximumSections': 'max_step'}) y = eqssh_shunts['gPerSection'] + eqssh_shunts['bPerSection'] * 1j s = eqssh_shunts['vn_kv'] ** 2 * np.conj(y) eqssh_shunts['p_mw'] = s.values.real diff --git a/pandapower/converter/cim/cim2pp/converter_classes/shunts/nonLinearShuntCompensatorCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/shunts/nonLinearShuntCompensatorCim16.py index 0b43208bf..0f4b843fe 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/shunts/nonLinearShuntCompensatorCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/shunts/nonLinearShuntCompensatorCim16.py @@ -59,9 +59,9 @@ def _prepare_nonlinear_shunt_compensator_cim16(self) -> pd.DataFrame: eqssh_shunts.loc[eqssh_shunts['sections'] >= eqssh_shunts['sectionNumber'], 'q'] = \ eqssh_shunts['q'] + eqssh_shunts['q_temp'] eqssh_shunts = eqssh_shunts[eqssh_shunts_cols] - eqssh_shunts.rename(columns={ + eqssh_shunts = eqssh_shunts.rename(columns={ 'rdfId': sc['o_id'], 'rdfId_Terminal': sc['t'], 'connected': 'in_service', 'index_bus': 'bus', - 'nomU': 'vn_kv', 'p': 'p_mw', 'q': 'q_mvar'}, inplace=True) + 'nomU': 'vn_kv', 'p': 'p_mw', 'q': 'q_mvar'}) eqssh_shunts['step'] = 1 eqssh_shunts['max_step'] = 1 return eqssh_shunts diff --git a/pandapower/converter/cim/cim2pp/converter_classes/shunts/staticVarCompensatorCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/shunts/staticVarCompensatorCim16.py index 200f4a0d8..1c8acf6ad 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/shunts/staticVarCompensatorCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/shunts/staticVarCompensatorCim16.py @@ -31,7 +31,7 @@ def convert_static_var_compensator_cim16(self): def _prepare_static_var_compensator_cim16(self) -> pd.DataFrame: eq_stat_coms = self.cimConverter.merge_eq_ssh_profile('StaticVarCompensator', True) eq_stat_coms = pd.merge(eq_stat_coms, self.cimConverter.bus_merge, how='left', on='rdfId') - eq_stat_coms.rename(columns={'q': 'q_mvar'}, inplace=True) + eq_stat_coms = eq_stat_coms.rename(columns={'q': 'q_mvar'}) # get the active power and reactive power from SV profile eq_stat_coms = pd.merge(eq_stat_coms, self.cimConverter.cim['sv']['SvPowerFlow'][['p', 'q', 'Terminal']], how='left', left_on='rdfId_Terminal', right_on='Terminal') diff --git a/pandapower/converter/cim/cim2pp/converter_classes/switches/switchesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/switches/switchesCim16.py index 951bc3557..1587f3059 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/switches/switchesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/switches/switchesCim16.py @@ -50,7 +50,7 @@ def _prepare_switches_cim16(self) -> pd.DataFrame: ignore_index=True, sort=False) eqssh_switches.type[start_index_cim_net:] = 'LS' # drop all duplicates to fix class inherit problem in jpa - eqssh_switches.drop_duplicates(subset=['rdfId'], keep='first', inplace=True) + eqssh_switches = eqssh_switches.drop_duplicates(subset=['rdfId'], keep='first') switch_length_before_merge = eqssh_switches.index.size # until now eqssh_switches looks like: # rdfId name open ... @@ -58,7 +58,7 @@ def _prepare_switches_cim16(self) -> pd.DataFrame: # _x02 switch2 False ... # now join with the terminals eqssh_switches = pd.merge(eqssh_switches, self.cimConverter.bus_merge, how='left', on='rdfId') - eqssh_switches.sort_values(by=['rdfId', 'sequenceNumber'], inplace=True) + eqssh_switches = eqssh_switches.sort_values(by=['rdfId', 'sequenceNumber']) eqssh_switches.reset_index(inplace=True) # copy the columns which are needed to reduce the eqssh_switches to one line per switch eqssh_switches['rdfId_Terminal2'] = eqssh_switches['rdfId_Terminal'].copy() @@ -70,7 +70,7 @@ def _prepare_switches_cim16(self) -> pd.DataFrame: eqssh_switches.rdfId_Terminal2 = eqssh_switches.rdfId_Terminal2.iloc[1:].reset_index().rdfId_Terminal2 eqssh_switches.connected2 = eqssh_switches.connected2.iloc[1:].reset_index().connected2 eqssh_switches.index_bus2 = eqssh_switches.index_bus2.iloc[1:].reset_index().index_bus2 - eqssh_switches.drop_duplicates(subset=['rdfId'], keep='first', inplace=True) + eqssh_switches = eqssh_switches.drop_duplicates(subset=['rdfId'], keep='first') else: self.logger.error("Something went wrong at switches, seems like that terminals for connection with " "connectivity nodes are missing!") @@ -87,8 +87,8 @@ def _prepare_switches_cim16(self) -> pd.DataFrame: level=LogLevel.WARNING, code=ReportCode.WARNING_CONVERTING, message="The switch with RDF ID %s has %s Terminals!" % (rdfId, count))) eqssh_switches = eqssh_switches[0:0] - eqssh_switches.rename(columns={'rdfId': sc['o_id'], 'index_bus': 'bus', 'index_bus2': 'element', - 'rdfId_Terminal': sc['t_bus'], 'rdfId_Terminal2': sc['t_ele']}, inplace=True) + eqssh_switches = eqssh_switches.rename(columns={'rdfId': sc['o_id'], 'index_bus': 'bus', 'index_bus2': 'element', + 'rdfId_Terminal': sc['t_bus'], 'rdfId_Terminal2': sc['t_ele']}) eqssh_switches['et'] = 'b' eqssh_switches['z_ohm'] = 0 if eqssh_switches.index.size > 0: diff --git a/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py index 52d981bd8..808f6e87a 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py @@ -29,7 +29,7 @@ def convert_power_transformers_cim16(self): power_trafo2w = power_trafo_counts[power_trafo_counts == 2].index.tolist() power_trafo3w = power_trafo_counts[power_trafo_counts == 3].index.tolist() - eq_power_transformers.set_index('PowerTransformer', inplace=True) + eq_power_transformers = eq_power_transformers.set_index('PowerTransformer') power_trafo2w = eq_power_transformers.loc[power_trafo2w].reset_index() power_trafo3w = eq_power_transformers.loc[power_trafo3w].reset_index() @@ -74,7 +74,7 @@ def _create_trafo_characteristics(self, trafo_type, trafo_df_origin): ptct = pd.concat([ptct, ptct_ratio], ignore_index=True, sort=False) ptct.rename(columns={'step': 'tabular_step', 'r': 'r_dev', 'x': 'x_dev', 'TransformerEnd': sc['pte_id']}, inplace=True) - ptct.drop(columns=['PhaseTapChangerTable'], inplace=True) + ptct = ptct.drop(columns=['PhaseTapChangerTable']) if trafo_type == 'trafo': trafo_df = trafo_df_origin.sort_values(['PowerTransformer', 'endNumber']).reset_index() # precessing the transformer data @@ -89,10 +89,10 @@ def _create_trafo_characteristics(self, trafo_type, trafo_df_origin): del copy_list, one_item fillna_list = ['neutralStep', 'lowStep', 'highStep', 'step'] for one_item in fillna_list: - trafo_df[one_item].fillna(trafo_df[one_item + '_lv'], inplace=True) + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv']) del fillna_list, one_item # just keep one transformer - trafo_df.drop_duplicates(subset=['PowerTransformer'], keep='first', inplace=True) + trafo_df = trafo_df.drop_duplicates(subset=['PowerTransformer'], keep='first') # merge the trafos with the tap changers trafo_df = pd.merge(trafo_df, ptct, how='left', on=sc['pte_id']) trafo_df = pd.merge(trafo_df, ptct.rename(columns={'tabular_step': 'tabular_step_lv', 'r_dev': 'r_dev_lv', @@ -101,12 +101,12 @@ def _create_trafo_characteristics(self, trafo_type, trafo_df_origin): how='left', on=sc['pte_id'] + '_lv') fillna_list = ['tabular_step'] for one_item in fillna_list: - trafo_df[one_item].fillna(trafo_df[one_item + '_lv'], inplace=True) - del fillna_list, one_item + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv']) + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv'] trafo_df.dropna(subset=['r_dev', 'r_dev_lv'], how='all', inplace=True) fillna_list = ['r_dev', 'r_dev_lv', 'x_dev', 'x_dev_lv'] for one_item in fillna_list: - trafo_df[one_item].fillna(0, inplace=True) + trafo_df[one_item] = trafo_df[one_item].fillna(0) # special fix for the case that the impedance is given at the hv side but the tap changer is attached at # the lv side (so r_lv = 0 and r_dev_lv > 0): trafo_df.loc[(trafo_df['r_dev_lv'] != 0) & (trafo_df['r_lv'] == 0) & (trafo_df['r_dev'] == 0), 'r_dev'] = \ @@ -148,11 +148,11 @@ def _create_trafo_characteristics(self, trafo_type, trafo_df_origin): del copy_list, one_item fillna_list = ['neutralStep', 'lowStep', 'highStep', 'step'] for one_item in fillna_list: - trafo_df[one_item].fillna(trafo_df[one_item + '_mv'], inplace=True) - trafo_df[one_item].fillna(trafo_df[one_item + '_lv'], inplace=True) + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_mv']) + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv']) del fillna_list, one_item # just keep one transformer - trafo_df.drop_duplicates(subset=['PowerTransformer'], keep='first', inplace=True) + trafo_df = trafo_df.drop_duplicates(subset=['PowerTransformer'], keep='first') # merge the trafos with the tap changers trafo_df = pd.concat([pd.merge(trafo_df, ptct, how='left', on=sc['pte_id']), pd.merge(trafo_df, @@ -174,13 +174,13 @@ def _create_trafo_characteristics(self, trafo_type, trafo_df_origin): ~trafo_df.RatioTapChangerTable.isna())] fillna_list = ['tabular_step'] for one_item in fillna_list: - trafo_df[one_item].fillna(trafo_df[one_item + '_mv'], inplace=True) - trafo_df[one_item].fillna(trafo_df[one_item + '_lv'], inplace=True) - del fillna_list, one_item + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_mv']) + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv']) + trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_mv'] trafo_df.dropna(subset=['r_dev', 'r_dev_mv', 'r_dev_lv'], how='all', inplace=True) fillna_list = ['r_dev', 'r_dev_mv', 'r_dev_lv', 'x_dev', 'x_dev_mv', 'x_dev_lv'] for one_item in fillna_list: - trafo_df[one_item].fillna(0, inplace=True) + trafo_df[one_item] = trafo_df[one_item].fillna(0) # calculate vkr_percent and vk_percent trafo_df['r'] = trafo_df['r'] * (1 + trafo_df['r_dev'] / 100) trafo_df['r_mv'] = trafo_df['r_mv'] * (1 + trafo_df['r_dev_mv'] / 100) @@ -287,7 +287,7 @@ def _prepare_power_transformers_cim16(self) -> pd.DataFrame: self.cimConverter.cim['ssh']['PhaseTapChangerAsymmetrical'], how='left', on='rdfId') eqssh_tap_changers_async['stepVoltageIncrement'] = eqssh_tap_changers_async['voltageStepIncrement'][:] - eqssh_tap_changers_async.drop(columns=['voltageStepIncrement'], inplace=True) + eqssh_tap_changers_async = eqssh_tap_changers_async.drop(columns=['voltageStepIncrement']) eqssh_tap_changers_async[sc['tc']] = 'PhaseTapChangerAsymmetrical' eqssh_tap_changers_async[sc['tc_id']] = eqssh_tap_changers_async['rdfId'].copy() eqssh_tap_changers = pd.concat([eqssh_tap_changers, eqssh_tap_changers_async], ignore_index=True, sort=False) @@ -295,7 +295,7 @@ def _prepare_power_transformers_cim16(self) -> pd.DataFrame: self.cimConverter.cim['ssh']['PhaseTapChangerSymmetrical'], how='left', on='rdfId') eqssh_ratio_tap_changers_sync['stepVoltageIncrement'] = eqssh_ratio_tap_changers_sync['voltageStepIncrement'] - eqssh_ratio_tap_changers_sync.drop(columns=['voltageStepIncrement'], inplace=True) + eqssh_ratio_tap_changers_sync = eqssh_ratio_tap_changers_sync.drop(columns=['voltageStepIncrement']) eqssh_ratio_tap_changers_sync[sc['tc']] = 'PhaseTapChangerSymmetrical' eqssh_ratio_tap_changers_sync[sc['tc_id']] = eqssh_ratio_tap_changers_sync['rdfId'].copy() eqssh_tap_changers = \ @@ -305,7 +305,7 @@ def _prepare_power_transformers_cim16(self) -> pd.DataFrame: self.cimConverter.cim['eq']['PhaseTapChangerTabular'][['rdfId', 'TransformerEnd', 'PhaseTapChangerTable', 'highStep', 'lowStep', 'neutralStep']], self.cimConverter.cim['ssh']['PhaseTapChangerTabular'][['rdfId', 'step']], how='left', on='rdfId') - ptct.rename(columns={'step': 'current_step'}, inplace=True) + ptct = ptct.rename(columns={'step': 'current_step'}) ptct = pd.merge(ptct, self.cimConverter.cim['eq']['PhaseTapChangerTablePoint'][ ['PhaseTapChangerTable', 'step', 'angle', 'ratio']], how='left', on='PhaseTapChangerTable') for one_id, one_df in ptct.groupby('TransformerEnd'): @@ -316,19 +316,19 @@ def _prepare_power_transformers_cim16(self) -> pd.DataFrame: else: self.logger.warning("Ignoring PhaseTapChangerTabular with ID: %s. The current tap position is missing " "in the PhaseTapChangerTablePoints!" % one_id) - ptct.drop(drop_index, inplace=True) + ptct = ptct.drop(drop_index) continue current_step = one_df['current_step'].iloc[0] - one_df.set_index('step', inplace=True) - neutral_step = one_df['neutralStep'].iloc[0] + one_df = one_df.set_index('step') + one_df = one_df.set_index('step''].iloc[0] ptct.drop(drop_index, inplace=True) # ptct.loc[keep_index, 'angle'] = # one_df.loc[current_step, 'angle'] / max(1, abs(current_step - neutral_step)) ptct.loc[keep_index, 'angle'] = one_df.loc[current_step, 'angle'] # todo fix if pp supports them ptct.loc[keep_index, 'ratio'] = \ (one_df.loc[current_step, 'ratio'] - 1) * 100 / max(1, abs(current_step - neutral_step)) - ptct.drop(columns=['rdfId', 'PhaseTapChangerTable', 'step'], inplace=True) - ptct.rename(columns={'current_step': 'step'}, inplace=True) + ptct = ptct.drop(columns=['rdfId', 'PhaseTapChangerTable', 'step']) + ptct = ptct.rename(columns={'current_step': 'step'}) # ptct['stepPhaseShiftIncrement'] = ptct['angle'][:] # todo fix if pp supports them ptct['stepVoltageIncrement'] = ptct['ratio'][:] eqssh_tap_changers = pd.concat([eqssh_tap_changers, ptct], ignore_index=True, sort=False) @@ -339,12 +339,12 @@ def _prepare_power_transformers_cim16(self) -> pd.DataFrame: # self.logger.info("dups:") # for _, one_dup in eqssh_tap_changers[eqssh_tap_changers.duplicated('TransformerEnd', keep=False)].iterrows(): # self.logger.info(one_dup) # no example for testing found - eqssh_tap_changers.drop_duplicates(subset=['TransformerEnd'], inplace=True) + eqssh_tap_changers = eqssh_tap_changers.drop_duplicates(subset=['TransformerEnd']) # prepare the controllers eq_ssh_tap_controllers = self.cimConverter.merge_eq_ssh_profile('TapChangerControl') eq_ssh_tap_controllers = \ eq_ssh_tap_controllers[['rdfId', 'Terminal', 'discrete', 'enabled', 'targetValue', 'targetDeadband']] - eq_ssh_tap_controllers.rename(columns={'rdfId': 'TapChangerControl'}, inplace=True) + eq_ssh_tap_controllers = eq_ssh_tap_controllers.rename(columns={'rdfId': 'TapChangerControl'}) # first merge with the VoltageLimits eq_vl = self.cimConverter.cim['eq']['VoltageLimit'][['OperationalLimitSet', 'OperationalLimitType', 'value']] eq_vl = pd.merge(eq_vl, self.cimConverter.cim['eq']['OperationalLimitType'][['rdfId', 'limitType']].rename( @@ -359,35 +359,35 @@ def _prepare_power_transformers_cim16(self) -> pd.DataFrame: eq_vl = pd.merge(eq_vl_low, eq_vl_up, how='left', on='Terminal') eq_ssh_tap_controllers = pd.merge(eq_ssh_tap_controllers, eq_vl, how='left', on='Terminal') eq_ssh_tap_controllers['c_Terminal'] = eq_ssh_tap_controllers['Terminal'][:] - eq_ssh_tap_controllers.rename(columns={'Terminal': 'rdfId', 'enabled': 'c_in_service', - 'targetValue': 'c_vm_set_pu', 'targetDeadband': 'c_tol'}, inplace=True) + eq_ssh_tap_controllers = eq_ssh_tap_controllers.rename(columns={'Terminal': 'rdfId', 'enabled': 'c_in_service', + 'targetValue': 'c_vm_set_pu', 'targetDeadband': 'c_tol'}) # get the Terminal, ConnectivityNode and bus voltage eq_ssh_tap_controllers = \ pd.merge(eq_ssh_tap_controllers, pd.concat([self.cimConverter.cim['eq']['Terminal'], self.cimConverter.cim['eq_bd']['Terminal']], ignore_index=True, sort=False)[ ['rdfId', 'ConnectivityNode']], how='left', on='rdfId') - eq_ssh_tap_controllers.drop(columns=['rdfId'], inplace=True) - eq_ssh_tap_controllers.rename(columns={'ConnectivityNode': sc['o_id']}, inplace=True) + eq_ssh_tap_controllers = eq_ssh_tap_controllers.drop(columns=['rdfId']) + eq_ssh_tap_controllers = eq_ssh_tap_controllers.rename(columns={'ConnectivityNode': sc['o_id']}) eq_ssh_tap_controllers = pd.merge(eq_ssh_tap_controllers, self.cimConverter.net['bus'].reset_index(level=0)[ ['index', sc['o_id'], 'vn_kv']], how='left', on=sc['o_id']) - eq_ssh_tap_controllers.drop(columns=[sc['o_id']], inplace=True) - eq_ssh_tap_controllers.rename(columns={'index': 'c_bus_id'}, inplace=True) + eq_ssh_tap_controllers = eq_ssh_tap_controllers.drop(columns=[sc['o_id']]) + eq_ssh_tap_controllers = eq_ssh_tap_controllers.rename(columns={'index': 'c_bus_id'}) eq_ssh_tap_controllers['c_vm_set_pu'] = eq_ssh_tap_controllers['c_vm_set_pu'] / eq_ssh_tap_controllers['vn_kv'] eq_ssh_tap_controllers['c_tol'] = eq_ssh_tap_controllers['c_tol'] / eq_ssh_tap_controllers['vn_kv'] eq_ssh_tap_controllers['c_vm_lower_pu'] = \ eq_ssh_tap_controllers['c_vm_lower_pu'] / eq_ssh_tap_controllers['vn_kv'] eq_ssh_tap_controllers['c_vm_upper_pu'] = \ eq_ssh_tap_controllers['c_vm_upper_pu'] / eq_ssh_tap_controllers['vn_kv'] - eq_ssh_tap_controllers.drop(columns=['vn_kv'], inplace=True) + eq_ssh_tap_controllers = eq_ssh_tap_controllers.drop(columns=['vn_kv']) eqssh_tap_changers = pd.merge(eqssh_tap_changers, eq_ssh_tap_controllers, how='left', on='TapChangerControl') - eqssh_tap_changers.rename(columns={'TransformerEnd': sc['pte_id']}, inplace=True) + eqssh_tap_changers = eqssh_tap_changers.rename(columns={'TransformerEnd': sc['pte_id']}) - eq_power_transformers.rename(columns={'rdfId': 'PowerTransformer'}, inplace=True) - eq_power_transformer_ends.rename(columns={'rdfId': sc['pte_id']}, inplace=True) + eq_power_transformers = eq_power_transformers.rename(columns={'rdfId': 'PowerTransformer'}) + eq_power_transformer_ends = eq_power_transformer_ends.rename(columns={'rdfId': sc['pte_id']}) # add the PowerTransformerEnds eq_power_transformers = pd.merge(eq_power_transformers, eq_power_transformer_ends, how='left', on='PowerTransformer') @@ -419,10 +419,10 @@ def _prepare_trafos_cim16(self, power_trafo2w: pd.DataFrame) -> pd.DataFrame: fillna_list = ['neutralStep', 'lowStep', 'highStep', 'stepVoltageIncrement', 'stepPhaseShiftIncrement', 'step', sc['tc'], sc['tc_id']] for one_item in fillna_list: - power_trafo2w[one_item].fillna(power_trafo2w[one_item + '_lv'], inplace=True) + power_trafo2w[one_item] = power_trafo2w[one_item].fillna(power_trafo2w[one_item + '_lv']) del fillna_list, one_item # just keep one transformer - power_trafo2w.drop_duplicates(subset=['PowerTransformer'], keep='first', inplace=True) + power_trafo2w = power_trafo2w.drop_duplicates(subset=['PowerTransformer'], keep='first') power_trafo2w['pfe_kw'] = (power_trafo2w.g * power_trafo2w.ratedU ** 2 + power_trafo2w.g_lv * power_trafo2w.ratedU_lv ** 2) * 1000 @@ -489,13 +489,13 @@ def _prepare_trafos_cim16(self, power_trafo2w: pd.DataFrame) -> pd.DataFrame: power_trafo2w.loc[~power_trafo2w['grounded_lv'].astype('bool'), 'connectionKind_lv'].str.replace('n', '') power_trafo2w['vector_group'] = power_trafo2w.connectionKind + power_trafo2w.connectionKind_lv power_trafo2w.loc[power_trafo2w['vector_group'] == '', 'vector_group'] = None - power_trafo2w.rename(columns={ + power_trafo2w = power_trafo2w.rename(columns={ 'PowerTransformer': sc['o_id'], 'Terminal': sc['t_hv'], 'Terminal_lv': sc['t_lv'], sc['pte_id']: sc['pte_id_hv'], sc['pte_id'] + '_lv': sc['pte_id_lv'], 'index_bus': 'hv_bus', 'index_bus_lv': 'lv_bus', 'neutralStep': 'tap_neutral', 'lowStep': 'tap_min', 'highStep': 'tap_max', 'step': 'tap_pos', 'stepVoltageIncrement': 'tap_step_percent', 'stepPhaseShiftIncrement': 'tap_step_degree', 'isPartOfGeneratorUnit': 'power_station_unit', 'ratedU': 'vn_hv_kv', 'ratedU_lv': 'vn_lv_kv', - 'ratedS': 'sn_mva', 'xground': 'xn_ohm', 'grounded': 'oltc'}, inplace=True) + 'ratedS': 'sn_mva', 'xground': 'xn_ohm', 'grounded': 'oltc'}) return power_trafo2w def _prepare_trafo3w_cim16(self, power_trafo3w: pd.DataFrame) -> pd.DataFrame: @@ -524,11 +524,11 @@ def _prepare_trafo3w_cim16(self, power_trafo3w: pd.DataFrame) -> pd.DataFrame: fillna_list = ['neutralStep', 'lowStep', 'highStep', 'stepVoltageIncrement', 'stepPhaseShiftIncrement', 'step', sc['tc'], sc['tc_id']] for one_item in fillna_list: - power_trafo3w[one_item].fillna(power_trafo3w[one_item + '_mv'], inplace=True) - power_trafo3w[one_item].fillna(power_trafo3w[one_item + '_lv'], inplace=True) + power_trafo3w[one_item] = power_trafo3w[one_item].fillna(power_trafo3w[one_item + '_mv']) + power_trafo3w[one_item] = power_trafo3w[one_item].fillna(power_trafo3w[one_item + '_lv']) del fillna_list, one_item # just keep one transformer - power_trafo3w.drop_duplicates(subset=['PowerTransformer'], keep='first', inplace=True) + power_trafo3w = power_trafo3w.drop_duplicates(subset=['PowerTransformer'], keep='first') power_trafo3w['min_s_hvmv'] = power_trafo3w[["ratedS", "ratedS_mv"]].min(axis=1) power_trafo3w['min_s_mvlv'] = power_trafo3w[["ratedS_mv", "ratedS_lv"]].min(axis=1) diff --git a/pandapower/converter/cim/cim2pp/converter_classes/wards/equivalentInjectionsCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/wards/equivalentInjectionsCim16.py index 037205a60..7b9ee4225 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/wards/equivalentInjectionsCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/wards/equivalentInjectionsCim16.py @@ -38,14 +38,14 @@ def _prepare_equivalent_injections_cim16(self) -> pd.DataFrame: eq_base_voltages = pd.concat([self.cimConverter.cim['eq']['BaseVoltage'][['rdfId', 'nominalVoltage']], self.cimConverter.cim['eq_bd']['BaseVoltage'][['rdfId', 'nominalVoltage']]], sort=False) - eq_base_voltages.drop_duplicates(subset=['rdfId'], inplace=True) - eq_base_voltages.rename(columns={'rdfId': 'BaseVoltage'}, inplace=True) + eq_base_voltages = eq_base_voltages.drop_duplicates(subset=['rdfId']) + eq_base_voltages = eq_base_voltages.rename(columns={'rdfId': 'BaseVoltage'}) eqssh_ei = pd.merge(eqssh_ei, eq_base_voltages, how='left', on='BaseVoltage') eqssh_ei = pd.merge(eqssh_ei, self.cimConverter.bus_merge, how='left', on='rdfId') # maybe the BaseVoltage is not given, also get the nominalVoltage from the buses eqssh_ei = pd.merge(eqssh_ei, self.cimConverter.net.bus[['vn_kv']], how='left', left_on='index_bus', right_index=True) - eqssh_ei.nominalVoltage.fillna(eqssh_ei.vn_kv, inplace=True) + eqssh_ei.nominalVoltage = eqssh_ei.nominalVoltage.fillna(eqssh_ei.vn_kv) eqssh_ei['regulationStatus'].fillna(False, inplace=True) eqssh_ei['vm_pu'] = eqssh_ei.regulationTarget / eqssh_ei.nominalVoltage eqssh_ei.rename(columns={'rdfId_Terminal': sc['t'], 'rdfId': sc['o_id'], 'connected': 'in_service', diff --git a/pandapower/converter/cim/cim_classes.py b/pandapower/converter/cim/cim_classes.py index b8f8975a6..8d59c7091 100644 --- a/pandapower/converter/cim/cim_classes.py +++ b/pandapower/converter/cim/cim_classes.py @@ -96,7 +96,7 @@ def set_cim_data_types(self) -> CimParser: self.logger.debug("Setting data type of %s from CIM element %s as type %s" % (col, cim_element_type, data_type_col_str)) if col in default_values.keys(): # todo deprecated due to repair function? - self.cim[profile][cim_element_type][col].fillna(value=default_values[col], inplace=True) + self.cim[profile][cim_element_type][col] = self.cim[profile][cim_element_type][col].fillna(value=default_values[col]) if data_type_col == bool_type: self.cim[profile][cim_element_type][col] = \ self.cim[profile][cim_element_type][col].map(to_bool) @@ -519,7 +519,7 @@ def _parse_source_file(self, file: str, output: dict, encoding: str, profile_nam elif col_new.endswith('-ID'): col_new = 'rdfId' ns_dict[prf][element_type_c][col] = col_new - prf_content[element_type_c].rename(columns={**ns_dict[prf][element_type_c]}, inplace=True) + prf_content[element_type_c] = prf_content[element_type_c].rename(columns={**ns_dict[prf][element_type_c]}) if prf not in output.keys(): output[prf] = prf_content else: diff --git a/pandapower/converter/powerfactory/pp_import_functions.py b/pandapower/converter/powerfactory/pp_import_functions.py index eb3933979..0e541876c 100644 --- a/pandapower/converter/powerfactory/pp_import_functions.py +++ b/pandapower/converter/powerfactory/pp_import_functions.py @@ -1078,7 +1078,7 @@ def create_ext_net(net, item, pv_as_slack, is_unbalanced): except AttributeError: pass elm = 'ext_grid' - + get_pf_ext_grid_results(net, item, xid, is_unbalanced) # if item.HasResults(0): # 'm' results... @@ -1229,7 +1229,7 @@ def ask_load_params(item, pf_variable_p_loads, dict_net, variables): if pf_variable_p_loads == 'plini' else 1 if item.HasAttribute('zonefact'): params.scaling *= item.zonefact - + # p_mw = p_mw, q_mvar = q_mvar, scaling = scaling return params @@ -3017,4 +3017,4 @@ def remove_folder_of_std_types(net): continue for st in all_types: net.std_types[element][std_type] = net.std_types[element].pop(st) - net[element].std_type.replace(st, std_type, inplace=True) + net[element].std_type = net[element].std_type.replace(st, std_type) diff --git a/pandapower/converter/powerfactory/validate.py b/pandapower/converter/powerfactory/validate.py index e88b29ac3..e8353a676 100644 --- a/pandapower/converter/powerfactory/validate.py +++ b/pandapower/converter/powerfactory/validate.py @@ -272,7 +272,7 @@ def validate_pf_conversion(net, is_unbalanced=False, **kwargs): logger.info('pandapower net converged: %s' % net.converged) _set_pf_results(net, pf_results, is_unbalanced=is_unbalanced) - net.bus.name.fillna("", inplace=True) + net.bus.name = net.bus.name.fillna("") only_in_pandapower = np.union1d(net.bus[net.bus.name.str.endswith("_aux")].index, net.bus[net.bus.type == "ls"].index) in_both = np.setdiff1d(net.bus.index, only_in_pandapower) diff --git a/pandapower/create.py b/pandapower/create.py index 1a747210e..5737f2502 100644 --- a/pandapower/create.py +++ b/pandapower/create.py @@ -2689,7 +2689,7 @@ def create_transformer(net, hv_bus, lv_bus, std_type, name=None, tap_pos=nan, in _set_value_if_not_nan(net, index, xn_ohm, "xn_ohm", "trafo") # tap_phase_shifter default False - net.trafo.tap_phase_shifter.fillna(False, inplace=True) + net.trafo.tap_phase_shifter = net.trafo.tap_phase_shifter.fillna(False) if "tap2_phase_shifter" in net.trafo.columns: net.trafo.tap2_phase_shifter = net.trafo.tap2_phase_shifter.fillna(False).astype(bool_) diff --git a/pandapower/estimation/state_estimation.py b/pandapower/estimation/state_estimation.py index 26a322f77..d5a7d6fce 100644 --- a/pandapower/estimation/state_estimation.py +++ b/pandapower/estimation/state_estimation.py @@ -211,19 +211,19 @@ def estimate(self, v_start='flat', delta_start='flat', calculate_voltage_angles= **calculate_voltage_angles** - (boolean) - Take into account absolute voltage angles and phase shifts in transformers, if init is 'slack'. Default is True - + **zero_injection** - (str, iterable, None) - Defines which buses are zero injection bus or the method - to identify zero injection bus, with 'wls_estimator' virtual measurements will be added, with + to identify zero injection bus, with 'wls_estimator' virtual measurements will be added, with 'wls_estimator with zero constraints' the buses will be handled as constraints "auto": all bus without p,q measurement, without p, q value (load, sgen...) and aux buses will be - identified as zero injection bus + identified as zero injection bus "aux_bus": only aux bus will be identified as zero injection bus None: no bus will be identified as zero injection bus iterable: the iterable should contain index of the zero injection bus and also aux bus will be identified as zero-injection bus - **fuse_buses_with_bb_switch** - (str, iterable, None) - Defines how buses with closed bb switches should - be handled, if fuse buses will only fused to one for calculation, if not fuse, an auxiliary bus and + **fuse_buses_with_bb_switch** - (str, iterable, None) - Defines how buses with closed bb switches should + be handled, if fuse buses will only fused to one for calculation, if not fuse, an auxiliary bus and auxiliary line will be automatically added to the network to make the buses with different p,q injection measurements identifieble "all": all buses with bb-switches will be fused, the same as the default behaviour in load flow @@ -432,7 +432,7 @@ def perform_rn_max_test(self, v_in_out=None, delta_in_out=None, # Remove bad measurement: self.logger.debug("Removing measurement: %s" % self.net.measurement.loc[meas_idx].values[0]) - self.net.measurement.drop(meas_idx, inplace=True) + self.net.measurement = self.net.measurement.drop(meas_idx) self.logger.debug("Bad data removed from the set of measurements.") except np.linalg.linalg.LinAlgError: diff --git a/pandapower/estimation/util.py b/pandapower/estimation/util.py index a43f39b56..6d4f0f371 100644 --- a/pandapower/estimation/util.py +++ b/pandapower/estimation/util.py @@ -134,7 +134,7 @@ def reset_bb_switch_impedance(net): """ if "z_ohm_ori" in net.switch: net.switch["z_ohm"] = net.switch["z_ohm_ori"] - net.switch.drop("z_ohm_ori", axis=1, inplace=True) + net.switch = net.switch.drop("z_ohm_ori", axis=1) def add_virtual_meas_from_loadflow(net, v_std_dev=0.01, p_std_dev=0.03, q_std_dev=0.03, diff --git a/pandapower/grid_equivalents/auxiliary.py b/pandapower/grid_equivalents/auxiliary.py index 2b2877c8d..9e55a7d8b 100644 --- a/pandapower/grid_equivalents/auxiliary.py +++ b/pandapower/grid_equivalents/auxiliary.py @@ -157,7 +157,7 @@ def drop_internal_branch_elements(net, internal_buses, branch_elements=None): elif "trafo" in elm: pp.drop_trafos(net, idx_to_drop, table=elm) else: - net[elm].drop(idx_to_drop, inplace=True) + net[elm] = net[elm].drop(idx_to_drop) def calc_zpbn_parameters(net, boundary_buses, all_external_buses, slack_as="gen", @@ -285,14 +285,14 @@ def drop_assist_elms_by_creating_ext_net(net, elms=None): for elm in elms: target_elm_idx = net[elm].index[net[elm].name.astype(str).str.contains( "assist_"+elm, na=False, regex=False)] - net[elm].drop(target_elm_idx, inplace=True) + net[elm] = net[elm].drop(target_elm_idx) if net["res_"+elm].shape[0]: res_target_elm_idx = net["res_" + elm].index.intersection(target_elm_idx) - net["res_"+elm].drop(res_target_elm_idx, inplace=True) + net["res_"+elm] = net["res_"+elm].drop(res_target_elm_idx) if "name_equivalent" in net.bus.columns.tolist(): - net.bus.drop(columns=["name_equivalent"], inplace=True) + net.bus = net.bus.drop(columns=["name_equivalent"]) def build_ppc_and_Ybus(net): @@ -378,7 +378,7 @@ def match_controller_and_new_elements(net, net_org): net.controller.object[idx].__dict__["element_index"] = new_elm_idxs net.controller.object[idx].__dict__["matching_params"]["element_index"] = new_elm_idxs net.controller.object[idx].__dict__["profile_name"] = profile_name - net.controller.drop(tobe_removed, inplace=True) + net.controller = net.controller.drop(tobe_removed) # TODO: match the controllers in the external area def ensure_origin_id(net, no_start=0, elms=None): @@ -414,7 +414,7 @@ def drop_and_edit_cost_functions(net, buses, drop_cost, add_origin_id, idx]].values to_drop = net[cost_elm].index[net[cost_elm].bus.isin(buses) | net[cost_elm].bus.isnull()] - net[cost_elm].drop(to_drop, inplace=True) + net[cost_elm] = net[cost_elm].drop(to_drop) # add origin_id to cost df and corresponding elms if add_origin_id: @@ -439,13 +439,13 @@ def match_cost_functions_and_eq_net(net, boundary_buses, eq_type): for cost_elm in ["poly_cost", "pwl_cost"]: if len(net[cost_elm]): if "ward" not in eq_type: - net[cost_elm].sort_values(by=["origin_seq"], inplace=True) + net[cost_elm] = net[cost_elm].sort_values(by=["origin_seq"]) net[cost_elm].index = net[cost_elm]["origin_idx"].values for pc in net[cost_elm].itertuples(): new_idx = net[pc.et].index[ net[pc.et].origin_id == pc.et_origin_id].values net[cost_elm].element[pc.Index] = new_idx[0] - net[cost_elm].drop(columns=["bus", "et_origin_id", "origin_idx", "origin_seq"], inplace=True) + net[cost_elm] = net[cost_elm].drop(columns=["bus", "et_origin_id", "origin_idx", "origin_seq"]) def _check_network(net): @@ -555,8 +555,8 @@ def replace_motor_by_load(net, all_external_buses): p = p_mw if not np.isnan(net.res_bus.vm_pu[m.bus]) and m.in_service else 0.0 q = q_mvar if not np.isnan(net.res_bus.vm_pu[m.bus]) and m.in_service else 0.0 net.res_load.loc[li] = p, q - net.motor.drop(motors, inplace=True) - net.res_motor.drop(motors, inplace=True) + net.motor = net.motor.drop(motors) + net.res_motor = net.res_motor.drop(motors) if __name__ == "__main__": diff --git a/pandapower/grid_equivalents/get_equivalent.py b/pandapower/grid_equivalents/get_equivalent.py index 85cd7a68b..9803b785c 100644 --- a/pandapower/grid_equivalents/get_equivalent.py +++ b/pandapower/grid_equivalents/get_equivalent.py @@ -429,7 +429,7 @@ def drop_repeated_characteristic(net): repeated_idxs.append(m) else: idxs.append(idx) - net.characteristic.drop(repeated_idxs, inplace=True) + net.characteristic = net.characteristic.drop(repeated_idxs) def _determine_bus_groups(net, boundary_buses, internal_buses, @@ -583,8 +583,8 @@ def _get_buses_after_merge(net_eq, net_internal, bus_lookups, return_internal): net.gen.vm_pu[0] = 1.025 net.gen.vm_pu[1] = 1.025 - net.poly_cost.drop(net.poly_cost.index, inplace=True) - net.pwl_cost.drop(net.pwl_cost.index, inplace=True) + net.poly_cost = net.poly_cost.drop(net.poly_cost.index) + net.pwl_cost = net.pwl_cost.drop(net.pwl_cost.index) # pp.replace_gen_by_sgen(net) # net.sn_mva = 109.00 boundary_buses = [4, 8] diff --git a/pandapower/grid_equivalents/rei_generation.py b/pandapower/grid_equivalents/rei_generation.py index 5e5f4c3b6..47e907ee3 100644 --- a/pandapower/grid_equivalents/rei_generation.py +++ b/pandapower/grid_equivalents/rei_generation.py @@ -176,7 +176,7 @@ def _create_net_zpbn(net, boundary_buses, all_internal_buses, all_external_buses if not np.isnan(Z[elm+"_ground"].values).all(): if separate: - Z.drop([elm+"_integrated_total"], axis=1, inplace=True) + Z = Z.drop([elm+"_integrated_total"], axis=1) # add buses idxs = Z.index[~np.isnan(Z[elm+"_ground"].values)] @@ -215,7 +215,7 @@ def _create_net_zpbn(net, boundary_buses, all_internal_buses, all_external_buses g_buses += list(new_g_buses) t_buses += list(new_t_buses) else: - Z.drop([elm+"_separate_total"], axis=1, inplace=True) + Z = Z.drop([elm+"_separate_total"], axis=1) vn_kv = net_zpbn.bus.vn_kv[all_external_buses].values[0] new_g_bus = pp.create_bus(net_zpbn, vn_kv, name=elm+"_integrated-ground ") i_all_integrated = [] @@ -383,7 +383,7 @@ def _create_net_zpbn(net, boundary_buses, all_internal_buses, all_external_buses "aggregated " + elm + ". It is NOT correct at present.") df.element[pc_idx[0]] = net_zpbn[elm].index[net_zpbn[elm].name.str.contains( "integrated", na=False)][0] - df.drop(pc_idx[1:], inplace=True) + df = df.drop(pc_idx[1:]) elif len(pc_idx): related_bus = int(str(net_zpbn[elm].name[idx]).split("_")[-1]) pc_idx = df.index[(df.bus == related_bus) & @@ -398,7 +398,7 @@ def _create_net_zpbn(net, boundary_buses, all_internal_buses, all_external_buses pc_idx = df.index[(df.bus == related_bus) & (df.et == elm)] df.element[pc_idx[0]] = idx - df.drop(pc_idx[1:], inplace=True) + df = df.drop(pc_idx[1:]) elif len(pc_idx) == 1: df.element[pc_idx[0]] = idx net_zpbn[cost_elm] = df @@ -525,7 +525,7 @@ def _get_internal_and_external_nets(net, boundary_buses, all_internal_buses, net_external = deepcopy(net) if "group" in net_external: - net_external.group.drop(net_external.group.index, inplace=True) + net_external.group = net_external.group.drop(net_external.group.index) drop_and_edit_cost_functions(net_external, all_internal_buses, True, True) drop_measurements_and_controllers(net_external, net_external.bus.index.tolist()) @@ -625,7 +625,7 @@ def _replace_ext_area_by_impedances_and_shunts( # --- drop shunt elements attached to boundary buses traget_shunt_idx = net_eq.shunt.index[net_eq.shunt.bus.isin(bus_lookups[ "boundary_buses_inclusive_bswitch"])] - net_eq.shunt.drop(traget_shunt_idx, inplace=True) + net_eq.shunt = net_eq.shunt.drop(traget_shunt_idx) # --- create impedance not_very_low_imp = (impedance_params.rft_pu.abs() > imp_threshold) | ( @@ -645,7 +645,7 @@ def _replace_ext_area_by_impedances_and_shunts( # --- create switches instead of very low impedances new_sws = impedance_params[["from_bus", "to_bus"]].loc[~not_very_low_imp].astype(np.int64) - new_sws.rename(columns={"from_bus": "bus", "to_bus": "element"}, inplace=True) + new_sws = new_sws.rename(columns={"from_bus": "bus", "to_bus": "element"}) max_idx = net_eq.switch.index.max() if net_eq.switch.shape[0] else 0 new_sws.index = range(max_idx+1, max_idx+1+sum(~not_very_low_imp)) new_sws["et"] = "b" diff --git a/pandapower/grid_equivalents/ward_generation.py b/pandapower/grid_equivalents/ward_generation.py index 507e21cf9..2de8b9950 100644 --- a/pandapower/grid_equivalents/ward_generation.py +++ b/pandapower/grid_equivalents/ward_generation.py @@ -55,7 +55,7 @@ def _calculate_ward_and_impedance_parameters(Ybus_eq, bus_lookups, show_computin return ward_parameter, impedance_parameter -def _calculate_xward_and_impedance_parameters(net_external, Ybus_eq, bus_lookups, +def _calculate_xward_and_impedance_parameters(net_external, Ybus_eq, bus_lookups, show_computing_time, power_eq=0): """calculates the xwards and the equivalent impedance""" t_start = time.perf_counter() @@ -104,7 +104,7 @@ def create_passive_external_net_for_ward_admittance( # drops all power injections for elm in ["sgen", "gen", "load", "storage"]: target_idx = net[elm].index[net[elm].bus.isin(all_external_buses)] - net[elm].drop(target_idx, inplace=True) + net[elm] = net[elm].drop(target_idx) runpp_fct(net, calculate_voltage_angles=calc_volt_angles) @@ -123,7 +123,7 @@ def _replace_external_area_by_wards(net_external, bus_lookups, ward_parameter_no # --- drop shunt elements attached to boundary buses traget_shunt_idx = net_external.shunt.index[net_external.shunt.bus.isin(bus_lookups[ "boundary_buses_inclusive_bswitch"])] - net_external.shunt.drop(traget_shunt_idx, inplace=True) + net_external.shunt = net_external.shunt.drop(traget_shunt_idx) # --- creat impedance sn = net_external.sn_mva @@ -193,7 +193,7 @@ def _replace_external_area_by_wards(net_external, bus_lookups, ward_parameter_no def _replace_external_area_by_xwards(net_external, bus_lookups, xward_parameter_no_power, impedance_parameter, ext_buses_with_xward, - show_computing_time, calc_volt_angles=True, + show_computing_time, calc_volt_angles=True, runpp_fct=_runpp_except_voltage_angles): """replaces the external networks by xwards and equivalent impedance""" t_start = time.perf_counter() @@ -204,7 +204,7 @@ def _replace_external_area_by_xwards(net_external, bus_lookups, xward_parameter_ # --- drop shunt elements attached to boundary buses traget_shunt_idx = net_external.shunt.index[net_external.shunt.bus.isin(bus_lookups[ "boundary_buses_inclusive_bswitch"])] - net_external.shunt.drop(traget_shunt_idx, inplace=True) + net_external.shunt = net_external.shunt.drop(traget_shunt_idx) # --- creat impedance sn = net_external.sn_mva diff --git a/pandapower/groups.py b/pandapower/groups.py index c81970168..4f1739b0a 100644 --- a/pandapower/groups.py +++ b/pandapower/groups.py @@ -52,7 +52,7 @@ def drop_group(net, index): index : int index of the group which should be dropped """ - net.group.drop(index, inplace=True) + net.group = net.group.drop(index) def drop_group_and_elements(net, index): @@ -67,7 +67,7 @@ def drop_group_and_elements(net, index): res_et = "res_" + et if res_et in net.keys() and net[res_et].shape[0]: net[res_et].drop(net[res_et].index.intersection(idx), inplace=True) - net.group.drop(index, inplace=True) + net.group = net.group.drop(index) # ==================================== @@ -157,7 +157,7 @@ def attach_to_group(net, index, element_types, elements, reference_columns=None, temp_gr = create_group(net, [et], [elm], reference_columns=rc) set_group_reference_column(net, temp_gr, existing_rc, element_type=et) elm = net.group.element.at[temp_gr] - net.group.drop(temp_gr, inplace=True) + net.group = net.group.drop(temp_gr) else: raise UserWarning( f"The reference column of existing group {index} for element " @@ -870,7 +870,7 @@ def group_res_power_per_bus(net, index): pq_sum.index.name = "bus" # needs to be set for branch elements if len(pq_sums.columns.difference(pq_sum.columns)): cols_repl = {old: "p_mw" if "p" in old else "q_mvar" for old in pq_sum.columns} - pq_sum.rename(columns=cols_repl, inplace=True) + pq_sum = pq_sum.rename(columns=cols_repl) pq_sums = pq_sums.add(pq_sum, fill_value=0) if len(missing_res_idx): diff --git a/pandapower/io_utils.py b/pandapower/io_utils.py index 8ac2d4b16..c61ea0eb9 100644 --- a/pandapower/io_utils.py +++ b/pandapower/io_utils.py @@ -230,7 +230,7 @@ def from_dict_of_dfs(dodfs, net=None): net[c] = '' continue elif item in ["line_geodata", "bus_geodata"]: - table.rename_axis(net[item].index.name, inplace=True) + table = table.rename_axis(net[item].index.name) df_to_coords(net, item, table) elif item.endswith("_std_types"): # when loaded from Excel, the lists in the DataFrame cells are strings -> we want to convert them back @@ -243,7 +243,7 @@ def from_dict_of_dfs(dodfs, net=None): elif item.endswith("_profiles"): if "profiles" not in net.keys(): net["profiles"] = dict() - table.rename_axis(None, inplace=True) + table = table.rename_axis(None) net["profiles"][item[:-9]] = table continue # don't go into try..except elif item == "user_pf_options": @@ -255,7 +255,7 @@ def from_dict_of_dfs(dodfs, net=None): table[json_column] = table[json_column].apply( lambda x: json.loads(x, cls=PPJSONDecoder)) if not isinstance(table.index, pd.MultiIndex): - table.rename_axis(net[item].index.name, inplace=True) + table = table.rename_axis(net[item].index.name) net[item] = table # set the index to be Int try: diff --git a/pandapower/networks/power_system_test_cases.py b/pandapower/networks/power_system_test_cases.py index 60611a652..1469b23a8 100644 --- a/pandapower/networks/power_system_test_cases.py +++ b/pandapower/networks/power_system_test_cases.py @@ -39,7 +39,7 @@ def _change_ref_bus(net, ref_bus_idx, ext_grid_p=0): j = 0 for i in ext_grid_idx: ext_grid_data = net.ext_grid.loc[i] - net.ext_grid.drop(i, inplace=True) + net.ext_grid = net.ext_grid.drop(i) pp.create_gen(net, ext_grid_data.bus, ext_grid_p[j], vm_pu=ext_grid_data.vm_pu, controllable=True, min_q_mvar=ext_grid_data.min_q_mvar, max_q_mvar=ext_grid_data.max_q_mvar, @@ -48,7 +48,7 @@ def _change_ref_bus(net, ref_bus_idx, ext_grid_p=0): # old gen at ref_bus -> ext_grid (and sgen) for i in gen_idx: gen_data = net.gen.loc[i] - net.gen.drop(i, inplace=True) + net.gen = net.gen.drop(i) if gen_data.bus not in net.ext_grid.bus.values: pp.create_ext_grid(net, gen_data.bus, vm_pu=gen_data.vm_pu, va_degree=0., min_q_mvar=gen_data.min_q_mvar, max_q_mvar=gen_data.max_q_mvar, diff --git a/pandapower/opf/validate_opf_input.py b/pandapower/opf/validate_opf_input.py index fa710311e..60552992c 100644 --- a/pandapower/opf/validate_opf_input.py +++ b/pandapower/opf/validate_opf_input.py @@ -22,8 +22,8 @@ def _check_necessary_opf_parameters(net, logger): else: if "controllable" in net[element_type].columns: if element_type == 'gen': - net[element_type].controllable.fillna(True, inplace=True) - else: # 'sgen', 'load', 'storage' + net[element_type].controllable = net[element_type].controllable.fillna(True) + net[element_type].controllable = net[element_type].controllable.fillna(True net[element_type].controllable.fillna(False, inplace=True) controllables = net[element_type].index[net[element_type].controllable.astype( bool)] diff --git a/pandapower/plotting/generic_geodata.py b/pandapower/plotting/generic_geodata.py index ecb07c6a3..1508b7986 100644 --- a/pandapower/plotting/generic_geodata.py +++ b/pandapower/plotting/generic_geodata.py @@ -219,7 +219,7 @@ def create_generic_coordinates(net, mg=None, library="igraph", def _prepare_geodata_table(net, geodata_table, overwrite): if geodata_table in net and net[geodata_table].shape[0]: if overwrite: - net[geodata_table].drop(net[geodata_table].index, inplace=True) + net[geodata_table] = net[geodata_table].drop(net[geodata_table].index) else: raise UserWarning("Table %s is not empty - use overwrite=True to overwrite existing geodata"%geodata_table) diff --git a/pandapower/protection/oc_relay_model.py b/pandapower/protection/oc_relay_model.py index 870a140cc..73a70183c 100644 --- a/pandapower/protection/oc_relay_model.py +++ b/pandapower/protection/oc_relay_model.py @@ -9,7 +9,7 @@ import pandas as pd import warnings from math import isnan,nan -warnings.filterwarnings('ignore') +warnings.filterwarnings('ignore') from pandapower.protection.utility_functions import create_sc_bus,bus_path_multiple_ext_bus,get_line_path,get_line_idx,get_bus_idx,\ parallel_lines,plot_tripped_grid, create_I_t_plot @@ -17,78 +17,78 @@ # set the oc parameters def oc_parameters(net,relay_type, time_settings,sc_fraction=0.95, overload_factor=1.2, ct_current_factor=1.25, - safety_factor=1,inverse_overload_factor=1.2, pickup_current_manual=None, **kwargs): + safety_factor=1,inverse_overload_factor=1.2, pickup_current_manual=None, **kwargs): """ The main function is to create relay settings with oc parameters. - + INPUT: **net** (pandapowerNet) - Pandapower network and net.switch.type need to be specified as - + - 'CB_DTOC' (for using Definite Time Over Current Relay) - 'CB_IDMT' (Inverse Definite Minimum Time over current relay) - 'CB_IDTOC' (Inverse Definite Minimum Time over current relay - - **relay_type** (string)- oc relay type need to be specifiied either as - + + **relay_type** (string)- oc relay type need to be specifiied either as + - DTOC: Definite Time Over Current Relay - IDMT: Inverse Definite Minimum Time over current relay - IDTOC: Inverse Definite Time Minimum over current relay (combination of DTOC and IDMT) - - - **time_settings** (list or DataFrame) - Relay tripping time can be given as a list or a DataFrame - + + + **time_settings** (list or DataFrame) - Relay tripping time can be given as a list or a DataFrame + If given as a list, the time grading will be calculated based on topological grid search, and manual tripping time can be provided as a dataframe by respecting the column names. - + For DTOC: time_settings =[t>>, t>, t_diff] or Dataframe columns as 'switch_id', 't_gg', 't_g' - + - t>> (t_gg): instantaneous tripping time in seconds - t> (t_g): primary backup tripping time in seconds, - t_diff: time grading delay difference in seconds - - + + For IDMT: time_settings =[tms, t_delta] or Dataframe columns as 'switch_id', 'tms', 't_grade' - + - tms: time multiplier settings in seconds - - t_grade: time grading delay difference in seconds - + - t_grade: time grading delay difference in seconds + For IDTOC: time_settings =[t>>, t>, t_diff, tms,t_grade] or Dataframe columns as 'switch_id', 't_gg', 't_g','tms', 't_grade' - + - t>> (t_gg): instantaneous tripping time in seconds - t> (t_g): primary backup tripping time in seconds, - t_diff: time grading delay difference in seconds - tms: time multiplier settings in seconds - - t_grade: time grading delay difference in seconds + - t_grade: time grading delay difference in seconds + - **sc_fraction** (float, 0.95) - Maximum possible extent to which the short circuit can be created on the line - + **overload_factor** - (float, 1.25)- Allowable overloading on the line used to calculate the pick-up current - + **ct_current_factor** -(float, 1.2) - Current multiplication factor to calculate the pick-up current - + **safety_factor** -(float, 1) - Safety limit for the instantaneous pick-up current - + **inverse_overload_factor** -(float, 1.2)- Allowable inverse overloading to define the pick-up current in IDMT relay - - + + OPTIONAL: **pickup_current_manual** - (DataFrame, None) - User-defined relay trip currents can be given as a dataframe. - + DTOC: Dataframe with columns as 'switch_id', 'I_gg', 'I_g' - + IDMT: Dataframe with columns as 'switch_id', 'I_s' - + IDTOC: Dataframe with columns as 'switch_id', 'I_gg', 'I_g', 'I_s' KWARGS: **curve_type**- (String) - Relay trip time will vary depending on the curve slope for inverse Time Relays. The curve is used to coordinate with other protective devices for selectivity (according to IEC60255) - + Curve type can be : - + - 'standard_inverse' - 'very_inverse', - 'extremely_inverse', @@ -96,7 +96,7 @@ def oc_parameters(net,relay_type, time_settings,sc_fraction=0.95, overload_facto OUTPUT: **return** (DataFrame, float) - Return relay setting as a dataframe with required parameters for oc relay (DTOC, IDMT, IDTOC) """ - + oc_relay_settings= pd.DataFrame(columns = ["switch_id","line_id","bus_id","relay_type", "curve_type","I_g[kA]","I_gg[kA]","I_s[kA]", "t_g[s]","t_gg[s]", "tms[s]",'t_grade[s]' "alpha","k"]) for switch_id in net.switch.index: @@ -110,14 +110,14 @@ def oc_parameters(net,relay_type, time_settings,sc_fraction=0.95, overload_facto sc.calc_sc(net_sc, bus=max(net_sc.bus.index), branch_results=True) if (net.switch.type.at[switch_id] == "CB_DTOC") and relay_type=='DTOC': # Definite Time Over Current relay - + if pickup_current_manual is None: I_g = net_sc.line.max_i_ka.at[line_idx] * overload_factor * ct_current_factor I_gg = net_sc.res_line_sc.ikss_ka.at[line_idx] * safety_factor else: I_g= pickup_current_manual.I_g.at[switch_id] # take manual inputs I_gg=pickup_current_manual.I_gg.at[switch_id] - + df_protection_settings =time_grading(net,time_settings) t_gg=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_gg'].item() t_g=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_g'].item() @@ -125,8 +125,8 @@ def oc_parameters(net,relay_type, time_settings,sc_fraction=0.95, overload_facto t_grade=tms=alpha=k=I_s=float("NaN") if (net.switch.type.at[switch_id] == "CB_IDMT") and relay_type=='IDMT': - - # Inverse over current relay according to IEC 60255-3/BS142 + + # Inverse over current relay according to IEC 60255-3/BS142 if pickup_current_manual is None: I_s=net_sc.line.max_i_ka.at[line_idx]*inverse_overload_factor else: @@ -145,20 +145,20 @@ def oc_parameters(net,relay_type, time_settings,sc_fraction=0.95, overload_facto if kwargs['curve_type']=='long_inverse': k=120; alpha=1 - + curve_type=kwargs['curve_type'] time_grading(net,time_settings) - + df_protection_settings =time_grading(net,time_settings) t_grade=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_g'].item() tms=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_gg'].item() #tms= t_grade I_g=I_gg=t_g=t_gg=float("NaN") - - + + if (net.switch.type.at[switch_id] == "CB_IDTOC") and relay_type=='IDTOC' : # Inverse Definite Time relay - + if pickup_current_manual is None: I_g = net_sc.line.max_i_ka.at[line_idx] * overload_factor * ct_current_factor I_gg = net_sc.res_line_sc.ikss_ka.at[line_idx] * safety_factor @@ -167,19 +167,19 @@ def oc_parameters(net,relay_type, time_settings,sc_fraction=0.95, overload_facto I_g= pickup_current_manual.I_g.at[switch_id] # take manual inputs I_gg=pickup_current_manual.I_gg.at[switch_id] I_s= pickup_current_manual.I_s.at[switch_id] - + if len(time_settings)!=5: assert "length of time_setting for DTOC is a list of order 5 with t_gg,t_g,t_diff, tms,t_grade" - + if isinstance(time_settings, list): df_protection_settings =time_grading(net,[time_settings[0], time_settings[1], time_settings[2]]) t_gg=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_gg'].item() t_g=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_g'].item() - + df_protection_settings =time_grading(net,[time_settings[3], time_settings[4]]) tms=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_gg'].item() t_grade=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_g'].item() - + if isinstance(time_settings, pd.DataFrame): df_protection_settings =time_grading(net,time_settings) t_gg=df_protection_settings.loc[df_protection_settings['switch_id']==switch_id]['t_gg'].item() @@ -201,11 +201,11 @@ def oc_parameters(net,relay_type, time_settings,sc_fraction=0.95, overload_facto k=120; alpha=1 curve_type=kwargs['curve_type'] - + settings = pd.DataFrame([{"switch_id": switch_id, "line_id": line_idx, "bus_id": bus_idx,"relay_type":relay_type, "curve_type":curve_type,"I_g[kA]": I_g, "I_gg[kA]": I_gg, "I_s[kA]":I_s, "t_g[s]": t_g, "t_gg[s]": t_gg, "tms[s]":tms, "t_grade[s]":t_grade, "alpha":alpha,"k":k}]) - + oc_relay_settings = pd.concat([oc_relay_settings,settings],ignore_index=True) - oc_relay_settings.dropna(how='all', axis=1, inplace=True) + oc_relay_settings = oc_relay_settings.dropna(how='all', axis=1) return oc_relay_settings @@ -227,25 +227,25 @@ def oc_get_trip_decision(net, settings, i_ka): t_gg = settings["t_gg[s]"] relay_type=settings["relay_type"] t=I_s=nan - + if i_ka > max_igg: trip = True trip_type = "instantaneous" trip_time = t_gg - + elif i_ka > max_ig: trip = True trip_type = "backup" - trip_time = t_g - + trip_time = t_g + else: trip = False trip_type = "no trip" trip_time = np.inf - + if settings["relay_type"] == "IDMT": - + I_s=settings["I_s[kA]"] k=settings["k"] alpha=settings["k"] @@ -255,26 +255,26 @@ def oc_get_trip_decision(net, settings, i_ka): tms=settings["tms[s]"] t=(tms*k)/(((i_ka/I_s)**alpha)-1)+t_grade max_ig=max_igg=t_g=t_gg=nan - + if i_ka > I_s: trip = True trip_type = "instantaneous" trip_time = t - + else: trip = False trip_type = "no trip" trip_time = np.inf - # combination of DTOC and IDMT + # combination of DTOC and IDMT if settings["relay_type"] == "IDTOC": max_ig = settings["I_g[kA]"] max_igg = settings["I_gg[kA]"] t_g = settings["t_g[s]"] t_gg = settings["t_gg[s]"] t_grade=settings["t_grade[s]"] - - + + tms=settings["tms[s]"] I_s=settings["I_s[kA]"] k=settings["k"] @@ -287,12 +287,12 @@ def oc_get_trip_decision(net, settings, i_ka): trip = True trip_type = "instantaneous" trip_time = t_gg - + elif i_ka > max_ig: trip = True trip_type = "backup" - trip_time = t_g - + trip_time = t_g + elif i_ka > I_s: trip = True trip_type = "inverse instantaneous" @@ -311,179 +311,179 @@ def oc_get_trip_decision(net, settings, i_ka): return trip_decision # Time graded protection (backup) for over current relay - + # Get the bus path from all the ext grids def time_grading(net,time_settings): - + # Automated time grading calculation if isinstance(time_settings,list): if len(time_settings)==3: time_settings=time_settings if len(time_settings)==2: time_settings=[time_settings[0], time_settings[1], time_settings[1]] - + # Get the bus path to each lines from all the ext buses bus_paths=bus_path_multiple_ext_bus(net) - + # Get all the line paths - line_paths=[] + line_paths=[] # get sorted line path (last is the longest line path) for bus_path in bus_paths: line=get_line_path(net, bus_path) line_paths.append(line) sorted_line_path = sorted(line_paths, key=len) - - #assign tg based on longest line path + + #assign tg based on longest line path line_length_time={} for line_length in range(0,len(sorted_line_path[-1])) : - + distance_counter=len(sorted_line_path[-1])- line_length t_g=time_settings[1] + (line_length)* time_settings[2] line_length_time[ distance_counter]=t_g - - + + # line_time gets line id and time line_time={} for line in sorted_line_path: line_length=len(line) - for length in line_length_time: + for length in line_length_time: if line_length==length: line_time[line[-1]]=line_length_time[length] parallel_line=parallel_lines(net) - - # find the missing lines in line time (due to parallel lines) - missing_line=[] + + # find the missing lines in line time (due to parallel lines) + missing_line=[] for line in net.line.index: - + linecheck = [] for key in line_time: - + if line == key: linecheck.append(True) else: linecheck.append(False) - + if any(linecheck): - + pass else: missing_line.append(line) - - + + # assign time to parallel line from the original time of line - + for parallel in parallel_line: - + for line in missing_line: - + if parallel[0]==line: - + if parallel[1] not in line_time: pass - + else: line_time[line]=line_time[parallel[1]] - + if parallel[1]==line: - + if parallel[0] not in line_time: pass - + else: line_time[line]=line_time[parallel[0]] - - - # Assign time setting to switches + + + # Assign time setting to switches time_switches={} - tg_sw_setting=[] + tg_sw_setting=[] for switch in net.switch[net.switch.closed == True].index: line_id=net.switch[net.switch.closed == True].element.at[switch] - - tg = line_time[line_id] + + tg = line_time[line_id] time_switches[switch]=tg tgg=time_settings[0] tg_sw_setting.append([switch,tg,tgg]) - + # if there is multiple time setting for each switch take only the highest time protection_time_settings = pd.DataFrame(tg_sw_setting) protection_time_settings.columns=["switch_id","t_g","t_gg"] protection_time_settings= protection_time_settings.sort_values(by=['switch_id']) protection_time_settings=protection_time_settings.reset_index(drop=True) - + # Manual time grading settings if isinstance(time_settings, pd.DataFrame): protection_time_settings=pd.DataFrame(columns = ["switch_id","t_gg","t_g"]) - + if time_settings.columns.values.tolist()==['switch_id', 't_gg', 't_g']: protection_time_settings['switch_id']=time_settings['switch_id'] protection_time_settings['t_g']=time_settings['t_g'] protection_time_settings['t_gg']=time_settings['t_gg'] - + if time_settings.columns.values.tolist()==['switch_id', 'tms', 't_grade']: protection_time_settings['switch_id']=time_settings['switch_id'] protection_time_settings['t_g']=time_settings['t_grade'] protection_time_settings['t_gg']=time_settings['tms'] - + if time_settings.columns.values.tolist()==['switch_id', 't_gg', 't_gg', 'tms','t_grade']: protection_time_settings['switch_id']=time_settings['switch_id'] protection_time_settings['t_g']=time_settings['t_g'] protection_time_settings['t_gg']=time_settings['t_gg'] protection_time_settings['t_grade']=time_settings['t_grade'] protection_time_settings['tms']=time_settings['tms'] - + return protection_time_settings - + def run_fault_scenario_oc(net, sc_line_id, sc_location,relay_settings): """ The main function is to create fault scenarios in the network at the defined location to get the tripping decisions. - + INPUT: **net** (pandapowerNet) - Pandapower network - + **sc_line_id** (int, index)- Index of the line to create the short circuit - - **sc_location** (float)- The short circuit location on the given line id (between 0 and 1). - + + **sc_location** (float)- The short circuit location on the given line id (between 0 and 1). + **relay_settings** (Dataframe, float)- Relay setting given as a dataframe returned from oc parameters (manual relay settings given as dataframe by respecting the column names) - + - DTOC: - + Dataframe with columns as 'switch_id', 'line_id', 'bus_id', 'relay_type', 'I_g[kA]', 'I_gg[kA]', 't_g[s]', 't_gg[s]' - + - IDMT: - + Dataframe with columns as 'switch_id', 'line_id', 'bus_id', 'relay_type', 'curve_type', I_s[kA], 'tms[s]', 't_grade[s], 'k', 'alpha' - + - k and alpha are the curve constants according to IEC-60255 - + - IDTOC: - + Dataframe with columns as 'switch_id', 'line_id', 'bus_id', 'relay_type', 'I_g[kA]', 'I_gg[kA]', 'I_s[kA], 't_g[s]', 't_gg[s]', 'tms[s], 't_grade[s], 'k', 'alpha' - + OUTPUT: **return** (list(Dict),net_sc) - Return trip decision of each relay and short circuit net """ - + net_sc = create_sc_bus(net, sc_line_id, sc_location) sc.calc_sc(net_sc, bus=max(net_sc.bus.index), branch_results=True) trip_decisions = [] - + for index, settings in relay_settings.iterrows(): - + i_ka = oc_get_measurement_at_relay_location(net_sc, settings) - + trip_decision = oc_get_trip_decision(net_sc, settings, i_ka) trip_decisions.append(trip_decision) - + df_trip_decison = pd.DataFrame.from_dict(trip_decisions) df_decisions=df_trip_decison[["Switch ID","Switch type","Trip type","Trip","Fault Current [kA]","Trip time [s]"]] - + print(df_decisions) - - return trip_decisions, net_sc + + return trip_decisions, net_sc diff --git a/pandapower/sql_io.py b/pandapower/sql_io.py index ae1ba1c51..1d0a24da7 100644 --- a/pandapower/sql_io.py +++ b/pandapower/sql_io.py @@ -87,10 +87,10 @@ def download_sql_table(cursor, table_name, **id_columns): colnames = [desc[0] for desc in cursor.description] table = cursor.fetchall() df = pd.DataFrame(table, columns=colnames) - df.fillna(np.nan, inplace=True) + df = df.fillna(np.nan) index_name = f"{table_name.split('.')[-1]}_id" if index_name in df.columns: - df.set_index(index_name, inplace=True) + df = df.set_index(index_name) if len(id_columns) > 0: df.drop(id_columns.keys(), axis=1, inplace=True) return df diff --git a/pandapower/test/api/test_diagnostic.py b/pandapower/test/api/test_diagnostic.py index 76f60216b..0ae332108 100644 --- a/pandapower/test/api/test_diagnostic.py +++ b/pandapower/test/api/test_diagnostic.py @@ -561,7 +561,7 @@ def test_impedance_values_close_to_zero(test_net, diag_params, diag_errors, repo net.line.at[4, "length_km"] = 0 net.line.at[4, "r_ohm_per_km"] = 0 net.line.at[4, "x_ohm_per_km"] = 0 - net.xward.drop(net.xward.index, inplace=True) + net.xward = net.xward.drop(net.xward.index) check_result = pp.impedance_values_close_to_zero(net, diag_params['min_r_ohm'], diag_params['min_x_ohm'], diag_params['min_r_pu'], diag_params['min_x_pu']) if check_result: @@ -624,7 +624,7 @@ def test_impedance_values_close_to_zero(test_net, diag_params, diag_errors, repo # impedance test net = copy.deepcopy(test_net) - net.xward.drop(net.xward.index, inplace=True) + net.xward = net.xward.drop(net.xward.index) net.impedance.rft_pu = 0 net.impedance.xft_pu = 0 net.impedance.rtf_pu = 0 @@ -649,7 +649,7 @@ def test_impedance_values_close_to_zero(test_net, diag_params, diag_errors, repo assert report_check net = copy.deepcopy(test_net) - net.xward.drop(net.xward.index, inplace=True) + net.xward = net.xward.drop(net.xward.index) net.impedance.rft_pu = 1 net.impedance.xft_pu = 1 net.impedance.rtf_pu = 1 diff --git a/pandapower/test/api/test_file_io.py b/pandapower/test/api/test_file_io.py index 0ec16cc58..8e16be0a3 100644 --- a/pandapower/test/api/test_file_io.py +++ b/pandapower/test/api/test_file_io.py @@ -315,7 +315,7 @@ def test_convert_format_for_pp_objects(net_in): # needed to trigger conversion net_in.format_version = "2.1.0" - net_in.controller.rename(columns={'object': 'controller'}, inplace=True) + net_in.controller = net_in.controller.rename(columns={'object': 'controller'}) assert 'controller' in net_in.controller.columns s = json.dumps(net_in, cls=PPJSONEncoder) @@ -597,7 +597,7 @@ def test_json_list_of_stuff(): def test_multi_index(): df = pd.DataFrame(columns=["a", "b", "c"], dtype=np.int64) - df.set_index(["a", "b"], inplace=True) + df = df.set_index(["a", "b"]) df2 = pp.from_json_string(pp.to_json(df)) assert_frame_equal(df, df2) diff --git a/pandapower/test/contingency/test_contingency.py b/pandapower/test/contingency/test_contingency.py index a29022f00..5a3306902 100644 --- a/pandapower/test/contingency/test_contingency.py +++ b/pandapower/test/contingency/test_contingency.py @@ -377,7 +377,7 @@ def get_net(request): max_loading_percent=net.trafo.max_loading_percent.values) if len(net.trafo) > 0: for col in ("tap_neutral", "tap_step_percent", "tap_pos", "tap_step_degree"): - net.trafo[col].fillna(0, inplace=True) + net.trafo[col] = net.trafo[col].fillna(0) _randomize_indices(net) diff --git a/pandapower/test/estimation/test_wls_estimation.py b/pandapower/test/estimation/test_wls_estimation.py index 8d5a7a399..331b1933e 100644 --- a/pandapower/test/estimation/test_wls_estimation.py +++ b/pandapower/test/estimation/test_wls_estimation.py @@ -80,7 +80,7 @@ def test_3bus(): diff_v = target_v - v_result target_delta = np.array([0., 0.8677, 3.1381]) diff_delta = target_delta - delta_result - + if not (np.nanmax(abs(diff_v)) < 1e-4) or\ not (np.nanmax(abs(diff_delta)) < 1e-4): raise AssertionError("Estimation failed!") @@ -257,7 +257,7 @@ def test_3bus_with_transformer(): raise AssertionError("Estimation failed!") # Backwards check. Use state estimation results for power flow and check for equality - net.load.drop(net.load.index, inplace=True) + net.load = net.load.drop(net.load.index) net.ext_grid.vm_pu = net.res_bus_est.vm_pu.iloc[net.ext_grid.bus.iloc[0]] pp.create_load(net, 0, net.res_bus_est.p_mw.iloc[0], net.res_bus_est.q_mvar.iloc[0]) pp.create_load(net, 1, net.res_bus_est.p_mw.iloc[1], net.res_bus_est.q_mvar.iloc[1]) @@ -311,7 +311,7 @@ def test_3bus_with_2_slacks(): def test_3bus_with_i_line_measurements(): np.random.seed(1) net = load_3bus_network() - net.measurement.drop(net.measurement.index, inplace=True) + net.measurement = net.measurement.drop(net.measurement.index) pp.create_load(net, 1, p_mw=0.495974966, q_mvar=0.297749528) pp.create_load(net, 2, p_mw=1.514220983, q_mvar=0.787528929) pp.runpp(net) @@ -344,7 +344,7 @@ def test_3bus_with_i_line_measurements(): def test_3bus_with_pq_line_from_to_measurements(): np.random.seed(2017) net = load_3bus_network() - net.measurement.drop(net.measurement.index, inplace=True) + net.measurement = net.measurement.drop(net.measurement.index) pp.create_load(net, 1, p_mw=0.495974966, q_mvar=0.297749528) pp.create_load(net, 2, p_mw=1.514220983, q_mvar=0.787528929) pp.runpp(net) @@ -377,7 +377,7 @@ def test_3bus_with_pq_line_from_to_measurements(): def test_3bus_with_side_names(): np.random.seed(2017) net = load_3bus_network() - net.measurement.drop(net.measurement.index, inplace=True) + net.measurement = net.measurement.drop(net.measurement.index) pp.create_load(net, 1, p_mw=0.495974966, q_mvar=0.297749528) pp.create_load(net, 2, p_mw=1.514220983, q_mvar=0.787528929) pp.runpp(net) @@ -500,7 +500,7 @@ def test_init_slack_with_multiple_transformers(angles=True): "tap_side": "hv", "tap_neutral": 0, "tap_min": -9, "tap_max": 9, "tap_step_degree": 0, "tap_step_percent": 1.5, "tap_phase_shifter": False}, "63 MVA 110/10 kV v1.4.3 and older", element="trafo") - + pp.create_transformer(net, 3, 7, std_type="63 MVA 110/10 kV v1.4.3 and older", in_service=False) pp.create_transformer(net, 3, 4, std_type="63 MVA 110/10 kV v1.4.3 and older") pp.create_transformer(net, 0, 1, std_type="100 MVA 220/110 kV") @@ -609,7 +609,7 @@ def test_network_with_trafo3w_pq(): if not (np.nanmax(np.abs(net.res_bus.vm_pu.values - net.res_bus_est.vm_pu.values)) < 0.006) or\ not (np.nanmax(np.abs(net.res_bus.va_degree.values- net.res_bus_est.va_degree.values)) < 0.006): raise AssertionError("Estimation failed") - + #Try estimate with results initialization if not estimate(net, init="results"): raise AssertionError("Estimation failed!") @@ -667,7 +667,7 @@ def create_net_with_bb_switch(): bus3 = pp.create_bus(net, name="bus3", vn_kv=10.) bus4 = pp.create_bus(net, name="bus4", vn_kv=10.) bus5 = pp.create_bus(net, name="bus5", vn_kv=110.) - + pp.create_line_from_parameters(net, bus1, bus2, 10, r_ohm_per_km=.59, x_ohm_per_km=.35, c_nf_per_km=10.1, max_i_ka=1) pp.create_transformer(net, bus5, bus1, std_type="40 MVA 110/10 kV") @@ -705,7 +705,7 @@ def create_net_with_bb_switch(): pp.create_measurement(net, "p", "trafo", r2(net.res_trafo.p_hv_mw.iloc[0], .001), .01, side="hv", element=0) pp.create_measurement(net, "q", "trafo", r2(net.res_trafo.q_hv_mvar.iloc[0], .001), .01, - side="hv", element=0) + side="hv", element=0) return net @@ -757,7 +757,7 @@ def test_net_with_zero_injection(): b2 = pp.create_bus(net, name="Bus 2", vn_kv=220, index=2) b3 = pp.create_bus(net, name="Bus 3", vn_kv=220, index=3) b4 = pp.create_bus(net, name="Bus 4", vn_kv=220, index=4) - + pp.create_ext_grid(net, b1) # set the slack bus to bus 1 factor = 48.4 * 2 * np.pi * 50 * 1e-9 # capacity factor @@ -767,7 +767,7 @@ def test_net_with_zero_injection(): x_ohm_per_km=.242*48.4, c_nf_per_km=0.00384/factor, max_i_ka=1) l3 = pp.create_line_from_parameters(net, 2, 4, 1, r_ohm_per_km=.002*48.4, x_ohm_per_km=.0111*48.4, c_nf_per_km=0.00018/factor, max_i_ka=1) - + pp.create_measurement(net, "v", "bus", 1.063548, .001, b1) # V at bus 1 pp.create_measurement(net, "v", "bus", 1.068342, .001, b3) # V at bus 3 pp.create_measurement(net, "v", "bus", 1.069861, .001, b4) # V at bus 4 @@ -832,15 +832,15 @@ def test_zero_injection_aux_bus(): pp.create_measurement(net, "q", "line", r2(net.res_line.q_from_mvar.iloc[0], .002), .002, 0, side='from') pp.create_measurement(net, "p", "trafo", r2(net.res_trafo.p_hv_mw.iloc[0], .001), .01, - side="hv", element=0) + side="hv", element=0) pp.create_measurement(net, "q", "trafo", r2(net.res_trafo.q_hv_mvar.iloc[0], .001), .01, - side="hv", element=0) - + side="hv", element=0) + net_auto = deepcopy(net) net_aux = deepcopy(net) - + success_none = estimate(net, tolerance=1e-5, zero_injection=None) - + # In this case zero_injection in mode "aux_bus" and "auto" should be exact the same success_aux = estimate(net_aux, tolerance=1e-5, zero_injection='aux_bus') success_auto = estimate(net_auto, tolerance=1e-5, zero_injection='auto') @@ -878,7 +878,7 @@ def test_net_unobserved_island(): pp.create_measurement(net, "p", "bus", r2(net.res_bus.p_mw.iloc[bus4], .002), .002, element=bus4) pp.create_measurement(net, "q", "bus", r2(net.res_bus.q_mvar.iloc[bus4], .002), .002, element=bus4) - + # IF pq of bus2 is not available makes bus3 an unobserved island # pp.create_measurement(net, "p", "bus", -r2(net.res_bus.p_mw.iloc[bus2], .001), .001, element=bus2) # pp.create_measurement(net, "q", "bus", -r2(net.res_bus.q_mvar.iloc[bus2], .001), .001, element=bus2) @@ -889,9 +889,9 @@ def test_net_unobserved_island(): pp.create_measurement(net, "q", "line", r2(net.res_line.q_from_mvar.iloc[0], .002), .002, 0, side='from') pp.create_measurement(net, "p", "trafo", r2(net.res_trafo.p_hv_mw.iloc[0], .001), .01, - side="hv", element=0) + side="hv", element=0) pp.create_measurement(net, "q", "trafo", r2(net.res_trafo.q_hv_mvar.iloc[0], .001), .01, - side="hv", element=0) + side="hv", element=0) if not estimate(net, tolerance=1e-6, zero_injection=None): raise AssertionError("Estimation failed!") @@ -900,17 +900,17 @@ def test_net_oos_line(): net = nw.case9() net.line.in_service.iat[4] = False pp.runpp(net) - + for line_ix in net.line.index: pp.create_measurement(net, "p", "line", net.res_line.at[line_ix, "p_from_mw"], 0.01, element=line_ix, side="from") pp.create_measurement(net, "q", "line", net.res_line.at[line_ix, "q_from_mvar"], 0.01, element=line_ix, side="from") - + for bus_ix in net.bus.index: pp.create_measurement(net, "v", "bus", net.res_bus.at[bus_ix, "vm_pu"], 0.01, element=bus_ix) - + if not estimate(net, tolerance=1e-6, zero_injection=None): raise AssertionError("Estimation failed!") diff --git a/pandapower/test/grid_equivalents/test_get_equivalent.py b/pandapower/test/grid_equivalents/test_get_equivalent.py index 96d544938..0d908e8ab 100644 --- a/pandapower/test/grid_equivalents/test_get_equivalent.py +++ b/pandapower/test/grid_equivalents/test_get_equivalent.py @@ -78,8 +78,8 @@ def run_basic_usecases(eq_type, net=None): # UC3b tests whether this also works for 'internal_buses' as empty list eq_net3b = pp.grid_equivalents.get_equivalent( subnet, eq_type, boundary_buses=[1, 5], internal_buses=[]) - eq_net3a.sgen.drop(columns=["origin_id"], inplace=True) - eq_net3b.sgen.drop(columns=["origin_id"], inplace=True) + eq_net3a.sgen = eq_net3a.sgen.drop(columns=["origin_id"]) + eq_net3b.sgen = eq_net3b.sgen.drop(columns=["origin_id"]) assert set(eq_net3a["group"].index) == set(eq_net3b["group"].index) assert pandapower.toolbox.nets_equal(eq_net3a, eq_net3b, exclude_elms=["group"]) @@ -153,7 +153,7 @@ def test_cost_consideration(): if cost_type == "pwl_cost": for poly in net.poly_cost.itertuples(): - net.poly_cost.drop(poly.Index, inplace=True) + net.poly_cost = net.poly_cost.drop(poly.Index) pp.create_pwl_cost(net, poly.element, poly.et, [[0, 20, 1]], index=poly.Index) # eq generation @@ -246,7 +246,7 @@ def test_case9_with_slack_generator_in_external_net(): net = pp.networks.case9() idx = pp.replace_ext_grid_by_gen(net) net.gen.loc[idx, "slack"] = True - net.bus_geodata.drop(net.bus_geodata.index, inplace=True) + net.bus_geodata = net.bus_geodata.drop(net.bus_geodata.index) pp.runpp(net) # since the only slack is in the external_buses, we expect get_equivalent() to move the slack @@ -266,8 +266,8 @@ def test_case9_with_slack_generator_in_external_net(): # UC1 eq_net1 = pp.grid_equivalents.get_equivalent(net, eq_type, boundary_buses, internal_buses) eq_net1b = pp.grid_equivalents.get_equivalent(net, eq_type, list(boundary_buses), list(internal_buses)) - eq_net1.gen.drop(columns=["origin_id"], inplace=True) - eq_net1b.gen.drop(columns=["origin_id"], inplace=True) + eq_net1.gen = eq_net1.gen.drop(columns=["origin_id"]) + eq_net1b.gen = eq_net1b.gen.drop(columns=["origin_id"]) assert pandapower.toolbox.nets_equal(eq_net1, eq_net1b) assert net.bus.name.loc[list(boundary_buses | internal_buses | slack_bus)].isin( eq_net1.bus.name).all() @@ -536,7 +536,7 @@ def test_controller(): assert net_eq.controller.object[0].__dict__["matching_params"]["element_index"] == [0, 2] # test individual controller: - net.controller.drop(net.controller.index, inplace=True) + net.controller = net.controller.drop(net.controller.index) for li in net.load.index: ConstControl(net, element='load', variable='p_mw', element_index=[li], data_source=DFData(load_ts), profile_name=[li]) diff --git a/pandapower/test/loadflow/test_runpp.py b/pandapower/test/loadflow/test_runpp.py index 9e1b7e042..4b952e161 100644 --- a/pandapower/test/loadflow/test_runpp.py +++ b/pandapower/test/loadflow/test_runpp.py @@ -778,7 +778,7 @@ def test_zip_loads_out_of_service(): pp.runpp(net, tolerance_mva=1e-8) pp.runpp(net1, tolerance_mva=1e-8) assert np.allclose(net1.res_load.loc[oos_load].fillna(0), 0) - net1.res_load.drop(oos_load, inplace=True) + net1.res_load = net1.res_load.drop(oos_load) assert nets_equal(net, net1, check_only_results=True) diff --git a/pandapower/test/loadflow/test_scenarios.py b/pandapower/test/loadflow/test_scenarios.py index ec4192814..84b5e1b40 100644 --- a/pandapower/test/loadflow/test_scenarios.py +++ b/pandapower/test/loadflow/test_scenarios.py @@ -372,7 +372,7 @@ def test_two_oos_buses(): assert net.res_line.loading_percent.at[l2] > 0 assert np.isnan(net.res_line.loading_percent.at[l3]) - net.line.drop(l2, inplace=True) + net.line = net.line.drop(l2) pp.runpp(net) assert net.res_line.loading_percent.at[l1] > 0 assert np.isnan(net.res_line.loading_percent.at[l3]) diff --git a/pandapower/test/loadflow/test_tdpf.py b/pandapower/test/loadflow/test_tdpf.py index d59068346..69de7fe27 100644 --- a/pandapower/test/loadflow/test_tdpf.py +++ b/pandapower/test/loadflow/test_tdpf.py @@ -195,7 +195,7 @@ def test_tdpf_frank(): line_loading = line_mva / line_max_mva ref2 = pd.read_csv(os.path.join(pp.pp_dir, "test", "test_files", "tdpf", "case30_branch_details.csv")) - ref2.sort_values(by="R_THETA", ascending=False, inplace=True) + ref2 = ref2.sort_values(by="R_THETA", ascending=False) # compare p_loss assert np.allclose(ref2.PLoss_TDPF * net.sn_mva, net.res_line.loc[sorted_index, "pl_mw"], rtol=0, atol=1e-6) @@ -226,7 +226,7 @@ def test_temperature_r(): net2.line["temperature_degree_celsius"] = net.res_line.temperature_degree_celsius pp.runpp(net2, consider_line_temperature=True) - net.res_line.drop(["temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1, inplace=True) + net.res_line = net.res_line.drop(["temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1) assert_res_equal(net, net2) # now test transient results -> after 5 min @@ -235,7 +235,7 @@ def test_temperature_r(): net2.line["temperature_degree_celsius"] = net.res_line.temperature_degree_celsius pp.runpp(net2, consider_line_temperature=True) - net.res_line.drop(["temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1, inplace=True) + net.res_line = net.res_line.drop(["temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1) assert_res_equal(net, net2) @@ -324,7 +324,7 @@ def test_default_parameters(): # with TDPF algorithm but no relevant tdpf lines the results must match with normal runpp: net.line["conductor_outer_diameter_m"] = np.nan pp.runpp(net, tdpf=True) - net.res_line.drop(["r_ohm_per_km", "temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1, inplace=True) + net.res_line = net.res_line.drop(["r_ohm_per_km", "temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1) assert_res_equal(net, net_backup) with pytest.raises(UserWarning, match="required columns .*'mc_joule_per_m_k'.* are missing"): @@ -337,7 +337,7 @@ def test_default_parameters(): pp.runpp(net, tdpf=True, tdpf_update_r_theta=False) net.line["r_theta_kelvin_per_mw"] = np.nan pp.runpp(net, tdpf=True, tdpf_update_r_theta=False) - net.res_line.drop(["r_ohm_per_km", "temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1, inplace=True) + net.res_line = net.res_line.drop(["r_ohm_per_km", "temperature_degree_celsius", "r_theta_kelvin_per_mw"], axis=1) assert_res_equal(net, net_backup) # now define some tdpf lines with simplified method diff --git a/pandapower/test/opf/test_basic.py b/pandapower/test/opf/test_basic.py index 19964fce4..2f4669d13 100644 --- a/pandapower/test/opf/test_basic.py +++ b/pandapower/test/opf/test_basic.py @@ -844,8 +844,8 @@ def test_line_temperature(): @pytest.fixture def four_bus_net(): net = simple_four_bus_system() - net.sgen.drop(index=1, inplace=True) - net.load.drop(index=1, inplace=True) + net.sgen = net.sgen.drop(index=1) + net.load = net.load.drop(index=1) return net @@ -867,7 +867,7 @@ def test_only_gen_slack_vm_setpoint(four_bus_net): # tests a net with only gens of which one of them is a a slack # The vmin / vmax vm_pu setpoint should be correct net = four_bus_net - net.ext_grid.drop(index=net.ext_grid.index, inplace=True) + net.ext_grid = net.ext_grid.drop(index=net.ext_grid.index) net.bus.loc[:, "min_vm_pu"] = 0.9 net.bus.loc[:, "max_vm_pu"] = 1.1 # create two additional slacks with different voltage setpoints diff --git a/pandapower/test/opf/test_cost_consistency.py b/pandapower/test/opf/test_cost_consistency.py index d8ebf11c4..40142bb0b 100644 --- a/pandapower/test/opf/test_cost_consistency.py +++ b/pandapower/test/opf/test_cost_consistency.py @@ -52,7 +52,7 @@ def test_contingency_sgen(base_net): assert isclose(net.res_cost, -net.res_sgen.p_mw.at[0], atol=1e-4) - net.pwl_cost.drop(0, inplace=True) + net.pwl_cost = net.pwl_cost.drop(0) # first using a positive slope as in the case above pp.create_poly_cost(net, 0, "sgen", cp1_eur_per_mw=1.) @@ -102,7 +102,7 @@ def test_contingency_load(base_net): assert isclose(net.res_cost, -net.res_gen.p_mw.at[0], atol=1e-3) - net.pwl_cost.drop(0, inplace=True) + net.pwl_cost = net.pwl_cost.drop(0) # first using a positive slope as in the case above pp.create_poly_cost(net, 0, "gen", cp1_eur_per_mw=1) @@ -152,7 +152,7 @@ def test_contingency_gen(base_net): assert isclose(net.res_cost, -net.res_gen.p_mw.at[0], atol=1e-3) - net.pwl_cost.drop(0, inplace=True) + net.pwl_cost = net.pwl_cost.drop(0) # first using a positive slope as in the case above # pp.create_pwl_cost(net, 0, "gen", array([1, 0])) diff --git a/pandapower/test/opf/test_costs_mixed.py b/pandapower/test/opf/test_costs_mixed.py index ae2ff549e..f94e2f309 100644 --- a/pandapower/test/opf/test_costs_mixed.py +++ b/pandapower/test/opf/test_costs_mixed.py @@ -56,7 +56,7 @@ def test_cost_mixed(): assert np.isclose(net.res_cost, net.res_gen.p_mw.values ** 2 + 1) net.load.at[0, "controllable"] = False - net.pwl_cost.drop(net.pwl_cost.index, inplace=True) + net.pwl_cost = net.pwl_cost.drop(net.pwl_cost.index) pp.create_pwl_cost(net, 0, "ext_grid", [[-1000, 0, -2000], [0, 1000, 2000]], power_type="p") net.poly_cost.cp1_eur_per_mw.at[0] = 1000 diff --git a/pandapower/test/opf/test_pandamodels_runpm.py b/pandapower/test/opf/test_pandamodels_runpm.py index 536c4de96..a2d7553de 100644 --- a/pandapower/test/opf/test_pandamodels_runpm.py +++ b/pandapower/test/opf/test_pandamodels_runpm.py @@ -199,7 +199,7 @@ def test_compare_pwl_and_poly(net_3w_trafo_opf): vm_bus = net.res_bus.vm_pu.values va_bus = net.res_bus.va_degree.values - net.pwl_cost.drop(net.pwl_cost.index, inplace=True) + net.pwl_cost = net.pwl_cost.drop(net.pwl_cost.index) pp.create_poly_cost(net, 0, 'ext_grid', cp1_eur_per_mw=1) pp.create_poly_cost(net, 0, 'gen', cp1_eur_per_mw=3) @@ -252,7 +252,7 @@ def test_pwl(): assert np.isclose(net.res_gen.p_mw.iloc[0], net.res_gen.p_mw.iloc[1]) assert np.isclose(net.res_gen.q_mvar.iloc[0], net.res_gen.q_mvar.iloc[1]) - net.pwl_cost.drop(net.pwl_cost.index, inplace=True) + net.pwl_cost = net.pwl_cost.drop(net.pwl_cost.index) g3 = pp.create_gen(net, bus1, p_mw=80, min_p_mw=0, max_p_mw=80, vm_pu=1.01) pp.create_pwl_cost(net, g1, 'gen', [[0, 2, 1.], [2, 80, 8.]]) @@ -722,7 +722,7 @@ def test_runpm_ploss_loading(): ### test loss reduction with Q-optimierung assert net.res_line.pl_mw.values.sum() < net_org.res_line.pl_mw.values.sum() - net.line.drop(columns=["pm_param/target_branch"], inplace=True) + net.line = net.line.drop(columns=["pm_param/target_branch"]) net.trafo["pm_param/target_branch"] = True pp.runpm_ploss(net) diff --git a/pandapower/test/plotting/test_generic_coordinates.py b/pandapower/test/plotting/test_generic_coordinates.py index 647987add..04f776fe2 100644 --- a/pandapower/test/plotting/test_generic_coordinates.py +++ b/pandapower/test/plotting/test_generic_coordinates.py @@ -19,7 +19,7 @@ @pytest.mark.skipif(IGRAPH_INSTALLED is False, reason="Requires igraph.") def test_create_generic_coordinates_igraph(): net = create_test_network() - net.bus_geodata.drop(net.bus_geodata.index, inplace=True) + net.bus_geodata = net.bus_geodata.drop(net.bus_geodata.index) create_generic_coordinates(net, library="igraph") assert len(net.bus_geodata) == len(net.bus) @@ -28,7 +28,7 @@ def test_create_generic_coordinates_igraph(): "as AtlasViews are accessed with list logic.") def test_create_generic_coordinates_nx(): net = create_test_network() - net.bus_geodata.drop(net.bus_geodata.index, inplace=True) + net.bus_geodata = net.bus_geodata.drop(net.bus_geodata.index) create_generic_coordinates(net, library="networkx") assert len(net.bus_geodata) == len(net.bus) @@ -36,7 +36,7 @@ def test_create_generic_coordinates_nx(): def test_create_generic_coordinates_igraph_custom_table_index(): net = nw.simple_four_bus_system() for buses in [[0,1], [0,2], [0,1,2]]: - create_generic_coordinates(net, buses=buses, geodata_table="test", + create_generic_coordinates(net, buses=buses, geodata_table="test", overwrite=True) assert np.all(net.test.index == buses) diff --git a/pandapower/test/timeseries/test_timeseries_recycle.py b/pandapower/test/timeseries/test_timeseries_recycle.py index 9c3a496bc..9b66e9c2a 100644 --- a/pandapower/test/timeseries/test_timeseries_recycle.py +++ b/pandapower/test/timeseries/test_timeseries_recycle.py @@ -51,8 +51,8 @@ def test_batch_output_reader(simple_test_net): del net, ow, c net = simple_test_net - net.output_writer.drop(index=net.output_writer.index, inplace=True) - net.controller.drop(index=net.controller.index, inplace=True) + net.output_writer = net.output_writer.drop(index=net.output_writer.index) + net.controller = net.controller.drop(index=net.controller.index) add_const(net, ds, recycle=False) ow = OutputWriter(net, output_path=tempfile.gettempdir(), output_file_type=".json", log_variables=list()) ow.log_variable('res_line', 'i_from_ka') @@ -121,8 +121,8 @@ def _run_recycle(net, run): run_timeseries(net, time_steps, verbose=False, run=run) vm_pu = copy.deepcopy(ow.output[_v_var(run)]) ll = copy.deepcopy(ow.output["res_line.loading_percent"]) - net.controller.drop(index=net.controller.index, inplace=True) - net.output_writer.drop(index=net.output_writer.index, inplace=True) + net.controller = net.controller.drop(index=net.controller.index) + net.output_writer = net.output_writer.drop(index=net.output_writer.index) del ow return vm_pu, ll diff --git a/pandapower/test/toolbox/test_comparison.py b/pandapower/test/toolbox/test_comparison.py index 13b61265b..27181b4ba 100644 --- a/pandapower/test/toolbox/test_comparison.py +++ b/pandapower/test/toolbox/test_comparison.py @@ -28,7 +28,7 @@ def test_nets_equal(): net = copy.deepcopy(original) # detecting removed element - net["bus"].drop(net.bus.index[0], inplace=True) + net["bus"] = net["bus"].drop(net.bus.index[0]) assert not pandapower.toolbox.nets_equal(original, net) assert not pandapower.toolbox.nets_equal(net, original) net = copy.deepcopy(original) @@ -51,7 +51,7 @@ def test_nets_equal(): assert pandapower.toolbox.nets_equal(net, original, atol=0.1) # check controllers - original.trafo.tap_side.fillna("hv", inplace=True) + original.trafo.tap_side = original.trafo.tap_side.fillna("hv") net1 = original.deepcopy() net2 = original.deepcopy() pp.control.ContinuousTapControl(net1, 0, 1.0) diff --git a/pandapower/test/toolbox/test_data_modification.py b/pandapower/test/toolbox/test_data_modification.py index 40a4af5e8..a7a1d336a 100644 --- a/pandapower/test/toolbox/test_data_modification.py +++ b/pandapower/test/toolbox/test_data_modification.py @@ -173,10 +173,10 @@ def test_continuous_element_numbering(): net = nw.example_multivoltage() # Add noises to index with some large number - net.line.rename(index={4: 280}, inplace=True) - net.trafo.rename(index={0: 300}, inplace=True) - net.trafo.rename(index={1: 400}, inplace=True) - net.trafo3w.rename(index={0: 540}, inplace=True) + net.line = net.line.rename(index={4: 280}) + net.trafo = net.trafo.rename(index={0: 300}) + net.trafo = net.trafo.rename(index={1: 400}) + net.trafo3w = net.trafo3w.rename(index={0: 540}) net.switch.loc[(net.switch.et == "l") & (net.switch.element == 4), "element"] = 280 net.switch.loc[(net.switch.et == "t") & (net.switch.element == 0), "element"] = 300 diff --git a/pandapower/test/toolbox/test_grid_modification.py b/pandapower/test/toolbox/test_grid_modification.py index 6a9bf240b..8a61f9d6d 100644 --- a/pandapower/test/toolbox/test_grid_modification.py +++ b/pandapower/test/toolbox/test_grid_modification.py @@ -933,7 +933,7 @@ def test_merge_same_bus_generation_plants(): # manipulate net for different functionality checks # 1) q_mvar should be summed which is only possible if no gen or ext_grid has the same bus - net.gen.drop(net.gen.index[net.gen.bus == 22], inplace=True) + net.gen = net.gen.drop(net.gen.index[net.gen.bus == 22]) net.sgen["q_mvar"] = np.arange(net.sgen.shape[0]) # 2) remove limit columns or values to check whether merge_same_bus_generation_plants() can # handle that diff --git a/pandapower/toolbox/data_modification.py b/pandapower/toolbox/data_modification.py index f3897736e..17f64e5fa 100644 --- a/pandapower/toolbox/data_modification.py +++ b/pandapower/toolbox/data_modification.py @@ -318,7 +318,7 @@ def reindex_elements(net, element_type, new_indices=None, old_indices=None, look net["line_geodata"][place_holder] = net["line_geodata"].index net["line_geodata"].loc[old_indices.intersection(net.line_geodata.index), place_holder] = ( get_indices(old_indices.intersection(net.line_geodata.index), lookup)) - net["line_geodata"].set_index(place_holder, inplace=True) + net["line_geodata"] = net["line_geodata"].set_index(place_holder) net["line_geodata"].index.name = idx_name # --- adapt index in cost dataframes diff --git a/pandapower/toolbox/grid_modification.py b/pandapower/toolbox/grid_modification.py index 13f04501f..0c72e6941 100644 --- a/pandapower/toolbox/grid_modification.py +++ b/pandapower/toolbox/grid_modification.py @@ -532,7 +532,7 @@ def merge_same_bus_generation_plants(net, add_info=True, error=True, for elm in gen_df["elm_type"].loc[idxs[1:]].unique(): dupl_idx_elm = gen_df.loc[gen_df.index.isin(idxs[1:]) & (gen_df.elm_type == elm), "index"].values - net[elm].drop(dupl_idx_elm, inplace=True) + net[elm] = net[elm].drop(dupl_idx_elm) something_merged |= True return something_merged @@ -621,13 +621,13 @@ def drop_elements_simple(net, element_type, element_index): element_index = ensure_iterability(element_index) detach_from_groups(net, element_type, element_index) - net[element_type].drop(element_index, inplace=True) + net[element_type] = net[element_type].drop(element_index) # res_element res_element_type = "res_" + element_type if res_element_type in net.keys() and isinstance(net[res_element_type], pd.DataFrame): drop_res_idx = net[res_element_type].index.intersection(element_index) - net[res_element_type].drop(drop_res_idx, inplace=True) + net[res_element_type] = net[res_element_type].drop(drop_res_idx) # logging if number := len(element_index) > 0: @@ -640,10 +640,10 @@ def drop_buses(net, buses, drop_elements=True): them as well. """ detach_from_groups(net, "bus", buses) - net["bus"].drop(buses, inplace=True) + net["bus"] = net["bus"].drop(buses) net["bus_geodata"].drop(set(buses) & set(net["bus_geodata"].index), inplace=True) res_buses = net.res_bus.index.intersection(buses) - net["res_bus"].drop(res_buses, inplace=True) + net["res_bus"] = net["res_bus"].drop(res_buses) if drop_elements: drop_elements_at_buses(net, buses) drop_measurements_at_elements(net, "bus", idx=buses) @@ -661,7 +661,7 @@ def drop_trafos(net, trafos, table="trafo"): # remove any affected trafo or trafo3w switches i = net["switch"].index[(net["switch"]["element"].isin(trafos)) & (net["switch"]["et"] == et)] detach_from_groups(net, "switch", i) - net["switch"].drop(i, inplace=True) + net["switch"] = net["switch"].drop(i) num_switches = len(i) # drop measurements @@ -669,8 +669,8 @@ def drop_trafos(net, trafos, table="trafo"): # drop the trafos detach_from_groups(net, table, trafos) - net[table].drop(trafos, inplace=True) - res_trafos = net["res_" + table].index.intersection(trafos) + net[table] = net[table].drop(trafos) + net[table] = net[table].drop(trafoson(trafos) net["res_" + table].drop(res_trafos, inplace=True) logger.debug("Dropped %i %s%s with %i switches" % ( len(trafos), table, plural_s(len(trafos)), num_switches)) @@ -684,17 +684,17 @@ def drop_lines(net, lines): # drop connected switches i = net["switch"][(net["switch"]["element"].isin(lines)) & (net["switch"]["et"] == "l")].index detach_from_groups(net, "switch", i) - net["switch"].drop(i, inplace=True) + net["switch"] = net["switch"].drop(i) # drop measurements drop_measurements_at_elements(net, "line", idx=lines) # drop lines and geodata detach_from_groups(net, "line", lines) - net["line"].drop(lines, inplace=True) + net["line"] = net["line"].drop(lines) net["line_geodata"].drop(set(lines) & set(net["line_geodata"].index), inplace=True) res_lines = net.res_line.index.intersection(lines) - net["res_line"].drop(res_lines, inplace=True) + net["res_line"] = net["res_line"].drop(res_lines) logger.debug("Dropped %i line%s with %i line switches" % ( len(lines), plural_s(len(lines)), len(i))) @@ -717,12 +717,12 @@ def drop_elements_at_buses(net, buses, bus_elements=True, branch_elements=True, else: n_el = net[element_type].shape[0] detach_from_groups(net, element_type, eid) - net[element_type].drop(eid, inplace=True) + net[element_type] = net[element_type].drop(eid) # res_element_type res_element_type = "res_" + element_type if res_element_type in net.keys() and isinstance(net[res_element_type], pd.DataFrame): res_eid = net[res_element_type].index.intersection(eid) - net[res_element_type].drop(res_eid, inplace=True) + net[res_element_type] = net[res_element_type].drop(res_eid) if net[element_type].shape[0] < n_el: logger.debug("Dropped %d %s elements" % ( n_el - net[element_type].shape[0], element_type)) @@ -738,7 +738,7 @@ def drop_elements_at_buses(net, buses, bus_elements=True, branch_elements=True, def drop_switches_at_buses(net, buses): i = net["switch"][(net["switch"]["bus"].isin(buses)) | ((net["switch"]["element"].isin(buses)) & (net["switch"]["et"] == "b"))].index - net["switch"].drop(i, inplace=True) + net["switch"] = net["switch"].drop(i) logger.debug("Dropped %d switches" % len(i)) @@ -751,7 +751,7 @@ def drop_measurements_at_elements(net, element_type, idx=None, side=None): bool2 = net.measurement.element.isin(idx) bool3 = net.measurement.side == side if side is not None else [True]*net.measurement.shape[0] to_drop = net.measurement.index[bool1 & bool2 & bool3] - net.measurement.drop(to_drop, inplace=True) + net.measurement = net.measurement.drop(to_drop) def drop_controllers_at_elements(net, element_type, idx=None): @@ -770,7 +770,7 @@ def drop_controllers_at_elements(net, element_type, idx=None): net.controller.object[i].__dict__["element_index"] = list(set(elm_idx) - set(idx)) net.controller.object[i].__dict__["matching_params"]["element_index"] = list( set(elm_idx) - set(idx)) - net.controller.drop(to_drop, inplace=True) + net.controller = net.controller.drop(to_drop) def drop_controllers_at_buses(net, buses): @@ -795,7 +795,7 @@ def drop_duplicated_measurements(net, buses=None, keep="first"): "measurement_type", "element_type", "side", "element"], keep=keep).empty: idx_to_drop = analyzed_meas.index[analyzed_meas.duplicated(subset=[ "measurement_type", "element_type", "side", "element"], keep=keep)] - net.measurement.drop(idx_to_drop, inplace=True) + net.measurement = net.measurement.drop(idx_to_drop) def _inner_branches(net, buses, task, branch_elements=None): @@ -823,7 +823,7 @@ def _inner_branches(net, buses, task, branch_elements=None): elif "trafo" in elm: drop_trafos(net, net[elm].index[inner]) else: - net[elm].drop(net[elm].index[inner], inplace=True) + net[elm] = net[elm].drop(net[elm].index[inner]) elif task == "get": inner_branches[elm] = net[elm].index[inner] else: @@ -997,7 +997,7 @@ def replace_zero_branches_with_switches(net, elements=('line', 'impedance'), zer if elm == 'line': drop_lines(net, affected_elements) else: - net[elm].drop(affected_elements, inplace=True) + net[elm] = net[elm].drop(affected_elements) logger.info('replaced %d %ss by switches' % (len(affected_elements), elm)) else: @@ -1200,7 +1200,7 @@ def replace_ext_grid_by_gen(net, ext_grids=None, gen_indices=None, slack=False, _replace_group_member_element_type(net, ext_grids, "ext_grid", new_idx, "gen") # --- drop replaced ext_grids - net.ext_grid.drop(ext_grids, inplace=True) + net.ext_grid = net.ext_grid.drop(ext_grids) # --- adapt cost data for table in ["pwl_cost", "poly_cost"]: @@ -1283,7 +1283,7 @@ def replace_gen_by_ext_grid(net, gens=None, ext_grid_indices=None, cols_to_keep= _replace_group_member_element_type(net, gens, "gen", new_idx, "ext_grid") # --- drop replaced gens - net.gen.drop(gens, inplace=True) + net.gen = net.gen.drop(gens) # --- adapt cost data for table in ["pwl_cost", "poly_cost"]: @@ -1367,7 +1367,7 @@ def replace_gen_by_sgen(net, gens=None, sgen_indices=None, cols_to_keep=None, _replace_group_member_element_type(net, gens, "gen", new_idx, "sgen") # --- drop replaced gens - net.gen.drop(gens, inplace=True) + net.gen = net.gen.drop(gens) # --- adapt cost data for table in ["pwl_cost", "poly_cost"]: @@ -1466,7 +1466,7 @@ def replace_sgen_by_gen(net, sgens=None, gen_indices=None, cols_to_keep=None, _replace_group_member_element_type(net, sgens, "sgen", new_idx, "gen") # --- drop replaced sgens - net.sgen.drop(sgens, inplace=True) + net.sgen = net.sgen.drop(sgens) # --- adapt cost data for table in ["pwl_cost", "poly_cost"]: @@ -1586,7 +1586,7 @@ def replace_pq_elmtype(net, old_element_type, new_element_type, old_indices=None _replace_group_member_element_type(net, old_indices, old_element_type, new_idx, new_element_type) # --- drop replaced old_indices - net[old_element_type].drop(old_indices, inplace=True) + net[old_element_type] = net[old_element_type].drop(old_indices) # --- adapt cost data for table in ["pwl_cost", "poly_cost"]: @@ -1720,7 +1720,7 @@ def replace_xward_by_internal_elements(net, xwards=None, set_xward_bus_limits=Fa if net.res_xward.shape[0]: log_to_level("Implementations to move xward results to new internal elements are missing.", logger, log_level) - net.res_xward.drop(xwards, inplace=True) + net.res_xward = net.res_xward.drop(xwards) # --- drop replaced wards drop_elements_simple(net, "xward", xwards) diff --git a/pandapower/toolbox/result_info.py b/pandapower/toolbox/result_info.py index c0d2f35df..793f57204 100644 --- a/pandapower/toolbox/result_info.py +++ b/pandapower/toolbox/result_info.py @@ -415,7 +415,7 @@ def clear_result_tables(net): """ for key in net.keys(): if isinstance(net[key], pd.DataFrame) and key[:3] == "res" and net[key].shape[0]: - net[key].drop(net[key].index, inplace=True) + net[key] = net[key].drop(net[key].index) def res_power_columns(element_type, side=0): From 37620c7c9a3e1c8e1434ac6961c36f831244c4c2 Mon Sep 17 00:00:00 2001 From: Steffen Meinecke Date: Mon, 25 Mar 2024 12:49:05 +0100 Subject: [PATCH 05/17] skipif power_grid_model and tiny fix --- pandapower/opf/validate_opf_input.py | 6 ++---- pandapower/test/loadflow/test_runpp_pgm.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/pandapower/opf/validate_opf_input.py b/pandapower/opf/validate_opf_input.py index 60552992c..01019e1b6 100644 --- a/pandapower/opf/validate_opf_input.py +++ b/pandapower/opf/validate_opf_input.py @@ -21,10 +21,8 @@ def _check_necessary_opf_parameters(net, logger): controllables = net[element_type].index else: if "controllable" in net[element_type].columns: - if element_type == 'gen': - net[element_type].controllable = net[element_type].controllable.fillna(True) - net[element_type].controllable = net[element_type].controllable.fillna(True - net[element_type].controllable.fillna(False, inplace=True) + to_fill = element_type == 'gen' + net[element_type].controllable = net[element_type].controllable.fillna(to_fill) controllables = net[element_type].index[net[element_type].controllable.astype( bool)] else: diff --git a/pandapower/test/loadflow/test_runpp_pgm.py b/pandapower/test/loadflow/test_runpp_pgm.py index 143d4b661..f5c89cd9c 100644 --- a/pandapower/test/loadflow/test_runpp_pgm.py +++ b/pandapower/test/loadflow/test_runpp_pgm.py @@ -5,8 +5,15 @@ import pandapower as pp from pandapower.test.consistency_checks import runpp_pgm_with_consistency_checks, runpp_pgm_3ph_with_consistency_checks +try: + import power_grid_model + PGM_IMPORTED = True +except ImportError: + PGM_IMPORTED = False + @pytest.mark.parametrize("consistency_fn" , [runpp_pgm_with_consistency_checks, runpp_pgm_3ph_with_consistency_checks]) +@pytest.mark.skipif(not PGM_IMPORTED, reason="requires power_grid_model") def test_minimal_net_pgm(consistency_fn): # tests corner-case when the grid only has 1 bus and an ext-grid net = pp.create_empty_network() @@ -23,6 +30,7 @@ def test_minimal_net_pgm(consistency_fn): consistency_fn(net) +@pytest.mark.skipif(not PGM_IMPORTED, reason="requires power_grid_model") def test_runpp_pgm__invalid_algorithm(): net = pp.create_empty_network() with pytest.raises( @@ -33,6 +41,7 @@ def test_runpp_pgm__invalid_algorithm(): @patch("pandapower.run.logger") +@pytest.mark.skipif(not PGM_IMPORTED, reason="requires power_grid_model") def test_runpp_pgm__internal_pgm_error(mock_logger: MagicMock): net = pp.create_empty_network() b1 = pp.create_bus(net, 110) @@ -48,6 +57,7 @@ def test_runpp_pgm__internal_pgm_error(mock_logger: MagicMock): @patch("pandapower.run.logger") +@pytest.mark.skipif(not PGM_IMPORTED, reason="requires power_grid_model") def test_runpp_pgm__validation_fail(mock_logger: MagicMock): net = pp.create_empty_network() pp.create_bus(net, -110, index=123) From 71633d1ee61a5f341b7489d3ef007552cd27e41c Mon Sep 17 00:00:00 2001 From: Steffen Meinecke Date: Mon, 25 Mar 2024 14:34:12 +0100 Subject: [PATCH 06/17] fixes --- CHANGELOG.rst | 1 + pandapower/convert_format.py | 14 +++++++------- .../generators/synchronousMachinesCim16.py | 18 +++++++++--------- .../transformers/powerTransformersCim16.py | 12 ++++++------ pandapower/groups.py | 5 +++-- pandapower/toolbox/grid_modification.py | 4 ++-- 6 files changed, 28 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 92b743404..1c4bb3e08 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -50,6 +50,7 @@ Change Log - [ADDED] cim2pp: added description fields for each asset and added BusbarSection information to nodes - [CHANGED] cim2pp: reformat documentation for reading in files - [CHANGED] allow providing grid_tables as a parameter to the function that downloads net from PostgreSQL +- [FIXED] avoid FutureWarning of pandas 2.2 - [FIXED] compatibility with lightsim2grid after new version 0.8.0 [2.13.1] - 2023-05-12 diff --git a/pandapower/convert_format.py b/pandapower/convert_format.py index 8e7e489ed..b54db49cb 100644 --- a/pandapower/convert_format.py +++ b/pandapower/convert_format.py @@ -399,16 +399,16 @@ def _set_data_type_of_columns(net): def _convert_to_mw(net): replace = [("kw", "mw"), ("kvar", "mvar"), ("kva", "mva")] - for element, tab in net.items(): - if isinstance(tab, pd.DataFrame): + for element in net.keys(): + if isinstance(net[element], pd.DataFrame): for old, new in replace: - diff = {column: column.replace(old, new) for column in tab.columns if old in column - and column != "pfe_kw"} - tab = tab.rename(columns=diff) - if len(tab) == 0: + diff = {column: column.replace(old, new) for column in net[element].columns if + old in column and column != "pfe_kw"} + net[element] = net[element].rename(columns=diff) + if len(net[element]) == 0: continue for old, new in diff.items(): - tab[new] *= 1e-3 + net[element][new] *= 1e-3 for element, std_types in net.std_types.items(): for std_type, parameters in std_types.items(): diff --git a/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py index 37db5fc18..469b676e1 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/generators/synchronousMachinesCim16.py @@ -44,26 +44,26 @@ def _prepare_synchronous_machines_cim16(self) -> pd.DataFrame: eq_generating_units['type'] = 'GeneratingUnit' eq_generating_units = pd.concat([eq_generating_units, self.cimConverter.cim['eq']['WindGeneratingUnit']], sort=False) - eq_generating_units['type'].fillna('WP', inplace=True) + eq_generating_units['type'] = eq_generating_units['type'].fillna('WP') eq_generating_units = pd.concat([eq_generating_units, self.cimConverter.cim['eq']['HydroGeneratingUnit']], sort=False) - eq_generating_units['type'].fillna('Hydro', inplace=True) + eq_generating_units['type'] = eq_generating_units['type'].fillna('Hydro') eq_generating_units = pd.concat([eq_generating_units, self.cimConverter.cim['eq']['SolarGeneratingUnit']], sort=False) - eq_generating_units['type'].fillna('PV', inplace=True) + eq_generating_units['type'] = eq_generating_units['type'].fillna('PV') eq_generating_units = pd.concat([eq_generating_units, self.cimConverter.cim['eq']['ThermalGeneratingUnit']], sort=False) - eq_generating_units['type'].fillna('Thermal', inplace=True) + eq_generating_units['type'] = eq_generating_units['type'].fillna('Thermal') eq_generating_units = pd.concat([eq_generating_units, self.cimConverter.cim['eq']['NuclearGeneratingUnit']], sort=False) - eq_generating_units['type'].fillna('Nuclear', inplace=True) + eq_generating_units['type'] = eq_generating_units['type'].fillna('Nuclear') eq_generating_units = eq_generating_units.rename(columns={'rdfId': 'GeneratingUnit'}) - eqssh_synchronous_machines = self.cimConverter.merge_eq_ssh_profile('SynchronousMachine', - add_cim_type_column=True) + eqssh_synchronous_machines = self.cimConverter.merge_eq_ssh_profile( + 'SynchronousMachine', add_cim_type_column=True) if 'type' in eqssh_synchronous_machines.columns: eqssh_synchronous_machines = eqssh_synchronous_machines.drop(columns=['type']) - eqssh_synchronous_machines = eqssh_synchronous_machines.drop(columns=['type'] - eqssh_synchronous_machines.drop(columns=['EquipmentContainer'], inplace=True) + if 'EquipmentContainer' in eqssh_synchronous_machines.columns: + eqssh_synchronous_machines = eqssh_synchronous_machines.drop(columns=['EquipmentContainer']) eqssh_synchronous_machines = pd.merge(eqssh_synchronous_machines, eq_generating_units, how='left', on='GeneratingUnit') eqssh_reg_control = self.cimConverter.merge_eq_ssh_profile('RegulatingControl')[ diff --git a/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py b/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py index 808f6e87a..da046d7f3 100644 --- a/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py +++ b/pandapower/converter/cim/cim2pp/converter_classes/transformers/powerTransformersCim16.py @@ -102,8 +102,8 @@ def _create_trafo_characteristics(self, trafo_type, trafo_df_origin): fillna_list = ['tabular_step'] for one_item in fillna_list: trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv']) - trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv'] - trafo_df.dropna(subset=['r_dev', 'r_dev_lv'], how='all', inplace=True) + del fillna_list, one_item + trafo_df = trafo_df.dropna(subset=['r_dev', 'r_dev_lv'], how='all') fillna_list = ['r_dev', 'r_dev_lv', 'x_dev', 'x_dev_lv'] for one_item in fillna_list: trafo_df[one_item] = trafo_df[one_item].fillna(0) @@ -176,8 +176,8 @@ def _create_trafo_characteristics(self, trafo_type, trafo_df_origin): for one_item in fillna_list: trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_mv']) trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_lv']) - trafo_df[one_item] = trafo_df[one_item].fillna(trafo_df[one_item + '_mv'] - trafo_df.dropna(subset=['r_dev', 'r_dev_mv', 'r_dev_lv'], how='all', inplace=True) + del fillna_list, one_item + trafo_df = trafo_df.dropna(subset=['r_dev', 'r_dev_mv', 'r_dev_lv'], how='all') fillna_list = ['r_dev', 'r_dev_mv', 'r_dev_lv', 'x_dev', 'x_dev_mv', 'x_dev_lv'] for one_item in fillna_list: trafo_df[one_item] = trafo_df[one_item].fillna(0) @@ -320,8 +320,8 @@ def _prepare_power_transformers_cim16(self) -> pd.DataFrame: continue current_step = one_df['current_step'].iloc[0] one_df = one_df.set_index('step') - one_df = one_df.set_index('step''].iloc[0] - ptct.drop(drop_index, inplace=True) + neutral_step = one_df['neutralStep'].iloc[0] + ptct = ptct.drop(drop_index) # ptct.loc[keep_index, 'angle'] = # one_df.loc[current_step, 'angle'] / max(1, abs(current_step - neutral_step)) ptct.loc[keep_index, 'angle'] = one_df.loc[current_step, 'angle'] # todo fix if pp supports them diff --git a/pandapower/groups.py b/pandapower/groups.py index 4f1739b0a..e225efe81 100644 --- a/pandapower/groups.py +++ b/pandapower/groups.py @@ -169,8 +169,9 @@ def attach_to_group(net, index, element_types, elements, reference_columns=None, prev_elm = net.group.element.loc[group_et].at[index] prev_elm = [prev_elm] if isinstance(prev_elm, str) or not hasattr( prev_elm, "__iter__") else list(prev_elm) - net.group.loc[group_et, "element"] = [prev_elm + list(pd.Index(elm).difference( - pd.Index(prev_elm)))] + net.group.iat[np.arange(len(group_et), dtype=int)[group_et][0], + net.group.columns.get_loc("element")] = \ + prev_elm + list(pd.Index(elm).difference(pd.Index(prev_elm))) # --- prepare adding new rows to net.group (because no other elements of element type et # --- already belong to the group) diff --git a/pandapower/toolbox/grid_modification.py b/pandapower/toolbox/grid_modification.py index 0c72e6941..db4d4b2a0 100644 --- a/pandapower/toolbox/grid_modification.py +++ b/pandapower/toolbox/grid_modification.py @@ -670,8 +670,8 @@ def drop_trafos(net, trafos, table="trafo"): # drop the trafos detach_from_groups(net, table, trafos) net[table] = net[table].drop(trafos) - net[table] = net[table].drop(trafoson(trafos) - net["res_" + table].drop(res_trafos, inplace=True) + res_trafos = net["res_" + table].index.intersection(trafos) + net["res_" + table] = net["res_" + table].drop(res_trafos) logger.debug("Dropped %i %s%s with %i switches" % ( len(trafos), table, plural_s(len(trafos)), num_switches)) From 2c5dc6f693a2ccbbea2d23a938acd232cc6e22bd Mon Sep 17 00:00:00 2001 From: Steffen Meinecke Date: Mon, 25 Mar 2024 14:42:50 +0100 Subject: [PATCH 07/17] another fix and StringIO usage --- pandapower/io_utils.py | 5 +++-- .../synthetic_voltage_control_lv_networks.py | 4 ++-- .../grid_equivalents/test_get_equivalent.py | 11 ++++++----- .../test_grid_equivalents_auxiliary.py | 17 +++++++++-------- pandapower/test/opf/test_opf_cigre.py | 8 ++++---- pandapower/test/opf/test_pandamodels_runpm.py | 3 ++- 6 files changed, 26 insertions(+), 22 deletions(-) diff --git a/pandapower/io_utils.py b/pandapower/io_utils.py index c61ea0eb9..09cb2fa5b 100644 --- a/pandapower/io_utils.py +++ b/pandapower/io_utils.py @@ -8,6 +8,7 @@ import json import numbers import os +import io import pickle import sys import types @@ -488,7 +489,7 @@ def Series(self): is_multiindex = self.d.pop('is_multiindex', False) index_name = self.d.pop('index_name', None) index_names = self.d.pop('index_names', None) - ser = pd.read_json(self.obj, precise_float=True, **self.d) + ser = pd.read_json(io.StringIO(self.obj, precise_float=True, **self.d)) # restore index name and Multiindex if index_name is not None: @@ -520,7 +521,7 @@ def DataFrame(self): if isinstance(obj, str): obj = StringIO(obj) - df = pd.read_json(obj, precise_float=True, convert_axes=False, **self.d) + df = pd.read_json(io.StringIO(obj, precise_float=True, convert_axes=False, **self.d)) if not df.shape[0] or self.d.get("orient", False) == "columns": try: diff --git a/pandapower/networks/synthetic_voltage_control_lv_networks.py b/pandapower/networks/synthetic_voltage_control_lv_networks.py index 7b768b872..a66cfbb77 100644 --- a/pandapower/networks/synthetic_voltage_control_lv_networks.py +++ b/pandapower/networks/synthetic_voltage_control_lv_networks.py @@ -3,7 +3,7 @@ # Copyright (c) 2016-2023 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. - +import io import pandapower as pp import pandas as pd from numpy import nan, append @@ -193,7 +193,7 @@ def create_synthetic_voltage_control_lv_network(network_class="rural_1"): "village_2": '{"x":{"0":0.0,"1":0.0,"2":-3.0,"3":-3.5,"4":-4.0,"5":-4.5,"6":-5.0,"7":-5.5,"8":-6.0,"9":-6.5,"10":-7.0,"11":-2.5,"12":-3.0,"13":-3.5,"14":-4.0,"15":-4.5,"16":-5.0,"17":-5.5,"18":-6.0,"19":-7.0,"20":-1.0,"21":-1.5,"22":-2.0,"23":-2.5,"24":-3.0,"25":-3.5,"26":-4.0,"27":-4.5,"28":-5.0,"29":-5.5,"30":-6.0,"31":-6.5,"32":-0.5,"33":-1.0,"34":-1.5,"35":-2.0,"36":-2.5,"37":-3.0,"38":-3.5,"39":-4.0,"40":-4.5,"41":-5.0,"42":-5.5,"43":-6.5,"44":1.0,"45":0.5,"46":0.0,"47":-0.5,"48":-1.0,"49":1.5,"50":1.0,"51":0.5,"52":0.0,"53":-1.0,"54":3.0,"55":2.5,"56":2.0,"57":1.5,"58":1.0,"59":0.5,"60":0.0,"61":-0.5,"62":-1.0,"63":-1.5,"64":3.5,"65":3.0,"66":2.5,"67":2.0,"68":1.5,"69":1.0,"70":0.5,"71":0.0,"72":-0.5,"73":-1.5},"y":{"0":0.0,"1":1.0,"2":2.0,"3":3.0,"4":4.0,"5":5.0,"6":6.0,"7":7.0,"8":8.0,"9":9.0,"10":10.0,"11":3.0,"12":4.0,"13":5.0,"14":6.0,"15":7.0,"16":8.0,"17":9.0,"18":10.0,"19":11.0,"20":2.0,"21":3.0,"22":4.0,"23":5.0,"24":6.0,"25":7.0,"26":8.0,"27":9.0,"28":10.0,"29":11.0,"30":12.0,"31":13.0,"32":3.0,"33":4.0,"34":5.0,"35":6.0,"36":7.0,"37":8.0,"38":9.0,"39":10.0,"40":11.0,"41":12.0,"42":13.0,"43":14.0,"44":2.0,"45":3.0,"46":4.0,"47":5.0,"48":6.0,"49":3.0,"50":4.0,"51":5.0,"52":6.0,"53":7.0,"54":2.0,"55":3.0,"56":4.0,"57":5.0,"58":6.0,"59":7.0,"60":8.0,"61":9.0,"62":10.0,"63":11.0,"64":3.0,"65":4.0,"66":5.0,"67":6.0,"68":7.0,"69":8.0,"70":9.0,"71":10.0,"72":11.0,"73":12.0}}', "suburb_1": '{"x":{"0":0.0,"1":0.0,"2":-9.5,"3":-10.0,"4":-10.5,"5":-11.0,"6":-11.5,"7":-12.0,"8":-12.5,"9":-13.0,"10":-13.5,"11":-9.0,"12":-9.5,"13":-10.0,"14":-10.5,"15":-11.0,"16":-11.5,"17":-12.0,"18":-12.5,"19":-13.5,"20":-7.5,"21":-8.0,"22":-8.5,"23":-9.0,"24":-9.5,"25":-10.0,"26":-10.5,"27":-11.0,"28":-11.5,"29":-12.0,"30":-12.5,"31":-13.0,"32":-13.5,"33":-14.0,"34":-14.5,"35":-15.0,"36":-15.5,"37":-7.0,"38":-7.5,"39":-8.0,"40":-8.5,"41":-9.0,"42":-9.5,"43":-10.0,"44":-10.5,"45":-11.0,"46":-11.5,"47":-12.0,"48":-12.5,"49":-13.0,"50":-13.5,"51":-14.0,"52":-14.5,"53":-15.5,"54":-5.5,"55":-6.0,"56":-6.5,"57":-7.0,"58":-7.5,"59":-5.0,"60":-5.5,"61":-6.0,"62":-6.5,"63":-7.5,"64":-3.5,"65":-4.0,"66":-4.5,"67":-5.0,"68":-5.5,"69":-6.0,"70":-6.5,"71":-7.0,"72":-7.5,"73":-8.0,"74":-8.5,"75":-9.0,"76":-9.5,"77":-3.0,"78":-3.5,"79":-4.0,"80":-4.5,"81":-5.0,"82":-5.5,"83":-6.0,"84":-6.5,"85":-7.0,"86":-7.5,"87":-8.0,"88":-8.5,"89":-9.5,"90":-1.5,"91":-2.0,"92":-2.5,"93":-3.0,"94":-3.5,"95":-4.0,"96":-4.5,"97":-5.0,"98":-1.0,"99":-1.5,"100":-2.0,"101":-2.5,"102":-3.0,"103":-3.5,"104":-4.0,"105":-5.0,"106":0.0,"107":0.0,"108":1.5,"109":1.0,"110":0.5,"111":0.0,"112":-0.5,"113":-1.0,"114":-1.5,"115":-2.0,"116":-2.5,"117":2.0,"118":1.5,"119":1.0,"120":0.5,"121":0.0,"122":-0.5,"123":-1.0,"124":-1.5,"125":-2.5,"126":3.5,"127":3.0,"128":2.5,"129":2.0,"130":1.5,"131":1.0,"132":0.5,"133":0.0,"134":-0.5,"135":-1.0,"136":-1.5,"137":-2.0,"138":-2.5,"139":-3.0,"140":-3.5,"141":-4.0,"142":-4.5,"143":4.0,"144":3.5,"145":3.0,"146":2.5,"147":2.0,"148":1.5,"149":1.0,"150":0.5,"151":0.0,"152":-0.5,"153":-1.0,"154":-1.5,"155":-2.0,"156":-2.5,"157":-3.0,"158":-3.5,"159":-4.5,"160":5.5,"161":5.0,"162":4.5,"163":4.0,"164":3.5,"165":6.0,"166":5.5,"167":5.0,"168":4.5,"169":3.5,"170":7.5,"171":7.0,"172":6.5,"173":6.0,"174":5.5,"175":5.0,"176":4.5,"177":4.0,"178":3.5,"179":3.0,"180":2.5,"181":2.0,"182":1.5,"183":8.0,"184":7.5,"185":7.0,"186":6.5,"187":6.0,"188":5.5,"189":5.0,"190":4.5,"191":4.0,"192":3.5,"193":3.0,"194":2.5,"195":1.5,"196":9.5,"197":9.0,"198":8.5,"199":8.0,"200":10.0,"201":9.5,"202":9.0,"203":8.0},"y":{"0":0.0,"1":1.0,"2":2.0,"3":3.0,"4":4.0,"5":5.0,"6":6.0,"7":7.0,"8":8.0,"9":9.0,"10":10.0,"11":3.0,"12":4.0,"13":5.0,"14":6.0,"15":7.0,"16":8.0,"17":9.0,"18":10.0,"19":11.0,"20":2.0,"21":3.0,"22":4.0,"23":5.0,"24":6.0,"25":7.0,"26":8.0,"27":9.0,"28":10.0,"29":11.0,"30":12.0,"31":13.0,"32":14.0,"33":15.0,"34":16.0,"35":17.0,"36":18.0,"37":3.0,"38":4.0,"39":5.0,"40":6.0,"41":7.0,"42":8.0,"43":9.0,"44":10.0,"45":11.0,"46":12.0,"47":13.0,"48":14.0,"49":15.0,"50":16.0,"51":17.0,"52":18.0,"53":19.0,"54":2.0,"55":3.0,"56":4.0,"57":5.0,"58":6.0,"59":3.0,"60":4.0,"61":5.0,"62":6.0,"63":7.0,"64":2.0,"65":3.0,"66":4.0,"67":5.0,"68":6.0,"69":7.0,"70":8.0,"71":9.0,"72":10.0,"73":11.0,"74":12.0,"75":13.0,"76":14.0,"77":3.0,"78":4.0,"79":5.0,"80":6.0,"81":7.0,"82":8.0,"83":9.0,"84":10.0,"85":11.0,"86":12.0,"87":13.0,"88":14.0,"89":15.0,"90":2.0,"91":3.0,"92":4.0,"93":5.0,"94":6.0,"95":7.0,"96":8.0,"97":9.0,"98":3.0,"99":4.0,"100":5.0,"101":6.0,"102":7.0,"103":8.0,"104":9.0,"105":10.0,"106":2.0,"107":3.0,"108":2.0,"109":3.0,"110":4.0,"111":5.0,"112":6.0,"113":7.0,"114":8.0,"115":9.0,"116":10.0,"117":3.0,"118":4.0,"119":5.0,"120":6.0,"121":7.0,"122":8.0,"123":9.0,"124":10.0,"125":11.0,"126":2.0,"127":3.0,"128":4.0,"129":5.0,"130":6.0,"131":7.0,"132":8.0,"133":9.0,"134":10.0,"135":11.0,"136":12.0,"137":13.0,"138":14.0,"139":15.0,"140":16.0,"141":17.0,"142":18.0,"143":3.0,"144":4.0,"145":5.0,"146":6.0,"147":7.0,"148":8.0,"149":9.0,"150":10.0,"151":11.0,"152":12.0,"153":13.0,"154":14.0,"155":15.0,"156":16.0,"157":17.0,"158":18.0,"159":19.0,"160":2.0,"161":3.0,"162":4.0,"163":5.0,"164":6.0,"165":3.0,"166":4.0,"167":5.0,"168":6.0,"169":7.0,"170":2.0,"171":3.0,"172":4.0,"173":5.0,"174":6.0,"175":7.0,"176":8.0,"177":9.0,"178":10.0,"179":11.0,"180":12.0,"181":13.0,"182":14.0,"183":3.0,"184":4.0,"185":5.0,"186":6.0,"187":7.0,"188":8.0,"189":9.0,"190":10.0,"191":11.0,"192":12.0,"193":13.0,"194":14.0,"195":15.0,"196":2.0,"197":3.0,"198":4.0,"199":5.0,"200":3.0,"201":4.0,"202":5.0,"203":6.0}}' } - net.bus_geodata = pd.read_json(bus_geo[network_class]) + net.bus_geodata = pd.read_json(io.StringIO(bus_geo[network_class])) # Match bus.index net.bus_geodata = net.bus_geodata.loc[net.bus.index] return net diff --git a/pandapower/test/grid_equivalents/test_get_equivalent.py b/pandapower/test/grid_equivalents/test_get_equivalent.py index 0d908e8ab..e8568e88b 100644 --- a/pandapower/test/grid_equivalents/test_get_equivalent.py +++ b/pandapower/test/grid_equivalents/test_get_equivalent.py @@ -1,3 +1,4 @@ +import io import pytest import numpy as np import pandapower as pp @@ -414,10 +415,10 @@ def test_equivalent_groups(): def test_shifter_degree(): net = pp.networks.example_multivoltage() - net.trafo.shift_degree[0] = 30 - net.trafo.shift_degree[1] = -60 - net.trafo3w.shift_mv_degree[0] = 90 - net.trafo3w.shift_lv_degree[0] = 150 + net.trafo.at[0, "shift_degree"] = 30 + net.trafo.at[1, "shift_degree"] = -60 + net.trafo3w.at[0, "shift_mv_degree"] = 90 + net.trafo3w.at[0, "shift_lv_degree"] = 150 pp.runpp(net, calculate_voltage_angles=True) boundary_buses = list([net.trafo.hv_bus.values[1]]) + list(net.trafo.lv_bus.values) + \ @@ -499,7 +500,7 @@ def test_controller(): # load time series json_path = os.path.join(pp_dir, "test", "opf", "cigre_timeseries_15min.json") - time_series = pd.read_json(json_path) + time_series = pd.read_json(io.StringIO(json_path)) time_series.sort_index(inplace=True) sgen_p = net["sgen"].loc[:, "p_mw"].values load_p = net["load"].loc[:, "p_mw"].values diff --git a/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py b/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py index ecc03bdea..9a41b960a 100644 --- a/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py +++ b/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py @@ -1,3 +1,4 @@ +import io import pytest import os import pandapower as pp @@ -40,7 +41,7 @@ def test_trafo_phase_shifter(): net = pp.networks.create_cigre_network_mv(with_der="pv_wind") net.trafo.shift_degree[0] = 150 pp.runpp(net) - net_eq = pp.grid_equivalents.get_equivalent(net, "rei", [4, 8], [0], + net_eq = pp.grid_equivalents.get_equivalent(net, "rei", [4, 8], [0], retain_original_internal_indices=True) v, p = get_boundary_vp(net_eq, net_eq.bus_lookups) net.res_bus.vm_pu = net.res_bus.vm_pu.values + 1e-3 @@ -66,25 +67,25 @@ def test_drop_measurements_and_controllers(): net.measurement.loc[4] = ["mb", "p", "trafo", 0, 89.3, 0.01, "hv"] net.measurement.loc[5] = ["mb", "i", "trafo3w", 0, 23.56, 0.01, "mv"] assert len(net.measurement) == 6 - + # create controllers json_path = os.path.join(pp_dir, "test", "opf", "cigre_timeseries_15min.json") - time_series = pd.read_json(json_path) + time_series = pd.read_json(io.StringIO(json_path)) load_ts = pd.DataFrame(index=time_series.index.tolist(), columns=net.load.index.tolist()) gen_ts = pd.DataFrame(index=time_series.index.tolist(), columns=net.gen.index.tolist()) for t in range(96): load_ts.loc[t] = net.load.p_mw.values * time_series.at[t, "residential"] gen_ts.loc[t] = net.gen.p_mw.values * time_series.at[t, "pv"] - ConstControl(net, element="load", variable="p_mw", element_index=net.load.index.tolist(), + ConstControl(net, element="load", variable="p_mw", element_index=net.load.index.tolist(), profile_name=net.load.index.tolist(), data_source=DFData(load_ts)) - ConstControl(net, element="gen", variable="p_mw", element_index=net.gen.index.tolist(), + ConstControl(net, element="gen", variable="p_mw", element_index=net.gen.index.tolist(), profile_name=net.gen.index.tolist(), data_source=DFData(gen_ts)) for i in net.gen.index: - ConstControl(net, element="gen", variable="p_mw", element_index=i, + ConstControl(net, element="gen", variable="p_mw", element_index=i, profile_name=net.gen.index[i], data_source=DFData(gen_ts)) for i in net.load.index: - ConstControl(net, element="load", variable="p_mw", element_index=i, + ConstControl(net, element="load", variable="p_mw", element_index=i, profile_name=net.load.index[i], data_source=DFData(load_ts)) assert net.controller.object[0].__dict__["element_index"] == [0, 1, 2] @@ -105,7 +106,7 @@ def test_check_network(): net.bus.in_service[5] = False pp.runpp(net) _check_network(net) - + net.bus.in_service[5] = True pp.runpp(net) pp.create_bus(net, net.bus.vn_kv.values[0]) diff --git a/pandapower/test/opf/test_opf_cigre.py b/pandapower/test/opf/test_opf_cigre.py index e2be81aea..1448dc4ed 100644 --- a/pandapower/test/opf/test_opf_cigre.py +++ b/pandapower/test/opf/test_opf_cigre.py @@ -61,10 +61,10 @@ def test_some_sgens_not_controllable(): net.sgen["min_q_mvar"] = -0.01 net.sgen["controllable"] = True net.load["controllable"] = False - net.sgen.controllable[net.sgen.bus == 4] = False - net.sgen.controllable[net.sgen.bus == 6] = False - net.sgen.controllable[net.sgen.bus == 8] = False - net.sgen.controllable[net.sgen.bus == 9] = False + net.sgen.loc[net.sgen.bus == 4, "controllable"] = False + net.sgen.loc[net.sgen.bus == 6, "controllable"] = False + net.sgen.loc[net.sgen.bus == 8, "controllable"] = False + net.sgen.loc[net.sgen.bus == 9, "controllable"] = False for sgen_idx, row in net["sgen"].iterrows(): cost_sgen = pp.create_poly_cost(net, sgen_idx, 'sgen', cp1_eur_per_mw=1.) diff --git a/pandapower/test/opf/test_pandamodels_runpm.py b/pandapower/test/opf/test_pandamodels_runpm.py index a2d7553de..7c6ef6322 100644 --- a/pandapower/test/opf/test_pandamodels_runpm.py +++ b/pandapower/test/opf/test_pandamodels_runpm.py @@ -4,6 +4,7 @@ # and Energy System Technology (IEE), Kassel. All rights reserved. import os +import io import copy from pandapower.control import ConstControl from pandapower.timeseries import DFData @@ -58,7 +59,7 @@ def create_cigre_grid_with_time_series(json_path, net=None, add_ts_constaints=Fa net.sgen.loc[8, "type"] = "wind" # read the example time series - time_series = pd.read_json(json_path) + time_series = pd.read_json(io.StringIO(json_path)) time_series.sort_index(inplace=True) # this example time series has a 15min resolution with 96 time steps for one day From 7b25a7c980ece9bf7fb0f959441a64188037532f Mon Sep 17 00:00:00 2001 From: KS_HTK Date: Thu, 28 Mar 2024 11:34:19 +0100 Subject: [PATCH 08/17] Update io_utils.py fixed call of io.StringIO --- pandapower/io_utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandapower/io_utils.py b/pandapower/io_utils.py index f16b8b68d..6df2742a6 100644 --- a/pandapower/io_utils.py +++ b/pandapower/io_utils.py @@ -489,7 +489,7 @@ def Series(self): is_multiindex = self.d.pop('is_multiindex', False) index_name = self.d.pop('index_name', None) index_names = self.d.pop('index_names', None) - ser = pd.read_json(io.StringIO(self.obj, precise_float=True, **self.d)) + ser = pd.read_json(io.StringIO(self.obj), precise_float=True, **self.d) # restore index name and Multiindex if index_name is not None: @@ -521,7 +521,7 @@ def DataFrame(self): if isinstance(obj, str): obj = StringIO(obj) - df = pd.read_json(io.StringIO(obj, precise_float=True, convert_axes=False, **self.d)) + df = pd.read_json(io.StringIO(obj), precise_float=True, convert_axes=False, **self.d) if not df.shape[0] or self.d.get("orient", False) == "columns": try: From 2cf412b0647679d4ebd9c5d3222b4e075e8af27e Mon Sep 17 00:00:00 2001 From: KS_HTK Date: Thu, 28 Mar 2024 11:54:13 +0100 Subject: [PATCH 09/17] Update test_get_equivalent.py Removed use of io.StringIO here, as this is a os.PathLike object. So io.StringIO should never have been used here. --- pandapower/test/grid_equivalents/test_get_equivalent.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pandapower/test/grid_equivalents/test_get_equivalent.py b/pandapower/test/grid_equivalents/test_get_equivalent.py index e8568e88b..6f23b2cc2 100644 --- a/pandapower/test/grid_equivalents/test_get_equivalent.py +++ b/pandapower/test/grid_equivalents/test_get_equivalent.py @@ -1,4 +1,3 @@ -import io import pytest import numpy as np import pandapower as pp @@ -500,7 +499,7 @@ def test_controller(): # load time series json_path = os.path.join(pp_dir, "test", "opf", "cigre_timeseries_15min.json") - time_series = pd.read_json(io.StringIO(json_path)) + time_series = pd.read_json(json_path) time_series.sort_index(inplace=True) sgen_p = net["sgen"].loc[:, "p_mw"].values load_p = net["load"].loc[:, "p_mw"].values @@ -634,4 +633,4 @@ def test_ward_admittance(): if __name__ == "__main__": - pytest.main(['-x', __file__]) \ No newline at end of file + pytest.main(['-x', __file__]) From fe0b267444b4de741106944879d83850b3646e5d Mon Sep 17 00:00:00 2001 From: KS_HTK Date: Thu, 28 Mar 2024 11:56:01 +0100 Subject: [PATCH 10/17] Update test_grid_equivalents_auxiliary.py Removed use of io.StringIO here, as this is a os.PathLike object. So io.StringIO should never have been used here. --- .../test/grid_equivalents/test_grid_equivalents_auxiliary.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py b/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py index 9a41b960a..cf3a22478 100644 --- a/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py +++ b/pandapower/test/grid_equivalents/test_grid_equivalents_auxiliary.py @@ -1,4 +1,3 @@ -import io import pytest import os import pandapower as pp @@ -70,7 +69,7 @@ def test_drop_measurements_and_controllers(): # create controllers json_path = os.path.join(pp_dir, "test", "opf", "cigre_timeseries_15min.json") - time_series = pd.read_json(io.StringIO(json_path)) + time_series = pd.read_json(json_path) load_ts = pd.DataFrame(index=time_series.index.tolist(), columns=net.load.index.tolist()) gen_ts = pd.DataFrame(index=time_series.index.tolist(), columns=net.gen.index.tolist()) for t in range(96): @@ -128,4 +127,4 @@ def test_check_network(): # test_check_validity() # test_trafo_phase_shifter() # test_check_validity() - pass \ No newline at end of file + pass From 0282c5b1be1158ad371e9981ff83cc1d10fb1015 Mon Sep 17 00:00:00 2001 From: KS_HTK Date: Thu, 28 Mar 2024 12:02:22 +0100 Subject: [PATCH 11/17] Update test_pandamodels_runpm.py Removed use of io.StringIO here, as this is a os.PathLike object. So io.StringIO should never have been used here. --- pandapower/test/opf/test_pandamodels_runpm.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pandapower/test/opf/test_pandamodels_runpm.py b/pandapower/test/opf/test_pandamodels_runpm.py index 59e4d7b6d..85f9c7a3d 100644 --- a/pandapower/test/opf/test_pandamodels_runpm.py +++ b/pandapower/test/opf/test_pandamodels_runpm.py @@ -4,7 +4,6 @@ # and Energy System Technology (IEE), Kassel. All rights reserved. import os -import io import copy from pandapower.control import ConstControl from pandapower.timeseries import DFData @@ -59,7 +58,7 @@ def create_cigre_grid_with_time_series(json_path, net=None, add_ts_constaints=Fa net.sgen.loc[8, "type"] = "wind" # read the example time series - time_series = pd.read_json(io.StringIO(json_path)) + time_series = pd.read_json(json_path) time_series.sort_index(inplace=True) # this example time series has a 15min resolution with 96 time steps for one day From 978d63402e01617af1243e82a07b3ede09e3066c Mon Sep 17 00:00:00 2001 From: KS_HTK Date: Thu, 28 Mar 2024 12:09:19 +0100 Subject: [PATCH 12/17] Update io_utils.py Removed use of io.StringIO if obj is not str here, as this is sometimes a os.PathLike object. --- pandapower/io_utils.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/pandapower/io_utils.py b/pandapower/io_utils.py index 6df2742a6..cb32dfaf7 100644 --- a/pandapower/io_utils.py +++ b/pandapower/io_utils.py @@ -8,7 +8,6 @@ import json import numbers import os -import io import pickle import sys import types @@ -480,7 +479,7 @@ class FromSerializableRegistry(): module_name = '' def __init__(self, obj, d, pp_hook_funct): - self.obj = obj + self.obj = StringIO(obj) if isinstance(obj, str) else obj self.d = d self.pp_hook = pp_hook_funct @@ -489,7 +488,7 @@ def Series(self): is_multiindex = self.d.pop('is_multiindex', False) index_name = self.d.pop('index_name', None) index_names = self.d.pop('index_names', None) - ser = pd.read_json(io.StringIO(self.obj), precise_float=True, **self.d) + ser = pd.read_json(self.obj, precise_float=True, **self.d) # restore index name and Multiindex if index_name is not None: @@ -517,11 +516,9 @@ def DataFrame(self): column_name = self.d.pop('column_name', None) column_names = self.d.pop('column_names', None) - obj = self.obj - if isinstance(obj, str): - obj = StringIO(obj) + obj = StringIO(obj) if isinstance(obj, str) else self.obj - df = pd.read_json(io.StringIO(obj), precise_float=True, convert_axes=False, **self.d) + df = pd.read_json(obj, precise_float=True, convert_axes=False, **self.d) if not df.shape[0] or self.d.get("orient", False) == "columns": try: From b526a00148c7f5150ed97a76b59b2432e2c1d2e6 Mon Sep 17 00:00:00 2001 From: KS_HTK Date: Thu, 28 Mar 2024 12:13:45 +0100 Subject: [PATCH 13/17] Update io_utils.py fixed minor issue in assignments --- pandapower/io_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandapower/io_utils.py b/pandapower/io_utils.py index cb32dfaf7..670f9e87e 100644 --- a/pandapower/io_utils.py +++ b/pandapower/io_utils.py @@ -516,7 +516,7 @@ def DataFrame(self): column_name = self.d.pop('column_name', None) column_names = self.d.pop('column_names', None) - obj = StringIO(obj) if isinstance(obj, str) else self.obj + obj = StringIO(self.obj) if isinstance(obj, str) else self.obj df = pd.read_json(obj, precise_float=True, convert_axes=False, **self.d) From 9b46e1a37b874c86a68d373a212c0a8f8969e334 Mon Sep 17 00:00:00 2001 From: KS_HTK Date: Thu, 28 Mar 2024 12:17:01 +0100 Subject: [PATCH 14/17] Update io_utils.py fixed isinstance check on unbound var --- pandapower/io_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandapower/io_utils.py b/pandapower/io_utils.py index 670f9e87e..fa1987dd1 100644 --- a/pandapower/io_utils.py +++ b/pandapower/io_utils.py @@ -516,7 +516,7 @@ def DataFrame(self): column_name = self.d.pop('column_name', None) column_names = self.d.pop('column_names', None) - obj = StringIO(self.obj) if isinstance(obj, str) else self.obj + obj = StringIO(self.obj) if isinstance(self.obj, str) else self.obj df = pd.read_json(obj, precise_float=True, convert_axes=False, **self.d) From b002fc58ac89a51e8392c571f8e5bbb6f65de2f5 Mon Sep 17 00:00:00 2001 From: hkoertge Date: Thu, 28 Mar 2024 13:53:27 +0100 Subject: [PATCH 15/17] fixed issue in io_utils usage of StringIO on non fileLikes fixed issue in test_cost_consistency.py --- pandapower/io_utils.py | 7 ++----- pandapower/test/opf/test_cost_consistency.py | 4 +++- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/pandapower/io_utils.py b/pandapower/io_utils.py index fa1987dd1..ae1ccab5d 100644 --- a/pandapower/io_utils.py +++ b/pandapower/io_utils.py @@ -8,7 +8,6 @@ import json import numbers import os -import pickle import sys import types import weakref @@ -21,10 +20,8 @@ from deepdiff.diff import DeepDiff from packaging.version import Version from pandapower import __version__ -from pandapower.auxiliary import _preserve_dtypes import networkx import numpy -from io import StringIO import pandas as pd from networkx.readwrite import json_graph from numpy import ndarray, generic, equal, isnan, allclose, any as anynp @@ -479,7 +476,7 @@ class FromSerializableRegistry(): module_name = '' def __init__(self, obj, d, pp_hook_funct): - self.obj = StringIO(obj) if isinstance(obj, str) else obj + self.obj = obj self.d = d self.pp_hook = pp_hook_funct @@ -516,7 +513,7 @@ def DataFrame(self): column_name = self.d.pop('column_name', None) column_names = self.d.pop('column_names', None) - obj = StringIO(self.obj) if isinstance(self.obj, str) else self.obj + obj = self.obj df = pd.read_json(obj, precise_float=True, convert_axes=False, **self.d) diff --git a/pandapower/test/opf/test_cost_consistency.py b/pandapower/test/opf/test_cost_consistency.py index 40142bb0b..7aa08990c 100644 --- a/pandapower/test/opf/test_cost_consistency.py +++ b/pandapower/test/opf/test_cost_consistency.py @@ -1,6 +1,7 @@ import pandapower as pp import pytest from numpy import array, isclose +import pandas as pd @pytest.fixture() def base_net(): @@ -47,7 +48,8 @@ def test_contingency_sgen(base_net): # p_min_mw |\ # | \ # | \ - net.pwl_cost.loc[pwl, "points"] = [(0, net.sgen.max_p_mw.at[0], -1)] + + net.pwl_cost.points.loc[pwl] = [(0, net.sgen.max_p_mw.at[0], -1)] pp.runopp(net) assert isclose(net.res_cost, -net.res_sgen.p_mw.at[0], atol=1e-4) From e30f52082f4c74cfb5d6e98486fe7f9a6a4e6102 Mon Sep 17 00:00:00 2001 From: Roman Bolgaryn Date: Thu, 28 Mar 2024 14:24:21 +0100 Subject: [PATCH 16/17] enable --- CHANGELOG.rst | 1 + pandapower/plotting/generic_geodata.py | 22 +++++++++------ pandapower/topology/create_graph.py | 39 +++++++++++++++++--------- 3 files changed, 39 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 1229bce85..8c5751751 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,6 +3,7 @@ Change Log [upcoming release] - 2024-..-.. ------------------------------- +- [CHANGED] added possibility to provide custom weights to switches and transformers (before - always zero) when creating a graph [2.14.4] - 2024-03-28 ------------------------------- diff --git a/pandapower/plotting/generic_geodata.py b/pandapower/plotting/generic_geodata.py index 1508b7986..c2bac3fa2 100644 --- a/pandapower/plotting/generic_geodata.py +++ b/pandapower/plotting/generic_geodata.py @@ -27,7 +27,7 @@ logger = logging.getLogger(__name__) -def build_igraph_from_pp(net, respect_switches=False, buses=None): +def build_igraph_from_pp(net, respect_switches=False, buses=None, trafo_length_km=0.01, switch_length_km=0.001): """ This function uses the igraph library to create an igraph graph for a given pandapower network. Lines, transformers and switches are respected. @@ -68,7 +68,7 @@ def build_igraph_from_pp(net, respect_switches=False, buses=None): mask &= _get_switch_mask(net, "trafo", "t", open_switches) for trafo in net.trafo[mask].itertuples(): g.add_edge(pp_bus_mapping[trafo.hv_bus], - pp_bus_mapping[trafo.lv_bus], weight=0.01) + pp_bus_mapping[trafo.lv_bus], weight=trafo_length_km) # add trafo3w mask = _get_element_mask_from_nodes(net, "trafo3w", ["hv_bus", "mv_bus", "lv_bus"], buses) @@ -76,9 +76,9 @@ def build_igraph_from_pp(net, respect_switches=False, buses=None): mask &= _get_switch_mask(net, "trafo3w", "t3", open_switches) for trafo3w in net.trafo3w[mask].itertuples(): g.add_edge(pp_bus_mapping[trafo3w.hv_bus], - pp_bus_mapping[trafo3w.lv_bus], weight=0.01) + pp_bus_mapping[trafo3w.lv_bus], weight=trafo_length_km) g.add_edge(pp_bus_mapping[trafo3w.hv_bus], - pp_bus_mapping[trafo3w.mv_bus], weight=0.01) + pp_bus_mapping[trafo3w.mv_bus], weight=trafo_length_km) # add switches mask = net.switch.et.values == "b" @@ -87,7 +87,7 @@ def build_igraph_from_pp(net, respect_switches=False, buses=None): bus_mask = _get_element_mask_from_nodes(net, "switch", ["element", "bus"], buses) for switch in net.switch[mask & bus_mask].itertuples(): g.add_edge(pp_bus_mapping[switch.element], - pp_bus_mapping[switch.bus], weight=0.001) + pp_bus_mapping[switch.bus], weight=switch_length_km) meshed = _igraph_meshed(g) @@ -156,7 +156,7 @@ def coords_from_nxgraph(mg=None, layout_engine='neato'): for u, v in mg.edges(data=False): if 'key' in mg[int(u)][int(v)]: del mg[int(u)][int(v)]['key'] - if 'key' in mg[int(u)][int(v)][0]: + if 'key' in mg[int(u)][int(v)].get(0, ()): del mg[int(u)][int(v)][0]['key'] # ToDo: Insert fallback layout for nxgraph return list(zip(*(list(nx.drawing.nx_agraph.graphviz_layout(mg, prog=layout_engine).values())))) @@ -167,7 +167,9 @@ def create_generic_coordinates(net, mg=None, library="igraph", geodata_table="bus_geodata", buses=None, overwrite=False, - layout_engine='neato'): + layout_engine='neato', + trafo_length_km=0.01, + switch_length_km=0.001): """ This function will add arbitrary geo-coordinates for all buses based on an analysis of branches and rings. It will remove out of service buses/lines from the net. The coordinates will be @@ -199,12 +201,14 @@ def create_generic_coordinates(net, mg=None, library="igraph", if library == "igraph": if not IGRAPH_INSTALLED: soft_dependency_error("build_igraph_from_pp()", "igraph") - graph, meshed, roots = build_igraph_from_pp(net, respect_switches, buses=buses) + graph, meshed, roots = build_igraph_from_pp(net, respect_switches, buses=buses, + trafo_length_km=trafo_length_km, switch_length_km=switch_length_km) coords = coords_from_igraph(graph, roots, meshed) elif library == "networkx": if mg is None: nxg = top.create_nxgraph(net, respect_switches=respect_switches, - include_out_of_service=True) + include_out_of_service=True, + trafo_length_km=trafo_length_km, switch_length_km=switch_length_km) else: nxg = copy.deepcopy(mg) coords = coords_from_nxgraph(nxg, layout_engine=layout_engine) diff --git a/pandapower/topology/create_graph.py b/pandapower/topology/create_graph.py index f4d2a4abc..23bdd2c6a 100644 --- a/pandapower/topology/create_graph.py +++ b/pandapower/topology/create_graph.py @@ -44,7 +44,8 @@ def create_nxgraph(net, respect_switches=True, include_lines=True, include_imped include_dclines=True, include_trafos=True, include_trafo3ws=True, include_tcsc=True, nogobuses=None, notravbuses=None, multi=True, calc_branch_impedances=False, branch_impedance_unit="ohm", - library="networkx", include_out_of_service=False): + library="networkx", include_out_of_service=False, + include_switches=True, trafo_length_km=None, switch_length_km=None): """ Converts a pandapower network into a NetworkX graph, which is a is a simplified representation of a network's topology, reduced to nodes and edges. Busses are being represented by nodes @@ -206,6 +207,9 @@ def create_nxgraph(net, respect_switches=True, include_lines=True, include_imped indices[:, F_BUS] = trafo.hv_bus.values indices[:, T_BUS] = trafo.lv_bus.values + if trafo_length_km is not None: + parameter[:, WEIGHT] = trafo_length_km + if respect_switches: mask = (net.switch.et.values == "t") & open_sw if mask.any(): @@ -247,6 +251,10 @@ def create_nxgraph(net, respect_switches=True, include_lines=True, include_imped indices, parameter, in_service = init_par(trafo3w, calc_branch_impedances) indices[:, F_BUS] = trafo3w["%s_bus" % f].values indices[:, T_BUS] = trafo3w["%s_bus" % t].values + + if trafo_length_km is not None: + parameter[:, WEIGHT] = trafo_length_km + if respect_switches and len(open_trafo3w): for BUS in [F_BUS, T_BUS]: open_switch = np.in1d(indices[:, INDEX] + indices[:, BUS] * 1j, @@ -258,19 +266,22 @@ def create_nxgraph(net, respect_switches=True, include_lines=True, include_imped add_edges(mg, indices, parameter, in_service, net, "trafo3w", calc_branch_impedances, branch_impedance_unit) - switch = net.switch - if len(switch): - if respect_switches: - # add edges for closed bus-bus switches - in_service = (switch.et.values == "b") & ~open_sw - else: - # add edges for any bus-bus switches - in_service = (switch.et.values == "b") - indices, parameter = init_par(switch, calc_branch_impedances) - indices[:, F_BUS] = switch.bus.values - indices[:, T_BUS] = switch.element.values - add_edges(mg, indices, parameter, in_service, net, "switch", - calc_branch_impedances, branch_impedance_unit) + if include_switches: + switch = net.switch + if len(switch): + if respect_switches: + # add edges for closed bus-bus switches + in_service = (switch.et.values == "b") & ~open_sw + else: + # add edges for any bus-bus switches + in_service = (switch.et.values == "b") + indices, parameter = init_par(switch, calc_branch_impedances) + indices[:, F_BUS] = switch.bus.values + indices[:, T_BUS] = switch.element.values + if switch_length_km is not None: + parameter[:, WEIGHT] = switch_length_km + add_edges(mg, indices, parameter, in_service, net, "switch", + calc_branch_impedances, branch_impedance_unit) # add all buses that were not added when creating branches if len(mg.nodes()) < len(net.bus.index): From 72b7872597fb1ff35eaf9ce298a3abda80fce7f3 Mon Sep 17 00:00:00 2001 From: mvogt Date: Thu, 28 Mar 2024 14:28:15 +0100 Subject: [PATCH 17/17] bump version. --- CHANGELOG.rst | 4 ++++ setup.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 8c5751751..4822b45c9 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,7 +3,11 @@ Change Log [upcoming release] - 2024-..-.. ------------------------------- + +[2.14.5] - 2024-03-28 +------------------------------- - [CHANGED] added possibility to provide custom weights to switches and transformers (before - always zero) when creating a graph +- [FIXED] many futurewarnings and deprecation warnings [2.14.4] - 2024-03-28 ------------------------------- diff --git a/setup.py b/setup.py index 74614bb0a..6a98b2c13 100644 --- a/setup.py +++ b/setup.py @@ -34,7 +34,7 @@ setup( name='pandapower', - version='2.14.4', + version='2.14.5', author='Leon Thurner, Alexander Scheidler', author_email='leon.thurner@retoflow.de, alexander.scheidler@iee.fraunhofer.de', description='An easy to use open source tool for power system modeling, analysis and optimization with a high degree of automation.',