Skip to content

Commit

Permalink
Wip
Browse files Browse the repository at this point in the history
Signed-off-by: Geoffroy Jamgotchian <geoffroy.jamgotchian@rte-france.com>
  • Loading branch information
geofjamg committed Sep 22, 2023
1 parent 17bcb42 commit aefbb2e
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 72 deletions.
20 changes: 10 additions & 10 deletions cpp/src/pypowsybl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1462,43 +1462,43 @@ JavaHandle createVoltageLimitOverride(double minVoltage, double maxVoltage) {
}

void voltageInitializerAddSpecificVoltageLimits(const std::string& idPtr, double minVoltage, const JavaHandle& paramsHandle, double maxVoltage) {
pypowsybl::callJava(::VoltageInitializerAddSpecificVoltageLimits, (char*) idPtr.c_str(), minVoltage, paramsHandle, maxVoltage);
pypowsybl::callJava(::voltageInitializerAddSpecificVoltageLimits, (char*) idPtr.c_str(), minVoltage, paramsHandle, maxVoltage);
}

void voltageInitializerAddVariableShuntCompensators(const JavaHandle& paramsHandle, const std::string& idPtr) {
pypowsybl::callJava(::VoltageInitializerAddVariableShuntCompensators, paramsHandle, (char*) idPtr.c_str());
pypowsybl::callJava(::voltageInitializerAddVariableShuntCompensators, paramsHandle, (char*) idPtr.c_str());
}

void voltageInitializerAddConstantQGenerators(const JavaHandle& paramsHandle, const std::string& idPtr) {
pypowsybl::callJava(::VoltageInitializerAddConstantQGenerators, paramsHandle, (char*) idPtr.c_str());
pypowsybl::callJava(::voltageInitializerAddConstantQGenerators, paramsHandle, (char*) idPtr.c_str());
}

void voltageInitializerAddVariableTwoWindingsTransformers(const JavaHandle& paramsHandle, const std::string& idPtr) {
pypowsybl::callJava(::VoltageInitializerAddVariableTwoWindingsTransformers, paramsHandle, (char*) idPtr.c_str());
pypowsybl::callJava(::voltageInitializerAddVariableTwoWindingsTransformers, paramsHandle, (char*) idPtr.c_str());
}

void voltageInitializerAddAlgorithmParam(const JavaHandle& paramsHandle, const std::string& keyPtr, const std::string& valuePtr) {
pypowsybl::callJava(::VoltageInitializerAddAlgorithmParam, paramsHandle, (char*) keyPtr.c_str(), (char*) valuePtr.c_str());
pypowsybl::callJava(::voltageInitializerAddAlgorithmParam, paramsHandle, (char*) keyPtr.c_str(), (char*) valuePtr.c_str());
}

void voltageInitializerSetObjective(const JavaHandle& paramsHandle, VoltageInitializerObjective cObjective) {
pypowsybl::callJava(::VoltageInitializerSetObjective, paramsHandle, cObjective);
pypowsybl::callJava(::voltageInitializerSetObjective, paramsHandle, cObjective);
}

void voltageInitializerSetObjectiveDistance(const JavaHandle& paramsHandle, double dist) {
pypowsybl::callJava(::VoltageInitializerSetObjectiveDistance, paramsHandle, dist);
pypowsybl::callJava(::voltageInitializerSetObjectiveDistance, paramsHandle, dist);
}

void voltageInitializerApplyAllModifications(const JavaHandle& resultHandle, const JavaHandle& networkHandle) {
pypowsybl::callJava(::VoltageInitializerApplyAllModifications, resultHandle, networkHandle);
pypowsybl::callJava(::voltageInitializerApplyAllModifications, resultHandle, networkHandle);
}

VoltageInitializerStatus voltageInitializerGetStatus(const JavaHandle& resultHandle) {
return pypowsybl::callJava<VoltageInitializerStatus>(::VoltageInitializerGetStatus, resultHandle);
return pypowsybl::callJava<VoltageInitializerStatus>(::voltageInitializerGetStatus, resultHandle);
}

