diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index fcd3f8027b..189b15c28f 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -76,7 +76,7 @@ ExternalProject_Add(native-image DEPENDS mvn SOURCE_DIR ${PYPOWSYBL_JAVA_BIN_DIR} DOWNLOAD_COMMAND "" - PATCH_COMMAND $ENV{JAVA_HOME}/bin/native-image ${NATIVE_IMAGE_BUILD_OPTIONS} --class-path ${PYPOWSYBL_JAVA_SRC_DIR}/target/pypowsybl-java.jar${EXTRA_JARS} -march=compatibility --no-fallback --shared --gc=${NATIVE_IMAGE_GC} -o pypowsybl-java -H:CLibraryPath=${CMAKE_CURRENT_SOURCE_DIR}/src --add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.core.c=ALL-UNNAMED + PATCH_COMMAND $ENV{JAVA_HOME}/bin/native-image ${NATIVE_IMAGE_BUILD_OPTIONS} --class-path ${PYPOWSYBL_JAVA_SRC_DIR}/target/pypowsybl-java.jar${EXTRA_JARS} -march=compatibility --no-fallback --shared --gc=${NATIVE_IMAGE_GC} -o pypowsybl-java -H:CLibraryPath=${CMAKE_CURRENT_SOURCE_DIR}/src CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND ${CMAKE_COMMAND} -E copy ${PYPOWSYBL_JAVA_BIN_DIR}/${PYPOWSYBL_JAVA_OLD_LIB} ${PYPOWSYBL_JAVA_BIN_DIR}/${PYPOWSYBL_JAVA_LIB} ${NATIVE_IMAGE_INSTALL_EXTRA_COMMAND} diff --git a/java/src/main/java/com/powsybl/python/commons/CommonCFunctions.java b/java/src/main/java/com/powsybl/python/commons/CommonCFunctions.java index f959f89849..1b43ab390d 100644 --- a/java/src/main/java/com/powsybl/python/commons/CommonCFunctions.java +++ b/java/src/main/java/com/powsybl/python/commons/CommonCFunctions.java @@ -33,15 +33,21 @@ private CommonCFunctions() { @CEntryPoint(name = "setJavaLibraryPath") public static void setJavaLibraryPath(IsolateThread thread, CCharPointer javaLibraryPath, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - System.setProperty("java.library.path", CTypeUtil.toString(javaLibraryPath)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + System.setProperty("java.library.path", CTypeUtil.toString(javaLibraryPath)); + } }); } @CEntryPoint(name = "setConfigRead") public static void setConfigRead(IsolateThread thread, boolean read, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - PyPowsyblConfiguration.setReadConfig(read); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + PyPowsyblConfiguration.setReadConfig(read); + } }); } @@ -52,13 +58,23 @@ public static boolean isConfigRead(IsolateThread thread, ExceptionHandlerPointer @CEntryPoint(name = "getVersionTable") public static CCharPointer getVersionTable(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> CTypeUtil.toCharPtr(Version.getTableString())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public CCharPointer get() { + return CTypeUtil.toCharPtr(Version.getTableString()); + } + }); } @CEntryPoint(name = "freeStringArray") public static void freeStringArray(IsolateThread thread, ArrayPointer arrayPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> freeArrayContent(arrayPtr)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + freeArrayContent(arrayPtr); + } + }); } @CEntryPoint(name = "freeArray") @@ -71,11 +87,14 @@ public static void freeArray(IsolateThread thread, Array @CEntryPoint(name = "freeSeriesArray") public static void freeSeriesArray(IsolateThread thread, ArrayPointer seriesPtrArrayPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - for (int i = 0; i < seriesPtrArrayPtr.getLength(); i++) { - freeSeries(seriesPtrArrayPtr.getPtr().addressOf(i)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + for (int i = 0; i < seriesPtrArrayPtr.getLength(); i++) { + freeSeries(seriesPtrArrayPtr.getPtr().addressOf(i)); + } + freeArrayPointer(seriesPtrArrayPtr); } - freeArrayPointer(seriesPtrArrayPtr); }); } @@ -100,20 +119,33 @@ private static void freeArrayContent(ArrayPointer array) { @CEntryPoint(name = "destroyObjectHandle") public static void destroyObjectHandle(IsolateThread thread, ObjectHandle objectHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().destroy(objectHandle)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + ObjectHandles.getGlobal().destroy(objectHandle); + } + }); } @CEntryPoint(name = "getWorkingVariantId") public static CCharPointer getWorkingVariantId(IsolateThread thread, ObjectHandle networkHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - return CTypeUtil.toCharPtr(network.getVariantManager().getWorkingVariantId()); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public CCharPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + return CTypeUtil.toCharPtr(network.getVariantManager().getWorkingVariantId()); + } }); } @CEntryPoint(name = "freeString") public static void freeString(IsolateThread thread, CCharPointer string, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> UnmanagedMemory.free(string)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + UnmanagedMemory.free(string); + } + }); } @CEntryPoint(name = "closePypowsybl") @@ -123,12 +155,15 @@ public static void closePypowsybl(IsolateThread thread, ExceptionHandlerPointer @CEntryPoint(name = "freeStringMap") public static void freeStringMap(IsolateThread thread, StringMap map, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - for (int i = 0; i < map.getLength(); i++) { - UnmanagedMemory.free(map.getKeys().read(i)); - UnmanagedMemory.free(map.getValues().read(i)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + for (int i = 0; i < map.getLength(); i++) { + UnmanagedMemory.free(map.getKeys().read(i)); + UnmanagedMemory.free(map.getValues().read(i)); + } + UnmanagedMemory.free(map); } - UnmanagedMemory.free(map); }); } } diff --git a/java/src/main/java/com/powsybl/python/dataframe/CDataframeHandler.java b/java/src/main/java/com/powsybl/python/dataframe/CDataframeHandler.java index e9205374ab..fee87f695d 100644 --- a/java/src/main/java/com/powsybl/python/dataframe/CDataframeHandler.java +++ b/java/src/main/java/com/powsybl/python/dataframe/CDataframeHandler.java @@ -54,42 +54,72 @@ public void allocate(int seriesCount) { public StringSeriesWriter newStringIndex(String name, int size) { CCharPointerPointer dataPtr = UnmanagedMemory.calloc(size * SizeOf.get(CCharPointerPointer.class)); addIndex(name, size, dataPtr, STRING_SERIES_TYPE); - return (i, v) -> dataPtr.addressOf(i).write(CTypeUtil.toCharPtr(v)); + return new StringSeriesWriter() { + @Override + public void set(int i, String v) { + dataPtr.addressOf(i).write(CTypeUtil.toCharPtr(v)); + } + }; } @Override public IntSeriesWriter newIntIndex(String name, int size) { CIntPointer dataPtr = UnmanagedMemory.calloc(size * SizeOf.get(CIntPointer.class)); addIndex(name, size, dataPtr, INT_SERIES_TYPE); - return (i, v) -> dataPtr.addressOf(i).write(v); + return new IntSeriesWriter() { + @Override + public void set(int i, int v) { + dataPtr.addressOf(i).write(v); + } + }; } @Override public StringSeriesWriter newStringSeries(String name, int size) { CCharPointerPointer dataPtr = UnmanagedMemory.calloc(size * SizeOf.get(CCharPointerPointer.class)); addSeries(name, size, dataPtr, STRING_SERIES_TYPE); - return (i, v) -> dataPtr.addressOf(i).write(CTypeUtil.toCharPtr(v)); + return new StringSeriesWriter() { + @Override + public void set(int i, String v) { + dataPtr.addressOf(i).write(CTypeUtil.toCharPtr(v)); + } + }; } @Override public IntSeriesWriter newIntSeries(String name, int size) { CIntPointer dataPtr = UnmanagedMemory.calloc(size * SizeOf.get(CIntPointer.class)); addSeries(name, size, dataPtr, INT_SERIES_TYPE); - return (i, v) -> dataPtr.addressOf(i).write(v); + return new IntSeriesWriter() { + @Override + public void set(int i, int v) { + dataPtr.addressOf(i).write(v); + } + }; } @Override public BooleanSeriesWriter newBooleanSeries(String name, int size) { CCharPointer dataPtr = UnmanagedMemory.calloc(size * SizeOf.get(CCharPointer.class)); addSeries(name, size, dataPtr, BOOLEAN_SERIES_TYPE); - return (i, v) -> dataPtr.addressOf(i).write(v ? (byte) 1 : 0); + return new BooleanSeriesWriter() { + @Override + public void set(int i, boolean v) { + dataPtr.addressOf(i).write(v ? (byte) 1 : 0); + } + }; } @Override public DoubleSeriesWriter newDoubleSeries(String name, int size) { CDoublePointer dataPtr = UnmanagedMemory.calloc(size * SizeOf.get(CDoublePointer.class)); addSeries(name, size, dataPtr, DOUBLE_SERIES_TYPE); - return (i, v) -> dataPtr.addressOf(i).write(v); + return new DoubleSeriesWriter() { + @Override + public void set(int i, double v) { + dataPtr.addressOf(i).write(v); + } + }; } private void addSeries(String name, int count, PointerBase dataPtr, int type) { diff --git a/java/src/main/java/com/powsybl/python/dynamic/DynamicSimulationCFunctions.java b/java/src/main/java/com/powsybl/python/dynamic/DynamicSimulationCFunctions.java index 60e169db68..fc0089ac99 100644 --- a/java/src/main/java/com/powsybl/python/dynamic/DynamicSimulationCFunctions.java +++ b/java/src/main/java/com/powsybl/python/dynamic/DynamicSimulationCFunctions.java @@ -59,25 +59,45 @@ private static Logger logger() { @CEntryPoint(name = "createDynamicSimulationContext") public static ObjectHandle createDynamicSimulationContext(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new DynamicSimulationContext())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new DynamicSimulationContext()); + } + }); } @CEntryPoint(name = "createDynamicModelMapping") public static ObjectHandle createDynamicModelMapping(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new DynamicModelMapper())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new DynamicModelMapper()); + } + }); } @CEntryPoint(name = "createTimeseriesMapping") public static ObjectHandle createTimeseriesMapping(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new CurveMappingSupplier())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new CurveMappingSupplier()); + } + }); } @CEntryPoint(name = "createEventMapping") public static ObjectHandle createEventMapping(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new EventSupplier())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new EventSupplier()); + } + }); } @CEntryPoint(name = "runDynamicModel") @@ -89,21 +109,24 @@ public static ObjectHandle runDynamicModel(IsolateThread thread, ObjectHandle curvesSupplierHandle, int startTime, int stopTime, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DynamicSimulationContext dynamicContext = ObjectHandles.getGlobal().get(dynamicContextHandle); - Network network = ObjectHandles.getGlobal().get(networkHandle); - DynamicModelMapper dynamicMapping = ObjectHandles.getGlobal().get(dynamicMappingHandle); - EventModelsSupplier eventModelsSupplier = ObjectHandles.getGlobal().get(eventModelsSupplierHandle); - CurvesSupplier curvesSupplier = ObjectHandles.getGlobal().get(curvesSupplierHandle); - DynamicSimulationParameters dynamicSimulationParameters = new DynamicSimulationParameters(startTime, - stopTime); - DynamicSimulationResult result = dynamicContext.run(network, - dynamicMapping, - eventModelsSupplier, - curvesSupplier, - dynamicSimulationParameters); - logger().info("Dynamic simulation ran successfully in java"); - return ObjectHandles.getGlobal().create(result); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + DynamicSimulationContext dynamicContext = ObjectHandles.getGlobal().get(dynamicContextHandle); + Network network = ObjectHandles.getGlobal().get(networkHandle); + DynamicModelMapper dynamicMapping = ObjectHandles.getGlobal().get(dynamicMappingHandle); + EventModelsSupplier eventModelsSupplier = ObjectHandles.getGlobal().get(eventModelsSupplierHandle); + CurvesSupplier curvesSupplier = ObjectHandles.getGlobal().get(curvesSupplierHandle); + DynamicSimulationParameters dynamicSimulationParameters = new DynamicSimulationParameters(startTime, + stopTime); + DynamicSimulationResult result = dynamicContext.run(network, + dynamicMapping, + eventModelsSupplier, + curvesSupplier, + dynamicSimulationParameters); + logger().info("Dynamic simulation ran successfully in java"); + return ObjectHandles.getGlobal().create(result); + } }); } @@ -112,10 +135,13 @@ public static void addDynamicMapping(IsolateThread thread, ObjectHandle dynamicM DynamicMappingType mappingType, DataframePointer mappingDataframePtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - DynamicModelMapper dynamicMapping = ObjectHandles.getGlobal().get(dynamicMappingHandle); - UpdatingDataframe mappingDataframe = NetworkCFunctions.createDataframe(mappingDataframePtr); - DynamicMappingAdderFactory.getAdder(mappingType).addElements(dynamicMapping, mappingDataframe); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + DynamicModelMapper dynamicMapping = ObjectHandles.getGlobal().get(dynamicMappingHandle); + UpdatingDataframe mappingDataframe = NetworkCFunctions.createDataframe(mappingDataframePtr); + DynamicMappingAdderFactory.getAdder(mappingType).addElements(dynamicMapping, mappingDataframe); + } }); } @@ -123,8 +149,11 @@ public static void addDynamicMapping(IsolateThread thread, ObjectHandle dynamicM public static DataframeMetadataPointer getDynamicMappingsMetaData(IsolateThread thread, DynamicMappingType mappingType, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - return CTypeUtil.createSeriesMetadata(DynamicMappingAdderFactory.getAdder(mappingType).getMetadata()); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public DataframeMetadataPointer get() { + return CTypeUtil.createSeriesMetadata(DynamicMappingAdderFactory.getAdder(mappingType).getMetadata()); + } }); } @@ -134,11 +163,14 @@ public static void addCurve(IsolateThread thread, CCharPointer dynamicIdPtr, CCharPointer variablePtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - String dynamicId = CTypeUtil.toString(dynamicIdPtr); - String variable = CTypeUtil.toString(variablePtr); - CurveMappingSupplier timeSeriesSupplier = ObjectHandles.getGlobal().get(timeseriesSupplier); - timeSeriesSupplier.addCurve(dynamicId, variable); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + String dynamicId = CTypeUtil.toString(dynamicIdPtr); + String variable = CTypeUtil.toString(variablePtr); + CurveMappingSupplier timeSeriesSupplier = ObjectHandles.getGlobal().get(timeseriesSupplier); + timeSeriesSupplier.addCurve(dynamicId, variable); + } }); } @@ -150,10 +182,13 @@ public static void addEventBranchDisconnection(IsolateThread thread, boolean disconnectOrigin, boolean disconnectExtremity, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - String staticId = CTypeUtil.toString(staticIdPtr); - EventSupplier eventSupplier = ObjectHandles.getGlobal().get(eventSupplierHandle); - eventSupplier.addEventBranchDisconnection(staticId, eventTime, disconnectOrigin, disconnectExtremity); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + String staticId = CTypeUtil.toString(staticIdPtr); + EventSupplier eventSupplier = ObjectHandles.getGlobal().get(eventSupplierHandle); + eventSupplier.addEventBranchDisconnection(staticId, eventTime, disconnectOrigin, disconnectExtremity); + } }); } @@ -164,10 +199,13 @@ public static void addEventInjectionDisconnection(IsolateThread thread, double eventTime, boolean stateEvent, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - String staticId = CTypeUtil.toString(staticIdPtr); - EventSupplier eventSupplier = ObjectHandles.getGlobal().get(eventSupplierHandle); - eventSupplier.addEventInjectionDisconnection(staticId, eventTime, stateEvent); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + String staticId = CTypeUtil.toString(staticIdPtr); + EventSupplier eventSupplier = ObjectHandles.getGlobal().get(eventSupplierHandle); + eventSupplier.addEventInjectionDisconnection(staticId, eventTime, stateEvent); + } }); } @@ -175,9 +213,12 @@ public static void addEventInjectionDisconnection(IsolateThread thread, public static CCharPointer getDynamicSimulationResultsStatus(IsolateThread thread, ObjectHandle dynamicSimulationResultsHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DynamicSimulationResult simulationResult = ObjectHandles.getGlobal().get(dynamicSimulationResultsHandle); - return CTypeUtil.toCharPtr(simulationResult.isOk() ? "Ok" : "Not OK"); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public CCharPointer get() { + DynamicSimulationResult simulationResult = ObjectHandles.getGlobal().get(dynamicSimulationResultsHandle); + return CTypeUtil.toCharPtr(simulationResult.isOk() ? "Ok" : "Not OK"); + } }); } @@ -186,11 +227,14 @@ public static ArrayPointer getDynamicCurve(IsolateThread thread, ObjectHandle resultHandle, CCharPointer curveNamePtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DynamicSimulationResult result = ObjectHandles.getGlobal().get(resultHandle); - String curveName = CTypeUtil.toString(curveNamePtr); - TimeSeries curve = result.getCurve(curveName); - return Dataframes.createCDataframe(CurvesSeries.curvesDataFrameMapper(curveName), curve); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public ArrayPointer get() { + DynamicSimulationResult result = ObjectHandles.getGlobal().get(resultHandle); + String curveName = CTypeUtil.toString(curveNamePtr); + TimeSeries curve = result.getCurve(curveName); + return Dataframes.createCDataframe(CurvesSeries.curvesDataFrameMapper(curveName), curve); + } }); } @@ -198,9 +242,12 @@ public static ArrayPointer getDynamicCurve(IsolateThread thread, public static ArrayPointer getAllDynamicCurvesIds(IsolateThread thread, ObjectHandle resultHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DynamicSimulationResult result = ObjectHandles.getGlobal().get(resultHandle); - return Util.createCharPtrArray(result.getCurves().keySet().stream().collect(Collectors.toList())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public ArrayPointer get() { + DynamicSimulationResult result = ObjectHandles.getGlobal().get(resultHandle); + return Util.createCharPtrArray(result.getCurves().keySet().stream().collect(Collectors.toList())); + } }); } diff --git a/java/src/main/java/com/powsybl/python/flow_decomposition/FlowDecompositionCFunctions.java b/java/src/main/java/com/powsybl/python/flow_decomposition/FlowDecompositionCFunctions.java index 1a8cc89dfb..1ccd139be7 100644 --- a/java/src/main/java/com/powsybl/python/flow_decomposition/FlowDecompositionCFunctions.java +++ b/java/src/main/java/com/powsybl/python/flow_decomposition/FlowDecompositionCFunctions.java @@ -14,11 +14,7 @@ import com.powsybl.iidm.network.Network; import com.powsybl.loadflow.LoadFlowParameters; import com.powsybl.loadflow.LoadFlowProvider; -import com.powsybl.python.commons.CTypeUtil; -import com.powsybl.python.commons.CommonCFunctions; -import com.powsybl.python.commons.Directives; -import com.powsybl.python.commons.PyPowsyblApiHeader; -import com.powsybl.python.commons.PyPowsyblConfiguration; +import com.powsybl.python.commons.*; import com.powsybl.python.loadflow.LoadFlowCUtils; import com.powsybl.python.network.Dataframes; import org.graalvm.nativeimage.IsolateThread; @@ -52,7 +48,12 @@ private FlowDecompositionCFunctions() { @CEntryPoint(name = "createFlowDecomposition") public static ObjectHandle createFlowDecomposition(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new FlowDecompositionContext())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new FlowDecompositionContext()); + } + }); } @CEntryPoint(name = "addContingencyForFlowDecomposition") @@ -60,11 +61,14 @@ public static void addContingency(IsolateThread thread, ObjectHandle flowDecompo CCharPointer contingencyIdPtr, CCharPointerPointer elementIdPtrPtr, int elementCount, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); - Set elementsIds = new HashSet<>(toStringList(elementIdPtrPtr, elementCount)); - String contingencyId = CTypeUtil.toString(contingencyIdPtr); - flowDecompositionContext.getXnecProviderByIdsBuilder().addContingency(contingencyId, elementsIds); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); + Set elementsIds = new HashSet<>(toStringList(elementIdPtrPtr, elementCount)); + String contingencyId = CTypeUtil.toString(contingencyIdPtr); + flowDecompositionContext.getXnecProviderByIdsBuilder().addContingency(contingencyId, elementsIds); + } }); } @@ -72,10 +76,13 @@ public static void addContingency(IsolateThread thread, ObjectHandle flowDecompo public static void addPrecontingencyMonitoredElements(IsolateThread thread, ObjectHandle flowDecompositionContextHandle, CCharPointerPointer elementIdPtrPtr, int elementCount, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); - Set elementsIds = new HashSet<>(toStringList(elementIdPtrPtr, elementCount)); - flowDecompositionContext.getXnecProviderByIdsBuilder().addNetworkElementsOnBasecase(elementsIds); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); + Set elementsIds = new HashSet<>(toStringList(elementIdPtrPtr, elementCount)); + flowDecompositionContext.getXnecProviderByIdsBuilder().addNetworkElementsOnBasecase(elementsIds); + } }); } @@ -84,11 +91,14 @@ public static void addPostcontingencyMonitoredElements(IsolateThread thread, Obj CCharPointerPointer elementIdPtrPtr, int elementCount, CCharPointerPointer contingenciesIdPtrPtr, int contingenciesCount, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); - Set elementsIds = new HashSet<>(toStringList(elementIdPtrPtr, elementCount)); - Set contingenciesIds = new HashSet<>(toStringList(contingenciesIdPtrPtr, contingenciesCount)); - flowDecompositionContext.getXnecProviderByIdsBuilder().addNetworkElementsAfterContingencies(elementsIds, contingenciesIds); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); + Set elementsIds = new HashSet<>(toStringList(elementIdPtrPtr, elementCount)); + Set contingenciesIds = new HashSet<>(toStringList(contingenciesIdPtrPtr, contingenciesCount)); + flowDecompositionContext.getXnecProviderByIdsBuilder().addNetworkElementsAfterContingencies(elementsIds, contingenciesIds); + } }); } @@ -107,38 +117,51 @@ public static PyPowsyblApiHeader.ArrayPointer PyPowsyblApiHeader.FlowDecompositionParametersPointer flowDecompositionParametersPtr, PyPowsyblApiHeader.LoadFlowParametersPointer loadFlowParametersPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); - Network network = ObjectHandles.getGlobal().get(networkHandle); - - String lfProviderName = PyPowsyblConfiguration.getDefaultLoadFlowProvider(); - LoadFlowProvider loadFlowProvider = LoadFlowCUtils.getLoadFlowProvider(lfProviderName); - String sensiProviderName = PyPowsyblConfiguration.getDefaultSensitivityAnalysisProvider(); - LoadFlowParameters loadFlowParameters = LoadFlowCUtils.createLoadFlowParameters(DC, loadFlowParametersPtr, loadFlowProvider); - FlowDecompositionParameters flowDecompositionParameters = FlowDecompositionCUtils.createFlowDecompositionParameters(flowDecompositionParametersPtr); - - logger().debug("Loadflow provider used is : {}", loadFlowProvider.getName()); - logger().debug("Sensitivity analysis provider used is : {}", sensiProviderName); - logger().debug("Load flow parameters : {}", loadFlowParameters); - logger().debug("Flow decomposition parameters : {}", flowDecompositionParameters); - - FlowDecompositionComputer flowDecompositionComputer = new FlowDecompositionComputer(flowDecompositionParameters, loadFlowParameters, lfProviderName, sensiProviderName); - XnecProvider xnecProvider = flowDecompositionContext.getXnecProvider(); - FlowDecompositionResults flowDecompositionResults = flowDecompositionComputer.run(xnecProvider, network); - - return Dataframes.createCDataframe(Dataframes.flowDecompositionMapper(flowDecompositionResults.getZoneSet()), flowDecompositionResults); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + FlowDecompositionContext flowDecompositionContext = ObjectHandles.getGlobal().get(flowDecompositionContextHandle); + Network network = ObjectHandles.getGlobal().get(networkHandle); + + String lfProviderName = PyPowsyblConfiguration.getDefaultLoadFlowProvider(); + LoadFlowProvider loadFlowProvider = LoadFlowCUtils.getLoadFlowProvider(lfProviderName); + String sensiProviderName = PyPowsyblConfiguration.getDefaultSensitivityAnalysisProvider(); + LoadFlowParameters loadFlowParameters = LoadFlowCUtils.createLoadFlowParameters(DC, loadFlowParametersPtr, loadFlowProvider); + FlowDecompositionParameters flowDecompositionParameters = FlowDecompositionCUtils.createFlowDecompositionParameters(flowDecompositionParametersPtr); + + logger().debug("Loadflow provider used is : {}", loadFlowProvider.getName()); + logger().debug("Sensitivity analysis provider used is : {}", sensiProviderName); + logger().debug("Load flow parameters : {}", loadFlowParameters); + logger().debug("Flow decomposition parameters : {}", flowDecompositionParameters); + + FlowDecompositionComputer flowDecompositionComputer = new FlowDecompositionComputer(flowDecompositionParameters, loadFlowParameters, lfProviderName, sensiProviderName); + XnecProvider xnecProvider = flowDecompositionContext.getXnecProvider(); + FlowDecompositionResults flowDecompositionResults = flowDecompositionComputer.run(xnecProvider, network); + + return Dataframes.createCDataframe(Dataframes.flowDecompositionMapper(flowDecompositionResults.getZoneSet()), flowDecompositionResults); + } }); } @CEntryPoint(name = "createFlowDecompositionParameters") public static PyPowsyblApiHeader.FlowDecompositionParametersPointer createFlowDecompositionParameters(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> convertToFlowDecompositionParametersPointer(FlowDecompositionCUtils.createFlowDecompositionParameters())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public PyPowsyblApiHeader.FlowDecompositionParametersPointer get() { + return convertToFlowDecompositionParametersPointer(FlowDecompositionCUtils.createFlowDecompositionParameters()); + } + }); } @CEntryPoint(name = "freeFlowDecompositionParameters") public static void freeFlowDecompositionParameters(IsolateThread thread, PyPowsyblApiHeader.FlowDecompositionParametersPointer flowDecompositionParametersPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> UnmanagedMemory.free(flowDecompositionParametersPtr)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + UnmanagedMemory.free(flowDecompositionParametersPtr); + } + }); } private static PyPowsyblApiHeader.FlowDecompositionParametersPointer convertToFlowDecompositionParametersPointer(FlowDecompositionParameters parameters) { diff --git a/java/src/main/java/com/powsybl/python/glsk/GlskCFunctions.java b/java/src/main/java/com/powsybl/python/glsk/GlskCFunctions.java index 9985592f13..720bd438f9 100644 --- a/java/src/main/java/com/powsybl/python/glsk/GlskCFunctions.java +++ b/java/src/main/java/com/powsybl/python/glsk/GlskCFunctions.java @@ -22,6 +22,7 @@ import java.time.Instant; import java.util.List; +import java.util.function.LongSupplier; import static com.powsybl.python.commons.Util.*; @@ -38,56 +39,74 @@ private GlskCFunctions() { @CEntryPoint(name = "createGLSKdocument") public static ObjectHandle createGLSKdocument(IsolateThread thread, CCharPointer fileNamePtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - GlskDocumentContext importer = new GlskDocumentContext(); - String filename = CTypeUtil.toString(fileNamePtr); - importer.load(filename); - return ObjectHandles.getGlobal().create(importer); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + GlskDocumentContext importer = new GlskDocumentContext(); + String filename = CTypeUtil.toString(fileNamePtr); + importer.load(filename); + return ObjectHandles.getGlobal().create(importer); + } }); } @CEntryPoint(name = "getGLSKinjectionkeys") public static ArrayPointer getGLSKinjectionkeys(IsolateThread thread, ObjectHandle networkHandle, ObjectHandle importerHandle, CCharPointer countryPtr, long instant, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); - Network network = ObjectHandles.getGlobal().get(networkHandle); - String country = CTypeUtil.toString(countryPtr); - return createCharPtrArray(importer.getInjectionIdForCountry(network, country, Instant.ofEpochSecond(instant))); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); + Network network = ObjectHandles.getGlobal().get(networkHandle); + String country = CTypeUtil.toString(countryPtr); + return createCharPtrArray(importer.getInjectionIdForCountry(network, country, Instant.ofEpochSecond(instant))); + } }); } @CEntryPoint(name = "getGLSKcountries") public static ArrayPointer getGLSKcountries(IsolateThread thread, ObjectHandle importerHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); - return createCharPtrArray(importer.getCountries()); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); + return createCharPtrArray(importer.getCountries()); + } }); } @CEntryPoint(name = "getInjectionFactor") public static ArrayPointer getInjectionFactor(IsolateThread thread, ObjectHandle networkHandle, ObjectHandle importerHandle, CCharPointer countryPtr, long instant, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); - String country = CTypeUtil.toString(countryPtr); - List values = importer.getInjectionFactorForCountryTimeinterval(network, country, Instant.ofEpochSecond(instant)); - return createDoubleArray(values); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); + String country = CTypeUtil.toString(countryPtr); + List values = importer.getInjectionFactorForCountryTimeinterval(network, country, Instant.ofEpochSecond(instant)); + return createDoubleArray(values); + } }); } @CEntryPoint(name = "getInjectionFactorStartTimestamp") public static long getInjectionFactorStartTimestamp(IsolateThread thread, ObjectHandle importerHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); - return importer.getInjectionFactorStart().getEpochSecond(); + return doCatch(exceptionHandlerPtr, new LongSupplier() { + @Override + public long getAsLong() { + GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); + return importer.getInjectionFactorStart().getEpochSecond(); + } }); } @CEntryPoint(name = "getInjectionFactorEndTimestamp") public static long getInjectionFactorEndTimestamp(IsolateThread thread, ObjectHandle importerHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); - return importer.getInjectionFactorEnd().getEpochSecond(); + return doCatch(exceptionHandlerPtr, new LongSupplier() { + @Override + public long getAsLong() { + GlskDocumentContext importer = ObjectHandles.getGlobal().get(importerHandle); + return importer.getInjectionFactorEnd().getEpochSecond(); + } }); } } diff --git a/java/src/main/java/com/powsybl/python/loadflow/LoadFlowCFunctions.java b/java/src/main/java/com/powsybl/python/loadflow/LoadFlowCFunctions.java index 267aa081ac..612d98b64d 100644 --- a/java/src/main/java/com/powsybl/python/loadflow/LoadFlowCFunctions.java +++ b/java/src/main/java/com/powsybl/python/loadflow/LoadFlowCFunctions.java @@ -52,31 +52,44 @@ private LoadFlowCFunctions() { @CEntryPoint(name = "setDefaultLoadFlowProvider") public static void setDefaultLoadFlowProvider(IsolateThread thread, CCharPointer provider, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - PyPowsyblConfiguration.setDefaultLoadFlowProvider(CTypeUtil.toString(provider)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + PyPowsyblConfiguration.setDefaultLoadFlowProvider(CTypeUtil.toString(provider)); + } }); } @CEntryPoint(name = "getDefaultLoadFlowProvider") public static CCharPointer getDefaultLoadFlowProvider(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultLoadFlowProvider())); + return doCatch(exceptionHandlerPtr, () -> { + return CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultLoadFlowProvider()); + }); } @CEntryPoint(name = "freeLoadFlowComponentResultPointer") public static void freeLoadFlowComponentResultPointer(IsolateThread thread, PyPowsyblApiHeader.ArrayPointer componentResultArrayPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - for (int i = 0; i < componentResultArrayPtr.getLength(); i++) { - UnmanagedMemory.free(componentResultArrayPtr.getPtr().addressOf(i).getSlackBusId()); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + for (int i = 0; i < componentResultArrayPtr.getLength(); i++) { + UnmanagedMemory.free(componentResultArrayPtr.getPtr().addressOf(i).getSlackBusId()); + } + freeArrayPointer(componentResultArrayPtr); } - freeArrayPointer(componentResultArrayPtr); }); } @CEntryPoint(name = "getLoadFlowProviderNames") public static PyPowsyblApiHeader.ArrayPointer getLoadFlowProviderNames(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(LoadFlowProvider.findAll() - .stream().map(LoadFlowProvider::getName).collect(Collectors.toList()))); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + return createCharPtrArray(LoadFlowProvider.findAll() + .stream().map(LoadFlowProvider::getName).collect(Collectors.toList())); + } + }); } @CEntryPoint(name = "runLoadFlow") @@ -84,31 +97,42 @@ public static PyPowsyblApiHeader.ArrayPointer { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String providerStr = CTypeUtil.toString(provider); - LoadFlowProvider loadFlowProvider = LoadFlowCUtils.getLoadFlowProvider(providerStr); - logger().info("loadflow provider used is : {}", loadFlowProvider.getName()); - - LoadFlowParameters parameters = LoadFlowCUtils.createLoadFlowParameters(dc, loadFlowParametersPtr, loadFlowProvider); - LoadFlow.Runner runner = new LoadFlow.Runner(loadFlowProvider); - Reporter reporter = ReportCUtils.getReporter(reporterHandle); - LoadFlowResult result = runner.run(network, network.getVariantManager().getWorkingVariantId(), + return Util.doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String providerStr = CTypeUtil.toString(provider); + LoadFlowProvider loadFlowProvider = LoadFlowCUtils.getLoadFlowProvider(providerStr); + logger().info("loadflow provider used is : {}", loadFlowProvider.getName()); + + LoadFlowParameters parameters = LoadFlowCUtils.createLoadFlowParameters(dc, loadFlowParametersPtr, loadFlowProvider); + LoadFlow.Runner runner = new LoadFlow.Runner(loadFlowProvider); + Reporter reporter = ReportCUtils.getReporter(reporterHandle); + LoadFlowResult result = runner.run(network, network.getVariantManager().getWorkingVariantId(), CommonObjects.getComputationManager(), parameters, reporter); - return createLoadFlowComponentResultArrayPointer(result); + return createLoadFlowComponentResultArrayPointer(result); + } }); } @CEntryPoint(name = "createLoadFlowParameters") public static LoadFlowParametersPointer createLoadFlowParameters(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> convertToLoadFlowParametersPointer(LoadFlowCUtils.createLoadFlowParameters())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public LoadFlowParametersPointer get() { + return convertToLoadFlowParametersPointer(LoadFlowCUtils.createLoadFlowParameters()); + } + }); } @CEntryPoint(name = "freeLoadFlowParameters") public static void freeLoadFlowParameters(IsolateThread thread, LoadFlowParametersPointer loadFlowParametersPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - freeLoadFlowParametersPointer(loadFlowParametersPtr); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + freeLoadFlowParametersPointer(loadFlowParametersPtr); + } }); } @@ -168,19 +192,25 @@ public static LoadFlowParametersPointer convertToLoadFlowParametersPointer(LoadF @CEntryPoint(name = "getLoadFlowProviderParametersNames") public static PyPowsyblApiHeader.ArrayPointer getProviderParametersNames(IsolateThread thread, CCharPointer provider, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String providerStr = CTypeUtil.toString(provider); - return Util.createCharPtrArray(LoadFlowCUtils.getLoadFlowProvider(providerStr).getSpecificParameters().stream().map(Parameter::getName).collect(Collectors.toList())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + String providerStr = CTypeUtil.toString(provider); + return Util.createCharPtrArray(LoadFlowCUtils.getLoadFlowProvider(providerStr).getSpecificParameters().stream().map(Parameter::getName).collect(Collectors.toList())); + } }); } @CEntryPoint(name = "createLoadFlowProviderParametersSeriesArray") static PyPowsyblApiHeader.ArrayPointer createLoadFlowProviderParametersSeriesArray(IsolateThread thread, CCharPointer providerNamePtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String providerName = CTypeUtil.toString(providerNamePtr); - LoadFlowProvider provider = LoadFlowCUtils.getLoadFlowProvider(providerName); - return Dataframes.createCDataframe(LoadFlowCUtils.SPECIFIC_PARAMETERS_MAPPER, provider); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + String providerName = CTypeUtil.toString(providerNamePtr); + LoadFlowProvider provider = LoadFlowCUtils.getLoadFlowProvider(providerName); + return Dataframes.createCDataframe(LoadFlowCUtils.SPECIFIC_PARAMETERS_MAPPER, provider); + } }); } diff --git a/java/src/main/java/com/powsybl/python/loadflow/validation/LoadFlowValidationCFunctions.java b/java/src/main/java/com/powsybl/python/loadflow/validation/LoadFlowValidationCFunctions.java index b79d7f3701..eaf1ee1ef2 100644 --- a/java/src/main/java/com/powsybl/python/loadflow/validation/LoadFlowValidationCFunctions.java +++ b/java/src/main/java/com/powsybl/python/loadflow/validation/LoadFlowValidationCFunctions.java @@ -13,9 +13,7 @@ import com.powsybl.loadflow.LoadFlowParameters; import com.powsybl.loadflow.validation.ValidationConfig; import com.powsybl.loadflow.validation.ValidationType; -import com.powsybl.python.commons.Directives; -import com.powsybl.python.commons.PyPowsyblApiHeader; -import com.powsybl.python.commons.PyPowsyblConfiguration; +import com.powsybl.python.commons.*; import com.powsybl.python.network.Dataframes; import org.graalvm.nativeimage.IsolateThread; import org.graalvm.nativeimage.ObjectHandle; @@ -24,7 +22,6 @@ import org.graalvm.nativeimage.c.function.CEntryPoint; import org.graalvm.nativeimage.UnmanagedMemory; import org.graalvm.nativeimage.c.struct.SizeOf; -import com.powsybl.python.commons.CTypeUtil; import com.powsybl.python.loadflow.LoadFlowCUtils; import com.powsybl.python.loadflow.LoadFlowCFunctions; @@ -47,9 +44,12 @@ public static ArrayPointer createLoadFlowValidationSeriesArray(Is PyPowsyblApiHeader.ValidationType validationType, PyPowsyblApiHeader.LoadFlowValidationParametersPointer loadFlowValidationParametersPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - return createLoadFlowValidationSeriesArray(network, validationType, loadFlowValidationParametersPtr); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + return createLoadFlowValidationSeriesArray(network, validationType, loadFlowValidationParametersPtr); + } }); } @@ -109,7 +109,12 @@ private static ArrayPointer createCDataFrame(InMemoryValidationWr @CEntryPoint(name = "createValidationConfig") public static LoadFlowValidationParametersPointer createValidationConfig(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> convertToLoadFlowValidationParametersPointer(createValidationConfig())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public LoadFlowValidationParametersPointer get() { + return convertToLoadFlowValidationParametersPointer(createValidationConfig()); + } + }); } public static void copyToCLoadFlowValidationParameters(ValidationConfig parameters, LoadFlowValidationParametersPointer cParameters) { @@ -139,8 +144,11 @@ public static LoadFlowValidationParametersPointer convertToLoadFlowValidationPar @CEntryPoint(name = "freeValidationConfig") public static void freeValidationConfig(IsolateThread thread, LoadFlowValidationParametersPointer loadFlowValidationParametersPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - freeLoadFlowValidationParametersPointer(loadFlowValidationParametersPtr); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + freeLoadFlowValidationParametersPointer(loadFlowValidationParametersPtr); + } }); } diff --git a/java/src/main/java/com/powsybl/python/logging/LoggingCFunctions.java b/java/src/main/java/com/powsybl/python/logging/LoggingCFunctions.java index bdcc9482cc..bd61a347bd 100644 --- a/java/src/main/java/com/powsybl/python/logging/LoggingCFunctions.java +++ b/java/src/main/java/com/powsybl/python/logging/LoggingCFunctions.java @@ -39,16 +39,22 @@ public interface LoggerCallback extends CFunctionPointer { @CEntryPoint(name = "setupLoggerCallback") public static void setupLoggerCallback(IsolateThread thread, LoggerCallback fpointer, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - loggerCallback = fpointer; + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + loggerCallback = fpointer; + } }); } @CEntryPoint(name = "setLogLevel") public static void setLogLevel(IsolateThread thread, int logLevel, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Logger powsyblLogger = (Logger) LoggerFactory.getLogger("com.powsybl"); - powsyblLogger.setLevel(PyLoggingUtil.pythonLevelToLogbackLevel(logLevel)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Logger powsyblLogger = (Logger) LoggerFactory.getLogger("com.powsybl"); + powsyblLogger.setLevel(PyLoggingUtil.pythonLevelToLogbackLevel(logLevel)); + } }); } } diff --git a/java/src/main/java/com/powsybl/python/network/NetworkCFunctions.java b/java/src/main/java/com/powsybl/python/network/NetworkCFunctions.java index 232a989bd8..02e1e25f45 100644 --- a/java/src/main/java/com/powsybl/python/network/NetworkCFunctions.java +++ b/java/src/main/java/com/powsybl/python/network/NetworkCFunctions.java @@ -60,6 +60,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.*; +import java.util.function.BooleanSupplier; import static com.powsybl.python.commons.CTypeUtil.toStringList; import static com.powsybl.python.commons.PyPowsyblApiHeader.*; @@ -82,37 +83,52 @@ private NetworkCFunctions() { @CEntryPoint(name = "getNetworkImportFormats") public static ArrayPointer getNetworkImportFormats(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(new ArrayList<>(Importer.getFormats()))); + return doCatch(exceptionHandlerPtr, () -> { + return createCharPtrArray(new ArrayList<>(Importer.getFormats())); + }); } @CEntryPoint(name = "getNetworkExportFormats") public static ArrayPointer getNetworkExportFormats(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(new ArrayList<>(Exporter.getFormats()))); + return doCatch(exceptionHandlerPtr, () -> { + return createCharPtrArray(new ArrayList<>(Exporter.getFormats())); + }); } @CEntryPoint(name = "createNetwork") public static ObjectHandle createNetwork(IsolateThread thread, CCharPointer name, CCharPointer id, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String networkName = CTypeUtil.toString(name); - String networkId = CTypeUtil.toString(id); - Network network = Networks.create(networkName, networkId); - return ObjectHandles.getGlobal().create(network); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + String networkName = CTypeUtil.toString(name); + String networkId = CTypeUtil.toString(id); + Network network = Networks.create(networkName, networkId); + return ObjectHandles.getGlobal().create(network); + } }); } @CEntryPoint(name = "getNetworkMetadata") public static NetworkMetadataPointer getNetworkMetadata(IsolateThread thread, ObjectHandle networkHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - return createNetworkMetadata(network); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public NetworkMetadataPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + return createNetworkMetadata(network); + } }); } @CEntryPoint(name = "freeNetworkMetadata") public static void freeNetworkMetadata(IsolateThread thread, NetworkMetadataPointer ptr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> freeNetworkMetadata(ptr)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + freeNetworkMetadata(ptr); + } + }); } private static NetworkMetadataPointer createNetworkMetadata(Network network) { @@ -136,15 +152,18 @@ private static void freeNetworkMetadata(NetworkMetadataPointer networkMetadataPo public static ObjectHandle loadNetwork(IsolateThread thread, CCharPointer file, CCharPointerPointer parameterNamesPtrPtr, int parameterNamesCount, CCharPointerPointer parameterValuesPtrPtr, int parameterValuesCount, ObjectHandle reporterHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String fileStr = CTypeUtil.toString(file); - Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); - Reporter reporter = ObjectHandles.getGlobal().get(reporterHandle); - if (reporter == null) { - reporter = ReporterModel.NO_OP; + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + String fileStr = CTypeUtil.toString(file); + Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); + Reporter reporter = ObjectHandles.getGlobal().get(reporterHandle); + if (reporter == null) { + reporter = ReporterModel.NO_OP; + } + Network network = Network.read(Paths.get(fileStr), LocalComputationManager.getDefault(), ImportConfig.load(), parameters, IMPORTERS_LOADER_SUPPLIER, reporter); + return ObjectHandles.getGlobal().create(network); } - Network network = Network.read(Paths.get(fileStr), LocalComputationManager.getDefault(), ImportConfig.load(), parameters, IMPORTERS_LOADER_SUPPLIER, reporter); - return ObjectHandles.getGlobal().create(network); }); } @@ -153,19 +172,22 @@ public static ObjectHandle loadNetworkFromString(IsolateThread thread, CCharPoin CCharPointerPointer parameterNamesPtrPtr, int parameterNamesCount, CCharPointerPointer parameterValuesPtrPtr, int parameterValuesCount, ObjectHandle reporterHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String fileNameStr = CTypeUtil.toString(fileName); - String fileContentStr = CTypeUtil.toString(fileContent); - Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); - Reporter reporter = ReportCUtils.getReporter(reporterHandle); - try (InputStream is = new ByteArrayInputStream(fileContentStr.getBytes(StandardCharsets.UTF_8))) { - if (reporter == null) { - reporter = ReporterModel.NO_OP; + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + String fileNameStr = CTypeUtil.toString(fileName); + String fileContentStr = CTypeUtil.toString(fileContent); + Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); + Reporter reporter = ReportCUtils.getReporter(reporterHandle); + try (InputStream is = new ByteArrayInputStream(fileContentStr.getBytes(StandardCharsets.UTF_8))) { + if (reporter == null) { + reporter = ReporterModel.NO_OP; + } + Network network = Network.read(fileNameStr, is, LocalComputationManager.getDefault(), ImportConfig.load(), parameters, IMPORTERS_LOADER_SUPPLIER, reporter); + return ObjectHandles.getGlobal().create(network); + } catch (IOException e) { + throw new UncheckedIOException(e); } - Network network = Network.read(fileNameStr, is, LocalComputationManager.getDefault(), ImportConfig.load(), parameters, IMPORTERS_LOADER_SUPPLIER, reporter); - return ObjectHandles.getGlobal().create(network); - } catch (IOException e) { - throw new UncheckedIOException(e); } }); } @@ -174,39 +196,42 @@ public static ObjectHandle loadNetworkFromString(IsolateThread thread, CCharPoin public static ObjectHandle loadNetworkFromBinaryBuffers(IsolateThread thread, CCharPointerPointer data, CIntPointer dataSizes, int bufferCount, CCharPointerPointer parameterNamesPtrPtr, int parameterNamesCount, CCharPointerPointer parameterValuesPtrPtr, int parameterValuesCount, ObjectHandle reporterHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); - Reporter reporter = ObjectHandles.getGlobal().get(reporterHandle); - List bufferSizes = CTypeUtil.toIntegerList(dataSizes, bufferCount); - List dataSourceList = new ArrayList<>(); - for (int i = 0; i < bufferCount; ++i) { - ByteBuffer buffer = CTypeConversion.asByteBuffer(data.read(i), bufferSizes.get(i)); - Optional format = detectCompressionFormat(buffer); - if (format.isPresent() && CompressionFormat.ZIP.equals(format.get())) { - InMemoryZipFileDataSource ds = new InMemoryZipFileDataSource(binaryBufferToBytes(buffer)); - String commonBasename = null; - try { - for (String filename : ds.listNames(".*")) { - String basename = DataSourceUtil.getBaseName(filename); - commonBasename = commonBasename == null ? basename : StringUtils.getCommonPrefix(commonBasename, basename); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); + Reporter reporter = ObjectHandles.getGlobal().get(reporterHandle); + List bufferSizes = CTypeUtil.toIntegerList(dataSizes, bufferCount); + List dataSourceList = new ArrayList<>(); + for (int i = 0; i < bufferCount; ++i) { + ByteBuffer buffer = CTypeConversion.asByteBuffer(data.read(i), bufferSizes.get(i)); + Optional format = detectCompressionFormat(buffer); + if (format.isPresent() && CompressionFormat.ZIP.equals(format.get())) { + InMemoryZipFileDataSource ds = new InMemoryZipFileDataSource(binaryBufferToBytes(buffer)); + String commonBasename = null; + try { + for (String filename : ds.listNames(".*")) { + String basename = DataSourceUtil.getBaseName(filename); + commonBasename = commonBasename == null ? basename : StringUtils.getCommonPrefix(commonBasename, basename); + } + } catch (IOException e) { + throw new PowsyblException("Unsupported network data format in zip buffer."); } - } catch (IOException e) { - throw new PowsyblException("Unsupported network data format in zip buffer."); - } - if (commonBasename != null) { - ds.setBaseName(commonBasename); + if (commonBasename != null) { + ds.setBaseName(commonBasename); + } + dataSourceList.add(ds); + } else { + throw new PowsyblException("Network loading from memory buffer only supported with zipped networks."); } - dataSourceList.add(ds); - } else { - throw new PowsyblException("Network loading from memory buffer only supported with zipped networks."); } + if (reporter == null) { + reporter = Reporter.NO_OP; + } + MultipleReadOnlyDataSource dataSource = new MultipleReadOnlyDataSource(dataSourceList); + Network network = Network.read(dataSource, parameters, reporter); + return ObjectHandles.getGlobal().create(network); } - if (reporter == null) { - reporter = Reporter.NO_OP; - } - MultipleReadOnlyDataSource dataSource = new MultipleReadOnlyDataSource(dataSourceList); - Network network = Network.read(dataSource, parameters, reporter); - return ObjectHandles.getGlobal().create(network); }); } @@ -215,16 +240,19 @@ public static void dumpNetwork(IsolateThread thread, ObjectHandle networkHandle, CCharPointerPointer parameterNamesPtrPtr, int parameterNamesCount, CCharPointerPointer parameterValuesPtrPtr, int parameterValuesCount, ObjectHandle reporterHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String fileStr = CTypeUtil.toString(file); - String formatStr = CTypeUtil.toString(format); - Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); - Reporter reporter = ObjectHandles.getGlobal().get(reporterHandle); - if (reporter == null) { - reporter = ReporterModel.NO_OP; + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String fileStr = CTypeUtil.toString(file); + String formatStr = CTypeUtil.toString(format); + Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); + Reporter reporter = ObjectHandles.getGlobal().get(reporterHandle); + if (reporter == null) { + reporter = ReporterModel.NO_OP; + } + network.write(EXPORTERS_LOADER_SUPPLIER, formatStr, parameters, Paths.get(fileStr), reporter); } - network.write(EXPORTERS_LOADER_SUPPLIER, formatStr, parameters, Paths.get(fileStr), reporter); }); } @@ -233,29 +261,32 @@ public static CCharPointer dumpNetworkToString(IsolateThread thread, ObjectHandl CCharPointerPointer parameterNamesPtrPtr, int parameterNamesCount, CCharPointerPointer parameterValuesPtrPtr, int parameterValuesCount, ObjectHandle reporterHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String formatStr = CTypeUtil.toString(format); - Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); - MemDataSource dataSource = new MemDataSource(); - var exporter = Exporter.find(formatStr); - if (exporter == null) { - throw new PowsyblException("No exporter found for '" + formatStr + "' to export as a string"); - } - Reporter reporter = ReportCUtils.getReporter(reporterHandle); - exporter.export(network, parameters, dataSource, reporter); - try { - var names = dataSource.listNames(".*?"); - if (names.size() != 1) { - throw new PowsyblException("Currently we only support string export for single file format(ex, 'XIIDM')."); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public CCharPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String formatStr = CTypeUtil.toString(format); + Properties parameters = createParameters(parameterNamesPtrPtr, parameterNamesCount, parameterValuesPtrPtr, parameterValuesCount); + MemDataSource dataSource = new MemDataSource(); + var exporter = Exporter.find(formatStr); + if (exporter == null) { + throw new PowsyblException("No exporter found for '" + formatStr + "' to export as a string"); } - try (InputStream is = new ByteArrayInputStream(dataSource.getData(Iterables.getOnlyElement(names))); - ByteArrayOutputStream os = new ByteArrayOutputStream()) { - IOUtils.copy(is, os); - return CTypeUtil.toCharPtr(os.toString()); + Reporter reporter = ReportCUtils.getReporter(reporterHandle); + exporter.export(network, parameters, dataSource, reporter); + try { + var names = dataSource.listNames(".*?"); + if (names.size() != 1) { + throw new PowsyblException("Currently we only support string export for single file format(ex, 'XIIDM')."); + } + try (InputStream is = new ByteArrayInputStream(dataSource.getData(Iterables.getOnlyElement(names))); + ByteArrayOutputStream os = new ByteArrayOutputStream()) { + IOUtils.copy(is, os); + return CTypeUtil.toCharPtr(os.toString()); + } + } catch (IOException e) { + throw new UncheckedIOException(e); } - } catch (IOException e) { - throw new UncheckedIOException(e); } }); } @@ -268,31 +299,34 @@ public static void reduceNetwork(IsolateThread thread, ObjectHandle networkHandl CIntPointer depthsPtr, int depthsCount, boolean withDanglingLines, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - ReductionOptions options = new ReductionOptions(); - options.withDanglingLlines(withDanglingLines); - List predicates = new ArrayList<>(); - if (vMax != Double.MAX_VALUE || vMin != 0) { - predicates.add(new NominalVoltageNetworkPredicate(vMin, vMax)); - } - if (idsCount != 0) { - List ids = toStringList(idsPtrPtr, idsCount); - predicates.add(new IdentifierNetworkPredicate(ids)); - } - if (depthsCount != 0) { - final List depths = CTypeUtil.toIntegerList(depthsPtr, depthsCount); - final List voltageLeveles = toStringList(vlsPtrPtr, vlsCount); - for (int i = 0; i < depths.size(); i++) { - predicates.add(new SubNetworkPredicate(network.getVoltageLevel(voltageLeveles.get(i)), depths.get(i))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + ReductionOptions options = new ReductionOptions(); + options.withDanglingLlines(withDanglingLines); + List predicates = new ArrayList<>(); + if (vMax != Double.MAX_VALUE || vMin != 0) { + predicates.add(new NominalVoltageNetworkPredicate(vMin, vMax)); + } + if (idsCount != 0) { + List ids = toStringList(idsPtrPtr, idsCount); + predicates.add(new IdentifierNetworkPredicate(ids)); + } + if (depthsCount != 0) { + final List depths = CTypeUtil.toIntegerList(depthsPtr, depthsCount); + final List voltageLeveles = toStringList(vlsPtrPtr, vlsCount); + for (int i = 0; i < depths.size(); i++) { + predicates.add(new SubNetworkPredicate(network.getVoltageLevel(voltageLeveles.get(i)), depths.get(i))); + } } + final OrNetworkPredicate orNetworkPredicate = new OrNetworkPredicate(predicates); + NetworkReducer.builder() + .withNetworkPredicate(orNetworkPredicate) + .withReductionOptions(options) + .build() + .reduce(network); } - final OrNetworkPredicate orNetworkPredicate = new OrNetworkPredicate(predicates); - NetworkReducer.builder() - .withNetworkPredicate(orNetworkPredicate) - .withReductionOptions(options) - .build() - .reduce(network); }); } @@ -312,44 +346,59 @@ public static ArrayPointer getNetworkElementsIds(IsolateThr CDoublePointer nominalVoltagePtr, int nominalVoltageCount, CCharPointerPointer countryPtr, int countryCount, boolean mainCc, boolean mainSc, boolean notConnectedToSameBusAtBothSides, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - Set nominalVoltages = new HashSet<>(CTypeUtil.toDoubleList(nominalVoltagePtr, nominalVoltageCount)); - Set countries = new HashSet<>(toStringList(countryPtr, countryCount)); - List elementsIds = NetworkUtil.getElementsIds(network, elementType, nominalVoltages, countries, mainCc, mainSc, notConnectedToSameBusAtBothSides); - return createCharPtrArray(elementsIds); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + Set nominalVoltages = new HashSet<>(CTypeUtil.toDoubleList(nominalVoltagePtr, nominalVoltageCount)); + Set countries = new HashSet<>(toStringList(countryPtr, countryCount)); + List elementsIds = NetworkUtil.getElementsIds(network, elementType, nominalVoltages, countries, mainCc, mainSc, notConnectedToSameBusAtBothSides); + return createCharPtrArray(elementsIds); + } }); } @CEntryPoint(name = "cloneVariant") public static void cloneVariant(IsolateThread thread, ObjectHandle networkHandle, CCharPointer src, CCharPointer variant, boolean mayOverwrite, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - network.getVariantManager().cloneVariant(CTypeUtil.toString(src), CTypeUtil.toString(variant), mayOverwrite); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + network.getVariantManager().cloneVariant(CTypeUtil.toString(src), CTypeUtil.toString(variant), mayOverwrite); + } }); } @CEntryPoint(name = "setWorkingVariant") public static void setWorkingVariant(IsolateThread thread, ObjectHandle networkHandle, CCharPointer variant, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - network.getVariantManager().setWorkingVariant(CTypeUtil.toString(variant)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + network.getVariantManager().setWorkingVariant(CTypeUtil.toString(variant)); + } }); } @CEntryPoint(name = "removeVariant") public static void removeVariant(IsolateThread thread, ObjectHandle networkHandle, CCharPointer variant, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - network.getVariantManager().removeVariant(CTypeUtil.toString(variant)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + network.getVariantManager().removeVariant(CTypeUtil.toString(variant)); + } }); } @CEntryPoint(name = "getVariantsIds") public static ArrayPointer getVariantsIds(IsolateThread thread, ObjectHandle networkHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - return createCharPtrArray(List.copyOf(network.getVariantManager().getVariantIds())); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + return createCharPtrArray(List.copyOf(network.getVariantManager().getVariantIds())); + } }); } @@ -373,11 +422,14 @@ public static ArrayPointer createNetworkElementsSeriesArray(Isola CCharPointerPointer attributesPtrPtr, int attributesCount, DataframePointer selectedElementsDataframe, ExceptionHandlerPointer exceptionHandlerPtr) { - return Util.doCatch(exceptionHandlerPtr, () -> { - NetworkDataframeMapper mapper = NetworkDataframes.getDataframeMapper(convert(elementType)); - Network network = ObjectHandles.getGlobal().get(networkHandle); - DataframeFilter dataframeFilter = createDataframeFilter(filterAttributesType, attributesPtrPtr, attributesCount, selectedElementsDataframe); - return Dataframes.createCDataframe(mapper, network, dataframeFilter); + return Util.doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + NetworkDataframeMapper mapper = NetworkDataframes.getDataframeMapper(convert(elementType)); + Network network = ObjectHandles.getGlobal().get(networkHandle); + DataframeFilter dataframeFilter = createDataframeFilter(filterAttributesType, attributesPtrPtr, attributesCount, selectedElementsDataframe); + return Dataframes.createCDataframe(mapper, network, dataframeFilter); + } }); } @@ -389,20 +441,28 @@ public static ArrayPointer createNetworkElemen String name = CTypeUtil.toString(extensionName); String tempName = CTypeUtil.toString(cTableName); String tableName = tempName.isEmpty() ? null : tempName; - return doCatch(exceptionHandlerPtr, () -> { - NetworkDataframeMapper mapper = NetworkDataframes.getExtensionDataframeMapper(name, tableName); - if (mapper != null) { - Network network = ObjectHandles.getGlobal().get(networkHandle); - return Dataframes.createCDataframe(mapper, network); - } else { - throw new PowsyblException("extension " + name + " not found"); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + NetworkDataframeMapper mapper = NetworkDataframes.getExtensionDataframeMapper(name, tableName); + if (mapper != null) { + Network network = ObjectHandles.getGlobal().get(networkHandle); + return Dataframes.createCDataframe(mapper, network); + } else { + throw new PowsyblException("extension " + name + " not found"); + } } }); } @CEntryPoint(name = "getExtensionsNames") public static ArrayPointer getExtensionsNames(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(List.copyOf(NetworkExtensions.getExtensionsNames()))); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + return createCharPtrArray(List.copyOf(NetworkExtensions.getExtensionsNames())); + } + }); } @CEntryPoint(name = "getExtensionsInformation") @@ -415,14 +475,17 @@ public static void createElement(IsolateThread thread, ObjectHandle networkHandl ElementType elementType, DataframeArrayPointer cDataframes, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - DataframeElementType type = convert(elementType); - List dataframes = new ArrayList<>(); - for (int i = 0; i < cDataframes.getDataframesCount(); i++) { - dataframes.add(createDataframe(cDataframes.getDataframes().addressOf(i))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + DataframeElementType type = convert(elementType); + List dataframes = new ArrayList<>(); + for (int i = 0; i < cDataframes.getDataframesCount(); i++) { + dataframes.add(createDataframe(cDataframes.getDataframes().addressOf(i))); + } + NetworkElementAdders.addElements(type, network, dataframes); } - NetworkElementAdders.addElements(type, network, dataframes); }); } @@ -430,10 +493,13 @@ public static void createElement(IsolateThread thread, ObjectHandle networkHandl public static void updateNetworkElementsWithSeries(IsolateThread thread, ObjectHandle networkHandle, ElementType elementType, DataframePointer dataframe, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - UpdatingDataframe updatingDataframe = createDataframe(dataframe); - NetworkDataframes.getDataframeMapper(convert(elementType)).updateSeries(network, updatingDataframe); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + UpdatingDataframe updatingDataframe = createDataframe(dataframe); + NetworkDataframes.getDataframeMapper(convert(elementType)).updateSeries(network, updatingDataframe); + } }); } @@ -441,46 +507,52 @@ public static void updateNetworkElementsWithSeries(IsolateThread thread, ObjectH public static void removeAliases(IsolateThread thread, ObjectHandle networkHandle, DataframePointer cDataframe, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - UpdatingDataframe dataframe = createDataframe(cDataframe); - AliasDataframeAdder.deleteElements(network, dataframe); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + UpdatingDataframe dataframe = createDataframe(cDataframe); + AliasDataframeAdder.deleteElements(network, dataframe); + } }); } @CEntryPoint(name = "removeNetworkElements") public static void removeNetworkElements(IsolateThread thread, ObjectHandle networkHandle, CCharPointerPointer cElementIds, int elementCount, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - List elementIds = CTypeUtil.toStringList(cElementIds, elementCount); - elementIds.forEach(elementId -> { - Identifiable identifiable = network.getIdentifiable(elementId); - if (identifiable == null) { - throw new PowsyblException(String.format("identifiable with id : %s was not found", elementId)); - } - if (identifiable instanceof Connectable) { - ((Connectable) identifiable).remove(); - } else if (identifiable instanceof HvdcLine hvdcLine) { - hvdcLine.remove(); - } else if (identifiable instanceof VoltageLevel voltageLevel) { - voltageLevel.remove(); - } else if (identifiable instanceof Substation substation) { - substation.remove(); - } else if (identifiable instanceof Switch sw) { - VoltageLevel voltageLevel = sw.getVoltageLevel(); - switch (voltageLevel.getTopologyKind()) { - case NODE_BREAKER -> voltageLevel.getNodeBreakerView().removeSwitch(identifiable.getId()); - case BUS_BREAKER -> voltageLevel.getBusBreakerView().removeSwitch(identifiable.getId()); - default -> - throw new PowsyblException("this voltage level does not have a proper topology kind"); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + List elementIds = CTypeUtil.toStringList(cElementIds, elementCount); + elementIds.forEach(elementId -> { + Identifiable identifiable = network.getIdentifiable(elementId); + if (identifiable == null) { + throw new PowsyblException(String.format("identifiable with id : %s was not found", elementId)); } - } else if (identifiable instanceof TieLine tieLine) { - tieLine.remove(); - } else { - throw new PowsyblException(String.format("identifiable with id : %s can't be removed", identifiable.getId())); - } - }); + if (identifiable instanceof Connectable) { + ((Connectable) identifiable).remove(); + } else if (identifiable instanceof HvdcLine hvdcLine) { + hvdcLine.remove(); + } else if (identifiable instanceof VoltageLevel voltageLevel) { + voltageLevel.remove(); + } else if (identifiable instanceof Substation substation) { + substation.remove(); + } else if (identifiable instanceof Switch sw) { + VoltageLevel voltageLevel = sw.getVoltageLevel(); + switch (voltageLevel.getTopologyKind()) { + case NODE_BREAKER -> voltageLevel.getNodeBreakerView().removeSwitch(identifiable.getId()); + case BUS_BREAKER -> voltageLevel.getBusBreakerView().removeSwitch(identifiable.getId()); + default -> + throw new PowsyblException("this voltage level does not have a proper topology kind"); + } + } else if (identifiable instanceof TieLine tieLine) { + tieLine.remove(); + } else { + throw new PowsyblException(String.format("identifiable with id : %s can't be removed", identifiable.getId())); + } + }); + } }); } @@ -509,89 +581,116 @@ public static UpdatingDataframe createDataframe(DataframePointer dataframe) { @CEntryPoint(name = "getNodeBreakerViewSwitches") public static ArrayPointer getNodeBreakerViewSwitches(IsolateThread thread, ObjectHandle networkHandle, CCharPointer voltageLevel, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - VoltageLevel.NodeBreakerView nodeBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getNodeBreakerView(); - return Dataframes.createCDataframe(Dataframes.nodeBreakerViewSwitches(), nodeBreakerView); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + VoltageLevel.NodeBreakerView nodeBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getNodeBreakerView(); + return Dataframes.createCDataframe(Dataframes.nodeBreakerViewSwitches(), nodeBreakerView); + } }); } @CEntryPoint(name = "getNodeBreakerViewNodes") public static ArrayPointer getNodeBreakerViewNodes(IsolateThread thread, ObjectHandle networkHandle, CCharPointer voltageLevel, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - VoltageLevel.NodeBreakerView nodeBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getNodeBreakerView(); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + VoltageLevel.NodeBreakerView nodeBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getNodeBreakerView(); - return Dataframes.createCDataframe(Dataframes.nodeBreakerViewNodes(), nodeBreakerView); + return Dataframes.createCDataframe(Dataframes.nodeBreakerViewNodes(), nodeBreakerView); + } }); } @CEntryPoint(name = "getNodeBreakerViewInternalConnections") public static ArrayPointer getNodeBreakerViewInternalConnections(IsolateThread thread, ObjectHandle networkHandle, CCharPointer voltageLevel, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - VoltageLevel.NodeBreakerView nodeBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getNodeBreakerView(); - return Dataframes.createCDataframe(Dataframes.nodeBreakerViewInternalConnection(), nodeBreakerView); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + VoltageLevel.NodeBreakerView nodeBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getNodeBreakerView(); + return Dataframes.createCDataframe(Dataframes.nodeBreakerViewInternalConnection(), nodeBreakerView); + } }); } @CEntryPoint(name = "getBusBreakerViewSwitches") public static PyPowsyblApiHeader.ArrayPointer getBusBreakerViewSwitches(IsolateThread thread, ObjectHandle networkHandle, CCharPointer voltageLevel, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - VoltageLevel.BusBreakerView busBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getBusBreakerView(); - return Dataframes.createCDataframe(Dataframes.busBreakerViewSwitches(), busBreakerView); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + VoltageLevel.BusBreakerView busBreakerView = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)).getBusBreakerView(); + return Dataframes.createCDataframe(Dataframes.busBreakerViewSwitches(), busBreakerView); + } }); } @CEntryPoint(name = "getBusBreakerViewBuses") public static PyPowsyblApiHeader.ArrayPointer getBusBreakerViewBuses(IsolateThread thread, ObjectHandle networkHandle, CCharPointer voltageLevel, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - VoltageLevel voltageLevel1 = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)); - return Dataframes.createCDataframe(Dataframes.busBreakerViewBuses(), voltageLevel1); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + VoltageLevel voltageLevel1 = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)); + return Dataframes.createCDataframe(Dataframes.busBreakerViewBuses(), voltageLevel1); + } }); } @CEntryPoint(name = "getBusBreakerViewElements") public static PyPowsyblApiHeader.ArrayPointer getBusBreakerViewElements(IsolateThread thread, ObjectHandle networkHandle, CCharPointer voltageLevel, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - VoltageLevel voltageLevel1 = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)); - return Dataframes.createCDataframe(Dataframes.busBreakerViewElements(), voltageLevel1); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + VoltageLevel voltageLevel1 = network.getVoltageLevel(CTypeUtil.toString(voltageLevel)); + return Dataframes.createCDataframe(Dataframes.busBreakerViewElements(), voltageLevel1); + } }); } @CEntryPoint(name = "merge") public static ObjectHandle merge(IsolateThread thread, VoidPointerPointer networkHandles, int networkCount, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network[] networks = new Network[networkCount]; - for (int i = 0; i < networkCount; ++i) { - ObjectHandle networkHandle = networkHandles.read(i); - Network network = ObjectHandles.getGlobal().get(networkHandle); - networks[i] = network; + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + Network[] networks = new Network[networkCount]; + for (int i = 0; i < networkCount; ++i) { + ObjectHandle networkHandle = networkHandles.read(i); + Network network = ObjectHandles.getGlobal().get(networkHandle); + networks[i] = network; + } + return ObjectHandles.getGlobal().create(Network.merge(networks)); } - return ObjectHandles.getGlobal().create(Network.merge(networks)); }); } @CEntryPoint(name = "getSeriesMetadata") public static DataframeMetadataPointer getSeriesMetadata(IsolateThread thread, ElementType elementType, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DataframeElementType type = convert(elementType); - List seriesMetadata = NetworkDataframes.getDataframeMapper(type).getSeriesMetadata(); - return CTypeUtil.createSeriesMetadata(seriesMetadata); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public DataframeMetadataPointer get() { + DataframeElementType type = convert(elementType); + List seriesMetadata = NetworkDataframes.getDataframeMapper(type).getSeriesMetadata(); + return CTypeUtil.createSeriesMetadata(seriesMetadata); + } }); } @CEntryPoint(name = "freeDataframeMetadata") public static void freeDataframeMetadata(IsolateThread thread, DataframeMetadataPointer metadata, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - freeDataframeMetadataContent(metadata); - UnmanagedMemory.free(metadata); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + freeDataframeMetadataContent(metadata); + UnmanagedMemory.free(metadata); + } }); } @@ -599,56 +698,65 @@ public static void freeDataframeMetadata(IsolateThread thread, DataframeMetadata public static DataframesMetadataPointer getCreationMetadata(IsolateThread thread, ElementType elementType, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DataframeElementType type = convert(elementType); - List> metadata = NetworkElementAdders.getAdder(type).getMetadata(); - DataframeMetadataPointer dataframeMetadataArray = UnmanagedMemory.calloc(metadata.size() * SizeOf.get(DataframeMetadataPointer.class)); - int i = 0; - for (List dataframeMetadata : metadata) { - CTypeUtil.createSeriesMetadata(dataframeMetadata, dataframeMetadataArray.addressOf(i)); - i++; - } + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public DataframesMetadataPointer get() { + DataframeElementType type = convert(elementType); + List> metadata = NetworkElementAdders.getAdder(type).getMetadata(); + DataframeMetadataPointer dataframeMetadataArray = UnmanagedMemory.calloc(metadata.size() * SizeOf.get(DataframeMetadataPointer.class)); + int i = 0; + for (List dataframeMetadata : metadata) { + CTypeUtil.createSeriesMetadata(dataframeMetadata, dataframeMetadataArray.addressOf(i)); + i++; + } - DataframesMetadataPointer res = UnmanagedMemory.calloc(SizeOf.get(DataframesMetadataPointer.class)); - res.setDataframesMetadata(dataframeMetadataArray); - res.setDataframesCount(metadata.size()); - return res; + DataframesMetadataPointer res = UnmanagedMemory.calloc(SizeOf.get(DataframesMetadataPointer.class)); + res.setDataframesMetadata(dataframeMetadataArray); + res.setDataframesCount(metadata.size()); + return res; + } }); } @CEntryPoint(name = "freeDataframesMetadata") public static void freeDataframesMetadata(IsolateThread thread, DataframesMetadataPointer cMetadata, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - for (int i = 0; i < cMetadata.getDataframesCount(); i++) { - DataframeMetadataPointer cDataframeMetadata = cMetadata.getDataframesMetadata().addressOf(i); - freeDataframeMetadataContent(cDataframeMetadata); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + for (int i = 0; i < cMetadata.getDataframesCount(); i++) { + DataframeMetadataPointer cDataframeMetadata = cMetadata.getDataframesMetadata().addressOf(i); + freeDataframeMetadataContent(cDataframeMetadata); + } + UnmanagedMemory.free(cMetadata.getDataframesMetadata()); + UnmanagedMemory.free(cMetadata); } - UnmanagedMemory.free(cMetadata.getDataframesMetadata()); - UnmanagedMemory.free(cMetadata); }); } @CEntryPoint(name = "addNetworkElementProperties") public static void addNetworkElementProperties(IsolateThread thread, ObjectHandle networkHandle, DataframePointer properties, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - UpdatingDataframe propertiesDataframe = createDataframe(properties); - Objects.requireNonNull(propertiesDataframe); - Network network = ObjectHandles.getGlobal().get(networkHandle); - StringSeries idSerie = propertiesDataframe.getStrings("id"); - if (idSerie == null) { - throw new PowsyblException("id is missing"); - } - for (SeriesMetadata column : propertiesDataframe.getSeriesMetadata()) { - if (!column.isIndex() && column.getType() == SeriesDataType.STRING) { - String seriesName = column.getName(); - StringSeries columnSerie = propertiesDataframe.getStrings(seriesName); - for (int i = 0; i < propertiesDataframe.getRowCount(); i++) { - String id = idSerie.get(i); - Identifiable identifiable = network.getIdentifiable(id); - if (identifiable != null) { - identifiable.setProperty(seriesName, columnSerie.get(i)); - } else { - throw new PowsyblException(String.format("identifiable with id : %s does not exist", id)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + UpdatingDataframe propertiesDataframe = createDataframe(properties); + Objects.requireNonNull(propertiesDataframe); + Network network = ObjectHandles.getGlobal().get(networkHandle); + StringSeries idSerie = propertiesDataframe.getStrings("id"); + if (idSerie == null) { + throw new PowsyblException("id is missing"); + } + for (SeriesMetadata column : propertiesDataframe.getSeriesMetadata()) { + if (!column.isIndex() && column.getType() == SeriesDataType.STRING) { + String seriesName = column.getName(); + StringSeries columnSerie = propertiesDataframe.getStrings(seriesName); + for (int i = 0; i < propertiesDataframe.getRowCount(); i++) { + String id = idSerie.get(i); + Identifiable identifiable = network.getIdentifiable(id); + if (identifiable != null) { + identifiable.setProperty(seriesName, columnSerie.get(i)); + } else { + throw new PowsyblException(String.format("identifiable with id : %s does not exist", id)); + } } } } @@ -658,11 +766,14 @@ public static void addNetworkElementProperties(IsolateThread thread, ObjectHandl @CEntryPoint(name = "removeNetworkElementProperties") public static void removeNetworkElementProperties(IsolateThread thread, ObjectHandle networkHandle, CCharPointerPointer idsPointer, int idsCount, CCharPointerPointer propertiesPointer, int propertiesCount, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - List ids = CTypeUtil.toStringList(idsPointer, idsCount); - List properties = CTypeUtil.toStringList(propertiesPointer, propertiesCount); - ids.forEach(id -> properties.forEach(property -> network.getIdentifiable(id).removeProperty(property))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + List ids = CTypeUtil.toStringList(idsPointer, idsCount); + List properties = CTypeUtil.toStringList(propertiesPointer, propertiesCount); + ids.forEach(id -> properties.forEach(property -> network.getIdentifiable(id).removeProperty(property))); + } }); } @@ -693,20 +804,23 @@ private static void createSeriesMetadata(List metadata, Datafram public static void updateNetworkElementsExtensionsWithSeries(IsolateThread thread, ObjectHandle networkHandle, CCharPointer namePtr, CCharPointer tableNamePtr, DataframePointer dataframe, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - String name = CTypeUtil.toString(namePtr); - String tmpName = CTypeUtil.toString(tableNamePtr); - String tableName = tmpName.equals("") ? null : tmpName; - NetworkDataframeMapper mapper = NetworkDataframes.getExtensionDataframeMapper(name, tableName); - if (mapper != null) { - Network network = ObjectHandles.getGlobal().get(networkHandle); - UpdatingDataframe updatingDataframe = createDataframe(dataframe); - mapper.updateSeries(network, updatingDataframe); - } else { - if (tableName != null) { - throw new PowsyblException("table " + tableName + " of extension " + name + " not found"); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + String name = CTypeUtil.toString(namePtr); + String tmpName = CTypeUtil.toString(tableNamePtr); + String tableName = tmpName.equals("") ? null : tmpName; + NetworkDataframeMapper mapper = NetworkDataframes.getExtensionDataframeMapper(name, tableName); + if (mapper != null) { + Network network = ObjectHandles.getGlobal().get(networkHandle); + UpdatingDataframe updatingDataframe = createDataframe(dataframe); + mapper.updateSeries(network, updatingDataframe); + } else { + if (tableName != null) { + throw new PowsyblException("table " + tableName + " of extension " + name + " not found"); + } + throw new PowsyblException("extension " + name + " not found"); } - throw new PowsyblException("extension " + name + " not found"); } }); } @@ -716,27 +830,33 @@ public static void removeExtensions(IsolateThread thread, ObjectHandle networkHa CCharPointer namePtr, CCharPointerPointer idsPtr, int idsCount, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String name = CTypeUtil.toString(namePtr); - List ids = CTypeUtil.toStringList(idsPtr, idsCount); - NetworkExtensions.removeExtensions(network, name, ids); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String name = CTypeUtil.toString(namePtr); + List ids = CTypeUtil.toStringList(idsPtr, idsCount); + NetworkExtensions.removeExtensions(network, name, ids); + } }); } @CEntryPoint(name = "getExtensionSeriesMetadata") public static DataframeMetadataPointer getExtensionSeriesMetadata(IsolateThread thread, CCharPointer namePtr, CCharPointer tableNamePtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String name = CTypeUtil.toString(namePtr); - String tmpName = CTypeUtil.toString(tableNamePtr); - String tableName = tmpName.equals("") ? null : tmpName; - NetworkDataframeMapper mapper = NetworkDataframes.getExtensionDataframeMapper(name, tableName); - if (mapper != null) { - List seriesMetadata = mapper.getSeriesMetadata(); - return CTypeUtil.createSeriesMetadata(seriesMetadata); - } else { - throw new PowsyblException("extension " + name + " not found"); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public DataframeMetadataPointer get() { + String name = CTypeUtil.toString(namePtr); + String tmpName = CTypeUtil.toString(tableNamePtr); + String tableName = tmpName.equals("") ? null : tmpName; + NetworkDataframeMapper mapper = NetworkDataframes.getExtensionDataframeMapper(name, tableName); + if (mapper != null) { + List seriesMetadata = mapper.getSeriesMetadata(); + return CTypeUtil.createSeriesMetadata(seriesMetadata); + } else { + throw new PowsyblException("extension " + name + " not found"); + } } }); } @@ -746,14 +866,17 @@ public static void createExtensions(IsolateThread thread, ObjectHandle networkHa CCharPointer namePtr, DataframeArrayPointer cDataframes, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String name = CTypeUtil.toString(namePtr); - List dataframes = new ArrayList<>(); - for (int i = 0; i < cDataframes.getDataframesCount(); i++) { - dataframes.add(createDataframe(cDataframes.getDataframes().addressOf(i))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String name = CTypeUtil.toString(namePtr); + List dataframes = new ArrayList<>(); + for (int i = 0; i < cDataframes.getDataframesCount(); i++) { + dataframes.add(createDataframe(cDataframes.getDataframes().addressOf(i))); + } + NetworkElementAdders.addExtensions(name, network, dataframes); } - NetworkElementAdders.addExtensions(name, network, dataframes); }); } @@ -761,66 +884,81 @@ public static void createExtensions(IsolateThread thread, ObjectHandle networkHa public static DataframesMetadataPointer getExtensionsCreationMetadata(IsolateThread thread, CCharPointer namePtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String name = CTypeUtil.toString(namePtr); - List> metadata = NetworkElementAdders.getExtensionAdder(name).getMetadata(); - DataframeMetadataPointer dataframeMetadataArray = UnmanagedMemory.calloc(metadata.size() * SizeOf.get(DataframeMetadataPointer.class)); - int i = 0; - for (List dataframeMetadata : metadata) { - CTypeUtil.createSeriesMetadata(dataframeMetadata, dataframeMetadataArray.addressOf(i)); - i++; - } + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public DataframesMetadataPointer get() { + String name = CTypeUtil.toString(namePtr); + List> metadata = NetworkElementAdders.getExtensionAdder(name).getMetadata(); + DataframeMetadataPointer dataframeMetadataArray = UnmanagedMemory.calloc(metadata.size() * SizeOf.get(DataframeMetadataPointer.class)); + int i = 0; + for (List dataframeMetadata : metadata) { + CTypeUtil.createSeriesMetadata(dataframeMetadata, dataframeMetadataArray.addressOf(i)); + i++; + } - DataframesMetadataPointer res = UnmanagedMemory.calloc(SizeOf.get(DataframesMetadataPointer.class)); - res.setDataframesMetadata(dataframeMetadataArray); - res.setDataframesCount(metadata.size()); - return res; + DataframesMetadataPointer res = UnmanagedMemory.calloc(SizeOf.get(DataframesMetadataPointer.class)); + res.setDataframesMetadata(dataframeMetadataArray); + res.setDataframesCount(metadata.size()); + return res; + } }); } @CEntryPoint(name = "createImporterParametersSeriesArray") static ArrayPointer createImporterParametersSeriesArray(IsolateThread thread, CCharPointer formatPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String format = CTypeUtil.toString(formatPtr); - Importer importer = Importer.find(format); - if (importer == null) { - throw new PowsyblException("Format '" + format + "' not supported"); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + String format = CTypeUtil.toString(formatPtr); + Importer importer = Importer.find(format); + if (importer == null) { + throw new PowsyblException("Format '" + format + "' not supported"); + } + return Dataframes.createCDataframe(Dataframes.importerParametersMapper(), importer); } - return Dataframes.createCDataframe(Dataframes.importerParametersMapper(), importer); }); } @CEntryPoint(name = "createExporterParametersSeriesArray") static ArrayPointer createExporterParametersSeriesArray(IsolateThread thread, CCharPointer formatPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String format = CTypeUtil.toString(formatPtr); - var exporter = Exporter.find(format); - if (exporter == null) { - throw new PowsyblException("Format '" + format + "' not supported"); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + String format = CTypeUtil.toString(formatPtr); + var exporter = Exporter.find(format); + if (exporter == null) { + throw new PowsyblException("Format '" + format + "' not supported"); + } + return Dataframes.createCDataframe(Dataframes.exporterParametersMapper(), exporter); } - return Dataframes.createCDataframe(Dataframes.exporterParametersMapper(), exporter); }); } @CEntryPoint(name = "updateSwitchPosition") public static boolean updateSwitchPosition(IsolateThread thread, ObjectHandle networkHandle, CCharPointer id, boolean open, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String idStr = CTypeUtil.toString(id); - return NetworkUtil.updateSwitchPosition(network, idStr, open); + return doCatch(exceptionHandlerPtr, new BooleanSupplier() { + @Override + public boolean getAsBoolean() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String idStr = CTypeUtil.toString(id); + return NetworkUtil.updateSwitchPosition(network, idStr, open); + } }); } @CEntryPoint(name = "updateConnectableStatus") public static boolean updateConnectableStatus(IsolateThread thread, ObjectHandle networkHandle, CCharPointer id, boolean connected, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String idStr = CTypeUtil.toString(id); - return NetworkUtil.updateConnectableStatus(network, idStr, connected); + return doCatch(exceptionHandlerPtr, new BooleanSupplier() { + @Override + public boolean getAsBoolean() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String idStr = CTypeUtil.toString(id); + return NetworkUtil.updateConnectableStatus(network, idStr, connected); + } }); } @@ -841,7 +979,12 @@ public static SldParametersPointer convertToSldParametersPointer(SldParameters p @CEntryPoint(name = "createSldParameters") public static SldParametersPointer createSldParameters(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> convertToSldParametersPointer(SingleLineDiagramUtil.createSldParameters())); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public SldParametersPointer get() { + return convertToSldParametersPointer(SingleLineDiagramUtil.createSldParameters()); + } + }); } public static void freeSldParametersPointer(SldParametersPointer sldParametersPtr) { @@ -851,8 +994,11 @@ public static void freeSldParametersPointer(SldParametersPointer sldParametersPt @CEntryPoint(name = "freeSldParameters") public static void freeSldParameters(IsolateThread thread, SldParametersPointer sldParametersPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - freeSldParametersPointer(sldParametersPtr); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + freeSldParametersPointer(sldParametersPtr); + } }); } @@ -873,42 +1019,56 @@ public static SldParameters convertSldParameters(SldParametersPointer sldParamet public static void writeSingleLineDiagramSvg(IsolateThread thread, ObjectHandle networkHandle, CCharPointer containerId, CCharPointer svgFile, CCharPointer metadataFile, SldParametersPointer sldParametersPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String containerIdStr = CTypeUtil.toString(containerId); - String svgFileStr = CTypeUtil.toString(svgFile); - String metadataFileStr = metadataFile.isNonNull() ? CTypeUtil.toString(metadataFile) : null; - SldParameters sldParameters = convertSldParameters(sldParametersPtr); - SingleLineDiagramUtil.writeSvg(network, containerIdStr, svgFileStr, metadataFileStr, sldParameters); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String containerIdStr = CTypeUtil.toString(containerId); + String svgFileStr = CTypeUtil.toString(svgFile); + String metadataFileStr = metadataFile.isNonNull() ? CTypeUtil.toString(metadataFile) : null; + SldParameters sldParameters = convertSldParameters(sldParametersPtr); + SingleLineDiagramUtil.writeSvg(network, containerIdStr, svgFileStr, metadataFileStr, sldParameters); + } }); } @CEntryPoint(name = "getSingleLineDiagramSvg") public static CCharPointer getSingleLineDiagramSvg(IsolateThread thread, ObjectHandle networkHandle, CCharPointer containerId, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String containerIdStr = CTypeUtil.toString(containerId); - String svg = SingleLineDiagramUtil.getSvg(network, containerIdStr); - return CTypeUtil.toCharPtr(svg); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public CCharPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String containerIdStr = CTypeUtil.toString(containerId); + String svg = SingleLineDiagramUtil.getSvg(network, containerIdStr); + return CTypeUtil.toCharPtr(svg); + } }); } @CEntryPoint(name = "getSingleLineDiagramSvgAndMetadata") public static ArrayPointer getSingleLineDiagramSvgAndMetadata(IsolateThread thread, ObjectHandle networkHandle, CCharPointer containerId, SldParametersPointer sldParametersPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String containerIdStr = CTypeUtil.toString(containerId); - SldParameters sldParameters = convertSldParameters(sldParametersPtr); - List svgAndMeta = SingleLineDiagramUtil.getSvgAndMetadata(network, containerIdStr, sldParameters); - return createCharPtrArray(svgAndMeta); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String containerIdStr = CTypeUtil.toString(containerId); + SldParameters sldParameters = convertSldParameters(sldParametersPtr); + List svgAndMeta = SingleLineDiagramUtil.getSvgAndMetadata(network, containerIdStr, sldParameters); + return createCharPtrArray(svgAndMeta); + } }); } @CEntryPoint(name = "getSingleLineDiagramComponentLibraryNames") public static PyPowsyblApiHeader.ArrayPointer getSingleLineDiagramComponentLibraryNames(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(SingleLineDiagramUtil.getComponentLibraryNames())); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + return createCharPtrArray(SingleLineDiagramUtil.getComponentLibraryNames()); + } + }); } @CEntryPoint(name = "writeNetworkAreaDiagramSvg") @@ -916,11 +1076,14 @@ public static void writeNetworkAreaDiagramSvg(IsolateThread thread, ObjectHandle CCharPointerPointer voltageLevelIdsPointer, int voltageLevelIdCount, int depth, double highNominalVoltageBound, double lowNominalVoltageBound, boolean edgeNameDisplayed, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String svgFileStr = CTypeUtil.toString(svgFile); - List voltageLevelIds = toStringList(voltageLevelIdsPointer, voltageLevelIdCount); - NetworkAreaDiagramUtil.writeSvg(network, voltageLevelIds, depth, svgFileStr, highNominalVoltageBound, lowNominalVoltageBound, edgeNameDisplayed); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String svgFileStr = CTypeUtil.toString(svgFile); + List voltageLevelIds = toStringList(voltageLevelIdsPointer, voltageLevelIdCount); + NetworkAreaDiagramUtil.writeSvg(network, voltageLevelIds, depth, svgFileStr, highNominalVoltageBound, lowNominalVoltageBound, edgeNameDisplayed); + } }); } @@ -928,21 +1091,27 @@ public static void writeNetworkAreaDiagramSvg(IsolateThread thread, ObjectHandle public static CCharPointer getNetworkAreaDiagramSvg(IsolateThread thread, ObjectHandle networkHandle, CCharPointerPointer voltageLevelIdsPointer, int voltageLevelIdCount, int depth, double highNominalVoltageBound, double lowNominalVoltageBound, boolean edgeNameDisplayed, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - List voltageLevelIds = toStringList(voltageLevelIdsPointer, voltageLevelIdCount); - String svg = NetworkAreaDiagramUtil.getSvg(network, voltageLevelIds, depth, highNominalVoltageBound, lowNominalVoltageBound, edgeNameDisplayed); - return CTypeUtil.toCharPtr(svg); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public CCharPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + List voltageLevelIds = toStringList(voltageLevelIdsPointer, voltageLevelIdCount); + String svg = NetworkAreaDiagramUtil.getSvg(network, voltageLevelIds, depth, highNominalVoltageBound, lowNominalVoltageBound, edgeNameDisplayed); + return CTypeUtil.toCharPtr(svg); + } }); } @CEntryPoint(name = "getNetworkAreaDiagramDisplayedVoltageLevels") public static PyPowsyblApiHeader.ArrayPointer getNetworkAreaDiagramDisplayedVoltageLevels(IsolateThread thread, ObjectHandle networkHandle, CCharPointerPointer voltageLevelIdsPointer, int voltageLevelIdCount, int depth, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - List voltageLevelIds = toStringList(voltageLevelIdsPointer, voltageLevelIdCount); - return createCharPtrArray(NetworkAreaDiagramUtil.getDisplayedVoltageLevels(network, voltageLevelIds, depth)); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + List voltageLevelIds = toStringList(voltageLevelIdsPointer, voltageLevelIdCount); + return createCharPtrArray(NetworkAreaDiagramUtil.getDisplayedVoltageLevels(network, voltageLevelIds, depth)); + } }); } @@ -974,9 +1143,12 @@ public static ValidationLevelType validate(IsolateThread thread, ObjectHandle ne public static void setMinValidationLevel(IsolateThread thread, ObjectHandle networkHandle, ValidationLevelType levelType, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - network.setMinimumAcceptableValidationLevel(Util.convert(levelType)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + network.setMinimumAcceptableValidationLevel(Util.convert(levelType)); + } }); } @@ -985,42 +1157,51 @@ public static DataframesMetadataPointer getModificationMetadataWithElementType(I NetworkModificationType networkModificationType, ElementType elementType, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DataframeNetworkModificationType modificationType = convert(networkModificationType); - DataframeElementType type = convert(elementType); - List> metadata = NetworkModifications.getModification(modificationType).getMetadata(type); - DataframeMetadataPointer dataframeMetadataArray = UnmanagedMemory.calloc(metadata.size() * SizeOf.get(DataframeMetadataPointer.class)); - int i = 0; - for (List dataframeMetadata : metadata) { - createSeriesMetadata(dataframeMetadata, dataframeMetadataArray.addressOf(i)); - i++; + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public DataframesMetadataPointer get() { + DataframeNetworkModificationType modificationType = convert(networkModificationType); + DataframeElementType type = convert(elementType); + List> metadata = NetworkModifications.getModification(modificationType).getMetadata(type); + DataframeMetadataPointer dataframeMetadataArray = UnmanagedMemory.calloc(metadata.size() * SizeOf.get(DataframeMetadataPointer.class)); + int i = 0; + for (List dataframeMetadata : metadata) { + createSeriesMetadata(dataframeMetadata, dataframeMetadataArray.addressOf(i)); + i++; + } + DataframesMetadataPointer res = UnmanagedMemory.calloc(SizeOf.get(DataframesMetadataPointer.class)); + res.setDataframesMetadata(dataframeMetadataArray); + res.setDataframesCount(metadata.size()); + return res; } - DataframesMetadataPointer res = UnmanagedMemory.calloc(SizeOf.get(DataframesMetadataPointer.class)); - res.setDataframesMetadata(dataframeMetadataArray); - res.setDataframesCount(metadata.size()); - return res; }); } @CEntryPoint(name = "getSubNetwork") public static ObjectHandle getSubNetwork(IsolateThread thread, ObjectHandle networkHandle, CCharPointer subNetworkId, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String subNetworkIdStr = CTypeUtil.toString(subNetworkId); - Network subnetwork = network.getSubnetwork(subNetworkIdStr); - if (subnetwork == null) { - throw new PowsyblException("Sub network '" + subNetworkIdStr + "' not found"); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String subNetworkIdStr = CTypeUtil.toString(subNetworkId); + Network subnetwork = network.getSubnetwork(subNetworkIdStr); + if (subnetwork == null) { + throw new PowsyblException("Sub network '" + subNetworkIdStr + "' not found"); + } + return ObjectHandles.getGlobal().create(subnetwork); } - return ObjectHandles.getGlobal().create(subnetwork); }); } @CEntryPoint(name = "detachSubNetwork") public static ObjectHandle detachSubNetwork(IsolateThread thread, ObjectHandle subNetworkHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network subNetwork = ObjectHandles.getGlobal().get(subNetworkHandle); - Network detachNetwork = subNetwork.detach(); - return ObjectHandles.getGlobal().create(detachNetwork); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + Network subNetwork = ObjectHandles.getGlobal().get(subNetworkHandle); + Network detachNetwork = subNetwork.detach(); + return ObjectHandles.getGlobal().create(detachNetwork); + } }); } } diff --git a/java/src/main/java/com/powsybl/python/network/NetworkModificationsCFunctions.java b/java/src/main/java/com/powsybl/python/network/NetworkModificationsCFunctions.java index e66436a2d0..e905927ab6 100644 --- a/java/src/main/java/com/powsybl/python/network/NetworkModificationsCFunctions.java +++ b/java/src/main/java/com/powsybl/python/network/NetworkModificationsCFunctions.java @@ -54,13 +54,16 @@ private NetworkModificationsCFunctions() { @CEntryPoint(name = "getConnectablesOrderPositions") public static PyPowsyblApiHeader.ArrayPointer getConnectablesOrderPositions(IsolateThread thread, ObjectHandle networkHandle, CCharPointer voltageLevelId, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String voltageLevelIdStr = CTypeUtil.toString(voltageLevelId); - Network network = ObjectHandles.getGlobal().get(networkHandle); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + String voltageLevelIdStr = CTypeUtil.toString(voltageLevelId); + Network network = ObjectHandles.getGlobal().get(networkHandle); - VoltageLevel voltageLevel = network.getVoltageLevel(voltageLevelIdStr); - Map> feederPositionsOrders = getFeedersByConnectable(voltageLevel); - return Dataframes.createCDataframe(Dataframes.feederMapMapper(), feederPositionsOrders); + VoltageLevel voltageLevel = network.getVoltageLevel(voltageLevelIdStr); + Map> feederPositionsOrders = getFeedersByConnectable(voltageLevel); + return Dataframes.createCDataframe(Dataframes.feederMapMapper(), feederPositionsOrders); + } }); } @@ -68,22 +71,25 @@ public static PyPowsyblApiHeader.ArrayPointer public static PyPowsyblApiHeader.ArrayPointer getUnusedConnectableOrderPositions(IsolateThread thread, ObjectHandle networkHandle, CCharPointer busbarSectionId, CCharPointer beforeOrAfter, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - String busbarSectionIdStr = CTypeUtil.toString(busbarSectionId); - BusbarSection busbarSection = network.getBusbarSection(busbarSectionIdStr); - Optional> positionsOrders; - if (CTypeUtil.toString(beforeOrAfter).equals("BEFORE")) { - positionsOrders = getUnusedOrderPositionsBefore(busbarSection); - } else { - positionsOrders = getUnusedOrderPositionsAfter(busbarSection); - } - if (positionsOrders.isPresent()) { - int max = positionsOrders.get().getMaximum(); - int min = positionsOrders.get().getMinimum(); - return createIntegerArray(Arrays.asList(min, max)); - } else { - return createIntegerArray(Collections.emptyList()); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + String busbarSectionIdStr = CTypeUtil.toString(busbarSectionId); + BusbarSection busbarSection = network.getBusbarSection(busbarSectionIdStr); + Optional> positionsOrders; + if (CTypeUtil.toString(beforeOrAfter).equals("BEFORE")) { + positionsOrders = getUnusedOrderPositionsBefore(busbarSection); + } else { + positionsOrders = getUnusedOrderPositionsAfter(busbarSection); + } + if (positionsOrders.isPresent()) { + int max = positionsOrders.get().getMaximum(); + int min = positionsOrders.get().getMinimum(); + return createIntegerArray(Arrays.asList(min, max)); + } else { + return createIntegerArray(Collections.emptyList()); + } } }); } @@ -94,15 +100,18 @@ public static void createNetworkModification(IsolateThread thread, ObjectHandle PyPowsyblApiHeader.NetworkModificationType networkModificationType, boolean throwException, ObjectHandle reporterHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - Network network = ObjectHandles.getGlobal().get(networkHandle); - ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); - List dfs = new ArrayList<>(); - for (int i = 0; i < cDataframes.getDataframesCount(); i++) { - dfs.add(createDataframe(cDataframes.getDataframes().addressOf(i))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + Network network = ObjectHandles.getGlobal().get(networkHandle); + ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); + List dfs = new ArrayList<>(); + for (int i = 0; i < cDataframes.getDataframesCount(); i++) { + dfs.add(createDataframe(cDataframes.getDataframes().addressOf(i))); + } + DataframeNetworkModificationType type = convert(networkModificationType); + NetworkModifications.applyModification(type, network, dfs, throwException, reporter); } - DataframeNetworkModificationType type = convert(networkModificationType); - NetworkModifications.applyModification(type, network, dfs, throwException, reporter); }); } @@ -110,10 +119,13 @@ public static void createNetworkModification(IsolateThread thread, ObjectHandle public static PyPowsyblApiHeader.DataframeMetadataPointer getModificationMetadata(IsolateThread thread, PyPowsyblApiHeader.NetworkModificationType networkModificationType, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - DataframeNetworkModificationType type = convert(networkModificationType); - List metadata = NetworkModifications.getModification(type).getMetadata(); - return CTypeUtil.createSeriesMetadata(metadata); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public PyPowsyblApiHeader.DataframeMetadataPointer get() { + DataframeNetworkModificationType type = convert(networkModificationType); + List metadata = NetworkModifications.getModification(type).getMetadata(); + return CTypeUtil.createSeriesMetadata(metadata); + } }); } @@ -124,27 +136,30 @@ public static void removeElementsModification(IsolateThread thread, ObjectHandle PyPowsyblApiHeader.RemoveModificationType removeModificationType, boolean throwException, ObjectHandle reporterHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - List ids = toStringList(connectableIdsPtrPtr, connectableIdsCount); - Network network = ObjectHandles.getGlobal().get(networkHandle); - ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); - if (removeModificationType == PyPowsyblApiHeader.RemoveModificationType.REMOVE_FEEDER) { - ids.forEach(id -> new RemoveFeederBayBuilder().withConnectableId(id).build().apply(network, throwException, reporter == null ? Reporter.NO_OP : reporter)); - } else if (removeModificationType == PyPowsyblApiHeader.RemoveModificationType.REMOVE_VOLTAGE_LEVEL) { - ids.forEach(id -> new RemoveVoltageLevelBuilder().withVoltageLevelId(id).build().apply(network, throwException, reporter == null ? Reporter.NO_OP : reporter)); - } else if (removeModificationType == PyPowsyblApiHeader.RemoveModificationType.REMOVE_HVDC_LINE) { - UpdatingDataframe extraDataDf = createDataframe(extraDataDfPtr); - ids.forEach(hvdcId -> { - List shuntCompensatorList = Collections.EMPTY_LIST; - if (extraDataDf != null) { - Optional shuntCompensatorOptional = extraDataDf.getStringValue(hvdcId, 0); - String shuntCompensator = shuntCompensatorOptional.isEmpty() || shuntCompensatorOptional.get().isEmpty() ? "," : - shuntCompensatorOptional.get(); - shuntCompensatorList = Arrays.stream(shuntCompensator.split(",")).collect(Collectors.toList()); - } - new RemoveHvdcLineBuilder().withHvdcLineId(hvdcId).withShuntCompensatorIds(shuntCompensatorList).build().apply(network, throwException, reporter == null ? Reporter.NO_OP : reporter); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + List ids = toStringList(connectableIdsPtrPtr, connectableIdsCount); + Network network = ObjectHandles.getGlobal().get(networkHandle); + ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); + if (removeModificationType == PyPowsyblApiHeader.RemoveModificationType.REMOVE_FEEDER) { + ids.forEach(id -> new RemoveFeederBayBuilder().withConnectableId(id).build().apply(network, throwException, reporter == null ? Reporter.NO_OP : reporter)); + } else if (removeModificationType == PyPowsyblApiHeader.RemoveModificationType.REMOVE_VOLTAGE_LEVEL) { + ids.forEach(id -> new RemoveVoltageLevelBuilder().withVoltageLevelId(id).build().apply(network, throwException, reporter == null ? Reporter.NO_OP : reporter)); + } else if (removeModificationType == PyPowsyblApiHeader.RemoveModificationType.REMOVE_HVDC_LINE) { + UpdatingDataframe extraDataDf = createDataframe(extraDataDfPtr); + ids.forEach(hvdcId -> { + List shuntCompensatorList = Collections.EMPTY_LIST; + if (extraDataDf != null) { + Optional shuntCompensatorOptional = extraDataDf.getStringValue(hvdcId, 0); + String shuntCompensator = shuntCompensatorOptional.isEmpty() || shuntCompensatorOptional.get().isEmpty() ? "," : + shuntCompensatorOptional.get(); + shuntCompensatorList = Arrays.stream(shuntCompensator.split(",")).collect(Collectors.toList()); + } + new RemoveHvdcLineBuilder().withHvdcLineId(hvdcId).withShuntCompensatorIds(shuntCompensatorList).build().apply(network, throwException, reporter == null ? Reporter.NO_OP : reporter); - }); + }); + } } }); } diff --git a/java/src/main/java/com/powsybl/python/report/ReportCFunctions.java b/java/src/main/java/com/powsybl/python/report/ReportCFunctions.java index 70aa773ebb..211e7744f7 100644 --- a/java/src/main/java/com/powsybl/python/report/ReportCFunctions.java +++ b/java/src/main/java/com/powsybl/python/report/ReportCFunctions.java @@ -12,6 +12,7 @@ import com.powsybl.python.commons.CTypeUtil; import com.powsybl.python.commons.Directives; import com.powsybl.python.commons.PyPowsyblApiHeader; +import com.powsybl.python.commons.Util; import org.graalvm.nativeimage.IsolateThread; import org.graalvm.nativeimage.ObjectHandle; import org.graalvm.nativeimage.ObjectHandles; @@ -36,36 +37,45 @@ private ReportCFunctions() { @CEntryPoint(name = "createReporterModel") public static ObjectHandle createReporterModel(IsolateThread thread, CCharPointer taskKeyPtr, CCharPointer defaultNamePtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String taskKey = CTypeUtil.toString(taskKeyPtr); - String defaultName = CTypeUtil.toString(defaultNamePtr); - ReporterModel reporterModel = new ReporterModel(taskKey, defaultName); - return ObjectHandles.getGlobal().create(reporterModel); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + String taskKey = CTypeUtil.toString(taskKeyPtr); + String defaultName = CTypeUtil.toString(defaultNamePtr); + ReporterModel reporterModel = new ReporterModel(taskKey, defaultName); + return ObjectHandles.getGlobal().create(reporterModel); + } }); } @CEntryPoint(name = "printReport") public static CCharPointer printReport(IsolateThread thread, ObjectHandle reporterModelHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - ReporterModel reporterModel = ObjectHandles.getGlobal().get(reporterModelHandle); - StringWriter reporterOut = new StringWriter(); - reporterModel.export(reporterOut); - return CTypeUtil.toCharPtr(reporterOut.toString()); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public CCharPointer get() { + ReporterModel reporterModel = ObjectHandles.getGlobal().get(reporterModelHandle); + StringWriter reporterOut = new StringWriter(); + reporterModel.export(reporterOut); + return CTypeUtil.toCharPtr(reporterOut.toString()); + } }); } @CEntryPoint(name = "jsonReport") public static CCharPointer jsonReport(IsolateThread thread, ObjectHandle reporterModelHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - ReporterModel reporterModel = ObjectHandles.getGlobal().get(reporterModelHandle); - StringWriter reporterOut = new StringWriter(); - ObjectMapper objectMapper = new ObjectMapper().registerModule(new ReporterModelJsonModule()); - try { - objectMapper.writerWithDefaultPrettyPrinter().writeValue(reporterOut, reporterModel); - } catch (IOException e) { - throw new UncheckedIOException(e); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public CCharPointer get() { + ReporterModel reporterModel = ObjectHandles.getGlobal().get(reporterModelHandle); + StringWriter reporterOut = new StringWriter(); + ObjectMapper objectMapper = new ObjectMapper().registerModule(new ReporterModelJsonModule()); + try { + objectMapper.writerWithDefaultPrettyPrinter().writeValue(reporterOut, reporterModel); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return CTypeUtil.toCharPtr(reporterOut.toString()); } - return CTypeUtil.toCharPtr(reporterOut.toString()); }); } } diff --git a/java/src/main/java/com/powsybl/python/security/SecurityAnalysisCFunctions.java b/java/src/main/java/com/powsybl/python/security/SecurityAnalysisCFunctions.java index 89922fd341..e9fe64b57f 100644 --- a/java/src/main/java/com/powsybl/python/security/SecurityAnalysisCFunctions.java +++ b/java/src/main/java/com/powsybl/python/security/SecurityAnalysisCFunctions.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Objects; import java.util.Set; +import java.util.function.Consumer; import java.util.stream.Collectors; import static com.powsybl.python.commons.CTypeUtil.toStringList; @@ -62,20 +63,33 @@ private static Logger logger() { @CEntryPoint(name = "getSecurityAnalysisProviderNames") public static PyPowsyblApiHeader.ArrayPointer getSecurityAnalysisProviderNames(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(SecurityAnalysisProvider.findAll() - .stream().map(SecurityAnalysisProvider::getName).collect(Collectors.toList()))); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + return createCharPtrArray(SecurityAnalysisProvider.findAll() + .stream().map(SecurityAnalysisProvider::getName).collect(Collectors.toList())); + } + }); } @CEntryPoint(name = "setDefaultSecurityAnalysisProvider") public static void setDefaultSecurityAnalysisProvider(IsolateThread thread, CCharPointer provider, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - PyPowsyblConfiguration.setDefaultSecurityAnalysisProvider(CTypeUtil.toString(provider)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + PyPowsyblConfiguration.setDefaultSecurityAnalysisProvider(CTypeUtil.toString(provider)); + } }); } @CEntryPoint(name = "getDefaultSecurityAnalysisProvider") public static CCharPointer getDefaultSecurityAnalysisProvider(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultSecurityAnalysisProvider())); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public CCharPointer get() { + return CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultSecurityAnalysisProvider()); + } + }); } @CEntryPoint(name = "addMonitoredElements") @@ -85,54 +99,77 @@ public static void addMonitoredElements(IsolateThread thread, ObjectHandle secur CCharPointerPointer threeWindingsTransformerIds, int threeWindingsTransformerIdsCount, CCharPointerPointer contingencyIds, int contingencyIdsCount, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(securityAnalysisContextHandle); - List contingencies = toStringList(contingencyIds, contingencyIdsCount); - contingencies.forEach(contingency -> { - 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)))); - }); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + SecurityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(securityAnalysisContextHandle); + List contingencies = toStringList(contingencyIds, contingencyIdsCount); + contingencies.forEach(new Consumer() { + @Override + public void accept(String contingency) { + 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)))); + } + }); + } }); } @CEntryPoint(name = "getBranchResults") public static PyPowsyblApiHeader.ArrayPointer getBranchResults(IsolateThread thread, ObjectHandle securityAnalysisResult, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResult); - return Dataframes.createCDataframe(Dataframes.branchResultsMapper(), result); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResult); + return Dataframes.createCDataframe(Dataframes.branchResultsMapper(), result); + } }); } @CEntryPoint(name = "getBusResults") public static PyPowsyblApiHeader.ArrayPointer getBusResults(IsolateThread thread, ObjectHandle securityAnalysisResult, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResult); - return Dataframes.createCDataframe(Dataframes.busResultsMapper(), result); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResult); + return Dataframes.createCDataframe(Dataframes.busResultsMapper(), result); + } }); } @CEntryPoint(name = "getThreeWindingsTransformerResults") public static PyPowsyblApiHeader.ArrayPointer getThreeWindingsTransformerResults(IsolateThread thread, ObjectHandle securityAnalysisResult, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResult); - return Dataframes.createCDataframe(Dataframes.threeWindingsTransformerResultsMapper(), result); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResult); + return Dataframes.createCDataframe(Dataframes.threeWindingsTransformerResultsMapper(), result); + } }); } @CEntryPoint(name = "createSecurityAnalysis") public static ObjectHandle createSecurityAnalysis(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new SecurityAnalysisContext())); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new SecurityAnalysisContext()); + } + }); } @CEntryPoint(name = "addContingency") public static void addContingency(IsolateThread thread, ObjectHandle contingencyContainerHandle, CCharPointer contingencyIdPtr, CCharPointerPointer elementIdPtrPtr, int elementCount, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - ContingencyContainer contingencyContainer = ObjectHandles.getGlobal().get(contingencyContainerHandle); - String contingencyId = CTypeUtil.toString(contingencyIdPtr); - List elementIds = toStringList(elementIdPtrPtr, elementCount); - contingencyContainer.addContingency(contingencyId, elementIds); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + ContingencyContainer contingencyContainer = ObjectHandles.getGlobal().get(contingencyContainerHandle); + String contingencyId = CTypeUtil.toString(contingencyIdPtr); + List elementIds = toStringList(elementIdPtrPtr, elementCount); + contingencyContainer.addContingency(contingencyId, elementIds); + } }); } @@ -201,73 +238,93 @@ public static ObjectHandle runSecurityAnalysis(IsolateThread thread, ObjectHandl ObjectHandle networkHandle, SecurityAnalysisParametersPointer securityAnalysisParametersPointer, CCharPointer providerName, boolean dc, ObjectHandle reporterHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(securityAnalysisContextHandle); - Network network = ObjectHandles.getGlobal().get(networkHandle); - SecurityAnalysisProvider provider = getProvider(CTypeUtil.toString(providerName)); - logger().info("Security analysis provider used for security analysis is : {}", provider.getName()); - SecurityAnalysisParameters securityAnalysisParameters = SecurityAnalysisCUtils.createSecurityAnalysisParameters(dc, securityAnalysisParametersPointer, provider); - ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); - SecurityAnalysisResult result = analysisContext.run(network, securityAnalysisParameters, provider.getName(), reporter); - return ObjectHandles.getGlobal().create(result); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public ObjectHandle get() { + SecurityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(securityAnalysisContextHandle); + Network network = ObjectHandles.getGlobal().get(networkHandle); + SecurityAnalysisProvider provider = getProvider(CTypeUtil.toString(providerName)); + logger().info("Security analysis provider used for security analysis is : {}", provider.getName()); + SecurityAnalysisParameters securityAnalysisParameters = SecurityAnalysisCUtils.createSecurityAnalysisParameters(dc, securityAnalysisParametersPointer, provider); + ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); + SecurityAnalysisResult result = analysisContext.run(network, securityAnalysisParameters, provider.getName(), reporter); + return ObjectHandles.getGlobal().create(result); + } }); } @CEntryPoint(name = "getPostContingencyResults") public static PyPowsyblApiHeader.ArrayPointer getPostContingencyResults(IsolateThread thread, ObjectHandle securityAnalysisResultHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResultHandle); - return createPostContingencyResultArrayPointer(result); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResultHandle); + return createPostContingencyResultArrayPointer(result); + } }); } @CEntryPoint(name = "getPreContingencyResult") public static PyPowsyblApiHeader.PreContingencyResultPointer getPreContingencyResult(IsolateThread thread, ObjectHandle securityAnalysisResultHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResultHandle); - return createPreContingencyResultArrayPointer(result); + return doCatch(exceptionHandlerPtr, new PointerProvider() { + @Override + public PyPowsyblApiHeader.PreContingencyResultPointer get() { + SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResultHandle); + return createPreContingencyResultArrayPointer(result); + } }); } @CEntryPoint(name = "getLimitViolations") public static PyPowsyblApiHeader.ArrayPointer getLimitViolations(IsolateThread thread, ObjectHandle securityAnalysisResultHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResultHandle); - return Dataframes.createCDataframe(Dataframes.limitViolationsMapper(), result); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + SecurityAnalysisResult result = ObjectHandles.getGlobal().get(securityAnalysisResultHandle); + return Dataframes.createCDataframe(Dataframes.limitViolationsMapper(), result); + } }); } @CEntryPoint(name = "freeContingencyResultArrayPointer") public static void freeContingencyResultArrayPointer(IsolateThread thread, PyPowsyblApiHeader.ArrayPointer contingencyResultArrayPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - for (int i = 0; i < contingencyResultArrayPtr.getLength(); i++) { - PyPowsyblApiHeader.PostContingencyResultPointer contingencyResultPtrPlus = contingencyResultArrayPtr.getPtr().addressOf(i); - UnmanagedMemory.free(contingencyResultPtrPlus.getContingencyId()); - for (int l = 0; l < contingencyResultPtrPlus.limitViolations().getLength(); l++) { - PyPowsyblApiHeader.LimitViolationPointer violation = contingencyResultPtrPlus.limitViolations().getPtr().addressOf(l); - UnmanagedMemory.free(violation.getSubjectId()); - UnmanagedMemory.free(violation.getSubjectName()); - UnmanagedMemory.free(violation.getLimitName()); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + for (int i = 0; i < contingencyResultArrayPtr.getLength(); i++) { + PyPowsyblApiHeader.PostContingencyResultPointer contingencyResultPtrPlus = contingencyResultArrayPtr.getPtr().addressOf(i); + UnmanagedMemory.free(contingencyResultPtrPlus.getContingencyId()); + for (int l = 0; l < contingencyResultPtrPlus.limitViolations().getLength(); l++) { + PyPowsyblApiHeader.LimitViolationPointer violation = contingencyResultPtrPlus.limitViolations().getPtr().addressOf(l); + UnmanagedMemory.free(violation.getSubjectId()); + UnmanagedMemory.free(violation.getSubjectName()); + UnmanagedMemory.free(violation.getLimitName()); + } + UnmanagedMemory.free(contingencyResultPtrPlus.limitViolations().getPtr()); } - UnmanagedMemory.free(contingencyResultPtrPlus.limitViolations().getPtr()); + freeArrayPointer(contingencyResultArrayPtr); } - freeArrayPointer(contingencyResultArrayPtr); }); } @CEntryPoint(name = "freeSecurityAnalysisParameters") public static void freeSecurityAnalysisParameters(IsolateThread thread, SecurityAnalysisParametersPointer parameters, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - LoadFlowCUtils.freeLoadFlowParametersContent(parameters.getLoadFlowParameters()); - UnmanagedMemory.free(parameters); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + LoadFlowCUtils.freeLoadFlowParametersContent(parameters.getLoadFlowParameters()); + UnmanagedMemory.free(parameters); + } }); } @CEntryPoint(name = "createSecurityAnalysisParameters") public static SecurityAnalysisParametersPointer createSecurityAnalysisParameters(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> convertToSecurityAnalysisParametersPointer(SecurityAnalysisCUtils.createSecurityAnalysisParameters())); + return doCatch(exceptionHandlerPtr, () -> { + return convertToSecurityAnalysisParametersPointer(SecurityAnalysisCUtils.createSecurityAnalysisParameters()); + }); } private static SecurityAnalysisParametersPointer convertToSecurityAnalysisParametersPointer(SecurityAnalysisParameters parameters) { @@ -285,9 +342,12 @@ private static SecurityAnalysisParametersPointer convertToSecurityAnalysisParame @CEntryPoint(name = "getSecurityAnalysisProviderParametersNames") public static PyPowsyblApiHeader.ArrayPointer getProviderParametersNames(IsolateThread thread, CCharPointer provider, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String providerStr = CTypeUtil.toString(provider); - return Util.createCharPtrArray(SecurityAnalysisCUtils.getSecurityAnalysisProvider(providerStr).getSpecificParametersNames()); + return doCatch(exceptionHandlerPtr, new PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + String providerStr = CTypeUtil.toString(provider); + return Util.createCharPtrArray(SecurityAnalysisCUtils.getSecurityAnalysisProvider(providerStr).getSpecificParametersNames()); + } }); } } diff --git a/java/src/main/java/com/powsybl/python/sensitivity/SensitivityAnalysisCFunctions.java b/java/src/main/java/com/powsybl/python/sensitivity/SensitivityAnalysisCFunctions.java index dcc1d436c8..ae2e4c293e 100644 --- a/java/src/main/java/com/powsybl/python/sensitivity/SensitivityAnalysisCFunctions.java +++ b/java/src/main/java/com/powsybl/python/sensitivity/SensitivityAnalysisCFunctions.java @@ -56,46 +56,67 @@ private static Logger logger() { @CEntryPoint(name = "getSensitivityAnalysisProviderNames") public static PyPowsyblApiHeader.ArrayPointer getSensitivityAnalysisProviderNames(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(SensitivityAnalysisProvider.findAll() - .stream().map(SensitivityAnalysisProvider::getName).collect(Collectors.toList()))); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + return createCharPtrArray(SensitivityAnalysisProvider.findAll() + .stream().map(SensitivityAnalysisProvider::getName).collect(Collectors.toList())); + } + }); } @CEntryPoint(name = "setDefaultSensitivityAnalysisProvider") public static void setDefaultSensitivityAnalysisProvider(IsolateThread thread, CCharPointer provider, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - PyPowsyblConfiguration.setDefaultSensitivityAnalysisProvider(CTypeUtil.toString(provider)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + PyPowsyblConfiguration.setDefaultSensitivityAnalysisProvider(CTypeUtil.toString(provider)); + } }); } @CEntryPoint(name = "getDefaultSensitivityAnalysisProvider") public static CCharPointer getDefaultSensitivityAnalysisProvider(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultSensitivityAnalysisProvider())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public CCharPointer get() { + return CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultSensitivityAnalysisProvider()); + } + }); } @CEntryPoint(name = "createSensitivityAnalysis") public static ObjectHandle createSensitivityAnalysis(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new SensitivityAnalysisContext())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new SensitivityAnalysisContext()); + } + }); } @CEntryPoint(name = "setZones") public static void setZones(IsolateThread thread, ObjectHandle sensitivityAnalysisContextHandle, PyPowsyblApiHeader.ZonePointerPointer zonePtrPtr, int zoneCount, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); - List variableSets = new ArrayList<>(zoneCount); - for (int zoneIndex = 0; zoneIndex < zoneCount; zoneIndex++) { - PyPowsyblApiHeader.ZonePointer zonePtrI = zonePtrPtr.read(zoneIndex); - String zoneId = CTypeUtil.toString(zonePtrI.getId()); - List injectionsIds = toStringList(zonePtrI.getInjectionsIds(), zonePtrI.getLength()); - List injectionsShiftKeys = CTypeUtil.toDoubleList(zonePtrI.getinjectionsShiftKeys(), zonePtrI.getLength()); - List variables = new ArrayList<>(injectionsIds.size()); - for (int injectionIndex = 0; injectionIndex < injectionsIds.size(); injectionIndex++) { - variables.add(new WeightedSensitivityVariable(injectionsIds.get(injectionIndex), injectionsShiftKeys.get(injectionIndex))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); + List variableSets = new ArrayList<>(zoneCount); + for (int zoneIndex = 0; zoneIndex < zoneCount; zoneIndex++) { + PyPowsyblApiHeader.ZonePointer zonePtrI = zonePtrPtr.read(zoneIndex); + String zoneId = CTypeUtil.toString(zonePtrI.getId()); + List injectionsIds = toStringList(zonePtrI.getInjectionsIds(), zonePtrI.getLength()); + List injectionsShiftKeys = CTypeUtil.toDoubleList(zonePtrI.getinjectionsShiftKeys(), zonePtrI.getLength()); + List variables = new ArrayList<>(injectionsIds.size()); + for (int injectionIndex = 0; injectionIndex < injectionsIds.size(); injectionIndex++) { + variables.add(new WeightedSensitivityVariable(injectionsIds.get(injectionIndex), injectionsShiftKeys.get(injectionIndex))); + } + variableSets.add(new SensitivityVariableSet(zoneId, variables)); } - variableSets.add(new SensitivityVariableSet(zoneId, variables)); + analysisContext.setVariableSets(variableSets); } - analysisContext.setVariableSets(variableSets); }); } @@ -105,12 +126,15 @@ public static void addBranchFlowFactorMatrix(IsolateThread thread, ObjectHandle CCharPointerPointer variableIdPtrPtr, int variableIdCount, CCharPointer matrixIdPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); - List branchesIds = toStringList(branchIdPtrPtr, branchIdCount); - List variablesIds = toStringList(variableIdPtrPtr, variableIdCount); - String matrixId = CTypeUtil.toString(matrixIdPtr); - analysisContext.addBranchFlowFactorMatrix(matrixId, branchesIds, variablesIds); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); + List branchesIds = toStringList(branchIdPtrPtr, branchIdCount); + List variablesIds = toStringList(variableIdPtrPtr, variableIdCount); + String matrixId = CTypeUtil.toString(matrixIdPtr); + analysisContext.addBranchFlowFactorMatrix(matrixId, branchesIds, variablesIds); + } }); } @@ -120,12 +144,15 @@ public static void addPreContingencyBranchFlowFactorMatrix(IsolateThread thread, CCharPointerPointer variableIdPtrPtr, int variableIdCount, CCharPointer matrixIdPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); - List branchesIds = toStringList(branchIdPtrPtr, branchIdCount); - List variablesIds = toStringList(variableIdPtrPtr, variableIdCount); - String matrixId = CTypeUtil.toString(matrixIdPtr); - analysisContext.addPreContingencyBranchFlowFactorMatrix(matrixId, branchesIds, variablesIds); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); + List branchesIds = toStringList(branchIdPtrPtr, branchIdCount); + List variablesIds = toStringList(variableIdPtrPtr, variableIdCount); + String matrixId = CTypeUtil.toString(matrixIdPtr); + analysisContext.addPreContingencyBranchFlowFactorMatrix(matrixId, branchesIds, variablesIds); + } }); } @@ -136,13 +163,16 @@ public static void addPostContingencyBranchFlowFactorMatrix(IsolateThread thread CCharPointerPointer contingenciesIdPtrPtr, int contingenciesIdCount, CCharPointer matrixIdPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); - List branchesIds = toStringList(branchIdPtrPtr, branchIdCount); - List variablesIds = toStringList(variableIdPtrPtr, variableIdCount); - List contingencies = toStringList(contingenciesIdPtrPtr, contingenciesIdCount); - String matrixId = CTypeUtil.toString(matrixIdPtr); - analysisContext.addPostContingencyBranchFlowFactorMatrix(matrixId, branchesIds, variablesIds, contingencies); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); + List branchesIds = toStringList(branchIdPtrPtr, branchIdCount); + List variablesIds = toStringList(variableIdPtrPtr, variableIdCount); + List contingencies = toStringList(contingenciesIdPtrPtr, contingenciesIdCount); + String matrixId = CTypeUtil.toString(matrixIdPtr); + analysisContext.addPostContingencyBranchFlowFactorMatrix(matrixId, branchesIds, variablesIds, contingencies); + } }); } @@ -151,11 +181,14 @@ public static void setBusVoltageFactorMatrix(IsolateThread thread, ObjectHandle CCharPointerPointer busVoltageIdPtrPtr, int branchIdCount, CCharPointerPointer targetVoltageIdPtrPtr, int injectionOrTransfoIdCount, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); - List busVoltageIds = toStringList(busVoltageIdPtrPtr, branchIdCount); - List targetVoltageIds = toStringList(targetVoltageIdPtrPtr, injectionOrTransfoIdCount); - analysisContext.setBusVoltageFactorMatrix(busVoltageIds, targetVoltageIds); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); + List busVoltageIds = toStringList(busVoltageIdPtrPtr, branchIdCount); + List targetVoltageIds = toStringList(targetVoltageIdPtrPtr, injectionOrTransfoIdCount); + analysisContext.setBusVoltageFactorMatrix(busVoltageIds, targetVoltageIds); + } }); } @@ -164,15 +197,18 @@ public static ObjectHandle runSensitivityAnalysis(IsolateThread thread, ObjectHa ObjectHandle networkHandle, boolean dc, SensitivityAnalysisParametersPointer sensitivityAnalysisParametersPtr, CCharPointer providerName, ObjectHandle reporterHandle, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); - Network network = ObjectHandles.getGlobal().get(networkHandle); - SensitivityAnalysisProvider provider = getProvider(CTypeUtil.toString(providerName)); - logger().info("Sensitivity analysis provider used for sensitivity analysis is : {}", provider.getName()); - SensitivityAnalysisParameters sensitivityAnalysisParameters = SensitivityAnalysisCUtils.createSensitivityAnalysisParameters(dc, sensitivityAnalysisParametersPtr, provider); - Reporter reporter = ReportCUtils.getReporter(reporterHandle); - SensitivityAnalysisResultContext resultContext = analysisContext.run(network, sensitivityAnalysisParameters, provider.getName(), reporter); - return ObjectHandles.getGlobal().create(resultContext); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + SensitivityAnalysisContext analysisContext = ObjectHandles.getGlobal().get(sensitivityAnalysisContextHandle); + Network network = ObjectHandles.getGlobal().get(networkHandle); + SensitivityAnalysisProvider provider = getProvider(CTypeUtil.toString(providerName)); + logger().info("Sensitivity analysis provider used for sensitivity analysis is : {}", provider.getName()); + SensitivityAnalysisParameters sensitivityAnalysisParameters = SensitivityAnalysisCUtils.createSensitivityAnalysisParameters(dc, sensitivityAnalysisParametersPtr, provider); + Reporter reporter = ReportCUtils.getReporter(reporterHandle); + SensitivityAnalysisResultContext resultContext = analysisContext.run(network, sensitivityAnalysisParameters, provider.getName(), reporter); + return ObjectHandles.getGlobal().create(resultContext); + } }); } @@ -180,21 +216,27 @@ public static ObjectHandle runSensitivityAnalysis(IsolateThread thread, ObjectHa public static PyPowsyblApiHeader.MatrixPointer getBranchFlowsSensitivityMatrix(IsolateThread thread, ObjectHandle sensitivityAnalysisResultContextHandle, CCharPointer matrixIdPtr, CCharPointer contingencyIdPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); - String contingencyId = CTypeUtil.toString(contingencyIdPtr); - String matrixId = CTypeUtil.toString(matrixIdPtr); - return resultContext.createBranchFlowsSensitivityMatrix(matrixId, contingencyId); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public PyPowsyblApiHeader.MatrixPointer get() { + SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); + String contingencyId = CTypeUtil.toString(contingencyIdPtr); + String matrixId = CTypeUtil.toString(matrixIdPtr); + return resultContext.createBranchFlowsSensitivityMatrix(matrixId, contingencyId); + } }); } @CEntryPoint(name = "getBusVoltagesSensitivityMatrix") public static PyPowsyblApiHeader.MatrixPointer getBusVoltagesSensitivityMatrix(IsolateThread thread, ObjectHandle sensitivityAnalysisResultContextHandle, CCharPointer contingencyIdPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); - String contingencyId = CTypeUtil.toString(contingencyIdPtr); - return resultContext.createBusVoltagesSensitivityMatrix(contingencyId); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public PyPowsyblApiHeader.MatrixPointer get() { + SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); + String contingencyId = CTypeUtil.toString(contingencyIdPtr); + return resultContext.createBusVoltagesSensitivityMatrix(contingencyId); + } }); } @@ -202,21 +244,27 @@ public static PyPowsyblApiHeader.MatrixPointer getBusVoltagesSensitivityMatrix(I public static PyPowsyblApiHeader.MatrixPointer getReferenceFlows(IsolateThread thread, ObjectHandle sensitivityAnalysisResultContextHandle, CCharPointer matrixIdPtr, CCharPointer contingencyIdPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); - String contingencyId = CTypeUtil.toString(contingencyIdPtr); - String matrixId = CTypeUtil.toString(matrixIdPtr); - return resultContext.createReferenceFlowsActivePower(matrixId, contingencyId); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public PyPowsyblApiHeader.MatrixPointer get() { + SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); + String contingencyId = CTypeUtil.toString(contingencyIdPtr); + String matrixId = CTypeUtil.toString(matrixIdPtr); + return resultContext.createReferenceFlowsActivePower(matrixId, contingencyId); + } }); } @CEntryPoint(name = "getReferenceVoltages") public static PyPowsyblApiHeader.MatrixPointer getReferenceVoltages(IsolateThread thread, ObjectHandle sensitivityAnalysisResultContextHandle, CCharPointer contingencyIdPtr, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); - String contingencyId = CTypeUtil.toString(contingencyIdPtr); - return resultContext.createReferenceVoltages(contingencyId); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public PyPowsyblApiHeader.MatrixPointer get() { + SensitivityAnalysisResultContext resultContext = ObjectHandles.getGlobal().get(sensitivityAnalysisResultContextHandle); + String contingencyId = CTypeUtil.toString(contingencyIdPtr); + return resultContext.createReferenceVoltages(contingencyId); + } }); } @@ -231,15 +279,23 @@ private static SensitivityAnalysisProvider getProvider(String name) { @CEntryPoint(name = "freeSensitivityAnalysisParameters") public static void freeSensitivityAnalysisParameters(IsolateThread thread, SensitivityAnalysisParametersPointer parameters, ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - LoadFlowCUtils.freeLoadFlowParametersContent(parameters.getLoadFlowParameters()); - UnmanagedMemory.free(parameters); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + LoadFlowCUtils.freeLoadFlowParametersContent(parameters.getLoadFlowParameters()); + UnmanagedMemory.free(parameters); + } }); } @CEntryPoint(name = "createSensitivityAnalysisParameters") public static SensitivityAnalysisParametersPointer createSensitivityAnalysisParameters(IsolateThread thread, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> convertToSensitivityAnalysisParametersPointer(SensitivityAnalysisCUtils.createSensitivityAnalysisParameters())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public SensitivityAnalysisParametersPointer get() { + return convertToSensitivityAnalysisParametersPointer(SensitivityAnalysisCUtils.createSensitivityAnalysisParameters()); + } + }); } private static SensitivityAnalysisParametersPointer convertToSensitivityAnalysisParametersPointer(SensitivityAnalysisParameters parameters) { @@ -252,9 +308,12 @@ private static SensitivityAnalysisParametersPointer convertToSensitivityAnalysis @CEntryPoint(name = "getSensitivityAnalysisProviderParametersNames") public static PyPowsyblApiHeader.ArrayPointer getProviderParametersNames(IsolateThread thread, CCharPointer provider, ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String providerStr = CTypeUtil.toString(provider); - return Util.createCharPtrArray(SensitivityAnalysisCUtils.getSensitivityAnalysisProvider(providerStr).getSpecificParametersNames()); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + String providerStr = CTypeUtil.toString(provider); + return Util.createCharPtrArray(SensitivityAnalysisCUtils.getSensitivityAnalysisProvider(providerStr).getSpecificParametersNames()); + } }); } } diff --git a/java/src/main/java/com/powsybl/python/shortcircuit/ShortCircuitAnalysisCFunctions.java b/java/src/main/java/com/powsybl/python/shortcircuit/ShortCircuitAnalysisCFunctions.java index 140f57f507..37f90faca6 100644 --- a/java/src/main/java/com/powsybl/python/shortcircuit/ShortCircuitAnalysisCFunctions.java +++ b/java/src/main/java/com/powsybl/python/shortcircuit/ShortCircuitAnalysisCFunctions.java @@ -55,25 +55,43 @@ private static Logger logger() { @CEntryPoint(name = "getShortCircuitAnalysisProviderNames") public static PyPowsyblApiHeader.ArrayPointer getShortCircuitAnalysisProviderNames(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> createCharPtrArray(ShortCircuitAnalysisProvider.findAll() - .stream().map(ShortCircuitAnalysisProvider::getName).collect(Collectors.toList()))); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + return createCharPtrArray(ShortCircuitAnalysisProvider.findAll() + .stream().map(ShortCircuitAnalysisProvider::getName).collect(Collectors.toList())); + } + }); } @CEntryPoint(name = "setDefaultShortCircuitAnalysisProvider") public static void setDefaultShortCircuitAnalysisProvider(IsolateThread thread, CCharPointer provider, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - PyPowsyblConfiguration.setDefaultShortCircuitAnalysisProvider(CTypeUtil.toString(provider)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + PyPowsyblConfiguration.setDefaultShortCircuitAnalysisProvider(CTypeUtil.toString(provider)); + } }); } @CEntryPoint(name = "getDefaultShortCircuitAnalysisProvider") public static CCharPointer getDefaultShortCircuitAnalysisProvider(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultShortCircuitAnalysisProvider())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public CCharPointer get() { + return CTypeUtil.toCharPtr(PyPowsyblConfiguration.getDefaultShortCircuitAnalysisProvider()); + } + }); } @CEntryPoint(name = "createShortCircuitAnalysis") public static ObjectHandle createShortCircuitAnalysis(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new ShortCircuitAnalysisContext())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new ShortCircuitAnalysisContext()); + } + }); } private static ShortCircuitAnalysisProvider getProvider(String name) { @@ -89,32 +107,43 @@ public static ObjectHandle runShortCircuitAnalysis(IsolateThread thread, ObjectH ObjectHandle networkHandle, ShortCircuitAnalysisParametersPointer shortCircuitAnalysisParametersPointer, CCharPointer providerName, ObjectHandle reporterHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - ShortCircuitAnalysisContext analysisContext = ObjectHandles.getGlobal().get(shortCircuitAnalysisContextHandle); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + ShortCircuitAnalysisContext analysisContext = ObjectHandles.getGlobal().get(shortCircuitAnalysisContextHandle); - Network network = ObjectHandles.getGlobal().get(networkHandle); + Network network = ObjectHandles.getGlobal().get(networkHandle); - ShortCircuitAnalysisProvider provider = getProvider(CTypeUtil.toString(providerName)); - logger().info("Short-circuit analysis provider used for short-circuit analysis is : {}", provider.getName()); - ShortCircuitParameters shortCircuitAnalysisParameters = ShortCircuitAnalysisCUtils.createShortCircuitAnalysisParameters(shortCircuitAnalysisParametersPointer, provider); + ShortCircuitAnalysisProvider provider = getProvider(CTypeUtil.toString(providerName)); + logger().info("Short-circuit analysis provider used for short-circuit analysis is : {}", provider.getName()); + ShortCircuitParameters shortCircuitAnalysisParameters = ShortCircuitAnalysisCUtils.createShortCircuitAnalysisParameters(shortCircuitAnalysisParametersPointer, provider); - ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); - ShortCircuitAnalysisResult results = analysisContext.run(network, shortCircuitAnalysisParameters, provider.getName(), reporter); - return ObjectHandles.getGlobal().create(results); + ReporterModel reporter = ObjectHandles.getGlobal().get(reporterHandle); + ShortCircuitAnalysisResult results = analysisContext.run(network, shortCircuitAnalysisParameters, provider.getName(), reporter); + return ObjectHandles.getGlobal().create(results); + } }); } @CEntryPoint(name = "freeShortCircuitAnalysisParameters") public static void freeShortCircuitAnalysisParameters(IsolateThread thread, ShortCircuitAnalysisParametersPointer parameters, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - UnmanagedMemory.free(parameters); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + UnmanagedMemory.free(parameters); + } }); } @CEntryPoint(name = "createShortCircuitAnalysisParameters") public static ShortCircuitAnalysisParametersPointer createShortCircuitAnalysisParameters(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> convertToShortCircuitAnalysisParametersPointer(ShortCircuitAnalysisCUtils.createShortCircuitAnalysisParameters())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ShortCircuitAnalysisParametersPointer get() { + return convertToShortCircuitAnalysisParametersPointer(ShortCircuitAnalysisCUtils.createShortCircuitAnalysisParameters()); + } + }); } private static ShortCircuitAnalysisParametersPointer convertToShortCircuitAnalysisParametersPointer(ShortCircuitParameters parameters) { @@ -138,9 +167,12 @@ static List getSpecificParametersNames(ShortCircuitAnalysisProvider prov @CEntryPoint(name = "getShortCircuitAnalysisProviderParametersNames") public static PyPowsyblApiHeader.ArrayPointer getProviderParametersNames(IsolateThread thread, CCharPointer provider, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - String providerStr = CTypeUtil.toString(provider); - return Util.createCharPtrArray(getSpecificParametersNames(ShortCircuitAnalysisCUtils.getShortCircuitAnalysisProvider(providerStr))); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + String providerStr = CTypeUtil.toString(provider); + return Util.createCharPtrArray(getSpecificParametersNames(ShortCircuitAnalysisCUtils.getShortCircuitAnalysisProvider(providerStr))); + } }); } @@ -148,8 +180,11 @@ public static PyPowsyblApiHeader.ArrayPointer getProviderPa public static DataframeMetadataPointer getFaultsDataframeMetaData(IsolateThread thread, ShortCircuitFaultType mappingType, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - return CTypeUtil.createSeriesMetadata(ShortCircuitFaultAdderFactory.getAdder(mappingType).getMetadata()); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public DataframeMetadataPointer get() { + return CTypeUtil.createSeriesMetadata(ShortCircuitFaultAdderFactory.getAdder(mappingType).getMetadata()); + } }); } @@ -158,42 +193,57 @@ public static void setFaults(IsolateThread thread, ObjectHandle contextHandle, ShortCircuitFaultType faultType, PyPowsyblApiHeader.DataframePointer cDataframe, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - doCatch(exceptionHandlerPtr, () -> { - ShortCircuitAnalysisContext context = ObjectHandles.getGlobal().get(contextHandle); - UpdatingDataframe faultDataframe = NetworkCFunctions.createDataframe(cDataframe); - ShortCircuitFaultAdderFactory.getAdder(faultType).addElements(context, faultDataframe); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + ShortCircuitAnalysisContext context = ObjectHandles.getGlobal().get(contextHandle); + UpdatingDataframe faultDataframe = NetworkCFunctions.createDataframe(cDataframe); + ShortCircuitFaultAdderFactory.getAdder(faultType).addElements(context, faultDataframe); + } }); } @CEntryPoint(name = "getFaultResults") public static PyPowsyblApiHeader.ArrayPointer getFaultResults(IsolateThread thread, ObjectHandle shortCircuitAnalysisResult, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); - return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisFaultResultsMapper(), result); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); + return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisFaultResultsMapper(), result); + } }); } @CEntryPoint(name = "getMagnitudeFeederResults") public static PyPowsyblApiHeader.ArrayPointer getMagnitudeFeederResults(IsolateThread thread, ObjectHandle shortCircuitAnalysisResult, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); - return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisMagnitudeFeederResultsMapper(), result); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); + return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisMagnitudeFeederResultsMapper(), result); + } }); } @CEntryPoint(name = "getLimitViolationsResults") public static PyPowsyblApiHeader.ArrayPointer getLimitViolationsResults(IsolateThread thread, ObjectHandle shortCircuitAnalysisResult, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); - return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisLimitViolationsResultsMapper(), result); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); + return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisLimitViolationsResultsMapper(), result); + } }); } @CEntryPoint(name = "getMagnitudeBusResults") public static PyPowsyblApiHeader.ArrayPointer getMagnitudeBusResults(IsolateThread thread, ObjectHandle shortCircuitAnalysisResult, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> { - ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); - return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisMagnitudeBusResultsMapper(), result); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider>() { + @Override + public PyPowsyblApiHeader.ArrayPointer get() { + ShortCircuitAnalysisResult result = ObjectHandles.getGlobal().get(shortCircuitAnalysisResult); + return Dataframes.createCDataframe(Dataframes.shortCircuitAnalysisMagnitudeBusResultsMapper(), result); + } }); } } diff --git a/java/src/main/java/com/powsybl/python/voltageinit/VoltageInitializerCFunctions.java b/java/src/main/java/com/powsybl/python/voltageinit/VoltageInitializerCFunctions.java index b55d2f806c..6b076dc384 100644 --- a/java/src/main/java/com/powsybl/python/voltageinit/VoltageInitializerCFunctions.java +++ b/java/src/main/java/com/powsybl/python/voltageinit/VoltageInitializerCFunctions.java @@ -51,14 +51,24 @@ private static Logger logger() { @CEntryPoint(name = "createVoltageInitializerParams") public static ObjectHandle createVoltageInitializerParams(IsolateThread thread, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - return doCatch(exceptionHandlerPtr, () -> ObjectHandles.getGlobal().create(new OpenReacParameters())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new OpenReacParameters()); + } + }); } @CEntryPoint(name = "createVoltageLimitOverride") public static ObjectHandle createVoltageLimitOverride(IsolateThread thread, double minVoltage, double maxVoltage, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { return doCatch(exceptionHandlerPtr, - () -> ObjectHandles.getGlobal().create(new VoltageLimitOverride(minVoltage, maxVoltage))); + new Util.PointerProvider() { + @Override + public ObjectHandle get() { + return ObjectHandles.getGlobal().create(new VoltageLimitOverride(minVoltage, maxVoltage)); + } + }); } @CEntryPoint(name = "voltageInitializerAddSpecificVoltageLimits") @@ -67,8 +77,13 @@ public static void addSpecificVoltageLimits(IsolateThread thread, CCharPointer i PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle); String voltageId = CTypeUtil.toString(idPtr); - doCatch(exceptionHandlerPtr, () -> params - .addSpecificVoltageLimits(Map.of(voltageId, new VoltageLimitOverride(minVoltage, maxVoltage)))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + params + .addSpecificVoltageLimits(Map.of(voltageId, new VoltageLimitOverride(minVoltage, maxVoltage))); + } + }); } @CEntryPoint(name = "voltageInitializerAddVariableShuntCompensators") @@ -76,7 +91,12 @@ public static void addVariableShuntCompensators(IsolateThread thread, ObjectHand CCharPointer idPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle); String id = CTypeUtil.toString(idPtr); - doCatch(exceptionHandlerPtr, () -> params.addVariableShuntCompensators(List.of(id))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + params.addVariableShuntCompensators(List.of(id)); + } + }); } @CEntryPoint(name = "voltageInitializerAddConstantQGenerators") @@ -84,7 +104,12 @@ public static void addConstantQGenerators(IsolateThread thread, ObjectHandle par CCharPointer idPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle); String id = CTypeUtil.toString(idPtr); - doCatch(exceptionHandlerPtr, () -> params.addConstantQGenerators(List.of(id))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + params.addConstantQGenerators(List.of(id)); + } + }); } @CEntryPoint(name = "voltageInitializerAddVariableTwoWindingsTransformers") @@ -92,7 +117,12 @@ public static void addVariableTwoWindingsTransformers(IsolateThread thread, Obje CCharPointer idPtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle); String id = CTypeUtil.toString(idPtr); - doCatch(exceptionHandlerPtr, () -> params.addVariableTwoWindingsTransformers(List.of(id))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + params.addVariableTwoWindingsTransformers(List.of(id)); + } + }); } @CEntryPoint(name = "voltageInitializerAddAlgorithmParam") @@ -100,21 +130,36 @@ public static void addAlgorithmParam(IsolateThread thread, ObjectHandle paramsHa CCharPointer valuePtr, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { OpenReacParameters params = ObjectHandles.getGlobal().get(paramsHandle); doCatch(exceptionHandlerPtr, - () -> params.addAlgorithmParam(CTypeUtil.toString(keyPtr), CTypeUtil.toString(valuePtr))); + new Runnable() { + @Override + public void run() { + params.addAlgorithmParam(CTypeUtil.toString(keyPtr), CTypeUtil.toString(valuePtr)); + } + }); } @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))); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + params.setObjective(Util.convert(cObjective)); + } + }); } @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)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + params.setObjectiveDistance(dist); + } + }); } @CEntryPoint(name = "voltageInitializerApplyAllModifications") @@ -122,7 +167,12 @@ public static void applyAllModifications(IsolateThread thread, ObjectHandle resu ObjectHandle networkHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { OpenReacResult result = ObjectHandles.getGlobal().get(resultHandle); Network network = ObjectHandles.getGlobal().get(networkHandle); - doCatch(exceptionHandlerPtr, () -> result.applyAllModifications(network)); + doCatch(exceptionHandlerPtr, new Runnable() { + @Override + public void run() { + result.applyAllModifications(network); + } + }); } @CEntryPoint(name = "voltageInitializerGetStatus") @@ -136,22 +186,30 @@ public static VoltageInitializerStatus getStatus(IsolateThread thread, ObjectHan public static StringMap getIndicators(IsolateThread thread, ObjectHandle resultHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { OpenReacResult result = ObjectHandles.getGlobal().get(resultHandle); - return doCatch(exceptionHandlerPtr, () -> CTypeUtil.fromStringMap(result.getIndicators())); + return doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public StringMap get() { + return CTypeUtil.fromStringMap(result.getIndicators()); + } + }); } @CEntryPoint(name = "runVoltageInitializer") public static ObjectHandle runVoltageInitializer(IsolateThread thread, boolean debug, ObjectHandle networkHandle, ObjectHandle paramsHandle, PyPowsyblApiHeader.ExceptionHandlerPointer exceptionHandlerPtr) { - 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"); - - return ObjectHandles.getGlobal().create(result); + return Util.doCatch(exceptionHandlerPtr, new Util.PointerProvider() { + @Override + public ObjectHandle get() { + 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"); + + return ObjectHandles.getGlobal().create(result); + } }); }