diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/SensitivityAnalysisController.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/SensitivityAnalysisController.java index e8c745a6..98d6fa8e 100644 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/SensitivityAnalysisController.java +++ b/src/main/java/org/gridsuite/sensitivityanalysis/server/SensitivityAnalysisController.java @@ -23,16 +23,12 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import org.gridsuite.sensitivityanalysis.server.dto.*; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyInputData; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyStatus; import org.gridsuite.sensitivityanalysis.server.dto.resultselector.ResultTab; import org.gridsuite.sensitivityanalysis.server.dto.resultselector.ResultsSelector; import org.gridsuite.sensitivityanalysis.server.service.SensitivityAnalysisParametersService; import org.gridsuite.sensitivityanalysis.server.service.SensitivityAnalysisRunContext; import org.gridsuite.sensitivityanalysis.server.service.SensitivityAnalysisService; import org.gridsuite.sensitivityanalysis.server.service.SensitivityAnalysisWorkerService; -import org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy.NonEvacuatedEnergyRunContext; -import org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy.NonEvacuatedEnergyService; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -59,17 +55,13 @@ public class SensitivityAnalysisController { private final SensitivityAnalysisWorkerService workerService; private final SensitivityAnalysisParametersService sensitivityAnalysisParametersService; - private final NonEvacuatedEnergyService nonEvacuatedEnergyService; - private final ObjectMapper objectMapper; public SensitivityAnalysisController(SensitivityAnalysisService service, SensitivityAnalysisWorkerService workerService, - NonEvacuatedEnergyService nonEvacuatedEnergyService, SensitivityAnalysisParametersService sensitivityAnalysisParametersService, ObjectMapper objectMapper) { this.service = service; this.workerService = workerService; - this.nonEvacuatedEnergyService = nonEvacuatedEnergyService; this.sensitivityAnalysisParametersService = sensitivityAnalysisParametersService; this.objectMapper = objectMapper; } @@ -264,85 +256,4 @@ public ResponseEntity exportSensitivityResultsAsCsv(@Parameter(descripti return ResponseEntity.badRequest().build(); } } - - @PostMapping(value = "/networks/{networkUuid}/non-evacuated-energy/run-and-save", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) - @Operation(summary = "Run a non evacuated energy sensitivity analysis on a network and save results in the database") - @ApiResponses(@ApiResponse(responseCode = "200", description = "The non evacuated energy sensitivity analysis default provider has been found")) - public ResponseEntity runNonEvacuatedEnergy(@Parameter(description = "Network UUID") @PathVariable("networkUuid") UUID networkUuid, - @Parameter(description = "Variant Id") @RequestParam(name = "variantId", required = false) String variantId, - @Parameter(description = "Result receiver") @RequestParam(name = "receiver", required = false) String receiver, - @Parameter(description = "Provider") @RequestParam(name = "provider", required = false) String provider, - @Parameter(description = "reportUuid") @RequestParam(name = "reportUuid", required = false) UUID reportUuid, - @Parameter(description = "reporterId") @RequestParam(name = "reporterId", required = false) String reporterId, - @Parameter(description = "The type name for the report") @RequestParam(name = "reportType", required = false, defaultValue = "NonEvacuatedEnergy") String reportType, - @Parameter(description = "loadFlow parameters uuid") @RequestParam(name = "loadFlowParametersUuid") UUID loadFlowParametersUuid, - @RequestBody NonEvacuatedEnergyInputData nonEvacuatedEnergyInputData, - @RequestHeader(HEADER_USER_ID) String userId) { - - NonEvacuatedEnergyRunContext runContext = sensitivityAnalysisParametersService.createNonEvacuatedEnergyRunContext( - networkUuid, - variantId, - receiver, - new ReportInfos(reportUuid, reporterId, reportType), - userId, - provider, - loadFlowParametersUuid, - nonEvacuatedEnergyInputData - ); - - UUID resultUuid = nonEvacuatedEnergyService.runAndSaveResult(runContext); - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(resultUuid); - } - - @GetMapping(value = "/non-evacuated-energy/results/{resultUuid}", produces = APPLICATION_JSON_VALUE) - @Operation(summary = "Get a non evacuated energy result from the database") - @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The non evacuated energy result"), - @ApiResponse(responseCode = "404", description = "Non evacuated energy result has not been found")}) - public ResponseEntity getResult(@Parameter(description = "Result UUID") - @PathVariable("resultUuid") UUID resultUuid) { - String result = nonEvacuatedEnergyService.getRunResult(resultUuid); - return result != null ? ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(result) - : ResponseEntity.notFound().build(); - } - - @DeleteMapping(value = "/non-evacuated-energy/results", produces = APPLICATION_JSON_VALUE) - @Operation(summary = "Delete non evacuated energy results from the database") - @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "All non evacuated energy results have been deleted")}) - public ResponseEntity deleteNonEvacuatedEnergyResults(@Parameter(description = "Results UUID") @RequestParam(value = "resultsUuids", required = false) List resultsUuids) { - nonEvacuatedEnergyService.deleteResults(resultsUuids); - return ResponseEntity.ok().build(); - } - - @GetMapping(value = "/non-evacuated-energy/results/{resultUuid}/status", produces = APPLICATION_JSON_VALUE) - @Operation(summary = "Get the non evacuated energy status from the database") - @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The non evacuated energy status status")}) - public ResponseEntity getNonEvacuatedEnergyStatus(@Parameter(description = "Result UUID") @PathVariable("resultUuid") UUID resultUuid) { - NonEvacuatedEnergyStatus result = nonEvacuatedEnergyService.getStatus(resultUuid); - return ResponseEntity.ok().body(result == null ? null : result.name()); - } - - @PutMapping(value = "/non-evacuated-energy/results/invalidate-status", produces = APPLICATION_JSON_VALUE) - @Operation(summary = "Invalidate the non evacuated energy status from the database") - @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The non evacuated energy status has been invalidated")}) - public ResponseEntity invalidateNonEvacuatedEnergyStatus(@Parameter(description = "Result uuids") @RequestParam(name = "resultUuid") List resultUuids) { - nonEvacuatedEnergyService.setStatus(resultUuids, NonEvacuatedEnergyStatus.NOT_DONE); - return ResponseEntity.ok().build(); - } - - @PutMapping(value = "/non-evacuated-energy/results/{resultUuid}/stop", produces = APPLICATION_JSON_VALUE) - @Operation(summary = "Stop a non evacuated energy computation") - @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The non evacuated energy has been stopped")}) - public ResponseEntity stopNonEvacuatedEnergy(@Parameter(description = "Result UUID") @PathVariable("resultUuid") UUID resultUuid, - @Parameter(description = "Result receiver") @RequestParam(name = "receiver", required = false) String receiver, - @RequestHeader(HEADER_USER_ID) String userId) { - nonEvacuatedEnergyService.stop(resultUuid, receiver, userId); - return ResponseEntity.ok().build(); - } - - @GetMapping(value = "/non-evacuated-energy-default-provider", produces = TEXT_PLAIN_VALUE) - @Operation(summary = "Get sensitivity analysis non evacuated energy default provider") - @ApiResponses(@ApiResponse(responseCode = "200", description = "The sensitivity analysis non evacuated energy default provider has been found")) - public ResponseEntity getNonEvacuatedEnergyDefaultProvider() { - return ResponseEntity.ok().body(nonEvacuatedEnergyService.getDefaultProvider()); - } } diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/SupervisionController.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/SupervisionController.java index 8b721bc2..e41f7846 100644 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/SupervisionController.java +++ b/src/main/java/org/gridsuite/sensitivityanalysis/server/SupervisionController.java @@ -36,11 +36,4 @@ public SupervisionController(SupervisionService supervisionService) { public ResponseEntity getResultsCount() { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(supervisionService.getAnalysisResultsCount()); } - - @GetMapping(value = "/non-evacuated-energy/results-count") - @Operation(summary = "Get non evacuated energy results count") - @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "The count of all non evacuated energy results")}) - public ResponseEntity getNonEvacuatedEnergyResultsCount() { - return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(supervisionService.getNonEvacuatedEnergyResultsCount()); - } } diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyContingencies.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyContingencies.java deleted file mode 100644 index 24175033..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyContingencies.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.gridsuite.sensitivityanalysis.server.dto.EquipmentsContainer; - -import java.util.List; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy contingencies") -public class NonEvacuatedEnergyContingencies { - List contingencies; - - boolean activated; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyGeneratorsCappings.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyGeneratorsCappings.java deleted file mode 100644 index b85f97b4..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyGeneratorsCappings.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.List; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy generators cappings") -public class NonEvacuatedEnergyGeneratorsCappings { - Double sensitivityThreshold; - - List generators; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyGeneratorsCappingsByType.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyGeneratorsCappingsByType.java deleted file mode 100644 index bb068b41..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyGeneratorsCappingsByType.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -import com.powsybl.iidm.network.EnergySource; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.gridsuite.sensitivityanalysis.server.dto.EquipmentsContainer; - -import java.util.List; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy generators cappings by type") -public class NonEvacuatedEnergyGeneratorsCappingsByType { - List generators; - - EnergySource energySource; - - boolean activated; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyInputData.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyInputData.java deleted file mode 100644 index a056dfbe..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyInputData.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -import com.powsybl.sensitivity.SensitivityAnalysisParameters; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.List; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy input data") -public class NonEvacuatedEnergyInputData { - private List nonEvacuatedEnergyStagesDefinition; - - private List nonEvacuatedEnergyStagesSelection; - - private NonEvacuatedEnergyGeneratorsCappings nonEvacuatedEnergyGeneratorsCappings; - - private List nonEvacuatedEnergyMonitoredBranches; - - private List nonEvacuatedEnergyContingencies; - - @Schema(description = "Sensitivity parameters") - private SensitivityAnalysisParameters parameters; - - @Schema(description = "Loadflow model-specific parameters") - private Map loadFlowSpecificParameters; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyMonitoredBranches.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyMonitoredBranches.java deleted file mode 100644 index d7bfd9ff..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyMonitoredBranches.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.gridsuite.sensitivityanalysis.server.dto.EquipmentsContainer; - -import java.util.List; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy monitored branches") -public class NonEvacuatedEnergyMonitoredBranches { - List branches; - - boolean activated; - - boolean istN; - - String limitNameN; - - @JsonProperty("nCoefficient") - float nCoefficient; - - boolean istNm1; - - String limitNameNm1; - - float nm1Coefficient; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStageDefinition.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStageDefinition.java deleted file mode 100644 index a94f7057..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStageDefinition.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.powsybl.iidm.network.EnergySource; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.gridsuite.sensitivityanalysis.server.dto.EquipmentsContainer; - -import java.util.List; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -@Schema(description = "Sensitivity analysis non evacuated energy stage definition") -public class NonEvacuatedEnergyStageDefinition { - List generators; - - EnergySource energySource; - - @JsonProperty("pMaxPercents") - List pMaxPercents; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStagesSelection.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStagesSelection.java deleted file mode 100644 index dc9f8eef..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStagesSelection.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy stages selection") -public class NonEvacuatedEnergyStagesSelection { - String name; - - @Builder.Default - List stagesDefinitionIndex = new ArrayList<>(); - - @Builder.Default - @JsonProperty("pMaxPercentsIndex") - List pMaxPercentsIndex = new ArrayList<>(); - - boolean activated; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStatus.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStatus.java deleted file mode 100644 index 283d75cd..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/NonEvacuatedEnergyStatus.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy; - -/** - * @author Franck Lecuyer - */ -public enum NonEvacuatedEnergyStatus { - NOT_DONE, - RUNNING, - COMPLETED -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/ContingencyStageDetailResult.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/ContingencyStageDetailResult.java deleted file mode 100644 index 4d85a91c..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/ContingencyStageDetailResult.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy stage detail result for a contingency") -public class ContingencyStageDetailResult { - @Builder.Default - private Map resultsByMonitoredBranch = new HashMap<>(); -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/GeneratorCapping.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/GeneratorCapping.java deleted file mode 100644 index bb9854e4..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/GeneratorCapping.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.powsybl.iidm.network.EnergySource; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * @author Franck Lecuyer - */ -@NoArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy generator capping") -public class GeneratorCapping { - private String generatorId; - - private EnergySource energySource; - - @JsonProperty("pInit") - private Double pInit; - - @JsonIgnore - private Double capping; - - private Double cumulatedCapping; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/MonitoredBranchDetailResult.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/MonitoredBranchDetailResult.java deleted file mode 100644 index 9a0fac31..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/MonitoredBranchDetailResult.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.powsybl.iidm.network.EnergySource; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy monitored branch detail result") -public class MonitoredBranchDetailResult { - private Double intensity; - - private String limitName; - - private Double limitValue; - - private Double percentOverload; - - @JsonProperty("p") - private Double p; - - @Builder.Default - Map cappingByEnergySource = new EnumMap<>(EnergySource.class); - - private Double overallCapping; - - @Builder.Default - Map sensitivityByEnergySource = new EnumMap<>(EnergySource.class); - - @Builder.Default - Map generatorsCapping = new HashMap<>(); -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/NonEvacuatedEnergyResults.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/NonEvacuatedEnergyResults.java deleted file mode 100644 index 01f173c2..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/NonEvacuatedEnergyResults.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy result") -public class NonEvacuatedEnergyResults { - @Builder.Default - private Map stagesSummary = new HashMap<>(); - - @Builder.Default - private Map stagesDetail = new HashMap<>(); -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageDetailResult.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageDetailResult.java deleted file mode 100644 index f77d4984..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageDetailResult.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.powsybl.iidm.network.EnergySource; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy stage detail result") -public class StageDetailResult { - @Builder.Default - @JsonProperty("pInitByEnergySource") - private Map pInitByEnergySource = new EnumMap<>(EnergySource.class); - - @Builder.Default - private Map resultsByContingency = new HashMap<>(); // key is null for N -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageSummaryContingencyResult.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageSummaryContingencyResult.java deleted file mode 100644 index 09d7cc52..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageSummaryContingencyResult.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * @author Franck Lecuyer - */ -@NoArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy stage summary contingency result") -public class StageSummaryContingencyResult { - private Boolean limitViolated; - - private String monitoredEquipmentWithMaxLimit; - - private Double monitoredEquipmentPower; - - private Double percentOverload; - - private Double capping; - - @JsonProperty("pLim") - private Double pLim; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageSummaryResult.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageSummaryResult.java deleted file mode 100644 index 47a0a2d0..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/dto/nonevacuatedenergy/results/StageSummaryResult.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.powsybl.iidm.network.EnergySource; -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Schema(description = "Sensitivity analysis non evacuated energy stage summary result") -public class StageSummaryResult { - @JsonProperty("pLimN") - private Double pLimN; - - @JsonProperty("pLimNm1") - private Double pLimNm1; - - @Builder.Default - @JsonProperty("pInitByEnergySource") - private Map pInitByEnergySource = new EnumMap<>(EnergySource.class); - - // monitored equipment infos related to pLim - @JsonProperty("pLimMonitoredEquipment") - private String pLimMonitoredEquipment; - - @JsonProperty("pLimLimit") - private String pLimLimit; - - private Double percentOverload; - - private String contingencyId; // null if N - - @Builder.Default - private Map resultsByContingency = new HashMap<>(); // key is null for N -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/entities/nonevacuatedenergy/NonEvacuatedEnergyGlobalStatusEntity.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/entities/nonevacuatedenergy/NonEvacuatedEnergyGlobalStatusEntity.java deleted file mode 100644 index 23971ada..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/entities/nonevacuatedenergy/NonEvacuatedEnergyGlobalStatusEntity.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2022, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.entities.nonevacuatedenergy; - -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Table; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; - -import java.io.Serializable; -import java.util.UUID; - -/** - * @author Franck Lecuyer - */ -@Getter -@AllArgsConstructor -@NoArgsConstructor -@Entity -@Table(name = "non_evacuated_energy_global_status") -public class NonEvacuatedEnergyGlobalStatusEntity implements Serializable { - @Id - private UUID resultUuid; - - private String status; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/entities/nonevacuatedenergy/NonEvacuatedEnergyResultEntity.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/entities/nonevacuatedenergy/NonEvacuatedEnergyResultEntity.java deleted file mode 100644 index c41c78ec..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/entities/nonevacuatedenergy/NonEvacuatedEnergyResultEntity.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.entities.nonevacuatedenergy; - -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Table; -import jakarta.persistence.Id; -import lombok.Getter; -import lombok.NoArgsConstructor; - -import java.io.Serializable; -import java.time.Instant; -import java.util.UUID; - -/** - * @author Franck Lecuyer - */ -@Getter -@NoArgsConstructor -@Entity -@Table(name = "non_evacuated_energy_result") -public class NonEvacuatedEnergyResultEntity implements Serializable { - @Id - private UUID resultUuid; - - @Column(columnDefinition = "timestamptz") - private Instant writeTimeStamp; - - @Column(name = "result", columnDefinition = "CLOB") - private String result; - - public NonEvacuatedEnergyResultEntity(UUID resultUuid, Instant writeTimeStamp, String result) { - this.resultUuid = resultUuid; - this.writeTimeStamp = writeTimeStamp; - this.result = result; - } -} - - diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/repositories/nonevacuatedenergy/NonEvacuatedEnergyResultRepository.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/repositories/nonevacuatedenergy/NonEvacuatedEnergyResultRepository.java deleted file mode 100644 index 9d8ba0c2..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/repositories/nonevacuatedenergy/NonEvacuatedEnergyResultRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.repositories.nonevacuatedenergy; - -import org.gridsuite.sensitivityanalysis.server.entities.nonevacuatedenergy.NonEvacuatedEnergyResultEntity; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.UUID; - -/** - * @author Franck Lecuyer - */ -@Repository -public interface NonEvacuatedEnergyResultRepository extends JpaRepository { - NonEvacuatedEnergyResultEntity findByResultUuid(UUID resultUuid); - - void deleteByResultUuid(UUID resultUuid); -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/repositories/nonevacuatedenergy/NonEvacuatedEnergyStatusRepository.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/repositories/nonevacuatedenergy/NonEvacuatedEnergyStatusRepository.java deleted file mode 100644 index ed152c93..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/repositories/nonevacuatedenergy/NonEvacuatedEnergyStatusRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.repositories.nonevacuatedenergy; - -import org.gridsuite.sensitivityanalysis.server.entities.nonevacuatedenergy.NonEvacuatedEnergyGlobalStatusEntity; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.UUID; - -/** - * @author Franck Lecuyer - */ -@Repository -public interface NonEvacuatedEnergyStatusRepository extends JpaRepository { - NonEvacuatedEnergyGlobalStatusEntity findByResultUuid(UUID resultUuid); - - void deleteByResultUuid(UUID resultUuid); -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SensitivityAnalysisParametersService.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SensitivityAnalysisParametersService.java index 2f4fd863..9a3e7437 100644 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SensitivityAnalysisParametersService.java +++ b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SensitivityAnalysisParametersService.java @@ -10,12 +10,10 @@ import com.powsybl.sensitivity.SensitivityAnalysisParameters; import org.gridsuite.computation.dto.ReportInfos; import org.gridsuite.sensitivityanalysis.server.dto.*; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyInputData; import org.gridsuite.sensitivityanalysis.server.dto.parameters.LoadFlowParametersValues; import org.gridsuite.sensitivityanalysis.server.dto.parameters.SensitivityAnalysisParametersInfos; import org.gridsuite.sensitivityanalysis.server.entities.parameters.SensitivityAnalysisParametersEntity; import org.gridsuite.sensitivityanalysis.server.repositories.SensitivityAnalysisParametersRepository; -import org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy.NonEvacuatedEnergyRunContext; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -133,33 +131,6 @@ public SensitivityAnalysisParametersInfos getDefauSensitivityAnalysisParametersI return SensitivityAnalysisParametersInfos.builder().provider(defaultProvider).build(); } - public NonEvacuatedEnergyRunContext createNonEvacuatedEnergyRunContext(UUID networkUuid, String variantId, - String receiver, - ReportInfos reportInfos, - String userId, - String provider, - UUID loadFlowParametersUuid, - NonEvacuatedEnergyInputData nonEvacuatedEnergyInputData) { - NonEvacuatedEnergyRunContext nonEvacuatedEnergyRunContext = new NonEvacuatedEnergyRunContext(networkUuid, - variantId, - nonEvacuatedEnergyInputData, - receiver, - provider != null ? provider : "default-provider", // TODO : remove test on provider null when fix in powsybl-ws-commons will handle null provider - reportInfos, - userId); - - // complete nonEvacuatedEnergyRunContext with loadFlowParameters - completeNonEvacuatedEnergyRunContext(nonEvacuatedEnergyRunContext, loadFlowParametersUuid); - - return nonEvacuatedEnergyRunContext; - } - - private void completeNonEvacuatedEnergyRunContext(NonEvacuatedEnergyRunContext nonEvacuatedEnergyRunContext, UUID loadFlowParametersUuid) { - LoadFlowParametersValues loadFlowParametersValues = loadFlowService.getLoadFlowParameters(loadFlowParametersUuid, nonEvacuatedEnergyRunContext.getProvider()); - nonEvacuatedEnergyRunContext.getNonEvacuatedEnergyInputData().setLoadFlowSpecificParameters(loadFlowParametersValues.specificParameters()); - nonEvacuatedEnergyRunContext.getNonEvacuatedEnergyInputData().getParameters().setLoadFlowParameters(loadFlowParametersValues.commonParameters()); - } - @Transactional(readOnly = true) public SensitivityAnalysisRunContext createRunContext(UUID networkUuid, String variantId, String receiver, diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SupervisionService.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SupervisionService.java index 6d646ad3..e745aac3 100644 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SupervisionService.java +++ b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/SupervisionService.java @@ -7,7 +7,6 @@ package org.gridsuite.sensitivityanalysis.server.service; import org.gridsuite.sensitivityanalysis.server.repositories.AnalysisResultRepository; -import org.gridsuite.sensitivityanalysis.server.repositories.nonevacuatedenergy.NonEvacuatedEnergyResultRepository; import org.springframework.stereotype.Service; /** @@ -16,19 +15,12 @@ @Service public class SupervisionService { private final AnalysisResultRepository analysisResultRepository; - private final NonEvacuatedEnergyResultRepository nonEvacuatedEnergyResultRepository; - public SupervisionService(AnalysisResultRepository analysisResultRepository, - NonEvacuatedEnergyResultRepository nonEvacuatedEnergyResultRepository) { + public SupervisionService(AnalysisResultRepository analysisResultRepository) { this.analysisResultRepository = analysisResultRepository; - this.nonEvacuatedEnergyResultRepository = nonEvacuatedEnergyResultRepository; } public Integer getAnalysisResultsCount() { return (int) analysisResultRepository.count(); } - - public Integer getNonEvacuatedEnergyResultsCount() { - return (int) nonEvacuatedEnergyResultRepository.count(); - } } diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/LimitInfos.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/LimitInfos.java deleted file mode 100644 index 2b798394..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/LimitInfos.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import com.powsybl.iidm.network.TwoSides; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * @author Franck Lecuyer - */ -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -public class LimitInfos { - String name; - - double value; - - TwoSides side; -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/MonitoredBranchThreshold.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/MonitoredBranchThreshold.java deleted file mode 100644 index 38d73de9..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/MonitoredBranchThreshold.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import com.powsybl.iidm.network.Branch; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * @author Franck Lecuyer - */ -@NoArgsConstructor -@Getter -@Setter -public class MonitoredBranchThreshold { - Branch branch; - - boolean istN; - - String nLimitName; // null if istN = true - - Float nCoeff; - - boolean istNm1; - - String nm1LimitName; // null if istNm1 = true - - Float nm1Coeff; - - public MonitoredBranchThreshold(Branch branch) { - this.branch = branch; - this.istN = false; - this.istNm1 = false; - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyInputBuilderService.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyInputBuilderService.java deleted file mode 100644 index 1f6f7de5..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyInputBuilderService.java +++ /dev/null @@ -1,507 +0,0 @@ -/** - * Copyright (c) 2022, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import com.powsybl.commons.PowsyblException; -import com.powsybl.commons.report.ReportNode; -import com.powsybl.commons.report.ReportNodeAdder; -import com.powsybl.commons.report.TypedValue; -import com.powsybl.contingency.Contingency; -import com.powsybl.contingency.ContingencyContext; -import com.powsybl.iidm.network.*; -import com.powsybl.sensitivity.*; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.gridsuite.sensitivityanalysis.server.dto.ContingencyListExportResult; -import org.gridsuite.sensitivityanalysis.server.dto.EquipmentsContainer; -import org.gridsuite.sensitivityanalysis.server.dto.IdentifiableAttributes; -import org.gridsuite.sensitivityanalysis.server.dto.SensitivityAnalysisInputData; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyContingencies; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyGeneratorsCappingsByType; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyMonitoredBranches; -import org.gridsuite.sensitivityanalysis.server.service.ActionsService; -import org.gridsuite.sensitivityanalysis.server.service.FilterService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * @author Franck Lecuyer - */ -@Service -public class NonEvacuatedEnergyInputBuilderService { - private static final String EXPECTED_TYPE = "expectedType"; - private static final Logger LOGGER = LoggerFactory.getLogger(NonEvacuatedEnergyInputBuilderService.class); - private final ActionsService actionsService; - private final FilterService filterService; - - public NonEvacuatedEnergyInputBuilderService(ActionsService actionsService, FilterService filterService) { - this.actionsService = actionsService; - this.filterService = filterService; - } - - private static void addReport(ReportNode parent, String messageKey, Map values, TypedValue severity) { - ReportNodeAdder adder = parent.newReportNode().withMessageTemplate(messageKey); - values.entrySet().forEach(v -> adder.withUntypedValue(v.getKey(), v.getValue())); - adder.withSeverity(TypedValue.ERROR_SEVERITY).add(); - } - - private List goGetContingencies(List contingencyListIdent, UUID networkUuid, String variantId, ReportNode reporter) { - List contingencyListIds = contingencyListIdent.stream().map(EquipmentsContainer::getContainerId).toList(); - ContingencyListExportResult contingencies = actionsService.getContingencyList(contingencyListIds, networkUuid, variantId); - if (contingencies == null) { - return List.of(); - } - - if (contingencies.getContingenciesNotFound() != null) { - contingencies.getContingenciesNotFound().forEach(id -> { - EquipmentsContainer container = contingencyListIdent.stream().filter(c -> c.getContainerId().equals(id)).findFirst().orElseThrow(); - LOGGER.error("Could not get contingencies from {}", container.getContainerName()); - addReport(reporter, - "sensitivity.analysis.server.contingencyTranslationFailure", - Map.of("name", container.getContainerName()), - TypedValue.ERROR_SEVERITY - ); - }); - } - - return contingencies.getContingenciesFound() == null ? List.of() : contingencies.getContingenciesFound(); - } - - public List buildContingencies(UUID networkUuid, String variantId, List contingencyListsContainerIdents, ReportNode reporter) { - return goGetContingencies(contingencyListsContainerIdents, networkUuid, variantId, reporter); - } - - private double getGeneratorWeight(Generator generator, SensitivityAnalysisInputData.DistributionType distributionType, Double distributionKey) { - switch (distributionType) { - case PROPORTIONAL: - return !Double.isNaN(generator.getTerminal().getP()) ? generator.getTerminal().getP() : 0.; - case PROPORTIONAL_MAXP: - return generator.getMaxP(); - case REGULAR: - return 1.; - case VENTILATION: - if (distributionKey == null) { - throw new PowsyblException("Distribution key required for VENTILATION distribution type !!"); - } - return distributionKey; - default: - throw new UnsupportedOperationException("Distribution type not allowed for generator"); - } - } - - private List goGetIdentifiables(EquipmentsContainer filter, UUID networkUuid, String variantId, ReportNode reporter) { - try { - return filterService.getIdentifiablesFromFilter(filter.getContainerId(), networkUuid, variantId); - } catch (Exception ex) { - LOGGER.error("Could not get identifiables from filter " + filter.getContainerName(), ex); - addReport(reporter, - "sensitivity.analysis.server.filterTranslationFailure", - Map.of("exception", ex.getMessage(), "name", filter.getContainerName()), - TypedValue.ERROR_SEVERITY - ); - return List.of(); - } - } - - public Stream getIdentifiablesFromContainer(UUID networkUuid, String variantId, EquipmentsContainer filter, - List equipmentsTypesAllowed, ReportNode reporter) { - - List listIdentAttributes = goGetIdentifiables(filter, networkUuid, variantId, reporter); - - // check that monitored equipments type is allowed - if (!listIdentAttributes.stream().allMatch(i -> equipmentsTypesAllowed.contains(i.getType()))) { - addReport(reporter, - "sensitivity.analysis.server.badEquipmentType", - Map.of("name", filter.getContainerName(), EXPECTED_TYPE, equipmentsTypesAllowed.toString()), - TypedValue.WARN_SEVERITY - ); - return Stream.empty(); - } - - return listIdentAttributes.stream(); - } - - private Stream getMonitoredIdentifiablesFromContainer(UUID networkUuid, String variantId, EquipmentsContainer filter, List equipmentsTypesAllowed, ReportNode reporter) { - List listIdentAttributes = goGetIdentifiables(filter, networkUuid, variantId, reporter); - - // check that monitored equipments type is allowed - if (!listIdentAttributes.stream().allMatch(i -> equipmentsTypesAllowed.contains(i.getType()))) { - addReport(reporter, - "sensitivity.analysis.server.badMonitoredEquipmentType", - Map.of("name", filter.getContainerName(), EXPECTED_TYPE, equipmentsTypesAllowed.toString()), - TypedValue.WARN_SEVERITY - ); - return Stream.empty(); - } - - return listIdentAttributes.stream(); - } - - private List buildSensitivityVariableSets(UUID networkUuid, String variantId, Network network, ReportNode reporter, - List variablesTypesAllowed, - List filters, - EnergySource energySource, - SensitivityAnalysisInputData.DistributionType distributionType) { - List result = new ArrayList<>(); - - Stream>> variablesContainersLists = filters.stream() - .map(filter -> Pair.of(filter.getContainerName(), getIdentifiablesFromContainer(networkUuid, variantId, filter, variablesTypesAllowed, reporter).collect(Collectors.toList()))) - .filter(list -> !list.getRight().isEmpty()); - - variablesContainersLists.forEach(variablesList -> { - List variables = new ArrayList<>(); - for (IdentifiableAttributes identifiableAttributes : variablesList.getRight()) { - if (identifiableAttributes.getType() == IdentifiableType.GENERATOR) { - Generator generator = network.getGenerator(identifiableAttributes.getId()); - if (generator == null) { - throw new PowsyblException("Generator '" + identifiableAttributes.getId() + "' not found !!"); - } - if (generator.getEnergySource() != energySource) { - addReport(reporter, - "sensitivity.analysis.server.BadGeneratorEnergySource", - Map.of("generatorId", generator.getId(), "energySource", energySource.name()), - TypedValue.WARN_SEVERITY - ); - } else { - double weight = getGeneratorWeight(generator, distributionType, identifiableAttributes.getDistributionKey()); - variables.add(new WeightedSensitivityVariable(identifiableAttributes.getId(), weight)); - } - } - } - result.add(new SensitivityVariableSet(variablesList.getLeft() + " (" + distributionType.name() + ")", variables)); - }); - - return result; - } - - private List buildSensitivityFactorsFromVariablesSets(NonEvacuatedEnergyRunContext context, - Network network, - ReportNode reporter, - List monitoredEquipmentsTypesAllowed, - NonEvacuatedEnergyMonitoredBranches branches, - List variablesSets, - List contingencies, - SensitivityVariableType sensitivityVariableType) { - if (variablesSets.isEmpty()) { - return List.of(); - } - - List monitoredEquipments = branches.getBranches().stream() - .flatMap(filter -> getMonitoredIdentifiablesFromContainer(context.getNetworkUuid(), context.getVariantId(), filter, monitoredEquipmentsTypesAllowed, reporter)) - .collect(Collectors.toList()); - - return getSensitivityFactorsFromEquipments(context, network, variablesSets.stream().map(SensitivityVariableSet::getId).collect(Collectors.toList()), - monitoredEquipments, branches, contingencies, sensitivityVariableType, reporter, true); - } - - private List buildSensitivityFactors(NonEvacuatedEnergyRunContext context, - Network network, - ReportNode reporter, - List monitoredEquipmentsTypesAllowed, - NonEvacuatedEnergyMonitoredBranches branches, - List injectionsFilters, - List contingencies, - SensitivityVariableType sensitivityVariableType) { - - List equipments = injectionsFilters.stream() - .flatMap(filter -> getIdentifiablesFromContainer(context.getNetworkUuid(), context.getVariantId(), filter, List.of(IdentifiableType.GENERATOR), reporter)) - .toList(); - if (equipments.isEmpty()) { - return List.of(); - } - - List monitoredEquipments = branches.getBranches().stream() - .flatMap(filter -> getMonitoredIdentifiablesFromContainer(context.getNetworkUuid(), context.getVariantId(), filter, monitoredEquipmentsTypesAllowed, reporter)) - .collect(Collectors.toList()); - - return getSensitivityFactorsFromEquipments(context, network, equipments.stream().map(IdentifiableAttributes::getId).toList(), monitoredEquipments, branches, contingencies, sensitivityVariableType, reporter, false); - } - - private void genSensitivityFactorPerVariableId(List variableIds, - SensitivityFunctionType functionType, - String monitoredEquipmentId, - SensitivityVariableType variableType, - boolean variableSet, - List result) { - variableIds.forEach(varId -> result.add(new SensitivityFactor(functionType, monitoredEquipmentId, variableType, varId, variableSet, ContingencyContext.none()))); - } - - private void genSensitivityFactorPerVariableIdsAndContingencyIds(List variableIds, - List contingencies, - SensitivityFunctionType functionType, - String monitoredEquipmentId, - SensitivityVariableType variableType, - boolean variableSet, - List result) { - variableIds.forEach(varId -> - contingencies.forEach(contingency -> - result.add(new SensitivityFactor(functionType, monitoredEquipmentId, variableType, varId, variableSet, ContingencyContext.specificContingency(contingency.getId()))) - )); - } - - private boolean genFactorForPermanentLimit(Branch branch, - TwoSides side, - Optional currentLimits, - List variableIds, - boolean variableSet, - SensitivityVariableType sensitivityVariableType, - NonEvacuatedEnergyMonitoredBranches branches, - MonitoredBranchThreshold monitoredBranchThreshold, - List contingencies, - List result, - ReportNode reporter) { - if (currentLimits.isEmpty()) { - return false; - } - if (Double.isNaN(currentLimits.get().getPermanentLimit())) { - // no permanent limit on side found : report and throw exception - addReport(reporter, - "sensitivity.analysis.server.monitoredBranchNoCurrentOrPermanentLimitsOnSide", - Map.of("id", branch.getId(), "side", side.name()), - TypedValue.ERROR_SEVERITY - ); - throw new PowsyblException("Branch '" + branch.getId() + "' has no permanent limit on side '" + side.name() + "' !!"); - } - - SensitivityFunctionType functionTypeActivePower = side == TwoSides.ONE ? SensitivityFunctionType.BRANCH_ACTIVE_POWER_1 : SensitivityFunctionType.BRANCH_ACTIVE_POWER_2; - SensitivityFunctionType functionTypeCurrent = side == TwoSides.ONE ? SensitivityFunctionType.BRANCH_CURRENT_1 : SensitivityFunctionType.BRANCH_CURRENT_2; - - if (branches.isIstN()) { // just one SensitivityFactor per variable id - genSensitivityFactorPerVariableId(variableIds, variableSet ? functionTypeActivePower : functionTypeCurrent, branch.getId(), sensitivityVariableType, variableSet, result); - monitoredBranchThreshold.setIstN(true); - monitoredBranchThreshold.setNCoeff(branches.getNCoefficient()); - } - if (branches.isIstNm1()) { // one SensitivityFactor per variable id and per contingency id - genSensitivityFactorPerVariableIdsAndContingencyIds(variableIds, contingencies, variableSet ? functionTypeActivePower : functionTypeCurrent, branch.getId(), sensitivityVariableType, variableSet, result); - monitoredBranchThreshold.setIstNm1(true); - monitoredBranchThreshold.setNm1Coeff(branches.getNm1Coefficient()); - } - return true; - } - - private boolean genFactorForTemporaryLimit(Branch branch, - TwoSides side, - Optional currentLimits, - String limitName, - boolean inN, - List variableIds, - boolean variableSet, - SensitivityVariableType sensitivityVariableType, - NonEvacuatedEnergyMonitoredBranches branches, - MonitoredBranchThreshold monitoredBranchThreshold, - List contingencies, - List result) { - if (currentLimits.isEmpty() || currentLimits.get().getTemporaryLimits().stream().noneMatch(l -> l.getName().equals(limitName))) { - return false; - } - - SensitivityFunctionType functionTypeActivePower = side == TwoSides.ONE ? SensitivityFunctionType.BRANCH_ACTIVE_POWER_1 : SensitivityFunctionType.BRANCH_ACTIVE_POWER_2; - SensitivityFunctionType functionTypeCurrent = side == TwoSides.ONE ? SensitivityFunctionType.BRANCH_CURRENT_1 : SensitivityFunctionType.BRANCH_CURRENT_2; - - if (inN) { - genSensitivityFactorPerVariableId(variableIds, variableSet ? functionTypeActivePower : functionTypeCurrent, branch.getId(), sensitivityVariableType, variableSet, result); - monitoredBranchThreshold.setIstN(false); - monitoredBranchThreshold.setNLimitName(limitName); - monitoredBranchThreshold.setNCoeff(branches.getNCoefficient()); - } else { - genSensitivityFactorPerVariableIdsAndContingencyIds(variableIds, contingencies, variableSet ? functionTypeActivePower : functionTypeCurrent, branch.getId(), sensitivityVariableType, variableSet, result); - monitoredBranchThreshold.setIstNm1(false); - monitoredBranchThreshold.setNm1LimitName(limitName); - monitoredBranchThreshold.setNm1Coeff(branches.getNm1Coefficient()); - } - return true; - } - - private List getSensitivityFactorsFromEquipments(NonEvacuatedEnergyRunContext context, - Network network, - List variableIds, - List monitoredEquipments, - NonEvacuatedEnergyMonitoredBranches branches, - List contingencies, - SensitivityVariableType sensitivityVariableType, - ReportNode reporter, - boolean variableSet) { - List result = new ArrayList<>(); - - monitoredEquipments.forEach(monitoredEquipment -> { - // get branch from network - Branch branch = network.getBranch(monitoredEquipment.getId()); - if (branch == null) { // branch not found : just report and ignore the branch - addReport(reporter, - "sensitivity.analysis.server.monitoredBranchNotFound", - Map.of("id", monitoredEquipment.getId()), - TypedValue.ERROR_SEVERITY - ); - return; - } - Optional currentLimits1 = branch.getCurrentLimits1(); - Optional currentLimits2 = branch.getCurrentLimits2(); - if (currentLimits1.isEmpty() && currentLimits2.isEmpty()) { - // no current limits on both sides found : report and throw exception - addReport(reporter, - "sensitivity.analysis.server.monitoredBranchNoCurrentLimits", - Map.of("id", monitoredEquipment.getId()), - TypedValue.ERROR_SEVERITY - ); - throw new PowsyblException("Branch '" + branch.getId() + "' has no current limits !!"); - } - - MonitoredBranchThreshold monitoredBranchThreshold = new MonitoredBranchThreshold(branch); - - if (branches.isIstN() || branches.isIstNm1()) { // Ist activated : we consider the permanent limit - // permanent limit on side 1 - boolean factors1Generated = genFactorForPermanentLimit(branch, TwoSides.ONE, currentLimits1, variableIds, variableSet, sensitivityVariableType, branches, monitoredBranchThreshold, contingencies, result, reporter); - - // permanent limit on side 2 - boolean factors2Generated = genFactorForPermanentLimit(branch, TwoSides.TWO, currentLimits2, variableIds, variableSet, sensitivityVariableType, branches, monitoredBranchThreshold, contingencies, result, reporter); - - if (!factors1Generated && !factors2Generated) { - // no temporary limit on one side : report and throw exception - addReport(reporter, - "sensitivity.analysis.server.monitoredBranchNoPermanentLimits", - Map.of("id", monitoredEquipment.getId()), - TypedValue.ERROR_SEVERITY - ); - throw new PowsyblException("Branch '" + branch.getId() + "' has no permanent limits !!"); - } - } - - if (!branches.isIstN() && StringUtils.isNotEmpty(branches.getLimitNameN())) { // here we consider the temporary limits - // temporary limits on side 1 - boolean factors1Generated = genFactorForTemporaryLimit(branch, TwoSides.ONE, currentLimits1, branches.getLimitNameN(), true, variableIds, variableSet, sensitivityVariableType, branches, monitoredBranchThreshold, contingencies, result); - - // temporary limits on side 2 - boolean factors2Generated = genFactorForTemporaryLimit(branch, TwoSides.TWO, currentLimits2, branches.getLimitNameN(), true, variableIds, variableSet, sensitivityVariableType, branches, monitoredBranchThreshold, contingencies, result); - - if (!factors1Generated && !factors2Generated) { - addReport(reporter, - "sensitivity.analysis.server.monitoredBranchTemporaryLimitNotFound", - Map.of("limitName", branches.getLimitNameN(), "id", branch.getId()), - TypedValue.ERROR_SEVERITY - ); - throw new PowsyblException("Temporary limit '" + branches.getLimitNameN() + "' not found for branch '" + branch.getId() + "' !!"); - } - } - - if (!branches.isIstNm1() && StringUtils.isNotEmpty(branches.getLimitNameNm1())) { // here we consider the temporary limit - // temporary limits on side 1 - boolean factors1Generated = genFactorForTemporaryLimit(branch, TwoSides.ONE, currentLimits1, branches.getLimitNameNm1(), false, variableIds, variableSet, sensitivityVariableType, branches, monitoredBranchThreshold, contingencies, result); - - // temporary limits on side 2 - boolean factors2Generated = genFactorForTemporaryLimit(branch, TwoSides.TWO, currentLimits2, branches.getLimitNameNm1(), false, variableIds, variableSet, sensitivityVariableType, branches, monitoredBranchThreshold, contingencies, result); - - if (!factors1Generated && !factors2Generated) { - addReport(reporter, - "sensitivity.analysis.server.monitoredBranchTemporaryLimitNotFound", - Map.of("limitName", branches.getLimitNameNm1(), "id", branch.getId()), - TypedValue.ERROR_SEVERITY - ); - throw new PowsyblException("Temporary limit '" + branches.getLimitNameNm1() + "' not found for branch '" + branch.getId() + "' !!"); - } - } - - if (!result.isEmpty()) { - context.getNonEvacuatedEnergyInputs().getBranchesThresholds().put(monitoredEquipment.getId(), monitoredBranchThreshold); - } - }); - - return result; - } - - private void buildSensitivityFactorsAndVariableSets(NonEvacuatedEnergyRunContext context, - Network network, - ReportNode reporter) { - List monitoredBranches = context.getNonEvacuatedEnergyInputData().getNonEvacuatedEnergyMonitoredBranches(); - List generatorsCappingsByType = context.getNonEvacuatedEnergyInputData().getNonEvacuatedEnergyGeneratorsCappings().getGenerators(); - - // build inputs for the sensitivities in MW per generation kind (similar to sensitivity analysis computation with injections set) - generatorsCappingsByType.stream() - .filter(NonEvacuatedEnergyGeneratorsCappingsByType::isActivated) // we keep only activated generators limits - .forEach(generatorLimitByType -> { - // build sensitivity variable sets from generators limits in input data - List vInjectionsSets = buildSensitivityVariableSets( - context.getNetworkUuid(), context.getVariantId(), network, reporter, - List.of(IdentifiableType.GENERATOR), - generatorLimitByType.getGenerators(), - generatorLimitByType.getEnergySource(), - SensitivityAnalysisInputData.DistributionType.PROPORTIONAL_MAXP); - context.getNonEvacuatedEnergyInputs().addSensitivityVariableSets(vInjectionsSets); - - // we store the cappings generators by energy source - context.getNonEvacuatedEnergyInputs().getCappingsGenerators().put(generatorLimitByType.getEnergySource(), - vInjectionsSets.stream().flatMap(v -> v.getVariablesById().keySet().stream()).toList()); - - // build sensitivity factors from the variable sets (=set of generators), the contingencies and the monitored branches sets - monitoredBranches.stream() - .filter(NonEvacuatedEnergyMonitoredBranches::isActivated) // we keep only activated monitored branches set - .forEach(branches -> { - List fInjectionsSet = buildSensitivityFactorsFromVariablesSets( - context, network, reporter, - List.of(IdentifiableType.LINE, IdentifiableType.TWO_WINDINGS_TRANSFORMER), - branches, - vInjectionsSets, - context.getNonEvacuatedEnergyInputs().getContingencies(), - SensitivityVariableType.INJECTION_ACTIVE_POWER); - context.getNonEvacuatedEnergyInputs().addSensitivityFactors(fInjectionsSet); - }); - }); - - // build inputs for the sensitivities in A for each generator (similar to sensitivity analysis computation with injections) - generatorsCappingsByType.stream() - .filter(NonEvacuatedEnergyGeneratorsCappingsByType::isActivated) // we keep only activated generators limits - .forEach(generatorLimitByType -> { - // build sensitivity factors from the variables (=generators), the contingencies and the monitored branches sets - monitoredBranches.stream() - .filter(NonEvacuatedEnergyMonitoredBranches::isActivated) // we keep only activated monitored branches set - .forEach(branches -> { - // build the sensitivity factors for each monitored branch - List fInjectionsSet = buildSensitivityFactors( - context, network, reporter, - List.of(IdentifiableType.LINE, IdentifiableType.TWO_WINDINGS_TRANSFORMER), - branches, - generatorLimitByType.getGenerators(), - context.getNonEvacuatedEnergyInputs().getContingencies(), - SensitivityVariableType.INJECTION_ACTIVE_POWER); - context.getNonEvacuatedEnergyInputs().addSensitivityFactors(fInjectionsSet); - }); - }); - } - - public void build(NonEvacuatedEnergyRunContext context, Network network, ReportNode reporter) { - try { - // build all contingencies from the input data - context.getNonEvacuatedEnergyInputs().addContingencies(buildContingencies(context.getNetworkUuid(), - context.getVariantId(), - context.getNonEvacuatedEnergyInputData().getNonEvacuatedEnergyContingencies().stream() - .filter(NonEvacuatedEnergyContingencies::isActivated) // we keep only the activated contingencies - .map(NonEvacuatedEnergyContingencies::getContingencies) - .flatMap(List::stream) - .toList(), - reporter)); - - // build all sensitivity variables and factors from the input data - buildSensitivityFactorsAndVariableSets(context, network, reporter); - } catch (Exception ex) { - String msg = ex.getMessage(); - if (msg == null) { - msg = ex.getClass().getName(); - } - addReport(reporter, - "sensitivity.analysis.server.NonEvacuatedEnergyInputParametersTranslationFailure", - Map.of("exception", msg), - TypedValue.ERROR_SEVERITY - ); - LOGGER.error("Running non evacuated energy context translation failure, report added"); - throw ex; - } - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyInputs.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyInputs.java deleted file mode 100644 index e4f1e24d..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyInputs.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import com.powsybl.contingency.Contingency; -import com.powsybl.iidm.network.EnergySource; -import com.powsybl.sensitivity.SensitivityFactor; -import com.powsybl.sensitivity.SensitivityVariableSet; -import lombok.Getter; -import lombok.NoArgsConstructor; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@NoArgsConstructor -@Getter -public class NonEvacuatedEnergyInputs { - private final List contingencies = new ArrayList<>(); - - private final List factors = new ArrayList<>(); - - private final List variablesSets = new ArrayList<>(); - - // intermediate data used during the computation process - private final Map branchesThresholds = new HashMap<>(); // monitored branches information - private final Map> cappingsGenerators = new EnumMap<>(EnergySource.class); // list of capping generators by energy source - private final Map generatorsPInit = new HashMap<>(); // initial targetP for the capping generators - private final Map generatorsPInitByEnergySource = new EnumMap<>(EnergySource.class); // initial overall targetP for the capping generators by energy source - - public void addContingencies(List contingencies) { - this.contingencies.addAll(contingencies); - } - - public void addSensitivityFactors(List factors) { - this.factors.addAll(factors); - } - - public void addSensitivityVariableSets(List variablesSets) { - this.variablesSets.addAll(variablesSets); - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyObserver.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyObserver.java deleted file mode 100644 index 3f83d69b..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyObserver.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2024, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.observation.ObservationRegistry; -import lombok.NonNull; -import org.gridsuite.computation.service.AbstractComputationObserver; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyInputData; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results.NonEvacuatedEnergyResults; -import org.springframework.stereotype.Service; - -/** - * @author Mathieu DEHARBE - */ -@Service -public class NonEvacuatedEnergyObserver extends AbstractComputationObserver { - private static final String COMPUTATION_TYPE = "nonEvacuatedEnergy"; - - public NonEvacuatedEnergyObserver(@NonNull ObservationRegistry observationRegistry, - @NonNull MeterRegistry meterRegistry) { - super(observationRegistry, meterRegistry); - } - - @Override - protected String getComputationType() { - return COMPUTATION_TYPE; - } - - @Override - protected String getResultStatus(NonEvacuatedEnergyResults res) { - return res == null ? "NOK" : "OK"; - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyResultContext.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyResultContext.java deleted file mode 100644 index 8161015d..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyResultContext.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.gridsuite.computation.service.AbstractResultContext; -import org.gridsuite.computation.dto.ReportInfos; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyInputData; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHeaders; - -import java.io.UncheckedIOException; -import java.util.Objects; -import java.util.UUID; - -import static org.gridsuite.computation.service.NotificationService.HEADER_USER_ID; -import static org.gridsuite.computation.utils.MessageUtils.getNonNullHeader; - -/** - * @author Franck Lecuyer - */ -public class NonEvacuatedEnergyResultContext extends AbstractResultContext { - - public NonEvacuatedEnergyResultContext(UUID resultUuid, NonEvacuatedEnergyRunContext runContext) { - super(resultUuid, runContext); - } - - public static NonEvacuatedEnergyResultContext fromMessage(Message message, ObjectMapper objectMapper) { - Objects.requireNonNull(message); - MessageHeaders headers = message.getHeaders(); - UUID resultUuid = UUID.fromString(getNonNullHeader(headers, "resultUuid")); - UUID networkUuid = UUID.fromString(getNonNullHeader(headers, "networkUuid")); - String variantId = (String) headers.get("variantId"); - - String receiver = (String) headers.get("receiver"); - String provider = (String) headers.get("provider"); - String userId = (String) headers.get(HEADER_USER_ID); - NonEvacuatedEnergyInputData nonEvacuatedEnergyInputData; - try { - nonEvacuatedEnergyInputData = objectMapper.readValue(message.getPayload(), new TypeReference<>() { }); - } catch (JsonProcessingException e) { - throw new UncheckedIOException(e); - } - UUID reportUuid = headers.containsKey(REPORT_UUID_HEADER) ? UUID.fromString((String) Objects.requireNonNull(headers.get(REPORT_UUID_HEADER))) : null; - String reporterId = headers.containsKey(REPORTER_ID_HEADER) ? (String) headers.get(REPORTER_ID_HEADER) : null; - String reportType = headers.containsKey(REPORT_TYPE_HEADER) ? (String) headers.get(REPORT_TYPE_HEADER) : null; - NonEvacuatedEnergyRunContext nonEvacuatedEnergyRunContext = new NonEvacuatedEnergyRunContext(networkUuid, variantId, nonEvacuatedEnergyInputData, receiver, provider, new ReportInfos(reportUuid, reporterId, reportType), userId); - return new NonEvacuatedEnergyResultContext(resultUuid, nonEvacuatedEnergyRunContext); - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyResultService.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyResultService.java deleted file mode 100644 index ca8e2214..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyResultService.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import org.gridsuite.computation.service.AbstractComputationResultService; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyStatus; -import org.gridsuite.sensitivityanalysis.server.entities.nonevacuatedenergy.NonEvacuatedEnergyGlobalStatusEntity; -import org.gridsuite.sensitivityanalysis.server.entities.nonevacuatedenergy.NonEvacuatedEnergyResultEntity; -import org.gridsuite.sensitivityanalysis.server.repositories.nonevacuatedenergy.NonEvacuatedEnergyResultRepository; -import org.gridsuite.sensitivityanalysis.server.repositories.nonevacuatedenergy.NonEvacuatedEnergyStatusRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.Objects; -import java.util.UUID; - -/** - * @author Franck Lecuyer - */ -@Service -public class NonEvacuatedEnergyResultService extends AbstractComputationResultService { - - private final NonEvacuatedEnergyStatusRepository nonEvacuatedEnergyStatusRepository; - - private final NonEvacuatedEnergyResultRepository nonEvacuatedEnergyResultRepository; - - public NonEvacuatedEnergyResultService(NonEvacuatedEnergyStatusRepository nonEvacuatedEnergyStatusRepository, - NonEvacuatedEnergyResultRepository nonEvacuatedEnergyResultRepository) { - this.nonEvacuatedEnergyStatusRepository = nonEvacuatedEnergyStatusRepository; - this.nonEvacuatedEnergyResultRepository = nonEvacuatedEnergyResultRepository; - } - - private static NonEvacuatedEnergyGlobalStatusEntity toStatusEntity(UUID resultUuid, String status) { - return new NonEvacuatedEnergyGlobalStatusEntity(resultUuid, status); - } - - @Transactional - @Override - public void insertStatus(List resultUuids, NonEvacuatedEnergyStatus status) { - Objects.requireNonNull(resultUuids); - nonEvacuatedEnergyStatusRepository.saveAll(resultUuids.stream() - .map(uuid -> toStatusEntity(uuid, status.name())).toList()); - } - - @Transactional - public void insert(UUID resultUuid, String result, NonEvacuatedEnergyStatus status) { - Objects.requireNonNull(resultUuid); - if (result != null) { - nonEvacuatedEnergyResultRepository.save(new NonEvacuatedEnergyResultEntity(resultUuid, - Instant.now().truncatedTo(ChronoUnit.MICROS), - result)); - } - nonEvacuatedEnergyStatusRepository.save(toStatusEntity(resultUuid, status.name())); - } - - @Transactional - @Override - public void delete(UUID resultUuid) { - Objects.requireNonNull(resultUuid); - nonEvacuatedEnergyStatusRepository.deleteByResultUuid(resultUuid); - nonEvacuatedEnergyResultRepository.deleteByResultUuid(resultUuid); - } - - @Transactional - @Override - public void deleteAll() { - nonEvacuatedEnergyStatusRepository.deleteAll(); - nonEvacuatedEnergyResultRepository.deleteAll(); - } - - @Transactional(readOnly = true) - @Override - public NonEvacuatedEnergyStatus findStatus(UUID resultUuid) { - Objects.requireNonNull(resultUuid); - NonEvacuatedEnergyGlobalStatusEntity globalEntity = nonEvacuatedEnergyStatusRepository.findByResultUuid(resultUuid); - if (globalEntity != null) { - return NonEvacuatedEnergyStatus.valueOf(globalEntity.getStatus()); - } else { - return null; - } - } - - @Transactional(readOnly = true) - public String getRunResult(UUID resultUuid) { - NonEvacuatedEnergyResultEntity resultEntity = nonEvacuatedEnergyResultRepository.findByResultUuid(resultUuid); - if (resultEntity == null) { - return null; - } - return resultEntity.getResult(); - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyRunContext.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyRunContext.java deleted file mode 100644 index 23265f73..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyRunContext.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import lombok.Getter; -import org.gridsuite.computation.service.AbstractComputationRunContext; -import org.gridsuite.computation.dto.ReportInfos; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyInputData; - -import java.util.UUID; - -/** - * @author Franck Lecuyer - */ -@Getter -public class NonEvacuatedEnergyRunContext extends AbstractComputationRunContext { - - private final NonEvacuatedEnergyInputs nonEvacuatedEnergyInputs; - - public NonEvacuatedEnergyRunContext(UUID networkUuid, - String variantId, - NonEvacuatedEnergyInputData nonEvacuatedEnergyInputData, - String receiver, - String provider, - ReportInfos reportInfos, - String userId) { - super(networkUuid, - variantId, - receiver, - reportInfos != null ? reportInfos : new ReportInfos(null, null, null), - userId, - provider, - nonEvacuatedEnergyInputData); - this.nonEvacuatedEnergyInputs = new NonEvacuatedEnergyInputs(); - } - - public NonEvacuatedEnergyInputData getNonEvacuatedEnergyInputData() { - return getParameters(); - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyService.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyService.java deleted file mode 100644 index 38dda379..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyService.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.gridsuite.computation.service.AbstractComputationService; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyStatus; -import org.gridsuite.computation.service.UuidGeneratorService; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.UUID; - -/** - * @author Franck Lecuyer - */ -@Service -public class NonEvacuatedEnergyService extends AbstractComputationService { - - public NonEvacuatedEnergyService(@Value("${non-evacuated-energy.default-provider}") String defaultProvider, - NonEvacuatedEnergyResultService resultService, - UuidGeneratorService uuidGeneratorService, - NonEvacuatedNotificationService notificationService, - ObjectMapper objectMapper) { - super(notificationService, resultService, objectMapper, uuidGeneratorService, defaultProvider); - } - - @Override - public List getProviders() { - return Collections.singletonList(getDefaultProvider()); - } - - @Override - public UUID runAndSaveResult(NonEvacuatedEnergyRunContext nonEvacuatedEnergyRunContext) { - Objects.requireNonNull(nonEvacuatedEnergyRunContext); - - var resultUuid = uuidGeneratorService.generate(); - // update status to running status - setStatus(List.of(resultUuid), NonEvacuatedEnergyStatus.RUNNING); - notificationService.sendRunMessage(new NonEvacuatedEnergyResultContext(resultUuid, nonEvacuatedEnergyRunContext).toMessage(objectMapper)); - return resultUuid; - } - - public String getRunResult(UUID resultUuid) { - return resultService.getRunResult(resultUuid); - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyWorkerService.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyWorkerService.java deleted file mode 100644 index 5ff2d0f4..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedEnergyWorkerService.java +++ /dev/null @@ -1,857 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import com.google.common.util.concurrent.AtomicDouble; -import com.powsybl.commons.PowsyblException; -import com.powsybl.commons.extensions.Extension; -import com.powsybl.commons.report.ReportNode; -import com.powsybl.commons.report.TypedValue; -import com.powsybl.computation.ComputationManager; -import com.powsybl.iidm.network.*; -import com.powsybl.loadflow.LoadFlowParameters; -import com.powsybl.loadflow.LoadFlowProvider; -import com.powsybl.network.store.client.NetworkStoreService; -import com.powsybl.sensitivity.*; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.gridsuite.computation.service.AbstractResultContext; -import org.gridsuite.computation.service.AbstractWorkerService; -import org.gridsuite.sensitivityanalysis.server.dto.IdentifiableAttributes; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyInputData; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyStageDefinition; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyStagesSelection; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.NonEvacuatedEnergyStatus; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.results.*; -import org.gridsuite.computation.service.ReportService; -import org.gridsuite.computation.service.ExecutionService; -import org.gridsuite.sensitivityanalysis.server.util.SensitivityAnalysisRunnerSupplier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.messaging.Message; -import org.springframework.stereotype.Service; - -import java.io.IOException; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; -import java.util.function.Function; - -import static java.lang.Math.abs; -import static java.util.stream.Collectors.toMap; - -/** - * @author Franck Lecuyer - */ -@Service -public class NonEvacuatedEnergyWorkerService extends AbstractWorkerService { - private static final Logger LOGGER = LoggerFactory.getLogger(NonEvacuatedEnergyWorkerService.class); - public static final String COMPUTATION_TYPE = "Non Evacuated Energy Sensitivity analysis"; - - private final NonEvacuatedEnergyInputBuilderService nonEvacuatedEnergyInputBuilderService; - - private Function sensitivityAnalysisFactorySupplier; - - private static final double EPSILON = 0.0001; - - private static final int MAX_ITERATION_IN_STAGE = 4; - - private static final double EPSILON_MAX_VARIATION = 0.3; - - // to serialize null key in results by contingency HashMap as "" (for pre-contingency results) - static class NullKeySerializer extends StdSerializer { - public NullKeySerializer() { - this(null); - } - - public NullKeySerializer(Class t) { - super(t); - } - - @Override - public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException { - jsonGenerator.writeFieldName(""); - } - } - - public NonEvacuatedEnergyWorkerService(NetworkStoreService networkStoreService, ReportService reportService, - NonEvacuatedNotificationService notificationService, - NonEvacuatedEnergyInputBuilderService nonEvacuatedEnergyInputBuilderService, - ExecutionService executionService, - NonEvacuatedEnergyResultService resultService, ObjectMapper objectMapper, - SensitivityAnalysisRunnerSupplier sensitivityAnalysisRunnerSupplier, - NonEvacuatedEnergyObserver observer) { - super(networkStoreService, notificationService, reportService, resultService, executionService, observer, objectMapper); - this.nonEvacuatedEnergyInputBuilderService = nonEvacuatedEnergyInputBuilderService; - this.objectMapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer()); - sensitivityAnalysisFactorySupplier = sensitivityAnalysisRunnerSupplier::getRunner; - } - - public void setSensitivityAnalysisFactorySupplier(Function sensitivityAnalysisFactorySupplier) { - this.sensitivityAnalysisFactorySupplier = Objects.requireNonNull(sensitivityAnalysisFactorySupplier); - } - - private static SensitivityAnalysisParameters buildParameters(NonEvacuatedEnergyRunContext context) { - SensitivityAnalysisParameters params = context.getNonEvacuatedEnergyInputData().getParameters() == null ? - new SensitivityAnalysisParameters() : context.getNonEvacuatedEnergyInputData().getParameters(); - - // set the flowFlowThreshold value - params.setFlowFlowSensitivityValueThreshold(context.getNonEvacuatedEnergyInputData().getNonEvacuatedEnergyGeneratorsCappings().getSensitivityThreshold()); - - if (context.getNonEvacuatedEnergyInputData().getLoadFlowSpecificParameters() == null - || context.getNonEvacuatedEnergyInputData().getLoadFlowSpecificParameters().isEmpty()) { - return params; // no specific LF params - } - LoadFlowProvider lfProvider = LoadFlowProvider.findAll().stream() - .filter(p -> p.getName().equals(context.getProvider())) - .findFirst().orElseThrow(() -> new PowsyblException("Load flow provider not found " + context.getProvider())); - Extension extension = lfProvider.loadSpecificParameters(context.getNonEvacuatedEnergyInputData().getLoadFlowSpecificParameters()) - .orElseThrow(() -> new PowsyblException("Cannot add specific loadflow parameters with sensitivity analysis provider " + context.getProvider())); - params.getLoadFlowParameters().addExtension((Class) extension.getClass(), extension); - return params; - } - - private void cloneNetworkVariant(Network network, String originVariantId, String destinationVariantId) { - String startingVariant = StringUtils.isBlank(originVariantId) ? VariantManagerConstants.INITIAL_VARIANT_ID : originVariantId; - try { - network.getVariantManager().cloneVariant(startingVariant, destinationVariantId, true); // cloning variant - network.getVariantManager().setWorkingVariant(destinationVariantId); // set current variant to destination variant - } catch (PowsyblException e) { - throw new PowsyblException("Variant '" + startingVariant + "' not found !!"); - } - } - - private void applyStage(Network network, - NonEvacuatedEnergyStagesSelection stageSelection, - NonEvacuatedEnergyRunContext context, - ReportNode reporter) { - // loop on each energy source in the stage input data - for (int i = 0; i < stageSelection.getStagesDefinitionIndex().size(); ++i) { - int stageDefinitionIndex = stageSelection.getStagesDefinitionIndex().get(i); - NonEvacuatedEnergyStageDefinition stageDefinition = context.getNonEvacuatedEnergyInputData().getNonEvacuatedEnergyStagesDefinition().get(stageDefinitionIndex); - float pMaxPercent = stageDefinition.getPMaxPercents().get(stageSelection.getPMaxPercentsIndex().get(i)); - - stageDefinition.getGenerators().stream() - .flatMap(generatorFilter -> nonEvacuatedEnergyInputBuilderService.getIdentifiablesFromContainer(context.getNetworkUuid(), context.getVariantId(), generatorFilter, List.of(IdentifiableType.GENERATOR), reporter)) - .map(IdentifiableAttributes::getId) - .map(network::getGenerator) - .filter(Objects::nonNull) - .forEach(generator -> { - double oldTargetP = generator.getTargetP(); - double newTargetP = (generator.getMaxP() * pMaxPercent) / 100; - generator.setTargetP(newTargetP); - reporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.ApplyStageGeneratorTargetP") - .withSeverity(TypedValue.TRACE_SEVERITY) - .withUntypedValue("generatorId", generator.getId()) - .withUntypedValue("oldTargetP", oldTargetP) - .withUntypedValue("newTargetP", newTargetP) - .add(); - }); - } - } - - private LimitInfos getLimitInfos(SensitivityFactor factor, boolean isIst, Float coeff, String limitName, - Optional currentLimits1, Optional currentLimits2) { - String name = null; - double value = Double.NaN; - TwoSides side = TwoSides.ONE; - - if (isIst) { - name = "IST"; - if (factor.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - value = currentLimits1.map(l -> l.getPermanentLimit() * coeff / 100).orElse(Double.NaN); - } else if (factor.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_2) { - value = currentLimits2.map(l -> l.getPermanentLimit() * coeff / 100).orElse(Double.NaN); - side = TwoSides.TWO; - } - } else if (!StringUtils.isEmpty(limitName)) { - name = limitName; - if (factor.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - Optional limit = currentLimits1.flatMap(currentLimits -> currentLimits.getTemporaryLimits().stream().filter(l -> l.getName().equals(limitName)).findFirst()); - value = limit.map(temporaryLimit -> temporaryLimit.getValue() * coeff / 100).orElse(Double.NaN); - } else if (factor.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_2) { - Optional limit = currentLimits2.flatMap(currentLimits -> currentLimits.getTemporaryLimits().stream().filter(l -> l.getName().equals(limitName)).findFirst()); - value = limit.map(temporaryLimit -> temporaryLimit.getValue() * coeff / 100).orElse(Double.NaN); - side = TwoSides.TWO; - } - } - return new LimitInfos(name, value, side); - } - - private LimitInfos getLimitValueFromFactorAndSensitivityValue(SensitivityValue sensitivityValue, - SensitivityFactor factor, - MonitoredBranchThreshold monitoredBranchThreshold, - MonitoredBranchDetailResult monitoredBranchDetailResult) { - int contingencyIndex = sensitivityValue.getContingencyIndex(); - - Branch branch = monitoredBranchThreshold.getBranch(); - Optional currentLimits1 = branch.getCurrentLimits1(); - Optional currentLimits2 = branch.getCurrentLimits2(); - - // use contingencyIndex (-1 or not) to check istN/Nlimitname or istNm1/Nm1Limitname - // limits in iidm are in A, so consider only SensitivityFunctionType BRANCH_CURRENT to return - // the limit value multiplied by the input coefficient (nCoeff/nm1Coeff) - LimitInfos limitInfos; - if (contingencyIndex < 0) { // N - limitInfos = getLimitInfos(factor, monitoredBranchThreshold.isIstN(), monitoredBranchThreshold.getNCoeff(), monitoredBranchThreshold.getNLimitName(), currentLimits1, currentLimits2); - } else { // N-1 - limitInfos = getLimitInfos(factor, monitoredBranchThreshold.isIstNm1(), monitoredBranchThreshold.getNm1Coeff(), monitoredBranchThreshold.getNm1LimitName(), currentLimits1, currentLimits2); - } - - // update monitored branch detail result - if (!Double.isNaN(limitInfos.getValue())) { // sensitivity in A/MW - monitoredBranchDetailResult.setIntensity(sensitivityValue.getFunctionReference()); - monitoredBranchDetailResult.setLimitName(limitInfos.getName()); - monitoredBranchDetailResult.setLimitValue(limitInfos.getValue()); - monitoredBranchDetailResult.setPercentOverload((sensitivityValue.getFunctionReference() / limitInfos.getValue()) * 100.); - } - - // limit value is set only for sensitivity in A/MW : it will be NaN for sensitivity in MW/MW - return limitInfos; - } - - private double computeVariationForMonitoredBranch(Network network, - NonEvacuatedEnergyInputs nonEvacuatedEnergyInputs, - SensitivityFactor factor, - MonitoredBranchThreshold monitoredBranchThreshold, - String contingencyId, - Map generatorsSensitivities, - SensitivityValue sensitivityValue, - Map generatorCappings, - MonitoredBranchDetailResult monitoredBranchDetailResult, - ReportNode reporter) { - double injectionVariation = Double.NaN; - double functionReference = sensitivityValue.getFunctionReference(); - - // get the limit value (in A) to consider from the monitored branch limits, using the factor function type and the monitored branch thresholds parameters - LimitInfos limitInfos = getLimitValueFromFactorAndSensitivityValue(sensitivityValue, factor, monitoredBranchThreshold, monitoredBranchDetailResult); - - if (!Double.isNaN(limitInfos.getValue())) { - String contingencyStr = contingencyId != null ? ("Contingency " + contingencyId) : "N"; - reporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.MonitoredBranchLimitValueToConsider") - .withSeverity(TypedValue.TRACE_SEVERITY) - .withUntypedValue("contingency", contingencyStr) - .withUntypedValue("limitName", limitInfos.getName()) - .withUntypedValue("side", limitInfos.getSide().name()) - .withUntypedValue("branchId", monitoredBranchThreshold.getBranch().getId()) - .withUntypedValue("limitValue", limitInfos.getValue()) - .withUntypedValue("intensity", functionReference) - .add(); - - // compare the functionReference (monitored branch intensity in A) to the limit value (in A) - double delta = limitInfos.getValue() - functionReference; - if (delta < 0) { - reporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.MonitoredBranchConstraintDeltaFound") - .withSeverity(TypedValue.TRACE_SEVERITY) - .withUntypedValue("branchId", monitoredBranchThreshold.getBranch().getId()) - .withUntypedValue("delta", Math.abs(delta)) - .add(); - - // monitored branch is over the limit : - // we compute the generators cappings needed to set the monitored branch under the limit - injectionVariation = computeInjectionVariationForMonitoredBranch(network, nonEvacuatedEnergyInputs, generatorsSensitivities, delta, generatorCappings, monitoredBranchDetailResult); - - reporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.GeneratorsVariationForMonitoredBranch") - .withSeverity(TypedValue.TRACE_SEVERITY) - .withUntypedValue("branchId", monitoredBranchThreshold.getBranch().getId()) - .withUntypedValue("variation", injectionVariation) - .add(); - } else { - reporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.MonitoredBranchNoConstraint") - .withSeverity(TypedValue.TRACE_SEVERITY) - .withUntypedValue("branchId", monitoredBranchThreshold.getBranch().getId()) - .add(); - } - } - - return injectionVariation; - } - - private Map getSensitivityCoeffs(Map sensitivities) { - Double referenceSensitivity = 1.; - Map sensitivityCoeff = new HashMap<>(); - int i = 0; - String referenceGroupId; - - for (Map.Entry entry : sensitivities.entrySet()) { - if (i == 0) { // generator with the most impact is the reference generator : define a sensitivity coefficient of 1 - referenceGroupId = entry.getKey(); - sensitivityCoeff.put(referenceGroupId, 1.); - referenceSensitivity = entry.getValue(); - i++; - } else { // other generator : compute sensitivity coefficient from sensitivity value and reference generator sensitivity value - sensitivityCoeff.put(entry.getKey(), entry.getValue() / referenceSensitivity); - } - } - return sensitivityCoeff; - } - - private double computeInjectionVariationForMonitoredBranch(Network network, - NonEvacuatedEnergyInputs nonEvacuatedEnergyInputs, - Map generatorsSensitivities, - double delta, - Map generatorCappings, - MonitoredBranchDetailResult monitoredBranchDetailResult) { - // sort the map in reverse order to get first the generator which have the most impact - LinkedHashMap sensitivities = generatorsSensitivities.entrySet() - .stream() - .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); - - // define sensitivity coefficient for each generator - Map sensitivityCoeff = getSensitivityCoeffs(sensitivities); - - // compute the generators cappings needed to set the monitored branch under the limit - Map variationsByEnergySource = new EnumMap<>(EnergySource.class); - double injectionVariation = computeInjectionVariationFromGeneratorsSensitivities(network, nonEvacuatedEnergyInputs, sensitivities, sensitivityCoeff, delta, variationsByEnergySource, generatorCappings); - - // update sensitivities by energy source in monitored branch result - Map sensitivitiesByEnergySource = new EnumMap<>(EnergySource.class); - sensitivities.forEach((key, value) -> { - Generator generator = network.getGenerator(key); - if (generator != null) { - if (!sensitivitiesByEnergySource.containsKey(generator.getEnergySource())) { - sensitivitiesByEnergySource.put(generator.getEnergySource(), value); - } else { - sensitivitiesByEnergySource.put(generator.getEnergySource(), sensitivitiesByEnergySource.get(generator.getEnergySource()) + value); - } - } - }); - monitoredBranchDetailResult.getSensitivityByEnergySource().putAll(sensitivitiesByEnergySource); - - return injectionVariation; - } - - private double computeInjectionVariationFromGeneratorsSensitivities(Network network, - NonEvacuatedEnergyInputs nonEvacuatedEnergyInputs, - Map generatorsSensitivities, - Map sensitivitiesCoefficients, - double delta, - Map variationsByEnergySource, - Map generatorCappings) { - double injectionVariation = 0; - - // compute the coefficient sum - double coeffSum = 0; - for (Map.Entry entry : generatorsSensitivities.entrySet()) { - coeffSum += entry.getValue() * sensitivitiesCoefficients.get(entry.getKey()); - } - double referenceGeneratorVariation = abs(delta / coeffSum); - - // for each generator, we try to limit his power - double remaining = 0; - List generatorsToDispatch = new ArrayList<>(); - - // compute the variation to do for each generator - for (Map.Entry entry : sensitivitiesCoefficients.entrySet()) { - String generatorId = entry.getKey(); - Generator generator = network.getGenerator(generatorId); - double sensitivityCoefficent = entry.getValue(); - double generatorVariation = sensitivityCoefficent * referenceGeneratorVariation; - double targetP = generator.getTargetP(); - - if (generatorVariation > targetP) { - // the generator variation is higher than the generator targetP : - // we cap the generator variation to the targetP and this generator will no more be considered in the further dispatching process - // we add the delta between the generation variation and the generator targetP the remaining - remaining += generatorVariation - targetP; - generatorVariation = targetP; - } else { - // variation is lower than generator targetP : - // we keep this generator for the further dispatching process - generatorsToDispatch.add(generator); - } - injectionVariation += sensitivityCoefficent * referenceGeneratorVariation; - GeneratorCapping generatorCapping = new GeneratorCapping(); - generatorCapping.setGeneratorId(generatorId); - generatorCapping.setEnergySource(generator.getEnergySource()); - generatorCapping.setPInit(nonEvacuatedEnergyInputs.getGeneratorsPInit().get(generatorId)); - generatorCapping.setCapping(generatorVariation); - generatorCapping.setCumulatedCapping(0.); - generatorCappings.put(generatorId, generatorCapping); - variationsByEnergySource.put(generator.getEnergySource(), generatorVariation); - } - - // there is a remaining, and we still have generators to dispatch - if (remaining >= EPSILON && !generatorsToDispatch.isEmpty()) { - int i = 0; - - // loop until no more remaining or no more generators to dispatch or max iteration reached - while (remaining >= EPSILON && !generatorsToDispatch.isEmpty() && i <= 10) { - i++; - int j = 0; - String referenceGeneratorId = ""; - Map sensitivityCoefficientRemaining = new HashMap<>(); - - // recomputing the remaining sensitivity coefficients for each generator to dispatch - coeffSum = 0; - for (Generator generator : generatorsToDispatch) { - String generatorId = generator.getId(); - if (j == 0) { - // first generator is the new reference generator and will have a coefficient of 1 - referenceGeneratorId = generatorId; - sensitivityCoefficientRemaining.put(referenceGeneratorId, 1.); - j++; - } else { - // other generator : compute sensitivity remaining coefficient from sensitivity value and reference generator sensitivity value - sensitivityCoefficientRemaining.put(generatorId, generatorsSensitivities.get(generatorId) / generatorsSensitivities.get(referenceGeneratorId)); - } - coeffSum += sensitivityCoefficientRemaining.get(generatorId); - } - - if (coeffSum != 0) { - referenceGeneratorVariation = abs(remaining / coeffSum); - - // for each generator to dispatch, we try to limit his power - ListIterator iterator = generatorsToDispatch.listIterator(); - while (iterator.hasNext()) { - Generator generator = iterator.next(); - String generatorId = generator.getId(); - double generatorVariation = sensitivityCoefficientRemaining.get(generatorId) * referenceGeneratorVariation; - double targetP = generator.getTargetP(); - - if (generatorVariation + generatorCappings.get(generatorId).getCapping() > targetP) { - // the sum of generator variation and generator capping is higher than the generator targetP : - // we update the generator capping with the targetP and remove this generator from the generators to dispatch - // we substract the delta between the generator targetP and the generator capping from the remaining - variationsByEnergySource.put(generator.getEnergySource(), variationsByEnergySource.get(generator.getEnergySource()) + targetP - generatorCappings.get(generatorId).getCapping()); - generatorCappings.get(generatorId).setCapping(targetP); - remaining -= targetP - generatorCappings.get(generatorId).getCapping(); - iterator.remove(); - } else { - // the sum of generator variation and generator capping is lower than generator targetP : - // we keep this generator for the further dispatching process - // we add the generator variation to the generator capping - // we substract the generator variation from the remaining - remaining -= generatorVariation; - variationsByEnergySource.put(generator.getEnergySource(), variationsByEnergySource.get(generator.getEnergySource()) + generatorVariation); - generatorCappings.get(generatorId).setCapping(generatorCappings.get(generatorId).getCapping() + generatorVariation); - } - } - } - } - } - - return injectionVariation; - } - - private Map collectSensitivitiesByBranches(SensitivityAnalysisResult sensiResult) { - Map sensitivitiesByBranches = new HashMap<>(); - for (SensitivityValue sensitivityValue : sensiResult.getValues()) { - int factorIndex = sensitivityValue.getFactorIndex(); - SensitivityFactor factor = sensiResult.getFactors().get(factorIndex); - SensitivityFunctionType functionType = factor.getFunctionType(); - // Here, we consider from the results only function type current - if (functionType == SensitivityFunctionType.BRANCH_CURRENT_1 || functionType == SensitivityFunctionType.BRANCH_CURRENT_2) { - String functionId = factor.getFunctionId(); // the function id here is a branch id - String variableId = factor.getVariableId(); // the variable id here is a generator id - int contingencyIndex = sensitivityValue.getContingencyIndex(); - String contingencyId; - if (contingencyIndex >= 0) { // N-1 - contingencyId = factor.getContingencyContext().getContingencyId(); - } else { - contingencyId = null; // N - } - - SensitivitiesByBranch branchContingencies = sensitivitiesByBranches.computeIfAbsent(functionId, k -> new SensitivitiesByBranch(functionId, new HashMap<>())); - Map generatorsSensitivities = branchContingencies.getSensitivitiesByContingency().computeIfAbsent(contingencyId, k -> new HashMap<>()); - generatorsSensitivities.put(variableId, sensitivityValue.getValue()); - } - } - return sensitivitiesByBranches; - } - - private void updateMonitoredBranchResultWithCappingsInfos(Network network, Map generatorCappings, - MonitoredBranchDetailResult monitoredBranchDetailResult) { - Map cappingsByEnergySource = new EnumMap<>(EnergySource.class); - for (Map.Entry entry : generatorCappings.entrySet()) { - Generator generator = network.getGenerator(entry.getKey()); - GeneratorCapping capping = !monitoredBranchDetailResult.getGeneratorsCapping().containsKey(entry.getKey()) - ? entry.getValue() : monitoredBranchDetailResult.getGeneratorsCapping().get(entry.getKey()); - capping.setCumulatedCapping(capping.getCumulatedCapping() + entry.getValue().getCapping()); - monitoredBranchDetailResult.getGeneratorsCapping().put(entry.getKey(), capping); - cappingsByEnergySource.putIfAbsent(generator.getEnergySource(), 0.); - cappingsByEnergySource.put(generator.getEnergySource(), cappingsByEnergySource.get(generator.getEnergySource()) + capping.getCumulatedCapping()); - } - monitoredBranchDetailResult.getCappingByEnergySource().putAll(cappingsByEnergySource); - monitoredBranchDetailResult.setOverallCapping(cappingsByEnergySource.values().stream().mapToDouble(d -> d).sum()); - } - - private Pair computeMaxVariationForAllMonitoredBranches(Network network, - NonEvacuatedEnergyInputs nonEvacuatedEnergyInputs, - SensitivityAnalysisResult sensiResult, - Map> mapEncounteredBranchesByContingency, - Map sensitivitiesByBranches, - StageDetailResult stageDetailResult, - Map maxGeneratorsCappings, - ReportNode reporter) { - double maxVariationForMonitoredBranch = -Double.MAX_VALUE; - String maxMonitoredBranchId = null; - - for (SensitivityValue sensitivityValue : sensiResult.getValues()) { - int factorIndex = sensitivityValue.getFactorIndex(); - SensitivityFactor factor = sensiResult.getFactors().get(factorIndex); - String functionId = factor.getFunctionId(); // the function id here is a branch id - int contingencyIndex = sensitivityValue.getContingencyIndex(); - String contingencyId = null; // N - if (contingencyIndex >= 0) { // N-1 - contingencyId = factor.getContingencyContext().getContingencyId(); - } - - Map mapEncounteredBranches = mapEncounteredBranchesByContingency.computeIfAbsent(contingencyId, k -> new HashMap<>()); - mapEncounteredBranches.putIfAbsent(functionId, Boolean.FALSE); - - // create or get result associated with the contingency in the stage detail result - ContingencyStageDetailResult contingencyStageDetailResult = stageDetailResult.getResultsByContingency().computeIfAbsent(contingencyId, k -> new ContingencyStageDetailResult()); - - // get monitored branch thresholds information from monitored branch id - MonitoredBranchThreshold monitoredBranchThreshold = nonEvacuatedEnergyInputs.getBranchesThresholds().get(functionId); - if (monitoredBranchThreshold != null) { - // create or get result associated to the monitored branch - MonitoredBranchDetailResult monitoredBranchDetailResult = contingencyStageDetailResult.getResultsByMonitoredBranch().computeIfAbsent(functionId, k -> new MonitoredBranchDetailResult()); - - if (factor.isVariableSet()) { - monitoredBranchDetailResult.setP(sensitivityValue.getFunctionReference()); - } - - if (Boolean.FALSE.equals(mapEncounteredBranches.get(functionId))) { // not already handled - // compute the variation for the monitored branch - SensitivitiesByBranch sensitivitiesByBranch = sensitivitiesByBranches.get(functionId); - Map generatorsSensitivities = sensitivitiesByBranch.getSensitivitiesByContingency().get(contingencyId); - Map generatorCappings = new HashMap<>(); - double variation = computeVariationForMonitoredBranch(network, nonEvacuatedEnergyInputs, factor, monitoredBranchThreshold, - contingencyId, generatorsSensitivities, sensitivityValue, generatorCappings, monitoredBranchDetailResult, reporter); - - // update monitored branch result with the cappings information - updateMonitoredBranchResultWithCappingsInfos(network, generatorCappings, monitoredBranchDetailResult); - - // keeping only the max computed variation - if (!Double.isNaN(variation) && maxVariationForMonitoredBranch < variation) { - maxVariationForMonitoredBranch = variation; - maxMonitoredBranchId = monitoredBranchThreshold.getBranch().getId(); - maxGeneratorsCappings.putAll(generatorCappings.entrySet().stream().collect(toMap(Map.Entry::getKey, e -> e.getValue().getCapping()))); - } - mapEncounteredBranches.put(functionId, Boolean.TRUE); - } - } - } - return Pair.of(maxMonitoredBranchId, maxVariationForMonitoredBranch); - } - - private boolean analyzeSensitivityResults(Network network, - NonEvacuatedEnergyInputs nonEvacuatedEnergyInputs, - SensitivityAnalysisResult sensiResult, - Map generatorsCappings, - StageDetailResult stageDetailResult, - ReportNode reporter) { - AtomicBoolean noMoreLimitViolation = new AtomicBoolean(true); - - Map maxGeneratorsCappings = new HashMap<>(); - - // collect, for each branch and then for each contingency, the sensitivity values for all generators who have an impact on the monitored branch - Map sensitivitiesByBranches = collectSensitivitiesByBranches(sensiResult); - - // loop on all sensitivity result values of the sensitivity analysis computation - // each sensitivity value will contain a sensitivity factor, a contingency and the delta and reference value for a monitored branch - Map> mapEncounteredBranchesByContingency = new HashMap<>(); - - Pair maxVariationForMonitoredBranch = computeMaxVariationForAllMonitoredBranches(network, nonEvacuatedEnergyInputs, - sensiResult, mapEncounteredBranchesByContingency, sensitivitiesByBranches, - stageDetailResult, maxGeneratorsCappings, reporter); - - if (maxVariationForMonitoredBranch.getValue() < EPSILON_MAX_VARIATION) { - // the max variation for all monitored branches is small : - // there is no limit violation detected and no further sensitivity analysis computation will be done for the current stage - noMoreLimitViolation.set(true); - } else { - // the max variation for all monitored branches is not small : - // there is a limit violation detected and a further sensitivity analysis computation will be done for the current stage, except if max iteration is reached - // we memorize the generators cappings needed to eliminate this limit violation - reporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.MaxVariationForMonitoredBranchToConsider") - .withSeverity(TypedValue.TRACE_SEVERITY) - .withUntypedValue("branchId", maxVariationForMonitoredBranch.getKey()) - .add(); - - generatorsCappings.putAll(maxGeneratorsCappings); - noMoreLimitViolation.set(false); - } - - return noMoreLimitViolation.get(); - } - - private void applyGeneratorsCappings(Network network, Map generatorsCappings, ReportNode reporter) { - for (Map.Entry g : generatorsCappings.entrySet()) { - Generator generator = network.getGenerator(g.getKey()); - if (generator != null) { - // we use the capping value to reduce the generator targetP - double oldTargetP = generator.getTargetP(); - double cappingValue = g.getValue(); - double newTargetP = generator.getTargetP() - cappingValue; - generator.setTargetP(newTargetP); - reporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.ApplyGeneratorCapping") - .withSeverity(TypedValue.TRACE_SEVERITY) - .withUntypedValue("generatorId", generator.getId()) - .withUntypedValue("oldTargetP", oldTargetP) - .withUntypedValue("cappingValue", cappingValue) - .withUntypedValue("newTargetP", newTargetP) - .add(); - } - } - } - - private void buildSummaryMonitoredBranchResults(Map.Entry monitoredBranchResultEntry, - Double pInitTotal, - String contingencyName, - StageSummaryResult stageSummaryResult, - StageSummaryContingencyResult stageSummaryContingencyResult) { - String monitoredBranchId = monitoredBranchResultEntry.getKey(); - MonitoredBranchDetailResult monitoredBranchDetailResult = monitoredBranchResultEntry.getValue(); - - Double deltaPEchTotal = monitoredBranchDetailResult.getCappingByEnergySource().values().stream().mapToDouble(d -> d).sum(); - if (deltaPEchTotal > stageSummaryContingencyResult.getPLim()) { - stageSummaryContingencyResult.setLimitViolated(true); - stageSummaryContingencyResult.setPLim(pInitTotal - deltaPEchTotal); - stageSummaryContingencyResult.setPercentOverload(monitoredBranchDetailResult.getPercentOverload()); - stageSummaryContingencyResult.setMonitoredEquipmentWithMaxLimit(monitoredBranchId); - stageSummaryContingencyResult.setMonitoredEquipmentPower(monitoredBranchDetailResult.getP()); - stageSummaryContingencyResult.setCapping(monitoredBranchDetailResult.getOverallCapping()); - } - - Double pLim = contingencyName == null ? stageSummaryResult.getPLimN() : stageSummaryResult.getPLimNm1(); - if (deltaPEchTotal > pLim) { - stageSummaryResult.setPLimMonitoredEquipment(monitoredBranchId); - stageSummaryResult.setContingencyId(contingencyName); - stageSummaryResult.setPLimLimit(monitoredBranchDetailResult.getLimitName()); - stageSummaryResult.setPercentOverload(monitoredBranchDetailResult.getPercentOverload()); - stageSummaryResult.setPLimN(deltaPEchTotal); - } - } - - private void buildSummaryContingencyResults(Map.Entry contingencyResultEntry, - Double pInitTotal, - StageSummaryResult stageSummaryResult) { - String contingencyName = contingencyResultEntry.getKey(); // null if N - ContingencyStageDetailResult contingencyResult = contingencyResultEntry.getValue(); - - StageSummaryContingencyResult stageSummaryContingencyResult = new StageSummaryContingencyResult(); - stageSummaryContingencyResult.setLimitViolated(false); - stageSummaryContingencyResult.setPLim(0.); - - // for each monitored branch in contingency result - contingencyResult.getResultsByMonitoredBranch().entrySet().forEach(entry -> buildSummaryMonitoredBranchResults(entry, pInitTotal, contingencyName, stageSummaryResult, stageSummaryContingencyResult)); - - stageSummaryResult.getResultsByContingency().put(contingencyName, stageSummaryContingencyResult); - } - - private void buildSummaryStageResults(NonEvacuatedEnergyResults nonEvacuatedEnergyResults, - Map.Entry stageResultEntry) { - String stageName = stageResultEntry.getKey(); - StageDetailResult stageDetailResult = stageResultEntry.getValue(); - - StageSummaryResult stageSummaryResult = new StageSummaryResult(); - stageSummaryResult.setPLimN(0.); - stageSummaryResult.setPLimNm1(0.); - - nonEvacuatedEnergyResults.getStagesSummary().put(stageName, stageSummaryResult); - stageSummaryResult.setPInitByEnergySource(stageDetailResult.getPInitByEnergySource()); - Double pInitTotal = stageDetailResult.getPInitByEnergySource().values().stream().mapToDouble(d -> d).sum(); - - // for each contingency results - stageDetailResult.getResultsByContingency().entrySet().forEach(entry -> buildSummaryContingencyResults(entry, pInitTotal, stageSummaryResult)); - } - - private void buildSummaryResults(NonEvacuatedEnergyResults nonEvacuatedEnergyResults) { - // for each stage detail result - nonEvacuatedEnergyResults.getStagesDetail().entrySet().forEach(entry -> buildSummaryStageResults(nonEvacuatedEnergyResults, entry)); - } - - private void computeCappingsGeneratorsInitialP(Network network, NonEvacuatedEnergyRunContext context) { - // memorize the initial targetP for the capping generators - // compute and memorize the initial overall targetP for the capping generators by energy source - context.getNonEvacuatedEnergyInputs().getGeneratorsPInit().clear(); - context.getNonEvacuatedEnergyInputs().getGeneratorsPInitByEnergySource().clear(); - - Map pInitByEnergySource = new EnumMap<>(EnergySource.class); - context.getNonEvacuatedEnergyInputs().getCappingsGenerators().forEach((key, value) -> value.forEach(generatorId -> { - Generator generator = network.getGenerator(generatorId); - if (generator != null) { - double targetP = generator.getTargetP(); - context.getNonEvacuatedEnergyInputs().getGeneratorsPInit().put(generatorId, targetP); - AtomicDouble sum = pInitByEnergySource.computeIfAbsent(generator.getEnergySource(), k -> new AtomicDouble(0)); - sum.addAndGet(generator.getTargetP()); - } - })); - pInitByEnergySource.forEach((key, value) -> context.getNonEvacuatedEnergyInputs().getGeneratorsPInitByEnergySource().put(key, value.get())); - } - - private NonEvacuatedEnergyResults run(NonEvacuatedEnergyRunContext context, - Network network, - SensitivityAnalysisParameters sensitivityAnalysisParameters, - SensitivityAnalysis.Runner sensitivityAnalysisRunner, - ComputationManager computationManager, - ReportNode reporter) { - // build the contingencies, variable sets and sensitivity factors used as input of the sensitivity analysis computation - nonEvacuatedEnergyInputBuilderService.build(context, network, reporter); - - List stages = context.getNonEvacuatedEnergyInputData().getNonEvacuatedEnergyStagesSelection(); - int stageIndex = 0; - - // create global result - NonEvacuatedEnergyResults nonEvacuatedEnergyResults = new NonEvacuatedEnergyResults(); - - // Loop on all generation stages - for (NonEvacuatedEnergyStagesSelection stageSelection : stages) { - ReportNode subReporter = reporter.newReportNode().withMessageTemplate("sensitivity.analysis.server.Stage") - .withUntypedValue("stageName", stageSelection.getName()) - .add(); - - if (!stageSelection.isActivated()) { // stage is not activated : we ignore it - continue; - } - - // create new network variant - String stageVariantId = context.getNetworkUuid() + "_stage_" + stageIndex++; - cloneNetworkVariant(network, context.getVariantId(), stageVariantId); - - try { - // create stage detail result - StageDetailResult stageDetailResult = new StageDetailResult(); - nonEvacuatedEnergyResults.getStagesDetail().put(stageSelection.getName(), stageDetailResult); - - // apply the generation stage before launching the sensitivity analysis - applyStage(network, stageSelection, context, subReporter); - - // compute the initial overall targetP for the capping generators by energy source - computeCappingsGeneratorsInitialP(network, context); - stageDetailResult.setPInitByEnergySource(context.getNonEvacuatedEnergyInputs().getGeneratorsPInitByEnergySource()); - - int iterationCount = 1; - boolean noMoreLimitViolation = true; - - // do sensitivity computation until no more limit violation detected on a monitored branch or max iteration reached - do { - // launch sensitivity analysis - CompletableFuture future = sensitivityAnalysisRunner.runAsync( - network, - stageVariantId, - context.getNonEvacuatedEnergyInputs().getFactors(), - context.getNonEvacuatedEnergyInputs().getContingencies(), - context.getNonEvacuatedEnergyInputs().getVariablesSets(), - sensitivityAnalysisParameters, - computationManager, - subReporter); - - SensitivityAnalysisResult sensiResult = future == null ? null : future.get(); - - // generators cappings needed to eliminate on eventually limit violation on a monitored branch - Map generatorsCappings = new HashMap<>(); - - ReportNode analyzeReporter = subReporter.newReportNode().withMessageTemplate("sensitivity.analysis.server.AnalyzingResults").add(); - - if (sensiResult != null) { - // analyze sensi results and generate the generators cappings - noMoreLimitViolation = analyzeSensitivityResults(network, context.getNonEvacuatedEnergyInputs(), sensiResult, generatorsCappings, stageDetailResult, analyzeReporter); - } - if (!noMoreLimitViolation) { // there is a limit violation on a monitored branch - // apply the generators cappings calculated just above to eliminate this limit violation - applyGeneratorsCappings(network, generatorsCappings, analyzeReporter); - } - - iterationCount++; - } while (iterationCount <= MAX_ITERATION_IN_STAGE && !noMoreLimitViolation); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (Exception e) { - String msg = e.getMessage(); - if (msg == null) { - msg = e.getClass().getName(); - } - subReporter.newReportNode() - .withMessageTemplate("sensitivity.analysis.server.sensitivityNonEvacuatedEnergyFailure") - .withSeverity(TypedValue.ERROR_SEVERITY) - .withUntypedValue("exception", msg) - .add(); - } finally { - // remove network variant - network.getVariantManager().removeVariant(stageVariantId); - } - } - - // Build the non evacuated energy stage summary results from all stage detail results calculated - buildSummaryResults(nonEvacuatedEnergyResults); - - return nonEvacuatedEnergyResults; - } - - @Override - protected CompletableFuture getCompletableFuture(NonEvacuatedEnergyRunContext runContext, String provider, UUID resultUuid) { - - SensitivityAnalysis.Runner sensitivityAnalysisRunner = sensitivityAnalysisFactorySupplier.apply(runContext.getProvider()); - - SensitivityAnalysisParameters sensitivityAnalysisParameters = buildParameters(runContext); - - if (sensitivityAnalysisParameters.getLoadFlowParameters().isDc()) { - // loadflow in dc mode not allowed - runContext.getReportNode().newReportNode() - .withMessageTemplate("sensitivity.analysis.server.NonEvacuatedEnergyLoadFlowDcNotAllowed") - .withSeverity(TypedValue.ERROR_SEVERITY) - .add(); - throw new PowsyblException("Loadflow in DC mode not allowed !!"); - } - - ComputationManager computationManager = executionService.getComputationManager(); - - return CompletableFuture.supplyAsync(() -> - run(runContext, runContext.getNetwork(), sensitivityAnalysisParameters, sensitivityAnalysisRunner, computationManager, runContext.getReportNode()) - ); - } - - @Override - protected String getComputationType() { - return COMPUTATION_TYPE; - } - - @Override - protected void saveResult(Network network, AbstractResultContext resultContext, NonEvacuatedEnergyResults result) { - String resultStr = null; - try { - resultStr = objectMapper.writeValueAsString(result); - } catch (JsonProcessingException e) { - LOGGER.error(e.toString()); - } - resultService.insert(resultContext.getResultUuid(), resultStr, NonEvacuatedEnergyStatus.COMPLETED); - } - - @Override - protected NonEvacuatedEnergyResultContext fromMessage(Message message) { - return NonEvacuatedEnergyResultContext.fromMessage(message, objectMapper); - } - - @Bean - public Consumer> consumeNonEvacuatedEnergyRun() { - return super.consumeRun(); - } - - @Bean - public Consumer> consumeNonEvacuatedEnergyCancel() { - return super.consumeCancel(); - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedNotificationService.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedNotificationService.java deleted file mode 100644 index 88a816d6..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/NonEvacuatedNotificationService.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) 2024, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import org.gridsuite.computation.service.NotificationService; -import org.springframework.cloud.stream.function.StreamBridge; -import org.springframework.stereotype.Service; - -/** - * @author Mathieu Deharbe - */ -@Service -public class NonEvacuatedNotificationService extends NotificationService { - public NonEvacuatedNotificationService(StreamBridge publisher) { - super(publisher, "publishNonEvacuatedEnergy"); - } -} diff --git a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/SensitivitiesByBranch.java b/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/SensitivitiesByBranch.java deleted file mode 100644 index 8d71a84f..00000000 --- a/src/main/java/org/gridsuite/sensitivityanalysis/server/service/nonevacuatedenergy/SensitivitiesByBranch.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2023, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Franck Lecuyer - */ -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -public class SensitivitiesByBranch { - private String branchId; - - Map> sensitivitiesByContingency = new HashMap<>(); -} diff --git a/src/main/resources/config/application.yaml b/src/main/resources/config/application.yaml index be8d3ec0..63b4d5ce 100644 --- a/src/main/resources/config/application.yaml +++ b/src/main/resources/config/application.yaml @@ -4,7 +4,7 @@ spring: cloud: function: - definition: consumeRun;consumeCancel;consumeNonEvacuatedEnergyRun;consumeNonEvacuatedEnergyCancel + definition: consumeRun;consumeCancel stream: bindings: consumeRun-in-0: @@ -26,25 +26,7 @@ spring: publishCancelFailed-out-0: destination: ${powsybl-ws.rabbitmq.destination.prefix:}sensitivityanalysis.cancelfailed - consumeNonEvacuatedEnergyRun-in-0: - destination: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.run - group: sensitivityanalysisGroup - consumer: - max-attempts: 1 - publishNonEvacuatedEnergyRun-out-0: - destination: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.run - publishNonEvacuatedEnergyResult-out-0: - destination: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.result - consumeNonEvacuatedEnergyCancel-in-0: - destination: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.cancel - publishNonEvacuatedEnergyCancel-out-0: - destination: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.cancel - publishNonEvacuatedEnergyStopped-out-0: - destination: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.stopped - publishNonEvacuatedEnergyCancelFailed-out-0: - destination: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.cancelfailed - - output-bindings: publishRun-out-0;publishResult-out-0;publishCancel-out-0;publishStopped-out-0;publishCancelFailed-out-0;publishNonEvacuatedEnergyRun-out-0;publishNonEvacuatedEnergyResult-out-0;publishNonEvacuatedEnergyCancel-out-0;publishNonEvacuatedEnergyStopped-out-0;publishNonEvacuatedEnergyCancelFailed-out-0 + output-bindings: publishRun-out-0;publishResult-out-0;publishCancel-out-0;publishStopped-out-0;publishCancelFailed-out-0 rabbit: bindings: consumeRun-in-0: @@ -56,15 +38,6 @@ spring: quorum: enabled: true delivery-limit: 2 - consumeNonEvacuatedEnergyRun-in-0: - consumer: - auto-bind-dlq: true - dead-letter-exchange: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.run.dlx - dead-letter-queue-name: ${powsybl-ws.rabbitmq.destination.prefix:}nonEvacuatedEnergy.run.dlx.dlq - dead-letter-exchange-type: topic - quorum: - enabled: true - delivery-limit: 2 jpa: properties: @@ -82,6 +55,3 @@ powsybl-ws: # default value for loadflow provider "OpenLoadFlow" sensitivity-analysis: default-provider: OpenLoadFlow - -non-evacuated-energy: - default-provider: OpenLoadFlow diff --git a/src/main/resources/db/changelog/changesets/changelog_20250926T134041Z.xml b/src/main/resources/db/changelog/changesets/changelog_20250926T134041Z.xml new file mode 100644 index 00000000..e1a46544 --- /dev/null +++ b/src/main/resources/db/changelog/changesets/changelog_20250926T134041Z.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml index cc4ea75a..a6ba23e5 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -33,4 +33,6 @@ databaseChangeLog: - include: file: changesets/changelog_20240527T155043Z.xml relativeToChangelogFile: true - + - include: + file: changesets/changelog_20250926T134041Z.xml + relativeToChangelogFile: true diff --git a/src/main/resources/org/gridsuite/sensitivityanalysis/server/reports.properties b/src/main/resources/org/gridsuite/sensitivityanalysis/server/reports.properties index 6cf77780..d69a9222 100644 --- a/src/main/resources/org/gridsuite/sensitivityanalysis/server/reports.properties +++ b/src/main/resources/org/gridsuite/sensitivityanalysis/server/reports.properties @@ -1,28 +1,10 @@ -sensitivity.analysis.server.AnalyzingResults = Analyzing results -sensitivity.analysis.server.ApplyGeneratorCapping = Capping generator ${generatorId} using capping value ${cappingValue} : targetP ${oldTargetP} --> ${newTargetP} -sensitivity.analysis.server.ApplyStageGeneratorTargetP = Generator ${generatorId} targetP modification : ${oldTargetP} --> ${newTargetP} -sensitivity.analysis.server.BadGeneratorEnergySource = Generator ${generatorId} is not of the required energy source : ${energySource} -sensitivity.analysis.server.GeneratorsVariationForMonitoredBranch = Generator variation found for monitored branch ${branchId} : ${variation} -sensitivity.analysis.server.MaxVariationForMonitoredBranchToConsider = The maximum variation has been found for monitored branch ${branchId} -sensitivity.analysis.server.MonitoredBranchConstraintDeltaFound = Constraint found for monitored branch ${branchId} : value of intensity to reduce = ${delta} -sensitivity.analysis.server.MonitoredBranchLimitValueToConsider = ${contingency} : ${limitName} limit value to consider on side ${side} for monitored branch ${branchId} = ${limitValue} to compare with I = ${intensity} -sensitivity.analysis.server.MonitoredBranchNoConstraint = No constraint found for monitored branch ${branchId} -sensitivity.analysis.server.NonEvacuatedEnergyInputParametersTranslationFailure = Failure while building inputs, exception : ${exception} -sensitivity.analysis.server.NonEvacuatedEnergyLoadFlowDcNotAllowed = Loadflow in DC mode not allowed !! -sensitivity.analysis.server.Stage = Stage (${stageName}) sensitivity.analysis.server.badEquipmentType = Equipments type in filter with name=${name} should be ${expectedType} : filter is ignored sensitivity.analysis.server.badMonitoredEquipmentType = Monitored equipments type in filter with name=${name} should be ${expectedType} : filter is ignored sensitivity.analysis.server.contingencyTranslationFailure = Could not get contingencies from contingencyListIdent ${name} : not found sensitivity.analysis.server.distributionTypeAllowedOnlyForManualContainer = Distribution type ${distributionType} is allowed only for manual filter : filter is ignored sensitivity.analysis.server.distributionTypeNotAllowedForLoadsContainer = Distribution type ${distributionType} is not allowed for loads filter : filter is ignored sensitivity.analysis.server.filterTranslationFailure = Could not get identifiables from filter ${name} : ${exception} -sensitivity.analysis.server.monitoredBranchNoCurrentLimits = No current limits for the monitored branch ${id} -sensitivity.analysis.server.monitoredBranchNoCurrentOrPermanentLimitsOnSide = No permanent limit for the monitored branch ${id} on side ${side} -sensitivity.analysis.server.monitoredBranchNoPermanentLimits = No permanent limits for the monitored branch ${id} -sensitivity.analysis.server.monitoredBranchNotFound = Could not find the monitored branch ${id} -sensitivity.analysis.server.monitoredBranchTemporaryLimitNotFound = Temporary limit ${limitName} not found for the monitored branch ${id} sensitivity.analysis.server.reportType = ${reportType} (${providerToUse}) sensitivity.analysis.server.rootReporterId = ${rootReporterId} sensitivity.analysis.server.sensitivityInputParametersTranslationFailure = Failure while building inputs, exception : ${exception} sensitivity.analysis.server.sensitivityNodesComputationNotSupported = Sensitivity nodes computation is only supported with OpenLoadFlow : computation ignored -sensitivity.analysis.server.sensitivityNonEvacuatedEnergyFailure = Failure while running non evacuated energy computation exception : ${exception} diff --git a/src/test/java/org/gridsuite/sensitivityanalysis/server/NonEvacuatedEnergyTest.java b/src/test/java/org/gridsuite/sensitivityanalysis/server/NonEvacuatedEnergyTest.java deleted file mode 100644 index 4cbfd5f7..00000000 --- a/src/test/java/org/gridsuite/sensitivityanalysis/server/NonEvacuatedEnergyTest.java +++ /dev/null @@ -1,841 +0,0 @@ -/** - * Copyright (c) 2022, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.sensitivityanalysis.server; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.io.ByteStreams; -import com.powsybl.commons.report.ReportNode; -import com.powsybl.computation.ComputationManager; -import com.powsybl.contingency.BranchContingency; -import com.powsybl.contingency.Contingency; -import com.powsybl.contingency.ContingencyContext; -import com.powsybl.iidm.network.EnergySource; -import com.powsybl.iidm.network.IdentifiableType; -import com.powsybl.iidm.network.Network; -import com.powsybl.iidm.network.VariantManagerConstants; -import com.powsybl.loadflow.LoadFlowParameters; -import com.powsybl.network.store.client.NetworkStoreService; -import com.powsybl.network.store.client.PreloadingStrategy; -import com.powsybl.sensitivity.*; -import org.gridsuite.computation.service.ReportService; -import org.gridsuite.computation.service.UuidGeneratorService; -import org.gridsuite.sensitivityanalysis.server.configuration.RestTemplateConfig; -import org.gridsuite.sensitivityanalysis.server.dto.ContingencyListExportResult; -import org.gridsuite.sensitivityanalysis.server.dto.EquipmentsContainer; -import org.gridsuite.sensitivityanalysis.server.dto.IdentifiableAttributes; -import org.gridsuite.sensitivityanalysis.server.dto.nonevacuatedenergy.*; -import org.gridsuite.sensitivityanalysis.server.dto.parameters.LoadFlowParametersValues; -import org.gridsuite.sensitivityanalysis.server.service.ActionsService; -import org.gridsuite.sensitivityanalysis.server.service.FilterService; -import org.gridsuite.sensitivityanalysis.server.service.LoadFlowService; -import org.gridsuite.sensitivityanalysis.server.service.nonevacuatedenergy.NonEvacuatedEnergyWorkerService; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.MockitoAnnotations; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.cloud.stream.binder.test.OutputDestination; -import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; -import org.springframework.http.MediaType; -import org.springframework.messaging.Message; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.ContextHierarchy; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static com.powsybl.network.store.model.NetworkStoreApi.VERSION; -import static org.gridsuite.computation.service.NotificationService.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * @author Franck Lecuyer - */ -@AutoConfigureMockMvc -@SpringBootTest -@ContextHierarchy({@ContextConfiguration(classes = {SensitivityAnalysisApplication.class, TestChannelBinderConfiguration.class})}) -class NonEvacuatedEnergyTest { - - private static final UUID NETWORK_UUID = UUID.randomUUID(); - private static final UUID NETWORK_ERROR_UUID = UUID.randomUUID(); - private static final UUID NETWORK_ERROR_PERMANENT_LIMIT_UUID = UUID.randomUUID(); - private static final UUID RESULT_UUID = UUID.randomUUID(); - private static final UUID OTHER_RESULT_UUID = UUID.randomUUID(); - - private static final UUID GENERATORS_WIND_FILTER_UUID = UUID.randomUUID(); - private static final UUID GENERATORS_SOLAR_FILTER_UUID = UUID.randomUUID(); - private static final UUID GENERATORS_HYDRO_FILTER_UUID = UUID.randomUUID(); - private static final UUID CAPPING_GENERATORS_WIND_FILTER_UUID = UUID.randomUUID(); - private static final UUID CAPPING_GENERATORS_SOLAR_FILTER_UUID = UUID.randomUUID(); - private static final UUID CAPPING_GENERATORS_HYDRO_FILTER_UUID = UUID.randomUUID(); - private static final UUID MONITORED_BRANCHES_1_FILTER_UUID = UUID.randomUUID(); - private static final UUID MONITORED_BRANCHES_2_FILTER_UUID = UUID.randomUUID(); - private static final UUID CONTINGENCIES_1_UUID = UUID.randomUUID(); - private static final UUID CONTINGENCIES_2_UUID = UUID.randomUUID(); - - private static final List CONTINGENCIES_1 = List.of( - new Contingency("c1", new BranchContingency("LINE_S2S3")) - ); - private static final List CONTINGENCIES_2 = List.of( - new Contingency("c2", new BranchContingency("line2")) - ); - - private static final List CONTINGENCIES_STATUSES = - Stream.concat(CONTINGENCIES_1.stream(), CONTINGENCIES_2.stream()) - .map(c -> new SensitivityAnalysisResult.SensitivityContingencyStatus(c.getId(), SensitivityAnalysisResult.Status.SUCCESS)) - .collect(Collectors.toList()); - - private static final List GENERATORS_WIND = List.of( - new IdentifiableAttributes("GROUP1", IdentifiableType.GENERATOR, null), - new IdentifiableAttributes("GROUP2", IdentifiableType.GENERATOR, null) - ); - private static final List GENERATORS_SOLAR = List.of( - new IdentifiableAttributes("GTH1", IdentifiableType.GENERATOR, null), - new IdentifiableAttributes("GTH2", IdentifiableType.GENERATOR, null) - ); - private static final List GENERATORS_HYDRO = List.of( - new IdentifiableAttributes("ABC", IdentifiableType.GENERATOR, null), - new IdentifiableAttributes("GH1", IdentifiableType.GENERATOR, null) - ); - - private static final List CAPPING_GENERATORS_WIND = List.of( - new IdentifiableAttributes("GROUP3", IdentifiableType.GENERATOR, null), - new IdentifiableAttributes("newGroup2", IdentifiableType.GENERATOR, null) - ); - private static final List CAPPING_GENERATORS_SOLAR = List.of( - new IdentifiableAttributes("TEST1", IdentifiableType.GENERATOR, null), - new IdentifiableAttributes("newGroup1", IdentifiableType.GENERATOR, null) - ); - private static final List CAPPING_GENERATORS_HYDRO = List.of( - new IdentifiableAttributes("GH2", IdentifiableType.GENERATOR, null), - new IdentifiableAttributes("GH3", IdentifiableType.GENERATOR, null) - ); - - private static final List BRANCHES_1 = List.of( - new IdentifiableAttributes("line3", IdentifiableType.LINE, null), - new IdentifiableAttributes("line4", IdentifiableType.LINE, null) - ); - private static final List BRANCHES_2 = List.of( - new IdentifiableAttributes("line2", IdentifiableType.LINE, null), - new IdentifiableAttributes("newLine", IdentifiableType.LINE, null) - ); - - private static final String VARIANT_ID = "variant_1"; - - private static final int TIMEOUT = 1000; - - private static final String ERROR_MESSAGE = "Error message test"; - - private String input; - private String inputWithTemporaryLimitNotFound; - - @Autowired - private OutputDestination output; - - @Autowired - private MockMvc mockMvc; - - @MockBean - private NetworkStoreService networkStoreService; - - @MockBean - private ActionsService actionsService; - - @MockBean - private FilterService filterService; - - @MockBean - private ReportService reportService; - - @MockBean - private UuidGeneratorService uuidGeneratorService; - - @SpyBean - private LoadFlowService loadFlowService; - - @SpyBean - private NonEvacuatedEnergyWorkerService nonEvacuatedEnergyWorkerService; - - @Value("${sensitivity-analysis.default-provider}") - private String defaultSensitivityAnalysisProvider; - - private final ObjectMapper mapper = RestTemplateConfig.objectMapper(); - - private static List buildStagesDefinition() { - return List.of(NonEvacuatedEnergyStageDefinition.builder() - .generators(List.of(new EquipmentsContainer(GENERATORS_WIND_FILTER_UUID, "generators_wind"))) - .energySource(EnergySource.WIND) - .pMaxPercents(List.of(100F, 70F)).build(), - NonEvacuatedEnergyStageDefinition.builder() - .generators(List.of(new EquipmentsContainer(GENERATORS_SOLAR_FILTER_UUID, "generators_solar"))) - .energySource(EnergySource.SOLAR) - .pMaxPercents(List.of(70F, 50F)).build(), - NonEvacuatedEnergyStageDefinition.builder() - .generators(List.of(new EquipmentsContainer(GENERATORS_HYDRO_FILTER_UUID, "generators_hydro"))) - .energySource(EnergySource.HYDRO) - .pMaxPercents(List.of(50F, 30F)).build()); - } - - private static List buildStagesSelection() { - return List.of(NonEvacuatedEnergyStagesSelection.builder() - .name("EOL_100-PV_70-HYDRO_50") - .activated(true) - .stagesDefinitionIndex(List.of(0, 1, 2)) - .pMaxPercentsIndex(List.of(0, 0, 0)) - .build(), - NonEvacuatedEnergyStagesSelection.builder() - .name("EOL_70-PV_50-HYDRO_30") - .activated(true) - .stagesDefinitionIndex(List.of(0, 1, 2)) - .pMaxPercentsIndex(List.of(1, 1, 1)) - .build()); - } - - private static NonEvacuatedEnergyGeneratorsCappings buildGeneratorsCappings() { - return NonEvacuatedEnergyGeneratorsCappings.builder() - .sensitivityThreshold(0.01) - .generators(List.of(NonEvacuatedEnergyGeneratorsCappingsByType.builder() - .energySource(EnergySource.WIND) - .activated(true) - .generators(List.of(new EquipmentsContainer(CAPPING_GENERATORS_WIND_FILTER_UUID, "capping_generators_wind"))) - .build(), - NonEvacuatedEnergyGeneratorsCappingsByType.builder() - .energySource(EnergySource.SOLAR) - .activated(true) - .generators(List.of(new EquipmentsContainer(CAPPING_GENERATORS_SOLAR_FILTER_UUID, "capping_generators_solar"))) - .build(), - NonEvacuatedEnergyGeneratorsCappingsByType.builder() - .energySource(EnergySource.HYDRO) - .activated(true) - .generators(List.of(new EquipmentsContainer(CAPPING_GENERATORS_HYDRO_FILTER_UUID, "capping_generators_hydro"))) - .build())) - .build(); - } - - private static List buildMonitoredBranches() { - return List.of(NonEvacuatedEnergyMonitoredBranches.builder() - .branches(List.of(new EquipmentsContainer(MONITORED_BRANCHES_1_FILTER_UUID, "branches_1"))) - .activated(true) - .istN(true) - .limitNameN(null) - .nCoefficient(100) - .istNm1(false) - .limitNameNm1("IT10") - .nm1Coefficient(90) - .build(), - NonEvacuatedEnergyMonitoredBranches.builder() - .branches(List.of(new EquipmentsContainer(MONITORED_BRANCHES_2_FILTER_UUID, "branches_2"))) - .activated(true) - .istN(false) - .limitNameN("IT5") - .nCoefficient(90) - .istNm1(true) - .limitNameNm1(null) - .nm1Coefficient(70) - .build(), - NonEvacuatedEnergyMonitoredBranches.builder() - .branches(List.of(new EquipmentsContainer(MONITORED_BRANCHES_2_FILTER_UUID, "branches_2"))) - .activated(true) - .istN(false) - .limitNameN("IT20") - .nCoefficient(70) - .istNm1(true) - .limitNameNm1(null) - .nm1Coefficient(80) - .build() - ); - } - - private static List buildContingencies() { - return List.of(NonEvacuatedEnergyContingencies.builder() - .activated(true) - .contingencies(List.of(new EquipmentsContainer(CONTINGENCIES_1_UUID, "contingency_1"))) - .build(), - NonEvacuatedEnergyContingencies.builder() - .activated(true) - .contingencies(List.of(new EquipmentsContainer(CONTINGENCIES_2_UUID, "contingency_2"))) - .build()); - } - - private static List buildSensitivityFactorsResults() { - // sensitivity variable set for each energy source (WIND, SOLAR, HYDRO) - SensitivityVariableSet sensitivityVariableSet1 = new SensitivityVariableSet(CAPPING_GENERATORS_WIND_FILTER_UUID.toString(), - CAPPING_GENERATORS_WIND.stream().map(g -> new WeightedSensitivityVariable(g.getId(), 1.)).toList()); - SensitivityVariableSet sensitivityVariableSet2 = new SensitivityVariableSet(CAPPING_GENERATORS_SOLAR_FILTER_UUID.toString(), - CAPPING_GENERATORS_SOLAR.stream().map(g -> new WeightedSensitivityVariable(g.getId(), 1.)).toList()); - SensitivityVariableSet sensitivityVariableSet3 = new SensitivityVariableSet(CAPPING_GENERATORS_HYDRO_FILTER_UUID.toString(), - CAPPING_GENERATORS_HYDRO.stream().map(g -> new WeightedSensitivityVariable(g.getId(), 1.)).toList()); - - // line3 (both sides with and without contingency) - List sensitivityFactorsLine3Side1WithoutContingency = List.of( - // for each variable id (capping generator) - new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, "GROUP3", false, ContingencyContext.none()), - new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, "newGroup2", false, ContingencyContext.none()), - new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, "TEST1", false, ContingencyContext.none()), - new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, "newGroup1", false, ContingencyContext.none()), - new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, "GH2", false, ContingencyContext.none()), - new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, "GH3", false, ContingencyContext.none()), - // for each variable set (capping generator by energy source) - new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, sensitivityVariableSet1.getId(), true, ContingencyContext.none()), - new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, sensitivityVariableSet2.getId(), true, ContingencyContext.none()), - new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_1, "line3", - SensitivityVariableType.INJECTION_ACTIVE_POWER, sensitivityVariableSet3.getId(), true, ContingencyContext.none()) - ); - - List sensitivityFactorsLine3Side2WithoutContingency = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> { - if (f.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_2, f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), f.getContingencyContext()); - } else { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_2, f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), f.getContingencyContext()); - } - }).toList(); - - List sensitivityFactorsLine3Side1WithContingency1 = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> new SensitivityFactor(f.getFunctionType(), f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c1"))).toList(); - List sensitivityFactorsLine3Side1WithContingency2 = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> new SensitivityFactor(f.getFunctionType(), f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c2"))).toList(); - - List sensitivityFactorsLine3Side2WithContingency1 = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> { - if (f.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_2, f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c1")); - } else { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_2, f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c1")); - } - }).toList(); - List sensitivityFactorsLine3Side2WithContingency2 = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> { - if (f.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_2, f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c2")); - } else { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_2, f.getFunctionId(), f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c2")); - } - }).toList(); - - // line2 (side2 with and without contingency) - List sensitivityFactorsLine2Side2WithoutContingency = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> { - if (f.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_2, "line2", f.getVariableType(), - f.getVariableId(), f.isVariableSet(), f.getContingencyContext()); - } else { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_2, "line2", f.getVariableType(), - f.getVariableId(), f.isVariableSet(), f.getContingencyContext()); - } - }).toList(); - - List sensitivityFactorsLine2Side2WithContingency1 = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> { - if (f.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_2, "line2", f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c1")); - } else { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_2, "line2", f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c1")); - } - }).toList(); - List sensitivityFactorsLine2Side2WithContingency2 = sensitivityFactorsLine3Side1WithoutContingency - .stream().map(f -> { - if (f.getFunctionType() == SensitivityFunctionType.BRANCH_CURRENT_1) { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_CURRENT_2, "line2", f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c2")); - } else { - return new SensitivityFactor(SensitivityFunctionType.BRANCH_ACTIVE_POWER_2, "line2", f.getVariableType(), - f.getVariableId(), f.isVariableSet(), ContingencyContext.specificContingency("c2")); - } - }).toList(); - - return Stream.of( - sensitivityFactorsLine3Side1WithoutContingency, - sensitivityFactorsLine3Side2WithoutContingency, - sensitivityFactorsLine3Side1WithContingency1, - sensitivityFactorsLine3Side1WithContingency2, - sensitivityFactorsLine3Side2WithContingency1, - sensitivityFactorsLine3Side2WithContingency2, - sensitivityFactorsLine2Side2WithoutContingency, - sensitivityFactorsLine2Side2WithContingency1, - sensitivityFactorsLine2Side2WithContingency2) - .flatMap(java.util.Collection::stream) - .collect(Collectors.toList()); - } - - private static List> buildSensitivityValuesResults() { - // stage 1 result 1 : at least, one limit violation detected - List sensitivityValues1 = List.of( - // line3 - new SensitivityValue(0, -1, 0.02, 130.), // line3, side1, GROUP3, N - new SensitivityValue(1, -1, 0.02, 230.), // line3, side1, newGroup2, N ----> limit violation should be detected here - new SensitivityValue(2, -1, 0.02, 150.), // line3, side1, TEST1, N - new SensitivityValue(3, -1, 0.02, 160.), // line3, side1, newGroup1, N - new SensitivityValue(4, -1, 0.02, 210.), // line3, side1, GH2, N ----> limit violation should be detected here - new SensitivityValue(5, -1, 0.02, 170.), // line3, side1, GH3, N - new SensitivityValue(6, -1, 0.02, 80.), // line3, side1, (GROUP3, newGroup2), N - new SensitivityValue(7, -1, 0.02, 110.), // line3, side1, (TEST1, newGroup1), N - new SensitivityValue(8, -1, 0.02, 140.), // line3, side1, (GH2, GH3), N - - new SensitivityValue(9, -1, 0.02, 160.), // line3, side2, GROUP3, N - new SensitivityValue(10, -1, 0.02, 200.), // line3, side2, newGroup2, N ----> limit violation should be detected here - new SensitivityValue(11, -1, 0.02, 130.), // line3, side2, TEST1, N - new SensitivityValue(12, -1, 0.02, 190.), // line3, side2, newGroup1, N ----> limit violation should be detected here - new SensitivityValue(13, -1, 0.02, 120.), // line3, side2, GH2, N - new SensitivityValue(14, -1, 0.02, 150.), // line3, side2, GH3, N - new SensitivityValue(15, -1, 0.02, 70.), // line3, side2, (GROUP3, newGroup2), N - new SensitivityValue(16, -1, 0.02, 100.), // line3, side2, (TEST1, newGroup1), N - new SensitivityValue(17, -1, 0.02, 160.), // line3, side2, (GH2, GH3), N - - new SensitivityValue(18, 0, 0.02, 120.), // line3, side1, GROUP3, c1 - new SensitivityValue(19, 0, 0.02, 260.), // line3, side1, newGroup2, c1 ----> limit violation should be detected here - new SensitivityValue(20, 0, 0.02, 130.), // line3, side1, TEST1, c1 - new SensitivityValue(21, 0, 0.02, 110.), // line3, side1, newGroup1, c1 - new SensitivityValue(22, 0, 0.02, 80.), // line3, side1, GH2, c1 - new SensitivityValue(23, 0, 0.02, 250.), // line3, side1, GH3, c1 ----> limit violation should be detected here - new SensitivityValue(24, 0, 0.02, 90.), // line3, side1, (GROUP3, newGroup2), c1 - new SensitivityValue(25, 0, 0.02, 100.), // line3, side1, (TEST1, newGroup1), c1 - new SensitivityValue(26, 0, 0.02, 210.), // line3, side1, (GH2, GH3), c1 - - new SensitivityValue(27, 1, 0.02, 100.), // line3, side1, GROUP3, c2 - new SensitivityValue(28, 1, 0.02, 120.), // line3, side1, newGroup2, c2 - new SensitivityValue(36, 0, 0.02, 100.), // line3, side2, GROUP3, c1 - new SensitivityValue(37, 0, 0.02, 120.), // line3, side2, newGroup2, c1 - new SensitivityValue(45, 1, 0.02, 100.), // line3, side2, GROUP3, c2 - new SensitivityValue(46, 1, 0.02, 120.), // line3, side2, newGroup2, c2 - - // line2 - new SensitivityValue(54, -1, 0.02, 170.), // line2, side2, GROUP3, N - new SensitivityValue(55, -1, 0.02, 190.), // line2, side2, newGroup2, N ----> limit violation should be detected here - new SensitivityValue(56, -1, 0.02, 120.), // line2, side2, TEST1, N - new SensitivityValue(57, -1, 0.02, 130.), // line2, side2, newGroup1, N - new SensitivityValue(58, -1, 0.02, 240.), // line2, side2, GH2, N ----> limit violation should be detected here - new SensitivityValue(59, -1, 0.02, 100.), // line2, side2, GH3, N - new SensitivityValue(60, -1, 0.02, 80.), // line2, side2, (GROUP3, newGroup2), N - new SensitivityValue(61, -1, 0.02, 100.), // line2, side2, (TEST1, newGroup1), N - new SensitivityValue(62, -1, 0.02, 160.), // line2, side2, (GH2, GH3), N - - new SensitivityValue(63, 0, 0.02, 130.), // line2, side2, GROUP3, c1 ----> limit violation should be detected here - new SensitivityValue(64, 0, 0.02, 90.), // line2, side2, newGroup2, c1 - new SensitivityValue(65, 0, 0.02, 70.), // line2, side2, TEST1, c1 - new SensitivityValue(66, 0, 0.02, 110.), // line2, side2, newGroup1, c1 - new SensitivityValue(67, 0, 0.02, 80.), // line2, side2, GH2, c1 - new SensitivityValue(68, 0, 0.02, 140.), // line2, side2, GH3, c1 ----> limit violation should be detected here - new SensitivityValue(69, 0, 0.02, 80.), // line2, side2, (GROUP3, newGroup2), c1 - new SensitivityValue(70, 0, 0.02, 100.), // line2, side2, (TEST1, newGroup1), c1 - new SensitivityValue(71, 0, 0.02, 70.), // line2, side2, (GH2, GH3), c1 - - new SensitivityValue(72, 0, 0.02, 100.), // line2, side2, GROUP3, c2 - new SensitivityValue(73, 0, 0.02, 120.), // line2, side2, newGroup2, c2 ----> limit violation should be detected here - new SensitivityValue(74, 0, 0.02, 70.), // line2, side2, TEST1, c2 - new SensitivityValue(75, 0, 0.02, 110.), // line2, side2, newGroup1, c2 - new SensitivityValue(76, 0, 0.02, 115.), // line2, side2, GH2, c2 ----> limit violation should be detected here - new SensitivityValue(77, 0, 0.02, 100.), // line2, side2, GH3, c2 - new SensitivityValue(78, 0, 0.02, 80.), // line2, side2, (GROUP3, newGroup2), c2 - new SensitivityValue(79, 0, 0.02, 100.), // line2, side2, (TEST1, newGroup1), c2 - new SensitivityValue(80, 0, 0.02, 60.) // line2, side2, (GH2, GH3), c2 - ); - - // stage 1 result 2 : no limit violation should be detected - List sensitivityValues2 = List.of( - // line3 - new SensitivityValue(0, -1, 0.02, 130.), // line3, side1, GROUP3, N - new SensitivityValue(1, -1, 0.02, 140.), // line3, side1, newGroup2, N - new SensitivityValue(2, -1, 0.02, 150.), // line3, side1, TEST1, N - new SensitivityValue(3, -1, 0.02, 160.), // line3, side1, newGroup1, N - new SensitivityValue(9, -1, 0.02, 160.), // line3, side2, GROUP3, N - new SensitivityValue(13, -1, 0.02, 120.), // line3, side2, GH2, N - new SensitivityValue(14, -1, 0.02, 150.), // line3, side2, GH3, N - new SensitivityValue(20, 0, 0.02, 130.), // line3, side1, TEST1, c1 - new SensitivityValue(21, 0, 0.02, 110.), // line3, side1, newGroup1, c1 - new SensitivityValue(27, 1, 0.02, 100.), // line3, side1, GROUP3, c2 - new SensitivityValue(28, 1, 0.02, 120.), // line3, side1, newGroup2, c2 - new SensitivityValue(36, 0, 0.02, 100.), // line3, side2, GROUP3, c1 - new SensitivityValue(37, 0, 0.02, 120.), // line3, side2, newGroup2, c1 - new SensitivityValue(45, 1, 0.02, 100.), // line3, side2, GROUP3, c2 - new SensitivityValue(46, 1, 0.02, 120.), // line3, side2, newGroup2, c2 - - // line2 - new SensitivityValue(54, -1, 0.02, 100.), // line2, side2, GROUP3, N - new SensitivityValue(56, -1, 0.02, 90.), // line2, side2, TEST1, N - new SensitivityValue(57, -1, 0.02, 105), // line2, side2, newGroup1, N - new SensitivityValue(64, 0, 0.02, 90.), // line2, side2, newGroup2, c1 - new SensitivityValue(65, 0, 0.02, 70.), // line2, side2, TEST1, c1 - new SensitivityValue(72, 0, 0.02, 100.), // line2, side2, GROUP3, c2 - new SensitivityValue(77, 0, 0.02, 70.) // line2, side2, GH3, c2 - ); - - // stage 2 result 1 : at least, one limit violation detected - List sensitivityValues3 = List.of( - // line3 - new SensitivityValue(0, -1, 0.02, 130.), // line3, side1, GROUP3, N - new SensitivityValue(1, -1, 0.02, 140.), // line3, side1, newGroup2, N - new SensitivityValue(2, -1, 0.02, 240.), // line3, side1, TEST1, N ----> limit violation should be detected here - new SensitivityValue(3, -1, 0.02, 160.), // line3, side1, newGroup1, N - new SensitivityValue(4, -1, 0.02, 130.), // line3, side1, GH2, N - new SensitivityValue(5, -1, 0.02, 220.), // line3, side1, GH3, N ----> limit violation should be detected here - new SensitivityValue(6, -1, 0.02, 80.), // line3, side1, (GROUP3, newGroup2), N - new SensitivityValue(7, -1, 0.02, 110.), // line3, side1, (TEST1, newGroup1), N - new SensitivityValue(8, -1, 0.02, 230.), // line3, side1, (GH2, GH3), N - new SensitivityValue(9, -1, 0.02, 270.), // line3, side2, GROUP3, N ----> limit violation should be detected here - new SensitivityValue(10, -1, 0.02, 160.), // line3, side2, newGroup2, N - new SensitivityValue(11, -1, 0.02, 130.), // line3, side2, TEST1, N - new SensitivityValue(12, -1, 0.02, 150.), // line3, side2, newGroup1, N - new SensitivityValue(13, -1, 0.02, 120.), // line3, side2, GH2, N - new SensitivityValue(14, -1, 0.02, 200.), // line3, side2, GH3, N ----> limit violation should be detected here - new SensitivityValue(15, -1, 0.02, 70.), // line3, side2, (GROUP3, newGroup2), N - new SensitivityValue(16, -1, 0.02, 100.), // line3, side2, (TEST1, newGroup1), N - new SensitivityValue(17, -1, 0.02, 160.), // line3, side2, (GH2, GH3), N - new SensitivityValue(18, 0, 0.02, 120.), // line3, side1, GROUP3, c1 - new SensitivityValue(19, 0, 0.02, 110.), // line3, side1, newGroup2, c1 - new SensitivityValue(20, 0, 0.02, 130.), // line3, side1, TEST1, c1 - new SensitivityValue(21, 0, 0.02, 260.), // line3, side1, newGroup1, c1 ----> limit violation should be detected here - new SensitivityValue(22, 0, 0.02, 250.), // line3, side1, GH2, c1 ----> limit violation should be detected here - new SensitivityValue(23, 0, 0.02, 90.), // line3, side1, GH3, c1 - new SensitivityValue(24, 0, 0.02, 90.), // line3, side1, (GROUP3, newGroup2), c1 - new SensitivityValue(25, 0, 0.02, 100.), // line3, side1, (TEST1, newGroup1), c1 - new SensitivityValue(26, 0, 0.02, 210.), // line3, side1, (GH2, GH3), c1 - new SensitivityValue(27, 1, 0.02, 100.), // line3, side1, GROUP3, c2 - new SensitivityValue(28, 1, 0.02, 120.), // line3, side1, newGroup2, c2 - new SensitivityValue(36, 0, 0.02, 100.), // line3, side2, GROUP3, c1 - new SensitivityValue(37, 0, 0.02, 120.), // line3, side2, newGroup2, c1 - new SensitivityValue(45, 1, 0.02, 100.), // line3, side2, GROUP3, c2 - new SensitivityValue(46, 1, 0.02, 120.), // line3, side2, newGroup2, c2 - - // line2 - new SensitivityValue(54, -1, 0.02, 170.), // line2, side2, GROUP3, N - new SensitivityValue(55, -1, 0.02, 120.), // line2, side2, newGroup2, N - new SensitivityValue(56, -1, 0.02, 195.), // line2, side2, TEST1, N ----> limit violation should be detected here - new SensitivityValue(57, -1, 0.02, 245.), // line2, side2, newGroup1, N ----> limit violation should be detected here - new SensitivityValue(58, -1, 0.02, 130.), // line2, side2, GH2, N - new SensitivityValue(59, -1, 0.02, 100.), // line2, side2, GH3, N - new SensitivityValue(60, -1, 0.02, 80.), // line2, side2, (GROUP3, newGroup2), N - new SensitivityValue(61, -1, 0.02, 100.), // line2, side2, (TEST1, newGroup1), N - new SensitivityValue(62, -1, 0.02, 160.), // line2, side2, (GH2, GH3), N - new SensitivityValue(63, 0, 0.02, 70.), // line2, side2, GROUP3, c1 - new SensitivityValue(64, 0, 0.02, 90.), // line2, side2, newGroup2, c1 - new SensitivityValue(65, 0, 0.02, 140.), // line2, side2, TEST1, c1 ----> limit violation should be detected here - new SensitivityValue(66, 0, 0.02, 110.), // line2, side2, newGroup1, c1 - new SensitivityValue(67, 0, 0.02, 140.), // line2, side2, GH2, c1 ----> limit violation should be detected here - new SensitivityValue(68, 0, 0.02, 80.), // line2, side2, GH3, c1 - new SensitivityValue(69, 0, 0.02, 80.), // line2, side2, (GROUP3, newGroup2), c1 - new SensitivityValue(70, 0, 0.02, 100.), // line2, side2, (TEST1, newGroup1), c1 - new SensitivityValue(71, 0, 0.02, 70.), // line2, side2, (GH2, GH3), c1 - new SensitivityValue(72, 0, 0.02, 130.), // line2, side2, GROUP3, c2 ----> limit violation should be detected here - new SensitivityValue(73, 0, 0.02, 90.), // line2, side2, newGroup2, c2 - new SensitivityValue(74, 0, 0.02, 70.), // line2, side2, TEST1, c2 - new SensitivityValue(75, 0, 0.02, 110.), // line2, side2, newGroup1, c2 - new SensitivityValue(76, 0, 0.02, 70.), // line2, side2, GH2, c2 - new SensitivityValue(77, 0, 0.02, 120.), // line2, side2, GH3, c2 ----> limit violation should be detected here - new SensitivityValue(78, 0, 0.02, 80.), // line2, side2, (GROUP3, newGroup2), c2 - new SensitivityValue(79, 0, 0.02, 100.), // line2, side2, (TEST1, newGroup1), c2 - new SensitivityValue(80, 0, 0.02, 60.) // line2, side2, (GH2, GH3), c2 - ); - - // stage 2 result 2 : no more limit violation detected - List sensitivityValues4 = List.of( - // line3 - new SensitivityValue(0, -1, 0.02, 130.), // line3, side1, GROUP3, N - new SensitivityValue(1, -1, 0.02, 140.), // line3, side1, newGroup2, N - new SensitivityValue(11, -1, 0.02, 130.), // line3, side2, TEST1, N - new SensitivityValue(12, -1, 0.02, 150.), // line3, side2, newGroup1, N - new SensitivityValue(17, -1, 0.02, 160.), // line3, side2, (GH2, GH3), N - new SensitivityValue(18, 0, 0.02, 120.), // line3, side1, GROUP3, c1 - new SensitivityValue(19, 0, 0.02, 110.), // line3, side1, newGroup2, c1 - new SensitivityValue(26, 0, 0.02, 210.), // line3, side1, (GH2, GH3), c1 - new SensitivityValue(27, 1, 0.02, 100.), // line3, side1, GROUP3, c2 - new SensitivityValue(45, 1, 0.02, 100.), // line3, side2, GROUP3, c2 - new SensitivityValue(46, 1, 0.02, 120.), // line3, side2, newGroup2, c2 - - // line2 - new SensitivityValue(54, -1, 0.02, 95.), // line2, side2, GROUP3, N - new SensitivityValue(55, -1, 0.02, 80.), // line2, side2, newGroup2, N - new SensitivityValue(59, -1, 0.02, 100.), // line2, side2, GH3, N - new SensitivityValue(60, -1, 0.02, 80.), // line2, side2, (GROUP3, newGroup2), N - new SensitivityValue(61, -1, 0.02, 100.), // line2, side2, (TEST1, newGroup1), N - new SensitivityValue(75, 0, 0.02, 110.), // line2, side2, newGroup1, c2 - new SensitivityValue(76, 0, 0.02, 70.) // line2, side2, GH2, c2 - ); - - return List.of(sensitivityValues1, sensitivityValues2, sensitivityValues3, sensitivityValues4); - } - - private void mockActions() { - given(actionsService.getContingencyList(eq(List.of(CONTINGENCIES_1_UUID)), any(), eq(VARIANT_ID))).willReturn(new ContingencyListExportResult(CONTINGENCIES_1, null)); - given(actionsService.getContingencyList(eq(List.of(CONTINGENCIES_2_UUID)), any(), eq(VARIANT_ID))).willReturn(new ContingencyListExportResult(CONTINGENCIES_2, null)); - //merge 2 lists into one - List contingencies = new ArrayList<>(CONTINGENCIES_1); - contingencies.addAll(CONTINGENCIES_2); - given(actionsService.getContingencyList(eq(List.of(CONTINGENCIES_1_UUID, CONTINGENCIES_2_UUID)), any(), eq(VARIANT_ID))).willReturn(new ContingencyListExportResult(contingencies, null)); - } - - private void mockFilters() { - given(filterService.getIdentifiablesFromFilter(eq(GENERATORS_WIND_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(GENERATORS_WIND); - given(filterService.getIdentifiablesFromFilter(eq(GENERATORS_SOLAR_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(GENERATORS_SOLAR); - given(filterService.getIdentifiablesFromFilter(eq(GENERATORS_HYDRO_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(GENERATORS_HYDRO); - given(filterService.getIdentifiablesFromFilter(eq(CAPPING_GENERATORS_WIND_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(CAPPING_GENERATORS_WIND); - given(filterService.getIdentifiablesFromFilter(eq(CAPPING_GENERATORS_SOLAR_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(CAPPING_GENERATORS_SOLAR); - given(filterService.getIdentifiablesFromFilter(eq(CAPPING_GENERATORS_HYDRO_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(CAPPING_GENERATORS_HYDRO); - given(filterService.getIdentifiablesFromFilter(eq(MONITORED_BRANCHES_1_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(BRANCHES_1); - given(filterService.getIdentifiablesFromFilter(eq(MONITORED_BRANCHES_2_FILTER_UUID), any(), eq(VARIANT_ID))).willReturn(BRANCHES_2); - } - - private static String resourceToString(String resource) throws IOException { - return new String(ByteStreams.toByteArray(Objects.requireNonNull(NonEvacuatedEnergyTest.class.getResourceAsStream(resource))), StandardCharsets.UTF_8); - } - - @BeforeEach - void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - - Network network = Network.read("testForNonEvacuatedEnergy.xiidm", getClass().getResourceAsStream("/testForNonEvacuatedEnergy.xiidm")); - network.getVariantManager().cloneVariant(VariantManagerConstants.INITIAL_VARIANT_ID, VARIANT_ID); - - Network networkWithNoPermamentLimit = Network.read("testForNonEvacuatedEnergyNoPermanentLimit.xiidm", getClass().getResourceAsStream("/testForNonEvacuatedEnergyNoPermanentLimit.xiidm")); - networkWithNoPermamentLimit.getVariantManager().cloneVariant(VariantManagerConstants.INITIAL_VARIANT_ID, VARIANT_ID); - - // network store service mocking - given(networkStoreService.getNetwork(NETWORK_UUID, PreloadingStrategy.COLLECTION)).willReturn(network); - given(networkStoreService.getNetwork(NETWORK_ERROR_UUID, PreloadingStrategy.COLLECTION)).willThrow(new RuntimeException(ERROR_MESSAGE)); - given(networkStoreService.getNetwork(NETWORK_ERROR_PERMANENT_LIMIT_UUID, PreloadingStrategy.COLLECTION)).willReturn(networkWithNoPermamentLimit); - - // build non evacuated energy input data - List stagesDefinition = buildStagesDefinition(); - List stagesSelection = buildStagesSelection(); - NonEvacuatedEnergyGeneratorsCappings generatorsCappings = buildGeneratorsCappings(); - List monitoredBranches = buildMonitoredBranches(); - List contingencies = buildContingencies(); - - NonEvacuatedEnergyInputData nonEvacuatedEnergyInputData = NonEvacuatedEnergyInputData.builder() - .nonEvacuatedEnergyStagesDefinition(stagesDefinition) - .nonEvacuatedEnergyStagesSelection(stagesSelection) - .nonEvacuatedEnergyGeneratorsCappings(generatorsCappings) - .nonEvacuatedEnergyMonitoredBranches(monitoredBranches) - .nonEvacuatedEnergyContingencies(contingencies) - .parameters(SensitivityAnalysisParameters.load()) - .build(); - input = mapper.writeValueAsString(nonEvacuatedEnergyInputData); - - nonEvacuatedEnergyInputData.getNonEvacuatedEnergyMonitoredBranches().get(0).setIstN(false); - nonEvacuatedEnergyInputData.getNonEvacuatedEnergyMonitoredBranches().get(0).setLimitNameN("limitNotFound"); - inputWithTemporaryLimitNotFound = mapper.writeValueAsString(nonEvacuatedEnergyInputData); - - // build the successive security analysis results - // (only some sensitivity factors in results for line3 and line2) - List sensitivityFactors = buildSensitivityFactorsResults(); - List> sensitivityValues = buildSensitivityValuesResults(); - - // 4 sensitivity analysis calls globally (2 for each generation stage) - SensitivityAnalysisResult result1 = new SensitivityAnalysisResult(sensitivityFactors, CONTINGENCIES_STATUSES, sensitivityValues.get(0)); - SensitivityAnalysisResult result2 = new SensitivityAnalysisResult(sensitivityFactors, CONTINGENCIES_STATUSES, sensitivityValues.get(1)); - SensitivityAnalysisResult result3 = new SensitivityAnalysisResult(sensitivityFactors, CONTINGENCIES_STATUSES, sensitivityValues.get(2)); - SensitivityAnalysisResult result4 = new SensitivityAnalysisResult(sensitivityFactors, CONTINGENCIES_STATUSES, sensitivityValues.get(3)); - - // action service mocking - mockActions(); - - // filter service mocking - mockFilters(); - - // report service mocking - doAnswer(i -> null).when(reportService).sendReport(any(), any()); - - // UUID service mocking to always generate the same result UUID - given(uuidGeneratorService.generate()).willReturn(RESULT_UUID); - - // mock the multiple successive calls to the sensitivity analysis runner : - // individual sensitivity analysis results are built in order to have 2 sensitivity analysis calls for each stage, so to have 4 - // sensitivity analysis calls globally - SensitivityAnalysis.Runner runner = mock(SensitivityAnalysis.Runner.class); - given(runner.getName()).willReturn(defaultSensitivityAnalysisProvider); - given(runner.runAsync(eq(network), anyString(), anyList(), anyList(), anyList(), - any(SensitivityAnalysisParameters.class), any(ComputationManager.class), any(ReportNode.class))) - .willReturn(CompletableFuture.completedFuture(result1)) - .willReturn(CompletableFuture.completedFuture(result2)) - .willReturn(CompletableFuture.completedFuture(result3)) - .willReturn(CompletableFuture.completedFuture(result4)); - nonEvacuatedEnergyWorkerService.setSensitivityAnalysisFactorySupplier(provider -> runner); - - // mock loadFlow parameters - LoadFlowParametersValues loadFlowParametersValues = LoadFlowParametersValues.builder() - .commonParameters(LoadFlowParameters.load()) - .specificParameters(Map.of()) - .build(); - doReturn(loadFlowParametersValues).when(loadFlowService).getLoadFlowParameters(any(), any()); - - // purge messages - while (output.receive(1000, "nonEvacuatedEnergy.result") != null) { - } - while (output.receive(1000, "nonEvacuatedEnergy.run") != null) { - } - while (output.receive(1000, "nonEvacuatedEnergy.cancel") != null) { - } - while (output.receive(1000, "nonEvacuatedEnergy.stopped") != null) { - } - while (output.receive(1000, "nonEvacuatedEnergy.failed") != null) { - } - while (output.receive(1000, "nonEvacuatedEnergy.cancelfailed") != null) { - } - } - - @AfterEach - void tearDown() throws Exception { - mockMvc.perform(delete("/" + VERSION + "/non-evacuated-energy/results")) - .andExpect(status().isOk()); - } - - @Test - void runTest() throws Exception { - MvcResult result = mockMvc.perform(post( - "/" + VERSION + "/networks/{networkUuid}/non-evacuated-energy/run-and-save?reportType=NonEvacuatedEnergy&receiver=me&variantId=" + VARIANT_ID + "&loadFlowParametersUuid=" + UUID.randomUUID(), NETWORK_UUID) - .contentType(MediaType.APPLICATION_JSON) - .header(HEADER_USER_ID, "userId") - .content(input)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - assertEquals(RESULT_UUID, mapper.readValue(result.getResponse().getContentAsString(), UUID.class)); - - Message resultMessage = output.receive(30 * TIMEOUT, "nonEvacuatedEnergy.result"); - assertEquals(RESULT_UUID.toString(), resultMessage.getHeaders().get("resultUuid")); - assertEquals("me", resultMessage.getHeaders().get("receiver")); - - // get result - result = mockMvc.perform(get("/" + VERSION + "/non-evacuated-energy/results/{resultUuid}", RESULT_UUID)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - String res = result.getResponse().getContentAsString(); - JSONAssert.assertEquals(resourceToString("/non-evacuated-energy-results.json"), res, JSONCompareMode.LENIENT); - - // should throw not found if result does not exist - mockMvc.perform(get("/" + VERSION + "/non-evacuated-energy/results/{resultUuid}", OTHER_RESULT_UUID)) - .andExpect(status().isNotFound()); - - // test one result deletion - mockMvc.perform(delete("/" + VERSION + "/non-evacuated-energy/results").queryParam("resultsUuids", RESULT_UUID.toString())) - .andExpect(status().isOk()); - - mockMvc.perform(get("/" + VERSION + "/non-evacuated-energy/results/{resultUuid}", RESULT_UUID)) - .andExpect(status().isNotFound()); - } - - @Test - void testStatus() throws Exception { - MvcResult result = mockMvc.perform(get( - "/" + VERSION + "/non-evacuated-energy/results/{resultUuid}/status", RESULT_UUID)) - .andExpect(status().isOk()) - .andReturn(); - assertEquals("", result.getResponse().getContentAsString()); - - mockMvc.perform(put("/" + VERSION + "/non-evacuated-energy/results/invalidate-status?resultUuid=" + RESULT_UUID)) - .andExpect(status().isOk()); - - result = mockMvc.perform(get( - "/" + VERSION + "/non-evacuated-energy/results/{resultUuid}/status", RESULT_UUID)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - assertEquals(NonEvacuatedEnergyStatus.NOT_DONE.name(), result.getResponse().getContentAsString()); - } - - @Test - void stopTest() throws Exception { - mockMvc.perform(post( - "/" + VERSION + "/networks/{networkUuid}/non-evacuated-energy/run-and-save?reportType=NonEvacuatedEnergy&receiver=me&variantId=" + VARIANT_ID + "&loadFlowParametersUuid=" + UUID.randomUUID(), NETWORK_UUID) - .contentType(MediaType.APPLICATION_JSON) - .header(HEADER_USER_ID, "userId") - .content(input)) - .andExpect(status().isOk()); - - // stop non evacuated energy analysis - mockMvc.perform(put("/" + VERSION + "/non-evacuated-energy/results/{resultUuid}/stop" + "?receiver=me", RESULT_UUID) - .header(HEADER_USER_ID, "userId")) - .andExpect(status().isOk()); - - // message stopped should have been sent - Message message = output.receive(TIMEOUT, "nonEvacuatedEnergy.cancelfailed"); - assertNotNull(message); - assertEquals(RESULT_UUID.toString(), message.getHeaders().get("resultUuid")); - assertEquals("me", message.getHeaders().get("receiver")); - assertEquals(getCancelFailedMessage(NonEvacuatedEnergyWorkerService.COMPUTATION_TYPE), - message.getHeaders().get("message")); - - //FIXME how to test the case when the computation is still in progress and we send a cancel request - } - - @Test - void testWithBadNetworkError() throws Exception { - MvcResult result = mockMvc.perform(post( - "/" + VERSION + "/networks/{networkUuid}/non-evacuated-energy/run-and-save?reportType=NonEvacuatedEnergy&receiver=me&variantId=" + VARIANT_ID + "&loadFlowParametersUuid=" + UUID.randomUUID(), NETWORK_ERROR_UUID) - .contentType(MediaType.APPLICATION_JSON) - .header(HEADER_USER_ID, "userId") - .content(input)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - assertEquals(RESULT_UUID, mapper.readValue(result.getResponse().getContentAsString(), UUID.class)); - - // No result available - mockMvc.perform(get("/" + VERSION + "/non-evacuated-energy/results/{resultUuid}", RESULT_UUID)) - .andExpect(status().isNotFound()); - } - - private void testLimitError(String inputData, String variantId, UUID networkUuid, String messageExpected) throws Exception { - MvcResult result = mockMvc.perform(post( - "/" + VERSION + "/networks/{networkUuid}/non-evacuated-energy/run-and-save?reportType=NonEvacuatedEnergy&receiver=me&variantId=" + variantId + "&loadFlowParametersUuid=" + UUID.randomUUID(), networkUuid) - .contentType(MediaType.APPLICATION_JSON) - .header(HEADER_USER_ID, "userId") - .content(inputData)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - assertEquals(RESULT_UUID, mapper.readValue(result.getResponse().getContentAsString(), UUID.class)); - - // No result available - mockMvc.perform(get("/" + VERSION + "/non-evacuated-energy/results/{resultUuid}", RESULT_UUID)) - .andExpect(status().isNotFound()); - } - - @Test - void testWithPermanentOrTemporaryLimitNotFound() throws Exception { - testLimitError(input, VARIANT_ID, NETWORK_ERROR_PERMANENT_LIMIT_UUID, "Branch 'line2' has no current limits !!"); - testLimitError(inputWithTemporaryLimitNotFound, VARIANT_ID, NETWORK_UUID, "Temporary limit 'limitNotFound' not found for branch 'line3' !!"); - } -} diff --git a/src/test/java/org/gridsuite/sensitivityanalysis/server/SupervisionControllerTest.java b/src/test/java/org/gridsuite/sensitivityanalysis/server/SupervisionControllerTest.java index ea14ccfd..126057df 100644 --- a/src/test/java/org/gridsuite/sensitivityanalysis/server/SupervisionControllerTest.java +++ b/src/test/java/org/gridsuite/sensitivityanalysis/server/SupervisionControllerTest.java @@ -39,13 +39,5 @@ void testResultCount() throws Exception { String resultCount = mvcResult.getResponse().getContentAsString(); assertEquals("0", resultCount); - - mvcResult = mockMvc.perform(get("/v1/supervision/non-evacuated-energy/results-count")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - - resultCount = mvcResult.getResponse().getContentAsString(); - assertEquals("0", resultCount); } }