std::map<std::string, std::string> voltageInitializerGetIndicators(const JavaHandle& resultHandle) {
string_map* indicators = pypowsybl::callJava<string_map*>(::VoltageInitializerGetIndicators, resultHandle);
string_map* indicators = pypowsybl::callJava<string_map*>(::voltageInitializerGetIndicators, resultHandle);
return convertMapStructToStdMap(indicators);
}

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ of pypowsybl classes and methods.
flowdecomposition
dynamic
shortcircuit
voltage_initialization
voltage_initializer
File renamed without changes.
7 changes: 2 additions & 5 deletions docs/user_guide/voltage_initializer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,17 @@ Here is a simple starting example:
import pypowsybl as pp
import pypowsybl.voltage_initializer as v_init
params = voltage_initializer.VoltageInitializerParameters()
params = v_init.VoltageInitializerParameters()
n = pp.network.create_eurostag_tutorial_example1_network()
some_gen_id = n.get_generators().iloc[0].name
params.add_constant_q_generators([some_gen_id])
# no shunts in eurostag_tutorial_example1_network
# some_shunt_id = n.get_shunt_compensators().iloc[0].name
# params.add_variable_shunt_compensators([n.get_shunt_compensators().iloc[0].name])
some_2wt_id = n.get_2_windings_transformers().iloc[0].name
params.add_variable_two_windings_transformers([some_2wt_id])
params.add_algorithm_param({"foo": "bar", "bar": "bar2"})
params.set_objective(VoltageInitializerObjective.SPECIFIC_VOLTAGE_PROFILE)
results = voltage_initializer.run(n, params, True)
results = v_init.run(n, params)
results.apply_all_modification(n)
print(results.status())
Expand Down
8 changes: 5 additions & 3 deletions java/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<parent>
<groupId>com.powsybl</groupId>
<artifactId>powsybl-parent</artifactId>
<version>11</version>
<version>14</version>
<relativePath/>
</parent>

Expand Down Expand Up @@ -61,13 +61,15 @@
<version>0.25.0-SNAPSHOT</version>

<properties>
<java.version>17</java.version>
<commons-collections4.version>4.4</commons-collections4.version>
<graalvm.version>23.0.0</graalvm.version>
<janino.version>3.1.0</janino.version>
<junit-jupiter.version>5.5.2</junit-jupiter.version>
<mapdb.version>3.0.8</mapdb.version>
<maven-dependency-plugin.version>3.2.0</maven-dependency-plugin.version>
<maven-dependency-plugin.version>3.6.0</maven-dependency-plugin.version>
<powsybl-dependencies.version>2023.2.4</powsybl-dependencies.version>
<powsybl-open-reac.version>0.2.0</powsybl-open-reac.version>
<zstdjni.version>1.5.2-5</zstdjni.version>
</properties>

Expand Down Expand Up @@ -363,7 +365,7 @@
<dependency>
<groupId>com.powsybl</groupId>
<artifactId>powsybl-open-reac</artifactId>
<version>0.2.0</version>
<version>${powsybl-open-reac.version}</version>
</dependency>

<!-- test -->
Expand Down
24 changes: 8 additions & 16 deletions java/src/main/java/com/powsybl/python/commons/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.powsybl.iidm.network.Branch;
import com.powsybl.iidm.network.ValidationLevel;
import com.powsybl.openreac.parameters.input.algo.OpenReacOptimisationObjective;
import com.powsybl.openreac.parameters.output.OpenReacStatus;
import com.powsybl.python.commons.PyPowsyblApiHeader.ArrayPointer;
import com.powsybl.python.commons.PyPowsyblApiHeader.VoltageInitializerObjective;
import com.powsybl.python.commons.PyPowsyblApiHeader.VoltageInitializerStatus;
Expand Down Expand Up @@ -386,25 +387,16 @@ public static DataframeNetworkModificationType convert(PyPowsyblApiHeader.Networ
}
}

