Skip to content

Commit

Permalink
Various refactors (#345)
Browse files Browse the repository at this point in the history
* Add equipment id to default model warning/report
* Remove deprecated and other minors errors
* Refactor ModelConfigsJsonDeserializer
* Fix test, checkstyle; replace AtomicReference with anonymous object

Signed-off-by: lisrte <[email protected]>
  • Loading branch information
Lisrte authored May 15, 2024
1 parent 51f94a1 commit fb8d952
Show file tree
Hide file tree
Showing 15 changed files with 125 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ private LogUtils() {

public static Optional<LogEntry> createLog(String severity, String message) {
if (severity == null) {
LOGGER.warn("Inconsistent log entry (modelName: '{}', message: '{}')", severity, message);
LOGGER.warn("Inconsistent log entry (message: '{}')", message);
} else {
if (emptyMessage(message)) {
LOGGER.debug("Empty message, the entry will be skipped : {}", message);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ void checkAllParametersAssignedToString() {
@Test
void defaultParametersSerialization() throws IOException {
LoadFlowParameters lfParameters = LoadFlowParameters.load(platformConfig);
lfParameters.setNoGeneratorReactiveLimits(true);
lfParameters.setUseReactiveLimits(false);
lfParameters.setPhaseShifterRegulationOn(false);

DynaFlowParameters dynaFlowParameters = new DynaFlowParameters();
Expand All @@ -212,25 +212,25 @@ void defaultParametersSerialization() throws IOException {
@Test
void parametersSerialization() throws IOException {
LoadFlowParameters lfParameters = LoadFlowParameters.load(platformConfig);
lfParameters.setNoGeneratorReactiveLimits(true);
lfParameters.setUseReactiveLimits(false);
lfParameters.setPhaseShifterRegulationOn(false);

DynaFlowParameters dynaFlowParameters = new DynaFlowParameters();
dynaFlowParameters.setSvcRegulationOn(true);
dynaFlowParameters.setShuntRegulationOn(false);
dynaFlowParameters.setAutomaticSlackBusOn(true);
dynaFlowParameters.setDsoVoltageLevel(32.4);
dynaFlowParameters.setActivePowerCompensation(ActivePowerCompensation.P);
dynaFlowParameters.setSettingPath("path/to/settingFile");
dynaFlowParameters.setAssemblingPath("path/to/assemblingFile");
dynaFlowParameters.setStartTime(0.);
dynaFlowParameters.setStopTime(100.);
dynaFlowParameters.setPrecision(0.);
dynaFlowParameters.setTimeOfEvent(10.);
dynaFlowParameters.setChosenOutputs(Collections.singletonList(OutputTypes.STEADYSTATE.name()));
dynaFlowParameters.setTimeStep(2.6);
dynaFlowParameters.setStartingPointMode(StartingPointMode.WARM);
dynaFlowParameters.setMergeLoads(false);
DynaFlowParameters dynaFlowParameters = new DynaFlowParameters()
.setSvcRegulationOn(true)
.setShuntRegulationOn(false)
.setAutomaticSlackBusOn(true)
.setDsoVoltageLevel(32.4)
.setActivePowerCompensation(ActivePowerCompensation.P)
.setSettingPath("path/to/settingFile")
.setAssemblingPath("path/to/assemblingFile")
.setStartTime(0.)
.setStopTime(100.)
.setPrecision(0.)
.setTimeOfEvent(10.)
.setChosenOutputs(Collections.singletonList(OutputTypes.STEADYSTATE.name()))
.setTimeStep(2.6)
.setStartingPointMode(StartingPointMode.WARM)
.setMergeLoads(false);
lfParameters.addExtension(DynaFlowParameters.class, dynaFlowParameters);

Path workingDir = fileSystem.getPath("dynaflow/workingDir");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

import static com.powsybl.commons.test.ComparisonUtils.compareXml;
import static com.powsybl.dynaflow.DynaFlowConstants.*;
import static com.powsybl.loadflow.LoadFlowResult.Status.FAILED;
import static com.powsybl.loadflow.LoadFlowResult.Status.FULLY_CONVERGED;
import static org.junit.jupiter.api.Assertions.*;

/**
Expand Down Expand Up @@ -134,7 +136,7 @@ void testWithoutMergeLoads() throws Exception {
ComputationManager computationManager = new LocalComputationManager(new LocalComputationConfig(fileSystem.getPath("/working-dir"), 1), commandExecutor, ForkJoinPool.commonPool());
LoadFlowResult result = dynaFlowSimulation.run(network, computationManager, params);
assertNotNull(result);
assertTrue(result.isOk());
assertEquals(FULLY_CONVERGED, result.getStatus());

InputStream pReferenceOutput = getClass().getResourceAsStream("/output.xiidm");
Network expectedNetwork = NetworkSerDe.read(pReferenceOutput);
Expand All @@ -155,7 +157,7 @@ void testWithMergeLoads() throws Exception {
ComputationManager computationManager = new LocalComputationManager(new LocalComputationConfig(fileSystem.getPath("/working-dir"), 1), commandExecutor, ForkJoinPool.commonPool());
LoadFlowResult result = dynaFlowSimulation.run(network, computationManager, params);
assertNotNull(result);
assertTrue(result.isOk());
assertEquals(FULLY_CONVERGED, result.getStatus());

InputStream pReferenceOutput = getClass().getResourceAsStream("/output.xiidm");
Network expectedNetwork = NetworkSerDe.read(pReferenceOutput);
Expand All @@ -175,7 +177,7 @@ void testFail() throws Exception {
ComputationManager computationManager = new LocalComputationManager(new LocalComputationConfig(fileSystem.getPath("/working-dir"), 1), commandExecutor, ForkJoinPool.commonPool());
LoadFlowResult result = dynaFlowSimulation.run(network, computationManager, params);
assertNotNull(result);
assertFalse(result.isOk());
assertEquals(FAILED, result.getStatus());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,24 +69,24 @@ void roundTripParameters() throws IOException {
InMemoryPlatformConfig platformConfig = new InMemoryPlatformConfig(fileSystem);

LoadFlowParameters parameters = LoadFlowParameters.load(platformConfig);
parameters.setNoGeneratorReactiveLimits(true);
parameters.setUseReactiveLimits(false);
parameters.setPhaseShifterRegulationOn(false);

DynaFlowParameters params = new DynaFlowParameters();
params.setSvcRegulationOn(true);
params.setShuntRegulationOn(false);
params.setAutomaticSlackBusOn(true);
params.setDsoVoltageLevel(54.23);
params.setActivePowerCompensation(DynaFlowConstants.ActivePowerCompensation.P);
params.setSettingPath("path/to/settingFile");
params.setAssemblingPath("path/to/assemblingFile");
params.setStartTime(0.);
params.setStopTime(100.);
params.setPrecision(0.);
params.setTimeOfEvent(10.);
params.setChosenOutputs(Collections.singletonList(DynaFlowConstants.OutputTypes.STEADYSTATE.name()));
params.setTimeStep(2.6);
params.setStartingPointMode(DynaFlowConstants.StartingPointMode.WARM);
DynaFlowParameters params = new DynaFlowParameters()
.setSvcRegulationOn(true)
.setShuntRegulationOn(false)
.setAutomaticSlackBusOn(true)
.setDsoVoltageLevel(54.23)
.setActivePowerCompensation(DynaFlowConstants.ActivePowerCompensation.P)
.setSettingPath("path/to/settingFile")
.setAssemblingPath("path/to/assemblingFile")
.setStartTime(0.)
.setStopTime(100.)
.setPrecision(0.)
.setTimeOfEvent(10.)
.setChosenOutputs(Collections.singletonList(DynaFlowConstants.OutputTypes.STEADYSTATE.name()))
.setTimeStep(2.6)
.setStartingPointMode(DynaFlowConstants.StartingPointMode.WARM);

parameters.addExtension(DynaFlowParameters.class, params);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/
package com.powsybl.dynawaltz.dsl

import com.powsybl.commons.report.ReportNode;
import com.powsybl.commons.report.ReportNode

/**
* @author Laurent Issertial {@literal <laurent.issertial at rte-france.com>}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private static Stream<Arguments> provideFileError() {
private List<CurveGroovyExtension> validateGroovyExtension() {
List<CurveGroovyExtension> extensions = GroovyExtension.find(CurveGroovyExtension.class, DynaWaltzProvider.NAME);
assertEquals(1, extensions.size());
assertTrue(extensions.get(0) instanceof DynaWaltzCurveGroovyExtension);
assertInstanceOf(DynaWaltzCurveGroovyExtension.class, extensions.get(0));
return extensions;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ faultTime should be strictly positive (0.0)
'staticId' field value 'SVC2' not found for equipment type(s) GENERATOR/LOAD
'deltaP' field is not set
Model Step_SVC2 cannot be instantiated
"""),
"""),
Arguments.of("/eventWarnings/missingDisconnectionEquipment.groovy", EurostagTutorialExample1Factory.create(),
"""
+ DSL tests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.powsybl.commons.json.JsonUtil;

import java.io.IOException;
import java.util.*;

import static com.fasterxml.jackson.core.JsonToken.VALUE_STRING;

/**
* @author Laurent Issertial {@literal <laurent.issertial at rte-france.com>}
*/
Expand All @@ -32,69 +31,60 @@ public Map<String, ModelConfigs> deserialize(JsonParser parser, DeserializationC
while (parser.nextToken() != JsonToken.END_OBJECT) {
String category = parser.getCurrentName();
parser.nextToken();
configMap.put(category, deserializeModelConfigs(parser));
configMap.put(category, parseModelConfigs(parser));
}
return configMap;
}

private ModelConfigs deserializeModelConfigs(JsonParser parser) throws IOException {
String defaultLib = null;
Map<String, ModelConfig> libs = null;
while (parser.nextToken() != JsonToken.END_OBJECT) {
switch (parser.getCurrentName()) {
case "defaultLib":
defaultLib = parser.getValueAsString();
break;
case "libs":
libs = deserializeLibsMap(parser);
break;
default:
throw new IllegalStateException("Unexpected field: " + parser.getCurrentName());
private static ModelConfigs parseModelConfigs(JsonParser parser) {
var parsingContext = new Object() {
String defaultLib = null;
final Map<String, ModelConfig> libs = new HashMap<>();
};
JsonUtil.parseObject(parser, name ->
switch (name) {
case "defaultLib" -> {
parsingContext.defaultLib = parser.nextTextValue();
yield true;
}
case "libs" -> {
JsonUtil.parseObjectArray(parser, mc -> parsingContext.libs.put(mc.name(), mc), ModelConfigsJsonDeserializer::parseModelConfig);
yield true;
}
default -> false;
}
}
return new ModelConfigs(libs, defaultLib);
);
return new ModelConfigs(parsingContext.libs, parsingContext.defaultLib);
}

private Map<String, ModelConfig> deserializeLibsMap(JsonParser parser) throws IOException {
Map<String, ModelConfig> libs = new HashMap<>();
while (parser.nextToken() != JsonToken.END_ARRAY) {
parser.nextToken();
private static ModelConfig parseModelConfig(JsonParser parser) {
var parsingContext = new Object() {
String lib = null;
String alias = null;
String internalModelPrefix = null;
List<String> properties = Collections.emptyList();
while (parser.nextToken() != JsonToken.END_OBJECT) {
switch (parser.getCurrentName()) {
case "lib":
lib = parser.getValueAsString();
break;
case "properties":
properties = deserializeProperties(parser);
break;
case "internalModelPrefix":
internalModelPrefix = parser.getValueAsString();
break;
case "alias":
alias = parser.getValueAsString();
break;
default:
throw new IllegalStateException("Unexpected field: " + parser.getCurrentName());
};
JsonUtil.parseObject(parser, name ->
switch (parser.getCurrentName()) {
case "lib" -> {
parsingContext.lib = parser.nextTextValue();
yield true;
}
case "properties" -> {
parsingContext.properties = JsonUtil.parseStringArray(parser);
yield true;
}
case "internalModelPrefix" -> {
parsingContext.internalModelPrefix = parser.nextTextValue();
yield true;
}
case "alias" -> {
parsingContext.alias = parser.nextTextValue();
yield true;
}
default -> false;
}
ModelConfig modelConfig = new ModelConfig(lib, alias, internalModelPrefix, properties);
libs.put(modelConfig.name(), modelConfig);
}
return libs;
}

private List<String> deserializeProperties(JsonParser parser) throws IOException {
List<String> properties = new ArrayList<>();
JsonToken token;
while ((token = parser.nextToken()) != JsonToken.END_ARRAY) {
if (token == VALUE_STRING) {
properties.add(parser.getValueAsString().toUpperCase());
}
}
return properties;
);
return new ModelConfig(parsingContext.lib, parsingContext.alias, parsingContext.internalModelPrefix, parsingContext.properties);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ public <T extends Model> T getDefaultModel(Identifiable<?> equipment, Class<T> c
return connectableClass.cast(defaultModel);
}
if (throwException) {
throw new PowsyblException("Default model " + defaultModel.getClass().getSimpleName() + " does not implement " + connectableClass.getSimpleName() + " interface");
throw new PowsyblException("Default model " + defaultModel.getClass().getSimpleName() + " for " + equipment.getId() + " does not implement " + connectableClass.getSimpleName() + " interface");
} else {
LOGGER.warn("Default model {} does not implement {} interface", defaultModel.getClass().getSimpleName(), connectableClass.getSimpleName());
LOGGER.warn("Default model {} for {} does not implement {} interface", defaultModel.getClass().getSimpleName(), equipment.getId(), connectableClass.getSimpleName());
return null;
}
}
Expand Down
Loading

0 comments on commit fb8d952

Please sign in to comment.