public static VoltageInitializerStatus convert(com.powsybl.openreac.parameters.output.OpenReacStatus obj) {
if (com.powsybl.openreac.parameters.output.OpenReacStatus.OK.equals(obj)) {
return VoltageInitializerStatus.OK;
} else {
return VoltageInitializerStatus.NOT_OK;
}
public static VoltageInitializerStatus convert(OpenReacStatus status) {
return status == OpenReacStatus.OK ? VoltageInitializerStatus.OK : VoltageInitializerStatus.NOT_OK;
}

public static OpenReacOptimisationObjective convert(VoltageInitializerObjective obj) {
switch (obj) {
case MIN_GENERATION:
return OpenReacOptimisationObjective.MIN_GENERATION;
case BETWEEN_HIGH_AND_LOW_VOLTAGE_LIMIT:
return OpenReacOptimisationObjective.BETWEEN_HIGH_AND_LOW_VOLTAGE_LIMIT;
case SPECIFIC_VOLTAGE_PROFILE:
return OpenReacOptimisationObjective.SPECIFIC_VOLTAGE_PROFILE;
default:
throw new PowsyblException("Unknown VoltageInitializerObjective type: " + obj);
}
return switch (obj) {
case MIN_GENERATION -> OpenReacOptimisationObjective.MIN_GENERATION;
case BETWEEN_HIGH_AND_LOW_VOLTAGE_LIMIT -> OpenReacOptimisationObjective.BETWEEN_HIGH_AND_LOW_VOLTAGE_LIMIT;
case SPECIFIC_VOLTAGE_PROFILE -> OpenReacOptimisationObjective.SPECIFIC_VOLTAGE_PROFILE;
};
}

public static byte[] binaryBufferToBytes(ByteBuffer buffer) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ static VoltageLevelFilter getNominalVoltageFilter(Network network, List<String>
if (vl == null) {
throw new PowsyblException("Unknown voltage level id '" + voltageLevelId + "'");
}
if ((lowNominalVoltageBound > 0 && vl.getNominalV() < lowNominalVoltageBound) ||
(highNominalVoltageBound > 0 && vl.getNominalV() > highNominalVoltageBound)) {
if (lowNominalVoltageBound > 0 && vl.getNominalV() < lowNominalVoltageBound ||
highNominalVoltageBound > 0 && vl.getNominalV() > highNominalVoltageBound) {
throw new PowsyblException("vl '" + voltageLevelId +
"' has his nominal voltage out of the indicated thresholds");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,7 @@ public static void addMonitoredElements(IsolateThread thread, ObjectHandle secur
SecurityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(securityAnalysisContextHandle);
List<String> contingencies = toStringList(contingencyIds, contingencyIdsCount);
contingencies.forEach(contingency -> {
if (contingency.equals("")) {
contingency = null;
}
analysisContext.addMonitor(new StateMonitor(new ContingencyContext(contingency, convert(contingencyContextType)),
analysisContext.addMonitor(new StateMonitor(new ContingencyContext(contingency.isEmpty() ? null : contingency, convert(contingencyContextType)),
Set.copyOf(toStringList(branchIds, branchIdsCount)), Set.copyOf(toStringList(voltageLevelIds, voltageLevelIdCount)),
Set.copyOf(toStringList(threeWindingsTransformerIds, threeWindingsTransformerIdsCount))));
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2020-2023, RTE (http://www.rte-france.com)
* Copyright (c) 2023, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
Expand Down Expand Up @@ -61,7 +61,7 @@ public static ObjectHandle createVoltageLimitOverride(IsolateThread thread, doub
() -> ObjectHandles.getGlobal().create(new VoltageLimitOverride(minVoltage, maxVoltage)));
}

@CEntryPoint(name = "VoltageInitializerAddSpecificVoltageLimits")
@CEntryPoint(name = "voltageInitializerAddSpecificVoltageLimits")
public static void addSpecificVoltageLimits(IsolateThread thread, CCharPointer idPtr, double minVoltage,
ObjectHandle paramsHandle, double maxVoltage,
PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
Expand All @@ -71,68 +71,68 @@ public static void addSpecificVoltageLimits(IsolateThread thread, CCharPointer i
.addSpecificVoltageLimits(Map.of(voltageId, new VoltageLimitOverride(minVoltage, maxVoltage))));
}

@CEntryPoint(name = "VoltageInitializerAddVariableShuntCompensators")
@CEntryPoint(name = "voltageInitializerAddVariableShuntCompensators")
public static void addVariableShuntCompensators(IsolateThread thread, ObjectHandle paramsHandle,
CCharPointer idPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);
String id = CTypeUtil.toString(idPtr);
doCatch(exceptionHandlerPtr, () -> params.addVariableShuntCompensators(List.of(id)));
}

@CEntryPoint(name = "VoltageInitializerAddConstantQGenerators")
@CEntryPoint(name = "voltageInitializerAddConstantQGenerators")
public static void addConstantQGenerators(IsolateThread thread, ObjectHandle paramsHandle,
CCharPointer idPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);
String id = CTypeUtil.toString(idPtr);
doCatch(exceptionHandlerPtr, () -> params.addConstantQGenerators(List.of(id)));
}

@CEntryPoint(name = "VoltageInitializerAddVariableTwoWindingsTransformers")
@CEntryPoint(name = "voltageInitializerAddVariableTwoWindingsTransformers")
public static void addVariableTwoWindingsTransformers(IsolateThread thread, ObjectHandle paramsHandle,
CCharPointer idPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);
String id = CTypeUtil.toString(idPtr);
doCatch(exceptionHandlerPtr, () -> params.addVariableTwoWindingsTransformers(List.of(id)));
}

@CEntryPoint(name = "VoltageInitializerAddAlgorithmParam")
@CEntryPoint(name = "voltageInitializerAddAlgorithmParam")
public static void addAlgorithmParam(IsolateThread thread, ObjectHandle paramsHandle, CCharPointer keyPtr,
CCharPointer valuePtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);
doCatch(exceptionHandlerPtr,
() -> params.addAlgorithmParam(CTypeUtil.toString(keyPtr), CTypeUtil.toString(valuePtr)));
}

@CEntryPoint(name = "VoltageInitializerSetObjective")
@CEntryPoint(name = "voltageInitializerSetObjective")
public static void setObjective(IsolateThread thread, ObjectHandle paramsHandle,
VoltageInitializerObjective cObjective, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);
doCatch(exceptionHandlerPtr, () -> params.setObjective(Util.convert(cObjective)));
}

@CEntryPoint(name = "VoltageInitializerSetObjectiveDistance")
@CEntryPoint(name = "voltageInitializerSetObjectiveDistance")
public static void setObjectiveDistance(IsolateThread thread, ObjectHandle paramsHandle, double dist,
PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);
doCatch(exceptionHandlerPtr, () -> params.setObjectiveDistance(dist));
}

@CEntryPoint(name = "VoltageInitializerApplyAllModifications")
@CEntryPoint(name = "voltageInitializerApplyAllModifications")
public static void applyAllModifications(IsolateThread thread, ObjectHandle resultHandle,
ObjectHandle networkHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacResult result = ObjectHandles.getGlobal().get(resultHandle);
Network network = ObjectHandles.getGlobal().get(networkHandle);
doCatch(exceptionHandlerPtr, () -> result.applyAllModifications(network));
}

@CEntryPoint(name = "VoltageInitializerGetStatus")
@CEntryPoint(name = "voltageInitializerGetStatus")
public static VoltageInitializerStatus getStatus(IsolateThread thread, ObjectHandle resultHandle,
PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacResult result = ObjectHandles.getGlobal().get(resultHandle);
return doCatch(exceptionHandlerPtr, () -> Util.convert(result.getStatus()));
}

@CEntryPoint(name = "VoltageInitializerGetIndicators")
@CEntryPoint(name = "voltageInitializerGetIndicators")
public static StringMap getIndicators(IsolateThread thread, ObjectHandle resultHandle,
PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
OpenReacResult result = ObjectHandles.getGlobal().get(resultHandle);
Expand All @@ -142,14 +142,17 @@ public static StringMap getIndicators(IsolateThread thread, ObjectHandle resultH
@CEntryPoint(name = "runVoltageInitializer")
public static ObjectHandle runVoltageInitializer(IsolateThread thread, boolean debug, ObjectHandle networkHandle,
ObjectHandle paramsHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) {
Network network = ObjectHandles.getGlobal().get(networkHandle);
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);
return Util.doCatch(exceptionHandlerPtr, () -> {
Network network = ObjectHandles.getGlobal().get(networkHandle);
OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle);

logger().info("Running voltage initializer");
OpenReacResult result = OpenReacRunner.run(network, network.getVariantManager().getWorkingVariantId(), params,
new OpenReacConfig(debug), LocalComputationManager.getDefault());
logger().info("Voltage initializer run done");

logger().info("Launching an VoltageInitializer run");
OpenReacResult result = OpenReacRunner.run(network, network.getVariantManager().getWorkingVariantId(), params,
new OpenReacConfig(debug), LocalComputationManager.getDefault());
logger().info("VoltageInitializer run done.");
return ObjectHandles.getGlobal().create(result);
return ObjectHandles.getGlobal().create(result);
});
}

}
2 changes: 2 additions & 0 deletions pypowsybl/voltage_initializer/impl/voltage_initializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ def apply_all_modifications(self, network: Network) -> None:
'''
voltage_initializer_apply_all_modifications(self._handle, network._handle)

@property
def status(self) -> VoltageInitializerStatus:
'''
If the optimisation failed, it can be useful to check the indicators.
Expand All @@ -131,6 +132,7 @@ def status(self) -> VoltageInitializerStatus:
'''
return self._status

@property
def indicators(self) -> Dict[str, str]:
'''
Returns:
Expand Down
21 changes: 8 additions & 13 deletions tests/test_voltage_initializer.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
#
# Copyright (c) 2020-2022, RTE (http://www.rte-france.com)
# Copyright (c) 2023, RTE (http://www.rte-france.com)
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
import pypowsybl as pp
import pypowsybl.voltage_initializer as va
import pytest
Expand All @@ -19,30 +17,27 @@ def test_parameters():
params.add_variable_two_windings_transformers(["twt1", "twt2"])

params.add_algorithm_param({"foo": "bar", "bar": "bar2"})
params.add_specific_voltage_limits({"vl_id": (0.5,1.2)})
params.add_specific_voltage_limits({"vl_id": (0.5, 1.2)})

params.set_objective(va.VoltageInitializerObjective.SPECIFIC_VOLTAGE_PROFILE)
params.set_objective_distance(1.3)


@pytest.mark.skip(reason="CI doesn't have a Ampl and Knitro runtime.")
def test_runner():
from pypowsybl import network, voltage_initializer as va
params = va.VoltageInitializerParameters()
from pypowsybl import network, voltage_initializer as v_init
params = v_init.VoltageInitializerParameters()
n = network.create_eurostag_tutorial_example1_network()
some_gen_id = n.get_generators().iloc[0].name
params.add_constant_q_generators([some_gen_id])
# no shunts in eurostag_tutorial_example1_network
# some_shunt_id = n.get_shunt_compensators().iloc[0].name
# params.add_variable_shunt_compensators([n.get_shunt_compensators().iloc[0].name])
some_2wt_id = n.get_2_windings_transformers().iloc[0].name
params.add_variable_two_windings_transformers([some_2wt_id])

params.add_algorithm_param({"foo": "bar", "bar": "bar2"})
params.set_objective(va.VoltageInitializerObjective.SPECIFIC_VOLTAGE_PROFILE)
params.set_objective(v_init.VoltageInitializerObjective.SPECIFIC_VOLTAGE_PROFILE)

results = va.run(n, params, True)
results = v_init.run(n, params, True)
results.apply_all_modifications(n)

print(results.status())
print(results.indicators())
assert results.status == v_init.VoltageInitializerStatus.OK
assert len(results.indicators) == 78

0 comments on commit aefbb2e

Please sign in to comment.