diff --git a/Jenkinsfile b/Jenkinsfile index 46e3837dd8..5abc76444c 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -426,12 +426,6 @@ def publishReports(String relativeProjectDir) { // publish scalatest reports for main project only (currently the only one with scala sources!) publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/tests/scalatest', reportFiles: 'index.html', reportName: "${relativeProjectDir}_scala_tests_report", reportTitles: '']) - // publish scapegoat src report for main project only - publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/scapegoat/src', reportFiles: 'scapegoat.html', reportName: "${relativeProjectDir}_scapegoat_src_report", reportTitles: '']) - - // publish scapegoat testsrc report for main project only - publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/scapegoat/testsrc', reportFiles: 'scapegoat.html', reportName: "${relativeProjectDir}_scapegoat_testsrc_report", reportTitles: '']) - // scoverage report dir publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/scoverageTest', reportFiles: 'scoverage.xml', reportName: "${relativeProjectDir}_scoverage_report", reportTitles: '']) } diff --git a/build.gradle b/build.gradle index 9d2e38be0b..e8a43a20e8 100644 --- a/build.gradle +++ b/build.gradle @@ -23,13 +23,12 @@ ext { //version (changing these should be considered thoroughly!) javaVersion = JavaVersion.VERSION_17 - scalaVersion = '2.13' - scalaBinaryVersion = '2.13.12' + scalaVersion = '3' + scalaBinaryVersion = '3.3.1' pekkoVersion = '1.0.1' jtsVersion = '1.19.0' confluentKafkaVersion = '7.4.0' tscfgVersion = '1.0.2' - scapegoatVersion = '2.1.3' testContainerVersion = '0.41.0' @@ -121,18 +120,18 @@ dependencies { /* --- Scala libs --- */ /* CORE Scala */ - implementation "org.scala-lang:scala-library:${scalaBinaryVersion}" + implementation "org.scala-lang:scala3-library_3:${scalaBinaryVersion}" /* CORE Pekko */ - implementation "org.apache.pekko:pekko-actor_${scalaVersion}:${pekkoVersion}" - implementation "org.apache.pekko:pekko-actor-typed_${scalaVersion}:${pekkoVersion}" - implementation "org.apache.pekko:pekko-slf4j_${scalaVersion}:${pekkoVersion}" - implementation "org.apache.pekko:pekko-connectors-csv_${scalaVersion}:${pekkoVersion}" + implementation "org.apache.pekko:pekko-actor_3:${pekkoVersion}" + implementation "org.apache.pekko:pekko-actor-typed_3:${pekkoVersion}" + implementation "org.apache.pekko:pekko-slf4j_3:${pekkoVersion}" + implementation "org.apache.pekko:pekko-connectors-csv_3:${pekkoVersion}" /* config */ implementation 'com.typesafe:config:1.4.3' implementation "com.github.carueda:tscfg_2.13:$tscfgVersion" - implementation "com.github.scopt:scopt_${scalaVersion}:4.1.0" // cmd args parser + implementation "com.github.scopt:scopt_3:4.1.0" // cmd args parser // JTS implementation ("org.locationtech.jts:jts-core:${jtsVersion}"){ @@ -140,14 +139,10 @@ dependencies { } implementation "org.locationtech.jts.io:jts-io-common:${jtsVersion}" - /* Scala compiler plugin for static code analysis */ - implementation "com.sksamuel.scapegoat:scalac-scapegoat-plugin_${scalaBinaryVersion}:${scapegoatVersion}" - scalaCompilerPlugin "com.sksamuel.scapegoat:scalac-scapegoat-plugin_${scalaBinaryVersion}:${scapegoatVersion}" - /* Kafka */ implementation "org.apache.kafka:kafka-clients:${confluentKafkaVersion}-ccs" implementation "io.confluent:kafka-streams-avro-serde:${confluentKafkaVersion}" - implementation "com.sksamuel.avro4s:avro4s-core_${scalaVersion}:4.1.1" + implementation "com.sksamuel.avro4s:avro4s-core_${scalaVersion}:5.0.6" implementation 'org.apache.commons:commons-math3:3.6.1' // apache commons math3 implementation 'org.apache.poi:poi-ooxml:5.2.5' // used for FilenameUtils @@ -185,30 +180,6 @@ shadowJar { archiveBaseName.set('simona') } - - -// scapegoat hook configuration -// https://github.com/sksamuel/scapegoat -// using compileScala instead of tasks.withType(ScalaCompile) prevents applying scapegoat to scala test classes -// see https://docs.gradle.org/current/userguide/scala_plugin.html#sec:configure_scala_classpath for details -tasks.withType(ScalaCompile) { - scalaCompileOptions.additionalParameters = [ - "-Xplugin:" + configurations.scalaCompilerPlugin.asPath, - "-P:scapegoat:dataDir:" + buildDir + "/reports/scapegoat/src/", - "-P:scapegoat:disabledInspections:VariableShadowing", - "-P:scapegoat:ignoredFiles:.*/SimonaConfig.scala" // see scapegoat-sbt page for this param - ] -} - -// separate scapegoat report for test classes -compileTestScala { - scalaCompileOptions.additionalParameters = [ - "-Xplugin:" + configurations.scalaCompilerPlugin.asPath, - "-P:scapegoat:dataDir:" + buildDir + "/reports/scapegoat/testsrc/", - "-P:scapegoat:disabledInspections:VariableShadowing" - ] -} - task printVersion { doLast { println project.version diff --git a/gradle/scripts/scoverage.gradle b/gradle/scripts/scoverage.gradle index 0a2e0157e8..5fd9598f90 100644 --- a/gradle/scripts/scoverage.gradle +++ b/gradle/scripts/scoverage.gradle @@ -4,7 +4,7 @@ scoverage { scoverageVersion = "2.0.11" - scoverageScalaVersion = scalaBinaryVersion + scoverageScalaVersion // defaults to the detected scala version coverageOutputHTML = false coverageOutputXML = true coverageOutputCobertura = false diff --git a/gradle/scripts/sonarqube.gradle b/gradle/scripts/sonarqube.gradle index 80a9db4fd1..4ffda4c6c5 100644 --- a/gradle/scripts/sonarqube.gradle +++ b/gradle/scripts/sonarqube.gradle @@ -16,10 +16,6 @@ sonarqube { property 'sonar.junit.reportPaths', [ 'build/test-results/test'] // Comma-delimited list of paths to Surefire XML-format reports. // unit tests reports dirs - // scapegoat report dir - property "sonar.scala.scapegoat.reportPaths", [ - "build/reports/scapegoat/src/scapegoat-scalastyle.xml", - "build/reports/scapegoat/testsrc/scapegoat-scalastyle.xml"] // Comma-delimited list of paths to Scapegoat reports in the Scalastyle format // scala specific stuff property 'sonar.scala.coverage.reportPaths', 'build/reports/scoverageTest/scoverage.xml' diff --git a/gradle/scripts/spotless.gradle b/gradle/scripts/spotless.gradle index 525b407e68..ee9964e6b2 100644 --- a/gradle/scripts/spotless.gradle +++ b/gradle/scripts/spotless.gradle @@ -34,7 +34,7 @@ spotless { //sets a license header, removes unused imports and formats conforming to the scala fmt formatter scala { - scalafmt() + scalafmt().configFile('scalafmt.conf') licenseHeader ie3LicHead, "package.*\\n" } diff --git a/scalafmt.conf b/scalafmt.conf new file mode 100644 index 0000000000..1b40590d20 --- /dev/null +++ b/scalafmt.conf @@ -0,0 +1,15 @@ +version = 3.7.3 +runner.dialect = scala3 + +rewrite.scala3.convertToNewSyntax = true +rewrite.scala3.removeOptionalBraces = false + + +rewrite.rules = [ + AvoidInfix, + RedundantBraces, + RedundantParens, + SortModifiers, + PreferCurlyFors, + Imports +] \ No newline at end of file diff --git a/src/main/scala/edu/ie3/simona/actor/SimonaActorNaming.scala b/src/main/scala/edu/ie3/simona/actor/SimonaActorNaming.scala index bc5b548f2f..9353b6f518 100644 --- a/src/main/scala/edu/ie3/simona/actor/SimonaActorNaming.scala +++ b/src/main/scala/edu/ie3/simona/actor/SimonaActorNaming.scala @@ -11,16 +11,11 @@ import org.apache.pekko.actor.{ActorRef, ActorRefFactory, Props} import java.util.UUID object SimonaActorNaming { - - implicit class RichActorRefFactory(private val refFactory: ActorRefFactory) - extends AnyVal { - + extension (refFactory: ActorRefFactory) def simonaActorOf(props: Props, actorId: String): ActorRef = refFactory.actorOf(props, actorName(props, actorId)) - def simonaActorOf(props: Props): ActorRef = refFactory.actorOf(props, actorName(props, simonaActorUuid)) - } /** Constructs a uuid and cuts it down to 6 digits for convenience. Although * this is dangerous as duplicates might be possible, it should be sufficient @@ -49,7 +44,7 @@ object SimonaActorNaming { * @return * the actor name based on simona conventions as string */ - def actorName(clz: Class[_], actorId: String): String = + def actorName(clz: Class[?], actorId: String): String = actorName(typeName(clz), actorId) /** Constructs an actor name based on the simona convention for actor names. @@ -82,10 +77,10 @@ object SimonaActorNaming { * @return * the type name */ - def typeName(props: Props): String = { + def typeName(props: Props): String = props.args.headOption .flatMap { - case clz: Class[_] => Some(clz) + case clz: Class[?] => Some(clz) case _ => None } .map(clz => typeName(clz)) @@ -94,14 +89,13 @@ object SimonaActorNaming { s"Cannot derive actor class from props: $props" ) ) - } /** Constructs the type name from given class. * * @return * the type name */ - def typeName(clz: Class[_]): String = + def typeName(clz: Class[?]): String = clz.getSimpleName.replace("$", "") /** Pekko prevents the usage of specific special characters as names. This diff --git a/src/main/scala/edu/ie3/simona/agent/SimonaAgent.scala b/src/main/scala/edu/ie3/simona/agent/SimonaAgent.scala index cfdd3372c3..417e6d1f8c 100644 --- a/src/main/scala/edu/ie3/simona/agent/SimonaAgent.scala +++ b/src/main/scala/edu/ie3/simona/agent/SimonaAgent.scala @@ -43,7 +43,7 @@ trait SimonaAgent[D] stay() case Event(CurrentState, _) => - goto(stateName) replying stateName + goto(stateName).replying(stateName) case event => log.error(s"Unhandled event '$event' from '${sender()}''") @@ -51,7 +51,7 @@ trait SimonaAgent[D] } def holdTick(tick: Long): Unit = { - if (_currentTick.isDefined) + if _currentTick.isDefined then throw new IllegalStateException( s"Expected both _currentTick to be 'None' but found ${_currentTick} instead, respectively." ) @@ -68,13 +68,12 @@ trait SimonaAgent[D] currentTick } - def currentTick: Long = { + def currentTick: Long = _currentTick.getOrElse( throw new RuntimeException( s"$actorName: CurrentTick has been requested, but is not set!" ) ) - } def currentTickDefined: Boolean = _currentTick.isDefined diff --git a/src/main/scala/edu/ie3/simona/agent/grid/DBFSAlgorithm.scala b/src/main/scala/edu/ie3/simona/agent/grid/DBFSAlgorithm.scala index 309fb1b7ef..45655b6a96 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/DBFSAlgorithm.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/DBFSAlgorithm.scala @@ -9,7 +9,7 @@ package edu.ie3.simona.agent.grid import org.apache.pekko.actor.typed.scaladsl.adapter.ClassicActorRefOps import org.apache.pekko.actor.{ActorRef, FSM, PoisonPill} import org.apache.pekko.pattern.{ask, pipe} -import org.apache.pekko.util.{Timeout => PekkoTimeout} +import org.apache.pekko.util.Timeout as PekkoTimeout import breeze.linalg.{DenseMatrix, DenseVector} import breeze.math.Complex import edu.ie3.datamodel.graph.SubGridGate @@ -19,12 +19,12 @@ import edu.ie3.powerflow.model.PowerFlowResult import edu.ie3.powerflow.model.PowerFlowResult.FailedPowerFlowResult.FailedNewtonRaphsonPFResult import edu.ie3.powerflow.model.PowerFlowResult.SuccessFullPowerFlowResult.ValidNewtonRaphsonPFResult import edu.ie3.powerflow.model.enums.NodeType -import edu.ie3.simona.agent.grid.GridAgent._ +import edu.ie3.simona.agent.grid.GridAgent.* import edu.ie3.simona.agent.grid.GridAgentData.{ GridAgentBaseData, PowerFlowDoneData } -import edu.ie3.simona.agent.grid.ReceivedValues._ +import edu.ie3.simona.agent.grid.ReceivedValues.* import edu.ie3.simona.agent.state.AgentState import edu.ie3.simona.agent.state.AgentState.Idle import edu.ie3.simona.agent.state.GridAgentState.{ @@ -36,16 +36,16 @@ import edu.ie3.simona.event.RuntimeEvent.PowerFlowFailed import edu.ie3.simona.exceptions.agent.DBFSAlgorithmException import edu.ie3.simona.model.grid.{NodeModel, RefSystem} import edu.ie3.simona.ontology.messages.Activation -import edu.ie3.simona.ontology.messages.PowerMessage._ +import edu.ie3.simona.ontology.messages.PowerMessage.* import edu.ie3.simona.ontology.messages.SchedulerMessage.Completion import edu.ie3.simona.ontology.messages.VoltageMessage.ProvideSlackVoltageMessage.ExchangeVoltage import edu.ie3.simona.ontology.messages.VoltageMessage.{ ProvideSlackVoltageMessage, RequestSlackVoltageMessage } -import edu.ie3.simona.util.TickUtil.TickLong +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.scala.quantities.Megavars -import edu.ie3.util.scala.quantities.SquantsUtils.RichElectricPotential +import edu.ie3.util.scala.quantities.SquantsUtils.* import squants.Each import squants.energy.Megawatts @@ -61,7 +61,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { this: GridAgent => // implicit ExecutionContext should be in scope // see https://pekko.apache.org/docs/pekko/current/futures.html - implicit val ec: ExecutionContext = context.dispatcher + given ExecutionContext = context.dispatcher when(SimulateGrid) { @@ -134,13 +134,13 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { log.debug( "{}", - if (allValuesReceived) + if allValuesReceived then "Got answers for all my requests for Slack Voltages and Power Values." else "Still waiting for answers my requests for Slack Voltages and Power Values." ) - if (gridAgentBaseData.isSuperior) { + if gridAgentBaseData.isSuperior then { goToCheckPowerDifferencesOrStay( allValuesReceived, updatedGridAgentBaseData @@ -240,9 +240,11 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { } } match { case exchangeVoltages => - stay() replying ProvideSlackVoltageMessage( - currentSweepNo, - exchangeVoltages + stay().replying( + ProvideSlackVoltageMessage( + currentSweepNo, + exchangeVoltages + ) ) } @@ -253,7 +255,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { RequestGridPowerMessage(requestSweepNo, _), gridAgentBaseData: GridAgentBaseData ) => - if (gridAgentBaseData.currentSweepNo == requestSweepNo) { + if gridAgentBaseData.currentSweepNo == requestSweepNo then { log.debug( s"Received request for grid power values for sweepNo {} before my first power flow calc. Stashing away.", requestSweepNo @@ -269,7 +271,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { self ! PrepareNextSweepTrigger(currentTick) stash() - stay() using gridAgentBaseData.copy(currentSweepNo = requestSweepNo) + stay().using(gridAgentBaseData.copy(currentSweepNo = requestSweepNo)) } // / after power flow calc for this sweepNo @@ -318,8 +320,8 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { // To model the exchanged power from the superior grid's point of view, -1 has to be multiplied. // (Inferior grid is a feed in facility to superior grid, which is negative then). Analogously for load case. ( - refSystem.pInSi(pInPu) * (-1), - refSystem.qInSi(qInPu) * (-1) + refSystem.pInSi(pInPu) * -1, + refSystem.qInSi(qInPu) * -1 ) case _ => /* TODO: As long as there are no multiple slack nodes, provide "real" power only for the slack node */ @@ -351,7 +353,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { // of having it only once in the code we put this here. Otherwise it would have to been put before EVERY // return with a valid power flow result (currently happens already in two situations) val updatedGridAgentBaseData = - if (stillPendingRequestAnswers.isEmpty) { + if stillPendingRequestAnswers.isEmpty then { gridAgentBaseData.storeSweepDataAndClearReceiveMaps( validNewtonRaphsonPFResult, gridAgentBaseData.superiorGridNodeUuids, @@ -363,20 +365,23 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { ) } - stay() replying - ProvideGridPowerMessage( - exchangePowers - ) using updatedGridAgentBaseData + stay() + .replying( + ProvideGridPowerMessage( + exchangePowers + ) + ) + .using(updatedGridAgentBaseData) case _: FailedNewtonRaphsonPFResult => - stay() replying FailedPowerFlow using gridAgentBaseData + stay().replying(FailedPowerFlow).using(gridAgentBaseData) } case None => /* It is not possible to determine, who has asked */ log.error( "I got a grid power request from a subgrid I don't know. Can't answer it properly." ) - stay() replying FailedPowerFlow using gridAgentBaseData + stay().replying(FailedPowerFlow).using(gridAgentBaseData) } // called when a grid power values request from a superior grid is received @@ -397,7 +402,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { log.debug(s"Going to {}", HandlePowerFlowCalculations) - goto(HandlePowerFlowCalculations) using gridAgentBaseData + goto(HandlePowerFlowCalculations).using(gridAgentBaseData) // last step which should includes a) information on inferior grids about finish and // b) cleanup of receiveMaps and sweepStore @@ -415,18 +420,18 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { // inform every system participant about the end of this grid simulation gridAgentBaseData.gridEnv.nodeToAssetAgents.foreach { case (_, actors) => - actors.foreach(actor => { + actors.foreach { actor => actor ! FinishGridSimulationTrigger( currentTick ) - }) + } } // notify listener about the results log.debug("Calculate results and sending the results to the listener ...") createAndSendPowerFlowResults( gridAgentBaseData, - currentTick.toDateTime(simStartTime) + currentTick.toDateTime(using simStartTime) ) // do my cleanup stuff @@ -449,7 +454,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { ) // return to Idle - goto(Idle) using cleanedGridAgentBaseData + goto(Idle).using(cleanedGridAgentBaseData) } @@ -521,10 +526,10 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { SimulateGrid ) unstashAll() // we can answer the stashed grid power requests now - goto(SimulateGrid) using powerFlowDoneData + goto(SimulateGrid).using(powerFlowDoneData) case Some(_) => // will return a future based on the `ask-pattern` which will be processed below - stay() using powerFlowDoneData + stay().using(powerFlowDoneData) } case failedNewtonRaphsonPFResult: FailedNewtonRaphsonPFResult => @@ -534,7 +539,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { "Power flow calculation before asking for updated powers did finally not converge!" ) unstashAll() // we can answer the stashed grid power requests now and report a failed power flow back - goto(SimulateGrid) using powerFlowDoneData + goto(SimulateGrid).using(powerFlowDoneData) } // handler for the future provided by `askForAssetPowers` to check if there are any changes in generation/load @@ -553,7 +558,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { case _ => false } - if (changed) { + if changed then { log.debug( "Assets have changed their exchanged power with the grid. Update nodal powers and prepare new power flow." ) @@ -577,7 +582,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { updatedGridAgentBaseData.allRequestedDataReceived log.debug( "{}", - if (readyForPowerFlow) + if readyForPowerFlow then "Got answers for all my requests for Slack Voltages and Power Values." else "Still waiting for answers my requests for Slack Voltages and Power Values." @@ -595,7 +600,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { SimulateGrid ) unstashAll() // we can answer the stashed grid power requests now - goto(SimulateGrid) using powerFlowDoneData + goto(SimulateGrid).using(powerFlowDoneData) } @@ -687,7 +692,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { PowerFlowDoneData(gridAgentBaseData, validPowerFlowResult) unstashAll() // we can answer the stashed grid power requests now - goto(SimulateGrid) using powerFlowDoneData + goto(SimulateGrid).using(powerFlowDoneData) case _ => log.debug( @@ -695,9 +700,11 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { ) // go back to simulate grid - goto(SimulateGrid) using gridAgentBaseData - .updateWithReceivedSlackVoltages(receivedSlackValues) - .copy(sweepValueStores = updatedSweepValueStore) + goto(SimulateGrid).using( + gridAgentBaseData + .updateWithReceivedSlackVoltages(receivedSlackValues) + .copy(sweepValueStores = updatedSweepValueStore) + ) } case failedNewtonRaphsonPFResult: FailedNewtonRaphsonPFResult => @@ -710,7 +717,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { "Power flow with updated slack voltage did finally not converge!" ) unstashAll() // we can answer the stashed grid power requests now and report a failed power flow back - goto(SimulateGrid) using powerFlowDoneData + goto(SimulateGrid).using(powerFlowDoneData) } @@ -766,7 +773,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { * simulation without a three winding transformer, the grid consists of only one node and we can mock the power * flow results. If there is a three winding transformer apparent, we actually have to perform power flow * calculations, as the high voltage branch of the transformer is modeled here. */ - (if (gridModel.gridComponents.transformers3w.isEmpty) { + (if gridModel.gridComponents.transformers3w.isEmpty then { val nodeData = operationPoint.map(StateData(_)) ValidNewtonRaphsonPFResult(-1, nodeData, DenseMatrix(0d, 0d)) } else { @@ -791,7 +798,8 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { case result: PowerFlowResult.FailedPowerFlowResult => result } - }) match { + }) + match { case validResult: ValidNewtonRaphsonPFResult => val updatedGridAgentBaseData: GridAgentBaseData = gridAgentBaseData @@ -804,7 +812,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { // the difference is checked @ the higher nodes of our transformers => the slack nodes // if we are either in the first backward sweep OR if the deviation is bigger as allowed, we need a second sweep - if (gridAgentBaseData.sweepValueStores.isEmpty) { + if gridAgentBaseData.sweepValueStores.isEmpty then { log.debug("Sweep value store is empty. Starting a second sweep ...") goToSimulateGridForNextSweepWith( updatedGridAgentBaseData, @@ -845,10 +853,10 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { gridAgentBaseData.powerFlowParams.maxSweepPowerDeviation (previousSweepNodePower - currentSweepNodePower).toScalaVector - .find(complex => { + .find { complex => Math.abs(complex.real) >= allowedDeviation | Math.abs(complex.imag) >= allowedDeviation - }) match { + } match { case Some(deviation) => // next sweep log.debug( "Deviation between the last two sweeps: {}", @@ -880,7 +888,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { ) self ! FinishGridSimulationTrigger(currentTick) handlePowerFlowFailure(gridAgentBaseData) - goto(SimulateGrid) using gridAgentBaseData + goto(SimulateGrid).using(gridAgentBaseData) } } @@ -905,9 +913,8 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { private def goToPowerFlowCalculationOrStay( allReceived: Boolean, gridAgentBaseData: GridAgentBaseData - ): FSM.State[AgentState, GridAgentData] = { - - if (allReceived) { + ): FSM.State[AgentState, GridAgentData] = + if allReceived then { log.debug( "All power values of inferior grids, assets + voltage superior grid slack voltages received." ) @@ -917,16 +924,18 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { gridAgentBaseData.receivedValueStore.nodeToReceivedPower.values .exists(v => v.exists(k => k._2.contains(FailedPowerFlow))) - if (powerFlowFailedSomewhereInInferior) { + if powerFlowFailedSomewhereInInferior then { log.warning("Received Failed Power Flow Result. Escalate to my parent.") unstashAll() // we want to answer the requests from our parent - stay() using PowerFlowDoneData( - gridAgentBaseData, - FailedNewtonRaphsonPFResult(-1, CalculationFailed) + stay().using( + PowerFlowDoneData( + gridAgentBaseData, + FailedNewtonRaphsonPFResult(-1, CalculationFailed) + ) ) } else { self ! DoPowerFlowTrigger(currentTick, gridAgentBaseData.currentSweepNo) - goto(HandlePowerFlowCalculations) using gridAgentBaseData + goto(HandlePowerFlowCalculations).using(gridAgentBaseData) } @@ -934,11 +943,9 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { log.debug( "Still waiting for asset or grid power values or slack voltage information of inferior grids" ) - stay() using gridAgentBaseData + stay().using(gridAgentBaseData) } - } - /** Normally only reached by the superior (dummy) agent! * * Checks if all data has been received and if yes checks if the there are @@ -965,8 +972,8 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { private def goToCheckPowerDifferencesOrStay( allReceived: Boolean, gridAgentBaseData: GridAgentBaseData - ): FSM.State[AgentState, GridAgentData] = { - if (allReceived) { + ): FSM.State[AgentState, GridAgentData] = + if allReceived then { log.debug("All power values of child assets + inferior grids received.") // if our superior grid received a FailedPowerFlow from the inferior grids it has to trigger a finish @@ -978,29 +985,28 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { actorPowerRequestResponse._2.contains(FailedPowerFlow) ) ) - if (powerFlowFailedSomewhere) { + if powerFlowFailedSomewhere then { log.warning("Power flow failed! This incident will be reported!") self ! FinishGridSimulationTrigger(currentTick) handlePowerFlowFailure(gridAgentBaseData) - goto(SimulateGrid) using gridAgentBaseData + goto(SimulateGrid).using(gridAgentBaseData) } else { self ! CheckPowerDifferencesTrigger(currentTick) - goto(CheckPowerDifferences) using gridAgentBaseData + goto(CheckPowerDifferences).using(gridAgentBaseData) } } else { log.debug( "Still waiting for asset or grid power values or slack voltage information of inferior grids" ) - stay() using gridAgentBaseData + stay().using(gridAgentBaseData) } - } private def handlePowerFlowFailure( gridAgentBaseData: GridAgentBaseData ): Unit = { environmentRefs.runtimeEventListener ! PowerFlowFailed - if (gridAgentBaseData.powerFlowParams.stopOnFailure) { + if gridAgentBaseData.powerFlowParams.stopOnFailure then { log.error("Stopping because of failed power flow.") self ! PoisonPill } @@ -1031,7 +1037,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { Some(currentTick) ) - goto(SimulateGrid) using gridAgentBaseData + goto(SimulateGrid).using(gridAgentBaseData) } @@ -1063,16 +1069,16 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { askTimeout: Duration ): Option[Future[ReceivedPowerValues]] = { - implicit val timeout: PekkoTimeout = PekkoTimeout.create(askTimeout) + given PekkoTimeout = PekkoTimeout.create(askTimeout) log.debug(s"asking assets for power values: {}", nodeToAssetAgents) - if (nodeToAssetAgents.values.flatten.nonEmpty) + if nodeToAssetAgents.values.flatten.nonEmpty then Some( Future .sequence( nodeToAssetAgents.flatten { case (nodeUuid, assetActorRefs) => - assetActorRefs.map(assetAgent => { + assetActorRefs.map { assetAgent => val (eInPu, fInPU) = sweepValueStore match { @@ -1109,14 +1115,13 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { case assetPowerUnchangedMessage: AssetPowerUnchangedMessage => (assetAgent, assetPowerUnchangedMessage) } - }) + } }.toVector ) - .map(ReceivedAssetPowerValues) + .map(ReceivedAssetPowerValues.apply) .pipeTo(self) ) - else - None + else None } /** Triggers an execution of the pekko `ask` pattern for all power values @ @@ -1139,7 +1144,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { inferiorGridGates: Seq[SubGridGate], askTimeout: Duration ): Option[Future[ReceivedPowerValues]] = { - implicit val timeout: PekkoTimeout = PekkoTimeout.create(askTimeout) + given PekkoTimeout = PekkoTimeout.create(askTimeout) log.debug( s"asking inferior grids for power values: {}", inferiorGridGates @@ -1173,7 +1178,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { } .toVector ) - .map(ReceivedGridPowerValues) + .map(ReceivedGridPowerValues.apply) .pipeTo(self) } } @@ -1198,7 +1203,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { superiorGridGates: Vector[SubGridGate], askTimeout: Duration ): Option[Future[ReceivedSlackVoltageValues]] = { - implicit val timeout: PekkoTimeout = PekkoTimeout.create(askTimeout) + given PekkoTimeout = PekkoTimeout.create(askTimeout) log.debug( s"asking superior grids for slack voltage values: {}", superiorGridGates @@ -1219,7 +1224,7 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { } .toVector ) - .map(ReceivedSlackVoltageValues) + .map(ReceivedSlackVoltageValues.apply) .pipeTo(self) } } @@ -1239,18 +1244,15 @@ trait DBFSAlgorithm extends PowerFlowSupport with GridResultsSupport { def createAndSendPowerFlowResults( gridAgentBaseData: GridAgentBaseData, currentTimestamp: ZonedDateTime - ): Unit = { + ): Unit = gridAgentBaseData.sweepValueStores.lastOption.foreach { case (_, valueStore) => notifyListener( this.createResultModels( gridAgentBaseData.gridEnv.gridModel, valueStore - )( - currentTimestamp - ) + )(using currentTimestamp) ) } - } } diff --git a/src/main/scala/edu/ie3/simona/agent/grid/GridAgent.scala b/src/main/scala/edu/ie3/simona/agent/grid/GridAgent.scala index b8677f607a..6f444c3b63 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/GridAgent.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/GridAgent.scala @@ -125,13 +125,11 @@ class GridAgent( log ) - override def postStop(): Unit = { + override def postStop(): Unit = log.debug("{} shutdown", self) - } - override def preStart(): Unit = { + override def preStart(): Unit = log.debug("{} started!", self) - } // general agent states // first fsm state of the agent @@ -148,7 +146,7 @@ class GridAgent( Some(unlockKey) ) - goto(Initializing) using gridAgentInitData + goto(Initializing).using(gridAgentInitData) } when(Initializing) { @@ -233,7 +231,7 @@ class GridAgent( Some(resolution) ) - goto(Idle) using gridAgentBaseData + goto(Idle).using(gridAgentBaseData) } when(Idle) { @@ -255,7 +253,7 @@ class GridAgent( Some(tick) ) - goto(SimulateGrid) using gridAgentBaseData + goto(SimulateGrid).using(gridAgentBaseData) case Event(StopMessage(_), data: GridAgentBaseData) => // shutdown children @@ -270,13 +268,11 @@ class GridAgent( // everything else whenUnhandled(myUnhandled()) - private def failFast(gridAgentInitData: GridAgentInitData): Unit = { - if ( - gridAgentInitData.superiorGridGates.isEmpty && gridAgentInitData.inferiorGridGates.isEmpty - ) + private def failFast(gridAgentInitData: GridAgentInitData): Unit = + if gridAgentInitData.superiorGridGates.isEmpty && gridAgentInitData.inferiorGridGates.isEmpty + then throw new GridAgentInitializationException( s"$actorName has neither superior nor inferior grids! This can either " + s"be cause by wrong subnetGate information or invalid parametrization of the simulation!" ) - } } diff --git a/src/main/scala/edu/ie3/simona/agent/grid/GridAgentController.scala b/src/main/scala/edu/ie3/simona/agent/grid/GridAgentController.scala index 9ec4aca397..c4fa118a0c 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/GridAgentController.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/GridAgentController.scala @@ -11,8 +11,8 @@ import org.apache.pekko.actor.{ActorContext, ActorRef} import org.apache.pekko.event.LoggingAdapter import com.typesafe.scalalogging.LazyLogging import edu.ie3.datamodel.models.input.container.{SubGridContainer, ThermalGrid} -import edu.ie3.datamodel.models.input.system._ -import edu.ie3.simona.actor.SimonaActorNaming._ +import edu.ie3.datamodel.models.input.system.* +import edu.ie3.simona.actor.SimonaActorNaming.* import edu.ie3.simona.agent.EnvironmentRefs import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService.{ ActorEvMovementsService, @@ -26,17 +26,17 @@ import edu.ie3.simona.agent.participant.pv.PvAgent import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.ParticipantInitializeStateData import edu.ie3.simona.agent.participant.wec.WecAgent import edu.ie3.simona.config.SimonaConfig -import edu.ie3.simona.config.SimonaConfig._ +import edu.ie3.simona.config.SimonaConfig.* import edu.ie3.simona.event.notifier.NotifierConfig import edu.ie3.simona.exceptions.agent.GridAgentInitializationException import edu.ie3.simona.ontology.messages.SchedulerMessage.ScheduleActivation import edu.ie3.simona.util.ConfigUtil -import edu.ie3.simona.util.ConfigUtil._ +import edu.ie3.simona.util.ConfigUtil.* import edu.ie3.simona.util.SimonaConstants.INIT_SIM_TICK import java.time.ZonedDateTime import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Holds all methods that should be available to a [[GridAgent]] * @@ -136,7 +136,7 @@ class GridAgentController( } } - if (notProcessedElements.nonEmpty) + if notProcessedElements.nonEmpty then log.warning( s"The following elements have been removed, " + s"as the agents are not implemented yet: $notProcessedElements" @@ -178,7 +178,7 @@ class GridAgentController( val outputConfigUtil = ConfigUtil.OutputConfigUtil(outputConfig) participants - .map(participant => { + .map { participant => val node = participant.getNode // build val actorRef = @@ -193,7 +193,7 @@ class GridAgentController( introduceAgentToEnvironment(actorRef) // return uuid to actorRef node.getUuid -> actorRef - }) + } .toSet[(UUID, ActorRef)] .groupMap(entry => entry._1)(entry => entry._2) } diff --git a/src/main/scala/edu/ie3/simona/agent/grid/GridAgentData.scala b/src/main/scala/edu/ie3/simona/agent/grid/GridAgentData.scala index 038d72cbc5..5e1b488025 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/GridAgentData.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/GridAgentData.scala @@ -35,7 +35,7 @@ object GridAgentData { /** Initial state data of the [[GridAgent]] */ - final case object GridAgentUninitializedData extends GridAgentData + object GridAgentUninitializedData extends GridAgentData /** Data that is send to the [[GridAgent]] directly after startup. It contains * the main information for initialization. This data should include all @@ -73,7 +73,7 @@ object GridAgentData { * Set of subgrid numbers of [[GridAgent]]s that don't have their request * answered, yet */ - final case class PowerFlowDoneData private ( + final case class PowerFlowDoneData( gridAgentBaseData: GridAgentBaseData, powerFlowResult: PowerFlowResult, pendingRequestAnswers: Set[Int] @@ -97,7 +97,7 @@ object GridAgentData { * be copied several times at several places for each state transition with * updated data. So be careful in adding more data on it! */ - final case object GridAgentBaseData extends GridAgentData { + object GridAgentBaseData extends GridAgentData { def apply( gridModel: GridModel, @@ -153,8 +153,7 @@ object GridAgentData { gridAgentBaseData: GridAgentBaseData, superiorGridNodeUuids: Vector[UUID], inferiorGridGates: Vector[SubGridGate] - ): GridAgentBaseData = { - + ): GridAgentBaseData = gridAgentBaseData.copy( receivedValueStore = ReceivedValuesStore.empty( gridAgentBaseData.gridEnv.nodeToAssetAgents, @@ -167,8 +166,6 @@ object GridAgentData { sweepValueStores = Map.empty[Int, SweepValueStore] ) - } - } /** The base aka default data of a [[GridAgent]]. Contains information on the @@ -188,7 +185,7 @@ object GridAgentData { * @param sweepValueStores * a value store for sweep results */ - final case class GridAgentBaseData private ( + final case class GridAgentBaseData( gridEnv: GridEnvironment, powerFlowParams: PowerFlowParams, currentSweepNo: Int, @@ -366,10 +363,8 @@ object GridAgentData { .find { case (_, receivedPowerMessages) => receivedPowerMessages.exists { case (ref, maybePowerResponse) => ref == senderRef && - (if (!replace) - maybePowerResponse.isEmpty - else - maybePowerResponse.isDefined) + (if !replace then maybePowerResponse.isEmpty + else maybePowerResponse.isDefined) } } .map { case (uuid, _) => uuid } diff --git a/src/main/scala/edu/ie3/simona/agent/grid/GridResultsSupport.scala b/src/main/scala/edu/ie3/simona/agent/grid/GridResultsSupport.scala index ecd073b1cf..c23db5d7d2 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/GridResultsSupport.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/GridResultsSupport.scala @@ -26,7 +26,7 @@ import edu.ie3.simona.model.grid.Transformer3wPowerFlowCase.{ PowerFlowCaseB, PowerFlowCaseC } -import edu.ie3.simona.model.grid._ +import edu.ie3.simona.model.grid.* import edu.ie3.util.quantities.PowerSystemUnits import edu.ie3.util.scala.quantities.QuantityUtil import squants.space.Degrees @@ -36,7 +36,7 @@ import tech.units.indriya.unit.Units import java.time.ZonedDateTime import java.util.UUID -import scala.math._ +import scala.math.* /** Trait that holds methods to convert the results of a power flow calculation * to their corresponding [[edu.ie3.datamodel.models.result.ResultEntity]] @@ -61,16 +61,16 @@ private[grid] trait GridResultsSupport { def createResultModels( grid: GridModel, sweepValueStore: SweepValueStore - )(implicit timestamp: ZonedDateTime): PowerFlowResultEvent = { + )(using timestamp: ZonedDateTime): PowerFlowResultEvent = { // no sanity check for duplicated uuid result data as we expect valid data at this point - implicit val sweepValueStoreData: Map[UUID, SweepValueStoreData] = + given sweepValueStoreData: Map[UUID, SweepValueStoreData] = sweepValueStore.sweepData .map(sweepValueStoreData => sweepValueStoreData.nodeUuid -> sweepValueStoreData ) .toMap - implicit val iNominal: ElectricCurrent = + given iNominal: ElectricCurrent = grid.mainRefSystem.nominalCurrent /* When creating node results, we have to consider two things: @@ -108,12 +108,12 @@ private[grid] trait GridResultsSupport { * @return * a set of [[LineResult]] s */ - private def buildLineResults(lines: Set[LineModel])(implicit + private def buildLineResults(lines: Set[LineModel])(using sweepValueStoreData: Map[UUID, SweepValueStoreData], iNominal: squants.ElectricCurrent, timestamp: ZonedDateTime - ): Set[LineResult] = { - lines.flatMap(lineModel => { + ): Set[LineResult] = + lines.flatMap { lineModel => sweepValueStoreData .get(lineModel.nodeAUuid) .zip(sweepValueStoreData.get(lineModel.nodeBUuid)) match { @@ -136,8 +136,7 @@ private[grid] trait GridResultsSupport { ) None } - }) - } + } /** Build instances of [[Transformer2WResult]] based on a provided set of * [[TransformerModel]] and the corresponding sweep value data @@ -155,12 +154,12 @@ private[grid] trait GridResultsSupport { * a set of [[Transformer2WResult]] s */ private def buildTransformer2wResults(transformers: Set[TransformerModel])( - implicit + using sweepValueStoreData: Map[UUID, SweepValueStoreData], iNominal: ElectricCurrent, timestamp: ZonedDateTime - ): Set[Transformer2WResult] = { - transformers.flatMap(trafo2w => { + ): Set[Transformer2WResult] = + transformers.flatMap { trafo2w => sweepValueStoreData .get(trafo2w.hvNodeUuid) .zip(sweepValueStoreData.get(trafo2w.lvNodeUuid)) match { @@ -183,8 +182,7 @@ private[grid] trait GridResultsSupport { ) None } - }) - } + } /** Build instances of [[Transformer3WResult]] based on a provided set of * [[Transformer3wModel]] and the corresponding sweep value data @@ -201,47 +199,44 @@ private[grid] trait GridResultsSupport { * @return * a set of [[PartialTransformer3wResult]] s */ - def buildTransformer3wResults(transformers3w: Set[Transformer3wModel])( - implicit + def buildTransformer3wResults(transformers3w: Set[Transformer3wModel])(using sweepValueStoreData: Map[UUID, SweepValueStoreData], iNominal: ElectricCurrent, timestamp: ZonedDateTime ): Set[PartialTransformer3wResult] = transformers3w.flatMap { trafo3w => - { - (trafo3w.powerFlowCase match { - case PowerFlowCaseA => - sweepValueStoreData - .get(trafo3w.hvNodeUuid) - .zip(sweepValueStoreData.get(trafo3w.nodeInternalUuid)) - case PowerFlowCaseB => - sweepValueStoreData - .get(trafo3w.mvNodeUuid) - .zip(sweepValueStoreData.get(trafo3w.nodeInternalUuid)) - case PowerFlowCaseC => - sweepValueStoreData - .get(trafo3w.lvNodeUuid) - .zip(sweepValueStoreData.get(trafo3w.nodeInternalUuid)) - }) match { - case Some((upperNodeStateData, internalNodeStateData)) => - Some( - calcTransformer3wResult( - trafo3w, - upperNodeStateData.stateData, - internalNodeStateData.stateData, - iNominal, - timestamp - ) - ) - case None => - log.warning( - s"Cannot find power flow result data for transformer3w {} with nodeHv {}, nodeMv {}, nodeLv {} and internalNode ${trafo3w.nodeInternalUuid}", - trafo3w.uuid, - trafo3w.hvNodeUuid, - trafo3w.mvNodeUuid, - trafo3w.lvNodeUuid + (trafo3w.powerFlowCase match { + case PowerFlowCaseA => + sweepValueStoreData + .get(trafo3w.hvNodeUuid) + .zip(sweepValueStoreData.get(trafo3w.nodeInternalUuid)) + case PowerFlowCaseB => + sweepValueStoreData + .get(trafo3w.mvNodeUuid) + .zip(sweepValueStoreData.get(trafo3w.nodeInternalUuid)) + case PowerFlowCaseC => + sweepValueStoreData + .get(trafo3w.lvNodeUuid) + .zip(sweepValueStoreData.get(trafo3w.nodeInternalUuid)) + }) match { + case Some((upperNodeStateData, internalNodeStateData)) => + Some( + calcTransformer3wResult( + trafo3w, + upperNodeStateData.stateData, + internalNodeStateData.stateData, + iNominal, + timestamp ) - None - } + ) + case None => + log.warning( + s"Cannot find power flow result data for transformer3w {} with nodeHv {}, nodeMv {}, nodeLv {} and internalNode ${trafo3w.nodeInternalUuid}", + trafo3w.uuid, + trafo3w.hvNodeUuid, + trafo3w.mvNodeUuid, + trafo3w.lvNodeUuid + ) + None } } @@ -285,14 +280,13 @@ private[grid] trait GridResultsSupport { protected def calcSwitchResult( switchModel: SwitchModel, timestamp: ZonedDateTime - ): SwitchResult = { + ): SwitchResult = /* can be adapted when https://github.com/ie3-institute/PowerSystemDataModel/issues/151 has been resolved */ new SwitchResult( timestamp, switchModel.uuid, switchModel.isClosed ) - } /** Creates an instance of [[LineResult]] based on the provided grid and power * flow result data @@ -316,9 +310,8 @@ private[grid] trait GridResultsSupport { nodeBStateData: StateData, iNominal: ElectricCurrent, timestamp: ZonedDateTime - ): LineResult = { - - if (line.isInOperation) { + ): LineResult = + if line.isInOperation then { val yij = new Complex( line.gij().value.doubleValue, line.bij().value.doubleValue @@ -352,7 +345,6 @@ private[grid] trait GridResultsSupport { QuantityUtil.zeroCompQuantity(PowerSystemUnits.DEGREE_GEOM) ) } - } /** Creates an instance of [[Transformer2WResult]] based on the provided grid * and power flow result data @@ -378,8 +370,8 @@ private[grid] trait GridResultsSupport { lvNodeStateData: StateData, iNominal: ElectricCurrent, timestamp: ZonedDateTime - ): Transformer2WResult = { - if (trafo2w.isInOperation) { + ): Transformer2WResult = + if trafo2w.isInOperation then { val (yab, yaa, ybb) = ( TransformerModel.yij(trafo2w), TransformerModel.y0(trafo2w, ConnectorPort.A), @@ -422,7 +414,6 @@ private[grid] trait GridResultsSupport { trafo2w.currentTapPos ) } - } /** Creates an instance of [[Transformer3WResult]] based on the provided grid * and power flow result data @@ -558,10 +549,8 @@ private[grid] trait GridResultsSupport { angle: Angle, dir: Double ): Angle = - if (dir < 0) - angle + Degrees(180d) - else - angle + if dir < 0 then angle + Degrees(180d) + else angle /** Calculates the electric current of a two-port element @ port i (=A) and j * (=B) based on the provided voltages @ each port and the corresponding @@ -589,12 +578,11 @@ private[grid] trait GridResultsSupport { yij: Complex, y0i: Complex, y0j: Option[Complex] = None - ): (Complex, Complex) = { + ): (Complex, Complex) = ( (uiPu - ujPu) * yij + (uiPu * y0i), (ujPu - uiPu) * yij + (ujPu * y0j.getOrElse(y0i)) ) - } } diff --git a/src/main/scala/edu/ie3/simona/agent/grid/PowerFlowSupport.scala b/src/main/scala/edu/ie3/simona/agent/grid/PowerFlowSupport.scala index afc26f47c1..315607ad17 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/PowerFlowSupport.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/PowerFlowSupport.scala @@ -16,7 +16,7 @@ import edu.ie3.powerflow.model.StartData.WithForcedStartVoltages import edu.ie3.powerflow.model.enums.NodeType import edu.ie3.simona.agent.grid.ReceivedValues.ReceivedSlackVoltageValues import edu.ie3.simona.exceptions.agent.DBFSAlgorithmException -import edu.ie3.simona.model.grid._ +import edu.ie3.simona.model.grid.* import edu.ie3.simona.ontology.messages.PowerMessage.ProvidePowerMessage import edu.ie3.simona.ontology.messages.VoltageMessage.ProvideSlackVoltageMessage.ExchangeVoltage import edu.ie3.util.scala.quantities.Kilovars @@ -76,7 +76,7 @@ trait PowerFlowSupport { val (operatingPoints, stateData) = nodes.map { nodeModel => // note: currently we only support pq nodes as we not distinguish between pq/pv nodes - // when slack emulators or pv-node assets are added this needs to be considered here - val nodeType = if (nodeModel.isSlack) NodeType.SL else NodeType.PQ + val nodeType = if nodeModel.isSlack then NodeType.SL else NodeType.PQ /* Determine the operating point for this given node */ val nodeIdx = nodeUuidToIndexMap.getOrElse( @@ -124,7 +124,7 @@ trait PowerFlowSupport { } val targetVoltage = - if (targetVoltageFromReceivedData && nodeModel.isSlack) { + if targetVoltageFromReceivedData && nodeModel.isSlack then { /* If the preset voltage is meant to be determined by means of received data and the node is a slack node * (only then there is received data), look it up and transform it */ val receivedSlackVoltage = @@ -147,8 +147,7 @@ trait PowerFlowSupport { } else { // Either the received data shall not be considered or the node is not a slack node Complex.one * - (if (!ignoreTargetVoltage) - nodeModel.vTarget.toEach + (if !ignoreTargetVoltage then nodeModel.vTarget.toEach else 1.0) } @@ -184,13 +183,12 @@ trait PowerFlowSupport { /* In case a model has more than one, set all others to PQ nodes. ATTENTION: This does not cover the power flow situation correctly! */ val adaptedOperatingPoint = operatingPoints.map { nodePreset => - if (nodePreset.nodeType == NodeType.SL) { + if nodePreset.nodeType == NodeType.SL then { // If this is the slack node we picked, leave it as a slack node. - if (nodePreset.index == slackNodeData.index) nodePreset + if nodePreset.index == slackNodeData.index then nodePreset // If it is not the one, make it a PQ node. else nodePreset.copy(nodeType = NodeType.PQ) - } else - nodePreset + } else nodePreset } ( @@ -230,7 +228,7 @@ trait PowerFlowSupport { ): (Array[PresetData], WithForcedStartVoltages) = sweepDataValues.map { sweepValueStoreData => val nodeStateData = sweepValueStoreData.stateData - val targetVoltage = if (nodeStateData.nodeType == NodeType.SL) { + val targetVoltage = if nodeStateData.nodeType == NodeType.SL then { val receivedSlackVoltage = receivedSlackValues.values .map { case (_, slackVoltageMsg) => slackVoltageMsg } .flatMap(_.nodalSlackVoltages) @@ -249,8 +247,7 @@ trait PowerFlowSupport { transformers3w, gridMainRefSystem ) - } else - Complex.one + } else Complex.one // note: target voltage will be ignored for slack node if provided ( @@ -288,7 +285,7 @@ trait PowerFlowSupport { */ private def combineOperatingPoint( operatingPoint: Array[PresetData] - ): Array[PresetData] = { + ): Array[PresetData] = operatingPoint .groupBy(_.index) .view @@ -303,7 +300,6 @@ trait PowerFlowSupport { .values .toArray .sortBy(_.index) - } /** Combines two [[PresetData]] instances to one. This is only possible if * they map to the same node index and have the same node type. @@ -381,7 +377,7 @@ trait PowerFlowSupport { gridModel: GridModel ): String = { val debugString = new mutable.StringBuilder("Power flow result: ") - validResult.nodeData.foreach(nodeStateData => { + validResult.nodeData.foreach { nodeStateData => // get node index val nodeIndex = nodeStateData.index // get nodeUUID @@ -405,7 +401,7 @@ trait PowerFlowSupport { .append(nodeStateData.voltage) .append(", |v| = ") .append(nodeStateData.voltage.abs) - }) + } debugString.toString() } @@ -432,7 +428,7 @@ trait PowerFlowSupport { transformers2w: Set[TransformerModel], transformers3w: Set[Transformer3wModel], gridRefSystem: RefSystem - ): Complex = { + ): Complex = (( transformers2w.find(_.hvNodeUuid == nodeUuid), transformers3w.find(_.nodeInternalUuid == nodeUuid) @@ -463,7 +459,6 @@ trait PowerFlowSupport { case (e: ElectricPotential, f: ElectricPotential) => toComplex(toPu(e, f, gridRefSystem)) } - } /** Transfer physical nodal voltage to correct voltage level, respecting the * transformer's voltage ratio @@ -556,12 +551,12 @@ trait PowerFlowSupport { * @return * The result of newton raphson power flow calculation */ - protected final def newtonRaphsonPF( + final protected def newtonRaphsonPF( gridModel: GridModel, maxIterations: Int, operatingPoint: Array[PresetData], slackVoltages: WithForcedStartVoltages - )(epsilons: Vector[Double]): PowerFlowResult = { + )(epsilons: Vector[Double]): PowerFlowResult = epsilons.headOption match { case Some(epsilon) => val admittanceMatrix = @@ -611,5 +606,4 @@ trait PowerFlowSupport { "ɛ is mandatory for a newton raphson power flow!" ) } - } } diff --git a/src/main/scala/edu/ie3/simona/agent/grid/ReceivedValuesStore.scala b/src/main/scala/edu/ie3/simona/agent/grid/ReceivedValuesStore.scala index 4c083629f3..f89e4933bb 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/ReceivedValuesStore.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/ReceivedValuesStore.scala @@ -39,7 +39,7 @@ import java.util.UUID * mapping of node uuids to received slack voltages from superior * [[GridAgent]] s if any */ -final case class ReceivedValuesStore private ( +final case class ReceivedValuesStore( nodeToReceivedPower: NodeToReceivedPower, nodeToReceivedSlackVoltage: NodeToReceivedSlackVoltage ) @@ -137,9 +137,8 @@ object ReceivedValuesStore { */ private def buildEmptyNodeToReceivedSlackVoltageValuesMap( superiorGridNodeUuids: Vector[UUID] - ): NodeToReceivedSlackVoltage = { + ): NodeToReceivedSlackVoltage = superiorGridNodeUuids.map(nodeId => nodeId -> None).toMap - } /** Composing method that combines [[buildEmptyNodeToReceivedPowerMap()]] and * [[buildEmptyNodeToReceivedSlackVoltageValuesMap()]] @@ -159,7 +158,7 @@ object ReceivedValuesStore { nodeToAssetAgents: Map[UUID, Set[ActorRef]], inferiorSubGridGateToActorRef: Map[SubGridGate, ActorRef], superiorGridNodeUuids: Vector[UUID] - ): (NodeToReceivedPower, NodeToReceivedSlackVoltage) = { + ): (NodeToReceivedPower, NodeToReceivedSlackVoltage) = ( buildEmptyNodeToReceivedPowerMap( nodeToAssetAgents, @@ -167,6 +166,5 @@ object ReceivedValuesStore { ), buildEmptyNodeToReceivedSlackVoltageValuesMap(superiorGridNodeUuids) ) - } } diff --git a/src/main/scala/edu/ie3/simona/agent/grid/SweepValueStore.scala b/src/main/scala/edu/ie3/simona/agent/grid/SweepValueStore.scala index dfe459fc72..4c4ac65508 100644 --- a/src/main/scala/edu/ie3/simona/agent/grid/SweepValueStore.scala +++ b/src/main/scala/edu/ie3/simona/agent/grid/SweepValueStore.scala @@ -34,7 +34,7 @@ case object SweepValueStore { * @param nodeUuid * node uuid of the sweep data */ - final case class SweepValueStoreData private ( + final case class SweepValueStoreData( nodeUuid: UUID, stateData: StateData ) @@ -57,8 +57,8 @@ case object SweepValueStore { nodes: Seq[NodeModel], nodeUuidToIndexMap: Map[UUID, Int] ): SweepValueStore = { - val sweepDataValues = nodes.foldLeft(Vector.empty[SweepValueStoreData])( - (valueStoreDataElements, node) => { + val sweepDataValues = nodes.foldLeft(Vector.empty[SweepValueStoreData]) { + (valueStoreDataElements, node) => val uuid = node.uuid val id = node.id val nodeIdxOpt = nodeUuidToIndexMap.get(uuid) @@ -74,8 +74,7 @@ case object SweepValueStore { ) valueStoreDataElements :+ SweepValueStoreData(uuid, stateData) - } - ) + } new SweepValueStore(sweepDataValues) } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgent.scala b/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgent.scala index aae1c04eab..528aaf713d 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgent.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgent.scala @@ -6,8 +6,6 @@ package edu.ie3.simona.agent.participant -import org.apache.pekko.actor.typed.scaladsl.adapter.ClassicActorRefOps -import org.apache.pekko.actor.{ActorRef, FSM} import edu.ie3.datamodel.models.input.system.SystemParticipantInput import edu.ie3.simona.agent.SimonaAgent import edu.ie3.simona.agent.grid.GridAgent.FinishGridSimulationTrigger @@ -19,16 +17,12 @@ import edu.ie3.simona.agent.participant.data.Data import edu.ie3.simona.agent.participant.data.Data.PrimaryData.PrimaryDataWithApparentPower import edu.ie3.simona.agent.participant.data.Data.{PrimaryData, SecondaryData} import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService +import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.* +import edu.ie3.simona.agent.participant.statedata.* import edu.ie3.simona.agent.participant.statedata.BaseStateData.{ FromOutsideBaseStateData, ParticipantModelBaseStateData } -import edu.ie3.simona.agent.participant.statedata.ParticipantStateData._ -import edu.ie3.simona.agent.participant.statedata.{ - BaseStateData, - DataCollectionStateData, - ParticipantStateData -} import edu.ie3.simona.agent.state.AgentState import edu.ie3.simona.agent.state.AgentState.{Idle, Uninitialized} import edu.ie3.simona.agent.state.ParticipantAgentState.{ @@ -50,6 +44,8 @@ import edu.ie3.simona.ontology.messages.services.ServiceMessage.{ } import edu.ie3.simona.util.SimonaConstants.INIT_SIM_TICK import edu.ie3.util.scala.quantities.ReactivePower +import org.apache.pekko.actor.typed.scaladsl.adapter.ClassicActorRefOps +import org.apache.pekko.actor.{ActorRef, FSM} import squants.{Dimensionless, Power} import java.time.ZonedDateTime @@ -102,15 +98,17 @@ abstract class ParticipantAgent[ initStateData.primaryServiceProxy ! PrimaryServiceRegistrationMessage( initStateData.inputModel.electricalInputModel.getUuid ) - goto(HandleInformation) using ParticipantInitializingStateData( - initStateData.inputModel, - initStateData.modelConfig, - initStateData.secondaryDataServices, - initStateData.simulationStartDate, - initStateData.simulationEndDate, - initStateData.resolution, - initStateData.requestVoltageDeviationThreshold, - initStateData.outputConfig + goto(HandleInformation).using( + ParticipantInitializingStateData( + initStateData.inputModel, + initStateData.modelConfig, + initStateData.secondaryDataServices, + initStateData.simulationStartDate, + initStateData.simulationEndDate, + initStateData.resolution, + initStateData.requestVoltageDeviationThreshold, + initStateData.outputConfig + ) ) } @@ -130,13 +128,15 @@ abstract class ParticipantAgent[ /* Remove this tick from the array of foreseen activation ticks */ val additionalActivationTicks = modelBaseStateData.additionalActivationTicks.rangeFrom(currentTick + 1) - goto(Calculate) using BaseStateData.updateBaseStateData( - modelBaseStateData, - modelBaseStateData.resultValueStore, - modelBaseStateData.requestValueStore, - modelBaseStateData.voltageValueStore, - additionalActivationTicks, - modelBaseStateData.foreseenDataTicks + goto(Calculate).using( + BaseStateData.updateBaseStateData( + modelBaseStateData, + modelBaseStateData.resultValueStore, + modelBaseStateData.requestValueStore, + modelBaseStateData.voltageValueStore, + additionalActivationTicks, + modelBaseStateData.foreseenDataTicks + ) ) case Event( @@ -266,10 +266,10 @@ abstract class ParticipantAgent[ isYetTriggered = true, currentTick, scheduler - )(stateData.baseStateData.outputConfig) + )(using stateData.baseStateData.outputConfig) case Event( - msg: ProvisionMessage[_], + msg: ProvisionMessage[?], stateData @ DataCollectionStateData( baseStateData: BaseStateData[PD], data, @@ -283,12 +283,12 @@ abstract class ParticipantAgent[ case _ => false } - if (data.contains(sender()) || unexpectedSender) { + if data.contains(sender()) || unexpectedSender then { /* Update the yet received information */ val updatedData = data + (sender() -> Some(msg.data)) /* If we have received unexpected data, we also have not been scheduled before */ - if (unexpectedSender) + if unexpectedSender then scheduler ! ScheduleActivation( self.toTyped, msg.tick, @@ -317,7 +317,7 @@ abstract class ParticipantAgent[ isYetTriggered, currentTick, scheduler - )(updatedBaseStateData.outputConfig) + )(using updatedBaseStateData.outputConfig) } else throw new IllegalStateException( s"Did not expect message from ${sender()} at tick $currentTick" @@ -327,7 +327,7 @@ abstract class ParticipantAgent[ RequestAssetPowerMessage(currentTick, _, _), DataCollectionStateData(_, data, yetTriggered) ) => - if (log.isDebugEnabled) { + if log.isDebugEnabled then { val awaitedSenders = data.filter(_._2.isEmpty).keys val yetReceivedSenders = data.filter(_._2.isDefined).map { case (actorRef, data) => s"$actorRef -> $data" @@ -339,7 +339,7 @@ abstract class ParticipantAgent[ s"$currentTick from ${sender()}", awaitedSenders, yetReceivedSenders, - if (yetTriggered) "" else "NOT" + if yetTriggered then "" else "NOT" ) } stash() @@ -383,7 +383,7 @@ abstract class ParticipantAgent[ stash() stay() - case Event(_: ProvisionMessage[_], _) | Event(Activation(_), _) => + case Event(_: ProvisionMessage[?], _) | Event(Activation(_), _) => /* I got faced to new data, also I'm not ready to handle it, yet OR I got asked to do something else, while I'm * still busy, I will put it aside and answer it later */ stash() @@ -425,7 +425,7 @@ abstract class ParticipantAgent[ def initializeParticipantForPrimaryDataReplay( inputModel: InputModelContainer[I], modelConfig: MC, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -463,7 +463,7 @@ abstract class ParticipantAgent[ def initializeParticipantForModelCalculation( inputModel: InputModelContainer[I], modelConfig: MC, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -523,13 +523,13 @@ abstract class ParticipantAgent[ yetTriggered = true ) - if (expectedSenders.nonEmpty || unforeseenPossible) { + if expectedSenders.nonEmpty || unforeseenPossible then { /* Do await provision messages in HandleInformation */ - goto(HandleInformation) using nextStateData + goto(HandleInformation).using(nextStateData) } else { /* I don't expect new data. Do a shortcut to Calculate */ self ! StartCalculationTrigger(currentTick) - goto(Calculate) using nextStateData + goto(Calculate).using(nextStateData) } } @@ -580,7 +580,7 @@ abstract class ParticipantAgent[ isYetTriggered: Boolean, tick: Long, scheduler: ActorRef - )(implicit + )(using outputConfig: NotifierConfig ): FSM.State[AgentState, ParticipantStateData[PD]] @@ -696,11 +696,11 @@ abstract class ParticipantAgent[ * Tick, the trigger belongs to */ def announceAssetPowerRequestReply( - baseStateData: BaseStateData[_], + baseStateData: BaseStateData[?], currentTick: Long, activePower: Power, reactivePower: ReactivePower - )(implicit outputConfig: NotifierConfig): Unit + )(using outputConfig: NotifierConfig): Unit /** Abstract definition to clean up agent value stores after power flow * convergence. This is necessary for agents whose results are time dependent @@ -735,9 +735,9 @@ object ParticipantAgent { * nodal voltage */ def getAndCheckNodalVoltage( - baseStateData: BaseStateData[_ <: PrimaryData], + baseStateData: BaseStateData[? <: PrimaryData], currentTick: Long - ): Dimensionless = { + ): Dimensionless = baseStateData.voltageValueStore.last(currentTick) match { case Some((_, voltage)) => voltage case None => @@ -745,5 +745,4 @@ object ParticipantAgent { "Not knowing any nodal voltage is not supposed to happen." ) } - } } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentals.scala b/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentals.scala index 9b7021865a..aee9bba09a 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentals.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentals.scala @@ -6,11 +6,6 @@ package edu.ie3.simona.agent.participant -import org.apache.pekko.actor.typed.scaladsl.adapter.ClassicActorRefOps -import org.apache.pekko.actor.{ActorRef, FSM, PoisonPill} -import org.apache.pekko.event.LoggingAdapter -import org.apache.pekko.util -import org.apache.pekko.util.Timeout import breeze.numerics.{ceil, floor, pow, sqrt} import edu.ie3.datamodel.models.input.system.SystemParticipantInput import edu.ie3.datamodel.models.result.ResultEntity @@ -29,19 +24,16 @@ import edu.ie3.simona.agent.participant.data.Data.PrimaryData.{ import edu.ie3.simona.agent.participant.data.Data.SecondaryData.DateTime import edu.ie3.simona.agent.participant.data.Data.{PrimaryData, SecondaryData} import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService +import edu.ie3.simona.agent.participant.statedata.* import edu.ie3.simona.agent.participant.statedata.BaseStateData.{ FromOutsideBaseStateData, + ModelBaseStateData, ParticipantModelBaseStateData } import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.{ CollectRegistrationConfirmMessages, InputModelContainer } -import edu.ie3.simona.agent.participant.statedata.{ - BaseStateData, - DataCollectionStateData, - ParticipantStateData -} import edu.ie3.simona.agent.state.AgentState import edu.ie3.simona.agent.state.AgentState.{Idle, Uninitialized} import edu.ie3.simona.agent.state.ParticipantAgentState.{ @@ -76,9 +68,14 @@ import edu.ie3.simona.ontology.messages.services.ServiceMessage.{ ProvisionMessage, RegistrationResponseMessage } -import edu.ie3.simona.util.TickUtil._ -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.simona.util.TickUtil.* +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.quantities.{Megavars, QuantityUtil, ReactivePower} +import org.apache.pekko.actor.typed.scaladsl.adapter.ClassicActorRefOps +import org.apache.pekko.actor.{ActorRef, FSM, PoisonPill} +import org.apache.pekko.event.LoggingAdapter +import org.apache.pekko.util +import org.apache.pekko.util.Timeout import squants.energy.Megawatts import squants.{Dimensionless, Each, Energy, Power} @@ -101,7 +98,7 @@ protected trait ParticipantAgentFundamentals[ ] extends ServiceRegistration[PD, CD, D, I, MC, M] { this: ParticipantAgent[PD, CD, D, I, MC, M] => protected val pdClassTag: ClassTag[PD] - protected implicit val timeout: util.Timeout = Timeout(10, TimeUnit.SECONDS) + protected given timeout: util.Timeout = Timeout(10, TimeUnit.SECONDS) /** Tries to extract the DateTime value from the base state data and verifies, * that it is there @@ -112,8 +109,8 @@ protected trait ParticipantAgentFundamentals[ * valid DateTime value */ def getAndCheckDateTime( - baseStateData: DataCollectionStateData[_] - ): ZonedDateTime = { + baseStateData: DataCollectionStateData[?] + ): ZonedDateTime = baseStateData.extract[DateTime]() match { case Some(dateTime) => dateTime.dateTime case None => @@ -121,12 +118,11 @@ protected trait ParticipantAgentFundamentals[ "Did not receive expected information about the date time!" ) } - } override def initializeParticipantForPrimaryDataReplay( inputModel: InputModelContainer[I], modelConfig: MC, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -151,7 +147,7 @@ protected trait ParticipantAgentFundamentals[ senderToMaybeTick._2.foreach { tick => scheduler ! Completion(self.toTyped, Some(tick)) } - goto(Idle) using stateData + goto(Idle).using(stateData) } /** Determine the needed base state data to use, when data from outside is @@ -267,7 +263,7 @@ protected trait ParticipantAgentFundamentals[ override def initializeParticipantForModelCalculation( inputModel: InputModelContainer[I], modelConfig: MC, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -293,10 +289,12 @@ protected trait ParticipantAgentFundamentals[ /* If we do have registered with secondary data providers, wait for their responses. If not, the agent does not * need additional data and therefore schedules itself for next activation. */ - if (awaitRegistrationResponsesFrom.nonEmpty) { - goto(HandleInformation) using CollectRegistrationConfirmMessages( - baseStateData, - awaitRegistrationResponsesFrom + if awaitRegistrationResponsesFrom.nonEmpty then { + goto(HandleInformation).using( + CollectRegistrationConfirmMessages( + baseStateData, + awaitRegistrationResponsesFrom + ) ) } else { /* Determine the next activation tick, create a ScheduleTriggerMessage and remove the recently triggered tick */ @@ -307,7 +305,7 @@ protected trait ParticipantAgentFundamentals[ log.debug(s"Going to {}, using {}", Idle, baseStateData) scheduler ! Completion(self.toTyped, newTick) - goto(Idle) using nextBaseStateData + goto(Idle).using(nextBaseStateData) } } catch { case _: AgentInitializationException | _: InconsistentStateException => @@ -322,7 +320,7 @@ protected trait ParticipantAgentFundamentals[ def determineModelBaseStateData( inputModel: InputModelContainer[I], modelConfig: MC, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -387,7 +385,7 @@ protected trait ParticipantAgentFundamentals[ simulationStartDate: ZonedDateTime, resolution: Long ): Long = { - if (3600L % resolution != 0) + if 3600L % resolution != 0 then throw new AgentInitializationException( "The data resolution has to be adjusted, so that an integer multiple of it fits a full hour." ) @@ -424,7 +422,7 @@ protected trait ParticipantAgentFundamentals[ val foreseenDataTicks = stateData.baseStateData.foreseenDataTicks + (sender() -> maybeNextTick) - if (remainingResponses.isEmpty) { + if remainingResponses.isEmpty then { /* All agent have responded. Determine the next to be used state data and reply completion to scheduler. */ val complementedBaseStateData = BaseStateData.updateBaseStateData( stateData.baseStateData, @@ -445,9 +443,11 @@ protected trait ParticipantAgentFundamentals[ } /* We not have yet received all responses. Wait here a bit for next messages. */ - stay() using stateData.copy( - pendingResponses = remainingResponses, - foreseenNextDataTicks = foreseenDataTicksFlattened + stay().using( + stateData.copy( + pendingResponses = remainingResponses, + foreseenNextDataTicks = foreseenDataTicksFlattened + ) ) } case RegistrationResponseMessage.RegistrationFailedMessage => @@ -481,10 +481,8 @@ protected trait ParticipantAgentFundamentals[ optTick match { case Some(tick) if msg.tick == tick => // expected data - if (actorRef == sender()) - Some(actorRef -> Some(msg.data)) - else - Some(actorRef -> None) + if actorRef == sender() then Some(actorRef -> Some(msg.data)) + else Some(actorRef -> None) case None if actorRef == sender() => // unexpected data Some(actorRef -> Some(msg.data)) @@ -499,7 +497,7 @@ protected trait ParticipantAgentFundamentals[ } /* If we have received unexpected data, we also have not been scheduled before */ - if (unexpectedSender) + if unexpectedSender then scheduler ! ScheduleActivation( self.toTyped, msg.tick, @@ -523,7 +521,7 @@ protected trait ParticipantAgentFundamentals[ expectedSenders, yetTriggered = false ) - goto(HandleInformation) using nextStateData + goto(HandleInformation).using(nextStateData) } /** Checks, if all data is available and change state accordingly. Three cases @@ -554,13 +552,13 @@ protected trait ParticipantAgentFundamentals[ isYetTriggered: Boolean, tick: Long, scheduler: ActorRef - )(implicit + )(using outputConfig: NotifierConfig - ): FSM.State[AgentState, ParticipantStateData[PD]] = { - if (!stateData.data.exists(_._2.isEmpty) && isYetTriggered) { + ): FSM.State[AgentState, ParticipantStateData[PD]] = + if !stateData.data.exists(_._2.isEmpty) && isYetTriggered then { /* We got everything we expect and we are yet triggered */ stateData.baseStateData match { - case fromOutsideBaseStateData: BaseStateData.FromOutsideBaseStateData[ + case fromOutsideBaseStateData: FromOutsideBaseStateData[ M, PD ] => @@ -607,10 +605,10 @@ protected trait ParticipantAgentFundamentals[ throw exception } - case _: BaseStateData.ModelBaseStateData[_, _, _] => + case _: ModelBaseStateData[?, ?, ?] => /* Go to calculation state and send a trigger for this to myself as well */ self ! StartCalculationTrigger(currentTick) - goto(Calculate) using stateData + goto(Calculate).using(stateData) case x => throw new IllegalStateException( s"Unsupported base state data '$x' when handling all expected incoming data" @@ -618,9 +616,8 @@ protected trait ParticipantAgentFundamentals[ } } else { /* We sill have to wait - either for data or activation */ - stay() using stateData + stay().using(stateData) } - } /** Determining the active to reactive power function to apply * @@ -635,7 +632,7 @@ protected trait ParticipantAgentFundamentals[ tick: Long, baseStateData: FromOutsideBaseStateData[M, PD] ): Power => ReactivePower = - if (baseStateData.fillUpReactivePowerWithModelFunc) { + if baseStateData.fillUpReactivePowerWithModelFunc then { /* Use the model's active to reactive power function */ val currentNodalVoltage = baseStateData.voltageValueStore @@ -644,12 +641,12 @@ protected trait ParticipantAgentFundamentals[ .getOrElse( Each(1d) ) - p: Power => + (p: Power) => baseStateData.model .activeToReactivePowerFunc( currentNodalVoltage )(p) - } else { _: Power => + } else { (_: Power) => /* Use trivial reactive power */ Megavars(0d) } @@ -664,7 +661,7 @@ protected trait ParticipantAgentFundamentals[ * A trial to get and process the needed data */ def prepareData( - data: Map[ActorRef, Option[_ <: Data]], + data: Map[ActorRef, Option[? <: Data]], reactivePowerFunction: Power => ReactivePower ): Try[PD] = data.headOption @@ -683,11 +680,11 @@ protected trait ParticipantAgentFundamentals[ Success(result) case primaryData: PrimaryData => primaryData match { - case pd: EnrichableData[_] => + case pd: EnrichableData[?] => val q = reactivePowerFunction(pd.p) val enriched = pd.add(q) - if (pdClassTag.runtimeClass.equals(enriched.getClass)) + if pdClassTag.runtimeClass.equals(enriched.getClass) then Success(enriched) else Failure( @@ -732,7 +729,7 @@ protected trait ParticipantAgentFundamentals[ releaseTick() scheduler ! Completion(self.toTyped, maybeNextTick) unstashAll() - goto(Idle) using updatedBaseStateData + goto(Idle).using(updatedBaseStateData) } /** Pop the next tick, in which the agent wishes to get triggered, build a @@ -837,7 +834,7 @@ protected trait ParticipantAgentFundamentals[ baseStateData.additionalActivationTicks.headOption.exists(_ < requestTick) val dataExpected = baseStateData.foreseenDataTicks.values.flatten.exists(_ < requestTick) - if (activationExpected || dataExpected) { + if activationExpected || dataExpected then { log.debug( s"I got a request for power from '{}' for tick '{}', but I'm still waiting for new" + s" results before this tick. Waiting with the response.", @@ -845,7 +842,7 @@ protected trait ParticipantAgentFundamentals[ requestTick ) stash() - stay() using baseStateData + stay().using(baseStateData) } else { /* Update the voltage value store */ @@ -920,7 +917,7 @@ protected trait ParticipantAgentFundamentals[ nodalVoltage: Dimensionless, lastNodalVoltage: Option[(Long, Dimensionless)] ): Option[FSM.State[AgentState, ParticipantStateData[PD]]] = { - implicit val outputConfig: NotifierConfig = + given outputConfig: NotifierConfig = baseStateData.outputConfig mostRecentRequest match { case Some((mostRecentRequestTick, latestProvidedValues)) @@ -933,30 +930,40 @@ protected trait ParticipantAgentFundamentals[ /* When data is provided from outside it is NOT altered depending on the node voltage. Send an * AssetPowerUnchangedMessage */ Some( - stay() using externalBaseStateData.copy( - voltageValueStore = voltageValueStore - ) replying AssetPowerUnchangedMessage( - latestProvidedValues.p, - latestProvidedValues.q - ) + stay() + .using( + externalBaseStateData.copy( + voltageValueStore = voltageValueStore + ) + ) + .replying( + AssetPowerUnchangedMessage( + latestProvidedValues.p, + latestProvidedValues.q + ) + ) ) case modelBaseStateData: ParticipantModelBaseStateData[PD, CD, M] => /* Check, if the last request has been made with the same nodal voltage. If not, recalculate the reactive * power. */ - implicit val puTolerance: Dimensionless = + given puTolerance: Dimensionless = Each(modelBaseStateData.requestVoltageDeviationThreshold) lastNodalVoltage match { case Some((voltageTick, lastVoltage)) if voltageTick == requestTick => - if (lastVoltage ~= nodalVoltage) { + if lastVoltage ~= nodalVoltage then { /* This is the very same request (same tick and same nodal voltage). Reply with * AssetPowerUnchangedMessage */ Some( - stay() using modelBaseStateData replying AssetPowerUnchangedMessage( - latestProvidedValues.p, - latestProvidedValues.q - ) + stay() + .using(modelBaseStateData) + .replying( + AssetPowerUnchangedMessage( + latestProvidedValues.p, + latestProvidedValues.q + ) + ) ) } else { /* If the voltage is not exactly equal, continue to determine the correct reply. */ @@ -1001,7 +1008,7 @@ protected trait ParticipantAgentFundamentals[ nodalVoltage: Dimensionless, updatedVoltageValueStore: ValueStore[Dimensionless], alternativeResult: PD - ): FSM.State[AgentState, ParticipantStateData[PD]] = { + ): FSM.State[AgentState, ParticipantStateData[PD]] = /* No fast reply possible --> Some calculations have to be made */ mostRecentRequest match { case Some((lastRequestTick, _)) if lastRequestTick > requestTick => @@ -1030,10 +1037,14 @@ protected trait ParticipantAgentFundamentals[ voltageValueStore = updatedVoltageValueStore ) - stay() using nextStateData replying AssetPowerChangedMessage( - lastResult.p, - nextReactivePower - ) + stay() + .using(nextStateData) + .replying( + AssetPowerChangedMessage( + lastResult.p, + nextReactivePower + ) + ) case unexpectedStateData => throw new IllegalStateException( s"The request reply should not be re-calculated for state data '$unexpectedStateData'" @@ -1070,7 +1081,6 @@ protected trait ParticipantAgentFundamentals[ ) } } - } /** Determine the relevant simulation results to calculate the average of * those, to answer a given request. The relevant results are those between @@ -1108,7 +1118,7 @@ protected trait ParticipantAgentFundamentals[ /* Let's see, if we got some simulation results between the first relevant simulation tick and this request's tick */ val simulationResults = resultValueStore.get(firstRelevantTick, averagingWindowEnd) - if (simulationResults.nonEmpty) { + if simulationResults.nonEmpty then { /* There is at least one simulation result. This might as well be the last simulation result before the last * request reply, which still is considered to be the last valid simulation result. */ Some( @@ -1135,7 +1145,7 @@ protected trait ParticipantAgentFundamentals[ */ private def determineTickWindow( requestTick: Long, - requestValueStore: ValueStore[_] + requestValueStore: ValueStore[?] ): (Long, Long) = requestValueStore.lastKnownTick(requestTick - 1) match { case Some(lastRequestTick) => (lastRequestTick, requestTick) @@ -1156,7 +1166,7 @@ protected trait ParticipantAgentFundamentals[ */ private def determineFirstRelevantTick( lastRequestTick: Long, - resultValueStore: ValueStore[_] + resultValueStore: ValueStore[?] ): Long = resultValueStore.lastKnownTick(lastRequestTick) match { case Some(firstRelevantDataTick) => firstRelevantDataTick @@ -1190,8 +1200,8 @@ protected trait ParticipantAgentFundamentals[ nodalVoltage: Dimensionless, voltageValueStore: ValueStore[Dimensionless], alternativeResult: PD - ): FSM.State[AgentState, ParticipantStateData[PD]] = { - if (relevantResults.relevantData.nonEmpty) { + ): FSM.State[AgentState, ParticipantStateData[PD]] = + if relevantResults.relevantData.nonEmpty then { averagePowerAndStay( baseData, relevantResults.relevantData, @@ -1213,7 +1223,6 @@ protected trait ParticipantAgentFundamentals[ voltageValueStore ) } - } /** Determines the reply result by averaging the given power values over the * queried tick frame. The next state is the very same and the agent replies @@ -1365,7 +1374,7 @@ protected trait ParticipantAgentFundamentals[ averageResult.toApparentPower match { case ApparentPower(p, q) => - stay() using nextStateData replying AssetPowerChangedMessage(p, q) + stay().using(nextStateData).replying(AssetPowerChangedMessage(p, q)) } } @@ -1408,7 +1417,7 @@ protected trait ParticipantAgentFundamentals[ baseStateData, currentTick, AccompaniedSimulationResult(result) - )(baseStateData.outputConfig) + )(using baseStateData.outputConfig) /* In this case, without secondary data, the agent has been triggered by an ActivityStartTrigger by itself, * therefore pop the next one */ @@ -1442,8 +1451,8 @@ protected trait ParticipantAgentFundamentals[ baseStateData: BaseStateData[PD], tick: Long, result: AccompaniedSimulationResult[PD] - )(implicit outputConfig: NotifierConfig): Unit = - if (outputConfig.simulationResultInfo) { + )(using outputConfig: NotifierConfig): Unit = + if outputConfig.simulationResultInfo then { notifyListener( buildResultEvent(baseStateData, tick, result.primaryData) ) @@ -1481,7 +1490,7 @@ protected trait ParticipantAgentFundamentals[ ) val updatedRelevantDataStore = baseStateData match { - case data: BaseStateData.ModelBaseStateData[_, _, _] => + case data: ModelBaseStateData[?, ?, ?] => ValueStore.updateValueStore( data.calcRelevantDateStore, currentTick, @@ -1498,7 +1507,7 @@ protected trait ParticipantAgentFundamentals[ baseStateData, currentTick, result - )(baseStateData.outputConfig) + )(using baseStateData.outputConfig) /* Update the base state data */ val baseStateDateWithUpdatedResults = @@ -1535,12 +1544,12 @@ protected trait ParticipantAgentFundamentals[ * Configuration of the output behaviour */ override def announceAssetPowerRequestReply( - baseStateData: BaseStateData[_], + baseStateData: BaseStateData[?], tick: Long, activePower: Power, reactivePower: ReactivePower - )(implicit outputConfig: NotifierConfig): Unit = - if (outputConfig.powerRequestReply) { + )(using outputConfig: NotifierConfig): Unit = + if outputConfig.powerRequestReply then { log.warning( "Writing out power request replies is currently not supported!" ) @@ -1568,9 +1577,9 @@ protected trait ParticipantAgentFundamentals[ currentTick, data.p, data.q - )(baseStateData.outputConfig) + )(using baseStateData.outputConfig) } - goto(Idle) using baseStateData + goto(Idle).using(baseStateData) } /** Determines the correct result event. @@ -1590,7 +1599,7 @@ protected trait ParticipantAgentFundamentals[ result: PD ): ParticipantResultEvent = { val uuid = baseStateData.modelUuid - val dateTime = tick.toDateTime(baseStateData.startDate) + val dateTime = tick.toDateTime(using baseStateData.startDate) ParticipantResultEvent( buildResult(uuid, dateTime, result) ) @@ -1645,9 +1654,9 @@ protected trait ParticipantAgentFundamentals[ * @return * secondary service of given type */ - protected def getService[T <: SecondaryDataService[_]]( - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]] - )(implicit tag: ClassTag[T]): ActorRef = + protected def getService[T <: SecondaryDataService[?]]( + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]] + )(using tag: ClassTag[T]): ActorRef = services .getOrElse( throw new InconsistentStateException( diff --git a/src/main/scala/edu/ie3/simona/agent/participant/ServiceRegistration.scala b/src/main/scala/edu/ie3/simona/agent/participant/ServiceRegistration.scala index d600049a27..64bfc82fa4 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/ServiceRegistration.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/ServiceRegistration.scala @@ -45,7 +45,7 @@ trait ServiceRegistration[ */ def registerForServices( inputModel: I, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]] + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]] ): Vector[ActorRef] = services .map(sources => @@ -126,7 +126,7 @@ trait ServiceRegistration[ private def registerForEvMovements( actorRef: ActorRef, inputModel: I - ): Unit = { + ): Unit = inputModel match { case evcsInput: EvcsInput => actorRef ! RegisterForEvDataMessage(evcsInput.getUuid) @@ -136,6 +136,5 @@ trait ServiceRegistration[ s"(${inputModel.getNode.getUuid}) of type ${inputModel.getClass.getName}, because only Evcs can register for this." ) } - } } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/data/Data.scala b/src/main/scala/edu/ie3/simona/agent/participant/data/Data.scala index 2bba0f0509..2663a24269 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/data/Data.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/data/Data.scala @@ -6,7 +6,7 @@ package edu.ie3.simona.agent.participant.data -import edu.ie3.datamodel.models.value._ +import edu.ie3.datamodel.models.value.* import edu.ie3.simona.agent.participant.data.Data.PrimaryData.ApparentPower import edu.ie3.util.quantities.PowerSystemUnits import edu.ie3.util.quantities.interfaces.EnergyPrice @@ -145,7 +145,7 @@ object Data { copy(q = q) } - implicit class RichValue(private val value: Value) { + extension (value: Value) def toPrimaryData: Try[PrimaryData] = value match { case hs: HeatAndSValue => @@ -235,7 +235,6 @@ object Data { ) ) } - } } /** Trait to describe data structures of secondary data, that is used by diff --git a/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgent.scala b/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgent.scala index 3814da101c..4deff33bc9 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgent.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgent.scala @@ -50,7 +50,7 @@ object EvcsAgent { ) ) - val neededServices: Vector[Class[_ <: SecondaryDataService[_]]] = Vector( + val neededServices: Vector[Class[? <: SecondaryDataService[?]]] = Vector( classOf[ActorEvMovementsService] ) } @@ -95,7 +95,7 @@ class EvcsAgent( ) => val updatedStateData = handleDepartingEvsRequest(tick, modelBaseStateData, departingEvs) - stay() using updatedStateData + stay().using(updatedStateData) } /** Determine the average result within the given tick window diff --git a/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgentFundamentals.scala b/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgentFundamentals.scala index 11da0c9bd4..de8405c27a 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgentFundamentals.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/evcs/EvcsAgentFundamentals.scala @@ -6,7 +6,6 @@ package edu.ie3.simona.agent.participant.evcs -import org.apache.pekko.actor.{ActorRef, FSM} import com.typesafe.scalalogging.LazyLogging import edu.ie3.datamodel.models.input.system.EvcsInput import edu.ie3.datamodel.models.result.system.{ @@ -38,8 +37,12 @@ import edu.ie3.simona.exceptions.agent.{ InvalidRequestException } import edu.ie3.simona.io.result.AccompaniedSimulationResult -import edu.ie3.simona.model.participant.EvcsModel import edu.ie3.simona.model.participant.EvcsModel.EvcsRelevantData +import edu.ie3.simona.model.participant.{ + CalcRelevantData, + EvcsModel, + SystemParticipant +} import edu.ie3.simona.ontology.messages.services.EvMessage.{ ArrivingEvsData, DepartingEvsResponse, @@ -49,6 +52,7 @@ import edu.ie3.simona.service.ev.ExtEvDataService.FALLBACK_EV_MOVEMENTS_STEM_DIS import edu.ie3.util.quantities.PowerSystemUnits.PU import edu.ie3.util.quantities.QuantityUtils.RichQuantityDouble import edu.ie3.util.scala.quantities.Kilovars +import org.apache.pekko.actor.{ActorRef, FSM} import squants.energy.Kilowatts import squants.{Dimensionless, Each} @@ -98,7 +102,7 @@ protected trait EvcsAgentFundamentals override def determineModelBaseStateData( inputModel: InputModelContainer[EvcsInput], modelConfig: EvcsRuntimeConfig, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, timeBin: Long, @@ -110,11 +114,10 @@ protected trait EvcsAgentFundamentals EvcsModel ] = { /* Check for needed services */ - if ( - !services.exists(serviceDefinitions => + if !services.exists(serviceDefinitions => serviceDefinitions.map(_.getClass).containsSlice(neededServices) ) - ) + then throw new AgentInitializationException( s"EvcsAgent cannot be initialized without an ev data service!" ) @@ -156,7 +159,7 @@ protected trait EvcsAgentFundamentals def baseStateDataForModelCalculation( inputModel: InputModelContainer[EvcsInput], modelConfig: EvcsRuntimeConfig, - servicesOpt: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + servicesOpt: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, timeBin: Long, @@ -251,8 +254,7 @@ protected trait EvcsAgentFundamentals collectionStateData: DataCollectionStateData[ApparentPower], currentTick: Long, scheduler: ActorRef - ): FSM.State[AgentState, ParticipantStateData[ApparentPower]] = { - + ): FSM.State[AgentState, ParticipantStateData[ApparentPower]] = collectionStateData.baseStateData match { case modelBaseStateData: ParticipantModelBaseStateData[ ApparentPower, @@ -282,7 +284,6 @@ protected trait EvcsAgentFundamentals "Cannot find a model for model calculation." ) } - } /** Returns the number of free parking lots based on the last available state * data. @@ -294,9 +295,9 @@ protected trait EvcsAgentFundamentals protected def handleFreeLotsRequest( tick: Long, modelBaseStateData: ParticipantModelBaseStateData[ - _ <: ApparentPower, - _, - _ + ? <: ApparentPower, + ?, + ? ] ): Unit = { val evServiceRef = getService[ActorEvMovementsService]( @@ -306,7 +307,7 @@ protected trait EvcsAgentFundamentals val (_, lastEvs) = getTickIntervalAndLastEvs(tick, modelBaseStateData) - val evcsModel = getEvcsModel(modelBaseStateData) + val evcsModel: EvcsModel = getEvcsModel(modelBaseStateData) evServiceRef ! FreeLotsResponse( evcsModel.uuid, @@ -349,7 +350,7 @@ protected trait EvcsAgentFundamentals validateDepartures(lastEvs, requestedDepartingEvs) - val evcsModel = getEvcsModel(modelBaseStateData) + val evcsModel: EvcsModel = getEvcsModel(modelBaseStateData) val voltage = getAndCheckNodalVoltage(modelBaseStateData, tick) @@ -378,7 +379,7 @@ protected trait EvcsAgentFundamentals currentEvs = stayingEvs ) - if (departingEvs.nonEmpty) { + if departingEvs.nonEmpty then { evServiceRef ! DepartingEvsResponse( evcsModel.uuid, departingEvs @@ -424,7 +425,7 @@ protected trait EvcsAgentFundamentals arrivingEvs: Seq[EvModel] ): FSM.State[AgentState, ParticipantStateData[ApparentPower]] = { - val evcsModel = getEvcsModel(modelBaseStateData) + val evcsModel: EvcsModel = getEvcsModel(modelBaseStateData) // retrieve the last updated set of parked EVs, which could stem from // the current tick if there were departures for this tick as well @@ -440,7 +441,7 @@ protected trait EvcsAgentFundamentals ) val updatedStateData = - if (tickInterval > 0) { + if tickInterval > 0 then { // if we haven't had any departing EVs for this tick, // this also means that we have not caught up with // calculating the current SOC @@ -509,7 +510,7 @@ protected trait EvcsAgentFundamentals * @return * Desired state change */ - private final def updateValueStoresInformListeners( + final private def updateValueStoresInformListeners( baseStateData: ParticipantModelBaseStateData[ ApparentPower, EvcsRelevantData, @@ -542,7 +543,7 @@ protected trait EvcsAgentFundamentals baseStateData, tick, AccompaniedSimulationResult(result) - )(baseStateData.outputConfig) + )(using baseStateData.outputConfig) /* Update the base state data */ baseStateData.copy( @@ -554,11 +555,11 @@ protected trait EvcsAgentFundamentals private def getTickIntervalAndLastEvs( currentTick: Long, modelBaseStateData: ParticipantModelBaseStateData[ - _ <: ApparentPower, - _, - _ + ? <: ApparentPower, + ?, + ? ] - ): (Long, Set[EvModel]) = { + ): (Long, Set[EvModel]) = modelBaseStateData.calcRelevantDateStore .last(currentTick) match { case Some((tick, EvcsRelevantData(_, evs))) => @@ -569,23 +570,20 @@ protected trait EvcsAgentFundamentals * As no evs are charging then, the tick interval should be ignored anyway. */ (FALLBACK_EV_MOVEMENTS_STEM_DISTANCE, Set.empty[EvModel]) } - } private def getEvcsModel( modelBaseStateData: ParticipantModelBaseStateData[ - _ <: ApparentPower, - _, - _ + ? <: ApparentPower, + ?, + SystemParticipant[?, ? <: ApparentPower] ] ): EvcsModel = - modelBaseStateData.model match { - case model: EvcsModel => - model + modelBaseStateData.model match + case model: EvcsModel => model case unsupportedModel => throw new InconsistentStateException( s"Wrong model: $unsupportedModel!" ) - } /** Determines the correct result. * @@ -621,14 +619,13 @@ protected trait EvcsAgentFundamentals protected def validateDepartures( lastEvs: Set[EvModel], departures: Seq[UUID] - ): Unit = { + ): Unit = departures.foreach { ev => - if (!lastEvs.exists(_.getUuid == ev)) + if !lastEvs.exists(_.getUuid == ev) then logger.warn( s"EV $ev should depart from this station (according to external simulation), but has not been parked here." ) } - } /** Checks whether provided arriving EVs are consistent with charging station * specifications and currently connected EVs. Only logs warnings, does not @@ -648,7 +645,7 @@ protected trait EvcsAgentFundamentals ): Unit = { arrivals.foreach { ev => - if (lastEvs.exists(_.getUuid == ev.getUuid)) + if lastEvs.exists(_.getUuid == ev.getUuid) then logger.warn( s"EV ${ev.getId} should arrive at this station (according to external simulation), but is already parked here." ) @@ -659,7 +656,7 @@ protected trait EvcsAgentFundamentals !lastEvs.exists(_.getUuid == ev.getUuid) } - if (newCount > chargingPoints) + if newCount > chargingPoints then logger.warn( "More EVs are parking at this station than physically possible." ) diff --git a/src/main/scala/edu/ie3/simona/agent/participant/fixedfeedin/FixedFeedInAgentFundamentals.scala b/src/main/scala/edu/ie3/simona/agent/participant/fixedfeedin/FixedFeedInAgentFundamentals.scala index 3f5717d8c6..a90d46c6b0 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/fixedfeedin/FixedFeedInAgentFundamentals.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/fixedfeedin/FixedFeedInAgentFundamentals.scala @@ -6,7 +6,6 @@ package edu.ie3.simona.agent.participant.fixedfeedin -import org.apache.pekko.actor.{ActorRef, FSM} import edu.ie3.datamodel.models.input.system.FixedFeedInInput import edu.ie3.datamodel.models.result.system.{ FixedFeedInResult, @@ -37,10 +36,11 @@ import edu.ie3.simona.exceptions.agent.{ import edu.ie3.simona.model.participant.CalcRelevantData.FixedRelevantData import edu.ie3.simona.model.participant.FixedFeedInModel import edu.ie3.simona.util.SimonaConstants -import edu.ie3.simona.util.TickUtil.RichZonedDateTime +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.quantities.PowerSystemUnits.PU import edu.ie3.util.quantities.QuantityUtils.RichQuantityDouble import edu.ie3.util.scala.quantities.ReactivePower +import org.apache.pekko.actor.{ActorRef, FSM} import squants.{Dimensionless, Each, Power} import java.time.ZonedDateTime @@ -89,7 +89,7 @@ protected trait FixedFeedInAgentFundamentals override def determineModelBaseStateData( inputModel: InputModelContainer[FixedFeedInInput], modelConfig: FixedFeedInRuntimeConfig, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -111,7 +111,8 @@ protected trait FixedFeedInAgentFundamentals /* Go and collect all ticks, in which new data will be available. Also register for * services, where needed. */ - val lastTickInSimulation = simulationEndDate.toTick(simulationStartDate) + val lastTickInSimulation = + simulationEndDate.toTick(using simulationStartDate) val dataTicks = /* As participant agents always return their last known operation point on request, it is sufficient * to let a fixed fixed in model determine it's operation point on: diff --git a/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgent.scala b/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgent.scala index 758711c3bd..d1f7e01de3 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgent.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgent.scala @@ -36,7 +36,7 @@ object HpAgent { ) ) - val neededServices: Vector[Class[_ <: SecondaryDataService[_]]] = Vector( + val neededServices: Vector[Class[? <: SecondaryDataService[?]]] = Vector( classOf[ActorWeatherService] ) } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgentFundamentals.scala b/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgentFundamentals.scala index 9e5a24cb4e..f4cd573082 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgentFundamentals.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/hp/HpAgentFundamentals.scala @@ -6,7 +6,6 @@ package edu.ie3.simona.agent.participant.hp -import org.apache.pekko.actor.{ActorRef, FSM} import edu.ie3.datamodel.models.input.system.HpInput import edu.ie3.datamodel.models.result.system.{ HpResult, @@ -44,10 +43,11 @@ import edu.ie3.simona.model.participant.HpModel import edu.ie3.simona.model.participant.HpModel.{HpRelevantData, HpState} import edu.ie3.simona.model.thermal.ThermalHouse import edu.ie3.simona.ontology.messages.services.WeatherMessage.WeatherData -import edu.ie3.simona.util.TickUtil.TickLong +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.quantities.PowerSystemUnits import edu.ie3.util.quantities.PowerSystemUnits.PU import edu.ie3.util.scala.quantities.{Megavars, ReactivePower} +import org.apache.pekko.actor.{ActorRef, FSM} import squants.energy.Megawatts import squants.{Dimensionless, Each, Power, Temperature} import tech.units.indriya.quantity.Quantities @@ -83,7 +83,7 @@ trait HpAgentFundamentals */ override val calculateModelPowerFunc: ( Long, - BaseStateData.ParticipantModelBaseStateData[ + ParticipantModelBaseStateData[ ApparentPowerAndHeat, HpRelevantData, HpModel @@ -125,7 +125,7 @@ trait HpAgentFundamentals val (result, relevantData) = collectionStateData.baseStateData match { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.model match { case hpModel: HpModel => /* extract weather data from secondary data, which should have been requested and received before */ @@ -158,14 +158,14 @@ trait HpAgentFundamentals weatherData.temp ) - val power = hpModel.calculatePower( + val power: ApparentPowerAndHeat = hpModel.calculatePower( currentTick, voltage, relevantData ) val thermalHouseResult = new ThermalHouseResult( - currentTick.toDateTime(modelBaseStateData.startDate), + currentTick.toDateTime(using modelBaseStateData.startDate), hpModel.thermalHouse.uuid, Quantities.getQuantity( power.qDot.toMegawatts, @@ -212,18 +212,18 @@ trait HpAgentFundamentals override def determineModelBaseStateData( inputModel: InputModelContainer[HpInput], modelConfig: HpRuntimeConfig, - services: Option[Vector[SecondaryDataService[_ <: Data.SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: Data.SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, requestVoltageDeviationThreshold: Double, outputConfig: NotifierConfig - ): BaseStateData.ParticipantModelBaseStateData[ + ): ParticipantModelBaseStateData[ ApparentPowerAndHeat, HpRelevantData, HpModel ] = { - if (!services.exists(_.map(_.getClass).containsSlice(neededServices))) + if !services.exists(_.map(_.getClass).containsSlice(neededServices)) then throw new AgentInitializationException( "HpAgent cannot be initialized without its needed services." ) diff --git a/src/main/scala/edu/ie3/simona/agent/participant/load/LoadAgentFundamentals.scala b/src/main/scala/edu/ie3/simona/agent/participant/load/LoadAgentFundamentals.scala index 64b37b56ae..6ef86baa05 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/load/LoadAgentFundamentals.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/load/LoadAgentFundamentals.scala @@ -6,7 +6,6 @@ package edu.ie3.simona.agent.participant.load -import org.apache.pekko.actor.{ActorRef, FSM} import edu.ie3.datamodel.models.input.system.LoadInput import edu.ie3.datamodel.models.result.system.{ LoadResult, @@ -50,11 +49,12 @@ import edu.ie3.simona.model.participant.load.{ LoadReference } import edu.ie3.simona.util.SimonaConstants -import edu.ie3.simona.util.TickUtil._ +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.quantities.PowerSystemUnits.PU import edu.ie3.util.quantities.QuantityUtils.RichQuantityDouble import edu.ie3.util.scala.OperationInterval import edu.ie3.util.scala.quantities.ReactivePower +import org.apache.pekko.actor.{ActorRef, FSM} import squants.{Dimensionless, Each, Power} import java.time.ZonedDateTime @@ -104,7 +104,7 @@ protected trait LoadAgentFundamentals[LD <: LoadRelevantData, LM <: LoadModel[ override def determineModelBaseStateData( inputModel: InputModelContainer[LoadInput], modelConfig: LoadRuntimeConfig, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -122,7 +122,8 @@ protected trait LoadAgentFundamentals[LD <: LoadRelevantData, LM <: LoadModel[ /* Go and collect all ticks, in which activation is needed in addition to the activations made by incoming data. * Also register for services, where needed. */ - val lastTickInSimulation = simulationEndDate.toTick(simulationStartDate) + val lastTickInSimulation = + simulationEndDate.toTick(using simulationStartDate) val additionalActivationTicks = model match { /* If no secondary data is needed (implicitly by fixed load model), add activation ticks for the simple model */ case fixedLoadModel: FixedLoadModel => @@ -358,7 +359,7 @@ case object LoadAgentFundamentals { ) => ApparentPower = (tick, baseStateData, voltage) => { val profileLoadModel = baseStateData.model val profileRelevantData = ProfileRelevantData( - tick.toDateTime(baseStateData.startDate) + tick.toDateTime(using baseStateData.startDate) ) profileLoadModel.calculatePower(currentTick, voltage, profileRelevantData) } @@ -396,7 +397,7 @@ case object LoadAgentFundamentals { ) => ApparentPower = (tick, baseStateData, voltage) => { val randomLoadModel = baseStateData.model val profileRelevantData = RandomRelevantData( - tick.toDateTime(baseStateData.startDate) + tick.toDateTime(using baseStateData.startDate) ) randomLoadModel.calculatePower(currentTick, voltage, profileRelevantData) } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgent.scala b/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgent.scala index d82002aaec..4d91bcc59a 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgent.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgent.scala @@ -36,7 +36,7 @@ object PvAgent { ) ) - val neededServices: Vector[Class[_ <: SecondaryDataService[_]]] = Vector( + val neededServices: Vector[Class[? <: SecondaryDataService[?]]] = Vector( classOf[ActorWeatherService] ) } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgentFundamentals.scala b/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgentFundamentals.scala index 64d955ff73..d7c4617796 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgentFundamentals.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/pv/PvAgentFundamentals.scala @@ -6,7 +6,6 @@ package edu.ie3.simona.agent.participant.pv -import org.apache.pekko.actor.{ActorRef, FSM} import edu.ie3.datamodel.models.input.system.PvInput import edu.ie3.datamodel.models.result.system.{ PvResult, @@ -42,10 +41,11 @@ import edu.ie3.simona.model.participant.PvModel import edu.ie3.simona.model.participant.PvModel.PvRelevantData import edu.ie3.simona.ontology.messages.services.WeatherMessage.WeatherData import edu.ie3.simona.service.weather.WeatherService.FALLBACK_WEATHER_STEM_DISTANCE -import edu.ie3.simona.util.TickUtil.TickLong +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.quantities.PowerSystemUnits.PU import edu.ie3.util.quantities.QuantityUtils.RichQuantityDouble import edu.ie3.util.scala.quantities.ReactivePower +import org.apache.pekko.actor.{ActorRef, FSM} import squants.{Dimensionless, Each, Power} import java.time.ZonedDateTime @@ -94,7 +94,7 @@ protected trait PvAgentFundamentals override def determineModelBaseStateData( inputModel: InputModelContainer[PvInput], modelConfig: PvRuntimeConfig, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -102,11 +102,10 @@ protected trait PvAgentFundamentals outputConfig: NotifierConfig ): ParticipantModelBaseStateData[ApparentPower, PvRelevantData, PvModel] = { /* Check for needed services */ - if ( - !services.exists(serviceDefinitions => + if !services.exists(serviceDefinitions => serviceDefinitions.map(_.getClass).containsSlice(neededServices) ) - ) + then throw new AgentInitializationException( s"PvAgent cannot be initialized without a weather service!" ) @@ -195,7 +194,7 @@ protected trait PvAgentFundamentals currentTick: Long, scheduler: ActorRef ): FSM.State[AgentState, ParticipantStateData[ApparentPower]] = { - implicit val startDateTime: ZonedDateTime = + given startDateTime: ZonedDateTime = collectionStateData.baseStateData.startDate val voltage = @@ -203,7 +202,7 @@ protected trait PvAgentFundamentals val (result, relevantData) = collectionStateData.baseStateData match { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.model match { case pvModel: PvModel => /* convert current tick to a datetime */ @@ -242,7 +241,7 @@ protected trait PvAgentFundamentals weatherData.dirIrr ) - val power = pvModel.calculatePower( + val power: ApparentPower = pvModel.calculatePower( currentTick, voltage, relevantData diff --git a/src/main/scala/edu/ie3/simona/agent/participant/statedata/BaseStateData.scala b/src/main/scala/edu/ie3/simona/agent/participant/statedata/BaseStateData.scala index a625778779..c51b40b005 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/statedata/BaseStateData.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/statedata/BaseStateData.scala @@ -6,13 +6,13 @@ package edu.ie3.simona.agent.participant.statedata -import org.apache.pekko.actor.ActorRef import edu.ie3.simona.agent.ValueStore import edu.ie3.simona.agent.participant.data.Data.PrimaryData.PrimaryDataWithApparentPower import edu.ie3.simona.agent.participant.data.Data.SecondaryData import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService import edu.ie3.simona.event.notifier.NotifierConfig import edu.ie3.simona.model.participant.{CalcRelevantData, SystemParticipant} +import org.apache.pekko.actor.ActorRef import squants.Dimensionless import java.time.ZonedDateTime @@ -89,7 +89,7 @@ object BaseStateData { trait ModelBaseStateData[ +PD <: PrimaryDataWithApparentPower[PD], CD <: CalcRelevantData, - +M <: SystemParticipant[_ <: CalcRelevantData, PD] + +M <: SystemParticipant[? <: CalcRelevantData, PD] ] extends BaseStateData[PD] { /** The physical system model @@ -98,7 +98,7 @@ object BaseStateData { /** The services, the physical model depends on */ - val services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]] + val services: Option[Vector[SecondaryDataService[? <: SecondaryData]]] /** Stores all data that are relevant to model calculation */ @@ -133,7 +133,7 @@ object BaseStateData { * Type of primary data, that the model produces */ final case class FromOutsideBaseStateData[M <: SystemParticipant[ - _ <: CalcRelevantData, + ? <: CalcRelevantData, P ], +P <: PrimaryDataWithApparentPower[P]]( model: M, @@ -188,13 +188,13 @@ object BaseStateData { final case class ParticipantModelBaseStateData[ +PD <: PrimaryDataWithApparentPower[PD], CD <: CalcRelevantData, - +M <: SystemParticipant[_ <: CalcRelevantData, PD] + +M <: SystemParticipant[? <: CalcRelevantData, PD] ]( override val startDate: ZonedDateTime, override val endDate: ZonedDateTime, override val model: M, override val services: Option[ - Vector[SecondaryDataService[_ <: SecondaryData]] + Vector[SecondaryDataService[? <: SecondaryData]] ], override val outputConfig: NotifierConfig, override val additionalActivationTicks: SortedSet[Long], @@ -239,9 +239,9 @@ object BaseStateData { updatedVoltageValueStore: ValueStore[Dimensionless], updatedAdditionalActivationTicks: SortedSet[Long], updatedForeseenTicks: Map[ActorRef, Option[Long]] - ): BaseStateData[PD] = { + ): BaseStateData[PD] = baseStateData match { - case external: FromOutsideBaseStateData[_, PD] => + case external: FromOutsideBaseStateData[?, PD] => external.copy( resultValueStore = updatedResultValueStore, requestValueStore = updatedRequestValueStore, @@ -249,7 +249,7 @@ object BaseStateData { additionalActivationTicks = updatedAdditionalActivationTicks, foreseenDataTicks = updatedForeseenTicks ) - case model: ParticipantModelBaseStateData[PD, _, _] => + case model: ParticipantModelBaseStateData[PD, ?, ?] => model.copy( resultValueStore = updatedResultValueStore, requestValueStore = updatedRequestValueStore, @@ -258,5 +258,4 @@ object BaseStateData { foreseenDataTicks = updatedForeseenTicks ) } - } } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/statedata/DataCollectionStateData.scala b/src/main/scala/edu/ie3/simona/agent/participant/statedata/DataCollectionStateData.scala index d9b7f63de2..553728f05a 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/statedata/DataCollectionStateData.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/statedata/DataCollectionStateData.scala @@ -31,7 +31,7 @@ final case class DataCollectionStateData[+PD <: PrimaryDataWithApparentPower[ PD ]]( baseStateData: BaseStateData[PD], - data: Map[ActorRef, Option[_ <: Data]], + data: Map[ActorRef, Option[? <: Data]], yetTriggered: Boolean ) extends ParticipantStateData[PD] { @@ -42,7 +42,7 @@ final case class DataCollectionStateData[+PD <: PrimaryDataWithApparentPower[ * @return * The secondary data */ - def extract[T <: Data: ClassTag](): Option[T] = { + def extract[T <: Data: ClassTag](): Option[T] = data.valuesIterator .flatMap { case Some(found: T) if classTag[T].runtimeClass.isInstance(found) => @@ -51,5 +51,4 @@ final case class DataCollectionStateData[+PD <: PrimaryDataWithApparentPower[ } .toList .headOption - } } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/statedata/ParticipantStateData.scala b/src/main/scala/edu/ie3/simona/agent/participant/statedata/ParticipantStateData.scala index d52896da0c..69f8388fa2 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/statedata/ParticipantStateData.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/statedata/ParticipantStateData.scala @@ -20,7 +20,8 @@ import java.time.ZonedDateTime /** Trait to denote all common forms of state data related to each participant * agent */ -trait ParticipantStateData[+PD <: PrimaryData] +trait ParticipantStateData[+PD <: PrimaryData]: +end ParticipantStateData object ParticipantStateData { @@ -68,7 +69,7 @@ object ParticipantStateData { inputModel: InputModelContainer[I], modelConfig: C, secondaryDataServices: Option[ - Vector[SecondaryDataService[_ <: SecondaryData]] + Vector[SecondaryDataService[? <: SecondaryData]] ], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, @@ -112,7 +113,7 @@ object ParticipantStateData { modelConfig: C, primaryServiceProxy: ActorRef, secondaryDataServices: Option[ - Vector[SecondaryDataService[_ <: SecondaryData]] + Vector[SecondaryDataService[? <: SecondaryData]] ], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, @@ -131,7 +132,7 @@ object ParticipantStateData { modelConfig: C, primaryServiceProxy: ActorRef, secondaryDataServices: Option[ - Vector[SecondaryDataService[_ <: SecondaryData]] + Vector[SecondaryDataService[? <: SecondaryData]] ], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, @@ -161,7 +162,7 @@ object ParticipantStateData { modelConfig: C, primaryServiceProxy: ActorRef, secondaryDataServices: Option[ - Vector[SecondaryDataService[_ <: SecondaryData]] + Vector[SecondaryDataService[? <: SecondaryData]] ], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, diff --git a/src/main/scala/edu/ie3/simona/agent/participant/statedata/UninitializedStateData.scala b/src/main/scala/edu/ie3/simona/agent/participant/statedata/UninitializedStateData.scala index 85700927c2..21c7b55b42 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/statedata/UninitializedStateData.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/statedata/UninitializedStateData.scala @@ -11,4 +11,5 @@ import edu.ie3.simona.agent.participant.data.Data.PrimaryData /** Properties common to all participant agents not yet initialized */ trait UninitializedStateData[+PD <: PrimaryData] - extends ParticipantStateData[PD] + extends ParticipantStateData[PD]: +end UninitializedStateData diff --git a/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgent.scala b/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgent.scala index 94a5c490a0..65e8bf737a 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgent.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgent.scala @@ -16,7 +16,7 @@ import edu.ie3.simona.agent.participant.statedata.ParticipantStateData import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.ParticipantInitializeStateData import edu.ie3.simona.config.SimonaConfig.WecRuntimeConfig import edu.ie3.simona.model.participant.WecModel -import edu.ie3.simona.model.participant.WecModel._ +import edu.ie3.simona.model.participant.WecModel.* object WecAgent { def props( @@ -36,7 +36,7 @@ object WecAgent { ) ) - val neededServices: Vector[Class[_ <: SecondaryDataService[_]]] = Vector( + val neededServices: Vector[Class[? <: SecondaryDataService[?]]] = Vector( classOf[ActorWeatherService] ) } diff --git a/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgentFundamentals.scala b/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgentFundamentals.scala index bbb9e55c6c..2989cee700 100644 --- a/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgentFundamentals.scala +++ b/src/main/scala/edu/ie3/simona/agent/participant/wec/WecAgentFundamentals.scala @@ -13,7 +13,7 @@ import edu.ie3.datamodel.models.result.system.{ WecResult } import edu.ie3.simona.agent.ValueStore -import edu.ie3.simona.agent.participant.ParticipantAgent._ +import edu.ie3.simona.agent.participant.ParticipantAgent.* import edu.ie3.simona.agent.participant.ParticipantAgentFundamentals import edu.ie3.simona.agent.participant.data.Data.PrimaryData.{ ApparentPower, @@ -21,7 +21,7 @@ import edu.ie3.simona.agent.participant.data.Data.PrimaryData.{ } import edu.ie3.simona.agent.participant.data.Data.SecondaryData import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService -import edu.ie3.simona.agent.participant.statedata.BaseStateData._ +import edu.ie3.simona.agent.participant.statedata.BaseStateData.* import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.InputModelContainer import edu.ie3.simona.agent.participant.statedata.{ DataCollectionStateData, @@ -41,7 +41,7 @@ import edu.ie3.simona.io.result.AccompaniedSimulationResult import edu.ie3.simona.model.participant.WecModel import edu.ie3.simona.model.participant.WecModel.WecRelevantData import edu.ie3.simona.ontology.messages.services.WeatherMessage.WeatherData -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.quantities.QuantityUtils.RichQuantityDouble import edu.ie3.util.scala.quantities.ReactivePower import squants.{Dimensionless, Each, Power} @@ -92,7 +92,7 @@ protected trait WecAgentFundamentals override def determineModelBaseStateData( inputModel: InputModelContainer[WecInput], modelConfig: WecRuntimeConfig, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -100,11 +100,10 @@ protected trait WecAgentFundamentals outputConfig: NotifierConfig ): ParticipantModelBaseStateData[ApparentPower, WecRelevantData, WecModel] = { /* Check for needed services */ - if ( - !services.exists(serviceDefinitions => + if !services.exists(serviceDefinitions => serviceDefinitions.map(_.getClass).containsSlice(neededServices) ) - ) + then throw new AgentInitializationException( s"$actorName cannot be initialized without a weather service!" ) @@ -201,7 +200,7 @@ protected trait WecAgentFundamentals currentTick: Long, scheduler: ActorRef ): FSM.State[AgentState, ParticipantStateData[ApparentPower]] = { - implicit val startDateTime: ZonedDateTime = + given startDateTime: ZonedDateTime = collectionStateData.baseStateData.startDate val voltage = @@ -209,7 +208,7 @@ protected trait WecAgentFundamentals val (result, relevantData) = collectionStateData.baseStateData match { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.model match { case wecModel: WecModel => /* extract weather data from secondary data, which should have been requested and received before */ diff --git a/src/main/scala/edu/ie3/simona/api/ExtSimAdapter.scala b/src/main/scala/edu/ie3/simona/api/ExtSimAdapter.scala index bce029ea33..064f8aabc6 100644 --- a/src/main/scala/edu/ie3/simona/api/ExtSimAdapter.scala +++ b/src/main/scala/edu/ie3/simona/api/ExtSimAdapter.scala @@ -15,7 +15,7 @@ import edu.ie3.simona.api.simulation.ontology.{ ActivationMessage, TerminationCompleted, TerminationMessage, - CompletionMessage => ExtCompletionMessage + CompletionMessage as ExtCompletionMessage } import edu.ie3.simona.logging.SimonaActorLogging import edu.ie3.simona.ontology.messages.SchedulerMessage.{ @@ -28,7 +28,7 @@ import edu.ie3.simona.scheduler.ScheduleLock import edu.ie3.simona.scheduler.ScheduleLock.ScheduleKey import edu.ie3.simona.util.SimonaConstants.INIT_SIM_TICK -import scala.jdk.OptionConverters._ +import scala.jdk.OptionConverters.* object ExtSimAdapter { @@ -61,12 +61,14 @@ final case class ExtSimAdapter(scheduler: ActorRef) INIT_SIM_TICK, Some(unlockKey) ) - context become receiveIdle( - ExtSimAdapterStateData(extSimAdapterData) + context.become( + receiveIdle( + ExtSimAdapterStateData(extSimAdapterData) + ) ) } - private def receiveIdle(implicit + private def receiveIdle(using stateData: ExtSimAdapterStateData ): Receive = { case Activation(tick) => @@ -78,8 +80,10 @@ final case class ExtSimAdapter(scheduler: ActorRef) tick ) - context become receiveIdle( - stateData.copy(currentTick = Some(tick)) + context.become( + receiveIdle( + stateData.copy(currentTick = Some(tick)) + ) ) case extCompl: ExtCompletionMessage => @@ -94,7 +98,7 @@ final case class ExtSimAdapter(scheduler: ActorRef) stateData.currentTick ) - context become receiveIdle(stateData.copy(currentTick = None)) + context.become(receiveIdle(stateData.copy(currentTick = None))) case scheduleDataService: ScheduleDataServiceMessage => val tick = stateData.currentTick.getOrElse( diff --git a/src/main/scala/edu/ie3/simona/config/ArgsParser.scala b/src/main/scala/edu/ie3/simona/config/ArgsParser.scala index 65c563bd80..e629ca2efd 100644 --- a/src/main/scala/edu/ie3/simona/config/ArgsParser.scala +++ b/src/main/scala/edu/ie3/simona/config/ArgsParser.scala @@ -6,15 +6,15 @@ package edu.ie3.simona.config -import com.typesafe.config.{ConfigFactory, Config => TypesafeConfig} +import com.typesafe.config.{ConfigFactory, Config as TypesafeConfig} import com.typesafe.scalalogging.LazyLogging import edu.ie3.simona.event.listener.SimonaListenerCompanion import edu.ie3.util.scala.ReflectionTools -import scopt.{OptionParser => scoptOptionParser} +import scopt.OptionParser as scoptOptionParser import java.io.File import java.nio.file.Paths -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* object ArgsParser extends LazyLogging { @@ -36,21 +36,21 @@ object ArgsParser extends LazyLogging { } // build the config parser using scopt library - private def buildParser: scoptOptionParser[Arguments] = { + private def buildParser: scoptOptionParser[Arguments] = new scoptOptionParser[Arguments]("simona") { opt[String]("config") - .action((value, args) => { + .action { (value, args) => args.copy( config = Some(parseTypesafeConfig(value)), configLocation = Option(value) ) - }) + } .validate(value => - if (value.trim.isEmpty) failure("config location cannot be empty") + if value.trim.isEmpty then failure("config location cannot be empty") else success ) .validate(value => - if (value.contains("\\")) + if value.contains("\\") then failure("wrong config path, expected: /, found: \\") else success ) @@ -79,21 +79,21 @@ object ArgsParser extends LazyLogging { opt[String]("node-host") .action((value, args) => args.copy(nodeHost = Option(value))) .validate(value => - if (value.trim.isEmpty) failure("node-host cannot be empty") + if value.trim.isEmpty then failure("node-host cannot be empty") else success ) .text("Host used to run the remote actor system") opt[String]("node-port") .action((value, args) => args.copy(nodePort = Option(value))) .validate(value => - if (value.trim.isEmpty) failure("node-port cannot be empty") + if value.trim.isEmpty then failure("node-port cannot be empty") else success ) .text("Port used to run the remote actor system") opt[String]("seed-address") .action((value, args) => args.copy(seedAddress = Option(value))) .validate(value => - if (value.trim.isEmpty) failure("seed-address cannot be empty") + if value.trim.isEmpty then failure("seed-address cannot be empty") else success ) .text( @@ -109,13 +109,12 @@ object ArgsParser extends LazyLogging { ) checkConfig(args => - if ( - args.useCluster && (args.nodeHost.isEmpty || args.nodePort.isEmpty || args.seedAddress.isEmpty) - ) + if args.useCluster && (args.nodeHost.isEmpty || args.nodePort.isEmpty || args.seedAddress.isEmpty) + then failure( "If using the cluster then node-host, node-port, and seed-address are required" ) - else if (args.useCluster && !args.useLocalWorker.getOrElse(true)) + else if args.useCluster && !args.useLocalWorker.getOrElse(true) then failure( "If using the cluster then use-local-worker MUST be true (or unprovided)" ) @@ -123,7 +122,6 @@ object ArgsParser extends LazyLogging { ) } - } private def parse( parser: scoptOptionParser[Arguments], @@ -135,12 +133,12 @@ object ArgsParser extends LazyLogging { private def parseTypesafeConfig(fileName: String): TypesafeConfig = { val file = Paths.get(fileName).toFile - if (!file.exists()) + if !file.exists() then throw new Exception(s"Missing config file on path $fileName") parseTypesafeConfig(file) } - private def parseTypesafeConfig(file: File): TypesafeConfig = { + private def parseTypesafeConfig(file: File): TypesafeConfig = ConfigFactory .parseFile(file) .withFallback( @@ -148,7 +146,6 @@ object ArgsParser extends LazyLogging { Map("simona.inputDirectory" -> file.getAbsoluteFile.getParent).asJava ) ) - } // sealed trait for cluster type sealed trait ClusterType diff --git a/src/main/scala/edu/ie3/simona/config/ConfigFailFast.scala b/src/main/scala/edu/ie3/simona/config/ConfigFailFast.scala index ab3b3895a9..37af3d9134 100644 --- a/src/main/scala/edu/ie3/simona/config/ConfigFailFast.scala +++ b/src/main/scala/edu/ie3/simona/config/ConfigFailFast.scala @@ -55,16 +55,15 @@ case object ConfigFailFast extends LazyLogging { * @param typeSafeConfig * Config to check */ - def check(typeSafeConfig: Config): Unit = { + def check(typeSafeConfig: Config): Unit = checkPekkoConfig(typeSafeConfig) - } /** Trying to get pekko config and checking it * * @param typeSafeConfig * Config to check */ - private def checkPekkoConfig(typeSafeConfig: Config): Unit = { + private def checkPekkoConfig(typeSafeConfig: Config): Unit = Try(typeSafeConfig.getConfig("pekko")) .map(pekkoConfig => checkPekkoLoggers(pekkoConfig)) match { case Failure(_: ConfigException.Missing) => @@ -78,14 +77,13 @@ case object ConfigFailFast extends LazyLogging { ) case Success(_) => } - } /** Try to check the pekko logging config * * @param typeSafeConfig * Config to check */ - private def checkPekkoLoggers(typeSafeConfig: Config): Unit = { + private def checkPekkoLoggers(typeSafeConfig: Config): Unit = Try(typeSafeConfig.getIsNull("loggers")) match { case Success(true) | Failure(_: ConfigException.Missing) => logger.warn( @@ -98,7 +96,6 @@ case object ConfigFailFast extends LazyLogging { ) case _ => } - } /** Main entrance to check a provided [[SimonaConfig]] * @@ -153,12 +150,11 @@ case object ConfigFailFast extends LazyLogging { private def checkDataSink(sink: SimonaConfig.Simona.Output.Sink): Unit = { // ensures failure if new output sinks are added to enforce adaptions of the check sink method as well val supportedSinks = Set("influxdb1x", "csv", "kafka") - if ( - !sink.productElementNames + if !sink.productElementNames .map(_.trim.toLowerCase) .toSet .equals(supportedSinks) - ) + then throw new InvalidConfigParameterException( s"Newly added sink(s) " + s"'${sink.productElementNames.map(_.toLowerCase).toSet.removedAll(supportedSinks)}' detected! " + @@ -167,20 +163,20 @@ case object ConfigFailFast extends LazyLogging { // failure if all sinks are not-configured val sinkConfigs = ReflectionTools.classFieldToVal(sink).values.map { - case o: Option[_] => o + case o: Option[?] => o case _ => throw new InvalidConfigParameterException( "All sinks in configuration must be optional!" ) } - if (sinkConfigs.forall(_.isEmpty)) + if sinkConfigs.forall(_.isEmpty) then throw new InvalidConfigParameterException( "No sink configuration found! Please ensure that at least one sink is " + s"configured! You can choose from: ${supportedSinks.mkString(", ")}." ) - if (sinkConfigs.count(_.isDefined) > 1) + if sinkConfigs.count(_.isDefined) > 1 then throw new InvalidConfigParameterException( "Multiple sink configurations are not supported! Please ensure that only " + "one sink is configured!" @@ -212,7 +208,7 @@ case object ConfigFailFast extends LazyLogging { val startDate = createDateTime(timeConfig.startDateTime) val endDate = createDateTime(timeConfig.endDateTime) - if (startDate.isAfter(endDate)) + if startDate.isAfter(endDate) then throw new InvalidConfigParameterException( s"Invalid time configuration." + s"Please ensure that the start time of the simulation is before the end time." @@ -227,10 +223,10 @@ case object ConfigFailFast extends LazyLogging { */ private def createDateTime( dateTimeString: String - ): ZonedDateTime = { - try { + ): ZonedDateTime = + try TimeUtil.withDefaults.toZonedDateTime(dateTimeString) - } catch { + catch { case e: DateTimeParseException => throw new InvalidConfigParameterException( s"Invalid dateTimeString: $dateTimeString." + @@ -238,7 +234,6 @@ case object ConfigFailFast extends LazyLogging { e ) } - } /** Checks all participant model runtime sub configuration trees * @@ -248,7 +243,7 @@ case object ConfigFailFast extends LazyLogging { private def checkParticipantRuntimeConfiguration( subConfig: SimonaConfig.Simona.Runtime.Participant ): Unit = { - if (subConfig.requestVoltageDeviationThreshold < 0) + if subConfig.requestVoltageDeviationThreshold < 0 then throw new InvalidConfigParameterException( "The participant power request voltage deviation threshold must be positive!" ) @@ -291,11 +286,10 @@ case object ConfigFailFast extends LazyLogging { */ private def checkRuntimeListenerConfiguration( listenerConfig: SimonaConfig.Simona.Runtime.Listener - ): Unit = { + ): Unit = listenerConfig.kafka.foreach(kafka => checkKafkaParams(kafka, Seq(kafka.topic)) ) - } /** Check participants's basic runtime configurations, as well as in default * as in individual configs. This comprises @@ -308,18 +302,17 @@ case object ConfigFailFast extends LazyLogging { ): Unit = { // special default config check val uuidString = defaultConfig.uuids.mkString(",") - if ( - StringUtils + if StringUtils .cleanString(uuidString) .toLowerCase != StringUtils.cleanString(defaultString).toLowerCase - ) + then logger.warn( s"You provided '$uuidString' as uuid reference for the default model config. Those references will not be considered!" ) // special individual configs check /* Check, if there are ambiguous configs and then check all configs */ - if (!CollectionUtils.isUniqueList(individualConfigs.flatMap(_.uuids))) + if !CollectionUtils.isUniqueList(individualConfigs.flatMap(_.uuids)) then throw new InvalidConfigParameterException( "The basic model configurations contain ambiguous definitions." ) @@ -330,7 +323,7 @@ case object ConfigFailFast extends LazyLogging { allConfigs.foreach { case (config, singleEntryStringOpt) => /* Checking the uuids */ - if (config.uuids.isEmpty) + if config.uuids.isEmpty then throw new InvalidConfigParameterException( "There has to be at least one identifier for each participant." ) @@ -340,9 +333,9 @@ case object ConfigFailFast extends LazyLogging { checkSingleString(singleString, config.uuids) case None => config.uuids.foreach(uuid => - try { + try UUID.fromString(uuid) - } catch { + catch { case e: IllegalArgumentException => throw new InvalidConfigParameterException( s"The UUID '$uuid' cannot be parsed as it is invalid.", @@ -353,7 +346,7 @@ case object ConfigFailFast extends LazyLogging { } // check for scaling - if (config.scaling < 0) + if config.scaling < 0 then throw new InvalidConfigParameterException( s"The scaling factor for system participants with UUID '${config.uuids.mkString(",")}' may not be negative." ) @@ -371,20 +364,19 @@ case object ConfigFailFast extends LazyLogging { singleString: String, uuids: List[String] ): Unit = { - if (uuids.toVector.size != 1) + if uuids.toVector.size != 1 then throw new InvalidConfigParameterException( "The list of UUIDs is supposed to only have one entry!" ) uuids.headOption match { case Some(singleEntry) => - if ( - StringUtils + if StringUtils .cleanString(singleEntry) .toLowerCase() != singleString - ) - try { + then + try UUID.fromString(singleEntry) - } catch { + catch { case e: IllegalArgumentException => throw new InvalidConfigParameterException( s"Found invalid UUID '$singleEntry' it was meant to be the string '$singleString' or a valid UUID.", @@ -404,17 +396,16 @@ case object ConfigFailFast extends LazyLogging { private def checkSpecificLoadModelConfig( loadModelConfig: SimonaConfig.LoadRuntimeConfig ): Unit = { - if (!LoadModelBehaviour.isEligibleInput(loadModelConfig.modelBehaviour)) + if !LoadModelBehaviour.isEligibleInput(loadModelConfig.modelBehaviour) then throw new InvalidConfigParameterException( s"The load model behaviour '${loadModelConfig.modelBehaviour}' for the loads with UUIDs '${loadModelConfig.uuids .mkString(",")}' is invalid." ) - if ( - !LoadReference.isEligibleKey( + if !LoadReference.isEligibleKey( loadModelConfig.reference ) - ) + then throw new InvalidConfigParameterException( s"The standard load profile reference '${loadModelConfig.reference}' for the loads with UUIDs '${loadModelConfig.uuids .mkString(",")}' is invalid." @@ -432,7 +423,7 @@ case object ConfigFailFast extends LazyLogging { refSystem.voltLvls.getOrElse(List.empty[SimonaConfig.VoltLvlConfig]) val gridIds = refSystem.gridIds.getOrElse(List.empty[String]) - if (voltLvls.isEmpty && gridIds.isEmpty) + if voltLvls.isEmpty && gridIds.isEmpty then throw new InvalidConfigParameterException( "The provided values for voltLvls and gridIds are empty! " + s"At least one of these optional parameters has to be provided for a valid refSystem! " + @@ -442,7 +433,7 @@ case object ConfigFailFast extends LazyLogging { voltLvls.foreach { voltLvl => Try(Quantities.getQuantity(voltLvl.vNom)) match { case Success(quantity) => - if (!quantity.getUnit.isCompatible(Units.VOLT)) + if !quantity.getUnit.isCompatible(Units.VOLT) then throw new InvalidConfigParameterException( s"The given nominal voltage '${voltLvl.vNom}' cannot be parsed to electrical potential! Please provide the volt level with its unit, e.g. \"20 kV\"" ) @@ -482,12 +473,11 @@ case object ConfigFailFast extends LazyLogging { ) } - def rangeCheck(from: Int, to: Int, gridIdRange: String): Unit = { - if (from >= to) + def rangeCheck(from: Int, to: Int, gridIdRange: String): Unit = + if from >= to then throw new InvalidConfigParameterException( s"Invalid gridId Range $gridIdRange. Start $from cannot be equals or bigger than end $to." ) - } } private def checkGridDataSource( @@ -495,7 +485,7 @@ case object ConfigFailFast extends LazyLogging { ): Unit = { // grid source information provided? - if (gridDataSource.id.isEmpty) { + if gridDataSource.id.isEmpty then { throw new InvalidConfigParameterException( "No grid data source information provided! Cannot proceed!" ) @@ -540,7 +530,7 @@ case object ConfigFailFast extends LazyLogging { ): Unit = { (subConfig.defaultConfig :: subConfig.individualConfigs).foreach(c => - if (c.powerRequestReply) + if c.powerRequestReply then throw new NotImplementedError( "PowerRequestReply output handling is not supported yet!" ) @@ -560,11 +550,9 @@ case object ConfigFailFast extends LazyLogging { */ private def checkPowerFlowResolutionConfiguration( powerFlow: SimonaConfig.Simona.Powerflow - ): Unit = { - + ): Unit = // check if time bin is not smaller than in seconds - if ( - (powerFlow.resolution.getUnits.contains( + if (powerFlow.resolution.getUnits.contains( ChronoUnit.NANOS ) && powerFlow.resolution.getNano != 0) || (powerFlow.resolution.getUnits.contains( @@ -575,13 +563,12 @@ case object ConfigFailFast extends LazyLogging { ChronoUnit.MILLIS ) && powerFlow.resolution .get(ChronoUnit.MILLIS) != 0) - ) { + then { throw new InvalidConfigParameterException( s"Invalid time resolution. Please ensure, that " + s"the time resolution for power flow calculation is at least rounded to a full second!" ) } - } /** Check the default config * @@ -593,16 +580,14 @@ case object ConfigFailFast extends LazyLogging { private def checkDefaultBaseOutputConfig( config: SimonaConfig.BaseOutputConfig, defaultString: String - ): Unit = { - if ( - StringUtils + ): Unit = + if StringUtils .cleanString(config.notifier) .toLowerCase != StringUtils.cleanString(defaultString).toLowerCase - ) + then logger.warn( s"You provided '${config.notifier}' as model type for the default participant output config. This will not be considered!" ) - } /** Checks the participant output configurations on duplicates * @@ -620,7 +605,7 @@ case object ConfigFailFast extends LazyLogging { } .keys - if (duplicateKeys.nonEmpty) + if duplicateKeys.nonEmpty then throw new InvalidConfigParameterException( s"There are multiple output configurations for participant types '${duplicateKeys.mkString(",")}'." ) @@ -633,24 +618,22 @@ case object ConfigFailFast extends LazyLogging { * @param config * to be checked */ - private def checkBaseOutputConfig(config: BaseOutputConfig): Unit = { + private def checkBaseOutputConfig(config: BaseOutputConfig): Unit = checkNotifierIdentifier(config.notifier) - } /** Check the validity of the identifier String * * @param id * identifier String to check */ - private def checkNotifierIdentifier(id: String): Unit = { - try { + private def checkNotifierIdentifier(id: String): Unit = + try NotifierIdentifier(id) - } catch { + catch { case e: NoSuchElementException => throw new InvalidConfigParameterException( s"The identifier '$id' you provided is not valid. Valid input: ${NotifierIdentifier.values.map(_.toString).mkString(",")}", e ) } - } } diff --git a/src/main/scala/edu/ie3/simona/config/RefSystemParser.scala b/src/main/scala/edu/ie3/simona/config/RefSystemParser.scala index 66bf1100c1..204b9c05d9 100644 --- a/src/main/scala/edu/ie3/simona/config/RefSystemParser.scala +++ b/src/main/scala/edu/ie3/simona/config/RefSystemParser.scala @@ -67,22 +67,20 @@ object RefSystemParser { configRefSystem.gridIds .map { _.flatMap { gridId => - { - val allGridIds = gridId match { - case ConfigConventions.gridIdDotRange(from, to) => - from.toInt to to.toInt - case ConfigConventions.gridIdMinusRange(from, to) => - from.toInt to to.toInt - case ConfigConventions.singleGridId(singleGridId) => - Seq(singleGridId.toInt) - case unknownGridIdFormat => - throw new InvalidConfigParameterException( - s"Unknown gridId format $unknownGridIdFormat provided for refSystem $configRefSystem" - ) - } - - allGridIds.map(gridId => (gridId, parsedRefSystem)) + val allGridIds = gridId match { + case ConfigConventions.gridIdDotRange(from, to) => + from.toInt to to.toInt + case ConfigConventions.gridIdMinusRange(from, to) => + from.toInt to to.toInt + case ConfigConventions.singleGridId(singleGridId) => + Seq(singleGridId.toInt) + case unknownGridIdFormat => + throw new InvalidConfigParameterException( + s"Unknown gridId format $unknownGridIdFormat provided for refSystem $configRefSystem" + ) } + + allGridIds.map(gridId => (gridId, parsedRefSystem)) } } .getOrElse(Seq.empty[(Int, RefSystem)]) @@ -100,20 +98,18 @@ object RefSystemParser { } // check for duplicates of gridIds and voltLevels which will be the key for the following map conversion - if ( - CollectionUtils.listHasDuplicates( + if CollectionUtils.listHasDuplicates( gridIdRefSystems.map { case (gridId, _) => gridId } ) - ) + then throw new InvalidConfigParameterException( s"The provided gridIds in simona.gridConfig.refSystems contains duplicates. " + s"Please check if there are either duplicate entries or overlapping ranges!" ) - if ( - CollectionUtils.listHasDuplicates( + if CollectionUtils.listHasDuplicates( voltLvlRefSystems.map { case (voltLvl, _) => voltLvl } ) - ) + then throw new InvalidConfigParameterException( s"The provided voltLvls in simona.gridConfig.refSystems contains duplicates. " + s"Please check your configuration for duplicates in voltLvl entries!" diff --git a/src/main/scala/edu/ie3/simona/config/SimonaConfig.scala b/src/main/scala/edu/ie3/simona/config/SimonaConfig.scala index 5072923c7c..593e70c8c7 100644 --- a/src/main/scala/edu/ie3/simona/config/SimonaConfig.scala +++ b/src/main/scala/edu/ie3/simona/config/SimonaConfig.scala @@ -20,21 +20,20 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.BaseCsvParams = { + ): SimonaConfig.BaseCsvParams = SimonaConfig.BaseCsvParams( csvSep = $_reqStr(parentPath, c, "csvSep", $tsCfgValidator), directoryPath = $_reqStr(parentPath, c, "directoryPath", $tsCfgValidator), isHierarchic = $_reqBln(parentPath, c, "isHierarchic", $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -42,15 +41,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -58,7 +56,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -93,7 +90,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.EvcsRuntimeConfig = { + ): SimonaConfig.EvcsRuntimeConfig = SimonaConfig.EvcsRuntimeConfig( calculateMissingReactivePowerWithModel = $_reqBln( parentPath, @@ -104,14 +101,13 @@ object SimonaConfig { scaling = $_reqDbl(parentPath, c, "scaling", $tsCfgValidator), uuids = $_L$_str(c.getList("uuids"), parentPath, $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -119,15 +115,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqDbl( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Double = { - if (c == null) 0 + ): scala.Double = + if c == null then 0 else try c.getDouble(path) catch { @@ -135,7 +130,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } } @@ -153,7 +147,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.FixedFeedInRuntimeConfig = { + ): SimonaConfig.FixedFeedInRuntimeConfig = SimonaConfig.FixedFeedInRuntimeConfig( calculateMissingReactivePowerWithModel = $_reqBln( parentPath, @@ -164,14 +158,13 @@ object SimonaConfig { scaling = $_reqDbl(parentPath, c, "scaling", $tsCfgValidator), uuids = $_L$_str(c.getList("uuids"), parentPath, $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -179,15 +172,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqDbl( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Double = { - if (c == null) 0 + ): scala.Double = + if c == null then 0 else try c.getDouble(path) catch { @@ -195,7 +187,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } } @@ -212,7 +203,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.GridOutputConfig = { + ): SimonaConfig.GridOutputConfig = SimonaConfig.GridOutputConfig( lines = c.hasPathOrNull("lines") && c.getBoolean("lines"), nodes = c.hasPathOrNull("nodes") && c.getBoolean("nodes"), @@ -223,14 +214,13 @@ object SimonaConfig { transformers3w = c.hasPathOrNull("transformers3w") && c.getBoolean("transformers3w") ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -238,7 +228,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -256,7 +245,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.HpRuntimeConfig = { + ): SimonaConfig.HpRuntimeConfig = SimonaConfig.HpRuntimeConfig( calculateMissingReactivePowerWithModel = $_reqBln( parentPath, @@ -267,14 +256,13 @@ object SimonaConfig { scaling = $_reqDbl(parentPath, c, "scaling", $tsCfgValidator), uuids = $_L$_str(c.getList("uuids"), parentPath, $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -282,15 +270,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqDbl( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Double = { - if (c == null) 0 + ): scala.Double = + if c == null then 0 else try c.getDouble(path) catch { @@ -298,7 +285,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } } @@ -325,7 +311,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.LoadRuntimeConfig = { + ): SimonaConfig.LoadRuntimeConfig = SimonaConfig.LoadRuntimeConfig( modelBehaviour = $_reqStr(parentPath, c, "modelBehaviour", $tsCfgValidator), @@ -339,14 +325,13 @@ object SimonaConfig { scaling = $_reqDbl(parentPath, c, "scaling", $tsCfgValidator), uuids = $_L$_str(c.getList("uuids"), parentPath, $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -354,15 +339,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqDbl( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Double = { - if (c == null) 0 + ): scala.Double = + if c == null then 0 else try c.getDouble(path) catch { @@ -370,15 +354,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -386,7 +369,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -400,7 +382,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.ParticipantBaseOutputConfig = { + ): SimonaConfig.ParticipantBaseOutputConfig = SimonaConfig.ParticipantBaseOutputConfig( powerRequestReply = $_reqBln(parentPath, c, "powerRequestReply", $tsCfgValidator), @@ -408,14 +390,13 @@ object SimonaConfig { simulationResult = $_reqBln(parentPath, c, "simulationResult", $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -423,15 +404,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -439,7 +419,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -454,24 +433,23 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.PrimaryDataCsvParams = { + ): SimonaConfig.PrimaryDataCsvParams = SimonaConfig.PrimaryDataCsvParams( timePattern = - if (c.hasPathOrNull("timePattern")) c.getString("timePattern") + if c.hasPathOrNull("timePattern") then c.getString("timePattern") else "yyyy-MM-dd'T'HH:mm:ss[.S[S][S]]'Z'", csvSep = $_reqStr(parentPath, c, "csvSep", $tsCfgValidator), directoryPath = $_reqStr(parentPath, c, "directoryPath", $tsCfgValidator), isHierarchic = $_reqBln(parentPath, c, "isHierarchic", $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -479,15 +457,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -495,7 +472,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -513,7 +489,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.PvRuntimeConfig = { + ): SimonaConfig.PvRuntimeConfig = SimonaConfig.PvRuntimeConfig( calculateMissingReactivePowerWithModel = $_reqBln( parentPath, @@ -524,14 +500,13 @@ object SimonaConfig { scaling = $_reqDbl(parentPath, c, "scaling", $tsCfgValidator), uuids = $_L$_str(c.getList("uuids"), parentPath, $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -539,15 +514,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqDbl( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Double = { - if (c == null) 0 + ): scala.Double = + if c == null then 0 else try c.getDouble(path) catch { @@ -555,7 +529,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } } @@ -570,10 +543,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.RefSystemConfig = { + ): SimonaConfig.RefSystemConfig = SimonaConfig.RefSystemConfig( gridIds = - if (c.hasPathOrNull("gridIds")) + if c.hasPathOrNull("gridIds") then scala.Some( $_L$_str(c.getList("gridIds"), parentPath, $tsCfgValidator) ) @@ -581,7 +554,7 @@ object SimonaConfig { sNom = $_reqStr(parentPath, c, "sNom", $tsCfgValidator), vNom = $_reqStr(parentPath, c, "vNom", $tsCfgValidator), voltLvls = - if (c.hasPathOrNull("voltLvls")) + if c.hasPathOrNull("voltLvls") then scala.Some( $_LSimonaConfig_VoltLvlConfig( c.getList("voltLvls"), @@ -591,13 +564,12 @@ object SimonaConfig { ) else None ) - } private def $_LSimonaConfig_VoltLvlConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.VoltLvlConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.VoltLvlConfig( @@ -613,8 +585,8 @@ object SimonaConfig { c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -622,7 +594,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -638,7 +609,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.ResultKafkaParams = { + ): SimonaConfig.ResultKafkaParams = SimonaConfig.ResultKafkaParams( topicNodeRes = $_reqStr(parentPath, c, "topicNodeRes", $tsCfgValidator), bootstrapServers = @@ -648,14 +619,13 @@ object SimonaConfig { schemaRegistryUrl = $_reqStr(parentPath, c, "schemaRegistryUrl", $tsCfgValidator) ) - } private def $_reqInt( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Int = { - if (c == null) 0 + ): scala.Int = + if c == null then 0 else try c.getInt(path) catch { @@ -663,15 +633,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -679,7 +648,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -695,7 +663,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.RuntimeKafkaParams = { + ): SimonaConfig.RuntimeKafkaParams = SimonaConfig.RuntimeKafkaParams( topic = $_reqStr(parentPath, c, "topic", $tsCfgValidator), bootstrapServers = @@ -705,14 +673,13 @@ object SimonaConfig { schemaRegistryUrl = $_reqStr(parentPath, c, "schemaRegistryUrl", $tsCfgValidator) ) - } private def $_reqInt( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Int = { - if (c == null) 0 + ): scala.Int = + if c == null then 0 else try c.getInt(path) catch { @@ -720,15 +687,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -736,7 +702,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -749,20 +714,19 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.SimpleOutputConfig = { + ): SimonaConfig.SimpleOutputConfig = SimonaConfig.SimpleOutputConfig( notifier = $_reqStr(parentPath, c, "notifier", $tsCfgValidator), simulationResult = $_reqBln(parentPath, c, "simulationResult", $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -770,15 +734,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -786,7 +749,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -799,19 +761,18 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.VoltLvlConfig = { + ): SimonaConfig.VoltLvlConfig = SimonaConfig.VoltLvlConfig( id = $_reqStr(parentPath, c, "id", $tsCfgValidator), vNom = $_reqStr(parentPath, c, "vNom", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -819,7 +780,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -837,7 +797,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.WecRuntimeConfig = { + ): SimonaConfig.WecRuntimeConfig = SimonaConfig.WecRuntimeConfig( calculateMissingReactivePowerWithModel = $_reqBln( parentPath, @@ -848,14 +808,13 @@ object SimonaConfig { scaling = $_reqDbl(parentPath, c, "scaling", $tsCfgValidator), uuids = $_L$_str(c.getList("uuids"), parentPath, $tsCfgValidator) ) - } private def $_reqBln( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Boolean = { - if (c == null) false + ): scala.Boolean = + if c == null then false else try c.getBoolean(path) catch { @@ -863,15 +822,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) false } - } private def $_reqDbl( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Double = { - if (c == null) 0 + ): scala.Double = + if c == null then 0 else try c.getDouble(path) catch { @@ -879,7 +837,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } } @@ -909,10 +866,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Event.Listener$Elm = { + ): SimonaConfig.Simona.Event.Listener$Elm = SimonaConfig.Simona.Event.Listener$Elm( eventsToProcess = - if (c.hasPathOrNull("eventsToProcess")) + if c.hasPathOrNull("eventsToProcess") then scala.Some( $_L$_str( c.getList("eventsToProcess"), @@ -924,14 +881,13 @@ object SimonaConfig { fullClassPath = $_reqStr(parentPath, c, "fullClassPath", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -939,7 +895,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -947,10 +902,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Event = { + ): SimonaConfig.Simona.Event = SimonaConfig.Simona.Event( listener = - if (c.hasPathOrNull("listener")) + if c.hasPathOrNull("listener") then scala.Some( $_LSimonaConfig_Simona_Event_Listener$Elm( c.getList("listener"), @@ -960,13 +915,12 @@ object SimonaConfig { ) else None ) - } private def $_LSimonaConfig_Simona_Event_Listener$Elm( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.Simona.Event.Listener$Elm] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.Simona.Event.Listener$Elm( @@ -987,7 +941,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.GridConfig = { + ): SimonaConfig.Simona.GridConfig = SimonaConfig.Simona.GridConfig( refSystems = $_LSimonaConfig_RefSystemConfig( c.getList("refSystems"), @@ -995,13 +949,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_RefSystemConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.RefSystemConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.RefSystemConfig( @@ -1033,10 +986,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Grid.Datasource = { + ): SimonaConfig.Simona.Input.Grid.Datasource = SimonaConfig.Simona.Input.Grid.Datasource( csvParams = - if (c.hasPathOrNull("csvParams")) + if c.hasPathOrNull("csvParams") then scala.Some( SimonaConfig.BaseCsvParams( c.getConfig("csvParams"), @@ -1047,14 +1000,13 @@ object SimonaConfig { else None, id = $_reqStr(parentPath, c, "id", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1062,7 +1014,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1070,17 +1021,17 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Grid = { + ): SimonaConfig.Simona.Input.Grid = SimonaConfig.Simona.Input.Grid( datasource = SimonaConfig.Simona.Input.Grid.Datasource( - if (c.hasPathOrNull("datasource")) c.getConfig("datasource") + if c.hasPathOrNull("datasource") then c.getConfig("datasource") else - com.typesafe.config.ConfigFactory.parseString("datasource{}"), + com.typesafe.config.ConfigFactory.parseString("datasource{}") + , parentPath + "datasource.", $tsCfgValidator ) ) - } } final case class Primary( @@ -1108,7 +1059,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Primary.CouchbaseParams = { + ): SimonaConfig.Simona.Input.Primary.CouchbaseParams = SimonaConfig.Simona.Input.Primary.CouchbaseParams( bucketName = $_reqStr(parentPath, c, "bucketName", $tsCfgValidator), @@ -1121,19 +1072,19 @@ object SimonaConfig { keyPrefix = $_reqStr(parentPath, c, "keyPrefix", $tsCfgValidator), password = $_reqStr(parentPath, c, "password", $tsCfgValidator), timePattern = - if (c.hasPathOrNull("timePattern")) c.getString("timePattern") + if c.hasPathOrNull("timePattern") then + c.getString("timePattern") else "yyyy-MM-dd'T'HH:mm:ss[.S[S][S]]'Z'", url = $_reqStr(parentPath, c, "url", $tsCfgValidator), userName = $_reqStr(parentPath, c, "userName", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1141,7 +1092,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1156,23 +1106,23 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Primary.InfluxDb1xParams = { + ): SimonaConfig.Simona.Input.Primary.InfluxDb1xParams = SimonaConfig.Simona.Input.Primary.InfluxDb1xParams( database = $_reqStr(parentPath, c, "database", $tsCfgValidator), port = $_reqInt(parentPath, c, "port", $tsCfgValidator), timePattern = - if (c.hasPathOrNull("timePattern")) c.getString("timePattern") + if c.hasPathOrNull("timePattern") then + c.getString("timePattern") else "yyyy-MM-dd'T'HH:mm:ss[.S[S][S]]'Z'", url = $_reqStr(parentPath, c, "url", $tsCfgValidator) ) - } private def $_reqInt( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Int = { - if (c == null) 0 + ): scala.Int = + if c == null then 0 else try c.getInt(path) catch { @@ -1180,15 +1130,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1196,7 +1145,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1212,26 +1160,26 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Primary.SqlParams = { + ): SimonaConfig.Simona.Input.Primary.SqlParams = SimonaConfig.Simona.Input.Primary.SqlParams( jdbcUrl = $_reqStr(parentPath, c, "jdbcUrl", $tsCfgValidator), password = $_reqStr(parentPath, c, "password", $tsCfgValidator), schemaName = - if (c.hasPathOrNull("schemaName")) c.getString("schemaName") + if c.hasPathOrNull("schemaName") then c.getString("schemaName") else "public", timePattern = - if (c.hasPathOrNull("timePattern")) c.getString("timePattern") + if c.hasPathOrNull("timePattern") then + c.getString("timePattern") else "yyyy-MM-dd'T'HH:mm:ss[.S[S][S]]'Z'", userName = $_reqStr(parentPath, c, "userName", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1239,7 +1187,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1247,10 +1194,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Primary = { + ): SimonaConfig.Simona.Input.Primary = SimonaConfig.Simona.Input.Primary( couchbaseParams = - if (c.hasPathOrNull("couchbaseParams")) + if c.hasPathOrNull("couchbaseParams") then scala.Some( SimonaConfig.Simona.Input.Primary.CouchbaseParams( c.getConfig("couchbaseParams"), @@ -1260,7 +1207,7 @@ object SimonaConfig { ) else None, csvParams = - if (c.hasPathOrNull("csvParams")) + if c.hasPathOrNull("csvParams") then scala.Some( SimonaConfig.PrimaryDataCsvParams( c.getConfig("csvParams"), @@ -1270,7 +1217,7 @@ object SimonaConfig { ) else None, influxDb1xParams = - if (c.hasPathOrNull("influxDb1xParams")) + if c.hasPathOrNull("influxDb1xParams") then scala.Some( SimonaConfig.Simona.Input.Primary.InfluxDb1xParams( c.getConfig("influxDb1xParams"), @@ -1280,7 +1227,7 @@ object SimonaConfig { ) else None, sqlParams = - if (c.hasPathOrNull("sqlParams")) + if c.hasPathOrNull("sqlParams") then scala.Some( SimonaConfig.Simona.Input.Primary.SqlParams( c.getConfig("sqlParams"), @@ -1290,7 +1237,6 @@ object SimonaConfig { ) else None ) - } } final case class Weather( @@ -1337,12 +1283,11 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource.SampleParams = { + ): SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource.SampleParams = SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource .SampleParams( use = !c.hasPathOrNull("use") || c.getBoolean("use") ) - } } final case class SqlParams( @@ -1357,7 +1302,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource.SqlParams = { + ): SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource.SqlParams = SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource .SqlParams( jdbcUrl = @@ -1365,7 +1310,7 @@ object SimonaConfig { password = $_reqStr(parentPath, c, "password", $tsCfgValidator), schemaName = - if (c.hasPathOrNull("schemaName")) + if c.hasPathOrNull("schemaName") then c.getString("schemaName") else "public", tableName = @@ -1373,14 +1318,13 @@ object SimonaConfig { userName = $_reqStr(parentPath, c, "userName", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1388,7 +1332,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1396,10 +1339,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource = { + ): SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource = SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource( csvParams = - if (c.hasPathOrNull("csvParams")) + if c.hasPathOrNull("csvParams") then scala.Some( SimonaConfig.BaseCsvParams( c.getConfig("csvParams"), @@ -1409,10 +1352,10 @@ object SimonaConfig { ) else None, gridModel = - if (c.hasPathOrNull("gridModel")) c.getString("gridModel") + if c.hasPathOrNull("gridModel") then c.getString("gridModel") else "icon", sampleParams = - if (c.hasPathOrNull("sampleParams")) + if c.hasPathOrNull("sampleParams") then scala.Some( SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource .SampleParams( @@ -1423,7 +1366,7 @@ object SimonaConfig { ) else None, sqlParams = - if (c.hasPathOrNull("sqlParams")) + if c.hasPathOrNull("sqlParams") then scala.Some( SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource .SqlParams( @@ -1434,7 +1377,6 @@ object SimonaConfig { ) else None ) - } } final case class CouchbaseParams( @@ -1450,7 +1392,7 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource.CouchbaseParams = { + ): SimonaConfig.Simona.Input.Weather.Datasource.CouchbaseParams = SimonaConfig.Simona.Input.Weather.Datasource.CouchbaseParams( bucketName = $_reqStr(parentPath, c, "bucketName", $tsCfgValidator), @@ -1466,14 +1408,13 @@ object SimonaConfig { url = $_reqStr(parentPath, c, "url", $tsCfgValidator), userName = $_reqStr(parentPath, c, "userName", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1481,7 +1422,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1495,20 +1435,19 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource.InfluxDb1xParams = { + ): SimonaConfig.Simona.Input.Weather.Datasource.InfluxDb1xParams = SimonaConfig.Simona.Input.Weather.Datasource.InfluxDb1xParams( database = $_reqStr(parentPath, c, "database", $tsCfgValidator), port = $_reqInt(parentPath, c, "port", $tsCfgValidator), url = $_reqStr(parentPath, c, "url", $tsCfgValidator) ) - } private def $_reqInt( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Int = { - if (c == null) 0 + ): scala.Int = + if c == null then 0 else try c.getInt(path) catch { @@ -1516,15 +1455,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1532,7 +1470,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1544,11 +1481,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource.SampleParams = { + ): SimonaConfig.Simona.Input.Weather.Datasource.SampleParams = SimonaConfig.Simona.Input.Weather.Datasource.SampleParams( use = !c.hasPathOrNull("use") || c.getBoolean("use") ) - } } final case class SqlParams( @@ -1563,25 +1499,25 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource.SqlParams = { + ): SimonaConfig.Simona.Input.Weather.Datasource.SqlParams = SimonaConfig.Simona.Input.Weather.Datasource.SqlParams( jdbcUrl = $_reqStr(parentPath, c, "jdbcUrl", $tsCfgValidator), password = $_reqStr(parentPath, c, "password", $tsCfgValidator), schemaName = - if (c.hasPathOrNull("schemaName")) c.getString("schemaName") + if c.hasPathOrNull("schemaName") then + c.getString("schemaName") else "public", tableName = $_reqStr(parentPath, c, "tableName", $tsCfgValidator), userName = $_reqStr(parentPath, c, "userName", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1589,7 +1525,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1597,20 +1532,21 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather.Datasource = { + ): SimonaConfig.Simona.Input.Weather.Datasource = SimonaConfig.Simona.Input.Weather.Datasource( coordinateSource = SimonaConfig.Simona.Input.Weather.Datasource.CoordinateSource( - if (c.hasPathOrNull("coordinateSource")) + if c.hasPathOrNull("coordinateSource") then c.getConfig("coordinateSource") else com.typesafe.config.ConfigFactory - .parseString("coordinateSource{}"), + .parseString("coordinateSource{}") + , parentPath + "coordinateSource.", $tsCfgValidator ), couchbaseParams = - if (c.hasPathOrNull("couchbaseParams")) + if c.hasPathOrNull("couchbaseParams") then scala.Some( SimonaConfig.Simona.Input.Weather.Datasource .CouchbaseParams( @@ -1621,7 +1557,7 @@ object SimonaConfig { ) else None, csvParams = - if (c.hasPathOrNull("csvParams")) + if c.hasPathOrNull("csvParams") then scala.Some( SimonaConfig.BaseCsvParams( c.getConfig("csvParams"), @@ -1631,7 +1567,7 @@ object SimonaConfig { ) else None, influxDb1xParams = - if (c.hasPathOrNull("influxDb1xParams")) + if c.hasPathOrNull("influxDb1xParams") then scala.Some( SimonaConfig.Simona.Input.Weather.Datasource .InfluxDb1xParams( @@ -1642,15 +1578,15 @@ object SimonaConfig { ) else None, maxCoordinateDistance = - if (c.hasPathOrNull("maxCoordinateDistance")) + if c.hasPathOrNull("maxCoordinateDistance") then c.getDouble("maxCoordinateDistance") else 50000, resolution = - if (c.hasPathOrNull("resolution")) + if c.hasPathOrNull("resolution") then Some(c.getLong("resolution").longValue()) else None, sampleParams = - if (c.hasPathOrNull("sampleParams")) + if c.hasPathOrNull("sampleParams") then scala.Some( SimonaConfig.Simona.Input.Weather.Datasource.SampleParams( c.getConfig("sampleParams"), @@ -1660,10 +1596,10 @@ object SimonaConfig { ) else None, scheme = - if (c.hasPathOrNull("scheme")) c.getString("scheme") + if c.hasPathOrNull("scheme") then c.getString("scheme") else "icon", sqlParams = - if (c.hasPathOrNull("sqlParams")) + if c.hasPathOrNull("sqlParams") then scala.Some( SimonaConfig.Simona.Input.Weather.Datasource.SqlParams( c.getConfig("sqlParams"), @@ -1673,56 +1609,54 @@ object SimonaConfig { ) else None, timestampPattern = - if (c.hasPathOrNull("timestampPattern")) + if c.hasPathOrNull("timestampPattern") then Some(c.getString("timestampPattern")) else None ) - } } def apply( c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input.Weather = { + ): SimonaConfig.Simona.Input.Weather = SimonaConfig.Simona.Input.Weather( datasource = SimonaConfig.Simona.Input.Weather.Datasource( - if (c.hasPathOrNull("datasource")) c.getConfig("datasource") + if c.hasPathOrNull("datasource") then c.getConfig("datasource") else - com.typesafe.config.ConfigFactory.parseString("datasource{}"), + com.typesafe.config.ConfigFactory.parseString("datasource{}") + , parentPath + "datasource.", $tsCfgValidator ) ) - } } def apply( c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Input = { + ): SimonaConfig.Simona.Input = SimonaConfig.Simona.Input( grid = SimonaConfig.Simona.Input.Grid( - if (c.hasPathOrNull("grid")) c.getConfig("grid") + if c.hasPathOrNull("grid") then c.getConfig("grid") else com.typesafe.config.ConfigFactory.parseString("grid{}"), parentPath + "grid.", $tsCfgValidator ), primary = SimonaConfig.Simona.Input.Primary( - if (c.hasPathOrNull("primary")) c.getConfig("primary") + if c.hasPathOrNull("primary") then c.getConfig("primary") else com.typesafe.config.ConfigFactory.parseString("primary{}"), parentPath + "primary.", $tsCfgValidator ), weather = SimonaConfig.Simona.Input.Weather( - if (c.hasPathOrNull("weather")) c.getConfig("weather") + if c.hasPathOrNull("weather") then c.getConfig("weather") else com.typesafe.config.ConfigFactory.parseString("weather{}"), parentPath + "weather.", $tsCfgValidator ) ) - } } final case class Output( @@ -1742,21 +1676,20 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Output.Base = { + ): SimonaConfig.Simona.Output.Base = SimonaConfig.Simona.Output.Base( addTimestampToOutputDir = !c.hasPathOrNull( "addTimestampToOutputDir" ) || c.getBoolean("addTimestampToOutputDir"), dir = $_reqStr(parentPath, c, "dir", $tsCfgValidator) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1764,7 +1697,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1779,13 +1711,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Output.Participant = { + ): SimonaConfig.Simona.Output.Participant = SimonaConfig.Simona.Output.Participant( defaultConfig = SimonaConfig.ParticipantBaseOutputConfig( - if (c.hasPathOrNull("defaultConfig")) c.getConfig("defaultConfig") + if c.hasPathOrNull("defaultConfig") then + c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -1795,13 +1729,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_ParticipantBaseOutputConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.ParticipantBaseOutputConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.ParticipantBaseOutputConfig( @@ -1831,21 +1764,20 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Output.Sink.Csv = { + ): SimonaConfig.Simona.Output.Sink.Csv = SimonaConfig.Simona.Output.Sink.Csv( fileFormat = - if (c.hasPathOrNull("fileFormat")) c.getString("fileFormat") + if c.hasPathOrNull("fileFormat") then c.getString("fileFormat") else ".csv", filePrefix = - if (c.hasPathOrNull("filePrefix")) c.getString("filePrefix") + if c.hasPathOrNull("filePrefix") then c.getString("filePrefix") else "", fileSuffix = - if (c.hasPathOrNull("fileSuffix")) c.getString("fileSuffix") + if c.hasPathOrNull("fileSuffix") then c.getString("fileSuffix") else "", isHierarchic = c.hasPathOrNull("isHierarchic") && c.getBoolean("isHierarchic") ) - } } final case class InfluxDb1x( @@ -1858,20 +1790,19 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Output.Sink.InfluxDb1x = { + ): SimonaConfig.Simona.Output.Sink.InfluxDb1x = SimonaConfig.Simona.Output.Sink.InfluxDb1x( database = $_reqStr(parentPath, c, "database", $tsCfgValidator), port = $_reqInt(parentPath, c, "port", $tsCfgValidator), url = $_reqStr(parentPath, c, "url", $tsCfgValidator) ) - } private def $_reqInt( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Int = { - if (c == null) 0 + ): scala.Int = + if c == null then 0 else try c.getInt(path) catch { @@ -1879,15 +1810,14 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -1895,7 +1825,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -1903,10 +1832,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Output.Sink = { + ): SimonaConfig.Simona.Output.Sink = SimonaConfig.Simona.Output.Sink( csv = - if (c.hasPathOrNull("csv")) + if c.hasPathOrNull("csv") then scala.Some( SimonaConfig.Simona.Output.Sink.Csv( c.getConfig("csv"), @@ -1916,7 +1845,7 @@ object SimonaConfig { ) else None, influxDb1x = - if (c.hasPathOrNull("influxDb1x")) + if c.hasPathOrNull("influxDb1x") then scala.Some( SimonaConfig.Simona.Output.Sink.InfluxDb1x( c.getConfig("influxDb1x"), @@ -1926,7 +1855,7 @@ object SimonaConfig { ) else None, kafka = - if (c.hasPathOrNull("kafka")) + if c.hasPathOrNull("kafka") then scala.Some( SimonaConfig.ResultKafkaParams( c.getConfig("kafka"), @@ -1936,7 +1865,6 @@ object SimonaConfig { ) else None ) - } } final case class Thermal( @@ -1948,13 +1876,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Output.Thermal = { + ): SimonaConfig.Simona.Output.Thermal = SimonaConfig.Simona.Output.Thermal( defaultConfig = SimonaConfig.SimpleOutputConfig( - if (c.hasPathOrNull("defaultConfig")) c.getConfig("defaultConfig") + if c.hasPathOrNull("defaultConfig") then + c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -1964,13 +1894,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_SimpleOutputConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.SimpleOutputConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.SimpleOutputConfig( @@ -1987,40 +1916,39 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Output = { + ): SimonaConfig.Simona.Output = SimonaConfig.Simona.Output( base = SimonaConfig.Simona.Output.Base( - if (c.hasPathOrNull("base")) c.getConfig("base") + if c.hasPathOrNull("base") then c.getConfig("base") else com.typesafe.config.ConfigFactory.parseString("base{}"), parentPath + "base.", $tsCfgValidator ), grid = SimonaConfig.GridOutputConfig( - if (c.hasPathOrNull("grid")) c.getConfig("grid") + if c.hasPathOrNull("grid") then c.getConfig("grid") else com.typesafe.config.ConfigFactory.parseString("grid{}"), parentPath + "grid.", $tsCfgValidator ), participant = SimonaConfig.Simona.Output.Participant( - if (c.hasPathOrNull("participant")) c.getConfig("participant") + if c.hasPathOrNull("participant") then c.getConfig("participant") else com.typesafe.config.ConfigFactory.parseString("participant{}"), parentPath + "participant.", $tsCfgValidator ), sink = SimonaConfig.Simona.Output.Sink( - if (c.hasPathOrNull("sink")) c.getConfig("sink") + if c.hasPathOrNull("sink") then c.getConfig("sink") else com.typesafe.config.ConfigFactory.parseString("sink{}"), parentPath + "sink.", $tsCfgValidator ), thermal = SimonaConfig.Simona.Output.Thermal( - if (c.hasPathOrNull("thermal")) c.getConfig("thermal") + if c.hasPathOrNull("thermal") then c.getConfig("thermal") else com.typesafe.config.ConfigFactory.parseString("thermal{}"), parentPath + "thermal.", $tsCfgValidator ) ) - } } final case class Powerflow( @@ -2040,20 +1968,19 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Powerflow.Newtonraphson = { + ): SimonaConfig.Simona.Powerflow.Newtonraphson = SimonaConfig.Simona.Powerflow.Newtonraphson( epsilon = $_L$_dbl(c.getList("epsilon"), parentPath, $tsCfgValidator), iterations = $_reqInt(parentPath, c, "iterations", $tsCfgValidator) ) - } private def $_reqInt( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Int = { - if (c == null) 0 + ): scala.Int = + if c == null then 0 else try c.getInt(path) catch { @@ -2061,7 +1988,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } } @@ -2069,34 +1995,36 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Powerflow = { + ): SimonaConfig.Simona.Powerflow = SimonaConfig.Simona.Powerflow( maxSweepPowerDeviation = $_reqDbl(parentPath, c, "maxSweepPowerDeviation", $tsCfgValidator), newtonraphson = SimonaConfig.Simona.Powerflow.Newtonraphson( - if (c.hasPathOrNull("newtonraphson")) c.getConfig("newtonraphson") + if c.hasPathOrNull("newtonraphson") then + c.getConfig("newtonraphson") else - com.typesafe.config.ConfigFactory.parseString("newtonraphson{}"), + com.typesafe.config.ConfigFactory.parseString("newtonraphson{}") + , parentPath + "newtonraphson.", $tsCfgValidator ), resolution = - if (c.hasPathOrNull("resolution")) c.getDuration("resolution") + if c.hasPathOrNull("resolution") then c.getDuration("resolution") else java.time.Duration.parse("PT1H"), stopOnFailure = c.hasPathOrNull("stopOnFailure") && c.getBoolean("stopOnFailure"), sweepTimeout = - if (c.hasPathOrNull("sweepTimeout")) c.getDuration("sweepTimeout") + if c.hasPathOrNull("sweepTimeout") then + c.getDuration("sweepTimeout") else java.time.Duration.parse("PT30S") ) - } private def $_reqDbl( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): scala.Double = { - if (c == null) 0 + ): scala.Double = + if c == null then 0 else try c.getDouble(path) catch { @@ -2104,7 +2032,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) 0 } - } } @@ -2124,10 +2051,10 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Listener = { + ): SimonaConfig.Simona.Runtime.Listener = SimonaConfig.Simona.Runtime.Listener( eventsToProcess = - if (c.hasPathOrNull("eventsToProcess")) + if c.hasPathOrNull("eventsToProcess") then scala.Some( $_L$_str( c.getList("eventsToProcess"), @@ -2137,7 +2064,7 @@ object SimonaConfig { ) else None, kafka = - if (c.hasPathOrNull("kafka")) + if c.hasPathOrNull("kafka") then scala.Some( SimonaConfig.RuntimeKafkaParams( c.getConfig("kafka"), @@ -2147,7 +2074,6 @@ object SimonaConfig { ) else None ) - } } final case class Participant( @@ -2169,14 +2095,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Participant.Evcs = { + ): SimonaConfig.Simona.Runtime.Participant.Evcs = SimonaConfig.Simona.Runtime.Participant.Evcs( defaultConfig = SimonaConfig.EvcsRuntimeConfig( - if (c.hasPathOrNull("defaultConfig")) + if c.hasPathOrNull("defaultConfig") then c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -2186,13 +2113,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_EvcsRuntimeConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.EvcsRuntimeConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.EvcsRuntimeConfig( @@ -2214,14 +2140,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Participant.FixedFeedIn = { + ): SimonaConfig.Simona.Runtime.Participant.FixedFeedIn = SimonaConfig.Simona.Runtime.Participant.FixedFeedIn( defaultConfig = SimonaConfig.FixedFeedInRuntimeConfig( - if (c.hasPathOrNull("defaultConfig")) + if c.hasPathOrNull("defaultConfig") then c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -2231,13 +2158,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_FixedFeedInRuntimeConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.FixedFeedInRuntimeConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.FixedFeedInRuntimeConfig( @@ -2259,14 +2185,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Participant.Hp = { + ): SimonaConfig.Simona.Runtime.Participant.Hp = SimonaConfig.Simona.Runtime.Participant.Hp( defaultConfig = SimonaConfig.HpRuntimeConfig( - if (c.hasPathOrNull("defaultConfig")) + if c.hasPathOrNull("defaultConfig") then c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -2276,13 +2203,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_HpRuntimeConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.HpRuntimeConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.HpRuntimeConfig( @@ -2304,14 +2230,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Participant.Load = { + ): SimonaConfig.Simona.Runtime.Participant.Load = SimonaConfig.Simona.Runtime.Participant.Load( defaultConfig = SimonaConfig.LoadRuntimeConfig( - if (c.hasPathOrNull("defaultConfig")) + if c.hasPathOrNull("defaultConfig") then c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -2321,13 +2248,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_LoadRuntimeConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.LoadRuntimeConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.LoadRuntimeConfig( @@ -2349,14 +2275,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Participant.Pv = { + ): SimonaConfig.Simona.Runtime.Participant.Pv = SimonaConfig.Simona.Runtime.Participant.Pv( defaultConfig = SimonaConfig.PvRuntimeConfig( - if (c.hasPathOrNull("defaultConfig")) + if c.hasPathOrNull("defaultConfig") then c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -2366,13 +2293,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_PvRuntimeConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.PvRuntimeConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.PvRuntimeConfig( @@ -2394,14 +2320,15 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Participant.Wec = { + ): SimonaConfig.Simona.Runtime.Participant.Wec = SimonaConfig.Simona.Runtime.Participant.Wec( defaultConfig = SimonaConfig.WecRuntimeConfig( - if (c.hasPathOrNull("defaultConfig")) + if c.hasPathOrNull("defaultConfig") then c.getConfig("defaultConfig") else com.typesafe.config.ConfigFactory - .parseString("defaultConfig{}"), + .parseString("defaultConfig{}") + , parentPath + "defaultConfig.", $tsCfgValidator ), @@ -2411,13 +2338,12 @@ object SimonaConfig { $tsCfgValidator ) ) - } private def $_LSimonaConfig_WecRuntimeConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.WecRuntimeConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.WecRuntimeConfig( @@ -2434,73 +2360,73 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime.Participant = { + ): SimonaConfig.Simona.Runtime.Participant = SimonaConfig.Simona.Runtime.Participant( evcs = SimonaConfig.Simona.Runtime.Participant.Evcs( - if (c.hasPathOrNull("evcs")) c.getConfig("evcs") + if c.hasPathOrNull("evcs") then c.getConfig("evcs") else com.typesafe.config.ConfigFactory.parseString("evcs{}"), parentPath + "evcs.", $tsCfgValidator ), fixedFeedIn = SimonaConfig.Simona.Runtime.Participant.FixedFeedIn( - if (c.hasPathOrNull("fixedFeedIn")) c.getConfig("fixedFeedIn") + if c.hasPathOrNull("fixedFeedIn") then c.getConfig("fixedFeedIn") else - com.typesafe.config.ConfigFactory.parseString("fixedFeedIn{}"), + com.typesafe.config.ConfigFactory.parseString("fixedFeedIn{}") + , parentPath + "fixedFeedIn.", $tsCfgValidator ), hp = SimonaConfig.Simona.Runtime.Participant.Hp( - if (c.hasPathOrNull("hp")) c.getConfig("hp") + if c.hasPathOrNull("hp") then c.getConfig("hp") else com.typesafe.config.ConfigFactory.parseString("hp{}"), parentPath + "hp.", $tsCfgValidator ), load = SimonaConfig.Simona.Runtime.Participant.Load( - if (c.hasPathOrNull("load")) c.getConfig("load") + if c.hasPathOrNull("load") then c.getConfig("load") else com.typesafe.config.ConfigFactory.parseString("load{}"), parentPath + "load.", $tsCfgValidator ), pv = SimonaConfig.Simona.Runtime.Participant.Pv( - if (c.hasPathOrNull("pv")) c.getConfig("pv") + if c.hasPathOrNull("pv") then c.getConfig("pv") else com.typesafe.config.ConfigFactory.parseString("pv{}"), parentPath + "pv.", $tsCfgValidator ), requestVoltageDeviationThreshold = - if (c.hasPathOrNull("requestVoltageDeviationThreshold")) + if c.hasPathOrNull("requestVoltageDeviationThreshold") then c.getDouble("requestVoltageDeviationThreshold") else 1e-14, wec = SimonaConfig.Simona.Runtime.Participant.Wec( - if (c.hasPathOrNull("wec")) c.getConfig("wec") + if c.hasPathOrNull("wec") then c.getConfig("wec") else com.typesafe.config.ConfigFactory.parseString("wec{}"), parentPath + "wec.", $tsCfgValidator ) ) - } } def apply( c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Runtime = { + ): SimonaConfig.Simona.Runtime = SimonaConfig.Simona.Runtime( listener = SimonaConfig.Simona.Runtime.Listener( - if (c.hasPathOrNull("listener")) c.getConfig("listener") + if c.hasPathOrNull("listener") then c.getConfig("listener") else com.typesafe.config.ConfigFactory.parseString("listener{}"), parentPath + "listener.", $tsCfgValidator ), participant = SimonaConfig.Simona.Runtime.Participant( - if (c.hasPathOrNull("participant")) c.getConfig("participant") + if c.hasPathOrNull("participant") then c.getConfig("participant") else com.typesafe.config.ConfigFactory.parseString("participant{}"), parentPath + "participant.", $tsCfgValidator ), selected_subgrids = - if (c.hasPathOrNull("selected_subgrids")) + if c.hasPathOrNull("selected_subgrids") then scala.Some( $_L$_int( c.getList("selected_subgrids"), @@ -2510,7 +2436,7 @@ object SimonaConfig { ) else None, selected_volt_lvls = - if (c.hasPathOrNull("selected_volt_lvls")) + if c.hasPathOrNull("selected_volt_lvls") then scala.Some( $_LSimonaConfig_VoltLvlConfig( c.getList("selected_volt_lvls"), @@ -2520,13 +2446,12 @@ object SimonaConfig { ) else None ) - } private def $_LSimonaConfig_VoltLvlConfig( cl: com.typesafe.config.ConfigList, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[SimonaConfig.VoltLvlConfig] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala .map(cv => SimonaConfig.VoltLvlConfig( @@ -2549,60 +2474,60 @@ object SimonaConfig { c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona.Time = { + ): SimonaConfig.Simona.Time = SimonaConfig.Simona.Time( endDateTime = - if (c.hasPathOrNull("endDateTime")) c.getString("endDateTime") + if c.hasPathOrNull("endDateTime") then c.getString("endDateTime") else "2011-05-01 01:00:00", schedulerReadyCheckWindow = - if (c.hasPathOrNull("schedulerReadyCheckWindow")) + if c.hasPathOrNull("schedulerReadyCheckWindow") then Some(c.getInt("schedulerReadyCheckWindow")) else None, startDateTime = - if (c.hasPathOrNull("startDateTime")) c.getString("startDateTime") + if c.hasPathOrNull("startDateTime") then + c.getString("startDateTime") else "2011-05-01 00:00:00" ) - } } def apply( c: com.typesafe.config.Config, parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): SimonaConfig.Simona = { + ): SimonaConfig.Simona = SimonaConfig.Simona( event = SimonaConfig.Simona.Event( - if (c.hasPathOrNull("event")) c.getConfig("event") + if c.hasPathOrNull("event") then c.getConfig("event") else com.typesafe.config.ConfigFactory.parseString("event{}"), parentPath + "event.", $tsCfgValidator ), gridConfig = SimonaConfig.Simona.GridConfig( - if (c.hasPathOrNull("gridConfig")) c.getConfig("gridConfig") + if c.hasPathOrNull("gridConfig") then c.getConfig("gridConfig") else com.typesafe.config.ConfigFactory.parseString("gridConfig{}"), parentPath + "gridConfig.", $tsCfgValidator ), input = SimonaConfig.Simona.Input( - if (c.hasPathOrNull("input")) c.getConfig("input") + if c.hasPathOrNull("input") then c.getConfig("input") else com.typesafe.config.ConfigFactory.parseString("input{}"), parentPath + "input.", $tsCfgValidator ), output = SimonaConfig.Simona.Output( - if (c.hasPathOrNull("output")) c.getConfig("output") + if c.hasPathOrNull("output") then c.getConfig("output") else com.typesafe.config.ConfigFactory.parseString("output{}"), parentPath + "output.", $tsCfgValidator ), powerflow = SimonaConfig.Simona.Powerflow( - if (c.hasPathOrNull("powerflow")) c.getConfig("powerflow") + if c.hasPathOrNull("powerflow") then c.getConfig("powerflow") else com.typesafe.config.ConfigFactory.parseString("powerflow{}"), parentPath + "powerflow.", $tsCfgValidator ), runtime = SimonaConfig.Simona.Runtime( - if (c.hasPathOrNull("runtime")) c.getConfig("runtime") + if c.hasPathOrNull("runtime") then c.getConfig("runtime") else com.typesafe.config.ConfigFactory.parseString("runtime{}"), parentPath + "runtime.", $tsCfgValidator @@ -2610,20 +2535,19 @@ object SimonaConfig { simulationName = $_reqStr(parentPath, c, "simulationName", $tsCfgValidator), time = SimonaConfig.Simona.Time( - if (c.hasPathOrNull("time")) c.getConfig("time") + if c.hasPathOrNull("time") then c.getConfig("time") else com.typesafe.config.ConfigFactory.parseString("time{}"), parentPath + "time.", $tsCfgValidator ) ) - } private def $_reqStr( parentPath: java.lang.String, c: com.typesafe.config.Config, path: java.lang.String, $tsCfgValidator: $TsCfgValidator - ): java.lang.String = { - if (c == null) null + ): java.lang.String = + if c == null then null else try c.getString(path) catch { @@ -2631,7 +2555,6 @@ object SimonaConfig { $tsCfgValidator.addBadPath(parentPath + path, e) null } - } } @@ -2640,7 +2563,7 @@ object SimonaConfig { val parentPath: java.lang.String = "" val $result = SimonaConfig( simona = SimonaConfig.Simona( - if (c.hasPathOrNull("simona")) c.getConfig("simona") + if c.hasPathOrNull("simona") then c.getConfig("simona") else com.typesafe.config.ConfigFactory.parseString("simona{}"), parentPath + "simona.", $tsCfgValidator @@ -2655,7 +2578,7 @@ object SimonaConfig { parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[scala.Double] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala.map(cv => $_dbl(cv)).toList } private def $_L$_int( @@ -2663,7 +2586,7 @@ object SimonaConfig { parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[scala.Int] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala.map(cv => $_int(cv)).toList } private def $_L$_str( @@ -2671,15 +2594,14 @@ object SimonaConfig { parentPath: java.lang.String, $tsCfgValidator: $TsCfgValidator ): scala.List[java.lang.String] = { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* cl.asScala.map(cv => $_str(cv)).toList } private def $_dbl(cv: com.typesafe.config.ConfigValue): scala.Double = { val u: Any = cv.unwrapped - if ( - (cv.valueType != com.typesafe.config.ConfigValueType.NUMBER) || + if (cv.valueType != com.typesafe.config.ConfigValueType.NUMBER) || !u.isInstanceOf[java.lang.Number] - ) throw $_expE(cv, "double") + then throw $_expE(cv, "double") u.asInstanceOf[java.lang.Number].doubleValue() } @@ -2691,22 +2613,20 @@ object SimonaConfig { new java.lang.RuntimeException( s"${cv.origin.lineNumber}: " + "expecting: " + exp + " got: " + - (if (u.isInstanceOf[java.lang.String]) "\"" + u + "\"" else u) + (if u.isInstanceOf[java.lang.String] then "\"" + u + "\"" else u) ) } private def $_int(cv: com.typesafe.config.ConfigValue): scala.Int = { val u: Any = cv.unwrapped - if ( - (cv.valueType != com.typesafe.config.ConfigValueType.NUMBER) || + if (cv.valueType != com.typesafe.config.ConfigValueType.NUMBER) || !u.isInstanceOf[Integer] - ) throw $_expE(cv, "integer") + then throw $_expE(cv, "integer") u.asInstanceOf[Integer] } - private def $_str(cv: com.typesafe.config.ConfigValue): java.lang.String = { + private def $_str(cv: com.typesafe.config.ConfigValue): java.lang.String = java.lang.String.valueOf(cv.unwrapped()) - } final class $TsCfgValidator { private val badPaths = @@ -2715,24 +2635,21 @@ object SimonaConfig { def addBadPath( path: java.lang.String, e: com.typesafe.config.ConfigException - ): Unit = { + ): Unit = badPaths += s"'$path': ${e.getClass.getName}(${e.getMessage})" - } def addInvalidEnumValue( path: java.lang.String, value: java.lang.String, enumName: java.lang.String - ): Unit = { + ): Unit = badPaths += s"'$path': invalid value $value for enumeration $enumName" - } - def validate(): Unit = { - if (badPaths.nonEmpty) { + def validate(): Unit = + if badPaths.nonEmpty then { throw new com.typesafe.config.ConfigException( badPaths.mkString("Invalid configuration:\n ", "\n ", "") ) {} } - } } } diff --git a/src/main/scala/edu/ie3/simona/config/VoltLvlParser.scala b/src/main/scala/edu/ie3/simona/config/VoltLvlParser.scala index 3d3ce38920..8c18c663a7 100644 --- a/src/main/scala/edu/ie3/simona/config/VoltLvlParser.scala +++ b/src/main/scala/edu/ie3/simona/config/VoltLvlParser.scala @@ -48,9 +48,9 @@ object VoltLvlParser { id: String, vNominal: ComparableQuantity[ElectricPotential] ): CommonVoltageLevel = - try { + try GermanVoltageLevelUtils.parse(id, vNominal) - } catch { + catch { case vle: VoltageLevelException => throw new InvalidConfigParameterException( s"Cannot find a common voltage level with id $id and nominal voltage $vNominal", @@ -67,12 +67,12 @@ object VoltLvlParser { */ private def parseNominalVoltage( quantString: String - ): ComparableQuantity[ElectricPotential] = { - try { + ): ComparableQuantity[ElectricPotential] = + try QuantityUtil.asComparable( Quantities.getQuantity(quantString).asType(classOf[ElectricPotential]) ) - } catch { + catch { case iae: IllegalArgumentException => throw new InvalidConfigParameterException( s"Cannot parse the nominal voltage $quantString", @@ -84,5 +84,4 @@ object VoltLvlParser { cce ) } - } } diff --git a/src/main/scala/edu/ie3/simona/event/listener/ResultEventListener.scala b/src/main/scala/edu/ie3/simona/event/listener/ResultEventListener.scala index 38539b2baa..5cf14529f3 100644 --- a/src/main/scala/edu/ie3/simona/event/listener/ResultEventListener.scala +++ b/src/main/scala/edu/ie3/simona/event/listener/ResultEventListener.scala @@ -21,7 +21,7 @@ import edu.ie3.simona.exceptions.{ FileHierarchyException, ProcessResultEventException } -import edu.ie3.simona.io.result._ +import edu.ie3.simona.io.result.* import edu.ie3.simona.ontology.messages.StopMessage import edu.ie3.simona.util.ResultFileHierarchy import org.slf4j.Logger @@ -35,13 +35,13 @@ object ResultEventListener extends Transformer3wResultSupport { trait ResultMessage extends Event - private final case class SinkResponse( - response: Map[Class[_], ResultEntitySink] + final private case class SinkResponse( + response: Map[Class[?], ResultEntitySink] ) extends ResultMessage - private final case class Failed(ex: Exception) extends ResultMessage + final private case class Failed(ex: Exception) extends ResultMessage - private final case object StopTimeout extends ResultMessage + final private case object StopTimeout extends ResultMessage /** [[ResultEventListener]] base data containing all information the listener * needs @@ -50,8 +50,8 @@ object ResultEventListener extends Transformer3wResultSupport { * a map containing the sink for each class that should be processed by the * listener */ - private final case class BaseData( - classToSink: Map[Class[_], ResultEntitySink], + final private case class BaseData( + classToSink: Map[Class[?], ResultEntitySink], threeWindingResults: Map[ Transformer3wKey, AggregatedTransformer3wResult @@ -69,11 +69,11 @@ object ResultEventListener extends Transformer3wResultSupport { */ private def initializeSinks( resultFileHierarchy: ResultFileHierarchy - ): Iterable[Future[(Class[_], ResultEntitySink)]] = { + ): Iterable[Future[(Class[?], ResultEntitySink)]] = resultFileHierarchy.resultSinkType match { case _: ResultSinkType.Csv => resultFileHierarchy.resultEntitiesToConsider - .map(resultClass => { + .map { resultClass => resultFileHierarchy.rawOutputDataFilePaths .get(resultClass) .map(Future.successful) @@ -86,7 +86,8 @@ object ResultEventListener extends Transformer3wResultSupport { ) ) .flatMap { fileName => - if (fileName.endsWith(".csv") || fileName.endsWith(".csv.gz")) { + if fileName.endsWith(".csv") || fileName.endsWith(".csv.gz") + then { Future { ( resultClass, @@ -105,7 +106,7 @@ object ResultEventListener extends Transformer3wResultSupport { ) } } - }) + } case ResultSinkType.InfluxDb1x(url, database, scenario) => // creates one connection per result entity that should be processed resultFileHierarchy.resultEntitiesToConsider @@ -122,7 +123,7 @@ object ResultEventListener extends Transformer3wResultSupport { schemaRegistryUrl, linger ) => - val classes: Iterable[Class[_ <: ResultEntity]] = Set( + val classes: Iterable[Class[? <: ResultEntity]] = Set( classOf[NodeResult] // currently, only NodeResults are sent out ) classes.map(clz => @@ -140,7 +141,6 @@ object ResultEventListener extends Transformer3wResultSupport { ) ) } - } /** Handle the given result and possibly update the state data * @@ -185,7 +185,7 @@ object ResultEventListener extends Transformer3wResultSupport { ) // add partial result val updatedResults = partialResult.add(result).map { updatedResult => - if (updatedResult.ready) { + if updatedResult.ready then { // if result is complete, we can write it out updatedResult.consolidate.foreach { handOverToSink(_, baseData.classToSink, log) @@ -220,7 +220,7 @@ object ResultEventListener extends Transformer3wResultSupport { */ private def handOverToSink( resultEntity: ResultEntity, - classToSink: Map[Class[_], ResultEntitySink], + classToSink: Map[Class[?], ResultEntitySink], log: Logger ): Unit = Try { diff --git a/src/main/scala/edu/ie3/simona/event/listener/RuntimeEventListener.scala b/src/main/scala/edu/ie3/simona/event/listener/RuntimeEventListener.scala index a45fdd5f86..3212d1228c 100644 --- a/src/main/scala/edu/ie3/simona/event/listener/RuntimeEventListener.scala +++ b/src/main/scala/edu/ie3/simona/event/listener/RuntimeEventListener.scala @@ -74,8 +74,7 @@ object RuntimeEventListener { case (ctx, event) => val process = eventsToProcess.forall(_.contains(event.id)) - if (process) - processEvent(listeners, event, runtimeStats, ctx.log) + if process then processEvent(listeners, event, runtimeStats, ctx.log) else ctx.log.debug( "Skipping event {} as it is not in the list of events to process.", diff --git a/src/main/scala/edu/ie3/simona/event/listener/Transformer3wResultSupport.scala b/src/main/scala/edu/ie3/simona/event/listener/Transformer3wResultSupport.scala index 5eb68a5653..8ea7d9472d 100644 --- a/src/main/scala/edu/ie3/simona/event/listener/Transformer3wResultSupport.scala +++ b/src/main/scala/edu/ie3/simona/event/listener/Transformer3wResultSupport.scala @@ -100,7 +100,7 @@ private[listener] trait Transformer3wResultSupport { def add( result: PartialTransformer3wResult - ): Try[AggregatedTransformer3wResult] = { + ): Try[AggregatedTransformer3wResult] = result match { case portA: PartialTransformer3wResult.PortA if a.isEmpty => Success(copy(a = Some(portA))) @@ -115,7 +115,6 @@ private[listener] trait Transformer3wResultSupport { ) ) } - } } final object AggregatedTransformer3wResult { diff --git a/src/main/scala/edu/ie3/simona/event/notifier/Notifier.scala b/src/main/scala/edu/ie3/simona/event/notifier/Notifier.scala index 916a97f9cb..4a987be226 100644 --- a/src/main/scala/edu/ie3/simona/event/notifier/Notifier.scala +++ b/src/main/scala/edu/ie3/simona/event/notifier/Notifier.scala @@ -13,7 +13,6 @@ trait Notifier extends Actor { def listener: Iterable[ActorRef] - def notifyListener(event: Event): Unit = { + def notifyListener(event: Event): Unit = listener.foreach(listener => listener ! event) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/CharacteristicsException.scala b/src/main/scala/edu/ie3/simona/exceptions/CharacteristicsException.scala index 7bd3b4a839..fa8078b0cd 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/CharacteristicsException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/CharacteristicsException.scala @@ -21,12 +21,10 @@ class CharacteristicsException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/FileHierarchyException.scala b/src/main/scala/edu/ie3/simona/exceptions/FileHierarchyException.scala index b2a830df4a..5725ddc993 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/FileHierarchyException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/FileHierarchyException.scala @@ -18,12 +18,10 @@ class FileHierarchyException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/FileIOException.scala b/src/main/scala/edu/ie3/simona/exceptions/FileIOException.scala index 2d66038485..0edaccfe74 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/FileIOException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/FileIOException.scala @@ -18,11 +18,9 @@ class FileIOException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/GridInconsistencyException.scala b/src/main/scala/edu/ie3/simona/exceptions/GridInconsistencyException.scala index 951663c3a1..facd8a0aeb 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/GridInconsistencyException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/GridInconsistencyException.scala @@ -18,12 +18,10 @@ class GridInconsistencyException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/InitializationException.scala b/src/main/scala/edu/ie3/simona/exceptions/InitializationException.scala index 7a1b849a09..7e555b50a4 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/InitializationException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/InitializationException.scala @@ -18,12 +18,10 @@ class InitializationException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/InvalidActionRequestException.scala b/src/main/scala/edu/ie3/simona/exceptions/InvalidActionRequestException.scala index 928e13ce74..3f1d2b7cc4 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/InvalidActionRequestException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/InvalidActionRequestException.scala @@ -19,12 +19,10 @@ class InvalidActionRequestException(message: String) initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/InvalidConfigParameterException.scala b/src/main/scala/edu/ie3/simona/exceptions/InvalidConfigParameterException.scala index 735549f081..72bbd23a54 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/InvalidConfigParameterException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/InvalidConfigParameterException.scala @@ -17,12 +17,10 @@ class InvalidConfigParameterException(message: String) initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/InvalidParameterException.scala b/src/main/scala/edu/ie3/simona/exceptions/InvalidParameterException.scala index 3ba3db6372..e990a159a5 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/InvalidParameterException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/InvalidParameterException.scala @@ -18,12 +18,10 @@ class InvalidParameterException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/ProcessResultEventException.scala b/src/main/scala/edu/ie3/simona/exceptions/ProcessResultEventException.scala index 40f9dc0964..aba7418999 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/ProcessResultEventException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/ProcessResultEventException.scala @@ -16,12 +16,10 @@ class ProcessResultEventException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/QControlException.scala b/src/main/scala/edu/ie3/simona/exceptions/QControlException.scala index 23dab92bee..7755877ada 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/QControlException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/QControlException.scala @@ -18,12 +18,10 @@ class QControlException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/QuantityException.scala b/src/main/scala/edu/ie3/simona/exceptions/QuantityException.scala index 92c21bddb8..abc0ea89e1 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/QuantityException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/QuantityException.scala @@ -19,11 +19,9 @@ class QuantityException(message: String) extends RuntimeException(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/SchedulerException.scala b/src/main/scala/edu/ie3/simona/exceptions/SchedulerException.scala index c46b25b7ad..2002edf126 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/SchedulerException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/SchedulerException.scala @@ -19,11 +19,9 @@ class SchedulerException(message: String) extends RuntimeException(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/ServiceException.scala b/src/main/scala/edu/ie3/simona/exceptions/ServiceException.scala index 7d7f3f2b9a..85880e3fcd 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/ServiceException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/ServiceException.scala @@ -13,12 +13,10 @@ final case class ServiceException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/SimonaAnalysisException.scala b/src/main/scala/edu/ie3/simona/exceptions/SimonaAnalysisException.scala index bc482e9115..9a4956c45b 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/SimonaAnalysisException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/SimonaAnalysisException.scala @@ -18,12 +18,10 @@ class SimonaAnalysisException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/agent/ActorNotRegisteredException.scala b/src/main/scala/edu/ie3/simona/exceptions/agent/ActorNotRegisteredException.scala index 4545a22269..7408f07102 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/agent/ActorNotRegisteredException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/agent/ActorNotRegisteredException.scala @@ -18,11 +18,9 @@ class ActorNotRegisteredException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/agent/AgentInitializationException.scala b/src/main/scala/edu/ie3/simona/exceptions/agent/AgentInitializationException.scala index 026dfaffb3..78534fcb19 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/agent/AgentInitializationException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/agent/AgentInitializationException.scala @@ -19,12 +19,10 @@ class AgentInitializationException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/agent/DBFSAlgorithmException.scala b/src/main/scala/edu/ie3/simona/exceptions/agent/DBFSAlgorithmException.scala index f81db9b9f5..c0402b154f 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/agent/DBFSAlgorithmException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/agent/DBFSAlgorithmException.scala @@ -18,12 +18,10 @@ class DBFSAlgorithmException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/agent/GridAgentInitializationException.scala b/src/main/scala/edu/ie3/simona/exceptions/agent/GridAgentInitializationException.scala index 0135485715..2f23269f4f 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/agent/GridAgentInitializationException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/agent/GridAgentInitializationException.scala @@ -19,12 +19,10 @@ class GridAgentInitializationException(message: String) initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/agent/InconsistentStateException.scala b/src/main/scala/edu/ie3/simona/exceptions/agent/InconsistentStateException.scala index 5de0ca87ba..dfd76743f9 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/agent/InconsistentStateException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/agent/InconsistentStateException.scala @@ -19,12 +19,10 @@ class InconsistentStateException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/agent/InvalidRequestException.scala b/src/main/scala/edu/ie3/simona/exceptions/agent/InvalidRequestException.scala index b64ac91e38..cfb067fd28 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/agent/InvalidRequestException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/agent/InvalidRequestException.scala @@ -18,11 +18,9 @@ class InvalidRequestException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/exceptions/agent/ServiceRegistrationException.scala b/src/main/scala/edu/ie3/simona/exceptions/agent/ServiceRegistrationException.scala index 1ed932efba..5e7adece64 100644 --- a/src/main/scala/edu/ie3/simona/exceptions/agent/ServiceRegistrationException.scala +++ b/src/main/scala/edu/ie3/simona/exceptions/agent/ServiceRegistrationException.scala @@ -17,11 +17,9 @@ class ServiceRegistrationException(message: String) extends Exception(message) { initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/main/scala/edu/ie3/simona/io/grid/CsvGridSource.scala b/src/main/scala/edu/ie3/simona/io/grid/CsvGridSource.scala index fa7016a09a..deed1bb7cb 100644 --- a/src/main/scala/edu/ie3/simona/io/grid/CsvGridSource.scala +++ b/src/main/scala/edu/ie3/simona/io/grid/CsvGridSource.scala @@ -7,9 +7,9 @@ package edu.ie3.simona.io.grid import edu.ie3.datamodel.io.naming.FileNamingStrategy -import edu.ie3.datamodel.io.source._ -import edu.ie3.datamodel.io.source.csv._ -import edu.ie3.datamodel.models.input.container._ +import edu.ie3.datamodel.io.source.* +import edu.ie3.datamodel.io.source.csv.* +import edu.ie3.datamodel.models.input.container.* import edu.ie3.datamodel.models.input.thermal.{ ThermalBusInput, ThermalHouseInput, @@ -17,7 +17,7 @@ import edu.ie3.datamodel.models.input.thermal.{ } import java.nio.file.Path -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* object CsvGridSource { def readThermalGrids( diff --git a/src/main/scala/edu/ie3/simona/io/grid/GridProvider.scala b/src/main/scala/edu/ie3/simona/io/grid/GridProvider.scala index 4818b95fb1..10f5b1c904 100644 --- a/src/main/scala/edu/ie3/simona/io/grid/GridProvider.scala +++ b/src/main/scala/edu/ie3/simona/io/grid/GridProvider.scala @@ -32,7 +32,7 @@ object GridProvider extends LazyLogging { def gridFromConfig( simulationName: String, gridDataSource: SimonaConfig.Simona.Input.Grid.Datasource - ): JointGridContainer = { + ): JointGridContainer = GridSourceType(gridDataSource.id.toLowerCase) match { case GridSourceType.CSV => gridDataSource.csvParams match { @@ -71,7 +71,6 @@ object GridProvider extends LazyLogging { .mkString(", ")}." ) } - } def getThermalGridsFromConfig( gridDataSource: SimonaConfig.Simona.Input.Grid.Datasource diff --git a/src/main/scala/edu/ie3/simona/io/result/ResultEntityCsvSink.scala b/src/main/scala/edu/ie3/simona/io/result/ResultEntityCsvSink.scala index 304dfde6a6..c142d53ee6 100644 --- a/src/main/scala/edu/ie3/simona/io/result/ResultEntityCsvSink.scala +++ b/src/main/scala/edu/ie3/simona/io/result/ResultEntityCsvSink.scala @@ -20,7 +20,7 @@ import java.lang import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, Future} -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.jdk.FutureConverters.CompletionStageOps import scala.util.{Failure, Success} @@ -57,7 +57,7 @@ final case class ResultEntityCsvSink private ( * @return * a future holding information about the handling process */ - def handleResultEntity(resultEntity: ResultEntity): Unit = { + def handleResultEntity(resultEntity: ResultEntity): Unit = try { val attributeToValue = resultEntityProcessor .handleEntity(resultEntity) @@ -65,7 +65,7 @@ final case class ResultEntityCsvSink private ( .view val columns = resultEntityProcessor.getHeaderElements - val text = if (attributeToValue.nonEmpty) { + val text = if attributeToValue.nonEmpty then { val resString: String = columns .map { column => @@ -83,7 +83,6 @@ final case class ResultEntityCsvSink private ( case e: EntityProcessorException => throw new ProcessResultEventException("Processing result failed", e) } - } /** Creat the initial the .csv-file and write the header in the first row * @@ -130,8 +129,7 @@ final case class ResultEntityCsvSink private ( fileWriter.close() // compress files if necessary - if (compressOutputFiles) - Await.ready(zipAndDel(outfileName), 100.minutes) + if compressOutputFiles then Await.ready(zipAndDel(outfileName), 100.minutes) } } @@ -171,8 +169,7 @@ object ResultEntityCsvSink { delimiter ) - if (!existedBefore) - resultEntityCsvSink.writeHeader() + if !existedBefore then resultEntityCsvSink.writeHeader() resultEntityCsvSink } } diff --git a/src/main/scala/edu/ie3/simona/io/result/ResultEntityKafkaSink.scala b/src/main/scala/edu/ie3/simona/io/result/ResultEntityKafkaSink.scala index b9d8f1f272..e56f111cfd 100644 --- a/src/main/scala/edu/ie3/simona/io/result/ResultEntityKafkaSink.scala +++ b/src/main/scala/edu/ie3/simona/io/result/ResultEntityKafkaSink.scala @@ -21,7 +21,7 @@ import org.apache.kafka.clients.producer.{ import org.apache.kafka.common.serialization.{Serdes, Serializer} import java.util.{Properties, UUID} -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.reflect.ClassTag final case class ResultEntityKafkaSink[ @@ -54,9 +54,9 @@ object ResultEntityKafkaSink { bootstrapServers: String, schemaRegistryUrl: String, linger: Int - )(implicit + )(using tag: ClassTag[R] - ): ResultEntityKafkaSink[_ <: ResultEntity, _ <: PlainResult] = { + ): ResultEntityKafkaSink[? <: ResultEntity, ? <: PlainResult] = { val props = new Properties() props.put(ProducerConfig.LINGER_MS_CONFIG, linger) props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers) @@ -69,7 +69,7 @@ object ResultEntityKafkaSink { tag.runtimeClass match { case NodeResClass => - implicit val recordFormat: RecordFormat[PlainNodeResult] = + given recordFormat: RecordFormat[PlainNodeResult] = RecordFormat[PlainNodeResult] createSink(schemaRegistryUrl, props, topic, NodeResultWriter(simRunId)) } diff --git a/src/main/scala/edu/ie3/simona/io/result/ResultSinkType.scala b/src/main/scala/edu/ie3/simona/io/result/ResultSinkType.scala index d4c444fdd7..728a6f410b 100644 --- a/src/main/scala/edu/ie3/simona/io/result/ResultSinkType.scala +++ b/src/main/scala/edu/ie3/simona/io/result/ResultSinkType.scala @@ -41,7 +41,7 @@ object ResultSinkType { val sink: Seq[Any] = Seq(sinkConfig.csv, sinkConfig.influxDb1x, sinkConfig.kafka).flatten - if (sink.size > 1) + if sink.size > 1 then throw new IllegalArgumentException( s"Multiple sinks are not supported! Provided sinks: '$sinkConfig'" ) @@ -73,7 +73,7 @@ object ResultSinkType { def buildInfluxDb1xUrl( sinkConfig: SimonaConfig.Simona.Output.Sink.InfluxDb1x ): String = { - if (sinkConfig.url.endsWith("/")) sinkConfig.url.replaceAll("/", "") + if sinkConfig.url.endsWith("/") then sinkConfig.url.replaceAll("/", "") else sinkConfig.url }.trim.concat(s":${sinkConfig.port}") diff --git a/src/main/scala/edu/ie3/simona/io/result/plain/PlainWriter.scala b/src/main/scala/edu/ie3/simona/io/result/plain/PlainWriter.scala index 993f43d0c9..06c95762da 100644 --- a/src/main/scala/edu/ie3/simona/io/result/plain/PlainWriter.scala +++ b/src/main/scala/edu/ie3/simona/io/result/plain/PlainWriter.scala @@ -55,7 +55,7 @@ object PlainWriter { final case class NodeResultWriter(simRunId: UUID) extends PlainWriter[NodeResult, PlainNodeResult] { - override def writePlain(full: NodeResult): PlainNodeResult = { + override def writePlain(full: NodeResult): PlainNodeResult = PlainNodeResult( simRunId, createSimpleTimeStamp(full.getTime), @@ -64,9 +64,8 @@ object PlainWriter { full.getvMag.getValue.doubleValue(), full.getvAng.getValue.doubleValue() ) - } - override def createFull(plain: PlainNodeResult): NodeResult = { + override def createFull(plain: PlainNodeResult): NodeResult = new NodeResult( plain.uuid, ZonedDateTime.parse(plain.time, timeFormatter), @@ -74,7 +73,6 @@ object PlainWriter { Quantities.getQuantity(plain.vMag, PowerSystemUnits.PU), Quantities.getQuantity(plain.vAng, PowerSystemUnits.DEGREE_GEOM) ) - } } def createSimpleTimeStamp(dateTime: ZonedDateTime): String = diff --git a/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventKafkaSink.scala b/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventKafkaSink.scala index dea2b50642..a8cf45a41c 100644 --- a/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventKafkaSink.scala +++ b/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventKafkaSink.scala @@ -22,7 +22,7 @@ import org.apache.kafka.common.serialization.{Serdes, Serializer} import org.slf4j.Logger import java.util.{Properties, UUID} -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Runtime event sink that sends events related to the simulation ending to a * kafka topic. @@ -43,7 +43,7 @@ final case class RuntimeEventKafkaSink( runtimeEvent: RuntimeEvent, runtimeStats: RuntimeStats, log: Logger - ): Unit = { + ): Unit = (runtimeEvent match { case Done(_, _, errorInSim) => Some( @@ -64,8 +64,6 @@ final case class RuntimeEventKafkaSink( ) } - } - override def close(): Unit = { producer.flush() producer.close() @@ -86,7 +84,7 @@ object RuntimeEventKafkaSink { true ) // exactly once delivery - implicit val recordFormat: RecordFormat[SimonaEndMessage] = + given recordFormat: RecordFormat[SimonaEndMessage] = RecordFormat[SimonaEndMessage] val keySerializer = Serdes.String().serializer() diff --git a/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventLogSink.scala b/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventLogSink.scala index 833b5907dd..c2880fc47a 100644 --- a/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventLogSink.scala +++ b/src/main/scala/edu/ie3/simona/io/runtime/RuntimeEventLogSink.scala @@ -6,7 +6,7 @@ package edu.ie3.simona.io.runtime import edu.ie3.simona.event.RuntimeEvent -import edu.ie3.simona.event.RuntimeEvent._ +import edu.ie3.simona.event.RuntimeEvent.* import edu.ie3.simona.io.runtime.RuntimeEventSink.RuntimeStats import edu.ie3.simona.util.TickUtil.TickLong import edu.ie3.util.TimeUtil @@ -54,7 +54,7 @@ final case class RuntimeEventLogSink( case Done(currentTick, duration, errorInSim) => val simStatus = - if (errorInSim) + if errorInSim then s"\u001b[0;31mERROR (Failed PF: ${runtimeStats.failedPowerFlows})\u001b[0;30m" else s"\u001b[0;32mSUCCESS (Failed PF: ${runtimeStats.failedPowerFlows})\u001b[0;30m" @@ -71,13 +71,12 @@ final case class RuntimeEventLogSink( ) } - private def calcTime(currentTick: Long): String = { + private def calcTime(currentTick: Long): String = TimeUtil.withDefaults.toString( currentTick.toDateTime( simulationStartDate ) ) - } private def convertDuration(duration: Long): String = { val durationInSeconds = duration / 1000 diff --git a/src/main/scala/edu/ie3/simona/logging/SimonaActorLogging.scala b/src/main/scala/edu/ie3/simona/logging/SimonaActorLogging.scala index 1a78a9f254..1fdfa9d440 100644 --- a/src/main/scala/edu/ie3/simona/logging/SimonaActorLogging.scala +++ b/src/main/scala/edu/ie3/simona/logging/SimonaActorLogging.scala @@ -12,7 +12,7 @@ import org.apache.pekko.event.LoggingAdapter trait SimonaActorLogging extends ActorLogging with SimonaLogging { this: Actor => - override final val log: LoggingAdapter = + final override val log: LoggingAdapter = SimonaLogging.createAdapter(context.system, this, actorName) } diff --git a/src/main/scala/edu/ie3/simona/logging/SimonaFSMActorLogging.scala b/src/main/scala/edu/ie3/simona/logging/SimonaFSMActorLogging.scala index cfc618bc85..3ca9f05800 100644 --- a/src/main/scala/edu/ie3/simona/logging/SimonaFSMActorLogging.scala +++ b/src/main/scala/edu/ie3/simona/logging/SimonaFSMActorLogging.scala @@ -10,9 +10,9 @@ import org.apache.pekko.actor.{ActorLogging, FSM} import org.apache.pekko.event.LoggingAdapter trait SimonaFSMActorLogging extends ActorLogging with SimonaLogging { - this: FSM[_, _] => + this: FSM[?, ?] => - override final val log: LoggingAdapter = + final override val log: LoggingAdapter = SimonaLogging.createAdapter( context.system, () => stateName, diff --git a/src/main/scala/edu/ie3/simona/logging/SimonaLogging.scala b/src/main/scala/edu/ie3/simona/logging/SimonaLogging.scala index 5cb449ab3d..97dd3760aa 100644 --- a/src/main/scala/edu/ie3/simona/logging/SimonaLogging.scala +++ b/src/main/scala/edu/ie3/simona/logging/SimonaLogging.scala @@ -77,12 +77,12 @@ object SimonaLogging { final case class SimonaBusLogging( bus: LoggingBus, logSource: String, - logClass: Class[_], + logClass: Class[?], loggingFilter: LoggingFilter, prefix: () => String ) extends LoggingAdapter { - import org.apache.pekko.event.Logging._ + import org.apache.pekko.event.Logging.* def isErrorEnabled: Boolean = loggingFilter.isErrorEnabled(logClass, logSource) diff --git a/src/main/scala/edu/ie3/simona/logging/logback/LogbackConfiguration.scala b/src/main/scala/edu/ie3/simona/logging/logback/LogbackConfiguration.scala index 8aa16d5174..fc3ada7b83 100644 --- a/src/main/scala/edu/ie3/simona/logging/logback/LogbackConfiguration.scala +++ b/src/main/scala/edu/ie3/simona/logging/logback/LogbackConfiguration.scala @@ -17,11 +17,11 @@ import com.typesafe.scalalogging.LazyLogging import org.slf4j.LoggerFactory import java.io.File -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* object LogbackConfiguration extends LazyLogging { - def default(logPath: String): Unit = { + def default(logPath: String): Unit = LoggerFactory.getILoggerFactory match { case loggerContext: LoggerContext => val rootLogger = loggerContext.getLogger("root") @@ -44,7 +44,7 @@ object LogbackConfiguration extends LazyLogging { ) rootLogger.iteratorForAppenders().asScala.foreach { - case rf: RollingFileAppender[_] => + case rf: RollingFileAppender[?] => rf.getTriggeringPolicy.start() rf.start() case appender => appender.start() @@ -55,8 +55,6 @@ object LogbackConfiguration extends LazyLogging { ) } - } - private def fileAppender( logPath: String, appenderName: String, @@ -77,7 +75,7 @@ object LogbackConfiguration extends LazyLogging { /* If applicable, apply the filters from existing file logger else log with "INFO"-Level */ maybeFilterList match { case Some(filterList) => - if (filterList.isEmpty) { // No filters in appenders -> Empty List + if filterList.isEmpty then { // No filters in appenders -> Empty List val filter = new ThresholdFilter() filter.setLevel("INFO") filter.start() diff --git a/src/main/scala/edu/ie3/simona/main/RunSimona.scala b/src/main/scala/edu/ie3/simona/main/RunSimona.scala index 449a16df25..0760e4289f 100644 --- a/src/main/scala/edu/ie3/simona/main/RunSimona.scala +++ b/src/main/scala/edu/ie3/simona/main/RunSimona.scala @@ -28,8 +28,8 @@ import scala.util.Random trait RunSimona[T <: SimonaSetup] extends LazyLogging { // timeout parameter - implicit val timeout: Timeout - implicit lazy val timeoutDuration: FiniteDuration = timeout.duration + given timeout: Timeout + given timeoutDuration: FiniteDuration = timeout.duration def main(args: Array[String]): Unit = { Locale.setDefault(Locale.ENGLISH) @@ -51,16 +51,14 @@ trait RunSimona[T <: SimonaSetup] extends LazyLogging { def shutdownGracefully( simonaSim: ActorRef - )(implicit timeout: FiniteDuration): Future[Boolean] = { + )(using timeout: FiniteDuration): Future[Boolean] = gracefulStop(simonaSim, timeout) - } // a fancy opener - protected def printOpener(): Unit = { + protected def printOpener(): Unit = logger.info( s"Starting SIMONA with interface '${getClass.getSimpleName.replaceAll("\\$", "")}'.\n" + " _____ ______ _______ _ _____ \n / ___// _/ |/ / __ \\/ | / / |\n \\__ \\ / // /|_/ / / / / |/ / /| |\n ___/ // // / / / /_/ / /| / ___ |\n/____/___/_/ /_/\\____/_/ |_/_/ |_|\n " ) - } def printGoodbye(): Unit = { val myWords = Array( diff --git a/src/main/scala/edu/ie3/simona/main/RunSimonaStandalone.scala b/src/main/scala/edu/ie3/simona/main/RunSimonaStandalone.scala index 5a8bee6d2e..c9d584f403 100644 --- a/src/main/scala/edu/ie3/simona/main/RunSimonaStandalone.scala +++ b/src/main/scala/edu/ie3/simona/main/RunSimonaStandalone.scala @@ -30,7 +30,7 @@ import scala.concurrent.Await */ object RunSimonaStandalone extends RunSimona[SimonaStandaloneSetup] { - override implicit val timeout: Timeout = Timeout(50000, TimeUnit.SECONDS) + override given timeout: Timeout = Timeout(50000, TimeUnit.SECONDS) override def setup( args: Array[String] diff --git a/src/main/scala/edu/ie3/simona/model/SystemComponent.scala b/src/main/scala/edu/ie3/simona/model/SystemComponent.scala index a81c235bf9..e007fe28d1 100644 --- a/src/main/scala/edu/ie3/simona/model/SystemComponent.scala +++ b/src/main/scala/edu/ie3/simona/model/SystemComponent.scala @@ -15,10 +15,10 @@ import edu.ie3.simona.exceptions.{ InvalidActionRequestException, InvalidParameterException } -import edu.ie3.simona.util.TickUtil._ +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.scala.OperationInterval -import scala.jdk.OptionConverters._ +import scala.jdk.OptionConverters.* import scala.util.{Failure, Success, Try} /** Interface that is implemented by all grid elements (e.g. lines, @@ -41,7 +41,7 @@ abstract class SystemComponent( private val elementType: String = this.getClass.getSimpleName // check if a uuid is provided - if (Option.apply(uuid).isEmpty) + if Option.apply(uuid).isEmpty then throw new InvalidParameterException( s"Uuid of $elementType $id cannot be null!" ) @@ -50,8 +50,8 @@ abstract class SystemComponent( /** Enable the corresponding element. */ - def enable(): Try[String] = { - if (_inOperation) { + def enable(): Try[String] = + if _inOperation then { Failure( new InvalidActionRequestException( s"$elementType $id is already in operation!" @@ -61,12 +61,11 @@ abstract class SystemComponent( _inOperation = true Success(s"$elementType $id enabled!") } - } /** Disable the corresponding element. */ - def disable(): Try[String] = { - if (_inOperation) { + def disable(): Try[String] = + if _inOperation then { _inOperation = false Success(s"$elementType $id disabled!") } else { @@ -76,7 +75,6 @@ abstract class SystemComponent( ) ) } - } def isInOperation: Boolean = _inOperation diff --git a/src/main/scala/edu/ie3/simona/model/grid/GridModel.scala b/src/main/scala/edu/ie3/simona/model/grid/GridModel.scala index fd1ea11df2..ae1bcd4d78 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/GridModel.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/GridModel.scala @@ -9,7 +9,7 @@ package edu.ie3.simona.model.grid import breeze.linalg.DenseMatrix import breeze.math.Complex import edu.ie3.datamodel.exceptions.InvalidGridException -import edu.ie3.datamodel.models.input.connector._ +import edu.ie3.datamodel.models.input.connector.* import edu.ie3.datamodel.models.input.container.SubGridContainer import edu.ie3.simona.exceptions.GridInconsistencyException import edu.ie3.simona.model.SystemComponent @@ -27,7 +27,7 @@ import org.jgrapht.graph.{DefaultEdge, SimpleGraph} import java.time.ZonedDateTime import java.util.UUID import scala.collection.immutable.ListSet -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Representation of one physical electrical grid. It holds the references to * nodes, lines, switches and transformers and fundamental properties (like @@ -65,9 +65,8 @@ case object GridModel { refSystem: RefSystem, startDate: ZonedDateTime, endDate: ZonedDateTime - ): GridModel = { + ): GridModel = buildAndValidate(subGridContainer, refSystem, startDate, endDate) - } /** structure that represents all grid components that are needed by a grid * model @@ -141,7 +140,7 @@ case object GridModel { val nodeInternal: Option[NodeModel] = nodes.find(_.uuid.equals(transformerInput.getNodeInternal.getUuid)) - if (nodeInternal.isEmpty) + if nodeInternal.isEmpty then throw new InvalidGridException( s"Internal node ${transformerInput.getNodeInternal.getId} of transformer3w ${transformerInput.getUuid} cannot be found in provided set of nodes!" ) @@ -156,12 +155,11 @@ case object GridModel { } } - private val throwNodeNotFoundException: UUID => InvalidGridException = { + private val throwNodeNotFoundException: UUID => InvalidGridException = nodeString: UUID => throw new InvalidGridException( s"Node $nodeString is not in nodeUuidToIndexMap! Cannot build admittanceMatrix!" ) - } def composeAdmittanceMatrix( nodeUuidToIndexMap: Map[UUID, Int], @@ -170,18 +168,14 @@ case object GridModel { val _returnAdmittanceMatrixIfValid : DenseMatrix[Complex] => DenseMatrix[Complex] = { - admittanceMatrix: DenseMatrix[Complex] => - if ( - !breeze.linalg.all( - { entry: Complex => - !entry.imag.isNaN & !entry.real.isNaN & entry.imag.isFinite & entry.real.isFinite - }, + (admittanceMatrix: DenseMatrix[Complex]) => + if !breeze.linalg.all( + (entry: Complex) => + !entry.imag.isNaN & !entry.real.isNaN & entry.imag.isFinite & entry.real.isFinite, admittanceMatrix ) - ) - throw new RuntimeException(s"Admittance matrix is illegal.") - else - admittanceMatrix + then throw new RuntimeException(s"Admittance matrix is illegal.") + else admittanceMatrix } /* @@ -221,8 +215,8 @@ case object GridModel { assets .filter(_.isInOperation) - .foldLeft(DenseMatrix.zeros[Complex](matrixDimension, matrixDimension))( - (admittanceMatrix, asset) => { + .foldLeft(DenseMatrix.zeros[Complex](matrixDimension, matrixDimension)) { + (admittanceMatrix, asset) => val (i, j, yab, yaa, ybb) = getAssetAdmittance(nodeUuidToIndexMap, asset) @@ -231,8 +225,7 @@ case object GridModel { admittanceMatrix(i, j) += (yab * -1) admittanceMatrix(j, i) += (yab * -1) admittanceMatrix - } - ) + } } private def getLinesAdmittance( @@ -337,18 +330,15 @@ case object GridModel { val graph: Graph[UUID, DefaultEdge] = new SimpleGraph(classOf[DefaultEdge]) gridModel.gridComponents.nodes - .filter(_.isInOperation) foreach (node => graph.addVertex(node.uuid)) + .filter(_.isInOperation) + .foreach(node => graph.addVertex(node.uuid)) gridModel.gridComponents.lines .filter(_.isInOperation) - .foreach(line => { - graph.addEdge(line.nodeAUuid, line.nodeBUuid) - }) + .foreach(line => graph.addEdge(line.nodeAUuid, line.nodeBUuid)) gridModel.gridComponents.transformers .filter(_.isInOperation) - .foreach(trafo => { - graph.addEdge(trafo.hvNodeUuid, trafo.lvNodeUuid) - }) + .foreach(trafo => graph.addEdge(trafo.hvNodeUuid, trafo.lvNodeUuid)) gridModel.gridComponents.transformers3w .filter(_.isInOperation) @@ -366,14 +356,12 @@ case object GridModel { gridModel.gridComponents.switches .filter(_.isInOperation) - .foreach(switch => { - graph.addEdge(switch.nodeAUuid, switch.nodeBUuid) - }) + .foreach(switch => graph.addEdge(switch.nodeAUuid, switch.nodeBUuid)) val inspector: ConnectivityInspector[UUID, DefaultEdge] = new ConnectivityInspector(graph) - if (!inspector.isConnected) { + if !inspector.isConnected then { throw new GridInconsistencyException( s"The grid with subnetNo ${gridModel.subnetNo} is not connected! Please ensure that all elements are connected correctly and inOperation is set to true!" ) @@ -383,10 +371,8 @@ case object GridModel { private def validateConsistency(gridModel: GridModel): Unit = { // null or empty elements in grid elements? - if ( - gridModel.gridComponents.nodes == null || gridModel.gridComponents.nodes.isEmpty - ) - throw new InvalidGridException("The grid contains no nodes.") + if gridModel.gridComponents.nodes == null || gridModel.gridComponents.nodes.isEmpty + then throw new InvalidGridException("The grid contains no nodes.") val noLines = gridModel.gridComponents.lines == null || gridModel.gridComponents.lines.isEmpty val noTransformers2w = @@ -395,31 +381,30 @@ case object GridModel { gridModel.gridComponents.transformers3w == null || gridModel.gridComponents.transformers3w.isEmpty val noOfNodes = gridModel.gridComponents.nodes.size val noOfSlackNodes = gridModel.slackNodesIndices.size - if ( - noLines && noTransformers2w && noTransformers3w && (noOfNodes > noOfSlackNodes) - ) + if noLines && noTransformers2w && noTransformers3w && (noOfNodes > noOfSlackNodes) + then throw new InvalidGridException( "The grid contains no basic branch elements (lines or transformers)." ) // slack - if (gridModel.slackNodesIndices.isEmpty) + if gridModel.slackNodesIndices.isEmpty then new InvalidGridException( s"The grid model for subnet ${gridModel.subnetNo} has no slack node!" ) // electrical struct data - if (gridModel.mainRefSystem.nominalPower.value.doubleValue < 0.0) + if gridModel.mainRefSystem.nominalPower.value.doubleValue < 0.0 then throw new InvalidGridException( s"Nominal Power of a grid cannot be < 0. Please correct the value of the reference system for grid no ${gridModel.subnetNo}" ) - if (gridModel.mainRefSystem.nominalVoltage.value.doubleValue < 0.0) + if gridModel.mainRefSystem.nominalVoltage.value.doubleValue < 0.0 then throw new InvalidGridException( s"Nominal Voltage of a grid cannot be < 0. Please correct the value of the reference system for grid no ${gridModel.subnetNo}" ) // subnet no - if (gridModel.subnetNo < 0) + if gridModel.subnetNo < 0 then throw new InvalidGridException( s"The grid model for subnet ${gridModel.subnetNo} has a subnet number less then zero." ) @@ -427,7 +412,7 @@ case object GridModel { // duplicate names for nodes val nodeUuids: List[UUID] = gridModel.gridComponents.nodes.toList.iterator.map(_.uuid).toList - if (CollectionUtils.listHasDuplicates(nodeUuids)) + if CollectionUtils.listHasDuplicates(nodeUuids) then throw new InvalidGridException( s"The grid model for subnet ${gridModel.subnetNo} has multiple nodes with the same name!" ) @@ -437,7 +422,7 @@ case object GridModel { Vector.empty[UUID] )((vector, switch) => (vector :+ switch.nodeAUuid) :+ switch.nodeBUuid) val uniqueSwitchNodeIds = switchVector.toSet.toList - if (switchVector.diff(uniqueSwitchNodeIds).nonEmpty) { + if switchVector.diff(uniqueSwitchNodeIds).nonEmpty then { throw new InvalidGridException( s"The grid model for subnet ${gridModel.subnetNo} has nodes with multiple switches. This is not supported yet! Duplicates are located @ nodes: ${switchVector .diff(uniqueSwitchNodeIds)}" @@ -474,7 +459,7 @@ case object GridModel { subGridContainer.getRawGrid.getTransformer2Ws.asScala.map { transformer2wInput => val (nodeA, _) = getConnectedNodes(transformer2wInput, nodes) - if (nodeA.isSlack) { + if nodeA.isSlack then { TransformerModel( transformer2wInput, refSystem, @@ -578,7 +563,7 @@ case object GridModel { ) case nodeModel: NodeModel => - if (!map.contains(nodeModel.uuid)) { + if !map.contains(nodeModel.uuid) then { val idx = map.values.toList.sorted.lastOption .getOrElse( -1 diff --git a/src/main/scala/edu/ie3/simona/model/grid/LineModel.scala b/src/main/scala/edu/ie3/simona/model/grid/LineModel.scala index 8ca2b2f0a9..da7082b72c 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/LineModel.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/LineModel.scala @@ -12,13 +12,13 @@ import edu.ie3.datamodel.exceptions.InvalidGridException import edu.ie3.datamodel.models.input.connector.LineInput import edu.ie3.simona.model.SystemComponent import edu.ie3.simona.util.SimonaConstants -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.OperationInterval import squants.Each import squants.electro.{Amperes, Ohms, Siemens} import tech.units.indriya.quantity.Quantities import tech.units.indriya.unit.Units -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.time.ZonedDateTime import java.util.UUID @@ -77,7 +77,7 @@ final case class LineModel( * branch conductance g_ij between node A and B of the element in p.u. */ override def gij(): squants.Dimensionless = - super.gij() * (amount) + super.gij() * amount /** see [[PiEquivalentCircuit.g0()]] * @@ -210,7 +210,7 @@ case object LineModel extends LazyLogging { ) // if the line input model is in operation, enable the model - if (operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION)) + if operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION) then lineModel.enable() // sanity check after creation for piEquivalent parameters r,x,g,b @@ -230,7 +230,7 @@ case object LineModel extends LazyLogging { */ def validateInputModel(lineInput: LineInput): Unit = { - if (lineInput.getNodeA == null || lineInput.getNodeB == null) + if lineInput.getNodeA == null || lineInput.getNodeB == null then throw new InvalidGridException( s"Nodes of line ${lineInput.getUuid} are missing." + s"NodeA: ${lineInput.getNodeA}, NodeB: ${lineInput.getNodeB}." @@ -241,69 +241,65 @@ case object LineModel extends LazyLogging { val vRatedNodeA = lineInput.getNodeA.getVoltLvl.getNominalVoltage val vRatedNodeB = lineInput.getNodeB.getVoltLvl.getNominalVoltage - if ( - lineType + if lineType .getvRated() .isLessThan(vRatedNodeA.subtract(ratedVoltageTolerance)) - ) + then throw new InvalidGridException( s"Line ${lineInput.getUuid} (${lineInput.getId}) has a rated voltage of ${lineType .getvRated()} but is connected to node A (${lineInput.getNodeA.getUuid} / ${lineInput.getNodeA.getId}), which has a rated voltage of $vRatedNodeA." ) - else if ( - lineType + else if lineType .getvRated() .isLessThan(vRatedNodeB.subtract(ratedVoltageTolerance)) - ) + then throw new InvalidGridException( s"Line ${lineInput.getUuid} (${lineInput.getId}) has a rated voltage of ${lineType .getvRated()} but is connected to node B (${lineInput.getNodeB.getUuid} / ${lineInput.getNodeB.getId}), which has a rated voltage of $vRatedNodeB." ) - else if ( - lineType + else if lineType .getvRated() .isGreaterThan(vRatedNodeA.add(ratedVoltageTolerance)) - ) + then logger.warn( s"Line ${lineInput.getUuid} (${lineInput.getId}) has a rated voltage of ${lineType .getvRated()} but is connected to node A (${lineInput.getNodeA.getUuid} / ${lineInput.getNodeA.getId}), which has a lower rated voltage of $vRatedNodeA." ) - else if ( - lineType + else if lineType .getvRated() .isGreaterThan(vRatedNodeB.add(ratedVoltageTolerance)) - ) + then logger.warn( s"Line ${lineInput.getUuid} (${lineInput.getId}) has a rated voltage of ${lineType .getvRated()} but is connected to node B (${lineInput.getNodeB.getUuid} / ${lineInput.getNodeB.getId}), which has a lower rated voltage of $vRatedNodeB." ) // length - if (lineInput.getLength.getValue.doubleValue() <= 0) + if lineInput.getLength.getValue.doubleValue() <= 0 then throw new InvalidGridException( s"Line ${lineInput.getUuid} has an invalid length of ${lineInput.getLength}" ) // electric params - if (lineType.getR.getValue.doubleValue() <= 0) + if lineType.getR.getValue.doubleValue() <= 0 then throw new InvalidGridException( s"Resistance r of lineType ${lineType.getUuid} used in line ${lineInput.getUuid} is 0 or smaller, " + s"which is not allowed! Please correct parameters!" ) - if (lineType.getX.getValue.doubleValue() <= 0) + if lineType.getX.getValue.doubleValue() <= 0 then throw new InvalidGridException( s"Reactance x of lineType ${lineType.getUuid} used in line ${lineInput.getUuid} is 0 or smaller," + s" which is not allowed! Please correct parameters!" ) - if (lineType.getB.getValue.doubleValue() < 0) + if lineType.getB.getValue.doubleValue() < 0 then throw new InvalidGridException( s"Susceptance b of lineType ${lineType.getUuid} used in line ${lineInput.getUuid} is smaller " + s"than 0, which is not allowed! Please correct parameters!" ) - if (lineType.getG.getValue.doubleValue() < 0) + if lineType.getG.getValue.doubleValue() < 0 then throw new InvalidGridException( s"Conductance g of lineType ${lineType.getUuid} used in line ${lineInput.getUuid} is smaller " + s"than 0, which is not allowed! Please correct parameters!" @@ -318,12 +314,11 @@ case object LineModel extends LazyLogging { * @return * phase-to-ground admittance Y_0 of the line model in p.u. */ - def y0(lineModel: LineModel): Complex = { + def y0(lineModel: LineModel): Complex = new Complex( lineModel.g0().value.doubleValue(), lineModel.b0().value.doubleValue() ) - } /** Calculate the branch admittance of a given line model * @@ -353,13 +348,12 @@ case object LineModel extends LazyLogging { lineModel: LineModel, iNodeA: squants.electro.ElectricCurrent, iNodeB: squants.electro.ElectricCurrent - ): squants.Dimensionless = { + ): squants.Dimensionless = Each( Math.max( iNodeA.toAmperes, iNodeB.toAmperes ) / lineModel.iNom.toAmperes * 100 / lineModel.amount ) - } } diff --git a/src/main/scala/edu/ie3/simona/model/grid/NodeModel.scala b/src/main/scala/edu/ie3/simona/model/grid/NodeModel.scala index 67acac7d8b..8995150b57 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/NodeModel.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/NodeModel.scala @@ -73,7 +73,7 @@ case object NodeModel { ) /* Checks, if the participant is in operation right from the start */ - if (operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION)) + if operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION) then nodeModel.enable() nodeModel @@ -88,20 +88,17 @@ case object NodeModel { * @param nodeInput * instance of [[NodeInput]] that should be validated */ - def validateInputModel(nodeInput: NodeInput): Unit = { - if ( - nodeInput.getvTarget() == null || nodeInput + def validateInputModel(nodeInput: NodeInput): Unit = + if nodeInput.getvTarget() == null || nodeInput .getvTarget() .getValue .doubleValue <= 0 || nodeInput .getvTarget() .getValue .doubleValue > 2 - ) + then throw new InvalidGridException( s"Invalid vTarget parameter in node ${nodeInput.getUuid}: ${nodeInput.getvTarget()}" ) - } - } diff --git a/src/main/scala/edu/ie3/simona/model/grid/PiEquivalentCircuit.scala b/src/main/scala/edu/ie3/simona/model/grid/PiEquivalentCircuit.scala index d1d85d7177..bb418ddb64 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/PiEquivalentCircuit.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/PiEquivalentCircuit.scala @@ -58,11 +58,10 @@ trait PiEquivalentCircuit extends LazyLogging { * branch conductance g_ij between node i and j of the element in p.u. */ protected def gij(): squants.Dimensionless = { - val gijVal: Double = { - if (rVal == 0) 0 - else if (xVal == 0) 1 / rVal + val gijVal: Double = + if rVal == 0 then 0 + else if xVal == 0 then 1 / rVal else rVal / (pow(rVal, 2) + pow(xVal, 2)) - } Each(gijVal) } @@ -80,11 +79,10 @@ trait PiEquivalentCircuit extends LazyLogging { * branch susceptance b_ij between node i and j of the element in p.u. */ protected def bij(): squants.Dimensionless = { - val bijVal = { - if (xVal == 0) 0 - else if (rVal == 0) -1 / xVal + val bijVal = + if xVal == 0 then 0 + else if rVal == 0 then -1 / xVal else -xVal / (pow(rVal, 2) + pow(xVal, 2)) - } Each(bijVal) } @@ -93,18 +91,16 @@ trait PiEquivalentCircuit extends LazyLogging { * @return * phase-to-ground conductance g_0 in p.u. */ - protected def g0(): squants.Dimensionless = { + protected def g0(): squants.Dimensionless = Each(gVal) - } /** "Computes" the TOTAL phase-to-ground susceptance of the grid element. * * @return * phase-to-ground susceptance b_0 in p.u. */ - protected def b0(): squants.Dimensionless = { + protected def b0(): squants.Dimensionless = Each(bVal) - } /** Simple method that displays a warning if the provided values seem * unreasonable high as this might cause trouble in further use. Note that, @@ -115,10 +111,10 @@ trait PiEquivalentCircuit extends LazyLogging { * @param modelType * optional model type to improve warning output */ - protected final def piEquivalentSanityCheck( + final protected def piEquivalentSanityCheck( modelType: String = "model" - ): Unit = { - if (rVal > 10 | xVal > 10 | bVal > 10 | gVal > 10) + ): Unit = + if rVal > 10 | xVal > 10 | bVal > 10 | gVal > 10 then logger.warn( s"PiEquivalent parameters for $modelType with uuid " + s"$uuid seem to be unreasonable. Values are r: {}, x: {}, g: {}, b: {}", @@ -127,6 +123,5 @@ trait PiEquivalentCircuit extends LazyLogging { g, b ) - } } diff --git a/src/main/scala/edu/ie3/simona/model/grid/RefSystem.scala b/src/main/scala/edu/ie3/simona/model/grid/RefSystem.scala index 53ee866930..0a0860b650 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/RefSystem.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/RefSystem.scala @@ -37,9 +37,8 @@ final case class RefSystem private ( */ def rInPu( r: squants.electro.ElectricalResistance - ): squants.Dimensionless = { + ): squants.Dimensionless = Each(r.toOhms / nominalImpedance.toOhms) - } /** Calculates the referenced reactance x (imaginary part of impedance z) of a * grid element. @@ -64,9 +63,8 @@ final case class RefSystem private ( */ def bInPu( b: squants.electro.ElectricalConductance - ): squants.Dimensionless = { + ): squants.Dimensionless = Each(b.toSiemens * nominalImpedance.toOhms) - } /** Calculates the referenced conductance g (real part of admittance y) of a * grid element. diff --git a/src/main/scala/edu/ie3/simona/model/grid/SwitchModel.scala b/src/main/scala/edu/ie3/simona/model/grid/SwitchModel.scala index 49d1d73402..8f344cd079 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/SwitchModel.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/SwitchModel.scala @@ -46,8 +46,8 @@ final case class SwitchModel( /** closes the switch or throws an exception if the switch is already closed */ - def close(): Try[String] = { - if (_isClosed) { + def close(): Try[String] = + if _isClosed then { Failure( new InvalidActionRequestException(s"Switch $id is already closed!") ) @@ -55,18 +55,16 @@ final case class SwitchModel( _isClosed = true Success(s"Switch $id closed!") } - } /** opens the switch or throws an exception if the switch is already opened */ - def open(): Try[String] = { - if (_isClosed) { + def open(): Try[String] = + if _isClosed then { _isClosed = false Success(s"Switch $id opened!") } else { Failure(new InvalidActionRequestException(s"Switch $id is already open!")) } - } /** returns the status information if the switch is closed * @return @@ -106,11 +104,10 @@ case object SwitchModel { switchInput.getNodeA.getUuid, switchInput.getNodeB.getUuid ) - if (!switchInput.isClosed) - switchModel.open() + if !switchInput.isClosed then switchModel.open() // if the switch input model is in operation, enable the model - if (operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION)) + if operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION) then switchModel.enable() switchModel @@ -128,16 +125,15 @@ case object SwitchModel { def validateInputModel(switchInput: SwitchInput): Unit = { // nodeA == nodeB ? - if (switchInput.getNodeA.getUuid == switchInput.getNodeB.getUuid) + if switchInput.getNodeA.getUuid == switchInput.getNodeB.getUuid then throw new InvalidGridException( s"Switch ${switchInput.getUuid} has the same nodes on port A and B! " + s"NodeA: ${switchInput.getNodeA.getUuid}, NodeB: ${switchInput.getNodeB.getUuid}" ) // nodeA.vRated != nodeB.vRated ? - if ( - switchInput.getNodeA.getVoltLvl.getNominalVoltage != switchInput.getNodeB.getVoltLvl.getNominalVoltage - ) + if switchInput.getNodeA.getVoltLvl.getNominalVoltage != switchInput.getNodeB.getVoltLvl.getNominalVoltage + then throw new InvalidGridException( s"Nodes of switch ${switchInput.getUuid} have different volt levels! " + s"vNom: (nodeA: ${switchInput.getNodeA.getVoltLvl.getNominalVoltage}, NodeB: ${switchInput.getNodeB.getVoltLvl.getNominalVoltage})" diff --git a/src/main/scala/edu/ie3/simona/model/grid/Transformer3wModel.scala b/src/main/scala/edu/ie3/simona/model/grid/Transformer3wModel.scala index 42f365a630..0673feff18 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/Transformer3wModel.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/Transformer3wModel.scala @@ -25,7 +25,7 @@ import edu.ie3.simona.model.grid.Transformer3wPowerFlowCase.{ PowerFlowCaseC } import edu.ie3.simona.util.SimonaConstants -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.OperationInterval import squants.electro.{Kilovolts, Ohms, Siemens} import squants.energy.Megawatts @@ -112,17 +112,15 @@ final case class Transformer3wModel( * @param newTapPos * the wanted tap position */ - override def updateTapPos(newTapPos: Int): Unit = { + override def updateTapPos(newTapPos: Int): Unit = powerFlowCase match { case PowerFlowCaseA => - if (newTapPos != currentTapPos) - super.updateTapPos(newTapPos) + if newTapPos != currentTapPos then super.updateTapPos(newTapPos) case _ => throw new InvalidActionRequestException( s"Updating tap position for transformer3w $uuid is not allowed in power flow case B and C." ) } - } /** Increase transformer tap position by the provided delta value. The * operation is only allowed in power flow case A. In all other cases an @@ -133,7 +131,7 @@ final case class Transformer3wModel( * @throws InvalidActionRequestException * in power flow cases B and C */ - override def incrTapPos(deltaTap: Int = 1): Unit = { + override def incrTapPos(deltaTap: Int = 1): Unit = powerFlowCase match { case PowerFlowCaseA => super.incrTapPos(deltaTap) @@ -142,7 +140,6 @@ final case class Transformer3wModel( s"Increasing tap position for transformer3w $uuid is not allowed in power flow case B and C." ) } - } /** Decrease transformer tap position by the provided delta value. The * operation is only allowed in power flow case A. In all other cases an @@ -153,7 +150,7 @@ final case class Transformer3wModel( * @throws InvalidActionRequestException * in power flow cases B and C */ - override def decrTapPos(deltaTap: Int): Unit = { + override def decrTapPos(deltaTap: Int): Unit = powerFlowCase match { case PowerFlowCaseA => super.decrTapPos(deltaTap) case _ => @@ -161,7 +158,6 @@ final case class Transformer3wModel( s"Decreasing tap position for transformer3w $uuid is not allowed in power flow case B and C." ) } - } } case object Transformer3wModel extends LazyLogging { @@ -284,7 +280,7 @@ case object Transformer3wModel extends LazyLogging { ) // if the transformer3w input model is in operation, enable the model - if (operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION)) + if operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION) then transformer3wModel.enable() // init the transformer tapping @@ -419,15 +415,15 @@ case object Transformer3wModel extends LazyLogging { val maxAllowedDeviation = 0.05 - if (nomVoltDevA > maxAllowedDeviation) + if nomVoltDevA > maxAllowedDeviation then throw new InvalidGridException( s"The rated voltage of node A is ${transformer3wInput.getNodeA.getVoltLvl.getNominalVoltage}, but the winding A is only rated for ${trafo3wType.getvRatedA}." ) - if (nomVoltDevB > maxAllowedDeviation) + if nomVoltDevB > maxAllowedDeviation then throw new InvalidGridException( s"The rated voltage of node B is ${transformer3wInput.getNodeB.getVoltLvl.getNominalVoltage}, but the winding B is only rated for ${trafo3wType.getvRatedB}." ) - if (nomVoltDevC > maxAllowedDeviation) + if nomVoltDevC > maxAllowedDeviation then throw new InvalidGridException( s"The rated voltage of node C is ${transformer3wInput.getNodeC.getVoltLvl.getNominalVoltage}, but the winding C is only rated for ${trafo3wType.getvRatedC}." ) @@ -440,21 +436,21 @@ case object Transformer3wModel extends LazyLogging { s"The rated voltage of node A is $vRatedNodeX, " + s"but the winding A is only rated for $typeVNodeX. Is the transformer connected correctly?" } - if (vNodeAVal < vTypeAVal) + if vNodeAVal < vTypeAVal then throw new InvalidGridException( transformerWrongPositionExceptionString( transformer3wInput.getNodeA.getVoltLvl.getNominalVoltage, trafo3wType.getvRatedA ) ) - if (vNodeBVal < vTypeBVal) + if vNodeBVal < vTypeBVal then throw new InvalidGridException( transformerWrongPositionExceptionString( transformer3wInput.getNodeB.getVoltLvl.getNominalVoltage, trafo3wType.getvRatedB ) ) - if (vNodeCVal < vTypeCVal) + if vNodeCVal < vTypeCVal then throw new InvalidGridException( transformerWrongPositionExceptionString( transformer3wInput.getNodeC.getVoltLvl.getNominalVoltage, @@ -467,9 +463,9 @@ case object Transformer3wModel extends LazyLogging { val sNomB = trafo3wType.getsRatedB.getValue.doubleValue val sNomC = trafo3wType.getsRatedC.getValue.doubleValue - if (sNomA < (sNomB + sNomC)) { + if sNomA < (sNomB + sNomC) then { val maxSNomUnderlying = max(sNomB, sNomC) - if (sNomA < maxSNomUnderlying) + if sNomA < maxSNomUnderlying then throw new InvalidParameterException( s"The winding A of transformer type has a lower rating ($sNomA) as winding B ($sNomB) or C ($sNomC)!" ) @@ -499,7 +495,7 @@ case object Transformer3wModel extends LazyLogging { * @return * Voltage ratio between high and low voltage side */ - def voltRatio(transformerModel: Transformer3wModel): BigDecimal = { + def voltRatio(transformerModel: Transformer3wModel): BigDecimal = transformerModel.powerFlowCase match { case Transformer3wPowerFlowCase.PowerFlowCaseA => BigDecimal @@ -509,7 +505,6 @@ case object Transformer3wModel extends LazyLogging { Transformer3wPowerFlowCase.PowerFlowCaseC => transformerModel.voltRatioNominal } - } /** Calculate the phase-to-ground admittance of a given transformer model. As * only the partial model for [[PowerFlowCaseA]] does contain a diff --git a/src/main/scala/edu/ie3/simona/model/grid/Transformer3wPowerFlowCase.scala b/src/main/scala/edu/ie3/simona/model/grid/Transformer3wPowerFlowCase.scala index 0b3e88252f..0a793a0c48 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/Transformer3wPowerFlowCase.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/Transformer3wPowerFlowCase.scala @@ -35,17 +35,13 @@ object Transformer3wPowerFlowCase { def apply( trafo3wInput: Transformer3WInput, subnetNo: Int - ): Transformer3wPowerFlowCase = { - if (trafo3wInput.getNodeA.getSubnet == subnetNo) - PowerFlowCaseA - else if (trafo3wInput.getNodeB.getSubnet == subnetNo) - PowerFlowCaseB - else if (trafo3wInput.getNodeC.getSubnet == subnetNo) - PowerFlowCaseC + ): Transformer3wPowerFlowCase = + if trafo3wInput.getNodeA.getSubnet == subnetNo then PowerFlowCaseA + else if trafo3wInput.getNodeB.getSubnet == subnetNo then PowerFlowCaseB + else if trafo3wInput.getNodeC.getSubnet == subnetNo then PowerFlowCaseC else throw new InvalidGridException( s"Requested transformer ${trafo3wInput.getUuid} has no node in subnet $subnetNo. Cannot determine the power flow calculation case!" ) - } } diff --git a/src/main/scala/edu/ie3/simona/model/grid/TransformerModel.scala b/src/main/scala/edu/ie3/simona/model/grid/TransformerModel.scala index e7f7abf08f..ceba486503 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/TransformerModel.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/TransformerModel.scala @@ -15,12 +15,12 @@ import edu.ie3.datamodel.models.input.connector.{ } import edu.ie3.simona.model.SystemComponent import edu.ie3.simona.util.SimonaConstants -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.OperationInterval import squants.Each import squants.electro.{Kilovolts, Ohms, Siemens} import squants.energy.Watts -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.time.ZonedDateTime import java.util.UUID @@ -181,7 +181,7 @@ case object TransformerModel { // iNomHv, iNomLv val calcINom : squants.electro.ElectricPotential => squants.electro.ElectricCurrent = { - portVoltage: squants.electro.ElectricPotential => + (portVoltage: squants.electro.ElectricPotential) => Watts( trafoType.getsRated .to(VOLTAMPERE) @@ -206,7 +206,8 @@ case object TransformerModel { // get the element port, where the transformer tap is located // if trafoType.isTapSide == true, tapper is on the low voltage side (== ConnectorPort.B) - val tapSide = if (trafoType.isTapSide) ConnectorPort.B else ConnectorPort.A + val tapSide = + if trafoType.isTapSide then ConnectorPort.B else ConnectorPort.A // / transformer tapping val transformerTappingModel = TransformerTappingModel( @@ -244,7 +245,7 @@ case object TransformerModel { ) // if the transformer input model is in operation, enable the model - if (operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION)) + if operationInterval.includes(SimonaConstants.FIRST_TICK_IN_SIMULATION) then transformerModel.enable() // initialize tapping @@ -274,8 +275,7 @@ case object TransformerModel { // check if transformer params are given for the low voltage side val vRef = refSystem.nominalVoltage - if ( - Math.abs( + if Math.abs( vRef.value .doubleValue() - trafoType.getvRatedA.getValue.doubleValue() ) @@ -283,7 +283,7 @@ case object TransformerModel { vRef.value .doubleValue() - trafoType.getvRatedB.getValue.doubleValue() ) - ) + then throw new InvalidGridException( s"The rated voltage of the high voltage side (${transformerInput.getType.getvRatedA()}) of transformer " + s"${transformerInput.getUuid} is closer to the reference voltage ($vRef), as the rated voltage of the " + @@ -294,12 +294,11 @@ case object TransformerModel { // valid r,x,g,b values? val (r, x, g, b) = (trafoType.getrSc, trafoType.getxSc, trafoType.getgM, trafoType.getbM) - if ( - r.getValue.doubleValue.isNaN || + if r.getValue.doubleValue.isNaN || x.getValue.doubleValue.isNaN || g.getValue.doubleValue.isNaN || b.getValue.doubleValue.isNaN - ) + then throw new InvalidGridException( s"Attempted to create a transformer with invalid values.\ntrafo: ${transformerInput.getUuid}, type: ${trafoType.getUuid}, r: $r, x: $x, g: $g, b: $b" ) @@ -391,7 +390,7 @@ case object TransformerModel { transformerModel: TransformerModel, iNodeHv: Quantity[ElectricCurrent], iNodeLv: Quantity[ElectricCurrent] - ): squants.Dimensionless = { + ): squants.Dimensionless = Each( Math.max( iNodeHv.getValue.doubleValue() / transformerModel.iNomHv.value @@ -400,6 +399,5 @@ case object TransformerModel { .doubleValue() ) * 100 ) - } } diff --git a/src/main/scala/edu/ie3/simona/model/grid/TransformerTapping.scala b/src/main/scala/edu/ie3/simona/model/grid/TransformerTapping.scala index 5337e0c829..c644310450 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/TransformerTapping.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/TransformerTapping.scala @@ -6,7 +6,7 @@ package edu.ie3.simona.model.grid -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import javax.measure.Quantity import javax.measure.quantity.Dimensionless import tech.units.indriya.quantity.Quantities diff --git a/src/main/scala/edu/ie3/simona/model/grid/TransformerTappingModel.scala b/src/main/scala/edu/ie3/simona/model/grid/TransformerTappingModel.scala index a40e4a5568..81605a5a2c 100644 --- a/src/main/scala/edu/ie3/simona/model/grid/TransformerTappingModel.scala +++ b/src/main/scala/edu/ie3/simona/model/grid/TransformerTappingModel.scala @@ -10,7 +10,7 @@ import breeze.numerics.{abs, floor, signum} import com.typesafe.scalalogging.LazyLogging import edu.ie3.datamodel.models.input.connector.ConnectorPort import edu.ie3.simona.exceptions.InvalidActionRequestException -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import javax.measure.Quantity import javax.measure.quantity.Dimensionless @@ -59,7 +59,7 @@ final case class TransformerTappingModel( */ def incrTapPos(deltaTap: Int = 1): Double = { val newTapPos = Math.min(_currentTapPos + Math.abs(deltaTap), tapMax) - if (_currentTapPos == newTapPos) + if _currentTapPos == newTapPos then logger.warn( "Maximal tap position reached. Cannot increase tap position anymore!" ) @@ -75,7 +75,7 @@ final case class TransformerTappingModel( */ def decrTapPos(deltaTap: Int = 1): Double = { val newTapPos = Math.max(_currentTapPos - Math.abs(deltaTap), tapMin) - if (_currentTapPos == newTapPos) + if _currentTapPos == newTapPos then logger.warn( "Minimal tap position reached. Cannot decrease tap position anymore!" ) @@ -91,7 +91,7 @@ final case class TransformerTappingModel( * the new tap ratio of the transformer */ def updateTapPos(newTapPos: Int): Double = { - if (newTapPos > tapMax | newTapPos < tapMin) + if newTapPos > tapMax | newTapPos < tapMin then throw new InvalidActionRequestException( s"Provided tap pos $newTapPos is not between allowed tapping range of tapMin: $tapMin and tapMax: $tapMax!" ) diff --git a/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatParticipant.scala b/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatParticipant.scala index 9fe21e87ac..5647ceacd3 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatParticipant.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatParticipant.scala @@ -7,6 +7,9 @@ package edu.ie3.simona.model.participant import edu.ie3.simona.agent.participant.data.Data.PrimaryData.ApparentPowerAndHeat +import edu.ie3.simona.model.participant.HpModel.HpRelevantData +import edu.ie3.simona.model.participant.control.QControl +import edu.ie3.util.scala.OperationInterval import squants.energy.Megawatts import squants.{Dimensionless, Power} @@ -19,10 +22,8 @@ trait ApparentPowerAndHeatParticipant[CD <: CalcRelevantData] { ): ApparentPowerAndHeat = { val apparentPower = calculateApparentPower(tick, voltage, data) val heat = - if (isInOperation(tick)) - calculateHeat(tick, data) - else - Megawatts(0d) + if isInOperation(tick) then calculateHeat(tick, data) + else Megawatts(0d) ApparentPowerAndHeat(apparentPower.p, apparentPower.q, heat) } diff --git a/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerParticipant.scala b/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerParticipant.scala index 51353fe437..b5a63cf954 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerParticipant.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/ApparentPowerParticipant.scala @@ -7,7 +7,10 @@ package edu.ie3.simona.model.participant import edu.ie3.simona.agent.participant.data.Data.PrimaryData.ApparentPower +import edu.ie3.simona.model.participant.control.QControl +import edu.ie3.util.scala.OperationInterval import squants.Dimensionless +import squants.energy.Power trait ApparentPowerParticipant[CD <: CalcRelevantData] { this: SystemParticipant[CD, ApparentPower] => diff --git a/src/main/scala/edu/ie3/simona/model/participant/BMModel.scala b/src/main/scala/edu/ie3/simona/model/participant/BMModel.scala index c8594f3e3c..fb7ba8d77b 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/BMModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/BMModel.scala @@ -16,7 +16,7 @@ import squants.{Dimensionless, Money, Power, Temperature} import java.time.ZonedDateTime import java.util.UUID -import scala.math._ +import scala.math.* /** This class represents a single biomass plant */ @@ -33,7 +33,7 @@ final case class BMModel( private val opex: Money, private val feedInTariff: EnergyPrice, private val loadGradient: Double -) extends SystemParticipant[BMCalcRelevantData, ApparentPower]( +) extends ApparentPowerParticipant[BMCalcRelevantData]( uuid, id, operationInterval, @@ -41,8 +41,7 @@ final case class BMModel( qControl, sRated, cosPhi - ) - with ApparentPowerParticipant[BMCalcRelevantData] { + ) { /** Saves power output of last cycle. Needed for load gradient */ @@ -112,13 +111,12 @@ final case class BMModel( * @return * factor k2 */ - private def calculateK2(time: ZonedDateTime): Double = { + private def calculateK2(time: ZonedDateTime): Double = time.getDayOfYear match { case x if x < 150 || x > 243 => 1.03 // correction factor in heating season case _ => 0.61 // correction factor outside heating season } - } /** Calculates heat demand * @param temp @@ -155,7 +153,7 @@ final case class BMModel( val maxHeat = Megawatts(43.14) val usageUnchecked = pTh / maxHeat - if (usageUnchecked < 1) usageUnchecked else 1 + if usageUnchecked < 1 then usageUnchecked else 1 } /** Calculates efficiency from usage. Efficiency is based on a regression @@ -183,13 +181,10 @@ final case class BMModel( val currOpex = opex.divide(eff) val avgOpex = (currOpex + opex).divide(2) - if ( - isCostControlled && avgOpex.value.doubleValue() < feedInTariff.value + if isCostControlled && avgOpex.value.doubleValue() < feedInTariff.value .doubleValue() - ) - sRated * cosPhi * (-1) - else - sRated * usage * eff * cosPhi * (-1) + then sRated * cosPhi * -1 + else sRated * usage * eff * cosPhi * -1 } /** Applies the load gradient to the electrical output @@ -200,7 +195,7 @@ final case class BMModel( */ private def applyLoadGradient( pEl: Power - ): Power = { + ): Power = _lastPower match { case None => pEl case Some(lastPowerVal) => @@ -209,13 +204,12 @@ final case class BMModel( pEl - lastPowerVal match { case pElDelta if pElDelta > pElDeltaMaxAbs => lastPowerVal + pElDeltaMaxAbs - case pElDelta if pElDelta < (pElDeltaMaxAbs * (-1)) => + case pElDelta if pElDelta < (pElDeltaMaxAbs * -1) => lastPowerVal - pElDeltaMaxAbs case _ => pEl } } - } } case object BMModel { diff --git a/src/main/scala/edu/ie3/simona/model/participant/ChpModel.scala b/src/main/scala/edu/ie3/simona/model/participant/ChpModel.scala index a335e696bb..e851e1530b 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/ChpModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/ChpModel.scala @@ -8,7 +8,7 @@ package edu.ie3.simona.model.participant import edu.ie3.datamodel.models.input.system.ChpInput import edu.ie3.simona.agent.participant.data.Data.PrimaryData.ApparentPower -import edu.ie3.simona.model.participant.ChpModel._ +import edu.ie3.simona.model.participant.ChpModel.* import edu.ie3.simona.model.participant.control.QControl import edu.ie3.simona.model.thermal.{MutableStorage, ThermalStorage} import edu.ie3.util.quantities.PowerSystemUnits @@ -52,7 +52,7 @@ final case class ChpModel( cosPhiRated: Double, pThermal: Power, storage: ThermalStorage with MutableStorage -) extends SystemParticipant[ChpRelevantData, ApparentPower]( +) extends ApparentPowerParticipantParticipant[ChpRelevantData]( uuid, id, operationInterval, @@ -60,8 +60,7 @@ final case class ChpModel( qControl, sRated, cosPhiRated - ) - with ApparentPowerParticipant[ChpRelevantData] { + ) { val pRated: Power = sRated * cosPhiRated @@ -197,7 +196,7 @@ final case class ChpModel( chpData: ChpRelevantData ): ChpState = { val differenceEnergy = chpEnergy(chpData) - chpData.heatDemand - if (differenceEnergy < KilowattHours(0d)) { + if differenceEnergy < KilowattHours(0d) then { // Returned lack is always zero, because demand is covered. storage.tryToTakeAndReturnLack(differenceEnergy * -1) calculateStateRunningSurplus(chpData) @@ -221,7 +220,7 @@ final case class ChpModel( private def calculateStateRunningSurplus( chpData: ChpRelevantData, surplus: Option[Energy] = None - ): ChpState = { + ): ChpState = surplus match { case Some(surplusEnergy) => ChpState( @@ -238,7 +237,6 @@ final case class ChpModel( chpEnergy(chpData) ) } - } /** Multiply the power with time running to get the total energy. * diff --git a/src/main/scala/edu/ie3/simona/model/participant/EvModelWrapper.scala b/src/main/scala/edu/ie3/simona/model/participant/EvModelWrapper.scala index 7b9019aede..e9dd7adbd9 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/EvModelWrapper.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/EvModelWrapper.scala @@ -7,7 +7,7 @@ package edu.ie3.simona.model.participant import edu.ie3.simona.api.data.ev.model.EvModel -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.quantities.QuantityUtils.RichQuantityDouble import squants.energy.{KilowattHours, Kilowatts} @@ -29,22 +29,20 @@ final case class EvModelWrapper( ) def departureTick: Long = original.getDepartureTick - def unwrap(): EvModel = { + def unwrap(): EvModel = original.copyWith( storedEnergy.toKilowattHours.asKiloWattHour ) - } } object EvModelWrapper { - def apply(evModel: EvModel): EvModelWrapper = { + def apply(evModel: EvModel): EvModelWrapper = new EvModelWrapper( KilowattHours( evModel.getStoredEnergy.to(KILOWATTHOUR).getValue.doubleValue ), evModel ) - } } diff --git a/src/main/scala/edu/ie3/simona/model/participant/EvcsModel.scala b/src/main/scala/edu/ie3/simona/model/participant/EvcsModel.scala index 710e62b02a..cd0abea23a 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/EvcsModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/EvcsModel.scala @@ -83,8 +83,8 @@ final case class EvcsModel( tick: Long, voltage: squants.Dimensionless, data: EvcsRelevantData - ): (ApparentPower, Set[EvModel]) = { - if (isInOperation(tick) && data.evMovementsDataFrameLength > 0) { + ): (ApparentPower, Set[EvModel]) = + if isInOperation(tick) && data.evMovementsDataFrameLength > 0 then { val (activePower, evModels) = calculateActivePowerAndEvSoc(data) val reactivePower = calculateReactivePower(activePower, voltage) @@ -104,7 +104,6 @@ final case class EvcsModel( data.currentEvs ) } - } /** Calculates active power based on given data. If sRated of this evcs is * exceeded, evs are dropped from charging at this time span. @@ -120,7 +119,7 @@ final case class EvcsModel( data.currentEvs, data.evMovementsDataFrameLength ) - if (powerSum <= sRated) { + if powerSum <= sRated then { (powerSum, models) } else { // if we exceed sRated, we scale down charging power of all evs proportionally @@ -138,10 +137,8 @@ final case class EvcsModel( ) { case ((calcEvs, noCalcEvs, powerSum), ev) => val newPower = powerSum + Kilowatts(ev.getSRatedAC.getValue.doubleValue()) - if (newPower <= sRated) - (calcEvs + ev, noCalcEvs, newPower) - else - (calcEvs, noCalcEvs + ev, powerSum) + if newPower <= sRated then (calcEvs + ev, noCalcEvs, newPower) + else (calcEvs, noCalcEvs + ev, powerSum) } val (power, newCalcEvs) = @@ -196,8 +193,8 @@ final case class EvcsModel( def charge( evModel: EvModel, duration: squants.Time - ): (squants.Energy, EvModel) = { - if (evModel.getStoredEnergy.isLessThan(evModel.getEStorage)) { + ): (squants.Energy, EvModel) = + if evModel.getStoredEnergy.isLessThan(evModel.getEStorage) then { val chargingPower = sRated.min( Kilowatts( @@ -244,7 +241,6 @@ final case class EvcsModel( DefaultQuantities.zeroKWH, evModel ) - } /** Calculate the active power behaviour of the model * diff --git a/src/main/scala/edu/ie3/simona/model/participant/FixedFeedInModel.scala b/src/main/scala/edu/ie3/simona/model/participant/FixedFeedInModel.scala index 89fd5096ce..1390cb18ed 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/FixedFeedInModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/FixedFeedInModel.scala @@ -69,7 +69,7 @@ final case class FixedFeedInModel( override protected def calculateActivePower( data: FixedRelevantData.type = FixedRelevantData ): Power = - sRated * (-1) * cosPhiRated * scalingFactor + sRated * -1 * cosPhiRated * scalingFactor } case object FixedFeedInModel extends LazyLogging { diff --git a/src/main/scala/edu/ie3/simona/model/participant/HpModel.scala b/src/main/scala/edu/ie3/simona/model/participant/HpModel.scala index 61b73df7f3..58ab9edc85 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/HpModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/HpModel.scala @@ -10,7 +10,7 @@ import java.util.UUID import edu.ie3.datamodel.models.input.system.HpInput import edu.ie3.simona.agent.participant.data.Data.PrimaryData.ApparentPowerAndHeat import edu.ie3.simona.model.SystemComponent -import edu.ie3.simona.model.participant.HpModel._ +import edu.ie3.simona.model.participant.HpModel.* import edu.ie3.simona.model.participant.control.QControl import edu.ie3.simona.model.thermal.ThermalHouse import edu.ie3.simona.util.TickUtil.TickLong @@ -156,8 +156,7 @@ final case class HpModel( */ private def calcState(hpData: HpRelevantData, isRunning: Boolean): HpState = { val (newActivePower, newThermalPower) = - if (isRunning) - (pRated, pThermal * scalingFactor) + if isRunning then (pRated, pThermal * scalingFactor) else (DefaultQuantities.zeroKW, DefaultQuantities.zeroKW) val duration: Time = diff --git a/src/main/scala/edu/ie3/simona/model/participant/PvModel.scala b/src/main/scala/edu/ie3/simona/model/participant/PvModel.scala index 847d45e5a1..3af197fe36 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/PvModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/PvModel.scala @@ -13,17 +13,17 @@ import edu.ie3.simona.model.participant.PvModel.PvRelevantData import edu.ie3.simona.model.participant.control.QControl import edu.ie3.util.quantities.PowerSystemUnits import edu.ie3.util.scala.OperationInterval -import edu.ie3.util.scala.quantities._ -import squants._ +import edu.ie3.util.scala.quantities.* +import squants.* import squants.energy.Kilowatts import squants.space.{Degrees, SquareMeters} import squants.time.Minutes -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.time.ZonedDateTime import java.util.UUID import java.util.stream.IntStream -import scala.math._ +import scala.math.* final case class PvModel private ( uuid: UUID, @@ -239,7 +239,7 @@ final case class PvModel private ( /** Calculates the sunrise hour angle omegaSR given omegaSS. */ private val calcSunriseAngleOmegaSR = - (omegaSS: Angle) => omegaSS * (-1) + (omegaSS: Angle) => omegaSS * -1 /** Calculates the solar altitude angle alphaS which represents the angle * between the horizontal and the line to the sun, that is, the complement of @@ -417,18 +417,17 @@ final case class PvModel private ( // (thetaG < 90°): sun is visible // (thetaG > 90°), otherwise: sun is behind the surface -> no direct radiation - if ( - thetaGInRad < toRadians(90) + if thetaGInRad < toRadians(90) // omega1 and omega2: sun has risen and has not set yet && omega2InRad > omegaSRInRad + omegaHalfHour && omega1InRad < omegaSSInRad - omegaHalfHour - ) { + then { val (finalOmega1, finalOmega2) = - if (omega1InRad < omegaSRInRad) { + if omega1InRad < omegaSRInRad then { // requested time earlier than sunrise (omegaSRInRad, omegaSRInRad + omegaOneHour) - } else if (omega2InRad > omegaSSInRad) { + } else if omega2InRad > omegaSSInRad then { // sunset earlier than requested time (omegaSSInRad - omegaOneHour, omegaSSInRad) } else { @@ -436,8 +435,7 @@ final case class PvModel private ( } Some(Radians(finalOmega1), Radians(finalOmega2)) - } else - None + } else None } /** Calculates the beam radiation on a sloped surface @@ -467,8 +465,7 @@ final case class PvModel private ( latitude: Angle, gammaE: Angle, alphaE: Angle - ): Irradiation = { - + ): Irradiation = omegas match { case Some((omega1, omega2)) => val deltaInRad = delta.toRadians @@ -502,7 +499,6 @@ final case class PvModel private ( eBeamH * r case None => WattHoursPerSquareMeter(0d) } - } /** Calculates the diffuse radiation on a sloped surface based on the model of * Perez et al. @@ -549,7 +545,7 @@ final case class PvModel private ( // if we have no clouds, the epsilon bin is 8, as epsilon bin for an epsilon in [6.2, inf.[ = 8 var x = 8 - if (eDifH.value.doubleValue > 0) { + if eDifH.value.doubleValue > 0 then { // if we have diffuse radiation on horizontal surface we have to check if we have another epsilon due to clouds get the epsilon var epsilon = ((eDifH + eBeamH) / eDifH + (5.535d * 1.0e-6) * pow( @@ -561,7 +557,7 @@ final case class PvModel private ( )) // get the corresponding bin if epsilon is smaller than 6.2 - if (epsilon < 6.2) { // define the bins based on Perez + if epsilon < 6.2 then { // define the bins based on Perez val discreteSkyClearnessCategories = Array( Array(1, 1.065), Array(1.065, 1.230), @@ -689,12 +685,12 @@ final case class PvModel private ( eTotalInWhPerSM * moduleSurface.toSquareMeters * etaConv.toEach * (genCorr * tempCorr) /* Calculate the foreseen active power output without boundary condition adaptions */ - val proposal = sRated * (-1) * ( + val proposal = sRated * -1 * ( actYield / irradiationSTC ) * cosPhiRated /* Do sanity check, if the proposed feed in is above the estimated maximum to be apparent active power of the plant */ - if (proposal < pMax) + if proposal < pMax then logger.warn( "The fed in active power is higher than the estimated maximum active power of this plant ({} < {}). " + "Did you provide wrong weather input data?", @@ -703,8 +699,7 @@ final case class PvModel private ( ) /* If the output is marginally small, suppress the output, as we are likely to be in night and then only produce incorrect output */ - if (proposal.compareTo(activationThreshold) > 0) - DefaultQuantities.zeroMW + if proposal.compareTo(activationThreshold) > 0 then DefaultQuantities.zeroMW else proposal } } diff --git a/src/main/scala/edu/ie3/simona/model/participant/SystemParticipant.scala b/src/main/scala/edu/ie3/simona/model/participant/SystemParticipant.scala index e8bbf14c5a..7f7f3f3b77 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/SystemParticipant.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/SystemParticipant.scala @@ -96,8 +96,8 @@ abstract class SystemParticipant[ tick: Long, voltage: Dimensionless, data: CD - ): ApparentPower = { - if (isInOperation(tick)) { + ): ApparentPower = + if isInOperation(tick) then { val activePower = calculateActivePower(data) val reactivePower = calculateReactivePower(activePower, voltage) @@ -108,7 +108,6 @@ abstract class SystemParticipant[ DefaultQuantities.zeroMVAr ) } - } /** Calculate the active power behaviour of the model * @@ -148,12 +147,11 @@ abstract class SystemParticipant[ def calculateReactivePower( activePower: Power, voltage: Dimensionless - ): ReactivePower = { + ): ReactivePower = limitReactivePower( activePower, activeToReactivePowerFunc(voltage)(activePower) ) - } /** Check if the calculated apparent power respects model limits and return * adjusted reactive power value if necessary @@ -169,44 +167,41 @@ abstract class SystemParticipant[ activePower: Power, reactivePower: ReactivePower ): ReactivePower = { - { - val apparentPower: Power = Kilowatts( - Math - .sqrt( - Math.pow(activePower.toKilowatts, 2) + Math - .pow(reactivePower.toKilovars, 2) - ) + val apparentPower: Power = Kilowatts( + Math + .sqrt( + Math.pow(activePower.toKilowatts, 2) + Math + .pow(reactivePower.toKilovars, 2) + ) + ) + + // tolerance for double inaccuracies + val sMaxWithTolerance = sMax * 1.00001d + + if apparentPower > sMaxWithTolerance then { + logger.debug( + s"The var characteristics \'$qControl\' of model \'$id\' ($uuid) imposes an apparent " + + s"power (= $apparentPower) that exceeds " + + s"rated apparent power specifications (= $sMax). " + + s"Therefore, setting reactive power output to the to the upper limit " + + s"in correspondence to the existing active power $activePower." ) - // tolerance for double inaccuracies - val sMaxWithTolerance = sMax * 1.00001d + val powerSquaredDifference = Math.pow(sMax.toMegawatts, 2) - + Math.pow(activePower.toMegawatts, 2) - if (apparentPower > sMaxWithTolerance) { - logger.debug( - s"The var characteristics \'$qControl\' of model \'$id\' ($uuid) imposes an apparent " + - s"power (= $apparentPower) that exceeds " + - s"rated apparent power specifications (= $sMax). " + - s"Therefore, setting reactive power output to the to the upper limit " + - s"in correspondence to the existing active power $activePower." + if powerSquaredDifference < 0 then { + logger.warn( + s"Active power of model exceeds sRated. Set reactive power to 0!" ) - - val powerSquaredDifference = Math.pow(sMax.toMegawatts, 2) - - Math.pow(activePower.toMegawatts, 2) - - if (powerSquaredDifference < 0) { - logger.warn( - s"Active power of model exceeds sRated. Set reactive power to 0!" - ) - Megavars(0d) - } else { - Megavars( - Math.sqrt(powerSquaredDifference) - ) * (if (reactivePower.toMegavars < 0) -1 - else 1) // preserve the sign of reactive power - } - } else - reactivePower - } + Megavars(0d) + } else { + Megavars( + Math.sqrt(powerSquaredDifference) + ) * (if reactivePower.toMegavars < 0 then -1 + else 1) // preserve the sign of reactive power + } + } else reactivePower } def getUuid: UUID = this.uuid diff --git a/src/main/scala/edu/ie3/simona/model/participant/WecModel.scala b/src/main/scala/edu/ie3/simona/model/participant/WecModel.scala index ca1719dbb0..fa3c41c836 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/WecModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/WecModel.scala @@ -17,15 +17,15 @@ import edu.ie3.simona.model.participant.WecModel.{ import edu.ie3.simona.model.participant.control.QControl import edu.ie3.simona.model.system.Characteristic import edu.ie3.simona.model.system.Characteristic.XYPair -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.OperationInterval import squants.energy.{Kilowatts, Watts} import squants.mass.{Kilograms, KilogramsPerCubicMeter} import squants.motion.{MetersPerSecond, Pressure} import squants.space.SquareMeters import squants.thermal.JoulesPerKelvin -import squants._ -import tech.units.indriya.unit.Units._ +import squants.* +import tech.units.indriya.unit.Units.* import java.time.ZonedDateTime import java.util.UUID @@ -96,7 +96,7 @@ final case class WecModel( val activePower = determinePower(wecData) val pMax = sMax * cosPhiRated - (if (activePower > pMax) { + (if activePower > pMax then { logger.warn( "The fed in active power is higher than the estimated maximum active power of this plant ({} > {}). " + "Did you provide wrong weather input data?", @@ -106,7 +106,8 @@ final case class WecModel( pMax } else { activePower - }) * (-1) + }) + * -1 } /** Determine the turbine output power with the air density ρ, the wind @@ -155,11 +156,10 @@ final case class WecModel( */ private def determineBetzCoefficient( windVelocity: Velocity - ): Dimensionless = { + ): Dimensionless = betzCurve.interpolateXy(windVelocity) match { case (_, cp) => cp } - } /** Calculate the correct air density, dependent on the current temperature * and air pressure. @@ -176,7 +176,7 @@ final case class WecModel( private def calculateAirDensity( temperature: Temperature, airPressure: Option[Pressure] - ): Density = { + ): Density = airPressure match { case None => KilogramsPerCubicMeter(1.2041d) @@ -187,7 +187,6 @@ final case class WecModel( MolarMassAir.toKilograms * pressure.toPascals / (UniversalGasConstantR.toJoulesPerKelvin * temperature.toKelvinScale) ) } - } } /** Create valid [[WecModel]] by calling the apply function. @@ -204,7 +203,7 @@ object WecModel { ) extends Characteristic[Velocity, Dimensionless] object WecCharacteristic { - import scala.jdk.CollectionConverters._ + import scala.jdk.CollectionConverters.* /** Transform the inputs points from [[java.util.SortedSet]] to * [[scala.collection.SortedSet]], which is fed into [[WecCharacteristic]]. diff --git a/src/main/scala/edu/ie3/simona/model/participant/control/QControl.scala b/src/main/scala/edu/ie3/simona/model/participant/control/QControl.scala index 02c42be94f..8679b26db5 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/control/QControl.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/control/QControl.scala @@ -18,13 +18,13 @@ import tech.units.indriya.AbstractUnit import scala.collection.SortedSet import scala.collection.immutable.TreeSet -import scala.jdk.CollectionConverters._ -import scala.math._ +import scala.jdk.CollectionConverters.* +import scala.math.* sealed trait QControl { protected val _cosPhiMultiplication: (Double, Power) => ReactivePower = (cosPhi: Double, p: Power) => - if ((cosPhi - 1).abs < 0.0000001) { + if (cosPhi - 1).abs < 0.0000001 then { Megavars(0d) } else { /* q = p * tan( phi ) = p * tan( acos( cosphi )) */ @@ -60,7 +60,7 @@ object QControl { def apply(varCharacteristic: ReactivePowerCharacteristic): QControl = varCharacteristic match { case cosPhiFixed: characteristic.CosPhiFixed => - if (cosPhiFixed.getPoints.size() > 1) + if cosPhiFixed.getPoints.size() > 1 then throw new QControlException( s"Got an invalid definition of fixed power factor: $cosPhiFixed. It may only contain one coordinate" ) @@ -119,9 +119,8 @@ object QControl { sRated: Power, cosPhiRated: Double, nodalVoltage: Dimensionless - ): Power => ReactivePower = { activePower: Power => + ): Power => ReactivePower = activePower: Power => _cosPhiMultiplication(cosPhi, activePower) - } } /** Voltage dependant var characteristic @@ -152,9 +151,8 @@ object QControl { def q( vInPu: Dimensionless, qMax: ReactivePower - ): ReactivePower = { + ): ReactivePower = qMax * interpolateXy(vInPu)._2.toEach - } /** Obtain the function, that transfers active into reactive power * @@ -171,7 +169,7 @@ object QControl { sRated: Power, cosPhiRated: Double, nodalVoltage: Dimensionless - ): Power => ReactivePower = { activePower: Power => + ): Power => ReactivePower = { (activePower: Power) => val qMaxFromP = Megavars( sqrt( pow(sRated.toMegawatts, 2) - @@ -199,10 +197,9 @@ object QControl { qMaxFromP: ReactivePower, qFromCharacteristic: ReactivePower ): ReactivePower = - if (qFromCharacteristic.abs >= qMaxFromP.abs) + if qFromCharacteristic.abs >= qMaxFromP.abs then qMaxFromP * copySign(1, qFromCharacteristic.toMegavars) - else - qFromCharacteristic + else qFromCharacteristic } /** Power dependant var characteristic @@ -246,7 +243,7 @@ object QControl { sRated: Power, cosPhiRated: Double, nodalVoltage: Dimensionless - ): Power => ReactivePower = { activePower: Power => + ): Power => ReactivePower = { (activePower: Power) => /* cosphi( P / P_N ) = cosphi( P / (S_N * cosphi_rated) ) */ val pInPu = activePower / (sRated * cosPhiRated) diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/LoadModel.scala b/src/main/scala/edu/ie3/simona/model/participant/load/LoadModel.scala index 6844fef7ff..167ea1b825 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/LoadModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/LoadModel.scala @@ -115,10 +115,9 @@ case object LoadModel extends LazyLogging { profileMaxPower: Power, profileEnergyScaling: Energy, safetyFactor: Double = 1d - ): Power = { + ): Power = (profileMaxPower / inputModel.getCosPhiRated) * ( energyConsumption / profileEnergyScaling ) * safetyFactor - } } diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/LoadReference.scala b/src/main/scala/edu/ie3/simona/model/participant/load/LoadReference.scala index b0c2877cf1..cf4e8f624b 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/LoadReference.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/LoadReference.scala @@ -43,9 +43,8 @@ case object LoadReference { override val key: String = "energy" } - def isEligibleKey(key: String): Boolean = { + def isEligibleKey(key: String): Boolean = Set("power", "energy").contains(key) - } /** Build a reference object, that denotes, to which reference a load model * behaviour might be scaled. If the behaviour is meant to be scaled to diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileKey.scala b/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileKey.scala index cb3cb60e90..1ab42d1fcd 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileKey.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileKey.scala @@ -65,21 +65,20 @@ case object LoadProfileKey { loadProfile: String, season: String, dayType: String - ): LoadProfileKey = { - try { + ): LoadProfileKey = + try new LoadProfileKey( StandardLoadProfile.parse(loadProfile), Season(season), DayType(dayType) ) - } catch { + catch { case e: ParsingException => throw new IllegalArgumentException( s"Cannot parse '$loadProfile' to a now StandardLoadProfile.", e ) } - } /** Creates a load profile key from a consumer type value and a ZonedDateTime * object @@ -94,11 +93,10 @@ case object LoadProfileKey { def apply( loadProfile: StandardLoadProfile, time: ZonedDateTime - ): LoadProfileKey = { + ): LoadProfileKey = new LoadProfileKey( loadProfile, profile.Season(time), load.DayType(time.getDayOfWeek) ) - } } diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileStore.scala b/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileStore.scala index 8c3769a9cf..bc68321d08 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileStore.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/profile/LoadProfileStore.scala @@ -24,7 +24,7 @@ import edu.ie3.simona.model.participant.load.{DayType, profile} import org.apache.commons.csv.CSVFormat import squants.energy.{KilowattHours, Watts} -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.math.pow // needs to be imported for max function @@ -89,7 +89,7 @@ class LoadProfileStore private (val reader: Reader) { */ def maxPower( loadProfile: StandardLoadProfile - ): squants.Power = { + ): squants.Power = maxParamMap.get(loadProfile) match { case Some(value) => Watts(value) @@ -98,7 +98,6 @@ class LoadProfileStore private (val reader: Reader) { "Max value for ConsumerType " + loadProfile.toString + " not found" ) } - } } object LoadProfileStore extends LazyLogging { @@ -200,35 +199,34 @@ object LoadProfileStore extends LazyLogging { val knownLoadProfiles: Set[StandardLoadProfile] = profileMap.keySet.map(key => key.standardLoadProfile) - knownLoadProfiles - .flatMap(loadProfile => { - (loadProfile match { - case BdewStandardLoadProfile.H0 => - // max load for h0 is expected to be exclusively found in winter, - // thus we only search there. - DayType.values - .map(dayType => { - val key = - profile.LoadProfileKey(loadProfile, Season.winter, dayType) - // maximum dynamization factor is on day 366 (leap year) or day 365 (regular year). - // The difference between day 365 and day 366 is negligible, thus pick 366 - profileMap - .get(key) - .map(typeDay => dynamization(typeDay.getMaxValue, 366)) - .getOrElse(0d) - }) - .maxOption - case _ => - (for (season <- Season.values; dayType <- DayType.values) yield { - val key = profile.LoadProfileKey(loadProfile, season, dayType) - profileMap.get(key) match { - case Some(value) => Option(value.getMaxValue) - case None => None - } - }).flatten.maxOption - }).map(maxConsumption => loadProfile -> maxConsumption) - }) - .toMap + knownLoadProfiles.flatMap { loadProfile => + (loadProfile match { + case BdewStandardLoadProfile.H0 => + // max load for h0 is expected to be exclusively found in winter, + // thus we only search there. + DayType.values.map { dayType => + val key = + profile.LoadProfileKey(loadProfile, Season.winter, dayType) + // maximum dynamization factor is on day 366 (leap year) or day 365 (regular year). + // The difference between day 365 and day 366 is negligible, thus pick 366 + profileMap + .get(key) + .map(typeDay => dynamization(typeDay.getMaxValue, 366)) + .getOrElse(0d) + }.maxOption + case _ => + (for + season <- Season.values + dayType <- DayType.values + yield { + val key = profile.LoadProfileKey(loadProfile, season, dayType) + profileMap.get(key) match { + case Some(value) => Option(value.getMaxValue) + case None => None + } + }).flatten.maxOption + }).map(maxConsumption => loadProfile -> maxConsumption) + }.toMap } /** @return diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/profile/ProfileLoadModel.scala b/src/main/scala/edu/ie3/simona/model/participant/load/profile/ProfileLoadModel.scala index 77782e4907..31fe3d659c 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/profile/ProfileLoadModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/profile/ProfileLoadModel.scala @@ -10,7 +10,7 @@ import edu.ie3.datamodel.models.profile.StandardLoadProfile import edu.ie3.datamodel.models.input.system.LoadInput import edu.ie3.simona.model.participant.CalcRelevantData.LoadRelevantData import edu.ie3.simona.model.participant.control.QControl -import edu.ie3.simona.model.participant.load.LoadReference._ +import edu.ie3.simona.model.participant.load.LoadReference.* import edu.ie3.simona.model.participant.load.profile.ProfileLoadModel.ProfileRelevantData import edu.ie3.simona.model.participant.load.{LoadModel, LoadReference} import edu.ie3.util.scala.OperationInterval diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/profile/Season.scala b/src/main/scala/edu/ie3/simona/model/participant/load/profile/Season.scala index 0d9bb6541c..ff78d77f3f 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/profile/Season.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/profile/Season.scala @@ -6,7 +6,7 @@ package edu.ie3.simona.model.participant.load.profile -import java.time.Month._ +import java.time.Month.* import java.time.ZonedDateTime /** Describes the season (winter, summer, transition) as part of a load profile diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/profile/TypeDayProfile.scala b/src/main/scala/edu/ie3/simona/model/participant/load/profile/TypeDayProfile.scala index dd2fcb6a18..cb1810bdf4 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/profile/TypeDayProfile.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/profile/TypeDayProfile.scala @@ -21,7 +21,7 @@ import scala.math.Ordering.Double.IeeeOrdering * 96 quarter-hour values for this load profile, */ final case class TypeDayProfile(private val values: Array[Double]) { - if (values.length != 96) + if values.length != 96 then throw new IllegalArgumentException( "You may only instantiate type day parameters with 96 values." ) diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadModel.scala b/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadModel.scala index 7d8db0c833..0b5d6e4ed4 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadModel.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadModel.scala @@ -11,7 +11,7 @@ import de.lmu.ifi.dbs.elki.utilities.random.RandomFactory import edu.ie3.datamodel.models.input.system.LoadInput import edu.ie3.simona.model.participant.CalcRelevantData.LoadRelevantData import edu.ie3.simona.model.participant.control.QControl -import edu.ie3.simona.model.participant.load.LoadReference._ +import edu.ie3.simona.model.participant.load.LoadReference.* import edu.ie3.simona.model.participant.load.random.RandomLoadModel.RandomRelevantData import edu.ie3.simona.model.participant.load.{DayType, LoadModel, LoadReference} import edu.ie3.util.TimeUtil @@ -95,8 +95,7 @@ final case class RandomLoadModel( /* Get a next random power (in kW) */ val randomPower = gev.nextRandom() - if (randomPower < 0) - calculateActivePower(data) + if randomPower < 0 then calculateActivePower(data) else { val profilePower = Kilowatts(randomPower) val activePower = reference match { @@ -179,7 +178,7 @@ case object RandomLoadModel { operationInterval: OperationInterval, scalingFactor: Double, reference: LoadReference - ): RandomLoadModel = { + ): RandomLoadModel = reference match { case ActivePower(power) => val sRatedPowerScaled = @@ -215,5 +214,4 @@ case object RandomLoadModel { reference ) } - } } diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadParamStore.scala b/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadParamStore.scala index 44f481eafe..837b5b1bbb 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadParamStore.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/random/RandomLoadParamStore.scala @@ -14,7 +14,7 @@ import edu.ie3.simona.model.participant.load.DayType import edu.ie3.simona.model.participant.load.random.RandomLoadParamStore.initializeDayTypeValues import org.apache.commons.csv.{CSVFormat, CSVRecord} -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Storage for a collection of random load parameters. */ @@ -90,14 +90,14 @@ case object RandomLoadParamStore extends LazyLogging { /* Go through all lines of the csv file */ records.asScala - .flatMap(record => { + .flatMap { record => val quartHour = record.get("quarterHour").toInt /* Go through all day types */ descriptorTree.map { case (dayType, parameterToCol) => - try { + try (dayType, quartHour, assembleParameters(record, parameterToCol)) - } catch { + catch { case e: FileIOException => throw new FileIOException( s"Cannot determine random load parameters for day type '$dayType' and quarter hour '$quartHour'", @@ -105,7 +105,7 @@ case object RandomLoadParamStore extends LazyLogging { ) } } - }) + } .groupMap { case (dayType, _, _) => dayType } { case (_, quarterHour, randomLoadParameters) => (quarterHour, randomLoadParameters) diff --git a/src/main/scala/edu/ie3/simona/model/participant/load/random/TypeDayParameters.scala b/src/main/scala/edu/ie3/simona/model/participant/load/random/TypeDayParameters.scala index 36360ff600..08fcc0f21b 100644 --- a/src/main/scala/edu/ie3/simona/model/participant/load/random/TypeDayParameters.scala +++ b/src/main/scala/edu/ie3/simona/model/participant/load/random/TypeDayParameters.scala @@ -21,7 +21,7 @@ import edu.ie3.util.TimeUtil final case class TypeDayParameters( private val values: Array[RandomLoadParameters] ) { - if (values.length != 96) + if values.length != 96 then throw new IllegalArgumentException( s"You may only instantiate type day parameters with 96 values. Apparent: ${values.length}." ) diff --git a/src/main/scala/edu/ie3/simona/model/system/Characteristic.scala b/src/main/scala/edu/ie3/simona/model/system/Characteristic.scala index 2be558d535..a9d8a77adc 100644 --- a/src/main/scala/edu/ie3/simona/model/system/Characteristic.scala +++ b/src/main/scala/edu/ie3/simona/model/system/Characteristic.scala @@ -8,7 +8,7 @@ package edu.ie3.simona.model.system import edu.ie3.simona.exceptions.CharacteristicsException import edu.ie3.simona.model.system.Characteristic.XYPair -import edu.ie3.simona.util.CollectionUtils._ +import edu.ie3.simona.util.CollectionUtils.* import squants.Quantity import scala.collection.SortedSet @@ -29,9 +29,7 @@ trait Characteristic[A <: Quantity[A], O <: Quantity[O]] { */ def interpolateXy( requestedAbscissaQuantity: A - )(implicit - tag: ClassTag[O] - ): (A, O) = { + )(using tag: ClassTag[O]): (A, O) = { val xyCoords: Seq[(A, O)] = closestKeyValuePairs[A, O]( @@ -43,7 +41,7 @@ trait Characteristic[A <: Quantity[A], O <: Quantity[O]] { xyCoords.foldLeft( (None: Option[A], None: Option[O]) - )({ + ) { case ((None, None), (x, y)) => /* We found the latest entry left of the requested abscissa element. Remember that one */ (Some(x), Some(y)) @@ -62,7 +60,7 @@ trait Characteristic[A <: Quantity[A], O <: Quantity[O]] { throw new CharacteristicsException( s"Unable to interpolate for given xyCoordinates: $xyCoords" ) - }) match { + } match { case (Some(resX), Some(resY)) => (resX, resY) case (_, _) => throw new CharacteristicsException( @@ -87,10 +85,8 @@ object Characteristic { */ override def compare(that: XYPair[A, O]): Int = { val xCompare = x.compare(that.x) - if (xCompare != 0) - xCompare - else - y.compare(that.y) + if xCompare != 0 then xCompare + else y.compare(that.y) } } diff --git a/src/main/scala/edu/ie3/simona/model/thermal/CylindricalThermalStorage.scala b/src/main/scala/edu/ie3/simona/model/thermal/CylindricalThermalStorage.scala index afe5372a0c..9662b88a1e 100644 --- a/src/main/scala/edu/ie3/simona/model/thermal/CylindricalThermalStorage.scala +++ b/src/main/scala/edu/ie3/simona/model/thermal/CylindricalThermalStorage.scala @@ -94,9 +94,9 @@ final case class CylindricalThermalStorage( override def tryToStoreAndReturnRemainder( addedEnergy: Energy ): Option[Energy] = { - if (addedEnergy > zeroEnergy) { + if addedEnergy > zeroEnergy then { _storedEnergy = _storedEnergy + addedEnergy - if (_storedEnergy > maxEnergyThreshold) { + if _storedEnergy > maxEnergyThreshold then { val surplus = _storedEnergy - maxEnergyThreshold _storedEnergy = maxEnergyThreshold return Option(surplus) @@ -108,9 +108,9 @@ final case class CylindricalThermalStorage( override def tryToTakeAndReturnLack( takenEnergy: Energy ): Option[Energy] = { - if (takenEnergy > zeroEnergy) { + if takenEnergy > zeroEnergy then { _storedEnergy = _storedEnergy - takenEnergy - if (_storedEnergy < minEnergyThreshold) { + if _storedEnergy < minEnergyThreshold then { val lack = minEnergyThreshold - _storedEnergy _storedEnergy = minEnergyThreshold return Option(lack) @@ -180,9 +180,8 @@ case object CylindricalThermalStorage { c: SpecificHeatCapacity, inletTemp: Temperature, returnTemp: Temperature - ): Energy = { + ): Energy = c.calcEnergy(returnTemp, inletTemp, volume) - } /** Equation from docs for the relation between stored heat and volume change. * diff --git a/src/main/scala/edu/ie3/simona/model/thermal/ThermalHouse.scala b/src/main/scala/edu/ie3/simona/model/thermal/ThermalHouse.scala index 639956e7b7..0e2c4a6a16 100644 --- a/src/main/scala/edu/ie3/simona/model/thermal/ThermalHouse.scala +++ b/src/main/scala/edu/ie3/simona/model/thermal/ThermalHouse.scala @@ -149,9 +149,8 @@ final case class ThermalHouse( */ private def calcInnerTemperatureChange( thermalEnergyChange: Energy - ): Temperature = { + ): Temperature = thermalEnergyChange / ethCapa - } /** Calculate the thermal energy change combining the added and lost energy * @@ -198,13 +197,12 @@ final case class ThermalHouse( innerTemperature: Temperature, ambientTemperature: Temperature, time: Time - ): Energy = { + ): Energy = ethLosses.thermalConductanceToEnergy( innerTemperature, ambientTemperature, time ) - } } diff --git a/src/main/scala/edu/ie3/simona/scheduler/RuntimeNotifier.scala b/src/main/scala/edu/ie3/simona/scheduler/RuntimeNotifier.scala index f80011fb2f..e83eddda86 100644 --- a/src/main/scala/edu/ie3/simona/scheduler/RuntimeNotifier.scala +++ b/src/main/scala/edu/ie3/simona/scheduler/RuntimeNotifier.scala @@ -8,7 +8,7 @@ package edu.ie3.simona.scheduler import org.apache.pekko.actor.typed.ActorRef import edu.ie3.simona.event.RuntimeEvent -import edu.ie3.simona.event.RuntimeEvent._ +import edu.ie3.simona.event.RuntimeEvent.* import edu.ie3.simona.scheduler.RuntimeNotifier.now import edu.ie3.simona.util.SimonaConstants.INIT_SIM_TICK @@ -65,10 +65,8 @@ final case class RuntimeNotifier( Simulating(tick, pauseOrEndTick) }) - if (tick > 0L) - copy(lastStartTime = nowTime) - else - copy(simStartTime = nowTime, lastStartTime = nowTime) + if tick > 0L then copy(lastStartTime = nowTime) + else copy(simStartTime = nowTime, lastStartTime = nowTime) } /** Notifier listeners that simulation is pausing at given tick @@ -95,12 +93,11 @@ final case class RuntimeNotifier( val nowTime = now() // check if InitComplete should be sent, then adjust lastCheck - val adjustedLastCheck = if (lastCheck <= -1) { - if (completedTick >= INIT_SIM_TICK) + val adjustedLastCheck = if lastCheck <= -1 then { + if completedTick >= INIT_SIM_TICK then notify(InitComplete(nowTime - simStartTime)) 0 - } else - lastCheck + } else lastCheck readyCheckWindow .flatMap { checkWindow => @@ -131,7 +128,7 @@ final case class RuntimeNotifier( * @param endTick * Last tick of the simulation */ - def finishing(endTick: Long): Unit = { + def finishing(endTick: Long): Unit = notify( Done( endTick, @@ -139,7 +136,6 @@ final case class RuntimeNotifier( errorInSim = false ) ) - } /** Notifier listeners that simulation has ended with error at given tick * diff --git a/src/main/scala/edu/ie3/simona/scheduler/ScheduleLock.scala b/src/main/scala/edu/ie3/simona/scheduler/ScheduleLock.scala index e9ca91c0d1..41ddd8cc4a 100644 --- a/src/main/scala/edu/ie3/simona/scheduler/ScheduleLock.scala +++ b/src/main/scala/edu/ie3/simona/scheduler/ScheduleLock.scala @@ -27,9 +27,9 @@ import java.util.UUID object ScheduleLock { sealed trait LockMsg - private final case class Init(adapter: ActorRef[Activation]) extends LockMsg + final private case class Init(adapter: ActorRef[Activation]) extends LockMsg - private final case object LockActivation extends LockMsg + final private case object LockActivation extends LockMsg /** @param key * the key that unlocks (part of) the lock @@ -41,8 +41,7 @@ object ScheduleLock { expectedTick: Long ): Behavior[Activation] = Behaviors.receive { case (ctx, Activation(tick)) => - if (tick == expectedTick) - lock ! LockActivation + if tick == expectedTick then lock ! LockActivation else ctx.log.error( s"Received lock activation for tick $tick, but expected $expectedTick" @@ -68,12 +67,12 @@ object ScheduleLock { def spawn[T](behavior: Behavior[T]): ActorRef[T] } - private final case class TypedSpawner(ctx: ActorContext[_]) extends Spawner { + final private case class TypedSpawner(ctx: ActorContext[?]) extends Spawner { override def spawn[T](behavior: Behavior[T]): ActorRef[T] = ctx.spawnAnonymous(behavior) } - private final case class ClassicSpawner( + final private case class ClassicSpawner( ctx: org.apache.pekko.actor.ActorContext ) extends Spawner { override def spawn[T](behavior: Behavior[T]): ActorRef[T] = @@ -93,7 +92,7 @@ object ScheduleLock { * A single key that unlocks the lock */ def singleKey( - ctx: ActorContext[_], + ctx: ActorContext[?], scheduler: ActorRef[SchedulerMessage], tick: Long ): ScheduleKey = @@ -154,7 +153,7 @@ object ScheduleLock { * A collection of keys that are needed to unlock the lock */ def multiKey( - ctx: ActorContext[_], + ctx: ActorContext[?], scheduler: ActorRef[SchedulerMessage], tick: Long, count: Int @@ -265,8 +264,7 @@ object ScheduleLock { ): Behavior[LockMsg] = Behaviors.receiveMessage { case Unlock(key) => val updatedKeys = awaitedKeys - key - if (updatedKeys.nonEmpty) - active(scheduler, updatedKeys, adapter) + if updatedKeys.nonEmpty then active(scheduler, updatedKeys, adapter) else { scheduler ! Completion(adapter) Behaviors.stopped diff --git a/src/main/scala/edu/ie3/simona/scheduler/Scheduler.scala b/src/main/scala/edu/ie3/simona/scheduler/Scheduler.scala index 455cc0c20f..5b655240a1 100644 --- a/src/main/scala/edu/ie3/simona/scheduler/Scheduler.scala +++ b/src/main/scala/edu/ie3/simona/scheduler/Scheduler.scala @@ -24,7 +24,7 @@ object Scheduler { trait Incoming - private final case class WrappedActivation(activation: Activation) + final private case class WrappedActivation(activation: Activation) extends Incoming def apply( @@ -66,7 +66,7 @@ object Scheduler { // also potentially schedule with parent if the new earliest tick is // different from the old earliest tick (including if nothing had // been scheduled before) - if (newEarliestTick != oldEarliestTick) + if newEarliestTick != oldEarliestTick then data.parent ! ScheduleActivation( data.activationAdapter, newTick, @@ -74,7 +74,7 @@ object Scheduler { ) else { // we don't need to escalate to the parent, this means that we can release the lock (if applicable) - unlockKey.foreach { _.unlock() } + unlockKey.foreach(_.unlock()) } inactive(updatedData, lastActiveTick) } @@ -101,7 +101,7 @@ object Scheduler { // if there's a lock: // since we're active and any scheduled activation can still influence our next activation, // we can directly unlock the lock with the key - unlockKey.foreach { _.unlock() } + unlockKey.foreach(_.unlock()) sendCurrentTriggers( scheduleTrigger(data, actor, newTick), @@ -130,7 +130,7 @@ object Scheduler { .map((_, updatedActivationData)) } .map { case (updatedData, updatedActivationData) => - if (isTickCompleted(updatedData, updatedActivationData)) { + if isTickCompleted(updatedData, updatedActivationData) then { // send completion to parent, if all completed completeWithParent(updatedData) inactive(updatedData, currentTick) @@ -161,11 +161,10 @@ object Scheduler { private def checkTriggerSchedule( minTick: Long, newTick: Long - ): Option[String] = { + ): Option[String] = Option.when(newTick < minTick) { s"Cannot schedule an event at tick $newTick when the last or currently activated tick is $minTick" } - } private def checkCompletion( activationData: ActivationData, diff --git a/src/main/scala/edu/ie3/simona/scheduler/TimeAdvancer.scala b/src/main/scala/edu/ie3/simona/scheduler/TimeAdvancer.scala index 5931cbb08a..9c2b5d0c5f 100644 --- a/src/main/scala/edu/ie3/simona/scheduler/TimeAdvancer.scala +++ b/src/main/scala/edu/ie3/simona/scheduler/TimeAdvancer.scala @@ -161,14 +161,13 @@ object TimeAdvancer { val notifierCompleted = notifier.completing(newTick - 1) - if (activeTick == INIT_SIM_TICK) + if activeTick == INIT_SIM_TICK then notifierCompleted.starting( newTick, pauseTick, data.endTick ) - else - notifierCompleted + else notifierCompleted } // activate next @@ -240,7 +239,7 @@ object TimeAdvancer { * @param endTick * the last tick of the simulation */ - private final case class TimeAdvancerData( + final private case class TimeAdvancerData( simulation: org.apache.pekko.actor.ActorRef, schedulee: ActorRef[Activation], endTick: Long diff --git a/src/main/scala/edu/ie3/simona/service/ExtDataSupport.scala b/src/main/scala/edu/ie3/simona/service/ExtDataSupport.scala index 31800da210..b6ca252233 100644 --- a/src/main/scala/edu/ie3/simona/service/ExtDataSupport.scala +++ b/src/main/scala/edu/ie3/simona/service/ExtDataSupport.scala @@ -15,15 +15,15 @@ trait ExtDataSupport[ ] { this: SimonaService[S] => - override def idleExternal(implicit stateData: S): Receive = { + override def idleExternal(using stateData: S): Receive = { case extMsg: DataMessageFromExt => val updatedStateData = handleDataMessage(extMsg)(stateData) - context become idle(updatedStateData) + context.become(idle(updatedStateData)) case extResponseMsg: EvResponseMessage => val updatedStateData = handleDataResponseMessage(extResponseMsg)(stateData) - context become idle(updatedStateData) + context.become(idle(updatedStateData)) } /** Handle a message from outside the simulation @@ -37,7 +37,7 @@ trait ExtDataSupport[ */ protected def handleDataMessage( extMsg: DataMessageFromExt - )(implicit serviceStateData: S): S + )(using serviceStateData: S): S /** Handle a message from inside SIMONA sent to external * @@ -50,5 +50,5 @@ trait ExtDataSupport[ */ protected def handleDataResponseMessage( extResponseMsg: EvResponseMessage - )(implicit serviceStateData: S): S + )(using serviceStateData: S): S } diff --git a/src/main/scala/edu/ie3/simona/service/SimonaService.scala b/src/main/scala/edu/ie3/simona/service/SimonaService.scala index 89d60e57c4..0b832c07cd 100644 --- a/src/main/scala/edu/ie3/simona/service/SimonaService.scala +++ b/src/main/scala/edu/ie3/simona/service/SimonaService.scala @@ -74,7 +74,7 @@ abstract class SimonaService[ Some(unlockKey) ) - context become initializing(initializeStateData) + context.become(initializing(initializeStateData)) // not ready yet to handle registrations, stash request away case _: ServiceRegistrationMessage => @@ -95,7 +95,7 @@ abstract class SimonaService[ case Success((serviceStateData, maybeNewTick)) => scheduler ! Completion(self.toTyped, maybeNewTick) unstashAll() - context become idle(serviceStateData) + context.become(idle(serviceStateData)) case Failure(exception) => // initialize service trigger with invalid data log.error( @@ -127,15 +127,15 @@ abstract class SimonaService[ * @return * default idleInternal method when the service is initialized */ - final protected def idle(implicit stateData: S): Receive = + final protected def idle(using stateData: S): Receive = idleExternal.applyOrElse(_, idleInternal(stateData)) - private def idleInternal(implicit stateData: S): Receive = { + private def idleInternal(using stateData: S): Receive = { // agent registration process case registrationMsg: ServiceRegistrationMessage => /* Someone asks to register for information from the service */ handleRegistrationRequest(registrationMsg) match { - case Success(stateData) => context become idle(stateData) + case Success(stateData) => context.become(idle(stateData)) case Failure(exception) => log.error( "Error during registration." + @@ -160,7 +160,7 @@ abstract class SimonaService[ val (updatedStateData, maybeNewTriggers) = announceInformation(tick)(stateData, context) scheduler ! Completion(self.toTyped, maybeNewTriggers) - context become idle(updatedStateData) + context.become(idle(updatedStateData)) // unhandled message case x => @@ -176,7 +176,7 @@ abstract class SimonaService[ * @return * empty behavior to ensure it only is called if it is overridden */ - private[service] def idleExternal(implicit stateData: S): Receive = + private[service] def idleExternal(using stateData: S): Receive = Actor.emptyBehavior /** Initialize the concrete service implementation using the provided @@ -209,7 +209,7 @@ abstract class SimonaService[ */ protected def handleRegistrationRequest( registrationMessage: ServiceRegistrationMessage - )(implicit + )(using serviceStateData: S ): Try[S] @@ -224,7 +224,7 @@ abstract class SimonaService[ * with updated values) together with the completion message that is send * in response to the trigger that was sent to start this announcement */ - protected def announceInformation(tick: Long)(implicit + protected def announceInformation(tick: Long)(using serviceStateData: S, ctx: ActorContext ): (S, Option[Long]) diff --git a/src/main/scala/edu/ie3/simona/service/ev/ExtEvDataService.scala b/src/main/scala/edu/ie3/simona/service/ev/ExtEvDataService.scala index 4bd2975747..01aa607a6a 100644 --- a/src/main/scala/edu/ie3/simona/service/ev/ExtEvDataService.scala +++ b/src/main/scala/edu/ie3/simona/service/ev/ExtEvDataService.scala @@ -10,11 +10,11 @@ import org.apache.pekko.actor.typed.scaladsl.adapter.ClassicActorRefOps import org.apache.pekko.actor.{ActorContext, ActorRef, Props} import edu.ie3.simona.api.data.ev.ExtEvData import edu.ie3.simona.api.data.ev.model.EvModel -import edu.ie3.simona.api.data.ev.ontology._ +import edu.ie3.simona.api.data.ev.ontology.* import edu.ie3.simona.api.data.ontology.DataMessageFromExt import edu.ie3.simona.exceptions.WeatherServiceException.InvalidRegistrationRequestException import edu.ie3.simona.exceptions.{InitializationException, ServiceException} -import edu.ie3.simona.ontology.messages.services.EvMessage._ +import edu.ie3.simona.ontology.messages.services.EvMessage.* import edu.ie3.simona.ontology.messages.services.ServiceMessage.RegistrationResponseMessage.RegistrationSuccessfulMessage import edu.ie3.simona.ontology.messages.services.ServiceMessage.ServiceRegistrationMessage import edu.ie3.simona.scheduler.ScheduleLock @@ -29,7 +29,7 @@ import edu.ie3.simona.service.ev.ExtEvDataService.{ import edu.ie3.simona.service.{ExtDataSupport, ServiceStateData, SimonaService} import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.util.{Failure, Success, Try} object ExtEvDataService { @@ -97,7 +97,7 @@ class ExtEvDataService(override val scheduler: ActorRef) */ override def handleRegistrationRequest( registrationMessage: ServiceRegistrationMessage - )(implicit + )(using serviceStateData: ExtEvStateData ): Try[ExtEvStateData] = registrationMessage match { @@ -128,7 +128,7 @@ class ExtEvDataService(override val scheduler: ActorRef) private def handleRegistrationRequest( agentToBeRegistered: ActorRef, evcs: UUID - )(implicit + )(using serviceStateData: ExtEvStateData ): ExtEvStateData = { log.debug( @@ -169,10 +169,10 @@ class ExtEvDataService(override val scheduler: ActorRef) */ override protected def announceInformation( tick: Long - )(implicit serviceStateData: ExtEvStateData, ctx: ActorContext): ( + )(using serviceStateData: ExtEvStateData, ctx: ActorContext): ( ExtEvStateData, Option[Long] - ) = { + ) = serviceStateData.extEvMessage.getOrElse( throw ServiceException( "ExtEvDataService was triggered without ExtEvMessage available" @@ -188,9 +188,8 @@ class ExtEvDataService(override val scheduler: ActorRef) ctx ) } - } - private def requestFreeLots(tick: Long)(implicit + private def requestFreeLots(tick: Long)(using serviceStateData: ExtEvStateData ): (ExtEvStateData, Option[Long]) = { serviceStateData.uuidToActorRef.foreach { case (_, evcsActor) => @@ -203,7 +202,7 @@ class ExtEvDataService(override val scheduler: ActorRef) } // if there are no evcs, we're sending response right away - if (freeLots.isEmpty) + if freeLots.isEmpty then serviceStateData.extEvData.queueExtResponseMsg(new ProvideEvcsFreeLots()) ( @@ -218,7 +217,7 @@ class ExtEvDataService(override val scheduler: ActorRef) private def requestDepartingEvs( tick: Long, requestedDepartingEvs: java.util.Map[UUID, java.util.List[UUID]] - )(implicit + )(using serviceStateData: ExtEvStateData ): (ExtEvStateData, Option[Long]) = { @@ -242,7 +241,7 @@ class ExtEvDataService(override val scheduler: ActorRef) // if there are no departing evs during this tick, // we're sending response right away - if (departingEvResponses.isEmpty) + if departingEvResponses.isEmpty then serviceStateData.extEvData.queueExtResponseMsg(new ProvideDepartingEvs()) ( @@ -257,7 +256,7 @@ class ExtEvDataService(override val scheduler: ActorRef) private def handleArrivingEvs( tick: Long, allArrivingEvs: java.util.Map[UUID, java.util.List[EvModel]] - )(implicit + )(using serviceStateData: ExtEvStateData, ctx: ActorContext ): (ExtEvStateData, Option[Long]) = { @@ -275,7 +274,7 @@ class ExtEvDataService(override val scheduler: ActorRef) } } - if (actorToEvs.nonEmpty) { + if actorToEvs.nonEmpty then { val keys = ScheduleLock.multiKey(ctx, scheduler.toTyped, tick, actorToEvs.size) @@ -299,7 +298,7 @@ class ExtEvDataService(override val scheduler: ActorRef) override protected def handleDataMessage( extMsg: DataMessageFromExt - )(implicit serviceStateData: ExtEvStateData): ExtEvStateData = + )(using serviceStateData: ExtEvStateData): ExtEvStateData = extMsg match { case extEvMessage: EvDataMessageFromExt => serviceStateData.copy( @@ -309,13 +308,13 @@ class ExtEvDataService(override val scheduler: ActorRef) override protected def handleDataResponseMessage( extResponseMsg: EvResponseMessage - )(implicit serviceStateData: ExtEvStateData): ExtEvStateData = { + )(using serviceStateData: ExtEvStateData): ExtEvStateData = extResponseMsg match { case DepartingEvsResponse(evcs, evModels) => val updatedResponses = serviceStateData.departingEvResponses + (evcs -> Some(evModels.toList)) - if (updatedResponses.values.toSeq.contains(None)) { + if updatedResponses.values.toSeq.contains(None) then { // responses are still incomplete serviceStateData.copy( departingEvResponses = updatedResponses @@ -336,7 +335,7 @@ class ExtEvDataService(override val scheduler: ActorRef) val updatedFreeLots = serviceStateData.freeLots + (evcs -> Some(freeLots)) - if (updatedFreeLots.values.toSeq.contains(None)) { + if updatedFreeLots.values.toSeq.contains(None) then { // responses are still incomplete serviceStateData.copy( freeLots = updatedFreeLots @@ -359,5 +358,4 @@ class ExtEvDataService(override val scheduler: ActorRef) ) } } - } } diff --git a/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceProxy.scala b/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceProxy.scala index 95103e347e..81c531ff58 100644 --- a/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceProxy.scala +++ b/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceProxy.scala @@ -31,9 +31,7 @@ import edu.ie3.datamodel.io.source.{ import edu.ie3.datamodel.models.value.Value import edu.ie3.simona.config.SimonaConfig.PrimaryDataCsvParams import edu.ie3.simona.config.SimonaConfig.Simona.Input.Primary.SqlParams -import edu.ie3.simona.config.SimonaConfig.Simona.Input.{ - Primary => PrimaryConfig -} +import edu.ie3.simona.config.SimonaConfig.Simona.Input.Primary as PrimaryConfig import edu.ie3.simona.exceptions.{ InitializationException, InvalidConfigParameterException @@ -66,7 +64,7 @@ import java.text.SimpleDateFormat import java.time.ZonedDateTime import java.util.UUID import scala.Option.when -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.jdk.OptionConverters.RichOptional import scala.util.{Failure, Success, Try} @@ -83,9 +81,9 @@ import scala.util.{Failure, Success, Try} */ case class PrimaryServiceProxy( scheduler: ActorRef, - initStateData: InitPrimaryServiceProxyStateData, - private implicit val startDateTime: ZonedDateTime -) extends Actor + initStateData: InitPrimaryServiceProxyStateData +)(using startDateTime: ZonedDateTime) + extends Actor with SimonaActorLogging { /** Start receiving without knowing specifics about myself @@ -110,7 +108,7 @@ case class PrimaryServiceProxy( ) match { case Success(stateData) => scheduler ! Completion(self.toTyped) - context become onMessage(stateData) + context.become(onMessage(stateData)) case Failure(exception) => log.error( exception, @@ -139,7 +137,7 @@ case class PrimaryServiceProxy( private def prepareStateData( primaryConfig: PrimaryConfig, simulationStart: ZonedDateTime - ): Try[PrimaryServiceStateData] = { + ): Try[PrimaryServiceStateData] = createSources(primaryConfig).map { case (mappingSource, metaInformationSource) => val modelToTimeSeries = mappingSource.getMapping.asScala.toMap @@ -175,11 +173,10 @@ case class PrimaryServiceProxy( mappingSource ) } - } private def createSources( primaryConfig: PrimaryConfig - ): Try[(TimeSeriesMappingSource, TimeSeriesMetaInformationSource)] = { + ): Try[(TimeSeriesMappingSource, TimeSeriesMetaInformationSource)] = Seq( primaryConfig.sqlParams, primaryConfig.influxDb1xParams, @@ -231,7 +228,6 @@ case class PrimaryServiceProxy( ) ) } - } /** Message handling, if the actor has been initialized already. This method * basically handles registration requests, checks, if pre-calculated, @@ -304,8 +300,10 @@ case class PrimaryServiceProxy( workerRef ! WorkerRegistrationMessage(requestingActor) /* Register the new worker within the state data and change the context */ - context become onMessage( - updateStateData(stateData, timeSeriesUuid, workerRef) + context.become( + onMessage( + updateStateData(stateData, timeSeriesUuid, workerRef) + ) ) case Failure(exception) => log.warning( @@ -384,7 +382,7 @@ case class PrimaryServiceProxy( valueClass: Class[V], timeSeriesUuid: String ): ActorRef = { - import edu.ie3.simona.actor.SimonaActorNaming._ + import edu.ie3.simona.actor.SimonaActorNaming.* context.system.simonaActorOf( PrimaryServiceWorker.props(scheduler, valueClass), timeSeriesUuid @@ -576,12 +574,12 @@ object PrimaryServiceProxy { primaryConfig.influxDb1xParams, primaryConfig.sqlParams ).filter(_.isDefined).flatten - if (sourceConfigs.size > 1) + if sourceConfigs.size > 1 then throw new InvalidConfigParameterException( s"${sourceConfigs.size} time series source types defined. " + s"Please define only one type!\nAvailable types:\n\t${supportedSources.mkString("\n\t")}" ) - else if (sourceConfigs.isEmpty) + else if sourceConfigs.isEmpty then throw new InvalidConfigParameterException( s"No time series source type defined. Please define exactly one type!" + s"\nAvailable types:\n\t${supportedSources.mkString("\n\t")}" diff --git a/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceWorker.scala b/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceWorker.scala index f7d7d58fb5..8e30f0b903 100644 --- a/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceWorker.scala +++ b/src/main/scala/edu/ie3/simona/service/primary/PrimaryServiceWorker.scala @@ -38,7 +38,7 @@ import edu.ie3.util.scala.collection.immutable.SortedDistinctSeq import java.nio.file.Path import java.time.ZonedDateTime import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.jdk.OptionConverters.RichOptional import scala.util.{Failure, Success, Try} @@ -64,7 +64,7 @@ final case class PrimaryServiceWorker[V <: Value]( PrimaryServiceInitializedStateData[V], Option[Long] ) - ] = { + ] = (initServiceData match { case PrimaryServiceWorker.CsvInitPrimaryServiceStateData( timeSeriesUuid, @@ -126,7 +126,7 @@ final case class PrimaryServiceWorker[V <: Value]( ) ) }).map { case (source, simulationStart) => - implicit val startDateTime: ZonedDateTime = simulationStart + given startDateTime: ZonedDateTime = simulationStart val (maybeNextTick, furtherActivationTicks) = SortedDistinctSeq( // Note: The whole data set is used here, which might be inefficient depending on the source implementation. @@ -152,7 +152,6 @@ final case class PrimaryServiceWorker[V <: Value]( ) (initializedStateData, maybeNextTick) } - } /** Handle a request to register for information from this service * @@ -166,7 +165,7 @@ final case class PrimaryServiceWorker[V <: Value]( */ override protected def handleRegistrationRequest( registrationMessage: ServiceMessage.ServiceRegistrationMessage - )(implicit + )(using serviceStateData: PrimaryServiceInitializedStateData[V] ): Try[PrimaryServiceInitializedStateData[V]] = registrationMessage match { case ServiceMessage.WorkerRegistrationMessage(requestingActor) => @@ -197,7 +196,7 @@ final case class PrimaryServiceWorker[V <: Value]( */ override protected def announceInformation( tick: Long - )(implicit + )(using serviceBaseStateData: PrimaryServiceInitializedStateData[V], ctx: ActorContext ): ( diff --git a/src/main/scala/edu/ie3/simona/service/weather/SampleWeatherSource.scala b/src/main/scala/edu/ie3/simona/service/weather/SampleWeatherSource.scala index d8bf55443f..4835287ea1 100644 --- a/src/main/scala/edu/ie3/simona/service/weather/SampleWeatherSource.scala +++ b/src/main/scala/edu/ie3/simona/service/weather/SampleWeatherSource.scala @@ -10,7 +10,7 @@ import edu.ie3.datamodel.io.source.IdCoordinateSource import edu.ie3.datamodel.models.input.NodeInput import edu.ie3.simona.ontology.messages.services.WeatherMessage.WeatherData import edu.ie3.simona.util.TickUtil -import edu.ie3.simona.util.TickUtil._ +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.geo.CoordinateDistance import edu.ie3.util.scala.quantities.WattsPerSquareMeter import org.locationtech.jts.geom.Point @@ -26,15 +26,14 @@ import java.time.temporal.ChronoField.{HOUR_OF_DAY, MONTH_OF_YEAR, YEAR} import java.util import java.util.{Collections, Optional} import javax.measure.quantity.Length -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* -final class SampleWeatherSource( - private implicit val simulationStart: ZonedDateTime +final class SampleWeatherSource(using + simulationStart: ZonedDateTime ) extends WeatherSource { private val resolution = 3600L - override protected val idCoordinateSource: IdCoordinateSource = { + override protected val idCoordinateSource: IdCoordinateSource = SampleWeatherSource.SampleIdCoordinateSource - } override val maxCoordinateDistance: ComparableQuantity[Length] = Quantities.getQuantity(50000d, Units.METRE) @@ -69,10 +68,9 @@ final class SampleWeatherSource( val month = wallClockTime.get(MONTH_OF_YEAR) - 1 val hour = wallClockTime.get(HOUR_OF_DAY) val year = - if ( - wallClockTime.get(YEAR) != 2011 && !(wallClockTime + if wallClockTime.get(YEAR) != 2011 && !(wallClockTime .get(YEAR) == 2012 && month == 0) - ) 2011 + then 2011 else wallClockTime.get(YEAR) val index = (((year - 2011) * 288) + (month * 24) + hour) + 1 val weatherResult = WeatherData( @@ -139,32 +137,28 @@ object SampleWeatherSource { coordinate: Point, n: Int, distance: ComparableQuantity[Length] - ): util.List[CoordinateDistance] = { - if (coordinate.getY.abs <= 90 && coordinate.getX.abs <= 180) + ): util.List[CoordinateDistance] = + if coordinate.getY.abs <= 90 && coordinate.getX.abs <= 180 then Vector( new CoordinateDistance( coordinate, coordinate ) ).asJava - else - Vector.empty[CoordinateDistance].asJava - } + else Vector.empty[CoordinateDistance].asJava override def getNearestCoordinates( coordinate: Point, i: Int - ): util.List[CoordinateDistance] = { - if (coordinate.getY.abs <= 90 && coordinate.getX.abs <= 180) + ): util.List[CoordinateDistance] = + if coordinate.getY.abs <= 90 && coordinate.getX.abs <= 180 then Vector( new CoordinateDistance( coordinate, coordinate ) ).asJava - else - Vector.empty[CoordinateDistance].asJava - } + else Vector.empty[CoordinateDistance].asJava } // these lists contain the hourly weather values for each first of the month of 2011 + january of diff --git a/src/main/scala/edu/ie3/simona/service/weather/WeatherService.scala b/src/main/scala/edu/ie3/simona/service/weather/WeatherService.scala index 12b2e6e2cb..2cd60f9e8a 100644 --- a/src/main/scala/edu/ie3/simona/service/weather/WeatherService.scala +++ b/src/main/scala/edu/ie3/simona/service/weather/WeatherService.scala @@ -15,7 +15,7 @@ import edu.ie3.simona.ontology.messages.services.ServiceMessage.RegistrationResp RegistrationSuccessfulMessage } import edu.ie3.simona.ontology.messages.services.ServiceMessage.ServiceRegistrationMessage -import edu.ie3.simona.ontology.messages.services.WeatherMessage._ +import edu.ie3.simona.ontology.messages.services.WeatherMessage.* import edu.ie3.simona.service.SimonaService import edu.ie3.simona.service.ServiceStateData.{ InitializeServiceStateData, @@ -47,10 +47,9 @@ object WeatherService { Props( new WeatherService( scheduler, - startDateTime, simulationEnd, amountOfInterpolationCoordinates - ) + )(using startDateTime) ) /** @param weatherSource @@ -97,9 +96,10 @@ object WeatherService { */ final case class WeatherService( override val scheduler: ActorRef, - private implicit val simulationStart: ZonedDateTime, simulationEnd: ZonedDateTime, private val amountOfInterpolationCoords: Int +)(using + simulationStart: ZonedDateTime ) extends SimonaService[ WeatherInitializedStateData ](scheduler) { @@ -167,7 +167,7 @@ final case class WeatherService( */ override def handleRegistrationRequest( registrationMessage: ServiceRegistrationMessage - )(implicit + )(using serviceStateData: WeatherInitializedStateData ): Try[WeatherInitializedStateData] = registrationMessage match { @@ -201,7 +201,7 @@ final case class WeatherService( agentToBeRegistered: ActorRef, latitude: Double, longitude: Double - )(implicit + )(using serviceStateData: WeatherInitializedStateData ): WeatherInitializedStateData = { log.debug( @@ -286,7 +286,7 @@ final case class WeatherService( * with updated values) together with the completion message that is send * in response to the trigger that was sent to start this announcement */ - override protected def announceInformation(tick: Long)(implicit + override protected def announceInformation(tick: Long)(using serviceStateData: WeatherInitializedStateData, ctx: ActorContext ): (WeatherInitializedStateData, Option[Long]) = { diff --git a/src/main/scala/edu/ie3/simona/service/weather/WeatherSource.scala b/src/main/scala/edu/ie3/simona/service/weather/WeatherSource.scala index 3a6961e321..2719462648 100644 --- a/src/main/scala/edu/ie3/simona/service/weather/WeatherSource.scala +++ b/src/main/scala/edu/ie3/simona/service/weather/WeatherSource.scala @@ -15,11 +15,11 @@ import edu.ie3.datamodel.io.factory.timeseries.{ import edu.ie3.datamodel.io.connectors.SqlConnector import edu.ie3.datamodel.io.naming.FileNamingStrategy import edu.ie3.datamodel.io.source.IdCoordinateSource -import edu.ie3.datamodel.io.source.csv.CsvIdCoordinateSource +import edu.ie3.datamodel.io.source.csv.{CsvDataSource, CsvIdCoordinateSource} import edu.ie3.datamodel.io.source.sql.SqlIdCoordinateSource import edu.ie3.datamodel.models.value.WeatherValue import edu.ie3.simona.config.SimonaConfig -import edu.ie3.simona.config.SimonaConfig.Simona.Input.Weather.Datasource._ +import edu.ie3.simona.config.SimonaConfig.Simona.Input.Weather.Datasource.* import edu.ie3.simona.exceptions.{ InvalidConfigParameterException, ServiceException @@ -39,7 +39,6 @@ import edu.ie3.simona.util.ConfigUtil.DatabaseConfigUtil.{ import edu.ie3.simona.util.ParsableEnumeration import edu.ie3.util.geo.{CoordinateDistance, GeoUtils} import edu.ie3.util.quantities.PowerSystemUnits -import edu.ie3.util.scala.io.CsvDataSourceAdapter import org.locationtech.jts.geom.{Coordinate, Point} import tech.units.indriya.ComparableQuantity import edu.ie3.util.scala.quantities.WattsPerSquareMeter @@ -51,7 +50,7 @@ import tech.units.indriya.unit.Units import java.nio.file.Paths import java.time.ZonedDateTime import javax.measure.quantity.{Dimensionless, Length} -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.jdk.OptionConverters.RichOptional import scala.util.{Failure, Success, Try} @@ -74,7 +73,7 @@ trait WeatherSource { def getWeightedCoordinates( coordinate: WeatherSource.AgentCoordinates, amountOfInterpolationCoords: Int - ): Try[WeatherSource.WeightedCoordinates] = { + ): Try[WeatherSource.WeightedCoordinates] = getNearestCoordinatesWithDistances( coordinate, amountOfInterpolationCoords @@ -89,7 +88,6 @@ trait WeatherSource { ) ) } - } /** Tries to find the nearest coordinates around the queried coordinate. If * the queried coordinate hits a weather coordinate directly, only this one @@ -137,7 +135,7 @@ trait WeatherSource { coordDistance.getDistance .isLessThan(maxCoordinateDistance) ) - if (nearestCoordsInMaxDistance.size < amountOfInterpolationCoords) { + if nearestCoordsInMaxDistance.size < amountOfInterpolationCoords then { Failure( ServiceException( s"There are not enough coordinates within the max coordinate distance of $maxCoordinateDistance. Found ${nearestCoordsInMaxDistance.size} but need $amountOfInterpolationCoords. Please make sure that there are enough coordinates within the given distance." @@ -158,7 +156,7 @@ trait WeatherSource { } /* There has to be a coordinate in each quadrant */ - if (topLeft && topRight && bottomLeft && bottomRight) + if topLeft && topRight && bottomLeft && bottomRight then Success(nearestCoords) else Failure( @@ -180,7 +178,7 @@ trait WeatherSource { */ def determineWeights( nearestCoordinates: Iterable[CoordinateDistance] - ): Try[WeightedCoordinates] = { + ): Try[WeightedCoordinates] = nearestCoordinates.headOption match { case Some(dist) if nearestCoordinates.size == 1 => /* There is only one coordinate -> weight this with 1 */ @@ -204,27 +202,24 @@ trait WeatherSource { .getValue .doubleValue() - if ( - totalDistanceToSurroundingCoordinates.isGreaterThan( + if totalDistanceToSurroundingCoordinates.isGreaterThan( Quantities.getQuantity(0d, Units.METRE) ) - ) { - val weightMap = nearestCoordinates - .map(coordinateDistance => { - /* Maybe some words on the calculus of the weight here: We intend to have a weight, that linear increases - * from zero to one, the closer the coordinate is to the coordinate in question. Therefore we calculate the - * proximity of each node as a linear function between 1 at 0m distance to the questioned coordinate to zero - * at the sum of all coordinates' distances (1 - d / d_sum). However, summing up this proximity over all - * n coordinates brings n*1 from the left part of the sum and -1 as the sum of all distances shares. - * Thereby all weights sum up to n-1. Therefore, we divide by this to scale the sum of weights to one. */ - val weight = - toProximity(coordinateDistance) / (nearestCoordinates.size - 1) - coordinateDistance.getCoordinateB -> weight - }) - .toMap + then { + val weightMap = nearestCoordinates.map { coordinateDistance => + /* Maybe some words on the calculus of the weight here: We intend to have a weight, that linear increases + * from zero to one, the closer the coordinate is to the coordinate in question. Therefore we calculate the + * proximity of each node as a linear function between 1 at 0m distance to the questioned coordinate to zero + * at the sum of all coordinates' distances (1 - d / d_sum). However, summing up this proximity over all + * n coordinates brings n*1 from the left part of the sum and -1 as the sum of all distances shares. + * Thereby all weights sum up to n-1. Therefore, we divide by this to scale the sum of weights to one. */ + val weight = + toProximity(coordinateDistance) / (nearestCoordinates.size - 1) + coordinateDistance.getCoordinateB -> weight + }.toMap val weightSum = weightMap.values.sum - if (weightSum > 0.99 && weightSum < 1.01) + if weightSum > 0.99 && weightSum < 1.01 then Success(WeightedCoordinates(weightMap)) else Failure( @@ -239,7 +234,6 @@ trait WeatherSource { ) ) } - } /** Get the weather data for the given tick as a weighted average taking into * account the given weighting of weather coordinates. @@ -321,7 +315,7 @@ object WeatherSource { ) /* Check, if the column scheme is supported */ - if (!WeatherScheme.isEligibleInput(weatherDataSourceCfg.scheme)) + if !WeatherScheme.isEligibleInput(weatherDataSourceCfg.scheme) then throw new InvalidConfigParameterException( s"The weather data scheme '${weatherDataSourceCfg.scheme}' is not supported. Supported schemes:\n\t${WeatherScheme.values .mkString("\n\t")}" @@ -348,7 +342,7 @@ object WeatherSource { ) // check that only one source is defined - if (definedWeatherSources.size > 1) + if definedWeatherSources.size > 1 then throw new InvalidConfigParameterException( s"Multiple weather sources defined: '${definedWeatherSources.map(_.getClass.getSimpleName).mkString("\n\t")}'." + s"Please define only one source!\nAvailable sources:\n\t${supportedWeatherSources.mkString("\n\t")}" @@ -452,7 +446,7 @@ object WeatherSource { ).filter(_.isDefined) // check that only one source is defined - if (definedCoordSources.size > 1) + if definedCoordSources.size > 1 then throw new InvalidConfigParameterException( s"Multiple coordinate sources defined: '${definedCoordSources.map(_.getClass.getSimpleName).mkString("\n\t")}'." + s"Please define only one source!\nAvailable sources:\n\t${supportedCoordinateSources.mkString("\n\t")}" @@ -470,7 +464,7 @@ object WeatherSource { () => new CsvIdCoordinateSource( idCoordinateFactory, - new CsvDataSourceAdapter( + new CsvDataSource( csvSep, Paths.get(directoryPath), new FileNamingStrategy() @@ -525,7 +519,7 @@ object WeatherSource { private def checkCoordinateFactory( gridModel: String ): IdCoordinateFactory = { - if (gridModel.isEmpty) + if gridModel.isEmpty then throw new InvalidConfigParameterException("No grid model defined!") gridModel.toLowerCase() match { case "icon" => new IconIdCoordinateFactory() @@ -553,7 +547,7 @@ object WeatherSource { def toWeatherData( weatherValue: WeatherValue - ): WeatherData = { + ): WeatherData = WeatherData( weatherValue.getSolarIrradiance.getDiffuseIrradiance.toScala match { case Some(irradiance) => @@ -597,12 +591,10 @@ object WeatherSource { } ) - } - /** Weather package private case class to combine the provided agent * coordinates into one single entity */ - private[weather] final case class AgentCoordinates( + final private[weather] case class AgentCoordinates( latitude: Double, longitude: Double ) { @@ -618,7 +610,7 @@ object WeatherSource { * @param weighting * Mapping from weather coordinate to it's weight in averaging */ - private[weather] final case class WeightedCoordinates( + final private[weather] case class WeightedCoordinates( weighting: Map[Point, Double] ) diff --git a/src/main/scala/edu/ie3/simona/service/weather/WeatherSourceWrapper.scala b/src/main/scala/edu/ie3/simona/service/weather/WeatherSourceWrapper.scala index 2fc48cd5f9..43a678b9aa 100644 --- a/src/main/scala/edu/ie3/simona/service/weather/WeatherSourceWrapper.scala +++ b/src/main/scala/edu/ie3/simona/service/weather/WeatherSourceWrapper.scala @@ -23,7 +23,7 @@ import edu.ie3.datamodel.io.source.influxdb.InfluxDbWeatherSource import edu.ie3.datamodel.io.source.sql.SqlWeatherSource import edu.ie3.datamodel.io.source.{ IdCoordinateSource, - WeatherSource => PsdmWeatherSource + WeatherSource as PsdmWeatherSource } import edu.ie3.simona.config.SimonaConfig.Simona.Input.Weather.Datasource.{ CouchbaseParams, @@ -39,7 +39,7 @@ import edu.ie3.simona.service.weather.WeatherSource.{ toWeatherData } import edu.ie3.simona.service.weather.WeatherSourceWrapper.WeightSum -import edu.ie3.simona.service.weather.{WeatherSource => SimonaWeatherSource} +import edu.ie3.simona.service.weather.WeatherSource as SimonaWeatherSource import edu.ie3.simona.util.TickUtil import edu.ie3.simona.util.TickUtil.TickLong import edu.ie3.util.DoubleUtils.ImplicitDouble @@ -68,13 +68,13 @@ import scala.util.{Failure, Success, Try} * @param simulationStart * start of the simulation */ -private[weather] final case class WeatherSourceWrapper private ( +final private[weather] case class WeatherSourceWrapper private ( source: PsdmWeatherSource, override val idCoordinateSource: IdCoordinateSource, resolution: Long, maxCoordinateDistance: ComparableQuantity[Length] -)( - private implicit val simulationStart: ZonedDateTime +)(using + simulationStart: ZonedDateTime ) extends SimonaWeatherSource with LazyLogging { @@ -206,7 +206,7 @@ private[weather] object WeatherSourceWrapper extends LazyLogging { scheme: String, resolution: Option[Long], maxCoordinateDistance: ComparableQuantity[Length] - )(implicit simulationStart: ZonedDateTime): WeatherSourceWrapper = { + )(using simulationStart: ZonedDateTime): WeatherSourceWrapper = { val idCoordinateSource = idCoordinateSourceFunction() val source = new CsvWeatherSource( csvSep, @@ -233,7 +233,7 @@ private[weather] object WeatherSourceWrapper extends LazyLogging { scheme: String, resolution: Option[Long], maxCoordinateDistance: ComparableQuantity[Length] - )(implicit simulationStart: ZonedDateTime): WeatherSourceWrapper = { + )(using simulationStart: ZonedDateTime): WeatherSourceWrapper = { val couchbaseConnector = new CouchbaseConnector( couchbaseParams.url, couchbaseParams.bucketName, @@ -267,7 +267,7 @@ private[weather] object WeatherSourceWrapper extends LazyLogging { scheme: String, resolution: Option[Long], maxCoordinateDistance: ComparableQuantity[Length] - )(implicit simulationStart: ZonedDateTime): WeatherSourceWrapper = { + )(using simulationStart: ZonedDateTime): WeatherSourceWrapper = { val influxDb1xConnector = new InfluxDbConnector(influxDbParams.url, influxDbParams.database) val idCoordinateSource = idCoordinateSourceFunction() @@ -294,7 +294,7 @@ private[weather] object WeatherSourceWrapper extends LazyLogging { scheme: String, resolution: Option[Long], maxCoordinateDistance: ComparableQuantity[Length] - )(implicit simulationStart: ZonedDateTime): WeatherSourceWrapper = { + )(using simulationStart: ZonedDateTime): WeatherSourceWrapper = { val sqlConnector = new SqlConnector( sqlParams.jdbcUrl, sqlParams.userName, @@ -385,15 +385,15 @@ private[weather] object WeatherSourceWrapper extends LazyLogging { */ def scale(weatherData: WeatherData): WeatherData = weatherData match { case WeatherData(diffIrr, dirIrr, temp, windVel) => - implicit val precision: Double = 1e-3 + given precision: Double = 1e-3 WeatherData( - if (this.diffIrr !~= 0d) diffIrr.divide(this.diffIrr) + if this.diffIrr !~= 0d then diffIrr.divide(this.diffIrr) else EMPTY_WEATHER_DATA.diffIrr, - if (this.dirIrr !~= 0d) dirIrr.divide(this.dirIrr) + if this.dirIrr !~= 0d then dirIrr.divide(this.dirIrr) else EMPTY_WEATHER_DATA.dirIrr, - if (this.temp !~= 0d) temp.divide(this.temp) + if this.temp !~= 0d then temp.divide(this.temp) else EMPTY_WEATHER_DATA.temp, - if (this.windVel !~= 0d) windVel.divide(this.windVel) + if this.windVel !~= 0d then windVel.divide(this.windVel) else EMPTY_WEATHER_DATA.windVel ) } diff --git a/src/main/scala/edu/ie3/simona/sim/SimonaSim.scala b/src/main/scala/edu/ie3/simona/sim/SimonaSim.scala index 7a619552eb..5635df88da 100644 --- a/src/main/scala/edu/ie3/simona/sim/SimonaSim.scala +++ b/src/main/scala/edu/ie3/simona/sim/SimonaSim.scala @@ -125,7 +125,7 @@ class SimonaSim(simonaSetup: SimonaSetup) case InitSim => // tell scheduler to process all init messages timeAdvancer ! StartSimMessage() - context become simonaSimReceive(data.copy(initSimSender = sender())) + context.become(simonaSimReceive(data.copy(initSimSender = sender()))) case StartSimulation(pauseScheduleAtTick) => timeAdvancer ! StartSimMessage(pauseScheduleAtTick) @@ -148,10 +148,12 @@ class SimonaSim(simonaSetup: SimonaSetup) stopAllChildrenGracefully(simulationSuccessful) // wait for listeners and send final message to parent - context become waitingForListener( - data.initSimSender, - simulationSuccessful, - systemParticipantsListener + context.become( + waitingForListener( + data.initSimSender, + simulationSuccessful, + systemParticipantsListener + ) ) case EmergencyShutdownInitiated => @@ -172,10 +174,12 @@ class SimonaSim(simonaSetup: SimonaSetup) stopAllChildrenGracefully(simulationSuccessful = false) // wait for listeners and send final message to parent - context become waitingForListener( - data.initSimSender, - successful = false, - systemParticipantsListener + context.become( + waitingForListener( + data.initSimSender, + successful = false, + systemParticipantsListener + ) ) } @@ -208,22 +212,24 @@ class SimonaSim(simonaSetup: SimonaSetup) updatedRemainingListeners ) - if (updatedRemainingListeners.isEmpty) { + if updatedRemainingListeners.isEmpty then { logger.info( "The last remaining result listener has been terminated. Exiting." ) val msg = - if (successful) SimulationSuccessful + if successful then SimulationSuccessful else SimulationFailure // inform InitSim Sender initSimSender ! msg } - context become waitingForListener( - initSimSender, - successful, - updatedRemainingListeners + context.become( + waitingForListener( + initSimSender, + successful, + updatedRemainingListeners + ) ) } @@ -269,7 +275,7 @@ object SimonaSim { */ case object EmergencyShutdownInitiated - private[SimonaSim] final case class SimonaSimStateData( + final private[SimonaSim] case class SimonaSimStateData( initSimSender: ActorRef = ActorRef.noSender ) diff --git a/src/main/scala/edu/ie3/simona/sim/setup/ExtSimLoader.scala b/src/main/scala/edu/ie3/simona/sim/setup/ExtSimLoader.scala index 4275ab7d33..7cd8d6d093 100644 --- a/src/main/scala/edu/ie3/simona/sim/setup/ExtSimLoader.scala +++ b/src/main/scala/edu/ie3/simona/sim/setup/ExtSimLoader.scala @@ -12,7 +12,7 @@ import edu.ie3.simona.api.ExtLinkInterface import java.io.{File, IOException} import java.net.URLClassLoader import java.util.ServiceLoader -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Finds and loads jars containing external simulations. */ @@ -22,7 +22,7 @@ object ExtSimLoader extends LazyLogging { def getStandardDirectory: File = { val workingDir = new File(System.getProperty("user.dir")) - if (!workingDir.isDirectory) + if !workingDir.isDirectory then throw new IOException("Error when accessing working directory.") new File(workingDir, extSimPath) @@ -31,7 +31,7 @@ object ExtSimLoader extends LazyLogging { def scanInputFolder( extSimDir: File = getStandardDirectory ): Iterable[File] = { - if (!extSimDir.isDirectory) { + if !extSimDir.isDirectory then { logger.warn( s"External simulation directory ${extSimDir.getPath} does not exist or is not a directory, no external simulation loaded." ) diff --git a/src/main/scala/edu/ie3/simona/sim/setup/ExtSimSetupData.scala b/src/main/scala/edu/ie3/simona/sim/setup/ExtSimSetupData.scala index 4706a50f09..4adce6ac9c 100644 --- a/src/main/scala/edu/ie3/simona/sim/setup/ExtSimSetupData.scala +++ b/src/main/scala/edu/ie3/simona/sim/setup/ExtSimSetupData.scala @@ -11,7 +11,7 @@ import edu.ie3.simona.service.ev.ExtEvDataService final case class ExtSimSetupData( extSimAdapters: Iterable[ActorRef], - extDataServices: Map[Class[_], ActorRef] + extDataServices: Map[Class[?], ActorRef] ) { def evDataService: Option[ActorRef] = diff --git a/src/main/scala/edu/ie3/simona/sim/setup/SetupHelper.scala b/src/main/scala/edu/ie3/simona/sim/setup/SetupHelper.scala index 1e319ecbcc..9e2e3017ea 100644 --- a/src/main/scala/edu/ie3/simona/sim/setup/SetupHelper.scala +++ b/src/main/scala/edu/ie3/simona/sim/setup/SetupHelper.scala @@ -7,7 +7,7 @@ package edu.ie3.simona.sim.setup import org.apache.pekko.actor.ActorRef -import com.typesafe.config.{Config => TypesafeConfig} +import com.typesafe.config.Config as TypesafeConfig import com.typesafe.scalalogging.LazyLogging import edu.ie3.datamodel.graph.SubGridGate import edu.ie3.datamodel.models.input.container.{SubGridContainer, ThermalGrid} @@ -102,17 +102,17 @@ trait SetupHelper extends LazyLogging { subGridGates .groupBy(gate => (gate.superiorNode, gate.inferiorNode)) .flatMap(_._2.headOption) - .map(gate => { + .map { gate => val superiorSubGrid = gate.getSuperiorSubGrid val inferiorSubGrid = gate.getInferiorSubGrid - if (inferiorSubGrid == currentSubGrid) { + if inferiorSubGrid == currentSubGrid then { /* This is a gate to a superior sub grid */ gate -> getActorRef( subGridToActorRefMap, currentSubGrid, superiorSubGrid ) - } else if (superiorSubGrid == currentSubGrid) { + } else if superiorSubGrid == currentSubGrid then { /* This is a gate to an inferior sub grid */ gate -> getActorRef( subGridToActorRefMap, @@ -124,7 +124,7 @@ trait SetupHelper extends LazyLogging { "I am supposed to connect sub grid " + currentSubGrid + " with itself, which is not allowed." ) } - }) + } .toMap /** Get the actor reference from the map or throw an exception, if it is not @@ -143,7 +143,7 @@ trait SetupHelper extends LazyLogging { subGridToActorRefMap: Map[Int, ActorRef], currentSubGrid: Int, queriedSubGrid: Int - ): ActorRef = { + ): ActorRef = subGridToActorRefMap.get(queriedSubGrid) match { case Some(hit) => hit case _ => @@ -151,7 +151,6 @@ trait SetupHelper extends LazyLogging { "I am supposed to connect sub grid " + currentSubGrid + " with " + queriedSubGrid + ", but I cannot find the matching actor reference." ) } - } /** Searches for the reference system to be used with the given * [[SubGridContainer]] within the information provided by config. @@ -179,11 +178,10 @@ trait SetupHelper extends LazyLogging { ) ) - if ( - !refSystem.nominalVoltage.equals( + if !refSystem.nominalVoltage.equals( subGridContainer.getPredominantVoltageLevel.getNominalVoltage ) - ) + then logger.warn( s"The configured RefSystem for subGrid ${subGridContainer.getSubnet} differs in its nominal voltage (${refSystem.nominalVoltage}) from the grids" + s"predominant voltage level nominal voltage (${subGridContainer.getPredominantVoltageLevel.getNominalVoltage}). If this is by intention and still valid, this " + @@ -248,7 +246,7 @@ case object SetupHelper { */ def allResultEntitiesToWrite( outputConfig: SimonaConfig.Simona.Output - ): Set[Class[_ <: ResultEntity]] = + ): Set[Class[? <: ResultEntity]] = GridOutputConfigUtil( outputConfig.grid ).simulationResultEntitiesToConsider ++ diff --git a/src/main/scala/edu/ie3/simona/sim/setup/SimonaStandaloneSetup.scala b/src/main/scala/edu/ie3/simona/sim/setup/SimonaStandaloneSetup.scala index 246fda0101..31a702aa6c 100644 --- a/src/main/scala/edu/ie3/simona/sim/setup/SimonaStandaloneSetup.scala +++ b/src/main/scala/edu/ie3/simona/sim/setup/SimonaStandaloneSetup.scala @@ -6,18 +6,12 @@ package edu.ie3.simona.sim.setup -import org.apache.pekko.actor.typed.scaladsl.adapter.{ - ClassicActorContextOps, - ClassicActorRefOps, - TypedActorRefOps -} -import org.apache.pekko.actor.{ActorContext, ActorRef, ActorSystem} import com.typesafe.config.Config import com.typesafe.scalalogging.LazyLogging import edu.ie3.datamodel.graph.SubGridTopologyGraph import edu.ie3.datamodel.models.input.container.{GridContainer, ThermalGrid} import edu.ie3.datamodel.models.input.thermal.ThermalBusInput -import edu.ie3.simona.actor.SimonaActorNaming._ +import edu.ie3.simona.actor.SimonaActorNaming.* import edu.ie3.simona.agent.EnvironmentRefs import edu.ie3.simona.agent.grid.GridAgent import edu.ie3.simona.api.ExtSimAdapter @@ -42,9 +36,15 @@ import edu.ie3.simona.util.ResultFileHierarchy import edu.ie3.simona.util.SimonaConstants.INIT_SIM_TICK import edu.ie3.simona.util.TickUtil.RichZonedDateTime import edu.ie3.util.TimeUtil +import org.apache.pekko.actor.typed.scaladsl.adapter.{ + ClassicActorContextOps, + ClassicActorRefOps, + TypedActorRefOps +} +import org.apache.pekko.actor.{ActorContext, ActorRef, ActorSystem} import java.util.concurrent.LinkedBlockingQueue -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Sample implementation to run a standalone simulation of simona configured * with the provided [[SimonaConfig]] and [[ResultFileHierarchy]] @@ -206,7 +206,7 @@ class SimonaStandaloneSetup( // setup data services that belong to this external simulation val (extData, extDataInit): ( Iterable[ExtData], - Iterable[(Class[_ <: SimonaService[_]], ActorRef)] + Iterable[(Class[? <: SimonaService[?]], ActorRef)] ) = extLink.getExtDataSimulations.asScala.zipWithIndex.map { case (_: ExtEvSimulation, dIndex) => @@ -294,7 +294,7 @@ class SimonaStandaloneSetup( override def systemParticipantsListener( context: ActorContext - ): Seq[ActorRef] = { + ): Seq[ActorRef] = // append ResultEventListener as well to write raw output files ArgsParser .parseListenerConfigOption(simonaConfig.simona.event.listener) @@ -313,18 +313,17 @@ class SimonaStandaloneSetup( ResultEventListener.getClass.getSimpleName ) .toClassic - } def buildSubGridToActorRefMap( subGridTopologyGraph: SubGridTopologyGraph, context: ActorContext, environmentRefs: EnvironmentRefs, systemParticipantListener: Seq[ActorRef] - ): Map[Int, ActorRef] = { + ): Map[Int, ActorRef] = subGridTopologyGraph .vertexSet() .asScala - .map(subGridContainer => { + .map { subGridContainer => val gridAgentRef = context.simonaActorOf( GridAgent.props( @@ -335,9 +334,8 @@ class SimonaStandaloneSetup( subGridContainer.getSubnet.toString ) subGridContainer.getSubnet -> gridAgentRef - }) + } .toMap - } /** Get all thermal grids, that apply for the given grid container * @param grid @@ -350,11 +348,10 @@ class SimonaStandaloneSetup( private def getThermalGrids( grid: GridContainer, thermalGridByBus: Map[ThermalBusInput, ThermalGrid] - ): Seq[ThermalGrid] = { + ): Seq[ThermalGrid] = grid.getSystemParticipants.getHeatPumps.asScala .flatten(hpInput => thermalGridByBus.get(hpInput.getThermalBus)) .toSeq - } } /** Companion object to provide [[SetupHelper]] methods for diff --git a/src/main/scala/edu/ie3/simona/util/CollectionUtils.scala b/src/main/scala/edu/ie3/simona/util/CollectionUtils.scala index 835f048cf6..1cd655a55b 100644 --- a/src/main/scala/edu/ie3/simona/util/CollectionUtils.scala +++ b/src/main/scala/edu/ie3/simona/util/CollectionUtils.scala @@ -62,7 +62,8 @@ object CollectionUtils { list match { case Nil => true case headEntry :: tailList => - if (set(headEntry)) false else isUniqueList(tailList, set + headEntry) + if set(headEntry) then false + else isUniqueList(tailList, set + headEntry) } /** Checks if the provided list is sorted in accordance to the provided @@ -79,7 +80,7 @@ object CollectionUtils { * otherwise */ @tailrec - def isSorted[T](list: List[T])(implicit ord: Ordering[T]): Boolean = + def isSorted[T](list: List[T])(using ord: Ordering[T]): Boolean = list match { case Nil => true // an empty list is sorted case _ :: Nil => true // a single-element list is sorted @@ -109,9 +110,9 @@ object CollectionUtils { key: A ): Seq[(A, O)] = { import scala.collection.immutable.TreeMap - implicit val ordering: Double.IeeeOrdering.type = + given ordering: Double.IeeeOrdering.type = Ordering.Double.IeeeOrdering - val treeMap = TreeMap(map.toSeq: _*) // preserves order + val treeMap = TreeMap(map.toSeq*) // preserves order Seq( treeMap.rangeTo(key).lastOption, diff --git a/src/main/scala/edu/ie3/simona/util/ConfigUtil.scala b/src/main/scala/edu/ie3/simona/util/ConfigUtil.scala index 0e3a8e412b..4c95bf1f6e 100644 --- a/src/main/scala/edu/ie3/simona/util/ConfigUtil.scala +++ b/src/main/scala/edu/ie3/simona/util/ConfigUtil.scala @@ -21,7 +21,7 @@ import edu.ie3.datamodel.models.result.connector.{ import edu.ie3.datamodel.models.result.{NodeResult, ResultEntity} import edu.ie3.simona.config.SimonaConfig import edu.ie3.simona.config.SimonaConfig.Simona.Input.Weather.Datasource.SqlParams -import edu.ie3.simona.config.SimonaConfig._ +import edu.ie3.simona.config.SimonaConfig.* import edu.ie3.simona.event.notifier.{Notifier, NotifierConfig} import edu.ie3.simona.exceptions.InvalidConfigParameterException import org.apache.kafka.clients.admin.AdminClient @@ -31,7 +31,7 @@ import java.io.File import java.util.concurrent.ExecutionException import java.util.{Properties, UUID} import scala.collection.mutable -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* import scala.reflect.ClassTag import scala.util.{Failure, Success, Try, Using} @@ -39,7 +39,7 @@ object ConfigUtil { final case class ParticipantConfigUtil private ( private val configs: Map[UUID, SimonaConfig.BaseRuntimeConfig], - private val defaultConfigs: Map[Class[_], BaseRuntimeConfig] + private val defaultConfigs: Map[Class[?], BaseRuntimeConfig] ) { /** Queries for a [[BaseRuntimeConfig]] of type [[T]], that applies for the @@ -53,7 +53,7 @@ object ConfigUtil { */ def getOrDefault[T <: BaseRuntimeConfig]( uuid: UUID - )(implicit tag: ClassTag[T]): T = + )(using tag: ClassTag[T]): T = configs.get(uuid) match { case Some(conf: T) => conf case _ => @@ -80,7 +80,7 @@ object ConfigUtil { */ def apply( subConfig: SimonaConfig.Simona.Runtime.Participant - ): ParticipantConfigUtil = { + ): ParticipantConfigUtil = ParticipantConfigUtil( buildUuidMapping( Seq( @@ -98,9 +98,8 @@ object ConfigUtil { subConfig.evcs.defaultConfig, subConfig.wec.defaultConfig, subConfig.hp.defaultConfig - ).map { conf => conf.getClass -> conf }.toMap + ).map(conf => conf.getClass -> conf).toMap ) - } private def buildUuidMapping( configs: Seq[BaseRuntimeConfig] @@ -142,7 +141,7 @@ object ConfigUtil { * A set of applicable notifiers */ def simulationResultIdentifiersToConsider: Set[NotifierIdentifier.Value] = - if (defaultConfig.simulationResultInfo) { + if defaultConfig.simulationResultInfo then { /* Generally inform about all simulation results, but not on those, that are explicitly marked */ NotifierIdentifier.values -- configs.flatMap { case ( @@ -164,7 +163,7 @@ object ConfigUtil { }.toSet } - def simulationResultEntitiesToConsider: Set[Class[_ <: ResultEntity]] = + def simulationResultEntitiesToConsider: Set[Class[? <: ResultEntity]] = simulationResultIdentifiersToConsider.map(notifierId => EntityMapperUtil.getResultEntityClass(notifierId) ) @@ -234,19 +233,14 @@ object ConfigUtil { * @return * Set of result entity classes */ - def simulationResultEntitiesToConsider: Set[Class[_ <: ResultEntity]] = { - val entities = mutable.Set.empty[Class[_ <: ResultEntity]] - - if (subConfig.nodes) - entities += classOf[NodeResult] - if (subConfig.lines) - entities += classOf[LineResult] - if (subConfig.switches) - entities += classOf[SwitchResult] - if (subConfig.transformers2w) - entities += classOf[Transformer2WResult] - if (subConfig.transformers3w) - entities += classOf[Transformer3WResult] + def simulationResultEntitiesToConsider: Set[Class[? <: ResultEntity]] = { + val entities = mutable.Set.empty[Class[? <: ResultEntity]] + + if subConfig.nodes then entities += classOf[NodeResult] + if subConfig.lines then entities += classOf[LineResult] + if subConfig.switches then entities += classOf[SwitchResult] + if subConfig.transformers2w then entities += classOf[Transformer2WResult] + if subConfig.transformers3w then entities += classOf[Transformer3WResult] entities.toSet } @@ -284,14 +278,13 @@ object ConfigUtil { csvParamsName: String ): Unit = params match { case BaseCsvParams(csvSep, directoryPath, _) => - if (!(csvSep.equals(";") || csvSep.equals(","))) + if !(csvSep.equals(";") || csvSep.equals(",")) then throw new InvalidConfigParameterException( s"The csvSep parameter '$csvSep' for '$csvParamsName' configuration is invalid! Please choose between ';' or ','!" ) - if ( - directoryPath.isEmpty || !new File(directoryPath) + if directoryPath.isEmpty || !new File(directoryPath) .exists() || new File(directoryPath).isFile - ) + then throw new InvalidConfigParameterException( s"The provided directoryPath for .csv-files '$directoryPath' for '$csvParamsName' configuration is invalid! Please correct the path!" ) @@ -303,14 +296,13 @@ object ConfigUtil { csvSep: String, folderPath: String ): Unit = { - if (!(csvSep.equals(";") || csvSep.equals(","))) + if !(csvSep.equals(";") || csvSep.equals(",")) then throw new InvalidConfigParameterException( s"The csvSep parameter '$csvSep' for '$csvParamsName' configuration is invalid! Please choose between ';' or ','!" ) - if ( - folderPath.isEmpty || !new File(folderPath) + if folderPath.isEmpty || !new File(folderPath) .exists() || new File(folderPath).isFile - ) + then throw new InvalidConfigParameterException( s"The provided folderPath for .csv-files '$folderPath' for '$csvParamsName' configuration is invalid! Please correct the path!" ) @@ -322,29 +314,29 @@ object ConfigUtil { def checkSqlParams( sql: edu.ie3.simona.config.SimonaConfig.Simona.Input.Weather.Datasource.SqlParams ): Unit = { - if (!sql.jdbcUrl.trim.startsWith("jdbc:")) { + if !sql.jdbcUrl.trim.startsWith("jdbc:") then { throw new InvalidConfigParameterException( s"The provided JDBC url '${sql.jdbcUrl}' is invalid! The url should start with 'jdbc:'" ) } - if (!sql.jdbcUrl.trim.startsWith("jdbc:postgresql://")) { + if !sql.jdbcUrl.trim.startsWith("jdbc:postgresql://") then { logger.warn( "It seems like you intend to use the SqlWeatherSource with an other dialect than PostgreSQL. Please be aware that this usage has neither been tested nor been considered in development." ) } - if (sql.userName.isEmpty) + if sql.userName.isEmpty then throw new InvalidConfigParameterException( "User name for SQL weather source cannot be empty" ) - if (sql.password.isEmpty) + if sql.password.isEmpty then logger.info( "Password for SQL weather source is empty. This is allowed, but not common. Please check if this an intended setting." ) - if (sql.tableName.isEmpty) + if sql.tableName.isEmpty then throw new InvalidConfigParameterException( "Weather table name for SQL weather source cannot be empty" ) - if (sql.schemaName.isEmpty) + if sql.schemaName.isEmpty then throw new InvalidConfigParameterException( "Schema name for SQL weather source cannot be empty" ) @@ -361,7 +353,7 @@ object ConfigUtil { case Success(connection) => val validConnection = connection.isValid(5000) connection.close() - if (!validConnection) + if !validConnection then throw new IllegalArgumentException( s"Unable to reach configured SQL database with url '${sql.jdbcUrl}' and user name '${sql.userName}'." ) @@ -375,27 +367,27 @@ object ConfigUtil { def checkCouchbaseParams( couchbase: edu.ie3.simona.config.SimonaConfig.Simona.Input.Weather.Datasource.CouchbaseParams ): Unit = { - if (couchbase.url.isEmpty) + if couchbase.url.isEmpty then throw new InvalidConfigParameterException( "URL for Couchbase weather source cannot be empty" ) - if (couchbase.userName.isEmpty) + if couchbase.userName.isEmpty then throw new InvalidConfigParameterException( "User name for Couchbase weather source cannot be empty" ) - if (couchbase.password.isEmpty) + if couchbase.password.isEmpty then throw new InvalidConfigParameterException( "Password for Couchbase weather source cannot be empty" ) - if (couchbase.bucketName.isEmpty) + if couchbase.bucketName.isEmpty then throw new InvalidConfigParameterException( "Bucket name for Couchbase weather source cannot be empty" ) - if (couchbase.coordinateColumnName.isEmpty) + if couchbase.coordinateColumnName.isEmpty then throw new InvalidConfigParameterException( "Coordinate column for Couchbase weather source cannot be empty" ) - if (couchbase.keyPrefix.isEmpty) + if couchbase.keyPrefix.isEmpty then throw new InvalidConfigParameterException( "Key prefix for Couchbase weather source cannot be empty" ) @@ -417,7 +409,7 @@ object ConfigUtil { case Success(connector) => val validConnection = connector.isConnectionValid connector.shutdown() - if (!validConnection) + if !validConnection then throw new IllegalArgumentException( s"Unable to reach configured Couchbase database with url '${couchbase.url}', bucket '${couchbase.bucketName}' and user name '${couchbase.userName}'" ) @@ -432,7 +424,7 @@ object ConfigUtil { influxDb1xParamsName: String, url: String, database: String - ): Unit = { + ): Unit = Try( new InfluxDbConnector(url, database).isConnectionValid ) match { @@ -450,15 +442,14 @@ object ConfigUtil { s"Successfully pinged influxDb1x with url '$url' for '$influxDb1xParamsName' configuration and s'$database'." ) } - } def checkKafkaParams( kafkaParams: KafkaParams, topics: Seq[String] ): Unit = { - try { + try UUID.fromString(kafkaParams.runId) - } catch { + catch { case e: IllegalArgumentException => throw new InvalidConfigParameterException( s"The UUID '${kafkaParams.runId}' cannot be parsed as it is invalid.", diff --git a/src/main/scala/edu/ie3/simona/util/EntityMapperUtil.scala b/src/main/scala/edu/ie3/simona/util/EntityMapperUtil.scala index a6e3398dcc..4d967477af 100644 --- a/src/main/scala/edu/ie3/simona/util/EntityMapperUtil.scala +++ b/src/main/scala/edu/ie3/simona/util/EntityMapperUtil.scala @@ -7,14 +7,14 @@ package edu.ie3.simona.util import edu.ie3.datamodel.models.result.ResultEntity -import edu.ie3.datamodel.models.result.system._ +import edu.ie3.datamodel.models.result.system.* import edu.ie3.datamodel.models.result.thermal.ThermalHouseResult import edu.ie3.simona.util.ConfigUtil.NotifierIdentifier -import edu.ie3.simona.util.ConfigUtil.NotifierIdentifier._ +import edu.ie3.simona.util.ConfigUtil.NotifierIdentifier.* case object EntityMapperUtil { private val entityMapping - : Map[NotifierIdentifier.Value, Class[_ <: ResultEntity]] = Map( + : Map[NotifierIdentifier.Value, Class[? <: ResultEntity]] = Map( PvPlant -> classOf[PvResult], Wec -> classOf[WecResult], Load -> classOf[LoadResult], @@ -38,7 +38,7 @@ case object EntityMapperUtil { */ def getResultEntityClass( notifierId: NotifierIdentifier.Value - ): Class[_ <: ResultEntity] = + ): Class[? <: ResultEntity] = entityMapping.getOrElse( notifierId, throw new NoSuchElementException( diff --git a/src/main/scala/edu/ie3/simona/util/ResultFileHierarchy.scala b/src/main/scala/edu/ie3/simona/util/ResultFileHierarchy.scala index 6f27310673..0ca281a326 100644 --- a/src/main/scala/edu/ie3/simona/util/ResultFileHierarchy.scala +++ b/src/main/scala/edu/ie3/simona/util/ResultFileHierarchy.scala @@ -9,7 +9,7 @@ package edu.ie3.simona.util import java.io.{BufferedWriter, File, FileWriter} import java.nio.file.{Files, Paths} import java.text.SimpleDateFormat -import com.typesafe.config.{ConfigRenderOptions, Config => TypesafeConfig} +import com.typesafe.config.{ConfigRenderOptions, Config as TypesafeConfig} import com.typesafe.scalalogging.LazyLogging import edu.ie3.datamodel.io.naming.{ EntityPersistenceNamingStrategy, @@ -22,7 +22,7 @@ import edu.ie3.simona.io.result.ResultSinkType.Csv import edu.ie3.simona.logging.logback.LogbackConfiguration import edu.ie3.simona.util.ResultFileHierarchy.ResultEntityPathConfig import edu.ie3.util.io.FileIOUtils -import org.apache.commons.io.FilenameUtils._ +import org.apache.commons.io.FilenameUtils.* import scala.jdk.OptionConverters.RichOptional @@ -62,10 +62,10 @@ final case class ResultFileHierarchy( val resultSinkType: ResultSinkType = resultEntityPathConfig.resultSinkType - val resultEntitiesToConsider: Set[Class[_ <: ResultEntity]] = + val resultEntitiesToConsider: Set[Class[? <: ResultEntity]] = resultEntityPathConfig.resultEntitiesToConsider - val rawOutputDataFilePaths: Map[Class[_ <: ResultEntity], String] = { + val rawOutputDataFilePaths: Map[Class[? <: ResultEntity], String] = resultSinkType match { case csv: Csv => resultEntityPathConfig.resultEntitiesToConsider @@ -84,7 +84,6 @@ final case class ResultFileHierarchy( case _ => Map.empty } - } val graphOutputDir: String = runOutputDir.concat(fileSeparator).concat("graphs") @@ -105,8 +104,7 @@ final case class ResultFileHierarchy( ) // needs to be the latest call because otherwise the values are null as they are not initialized yet - if (createDirs) - ResultFileHierarchy.createOutputDirectories(this) + if createDirs then ResultFileHierarchy.createOutputDirectories(this) // needs to be done after dir creation configureLogger(logOutputDir) @@ -134,7 +132,7 @@ final case class ResultFileHierarchy( */ private def buildRunOutputDir: String = { val optionalSuffix = - if (addTimeStampToOutputDir) s"_$runStartTimeUTC" else "" + if addTimeStampToOutputDir then s"_$runStartTimeUTC" else "" baseOutputDir .concat(fileSeparator) .concat(simulationName) @@ -151,7 +149,7 @@ object ResultFileHierarchy extends LazyLogging { * the type of the sink where result entities should be persisted */ final case class ResultEntityPathConfig( - resultEntitiesToConsider: Set[Class[_ <: ResultEntity]], + resultEntitiesToConsider: Set[Class[? <: ResultEntity]], resultSinkType: ResultSinkType ) @@ -168,14 +166,13 @@ object ResultFileHierarchy extends LazyLogging { * name + extension */ private def buildRawOutputFilePath( - modelClass: Class[_ <: ResultEntity], + modelClass: Class[? <: ResultEntity], csvSink: Csv, rawOutputDataDir: String, fileSeparator: String ): String = { val fileEnding = - if (csvSink.fileFormat.startsWith(".")) - csvSink.fileFormat + if csvSink.fileFormat.startsWith(".") then csvSink.fileFormat else ".".concat(csvSink.fileFormat) val namingStrategy = new FileNamingStrategy( new EntityPersistenceNamingStrategy( @@ -212,7 +209,7 @@ object ResultFileHierarchy extends LazyLogging { resultFileHierarchy: ResultFileHierarchy ): Unit = { // create output directories if they are not present yet - if (!runOutputDirExists(resultFileHierarchy)) + if !runOutputDirExists(resultFileHierarchy) then ResultFileHierarchy.createOutputDirectories(resultFileHierarchy) logger.info( @@ -246,11 +243,10 @@ object ResultFileHierarchy extends LazyLogging { * @return * true if it exists, false if not */ - def runOutputDirExists(outputFileHierarchy: ResultFileHierarchy): Boolean = { + def runOutputDirExists(outputFileHierarchy: ResultFileHierarchy): Boolean = new File(outputFileHierarchy.runOutputDir).exists() && new File( outputFileHierarchy.runOutputDir ).listFiles().length > 0 - } /** Creates all output directories of the provided [[ResultFileHierarchy]] * @@ -263,7 +259,7 @@ object ResultFileHierarchy extends LazyLogging { // try to create base output dir val baseOutputDir = Paths.get(outputFileHierarchy.baseOutputDir) // / check for existence of the provided baseOutputDir, if not create it - if (Files.exists(baseOutputDir) && baseOutputDir.toFile.isFile) { + if Files.exists(baseOutputDir) && baseOutputDir.toFile.isFile then { throw new FileHierarchyException( s"Provided base output path $baseOutputDir is a file and cannot be replaced with a directory!" ) @@ -271,7 +267,7 @@ object ResultFileHierarchy extends LazyLogging { // check if there is data inside the runOutputDir taking into account the provided FileHandling val runOutputDir = new File(outputFileHierarchy.runOutputDir) - if (runOutputDir.exists() && runOutputDir.listFiles().length > 0) { + if runOutputDir.exists() && runOutputDir.listFiles().length > 0 then { // files inside the runOutputDir -> fail throw new FileHierarchyException( s"The runOutputDir ${outputFileHierarchy.runOutputDir} already exists and is NOT empty! " + @@ -291,7 +287,7 @@ object ResultFileHierarchy extends LazyLogging { */ private def createDir(dir: String): Unit = { val dirFile = new File(dir) - if (!dirFile.mkdirs() && !dirFile.exists()) + if !dirFile.mkdirs() && !dirFile.exists() then throw new FileHierarchyException( "The output directory path " + dir + " could not be created. Check pathname and permissions! Full path: " + dirFile.getAbsolutePath @@ -303,8 +299,7 @@ object ResultFileHierarchy extends LazyLogging { * @param outputFileHierarchy * the [[ResultFileHierarchy]] which temp folder should be deleted */ - def deleteTmpDir(outputFileHierarchy: ResultFileHierarchy): Unit = { + def deleteTmpDir(outputFileHierarchy: ResultFileHierarchy): Unit = FileIOUtils.deleteRecursively(outputFileHierarchy.tmpDir) - } } diff --git a/src/main/scala/edu/ie3/simona/util/TickUtil.scala b/src/main/scala/edu/ie3/simona/util/TickUtil.scala index c95fc3b987..fe1e47e27c 100644 --- a/src/main/scala/edu/ie3/simona/util/TickUtil.scala +++ b/src/main/scala/edu/ie3/simona/util/TickUtil.scala @@ -18,25 +18,16 @@ import java.time.temporal.ChronoUnit */ object TickUtil { - /** Provides conversions from ZonedDateTime into ticks (actually seconds) */ - implicit class RichZonedDateTime(private val zdt: ZonedDateTime) - extends AnyVal { - - /** Calculates the difference between this date time and the provided date - * time in ticks (= actual seconds) - */ - def toTick(implicit startDateTime: ZonedDateTime): Long = - ChronoUnit.SECONDS.between(startDateTime, zdt) - - } - - /** Provides conversions from ticks (seconds) into instances of - * [[ZonedDateTime]] + /** Calculates the difference between this date time and the provided date + * time in ticks (= actual seconds) */ - implicit class TickLong(private val tick: Long) extends AnyVal { + extension (zdt: ZonedDateTime) + def toTick(using startDateTime: ZonedDateTime): Long = + ChronoUnit.SECONDS.between(startDateTime, zdt) - /** Calculates the current [[ZonedDateTime]] based on this tick */ - def toDateTime(implicit startDateTime: ZonedDateTime): ZonedDateTime = + /** Calculates the current [[ZonedDateTime]] based on this tick */ + extension (tick: Long) + def toDateTime(using startDateTime: ZonedDateTime): ZonedDateTime = startDateTime.plusSeconds(tick) /** Calculates time spam of given time bin resolution */ @@ -50,8 +41,6 @@ object TickUtil { ): Time = tickDuration * (otherTick - tick).toDouble - } - /** Determine an Array with all ticks between the request frame's start and * end according to the data resolution * @@ -65,7 +54,7 @@ object TickUtil { * Array with data ticks */ def getTicksInBetween(frameStart: Long, frameEnd: Long, resolution: Long)( - implicit startDateTime: ZonedDateTime + using startDateTime: ZonedDateTime ): Array[Long] = { val firstFullHourTick = TimeUtil .toNextFull(frameStart.toDateTime, ChronoUnit.HOURS) diff --git a/src/main/scala/edu/ie3/util/scala/ReflectionTools.scala b/src/main/scala/edu/ie3/util/scala/ReflectionTools.scala index d37280e16d..565e847f8a 100644 --- a/src/main/scala/edu/ie3/util/scala/ReflectionTools.scala +++ b/src/main/scala/edu/ie3/util/scala/ReflectionTools.scala @@ -52,7 +52,7 @@ object ReflectionTools { * @return * a map containing the field method and it's value of the object instance */ - def classFieldToVal[A](a: A)(implicit + def classFieldToVal[A](a: A)(using tt: TypeTag[A], ct: ClassTag[A] ): Map[universe.MethodSymbol, Any] = { diff --git a/src/main/scala/edu/ie3/util/scala/collection/immutable/SortedDistinctSeq.scala b/src/main/scala/edu/ie3/util/scala/collection/immutable/SortedDistinctSeq.scala index be8aa89b47..1aaaa2f1f4 100644 --- a/src/main/scala/edu/ie3/util/scala/collection/immutable/SortedDistinctSeq.scala +++ b/src/main/scala/edu/ie3/util/scala/collection/immutable/SortedDistinctSeq.scala @@ -40,7 +40,7 @@ final case class SortedDistinctSeq[V] private ( case object SortedDistinctSeq { def apply[V]( entries: Seq[V] - )(implicit ord: Ordering[V]): SortedDistinctSeq[V] = + )(using ord: Ordering[V]): SortedDistinctSeq[V] = new SortedDistinctSeq(entries.toIndexedSeq.distinct.sorted) def empty[V] = new SortedDistinctSeq[V](IndexedSeq.empty[V]) diff --git a/src/main/scala/edu/ie3/util/scala/collection/mutable/PriorityMultiBiSet.scala b/src/main/scala/edu/ie3/util/scala/collection/mutable/PriorityMultiBiSet.scala index e224b43314..c5b906017d 100644 --- a/src/main/scala/edu/ie3/util/scala/collection/mutable/PriorityMultiBiSet.scala +++ b/src/main/scala/edu/ie3/util/scala/collection/mutable/PriorityMultiBiSet.scala @@ -94,7 +94,7 @@ final case class PriorityMultiBiSet[K, V] private ( table.get(key).exists { set => val existed = set.remove(value) - if (set.isEmpty) { + if set.isEmpty then { table -= key queue -= key } @@ -112,7 +112,7 @@ final case class PriorityMultiBiSet[K, V] private ( * @return * The first element in the list of the first key */ - def getAndRemoveSet(key: K): Set[V] = { + def getAndRemoveSet(key: K): Set[V] = table .get(key) .map { set => @@ -128,7 +128,6 @@ final case class PriorityMultiBiSet[K, V] private ( immutableSet } .getOrElse(Set.empty) - } /** Tests whether there is no value for any key in the queue. * @return diff --git a/src/main/scala/edu/ie3/util/scala/io/CsvDataSourceAdapter.java b/src/main/scala/edu/ie3/util/scala/io/CsvDataSourceAdapter.java deleted file mode 100644 index 16ea4883b6..0000000000 --- a/src/main/scala/edu/ie3/util/scala/io/CsvDataSourceAdapter.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * © 2023. TU Dortmund University, - * Institute of Energy Systems, Energy Efficiency and Energy Economics, - * Research group Distribution grid planning and operation - */ - -package edu.ie3.util.scala.io; - -import edu.ie3.datamodel.io.naming.FileNamingStrategy; -import edu.ie3.datamodel.io.source.csv.CsvDataSource; -import java.nio.file.Path; - -public class CsvDataSourceAdapter extends CsvDataSource { - - public CsvDataSourceAdapter( - String csvSep, Path folderPath, FileNamingStrategy fileNamingStrategy) { - super(csvSep, folderPath, fileNamingStrategy); - } -} diff --git a/src/main/scala/edu/ie3/util/scala/io/GraphicDataCleaner.scala b/src/main/scala/edu/ie3/util/scala/io/GraphicDataCleaner.scala index 7737599d18..e4a66cbf5c 100644 --- a/src/main/scala/edu/ie3/util/scala/io/GraphicDataCleaner.scala +++ b/src/main/scala/edu/ie3/util/scala/io/GraphicDataCleaner.scala @@ -31,7 +31,7 @@ object GraphicDataCleaner { /* setup */ val dataSource: CsvDataSource = - new CsvDataSourceAdapter(csvSep, baseFolder, fileNamingStrategy) + new CsvDataSource(csvSep, baseFolder, fileNamingStrategy) val csvTypeSource: TypeSource = new TypeSource(dataSource) diff --git a/src/main/scala/edu/ie3/util/scala/io/ScalaReflectionSerde.scala b/src/main/scala/edu/ie3/util/scala/io/ScalaReflectionSerde.scala index e129c8dff6..8309207598 100644 --- a/src/main/scala/edu/ie3/util/scala/io/ScalaReflectionSerde.scala +++ b/src/main/scala/edu/ie3/util/scala/io/ScalaReflectionSerde.scala @@ -23,15 +23,13 @@ object ScalaReflectionSerde { val inner = new GenericAvroSerializer() override def configure( - configs: java.util.Map[String, _], + configs: java.util.Map[String, ?], isKey: Boolean ): Unit = inner.configure(configs, isKey) override def serialize(topic: String, maybeData: T): Array[Byte] = Option(maybeData) - .map(data => - inner.serialize(topic, implicitly[RecordFormat[T]].to(data)) - ) + .map(data => inner.serialize(topic, summon[RecordFormat[T]].to(data))) .getOrElse(Array.emptyByteArray) override def close(): Unit = inner.close() @@ -42,7 +40,7 @@ object ScalaReflectionSerde { val inner = new GenericAvroDeserializer() override def configure( - configs: java.util.Map[String, _], + configs: java.util.Map[String, ?], isKey: Boolean ): Unit = inner.configure(configs, isKey) @@ -50,7 +48,7 @@ object ScalaReflectionSerde { Option(maybeData) .filter(_.nonEmpty) .map(data => - implicitly[RecordFormat[T]].from(inner.deserialize(topic, data)) + summon[RecordFormat[T]].from(inner.deserialize(topic, data)) ) .getOrElse(null.asInstanceOf[T]) diff --git a/src/main/scala/edu/ie3/util/scala/quantities/EnergyDensity.scala b/src/main/scala/edu/ie3/util/scala/quantities/EnergyDensity.scala index 56806ea8da..596b9ea20d 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/EnergyDensity.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/EnergyDensity.scala @@ -6,7 +6,7 @@ package edu.ie3.util.scala.quantities -import squants._ +import squants.* import squants.energy.{KilowattHours, WattHours} import squants.space.CubicMeters @@ -34,7 +34,7 @@ final class EnergyDensity private ( } object EnergyDensity extends Dimension[EnergyDensity] { - def apply[A](n: A, unit: EnergyDensityUnit)(implicit num: Numeric[A]) = + def apply[A](n: A, unit: EnergyDensityUnit)(using num: Numeric[A]) = new EnergyDensity(num.toDouble(n), unit) def apply(value: Any): Try[EnergyDensity] = parse(value) def name = "EnergyDensity" @@ -46,7 +46,7 @@ object EnergyDensity extends Dimension[EnergyDensity] { trait EnergyDensityUnit extends UnitOfMeasure[EnergyDensity] with UnitConverter { - def apply[A](n: A)(implicit num: Numeric[A]): EnergyDensity = + def apply[A](n: A)(using num: Numeric[A]): EnergyDensity = EnergyDensity(n, this) } diff --git a/src/main/scala/edu/ie3/util/scala/quantities/EnergyPrice.scala b/src/main/scala/edu/ie3/util/scala/quantities/EnergyPrice.scala index 96a32d408a..7487e2ae10 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/EnergyPrice.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/EnergyPrice.scala @@ -31,7 +31,7 @@ final class EnergyPrice private ( } object EnergyPrice extends Dimension[EnergyPrice] { - def apply[A](n: A, unit: EnergyPriceUnit)(implicit num: Numeric[A]) = + def apply[A](n: A, unit: EnergyPriceUnit)(using num: Numeric[A]) = new EnergyPrice(num.toDouble(n), unit) def apply(value: Any): Try[EnergyPrice] = parse(value) def name = "EnergyPrice" @@ -43,7 +43,7 @@ object EnergyPrice extends Dimension[EnergyPrice] { } trait EnergyPriceUnit extends UnitOfMeasure[EnergyPrice] with UnitConverter { - def apply[A](n: A)(implicit num: Numeric[A]): EnergyPrice = + def apply[A](n: A)(using num: Numeric[A]): EnergyPrice = EnergyPrice(n, this) } diff --git a/src/main/scala/edu/ie3/util/scala/quantities/Irradiance.scala b/src/main/scala/edu/ie3/util/scala/quantities/Irradiance.scala index 2ad522980e..82dd09c6d7 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/Irradiance.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/Irradiance.scala @@ -6,7 +6,7 @@ package edu.ie3.util.scala.quantities -import squants._ +import squants.* import squants.energy.{WattHours, Watts} import squants.radio.{AreaTime, BecquerelsPerSquareMeterSecond, ParticleFlux} import squants.space.SquareMeters @@ -54,7 +54,7 @@ final class Irradiance private (val value: Double, val unit: IrradianceUnit) } object Irradiance extends Dimension[Irradiance] { - def apply[A](n: A, unit: IrradianceUnit)(implicit num: Numeric[A]) = + def apply[A](n: A, unit: IrradianceUnit)(using num: Numeric[A]) = new Irradiance(num.toDouble(n), unit) def apply(value: Any): Try[Irradiance] = parse(value) def name = "Irradiance" @@ -64,7 +64,7 @@ object Irradiance extends Dimension[Irradiance] { } trait IrradianceUnit extends UnitOfMeasure[Irradiance] with UnitConverter { - def apply[A](n: A)(implicit num: Numeric[A]): Irradiance = Irradiance(n, this) + def apply[A](n: A)(using num: Numeric[A]): Irradiance = Irradiance(n, this) } object WattsPerSquareMeter extends IrradianceUnit with PrimaryUnit with SiUnit { @@ -74,10 +74,9 @@ object WattsPerSquareMeter extends IrradianceUnit with PrimaryUnit with SiUnit { object IrradianceConversions { lazy val wattPerSquareMeter: Irradiance = WattsPerSquareMeter(1) - implicit class IrradianceConversions[A](n: A)(implicit num: Numeric[A]) { - def wattsPerSquareMeter: Irradiance = WattsPerSquareMeter(n) - - } + given wattsPerSquareMeter[A](using + num: Numeric[A] + ): Conversion[A, Irradiance] = WattsPerSquareMeter(_) implicit object IrradianceNumeric extends AbstractQuantityNumeric[Irradiance](Irradiance.primaryUnit) diff --git a/src/main/scala/edu/ie3/util/scala/quantities/Irradiation.scala b/src/main/scala/edu/ie3/util/scala/quantities/Irradiation.scala index 5b685fde7e..bcd1b7940e 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/Irradiation.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/Irradiation.scala @@ -6,7 +6,7 @@ package edu.ie3.util.scala.quantities -import squants._ +import squants.* import squants.energy.WattHours import squants.space.SquareMeters @@ -33,7 +33,7 @@ final class Irradiation private (val value: Double, val unit: IrradiationUnit) } object Irradiation extends Dimension[Irradiation] { - def apply[A](n: A, unit: IrradiationUnit)(implicit num: Numeric[A]) = + def apply[A](n: A, unit: IrradiationUnit)(using num: Numeric[A]) = new Irradiation(num.toDouble(n), unit) def apply(value: Any): Try[Irradiation] = parse(value) def name = "Irradiation" @@ -43,7 +43,7 @@ object Irradiation extends Dimension[Irradiation] { } trait IrradiationUnit extends UnitOfMeasure[Irradiation] with UnitConverter { - def apply[A](n: A)(implicit num: Numeric[A]): Irradiation = + def apply[A](n: A)(using num: Numeric[A]): Irradiation = Irradiation(n, this) } @@ -57,9 +57,9 @@ object WattHoursPerSquareMeter object IrradiationConversions { lazy val wattHoursPerSquareMeter: Irradiation = WattHoursPerSquareMeter(1) - implicit class IrradiationConversions[A](n: A)(implicit num: Numeric[A]) { - def wattHoursPerSquareMeter: Irradiation = WattHoursPerSquareMeter(n) - } + def wattHoursPerSquareMeter[A](using + num: Numeric[A] + ): Conversion[A, Irradiation] = WattHoursPerSquareMeter(_) implicit object IrradiationNumeric extends AbstractQuantityNumeric[Irradiation](Irradiation.primaryUnit) diff --git a/src/main/scala/edu/ie3/util/scala/quantities/QuantityUtil.scala b/src/main/scala/edu/ie3/util/scala/quantities/QuantityUtil.scala index d5aea08fdd..023c58aea5 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/QuantityUtil.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/QuantityUtil.scala @@ -7,7 +7,7 @@ package edu.ie3.util.scala.quantities import edu.ie3.simona.exceptions.QuantityException -import edu.ie3.util.quantities.{QuantityUtil => PSQuantityUtil} +import edu.ie3.util.quantities.QuantityUtil as PSQuantityUtil import squants.time.{Hours, TimeDerivative, TimeIntegral} import squants.{Quantity, Seconds, UnitOfMeasure} import tech.units.indriya.ComparableQuantity @@ -62,12 +62,12 @@ object QuantityUtil { values: Map[Long, Q], windowStart: Long, windowEnd: Long - ): Try[Q] = { - if (windowStart == windowEnd) + ): Try[Q] = + if windowStart == windowEnd then Failure( new IllegalArgumentException("Cannot average over trivial time window.") ) - else if (windowStart > windowEnd) + else if windowStart > windowEnd then Failure( new IllegalArgumentException("Window end is before window start.") ) @@ -79,7 +79,6 @@ object QuantityUtil { windowEnd ) / Seconds(windowEnd - windowStart) } - } /** Calculate the integration over provided values from window start until * window end @@ -125,15 +124,17 @@ object QuantityUtil { val (lastTick, lastValue) = endingValue(values, windowEnd) val valuesWithinWindow = mutable.LinkedHashMap.newBuilder .addAll( - (values filter { case (tick, _) => - tick >= windowStart && tick <= windowEnd - }).toSeq + values + .filter { case (tick, _) => + tick >= windowStart && tick <= windowEnd + } + .toSeq .sortBy(_._1) ) .result() /* We need a value at the window end, so if the last value is not exactly there, replicate it at that point */ - if (windowEnd > lastTick) + if windowEnd > lastTick then valuesWithinWindow.addOne(windowEnd -> lastValue) /* Actually determining the integral, but sweeping over values and summing up everything */ @@ -173,7 +174,7 @@ object QuantityUtil { private def startingValue[Q <: squants.Quantity[Q]]( values: Map[Long, Q], windowStart: Long - ): Q = { + ): Q = values .filter { case (tick, _) => tick <= windowStart @@ -190,7 +191,6 @@ object QuantityUtil { ) unit(0d) } - } /** Determine the last value for the integration * @@ -207,7 +207,7 @@ object QuantityUtil { private def endingValue[Q <: Quantity[Q]]( values: Map[Long, Q], windowEnd: Long - ): (Long, Q) = { + ): (Long, Q) = values .filter { case (tick, _) => tick <= windowEnd @@ -219,6 +219,5 @@ object QuantityUtil { "Cannot integrate over an empty set of values." ) } - } } diff --git a/src/main/scala/edu/ie3/util/scala/quantities/ReactivePower.scala b/src/main/scala/edu/ie3/util/scala/quantities/ReactivePower.scala index 02458bcd89..66368ce667 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/ReactivePower.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/ReactivePower.scala @@ -6,9 +6,9 @@ package edu.ie3.util.scala.quantities -import squants.energy._ +import squants.energy.* import squants.time.{Hours, Time, TimeDerivative, TimeIntegral} -import squants._ +import squants.* import scala.util.Try @@ -41,7 +41,7 @@ final class ReactivePower private ( } object ReactivePower extends Dimension[ReactivePower] { - private[quantities] def apply[A](n: A, unit: ReactivePowerUnit)(implicit + private[quantities] def apply[A](n: A, unit: ReactivePowerUnit)(using num: Numeric[A] ) = new ReactivePower(num.toDouble(n), unit) def apply(energy: Energy, time: Time): ReactivePower = @@ -58,7 +58,7 @@ object ReactivePower extends Dimension[ReactivePower] { trait ReactivePowerUnit extends UnitOfMeasure[ReactivePower] with UnitConverter { - def apply[A](n: A)(implicit num: Numeric[A]): ReactivePower = + def apply[A](n: A)(using num: Numeric[A]): ReactivePower = ReactivePower(n, this) } diff --git a/src/main/scala/edu/ie3/util/scala/quantities/ScalaNumberSystem.scala b/src/main/scala/edu/ie3/util/scala/quantities/ScalaNumberSystem.scala index 8b4f5e1eb3..2e662b7628 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/ScalaNumberSystem.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/ScalaNumberSystem.scala @@ -36,9 +36,9 @@ final class ScalaNumberSystem extends DefaultNumberSystem { val sign = signX * signY // handle corner cases when x or y are zero - if (sign == 0) { - if (signY == 0) throw new ArithmeticException("division by zero") - if (signX == 0) Array[Number](0, 0) + if sign == 0 then { + if signY == 0 then throw new ArithmeticException("division by zero") + if signX == 0 then Array[Number](0, 0) } val div = x.doubleValue / y.intValue() @@ -47,15 +47,14 @@ final class ScalaNumberSystem extends DefaultNumberSystem { Array(div, remainder) } - override def power(number: Number, exponent: Int): Number = { + override def power(number: Number, exponent: Int): Number = Math.pow(number.doubleValue, exponent) - } override def reciprocal(number: Number): Number = divide(1d, number) override def negate(number: Number): Number = - number.doubleValue * (-1d) + number.doubleValue * -1d override def signum(number: Number): Int = Math.signum(number.doubleValue).intValue diff --git a/src/main/scala/edu/ie3/util/scala/quantities/SpecificHeatCapacity.scala b/src/main/scala/edu/ie3/util/scala/quantities/SpecificHeatCapacity.scala index a9e2c24011..0a6f1c0895 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/SpecificHeatCapacity.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/SpecificHeatCapacity.scala @@ -6,7 +6,7 @@ package edu.ie3.util.scala.quantities -import squants._ +import squants.* import squants.energy.KilowattHours import scala.util.Try @@ -73,7 +73,7 @@ final class SpecificHeatCapacity private ( } object SpecificHeatCapacity extends Dimension[SpecificHeatCapacity] { - def apply[A](n: A, unit: SpecificHeatCapacityUnit)(implicit num: Numeric[A]) = + def apply[A](n: A, unit: SpecificHeatCapacityUnit)(using num: Numeric[A]) = new SpecificHeatCapacity(num.toDouble(n), unit) def apply(value: Any): Try[SpecificHeatCapacity] = parse(value) def name = "SpecificHeatCapacity" @@ -89,7 +89,7 @@ object SpecificHeatCapacity extends Dimension[SpecificHeatCapacity] { trait SpecificHeatCapacityUnit extends UnitOfMeasure[SpecificHeatCapacity] with UnitConverter { - def apply[A](n: A)(implicit num: Numeric[A]): SpecificHeatCapacity = + def apply[A](n: A)(using num: Numeric[A]): SpecificHeatCapacity = SpecificHeatCapacity(n, this) } diff --git a/src/main/scala/edu/ie3/util/scala/quantities/Sq.scala b/src/main/scala/edu/ie3/util/scala/quantities/Sq.scala index ef763ef4c6..1d8ad94429 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/Sq.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/Sq.scala @@ -10,12 +10,11 @@ import squants.{Quantity, UnitOfMeasure} object Sq { - def create[A <: Quantity[A]](num: Number, unit: UnitOfMeasure[A]): A = { + def create[A <: Quantity[A]](num: Number, unit: UnitOfMeasure[A]): A = num match { case d: java.lang.Double => unit.apply(d.doubleValue()) case i: java.lang.Integer => unit.apply(i.intValue()) } - } } diff --git a/src/main/scala/edu/ie3/util/scala/quantities/SquantsUtils.scala b/src/main/scala/edu/ie3/util/scala/quantities/SquantsUtils.scala index 13dc0c0908..5359f98742 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/SquantsUtils.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/SquantsUtils.scala @@ -12,26 +12,22 @@ import squants.energy.Energy import squants.space.{CubicMeters, Volume} object SquantsUtils { - implicit class RichEnergy(energy: Energy) { + + extension (energy: Energy) def calcVolume(that: EnergyDensity): Volume = CubicMeters( energy.toKilowattHours / that.toKilowattHoursPerCubicMeter ) - } - implicit class RichPower(power: squants.Power) { + + extension (power: squants.Power) def /(that: ReactivePower): squants.Dimensionless = Each( power.toWatts / that.toVars ) - } - implicit class RichElectricPotential( - electricPotential: squants.electro.ElectricPotential - ) { + extension (electricPotential: squants.electro.ElectricPotential) def multiplyWithDimensionles( that: squants.Dimensionless ): squants.electro.ElectricPotential = Volts( electricPotential.toVolts * that.toEach ) - } - } diff --git a/src/main/scala/edu/ie3/util/scala/quantities/ThermalConductance.scala b/src/main/scala/edu/ie3/util/scala/quantities/ThermalConductance.scala index 1d26ec1f35..58e1c958a4 100644 --- a/src/main/scala/edu/ie3/util/scala/quantities/ThermalConductance.scala +++ b/src/main/scala/edu/ie3/util/scala/quantities/ThermalConductance.scala @@ -6,7 +6,7 @@ package edu.ie3.util.scala.quantities -import squants._ +import squants.* import squants.energy.{WattHours, Watts} import scala.util.Try @@ -45,7 +45,7 @@ final class ThermalConductance private ( } object ThermalConductance extends Dimension[ThermalConductance] { - def apply[A](n: A, unit: ThermalConductanceUnit)(implicit num: Numeric[A]) = + def apply[A](n: A, unit: ThermalConductanceUnit)(using num: Numeric[A]) = new ThermalConductance(num.toDouble(n), unit) def apply(value: Any): Try[ThermalConductance] = parse(value) def name = "ThermalConductance" @@ -59,7 +59,7 @@ object ThermalConductance extends Dimension[ThermalConductance] { trait ThermalConductanceUnit extends UnitOfMeasure[ThermalConductance] with UnitConverter { - def apply[A](n: A)(implicit num: Numeric[A]): ThermalConductance = + def apply[A](n: A)(using num: Numeric[A]): ThermalConductance = ThermalConductance(n, this) } diff --git a/src/test/scala/edu/ie3/simona/agent/ValueStoreSpec.scala b/src/test/scala/edu/ie3/simona/agent/ValueStoreSpec.scala index 546a123bd6..2a2430ea78 100644 --- a/src/test/scala/edu/ie3/simona/agent/ValueStoreSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/ValueStoreSpec.scala @@ -16,7 +16,7 @@ class ValueStoreSpec extends UnitSpec with PrivateMethodTester { "be properly instantiated" in { val storeGetter = PrivateMethod[Map[Long, String]](Symbol("store")) - (emptyValueStore invokePrivate storeGetter()) shouldBe Map + emptyValueStore.invokePrivate(storeGetter()) shouldBe Map .empty[Long, String] emptyValueStore.maxTickSpan shouldBe Long.MaxValue } @@ -48,7 +48,7 @@ class ValueStoreSpec extends UnitSpec with PrivateMethodTester { "be properly instantiated" in { val storeGetter = PrivateMethod[Map[Long, String]](Symbol("store")) - (filledValueStore invokePrivate storeGetter()) shouldBe Map( + filledValueStore.invokePrivate(storeGetter()) shouldBe Map( 1L -> "One", 2L -> "Two", 3L -> "Three", @@ -81,7 +81,7 @@ class ValueStoreSpec extends UnitSpec with PrivateMethodTester { val updatedOnceAgain = ValueStore.updateValueStore(updated, 6L, "Six") val storeGetter = PrivateMethod[Map[Long, String]](Symbol("store")) - (updatedOnceAgain invokePrivate storeGetter()) shouldBe Map( + updatedOnceAgain.invokePrivate(storeGetter()) shouldBe Map( 2L -> "Two", 3L -> "Three", 4L -> "Four", diff --git a/src/test/scala/edu/ie3/simona/agent/grid/DBFSAlgorithmSupGridSpec.scala b/src/test/scala/edu/ie3/simona/agent/grid/DBFSAlgorithmSupGridSpec.scala index ca8687a44b..c51d89217c 100644 --- a/src/test/scala/edu/ie3/simona/agent/grid/DBFSAlgorithmSupGridSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/grid/DBFSAlgorithmSupGridSpec.scala @@ -133,7 +133,7 @@ class DBFSAlgorithmSupGridSpec s"start the simulation, do 2 sweeps and should end afterwards when no deviation on nodal " + s"power is recognized in the superior when an activation is sent is send" in { - for (sweepNo <- 0 to 1) { + for sweepNo <- 0 to 1 do { val requestedConnectionNodeUuids = Vector(UUID.fromString("9fe5fa33-6d3b-4153-a829-a16f4347bc4e")) @@ -248,7 +248,7 @@ class DBFSAlgorithmSupGridSpec ) // go on with testing the sweep behaviour - for (sweepNo <- 0 to maxNumberOfTestSweeps) { + for sweepNo <- 0 to maxNumberOfTestSweeps do { val requestedConnectionNodeUuids = Vector(UUID.fromString("9fe5fa33-6d3b-4153-a829-a16f4347bc4e")) diff --git a/src/test/scala/edu/ie3/simona/agent/grid/DBFSMockGridAgents.scala b/src/test/scala/edu/ie3/simona/agent/grid/DBFSMockGridAgents.scala index 0f19e2055d..e343103f8d 100644 --- a/src/test/scala/edu/ie3/simona/agent/grid/DBFSMockGridAgents.scala +++ b/src/test/scala/edu/ie3/simona/agent/grid/DBFSMockGridAgents.scala @@ -34,10 +34,11 @@ import scala.language.postfixOps */ trait DBFSMockGridAgents extends UnitSpec { private val floatPrecision: Double = 0.00000000001 - private implicit val powerTolerance: Power = Megawatts(1e-10) - private implicit val reactivePowerTolerance: ReactivePower = Megavars(1e-10) - private implicit val electricPotentialTolerance - : squants.electro.ElectricPotential = Volts(1e-6) + given powerTolerance: Power = Megawatts(1e-10) + given reactivePowerTolerance: ReactivePower = Megavars(1e-10) + given electricPotentialTolerance: squants.electro.ElectricPotential = Volts( + 1e-6 + ) sealed trait GAActorAndModel { val gaProbe: TestProbe @@ -62,7 +63,7 @@ trait DBFSMockGridAgents extends UnitSpec { def expectSlackVoltageProvision( expectedSweepNo: Int, expectedExchangedVoltages: Seq[ExchangeVoltage] - ): Unit = { + ): Unit = inside(gaProbe.expectMsgType[ProvideSlackVoltageMessage]) { case ProvideSlackVoltageMessage(sweepNo, exchangedVoltages) => sweepNo shouldBe expectedSweepNo @@ -83,7 +84,6 @@ trait DBFSMockGridAgents extends UnitSpec { } } } - } def requestSlackVoltage(receiver: ActorRef, sweepNo: Int): Unit = gaProbe.send( @@ -114,7 +114,7 @@ trait DBFSMockGridAgents extends UnitSpec { def expectGridPowerProvision( expectedExchangedPowers: Seq[ExchangePower], maxDuration: FiniteDuration = 30 seconds - ): Unit = { + ): Unit = inside(gaProbe.expectMsgType[ProvideGridPowerMessage](maxDuration)) { case ProvideGridPowerMessage(exchangedPower) => exchangedPower should have size expectedExchangedPowers.size @@ -133,9 +133,8 @@ trait DBFSMockGridAgents extends UnitSpec { } } - } - def requestGridPower(receiver: ActorRef, sweepNo: Int): Unit = { + def requestGridPower(receiver: ActorRef, sweepNo: Int): Unit = gaProbe.send( receiver, RequestGridPowerMessage( @@ -143,6 +142,5 @@ trait DBFSMockGridAgents extends UnitSpec { nodeUuids ) ) - } } } diff --git a/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup2WSpec.scala b/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup2WSpec.scala index e58ad3c2fb..115c38992b 100644 --- a/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup2WSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup2WSpec.scala @@ -52,8 +52,8 @@ class GridAgentSetup2WSpec "The setup of grid agents" must { "provide two grid agents on presence of a two winding transformer" in { - import org.apache.pekko.pattern._ - implicit val timeout: Timeout = Timeout(1, TimeUnit.SECONDS) + import org.apache.pekko.pattern.* + given timeout: Timeout = Timeout(1, TimeUnit.SECONDS) // in order to get an actor system we need a tmp actor that calls the corresponding method Await.ready( @@ -73,7 +73,7 @@ class GridAgentSetup2WSpec "test/tmp", "GridAgentSetup2WSpec", ResultEntityPathConfig( - Set.empty[Class[_ <: ResultEntity]], + Set.empty[Class[? <: ResultEntity]], ResultSinkType( simonaConfig.simona.output.sink, simonaConfig.simona.simulationName diff --git a/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup3WSpec.scala b/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup3WSpec.scala index f2b2d44f41..95bae01fae 100644 --- a/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup3WSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/grid/GridAgentSetup3WSpec.scala @@ -54,8 +54,8 @@ class GridAgentSetup3WSpec "The setup of grid agents" must { "provide three grid agents on presence of a three winding transformer" in { - import org.apache.pekko.pattern._ - implicit val timeout: Timeout = Timeout(1, TimeUnit.SECONDS) + import org.apache.pekko.pattern.* + given timeout: Timeout = Timeout(1, TimeUnit.SECONDS) // in order to get an actor system we need a tmp actor that calls the corresponding method Await.ready( @@ -75,7 +75,7 @@ class GridAgentSetup3WSpec "test/tmp", "GridAgentSetup3WSpec", ResultEntityPathConfig( - Set.empty[Class[_ <: ResultEntity]], + Set.empty[Class[? <: ResultEntity]], ResultSinkType( simonaConfig.simona.output.sink, simonaConfig.simona.simulationName diff --git a/src/test/scala/edu/ie3/simona/agent/grid/GridResultsSupportSpec.scala b/src/test/scala/edu/ie3/simona/agent/grid/GridResultsSupportSpec.scala index c9d17d2379..59920ae008 100644 --- a/src/test/scala/edu/ie3/simona/agent/grid/GridResultsSupportSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/grid/GridResultsSupportSpec.scala @@ -42,7 +42,7 @@ import edu.ie3.util.TimeUtil import edu.ie3.util.quantities.PowerSystemUnits.{DEGREE_GEOM, PU} import edu.ie3.util.quantities.QuantityUtil import edu.ie3.util.scala.OperationInterval -import edu.ie3.util.scala.quantities.{QuantityUtil => ScalaQuantityUtil} +import edu.ie3.util.scala.quantities.QuantityUtil as ScalaQuantityUtil import org.scalatest.prop.TableDrivenPropertyChecks import squants.Each import squants.electro.{Amperes, Volts} @@ -62,8 +62,8 @@ class GridResultsSupportSpec with TableDrivenPropertyChecks { override protected val log: LoggingAdapter = NoLogging - implicit val currentTolerance: squants.electro.ElectricCurrent = Amperes(1e-6) - implicit val angleTolerance: squants.Angle = Degrees(1e-6) + given currentTolerance: squants.electro.ElectricCurrent = Amperes(1e-6) + given angleTolerance: squants.Angle = Degrees(1e-6) "Preparing grid results" when { "calculating node results" should { @@ -300,13 +300,12 @@ class GridResultsSupportSpec expectedResult.getiBMag(), 1e-3 ) shouldBe true - if ( - QuantityUtil.isEquivalentAngle( + if QuantityUtil.isEquivalentAngle( actual.getiBAng(), expectedResult.getiBAng(), 1e-3 ) - ) { + then { /* Angles are considerably equal */ succeed } else { diff --git a/src/test/scala/edu/ie3/simona/agent/grid/PowerFlowSupportSpec.scala b/src/test/scala/edu/ie3/simona/agent/grid/PowerFlowSupportSpec.scala index 66805b06d9..24698e5e51 100644 --- a/src/test/scala/edu/ie3/simona/agent/grid/PowerFlowSupportSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/grid/PowerFlowSupportSpec.scala @@ -9,6 +9,7 @@ package edu.ie3.simona.agent.grid import org.apache.pekko.actor.ActorRef import org.apache.pekko.event.{LoggingAdapter, NoLogging} import edu.ie3.powerflow.model.PowerFlowResult.SuccessFullPowerFlowResult.ValidNewtonRaphsonPFResult +import edu.ie3.powerflow.model.StartData.WithForcedStartVoltages import edu.ie3.simona.model.grid.GridModel import edu.ie3.simona.ontology.messages.PowerMessage.ProvideGridPowerMessage.ExchangePower import edu.ie3.simona.ontology.messages.VoltageMessage.ProvideSlackVoltageMessage.ExchangeVoltage @@ -74,14 +75,11 @@ class PowerFlowSupportSpec */ private def normalizeAngle( angle: ComparableQuantity[Angle] - ): ComparableQuantity[Angle] = { - if (angle.isLessThan(0d.asDegreeGeom)) - angle.add(180.asDegreeGeom) - else if (angle.isGreaterThan(180d.asDegreeGeom)) + ): ComparableQuantity[Angle] = + if angle.isLessThan(0d.asDegreeGeom) then angle.add(180.asDegreeGeom) + else if angle.isGreaterThan(180d.asDegreeGeom) then angle.subtract(180.asDegreeGeom) - else - angle - } + else angle "PowerFlowSupport" when { "all switches are closed" must { @@ -90,7 +88,10 @@ class PowerFlowSupportSpec // switches are closed per default val gridModel = createGridCopy() - val (operatingPoint, slackNodeVoltages) = + val ( + operatingPoint: Array[PresetData], + slackNodeVoltages: WithForcedStartVoltages + ) = composeOperatingPoint( gridModel.gridComponents.nodes, gridModel.gridComponents.transformers, @@ -100,7 +101,9 @@ class PowerFlowSupportSpec gridModel.mainRefSystem ) - operatingPoint.length shouldBe 10 withClue "safety check: 13 nodes minus 3 closed switches" + (operatingPoint.length shouldBe 10).withClue( + "safety check: 13 nodes minus 3 closed switches" + ) val result = newtonRaphsonPF( gridModel, @@ -201,7 +204,9 @@ class PowerFlowSupportSpec gridModel.mainRefSystem ) - operatingPoint.length shouldBe 11 withClue "safety check: 13 nodes minus 2 closed switches" + (operatingPoint.length shouldBe 11).withClue( + "safety check: 13 nodes minus 2 closed switches" + ) val result = newtonRaphsonPF( gridModel, @@ -286,7 +291,9 @@ class PowerFlowSupportSpec gridModel.mainRefSystem ) - operatingPoint.length shouldBe 11 withClue "safety check: 13 nodes minus 2 closed switches" + (operatingPoint.length shouldBe 11).withClue( + "safety check: 13 nodes minus 2 closed switches" + ) val result = newtonRaphsonPF( gridModel, diff --git a/src/test/scala/edu/ie3/simona/agent/participant/EvcsAgentModelCalculationSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/EvcsAgentModelCalculationSpec.scala index 5f53c56304..2f3b45b180 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/EvcsAgentModelCalculationSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/EvcsAgentModelCalculationSpec.scala @@ -15,7 +15,7 @@ import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService.Acto import edu.ie3.simona.agent.participant.evcs.EvcsAgent import edu.ie3.simona.agent.participant.statedata.BaseStateData.ParticipantModelBaseStateData import edu.ie3.simona.agent.participant.statedata.DataCollectionStateData -import edu.ie3.simona.agent.participant.statedata.ParticipantStateData._ +import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.* import edu.ie3.simona.agent.state.AgentState.{Idle, Uninitialized} import edu.ie3.simona.agent.state.ParticipantAgentState.HandleInformation import edu.ie3.simona.config.SimonaConfig.EvcsRuntimeConfig @@ -31,7 +31,7 @@ import edu.ie3.simona.ontology.messages.SchedulerMessage.{ Completion, ScheduleActivation } -import edu.ie3.simona.ontology.messages.services.EvMessage._ +import edu.ie3.simona.ontology.messages.services.EvMessage.* import edu.ie3.simona.ontology.messages.services.ServiceMessage.PrimaryServiceRegistrationMessage import edu.ie3.simona.ontology.messages.services.ServiceMessage.RegistrationResponseMessage.{ RegistrationFailedMessage, @@ -68,8 +68,8 @@ class EvcsAgentModelCalculationSpec with EvTestData with TestSpawnerClassic { - private implicit val powerTolerance: Power = Watts(0.1) - private implicit val reactivePowerTolerance: ReactivePower = Vars(0.1) + given powerTolerance: Power = Watts(0.1) + given reactivePowerTolerance: ReactivePower = Vars(0.1) /* Alter the input model to have a voltage sensitive reactive power calculation */ private val voltageSensitiveInput = evcsInputModel @@ -117,7 +117,7 @@ class EvcsAgentModelCalculationSpec evcsAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(evcsAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${evcsAgent.stateData}." @@ -178,7 +178,7 @@ class EvcsAgentModelCalculationSpec evcsAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(evcsAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${evcsAgent.stateData}." @@ -294,7 +294,7 @@ class EvcsAgentModelCalculationSpec /* ... as well as corresponding state and state data */ evcsAgent.stateName shouldBe Idle evcsAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* Only check the awaited next data ticks, as the rest has yet been checked */ baseStateData.foreseenDataTicks shouldBe Map(evService.ref -> None) case _ => @@ -344,7 +344,7 @@ class EvcsAgentModelCalculationSpec ) inside(evcsAgent.stateData) { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.requestValueStore shouldBe ValueStore[ ApparentPower ]( @@ -407,7 +407,7 @@ class EvcsAgentModelCalculationSpec evcsAgent.stateName shouldBe HandleInformation evcsAgent.stateData match { case DataCollectionStateData( - baseStateData: ParticipantModelBaseStateData[_, _, _], + baseStateData: ParticipantModelBaseStateData[?, ?, ?], expectedSenders, isYetTriggered ) => @@ -440,7 +440,7 @@ class EvcsAgentModelCalculationSpec ) evcsAgent.stateName shouldBe Idle evcsAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* The store for calculation relevant data has been extended */ baseStateData.calcRelevantDateStore match { case ValueStore(_, store) => @@ -511,7 +511,7 @@ class EvcsAgentModelCalculationSpec evcsAgent.stateName shouldBe HandleInformation evcsAgent.stateData match { case DataCollectionStateData( - baseStateData: ParticipantModelBaseStateData[_, _, _], + baseStateData: ParticipantModelBaseStateData[?, ?, ?], expectedSenders, isYetTriggered ) => @@ -547,7 +547,7 @@ class EvcsAgentModelCalculationSpec ) evcsAgent.stateName shouldBe Idle evcsAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* The store for calculation relevant data has been extended */ baseStateData.calcRelevantDateStore match { case ValueStore(_, store) => diff --git a/src/test/scala/edu/ie3/simona/agent/participant/FixedFeedInAgentModelCalculationSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/FixedFeedInAgentModelCalculationSpec.scala index 1b3046f6f4..d1054d63c5 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/FixedFeedInAgentModelCalculationSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/FixedFeedInAgentModelCalculationSpec.scala @@ -62,8 +62,8 @@ class FixedFeedInAgentModelCalculationSpec ) ) with FixedFeedInputTestData { - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) /* Alter the input model to have a voltage sensitive reactive power calculation */ val voltageSensitiveInput: FixedFeedInInput = fixedFeedInput @@ -76,8 +76,8 @@ class FixedFeedInAgentModelCalculationSpec protected val simulationEndDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 01:00:00") - private implicit val powerTolerance: squants.Power = Watts(0.1) - private implicit val reactivePowerTolerance: ReactivePower = Vars(0.1) + implicit private val powerTolerance: squants.Power = Watts(0.1) + implicit private val reactivePowerTolerance: ReactivePower = Vars(0.1) private val simonaConfig: SimonaConfig = createSimonaConfig( @@ -129,7 +129,7 @@ class FixedFeedInAgentModelCalculationSpec fixedFeedAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(fixedFeedAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${fixedFeedAgent.stateData}." @@ -259,7 +259,7 @@ class FixedFeedInAgentModelCalculationSpec ) inside(fixedFeedAgent.stateData) { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.requestValueStore shouldBe ValueStore[ ApparentPower ]( @@ -309,9 +309,9 @@ class FixedFeedInAgentModelCalculationSpec awaitAssert(fixedFeedAgent.stateName shouldBe Idle) inside(fixedFeedAgent.stateData) { case participantModelBaseStateData: ParticipantModelBaseStateData[ - _, - _, - _ + ?, + ?, + ? ] => participantModelBaseStateData.resultValueStore.last(0L) match { case Some((tick, entry)) => diff --git a/src/test/scala/edu/ie3/simona/agent/participant/HpAgentModelCalculationSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/HpAgentModelCalculationSpec.scala index 95bfcfd6ff..d95611de4c 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/HpAgentModelCalculationSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/HpAgentModelCalculationSpec.scala @@ -18,7 +18,7 @@ import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService.Acto import edu.ie3.simona.agent.participant.hp.HpAgent import edu.ie3.simona.agent.participant.statedata.BaseStateData.ParticipantModelBaseStateData import edu.ie3.simona.agent.participant.statedata.DataCollectionStateData -import edu.ie3.simona.agent.participant.statedata.ParticipantStateData._ +import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.* import edu.ie3.simona.agent.state.AgentState.{Idle, Uninitialized} import edu.ie3.simona.agent.state.ParticipantAgentState.HandleInformation import edu.ie3.simona.config.SimonaConfig @@ -77,13 +77,13 @@ class HpAgentModelCalculationSpec with HpTestData with IntegrationSpecCommon with PrivateMethodTester { - implicit val simulationStart: ZonedDateTime = defaultSimulationStart - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) - implicit val powerTolerance: Power = Watts(1e-3) - implicit val reactivepowerTolerance: ReactivePower = Vars(1e-3) - implicit val temperatureTolerance: Temperature = Celsius(1e-10) - implicit val dimensionlessTolerance: Dimensionless = Each(1e-10) + given simulationStart: ZonedDateTime = defaultSimulationStart + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given powerTolerance: Power = Watts(1e-3) + given reactivepowerTolerance: ReactivePower = Vars(1e-3) + given temperatureTolerance: Temperature = Celsius(1e-10) + given dimensionlessTolerance: Dimensionless = Each(1e-10) /* Alter the input model to have a voltage sensitive reactive power calculation */ val hpInput: HpInput = inputModel @@ -142,7 +142,7 @@ class HpAgentModelCalculationSpec hpAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(hpAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${hpAgent.stateData}." @@ -204,7 +204,7 @@ class HpAgentModelCalculationSpec hpAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(hpAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${hpAgent.stateData}." @@ -322,7 +322,7 @@ class HpAgentModelCalculationSpec /* ... as well as corresponding state and state data */ hpAgent.stateName shouldBe Idle hpAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* Only check the awaited next data ticks, as the rest has yet been checked */ baseStateData.foreseenDataTicks shouldBe Map( weatherService.ref -> Some(4711L) @@ -374,7 +374,7 @@ class HpAgentModelCalculationSpec ) inside(hpAgent.stateData) { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.requestValueStore shouldBe ValueStore[ ApparentPowerAndHeat ]( @@ -435,7 +435,7 @@ class HpAgentModelCalculationSpec hpAgent.stateName shouldBe HandleInformation hpAgent.stateData match { case DataCollectionStateData( - baseStateData: ParticipantModelBaseStateData[_, _, _], + baseStateData: ParticipantModelBaseStateData[?, ?, ?], expectedSenders, isYetTriggered ) => @@ -466,7 +466,7 @@ class HpAgentModelCalculationSpec hpAgent.stateName shouldBe Idle hpAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* The store for calculation relevant data has been extended */ baseStateData.calcRelevantDateStore match { case ValueStore(_, store) => @@ -552,7 +552,7 @@ class HpAgentModelCalculationSpec hpAgent.stateName shouldBe HandleInformation hpAgent.stateData match { case DataCollectionStateData( - baseStateData: ParticipantModelBaseStateData[_, _, _], + baseStateData: ParticipantModelBaseStateData[?, ?, ?], expectedSenders, isYetTriggered ) => @@ -591,7 +591,7 @@ class HpAgentModelCalculationSpec /* Expect the state change to idle with updated base state data */ hpAgent.stateName shouldBe Idle hpAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* The store for calculation relevant data has been extended */ baseStateData.calcRelevantDateStore match { case ValueStore(_, store) => diff --git a/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentFixedModelCalculationSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentFixedModelCalculationSpec.scala index d7252f1dab..a792833714 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentFixedModelCalculationSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentFixedModelCalculationSpec.scala @@ -62,8 +62,8 @@ class LoadAgentFixedModelCalculationSpec ) with LoadTestData with PrivateMethodTester { - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) /* Alter the input model to have a voltage sensitive reactive power calculation */ val voltageSensitiveInput: LoadInput = loadInput @@ -90,8 +90,8 @@ class LoadAgentFixedModelCalculationSpec private val services = None private val resolution = simonaConfig.simona.powerflow.resolution.getSeconds - private implicit val powerTolerance: squants.Power = Watts(0.1) - private implicit val reactivePowerTolerance: ReactivePower = Vars(0.1) + given powerTolerance: squants.Power = Watts(0.1) + given reactivePowerTolerance: ReactivePower = Vars(0.1) "A load agent with fixed model calculation depending on no secondary data service" should { val initStateData = ParticipantInitializeStateData[ @@ -123,7 +123,7 @@ class LoadAgentFixedModelCalculationSpec loadAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(loadAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${loadAgent.stateData}." @@ -253,7 +253,7 @@ class LoadAgentFixedModelCalculationSpec ) inside(loadAgent.stateData) { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.requestValueStore shouldBe ValueStore[ ApparentPower ]( @@ -303,9 +303,9 @@ class LoadAgentFixedModelCalculationSpec awaitAssert(loadAgent.stateName shouldBe Idle) inside(loadAgent.stateData) { case participantModelBaseStateData: ParticipantModelBaseStateData[ - _, - _, - _ + ?, + ?, + ? ] => participantModelBaseStateData.resultValueStore.last(0L) match { case Some((tick, entry)) => diff --git a/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentProfileModelCalculationSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentProfileModelCalculationSpec.scala index ee17a58989..09049df994 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentProfileModelCalculationSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/LoadAgentProfileModelCalculationSpec.scala @@ -62,8 +62,8 @@ class LoadAgentProfileModelCalculationSpec ) with LoadTestData with PrivateMethodTester { - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) /* Alter the input model to have a voltage sensitive reactive power calculation */ val voltageSensitiveInput: LoadInput = loadInput @@ -90,8 +90,8 @@ class LoadAgentProfileModelCalculationSpec private val services = None private val resolution = simonaConfig.simona.powerflow.resolution.getSeconds - private implicit val powerTolerance: squants.Power = Watts(0.1) - private implicit val reactivePowerTolerance: ReactivePower = Vars(0.1) + given powerTolerance: squants.Power = Watts(0.1) + given reactivePowerTolerance: ReactivePower = Vars(0.1) "A load agent with profile model calculation depending on no secondary data service" should { val initStateData = ParticipantInitializeStateData[ @@ -123,7 +123,7 @@ class LoadAgentProfileModelCalculationSpec loadAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(loadAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${loadAgent.stateData}." @@ -253,7 +253,7 @@ class LoadAgentProfileModelCalculationSpec ) inside(loadAgent.stateData) { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.requestValueStore shouldBe ValueStore[ ApparentPower ]( @@ -303,9 +303,9 @@ class LoadAgentProfileModelCalculationSpec awaitAssert(loadAgent.stateName shouldBe Idle) inside(loadAgent.stateData) { case participantModelBaseStateData: ParticipantModelBaseStateData[ - _, - _, - _ + ?, + ?, + ? ] => participantModelBaseStateData.resultValueStore.last(0L) match { case Some((tick, entry)) => diff --git a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgent2ListenerSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgent2ListenerSpec.scala index 1007da8e77..862baca99a 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgent2ListenerSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgent2ListenerSpec.scala @@ -59,8 +59,8 @@ class ParticipantAgent2ListenerSpec with PrivateMethodTester with MockitoSugar { - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) /* Assign this test to receive the result events from agent */ override val systemListener: Iterable[ActorRef] = Vector(self) @@ -68,7 +68,7 @@ class ParticipantAgent2ListenerSpec private val testUUID = UUID.randomUUID private val testID = "PartAgentExternalMock" - private implicit val quantityTolerance: Double = 1e-6 // Equals to 1 W power + given quantityTolerance: Double = 1e-6 // Equals to 1 W power private val simonaConfig: SimonaConfig = createSimonaConfig( LoadModelBehaviour.FIX, diff --git a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentExternalSourceSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentExternalSourceSpec.scala index bff18f7a87..488051c673 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentExternalSourceSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentExternalSourceSpec.scala @@ -81,8 +81,8 @@ class ParticipantAgentExternalSourceSpec ) with DefaultTestData with MockitoSugar { - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) private val testUUID = UUID.randomUUID private val testID = "PartAgentExternalMock" @@ -117,8 +117,8 @@ class ParticipantAgentExternalSourceSpec private val resolution = simonaConfig.simona.powerflow.resolution.getSeconds - private implicit val powerTolerance: squants.Power = Watts(0.1) - private implicit val reactivePowerTolerance: ReactivePower = Vars(0.1) + given powerTolerance: squants.Power = Watts(0.1) + given reactivePowerTolerance: ReactivePower = Vars(0.1) "A participant agent with externally given data provider" should { val initStateData = ParticipantInitializeStateData[ @@ -149,7 +149,7 @@ class ParticipantAgentExternalSourceSpec mockAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(mockAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${mockAgent.stateData}." diff --git a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentalsSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentalsSpec.scala index 3d87971bca..2ec0ffb615 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentalsSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentFundamentalsSpec.scala @@ -62,10 +62,10 @@ class ParticipantAgentFundamentalsSpec with PrivateMethodTester with TableDrivenPropertyChecks with MockitoSugar { - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) - implicit val pTolerance: squants.Power = Megawatts(0.001) - implicit val qTolerance: ReactivePower = Megavars(0.001) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given pTolerance: squants.Power = Megawatts(0.001) + given qTolerance: ReactivePower = Megavars(0.001) private val outputConfig: NotifierConfig = NotifierConfig( @@ -168,16 +168,14 @@ class ParticipantAgentFundamentalsSpec resolution: Long, expectedFirstTick: Long ) => - { - val simulationStart = - TimeUtil.withDefaults.toZonedDateTime(simulationStartString) - val firstTick = mockAgent.firstFullResolutionInSimulation( - simulationStart, - resolution - ) + val simulationStart = + TimeUtil.withDefaults.toZonedDateTime(simulationStartString) + val firstTick = mockAgent.firstFullResolutionInSimulation( + simulationStart, + resolution + ) - firstTick shouldBe expectedFirstTick - } + firstTick shouldBe expectedFirstTick } } @@ -211,21 +209,19 @@ class ParticipantAgentFundamentalsSpec operationEnd: Long, expectedTicks: List[Long] ) => - { - val simulationStart = - TimeUtil.withDefaults.toZonedDateTime(simulationStartString) - val additionalActivationTicks = - mockAgent.activationTicksInOperationTime( - simulationStart, - resolution, - operationStart, - operationEnd - ) - - additionalActivationTicks.corresponds(expectedTicks)( - _ == _ - ) shouldBe true - } + val simulationStart = + TimeUtil.withDefaults.toZonedDateTime(simulationStartString) + val additionalActivationTicks = + mockAgent.activationTicksInOperationTime( + simulationStart, + resolution, + operationStart, + operationEnd + ) + + additionalActivationTicks.corresponds(expectedTicks)( + _ == _ + ) shouldBe true } } } diff --git a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentMock.scala b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentMock.scala index 2b0264258d..4e1f555411 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentMock.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/ParticipantAgentMock.scala @@ -153,7 +153,7 @@ class ParticipantAgentMock( override def determineModelBaseStateData( inputModel: InputModelContainer[SystemParticipantInput], modelConfig: SimonaConfig.BaseRuntimeConfig, - services: Option[Vector[SecondaryDataService[_ <: SecondaryData]]], + services: Option[Vector[SecondaryDataService[? <: SecondaryData]]], simulationStartDate: ZonedDateTime, simulationEndDate: ZonedDateTime, resolution: Long, @@ -240,7 +240,7 @@ class ParticipantAgentMock( baseStateData: BaseStateData[ApparentPower], currentTick: Long ): FSM.State[AgentState, ParticipantStateData[ApparentPower]] = - goto(Idle) using baseStateData + goto(Idle).using(baseStateData) /** Determine the average result within the given tick window * diff --git a/src/test/scala/edu/ie3/simona/agent/participant/PvAgentModelCalculationSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/PvAgentModelCalculationSpec.scala index 3a0882ed1c..06c906b5bf 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/PvAgentModelCalculationSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/PvAgentModelCalculationSpec.scala @@ -19,7 +19,7 @@ import edu.ie3.simona.agent.participant.data.secondary.SecondaryDataService.Acto import edu.ie3.simona.agent.participant.pv.PvAgent import edu.ie3.simona.agent.participant.statedata.BaseStateData.ParticipantModelBaseStateData import edu.ie3.simona.agent.participant.statedata.DataCollectionStateData -import edu.ie3.simona.agent.participant.statedata.ParticipantStateData._ +import edu.ie3.simona.agent.participant.statedata.ParticipantStateData.* import edu.ie3.simona.agent.state.AgentState.{Idle, Uninitialized} import edu.ie3.simona.agent.state.ParticipantAgentState.HandleInformation import edu.ie3.simona.config.SimonaConfig @@ -76,8 +76,8 @@ class PvAgentModelCalculationSpec ) with PrivateMethodTester with PvInputTestData { - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) /* Alter the input model to have a voltage sensitive reactive power calculation */ val voltageSensitiveInput: PvInput = pvInputModel @@ -111,8 +111,8 @@ class PvAgentModelCalculationSpec ) private val resolution = simonaConfig.simona.powerflow.resolution.getSeconds - private implicit val powerTolerance: Power = Watts(0.1) - private implicit val reactivePowerTolerance: ReactivePower = Vars(0.1) + given powerTolerance: Power = Watts(0.1) + given reactivePowerTolerance: ReactivePower = Vars(0.1) "A pv agent with model calculation depending on no secondary data service" should { val initStateData = ParticipantInitializeStateData[ @@ -144,7 +144,7 @@ class PvAgentModelCalculationSpec pvAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(pvAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${pvAgent.stateData}." @@ -205,7 +205,7 @@ class PvAgentModelCalculationSpec pvAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(pvAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${pvAgent.stateData}." @@ -321,7 +321,7 @@ class PvAgentModelCalculationSpec /* ... as well as corresponding state and state data */ pvAgent.stateName shouldBe Idle pvAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* Only check the awaited next data ticks, as the rest has yet been checked */ baseStateData.foreseenDataTicks shouldBe Map( weatherService.ref -> Some(4711L) @@ -373,7 +373,7 @@ class PvAgentModelCalculationSpec ) inside(pvAgent.stateData) { - case modelBaseStateData: ParticipantModelBaseStateData[_, _, _] => + case modelBaseStateData: ParticipantModelBaseStateData[?, ?, ?] => modelBaseStateData.requestValueStore shouldBe ValueStore[ ApparentPower ]( @@ -433,7 +433,7 @@ class PvAgentModelCalculationSpec pvAgent.stateName shouldBe HandleInformation pvAgent.stateData match { case DataCollectionStateData( - baseStateData: ParticipantModelBaseStateData[_, _, _], + baseStateData: ParticipantModelBaseStateData[?, ?, ?], expectedSenders, isYetTriggered ) => @@ -464,7 +464,7 @@ class PvAgentModelCalculationSpec pvAgent.stateName shouldBe Idle pvAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* The store for calculation relevant data has been extended */ baseStateData.calcRelevantDateStore match { case ValueStore(_, store) => @@ -528,7 +528,7 @@ class PvAgentModelCalculationSpec pvAgent.stateName shouldBe HandleInformation pvAgent.stateData match { case DataCollectionStateData( - baseStateData: ParticipantModelBaseStateData[_, _, _], + baseStateData: ParticipantModelBaseStateData[?, ?, ?], expectedSenders, isYetTriggered ) => @@ -567,7 +567,7 @@ class PvAgentModelCalculationSpec /* Expect the state change to idle with updated base state data */ pvAgent.stateName shouldBe Idle pvAgent.stateData match { - case baseStateData: ParticipantModelBaseStateData[_, _, _] => + case baseStateData: ParticipantModelBaseStateData[?, ?, ?] => /* The store for calculation relevant data has been extended */ baseStateData.calcRelevantDateStore match { case ValueStore(_, store) => diff --git a/src/test/scala/edu/ie3/simona/agent/participant/RichValueSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/RichValueSpec.scala index 5cf286ba8c..e8fab7546e 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/RichValueSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/RichValueSpec.scala @@ -82,16 +82,17 @@ class RichValueSpec extends UnitSpec with TableDrivenPropertyChecks { ) ) - forAll(table)({ maliciousValue: Value => - maliciousValue.toPrimaryData match { - case Failure(exception) => - exception.getMessage shouldBe s"Cannot convert '$maliciousValue' to primary data." - case Success(value) => - fail( - s"Conversion from '$maliciousValue' to primary data was meant to fail, but succeeded with '$value'." - ) - } - }) + forAll(table) { + maliciousValue: Value => + maliciousValue.toPrimaryData match { + case Failure(exception) => + exception.getMessage shouldBe s"Cannot convert '$maliciousValue' to primary data." + case Success(value) => + fail( + s"Conversion from '$maliciousValue' to primary data was meant to fail, but succeeded with '$value'." + ) + } + } } "transfer supported values correctly to primary data" in { @@ -135,7 +136,7 @@ class RichValueSpec extends UnitSpec with TableDrivenPropertyChecks { ) ) - forAll(table)({ case (value: Value, primaryData: PrimaryData) => + forAll(table) { case (value: Value, primaryData: PrimaryData) => value.toPrimaryData match { case Success(actualPrimaryData) => actualPrimaryData shouldBe primaryData @@ -145,7 +146,7 @@ class RichValueSpec extends UnitSpec with TableDrivenPropertyChecks { exception ) } - }) + } } } } diff --git a/src/test/scala/edu/ie3/simona/agent/participant/WecAgentModelCalculationSpec.scala b/src/test/scala/edu/ie3/simona/agent/participant/WecAgentModelCalculationSpec.scala index 24ccac5f34..413515a6e7 100644 --- a/src/test/scala/edu/ie3/simona/agent/participant/WecAgentModelCalculationSpec.scala +++ b/src/test/scala/edu/ie3/simona/agent/participant/WecAgentModelCalculationSpec.scala @@ -83,12 +83,12 @@ class WecAgentModelCalculationSpec with PrivateMethodTester with WecInputTestData { - protected implicit val simulationStartDate: ZonedDateTime = + given simulationStartDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 00:00:00") protected val simulationEndDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 01:00:00") - implicit val receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) - implicit val noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) + given receiveTimeOut: Timeout = Timeout(10, TimeUnit.SECONDS) + given noReceiveTimeOut: Timeout = Timeout(1, TimeUnit.SECONDS) /* Alter the input model to have a voltage sensitive reactive power calculation */ val voltageSensitiveInput: WecInput = wecInputModel @@ -118,8 +118,8 @@ class WecAgentModelCalculationSpec private val resolution = simonaConfig.simona.powerflow.resolution.getSeconds - private implicit val powerTolerance: squants.Power = Watts(0.1) - private implicit val reactivePowerTolerance: ReactivePower = Vars(0.1) + given powerTolerance: squants.Power = Watts(0.1) + given reactivePowerTolerance: ReactivePower = Vars(0.1) "A wec agent with model calculation depending on no second data service" should { val initStateData = ParticipantInitializeStateData[ @@ -154,7 +154,7 @@ class WecAgentModelCalculationSpec wecAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(wecAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${wecAgent.stateData}." @@ -218,7 +218,7 @@ class WecAgentModelCalculationSpec wecAgent.stateName shouldBe Uninitialized // ParticipantUninitializedStateData is an empty class (due to typing). If it contains content one day inside(wecAgent.stateData) { - case _: ParticipantUninitializedStateData[_] => succeed + case _: ParticipantUninitializedStateData[?] => succeed case _ => fail( s"Expected $ParticipantUninitializedStateData, but got ${wecAgent.stateData}." diff --git a/src/test/scala/edu/ie3/simona/api/ExtSimAdapterSpec.scala b/src/test/scala/edu/ie3/simona/api/ExtSimAdapterSpec.scala index 54dcd9f061..5b0a9807e3 100644 --- a/src/test/scala/edu/ie3/simona/api/ExtSimAdapterSpec.scala +++ b/src/test/scala/edu/ie3/simona/api/ExtSimAdapterSpec.scala @@ -16,7 +16,7 @@ import edu.ie3.simona.api.simulation.ontology.{ ActivationMessage, TerminationCompleted, TerminationMessage, - CompletionMessage => ExtCompletionMessage + CompletionMessage as ExtCompletionMessage } import edu.ie3.simona.ontology.messages.SchedulerMessage.{ Completion, diff --git a/src/test/scala/edu/ie3/simona/config/ConfigFailFastSpec.scala b/src/test/scala/edu/ie3/simona/config/ConfigFailFastSpec.scala index 33f9914a0f..ca6976ca99 100644 --- a/src/test/scala/edu/ie3/simona/config/ConfigFailFastSpec.scala +++ b/src/test/scala/edu/ie3/simona/config/ConfigFailFastSpec.scala @@ -29,11 +29,13 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "let valid input pass" in { noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkTimeConfig( - new Time( - "2020-06-18 13:41:00", - None, - "2020-05-18 13:41:00" + ConfigFailFast.invokePrivate( + checkTimeConfig( + new Time( + "2020-06-18 13:41:00", + None, + "2020-05-18 13:41:00" + ) ) ) } @@ -41,11 +43,13 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "identify invalid date or time configuration" in { intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkTimeConfig( - new Time( - "2020-06-18 13:41:00", - None, - "2020-07-18 13:41:00" + ConfigFailFast.invokePrivate( + checkTimeConfig( + new Time( + "2020-06-18 13:41:00", + None, + "2020-07-18 13:41:00" + ) ) ) }.getMessage shouldBe "Invalid time configuration." + @@ -61,16 +65,20 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "let valid input pass" in { - ConfigFailFast invokePrivate createDateTime( - dateTimeString + ConfigFailFast.invokePrivate( + createDateTime( + dateTimeString + ) ) shouldBe TimeUtil.withDefaults.toZonedDateTime(dateTimeString) } "identify invalid input" in { intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate createDateTime( - "total non-sense" + ConfigFailFast.invokePrivate( + createDateTime( + "total non-sense" + ) ) }.getMessage shouldBe "Invalid dateTimeString: total non-sense." + "Please ensure that your date/time parameter match the following pattern: 'yyyy-MM-dd HH:mm:ss'" @@ -83,16 +91,18 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "let valid input pass" in { noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkPowerFlowResolutionConfiguration( - new Powerflow( - 10, - new Newtonraphson( - List(10, 30), - 100 - ), - Duration.of(3600, ChronoUnit.SECONDS), - stopOnFailure = false, - Duration.of(3600, ChronoUnit.SECONDS) + ConfigFailFast.invokePrivate( + checkPowerFlowResolutionConfiguration( + new Powerflow( + 10, + new Newtonraphson( + List(10, 30), + 100 + ), + Duration.of(3600, ChronoUnit.SECONDS), + stopOnFailure = false, + Duration.of(3600, ChronoUnit.SECONDS) + ) ) ) } @@ -100,16 +110,18 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "identify invalid input" in { intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkPowerFlowResolutionConfiguration( - new Powerflow( - 10, - new Newtonraphson( - List(10, 30), - 100 - ), - resolution = Duration.of(3600, ChronoUnit.NANOS), - stopOnFailure = false, - sweepTimeout = Duration.of(3600, ChronoUnit.SECONDS) + ConfigFailFast.invokePrivate( + checkPowerFlowResolutionConfiguration( + new Powerflow( + 10, + new Newtonraphson( + List(10, 30), + 100 + ), + resolution = Duration.of(3600, ChronoUnit.NANOS), + stopOnFailure = false, + sweepTimeout = Duration.of(3600, ChronoUnit.SECONDS) + ) ) ) }.getMessage shouldBe "Invalid time resolution. Please ensure, that the time resolution for power flow calculation is at least rounded to a full second!" @@ -140,7 +152,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val malformedGridIds = List("10--100", "MS", "10..100") - malformedGridIds.foreach(malformedGridId => { + malformedGridIds.foreach { malformedGridId => val refSystemConfigAllEmpty = ConfigFactory.parseString(s"""simona.gridConfig.refSystems = [ @@ -157,11 +169,11 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { intercept[InvalidConfigParameterException] { faultySimonaConfig.simona.gridConfig.refSystems.foreach( refSystem => - ConfigFailFast invokePrivate checkRefSystem(refSystem) + ConfigFailFast.invokePrivate(checkRefSystem(refSystem)) ) }.getMessage shouldBe s"The provided gridId $malformedGridId is malformed!" - }) + } } "throw an InvalidConfigParameterException if the nominal voltage of the voltage level is malformed" in { @@ -180,7 +192,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { intercept[InvalidConfigParameterException] { faultySimonaConfig.simona.gridConfig.refSystems.foreach(refSystem => - ConfigFailFast invokePrivate checkRefSystem(refSystem) + ConfigFailFast.invokePrivate(checkRefSystem(refSystem)) ) }.getMessage shouldBe "The given nominal voltage 'foo' cannot be parsed to a quantity. Did you provide the volt level with it's unit (e.g. \"20 kV\")?" @@ -203,7 +215,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { intercept[InvalidConfigParameterException] { faultySimonaConfig.simona.gridConfig.refSystems.foreach(refSystem => - ConfigFailFast invokePrivate checkRefSystem(refSystem) + ConfigFailFast.invokePrivate(checkRefSystem(refSystem)) ) }.getMessage shouldBe "Invalid value for sNom from provided refSystem RefSystemConfig(None,100,0.4 kV,Some(List(VoltLvlConfig(MS,10 kV), VoltLvlConfig(HS,110 kV)))). Is a valid unit provided?" @@ -227,7 +239,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { intercept[InvalidConfigParameterException] { faultySimonaConfig.simona.gridConfig.refSystems.foreach(refSystem => - ConfigFailFast invokePrivate checkRefSystem(refSystem) + ConfigFailFast.invokePrivate(checkRefSystem(refSystem)) ) }.getMessage shouldBe "Invalid value for vNom from provided refSystem RefSystemConfig(None,100 MVA,0.4,Some(List(VoltLvlConfig(MS,10 kV), VoltLvlConfig(HS,110 kV)))). Is a valid unit provided?" @@ -255,9 +267,9 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { refSystemConfigAllEmpty.withFallback(typesafeConfig).resolve() val simonaConfig = SimonaConfig(config) - simonaConfig.simona.gridConfig.refSystems.foreach(refSystem => { - ConfigFailFast invokePrivate checkRefSystem(refSystem) - }) + simonaConfig.simona.gridConfig.refSystems.foreach { refSystem => + ConfigFailFast.invokePrivate(checkRefSystem(refSystem)) + } } } @@ -275,8 +287,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkParticipantRuntimeConfiguration( - simonaConfig.simona.runtime.participant + ConfigFailFast.invokePrivate( + checkParticipantRuntimeConfiguration( + simonaConfig.simona.runtime.participant + ) ) }.getMessage shouldBe "The participant power request voltage deviation threshold must be positive!" } @@ -306,8 +320,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkParticipantRuntimeConfiguration( - simonaConfig.simona.runtime.participant + ConfigFailFast.invokePrivate( + checkParticipantRuntimeConfiguration( + simonaConfig.simona.runtime.participant + ) ) } } @@ -356,8 +372,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { PrivateMethod[Unit](Symbol("checkParticipantRuntimeConfiguration")) noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkParticipantRuntimeConfiguration( - simonaConfig.simona.runtime.participant + ConfigFailFast.invokePrivate( + checkParticipantRuntimeConfiguration( + simonaConfig.simona.runtime.participant + ) ) } } @@ -415,8 +433,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkParticipantRuntimeConfiguration( - simonaConfig.simona.runtime.participant + ConfigFailFast.invokePrivate( + checkParticipantRuntimeConfiguration( + simonaConfig.simona.runtime.participant + ) ) } } @@ -447,10 +467,12 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkBaseRuntimeConfigs( - simonaConfig.simona.runtime.participant.load.defaultConfig, - simonaConfig.simona.runtime.participant.load.individualConfigs, - defaultString + ConfigFailFast.invokePrivate( + checkBaseRuntimeConfigs( + simonaConfig.simona.runtime.participant.load.defaultConfig, + simonaConfig.simona.runtime.participant.load.individualConfigs, + defaultString + ) ) }.getMessage shouldBe "There has to be at least one identifier for each participant." } @@ -473,10 +495,12 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkBaseRuntimeConfigs( - simonaConfig.simona.runtime.participant.load.defaultConfig, - simonaConfig.simona.runtime.participant.load.individualConfigs, - defaultString + ConfigFailFast.invokePrivate( + checkBaseRuntimeConfigs( + simonaConfig.simona.runtime.participant.load.defaultConfig, + simonaConfig.simona.runtime.participant.load.individualConfigs, + defaultString + ) ) }.getMessage shouldBe "Found invalid UUID 'blabla' it was meant to be the string 'default' or a valid UUID." } @@ -499,10 +523,12 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkBaseRuntimeConfigs( - simonaConfig.simona.runtime.participant.load.defaultConfig, - simonaConfig.simona.runtime.participant.load.individualConfigs, - defaultString + ConfigFailFast.invokePrivate( + checkBaseRuntimeConfigs( + simonaConfig.simona.runtime.participant.load.defaultConfig, + simonaConfig.simona.runtime.participant.load.individualConfigs, + defaultString + ) ) }.getMessage shouldBe s"Found invalid UUID 'blabla' it was meant to be the string 'default' or a valid UUID." } @@ -525,10 +551,12 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkBaseRuntimeConfigs( - simonaConfig.simona.runtime.participant.load.defaultConfig, - simonaConfig.simona.runtime.participant.load.individualConfigs, - defaultString + ConfigFailFast.invokePrivate( + checkBaseRuntimeConfigs( + simonaConfig.simona.runtime.participant.load.defaultConfig, + simonaConfig.simona.runtime.participant.load.individualConfigs, + defaultString + ) ) }.getMessage shouldBe "The scaling factor for system participants with UUID '49f250fa-41ff-4434-a083-79c98d260a76' may not be negative." } @@ -566,10 +594,12 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkBaseRuntimeConfigs( - simonaConfig.simona.runtime.participant.load.defaultConfig, - simonaConfig.simona.runtime.participant.load.individualConfigs, - defaultString + ConfigFailFast.invokePrivate( + checkBaseRuntimeConfigs( + simonaConfig.simona.runtime.participant.load.defaultConfig, + simonaConfig.simona.runtime.participant.load.individualConfigs, + defaultString + ) ) }.getMessage shouldBe "The basic model configurations contain ambiguous definitions." } @@ -599,8 +629,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkSpecificLoadModelConfig( - simonaConfig.simona.runtime.participant.load.defaultConfig + ConfigFailFast.invokePrivate( + checkSpecificLoadModelConfig( + simonaConfig.simona.runtime.participant.load.defaultConfig + ) ) }.getMessage shouldBe "The load model behaviour 'blabla' for the loads with UUIDs '49f250fa-41ff-4434-a083-79c98d260a76' is invalid." } @@ -623,8 +655,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkSpecificLoadModelConfig( - simonaConfig.simona.runtime.participant.load.defaultConfig + ConfigFailFast.invokePrivate( + checkSpecificLoadModelConfig( + simonaConfig.simona.runtime.participant.load.defaultConfig + ) ) }.getMessage shouldBe "The standard load profile reference 'blabla' for the loads with UUIDs '49f250fa-41ff-4434-a083-79c98d260a76' is invalid." } @@ -650,8 +684,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val simonaConfig = SimonaConfig(config) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkRuntimeListenerConfiguration( - simonaConfig.simona.runtime.listener + ConfigFailFast.invokePrivate( + checkRuntimeListenerConfiguration( + simonaConfig.simona.runtime.listener + ) ) }.getMessage shouldBe "Connection with kafka broker localhost:12345 failed." } @@ -663,15 +699,17 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "identify faulty notifier identifiers" in { intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkNotifierIdentifier("whatever") + ConfigFailFast.invokePrivate(checkNotifierIdentifier("whatever")) }.getMessage shouldBe s"The identifier 'whatever' you provided is not valid. Valid input: ${NotifierIdentifier.values.map(_.toString).mkString(",")}" } "let all valid notifier identifiers pass" in { noException shouldBe thrownBy { NotifierIdentifier.values.map(id => - ConfigFailFast invokePrivate checkNotifierIdentifier( - id.toString + ConfigFailFast.invokePrivate( + checkNotifierIdentifier( + id.toString + ) ) ) } @@ -702,8 +740,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkIndividualParticipantsOutputConfigs( - validInput + ConfigFailFast.invokePrivate( + checkIndividualParticipantsOutputConfigs( + validInput + ) ) } } @@ -728,8 +768,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) intercept[InvalidConfigParameterException]( - ConfigFailFast invokePrivate checkIndividualParticipantsOutputConfigs( - invalidInput + ConfigFailFast.invokePrivate( + checkIndividualParticipantsOutputConfigs( + invalidInput + ) ) ).getMessage shouldBe "There are multiple output configurations for participant types 'load'." } @@ -740,18 +782,20 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "throw an exception if no sink is provided" in { intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkDataSink(Sink(None, None, None)) + ConfigFailFast.invokePrivate(checkDataSink(Sink(None, None, None))) }.getLocalizedMessage shouldBe "No sink configuration found! Please ensure that at least " + "one sink is configured! You can choose from: influxdb1x, csv, kafka." } "throw an exception if more than one sink is provided" in { intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkDataSink( - Sink( - Some(Csv("", "", "", isHierarchic = false)), - Some(InfluxDb1x("", 0, "")), - None + ConfigFailFast.invokePrivate( + checkDataSink( + Sink( + Some(Csv("", "", "", isHierarchic = false)), + Some(InfluxDb1x("", 0, "")), + None + ) ) ) }.getLocalizedMessage shouldBe "Multiple sink configurations are not supported! Please ensure that only " + @@ -760,8 +804,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "throw an exception if an influxDb1x is configured, but not accessible" ignore { intercept[java.lang.IllegalArgumentException] { - ConfigFailFast invokePrivate checkDataSink( - Sink(None, Some(InfluxDb1x("", 0, "")), None) + ConfigFailFast.invokePrivate( + checkDataSink( + Sink(None, Some(InfluxDb1x("", 0, "")), None) + ) ) }.getLocalizedMessage shouldBe "Unable to reach configured influxDb1x with url ':0' for 'Sink' configuration and database ''. " + "Exception: java.lang.IllegalArgumentException: Unable to parse url: :0" @@ -769,17 +815,19 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { "throw an exception if kafka is configured, but connection to broker fails" in { intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkDataSink( - Sink( - None, - None, - Some( - ResultKafkaParams( - "localhost:12345", - 0, - "00000000-0000-0000-0000-000000000000", - "https://reg:123", - "topic" + ConfigFailFast.invokePrivate( + checkDataSink( + Sink( + None, + None, + Some( + ResultKafkaParams( + "localhost:12345", + 0, + "00000000-0000-0000-0000-000000000000", + "https://reg:123", + "topic" + ) ) ) ) @@ -861,7 +909,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkGridDataSource(gridDataSource) + ConfigFailFast.invokePrivate(checkGridDataSource(gridDataSource)) }.getMessage shouldBe "No grid data source information provided! Cannot proceed!" } @@ -872,7 +920,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkGridDataSource(gridDataSource) + ConfigFailFast.invokePrivate(checkGridDataSource(gridDataSource)) }.getMessage shouldBe "The provided grid data source 'someWhereUndefined' is not supported!" } @@ -883,7 +931,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkGridDataSource(gridDataSource) + ConfigFailFast.invokePrivate(checkGridDataSource(gridDataSource)) }.getMessage shouldBe "No grid data source csv parameters provided. If you intend to read grid data from " + ".csv-files, please provide .csv parameters!" } @@ -901,7 +949,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkGridDataSource(gridDataSource) + ConfigFailFast.invokePrivate(checkGridDataSource(gridDataSource)) } } } @@ -938,8 +986,10 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { Some("yyyy-MM-dd HH:mm") ) intercept[InvalidConfigParameterException] { - ConfigFailFast invokePrivate checkWeatherDataSource( - weatherDataSource + ConfigFailFast.invokePrivate( + checkWeatherDataSource( + weatherDataSource + ) ) }.getMessage shouldBe "The weather data scheme 'this won't work' is not supported. Supported schemes:\n\ticon\n\tcosmo" } @@ -955,7 +1005,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val maliciousConfig = ConfigFactory.parseString("") noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkPekkoLoggers(maliciousConfig) + ConfigFailFast.invokePrivate(checkPekkoLoggers(maliciousConfig)) } /* Testing the log message cannot be tested, as with LazyLogging, the logger of the class cannot be spied. */ } @@ -969,7 +1019,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkPekkoLoggers(properConfig) + ConfigFailFast.invokePrivate(checkPekkoLoggers(properConfig)) } /* Testing the log message cannot be tested, as with LazyLogging, the logger of the class cannot be spied. */ } @@ -982,7 +1032,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { val maliciousConfig = ConfigFactory.parseString("") noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkPekkoConfig(maliciousConfig) + ConfigFailFast.invokePrivate(checkPekkoConfig(maliciousConfig)) } /* Testing the log message cannot be tested, as with LazyLogging, the logger of the class cannot be spied. */ } @@ -996,7 +1046,7 @@ class ConfigFailFastSpec extends UnitSpec with ConfigTestData { ) noException shouldBe thrownBy { - ConfigFailFast invokePrivate checkPekkoConfig(properConfig) + ConfigFailFast.invokePrivate(checkPekkoConfig(properConfig)) } /* Testing the log message cannot be tested, as with LazyLogging, the logger of the class cannot be spied. */ } diff --git a/src/test/scala/edu/ie3/simona/config/RefSystemParserSpec.scala b/src/test/scala/edu/ie3/simona/config/RefSystemParserSpec.scala index be5d9b95c4..fae0f57af2 100644 --- a/src/test/scala/edu/ie3/simona/config/RefSystemParserSpec.scala +++ b/src/test/scala/edu/ie3/simona/config/RefSystemParserSpec.scala @@ -54,7 +54,7 @@ class RefSystemParserSpec extends UnitSpec { // check internal gridIdRefSystems val gridIdRefSystems = PrivateMethod[Map[Int, RefSystem]](Symbol("gridIdRefSystems")) - configRefSystems invokePrivate gridIdRefSystems() shouldBe Map( + configRefSystems.invokePrivate(gridIdRefSystems()) shouldBe Map( 1 -> configRefSystemOne, 2 -> configRefSystemOne, 3 -> configRefSystemOne, @@ -77,7 +77,7 @@ class RefSystemParserSpec extends UnitSpec { // check internal voltLvLRefSystems val voltLvLRefSystems = PrivateMethod[Map[String, RefSystem]](Symbol("voltLvLRefSystems")) - configRefSystems invokePrivate voltLvLRefSystems() shouldBe Map( + configRefSystems.invokePrivate(voltLvLRefSystems()) shouldBe Map( GermanVoltageLevelUtils.MV_10KV -> configRefSystemOne, GermanVoltageLevelUtils.MV_20KV -> configRefSystemOne, GermanVoltageLevelUtils.HV -> configRefSystemTwo, diff --git a/src/test/scala/edu/ie3/simona/event/NotifierSpec.scala b/src/test/scala/edu/ie3/simona/event/NotifierSpec.scala index a654ec289a..b733cdd512 100644 --- a/src/test/scala/edu/ie3/simona/event/NotifierSpec.scala +++ b/src/test/scala/edu/ie3/simona/event/NotifierSpec.scala @@ -11,16 +11,16 @@ import org.apache.pekko.actor.{ActorLogging, ActorRef, ActorSystem, Props} import org.apache.pekko.testkit.ImplicitSender import org.apache.pekko.util.Timeout import com.typesafe.config.ConfigFactory -import edu.ie3.datamodel.models.result.system._ +import edu.ie3.datamodel.models.result.system.* import edu.ie3.simona.event.NotifierSpec.{TestEvent, TestEventEnvelope} import edu.ie3.simona.event.notifier.Notifier import edu.ie3.simona.test.common.TestKitWithShutdown -import edu.ie3.simona.util.ConfigUtil.NotifierIdentifier._ +import edu.ie3.simona.util.ConfigUtil.NotifierIdentifier.* import edu.ie3.simona.util.EntityMapperUtil import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike -import scala.concurrent.duration._ +import scala.concurrent.duration.* import scala.language.postfixOps class NotifierSpec @@ -41,9 +41,8 @@ class NotifierSpec class NotifierActor(override val listener: Iterable[ActorRef]) extends Notifier with ActorLogging { - override def preStart(): Unit = { + override def preStart(): Unit = log.debug(s"{} started!", self) - } override def receive: Receive = { case TestEventEnvelope(testEvent, "Please notify others of this!") => @@ -63,7 +62,7 @@ class NotifierSpec val msgDate = Calendar.getInstance().getTime val msg = "Hello World" val testEvent = TestEvent(msg, msgDate) - implicit val timeout: Timeout = Timeout(5 seconds) + given timeout: Timeout = Timeout(5 seconds) notifier ! TestEventEnvelope(testEvent) expectMsg(testEvent) } diff --git a/src/test/scala/edu/ie3/simona/event/SimonaListenerSpec.scala b/src/test/scala/edu/ie3/simona/event/SimonaListenerSpec.scala index 538a4732f4..8b9e9766ae 100644 --- a/src/test/scala/edu/ie3/simona/event/SimonaListenerSpec.scala +++ b/src/test/scala/edu/ie3/simona/event/SimonaListenerSpec.scala @@ -44,17 +44,15 @@ class SimonaListenerSpec // test listenerActor class SimonaListenerActor(eventsToProcess: Option[List[String]] = None) extends SimonaListenerWithFilter(eventsToProcess) { - override def preStart(): Unit = { + override def preStart(): Unit = log.debug(s"{} started!", self) - } - override def processEvent(event: Event, sender: ActorRef): Unit = { + override def processEvent(event: Event, sender: ActorRef): Unit = event match { case TestEvent(str, date) => log.debug(s"Received '$str' from date $date") case _ => log.warning("Received unknown event") } - } } // global vals diff --git a/src/test/scala/edu/ie3/simona/event/listener/ResultEventListenerSpec.scala b/src/test/scala/edu/ie3/simona/event/listener/ResultEventListenerSpec.scala index 6f7aba992e..de6eed960c 100644 --- a/src/test/scala/edu/ie3/simona/event/listener/ResultEventListenerSpec.scala +++ b/src/test/scala/edu/ie3/simona/event/listener/ResultEventListenerSpec.scala @@ -38,7 +38,7 @@ import java.io.{File, FileInputStream} import java.util.UUID import java.util.zip.GZIPInputStream import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.duration._ +import scala.concurrent.duration.* import scala.concurrent.{Await, Future} import scala.io.Source import scala.language.postfixOps @@ -56,7 +56,7 @@ class ResultEventListenerSpec with ThreeWindingResultTestData with Transformer3wResultSupport { val simulationName = "testSim" - val resultEntitiesToBeWritten: Set[Class[_ <: ResultEntity]] = Set( + val resultEntitiesToBeWritten: Set[Class[? <: ResultEntity]] = Set( classOf[PvResult], classOf[NodeResult], classOf[Transformer2WResult], @@ -71,7 +71,7 @@ class ResultEventListenerSpec private def resultFileHierarchy( runId: Int, fileFormat: String, - classes: Set[Class[_ <: ResultEntity]] = resultEntitiesToBeWritten + classes: Set[Class[? <: ResultEntity]] = resultEntitiesToBeWritten ): ResultFileHierarchy = ResultFileHierarchy( outputDir = testTmpDir + File.separator + runId, @@ -91,7 +91,7 @@ class ResultEventListenerSpec Symbol("initializeSinks") ) - ResultEventListener invokePrivate initializeSinks(resultFileHierarchy) + ResultEventListener.invokePrivate(initializeSinks(resultFileHierarchy)) } private def getFileLinesLength(file: File) = { @@ -141,7 +141,7 @@ class ResultEventListenerSpec ) listener ! StopMessage(true) - deathWatch expectTerminated (listener, 10 seconds) + deathWatch.expectTerminated(listener, 10 seconds) } } diff --git a/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerKafkaSpec.scala b/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerKafkaSpec.scala index 1cfda26aa6..7d33804083 100644 --- a/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerKafkaSpec.scala +++ b/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerKafkaSpec.scala @@ -24,9 +24,9 @@ import org.scalatest.GivenWhenThen import org.scalatest.prop.TableDrivenPropertyChecks import java.util.UUID -import scala.concurrent.duration._ -import scala.jdk.CollectionConverters._ -import scala.jdk.DurationConverters._ +import scala.concurrent.duration.* +import scala.jdk.CollectionConverters.* +import scala.jdk.DurationConverters.* import scala.language.postfixOps class RuntimeEventListenerKafkaSpec @@ -37,7 +37,7 @@ class RuntimeEventListenerKafkaSpec with TableDrivenPropertyChecks { private var testConsumer: KafkaConsumer[Bytes, SimonaEndMessage] = _ - private implicit lazy val resultFormat: RecordFormat[SimonaEndMessage] = + given resultFormat: RecordFormat[SimonaEndMessage] = RecordFormat[SimonaEndMessage] private val deserializer: Deserializer[SimonaEndMessage] = ScalaReflectionSerde.reflectionDeserializer4S[SimonaEndMessage] @@ -133,7 +133,7 @@ class RuntimeEventListenerKafkaSpec testConsumer.poll((1 second) toJava).asScala.map(_.value()).toList } - records should have length 1 + (records should have).length(1) records should contain(expectedMsg) } diff --git a/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerSpec.scala b/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerSpec.scala index 22ef952a8a..d29d1f78dc 100644 --- a/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerSpec.scala +++ b/src/test/scala/edu/ie3/simona/event/listener/RuntimeEventListenerSpec.scala @@ -24,7 +24,7 @@ import edu.ie3.simona.event.RuntimeEvent.{ Ready, Simulating } -import edu.ie3.simona.util.TickUtil._ +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.TimeUtil import org.scalatest.PrivateMethodTester import org.scalatest.matchers.should @@ -81,7 +81,7 @@ class RuntimeEventListenerSpec Error(errMsg) ) - for (event <- eventsToQueue) { + for event <- eventsToQueue do { listenerRef ! event val actualEvent = eventQueue.poll(10, TimeUnit.SECONDS) actualEvent match { @@ -97,13 +97,12 @@ class RuntimeEventListenerSpec "return valid log messages for each status event" in { - def calcTime(curTick: Long): String = { + def calcTime(curTick: Long): String = TimeUtil.withDefaults.toString( curTick.toDateTime( TimeUtil.withDefaults.toZonedDateTime(startDateTimeString) ) ) - } // Fail two power flows, should get counted listenerRef ! PowerFlowFailed diff --git a/src/test/scala/edu/ie3/simona/integration/RunSimonaStandaloneIT.scala b/src/test/scala/edu/ie3/simona/integration/RunSimonaStandaloneIT.scala index 39e6aaa368..afb5f20c04 100644 --- a/src/test/scala/edu/ie3/simona/integration/RunSimonaStandaloneIT.scala +++ b/src/test/scala/edu/ie3/simona/integration/RunSimonaStandaloneIT.scala @@ -13,7 +13,7 @@ import edu.ie3.datamodel.models.result.ResultEntity import edu.ie3.datamodel.models.result.system.PvResult import edu.ie3.simona.config.{ConfigFailFast, SimonaConfig} import edu.ie3.simona.event.RuntimeEvent -import edu.ie3.simona.event.RuntimeEvent._ +import edu.ie3.simona.event.RuntimeEvent.* import edu.ie3.simona.integration.common.IntegrationSpecCommon import edu.ie3.simona.main.RunSimonaStandalone import edu.ie3.simona.sim.setup.SimonaStandaloneSetup @@ -23,7 +23,7 @@ import edu.ie3.util.io.FileIOUtils import org.scalatest.BeforeAndAfterAll import scala.io.{BufferedSource, Source} -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* class RunSimonaStandaloneIT extends IntegrationSpecCommon @@ -31,9 +31,8 @@ class RunSimonaStandaloneIT with BeforeAndAfterAll with IOTestCommons { - override def afterAll(): Unit = { + override def afterAll(): Unit = FileIOUtils.deleteRecursively(testTmpDir) - } "A simona standalone simulation" must { @@ -113,15 +112,14 @@ class RunSimonaStandaloneIT private def getFileSource( resultFileHierarchy: ResultFileHierarchy, - entityClass: Class[_ <: ResultEntity] - ): BufferedSource = { + entityClass: Class[? <: ResultEntity] + ): BufferedSource = Source.fromFile( resultFileHierarchy.rawOutputDataFilePaths.getOrElse( entityClass, fail(s"Unable to get output path for result entity: $entityClass") ) ) - } private def checkRuntimeEvents( runtimeEvents: Iterable[RuntimeEvent] @@ -137,18 +135,24 @@ class RunSimonaStandaloneIT } groupedRuntimeEvents.size shouldBe 5 - groupedRuntimeEvents.keySet should contain allOf (Simulating, CheckWindowPassed, InitComplete, Initializing, Done) + (groupedRuntimeEvents.keySet should contain).allOf( + Simulating, + CheckWindowPassed, + InitComplete, + Initializing, + Done + ) groupedRuntimeEvents .get(Simulating) - .foreach(simulatingEvents => { + .foreach { simulatingEvents => simulatingEvents.size shouldBe 1 simulatingEvents.headOption.foreach(_ shouldBe Simulating(0, 7200)) - }) + } groupedRuntimeEvents .get(CheckWindowPassed) - .foreach(checkWindowsPassed => { + .foreach { checkWindowsPassed => checkWindowsPassed.size shouldBe 7 checkWindowsPassed.foreach { case CheckWindowPassed(tick, _) => @@ -158,23 +162,19 @@ class RunSimonaStandaloneIT s"Invalid event when expecting CheckWindowPassed: $invalidEvent" ) } - }) + } groupedRuntimeEvents .get(InitComplete) - .foreach(initComplets => { - initComplets.size shouldBe 1 - }) + .foreach(initComplets => initComplets.size shouldBe 1) groupedRuntimeEvents .get(Initializing) - .foreach(initializings => { - initializings.size shouldBe 1 - }) + .foreach(initializings => initializings.size shouldBe 1) groupedRuntimeEvents .get(Done) - .foreach(dones => { + .foreach { dones => dones.size shouldBe 1 dones.headOption.foreach { case Done(tick, _, errorInSim) => @@ -183,7 +183,7 @@ class RunSimonaStandaloneIT case invalidEvent => fail(s"Invalid event when expecting Done: $invalidEvent") } - }) + } } } diff --git a/src/test/scala/edu/ie3/simona/io/file/ResultFileHierarchySpec.scala b/src/test/scala/edu/ie3/simona/io/file/ResultFileHierarchySpec.scala index e871b4ffb7..a750707dd0 100644 --- a/src/test/scala/edu/ie3/simona/io/file/ResultFileHierarchySpec.scala +++ b/src/test/scala/edu/ie3/simona/io/file/ResultFileHierarchySpec.scala @@ -29,10 +29,9 @@ class ResultFileHierarchySpec mainDir + fileSeparator + "output" + fileSeparator + "vn_simona" val runOutputDir = "vn_simona_test" - override def afterAll(): Unit = { + override def afterAll(): Unit = // delete created directories FileIOUtils.deleteRecursively(parentOutputFilePath) - } "A valid OutputFileHierarchy" should { @@ -85,7 +84,7 @@ class ResultFileHierarchySpec "write directories automatically on instantiation when requested so" in { // delete file if they exist - if (Files.exists(parentOutputFilePath)) + if Files.exists(parentOutputFilePath) then FileIOUtils.deleteRecursively(parentOutputFilePath) // init output file hierarchy with writing @@ -133,10 +132,9 @@ class ResultFileHierarchySpec } - private def relativizePath(fullPath: String): Path = { + private def relativizePath(fullPath: String): Path = new File(new File("").getAbsolutePath).toPath .relativize(new File(fullPath).toPath) - } // todo output model path config compression should always be disabled -> test for this diff --git a/src/test/scala/edu/ie3/simona/io/result/ResultEntityKafkaSpec.scala b/src/test/scala/edu/ie3/simona/io/result/ResultEntityKafkaSpec.scala index 9edf05b5ee..aa537543a8 100644 --- a/src/test/scala/edu/ie3/simona/io/result/ResultEntityKafkaSpec.scala +++ b/src/test/scala/edu/ie3/simona/io/result/ResultEntityKafkaSpec.scala @@ -30,9 +30,9 @@ import tech.units.indriya.quantity.Quantities import java.time.ZonedDateTime import java.util.UUID -import scala.concurrent.duration._ -import scala.jdk.CollectionConverters._ -import scala.jdk.DurationConverters._ +import scala.concurrent.duration.* +import scala.jdk.CollectionConverters.* +import scala.jdk.DurationConverters.* import scala.language.postfixOps /** Adapted from @@ -47,7 +47,7 @@ class ResultEntityKafkaSpec private var testConsumer: KafkaConsumer[Bytes, PlainNodeResult] = _ - private implicit lazy val resultFormat: RecordFormat[PlainNodeResult] = + given resultFormat: RecordFormat[PlainNodeResult] = RecordFormat[PlainNodeResult] private val deserializer: Deserializer[PlainNodeResult] = ScalaReflectionSerde.reflectionDeserializer4S[PlainNodeResult] @@ -147,7 +147,7 @@ class ResultEntityKafkaSpec val records: List[PlainNodeResult] = testConsumer.poll((1 second) toJava).asScala.map(_.value()).toList - records should have length 3 + (records should have).length(3) records should contain( PlainNodeResult( runId, diff --git a/src/test/scala/edu/ie3/simona/model/assets/control/QControlSpec.scala b/src/test/scala/edu/ie3/simona/model/assets/control/QControlSpec.scala index 23676e71ca..3144e0ca80 100644 --- a/src/test/scala/edu/ie3/simona/model/assets/control/QControlSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/assets/control/QControlSpec.scala @@ -9,8 +9,8 @@ package edu.ie3.simona.model.assets.control import edu.ie3.datamodel.models.input.system.characteristic import edu.ie3.datamodel.models.input.system.characteristic.{ CharacteristicPoint, - CosPhiP => CosPhiPInput, - QV => QVInput + CosPhiP as CosPhiPInput, + QV as QVInput } import edu.ie3.simona.exceptions.QControlException import edu.ie3.simona.model.participant.control.QControl @@ -21,11 +21,11 @@ import edu.ie3.simona.model.participant.control.QControl.{ } import edu.ie3.simona.model.system.Characteristic.XYPair import edu.ie3.simona.test.common.UnitSpec -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.quantities.{Megavars, ReactivePower} import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor2} import squants.Each -import tech.units.indriya.quantity.Quantities._ +import tech.units.indriya.quantity.Quantities.* import java.util import javax.measure.quantity.Dimensionless @@ -34,8 +34,8 @@ import scala.collection.immutable.TreeSet class QControlSpec extends UnitSpec with TableDrivenPropertyChecks { private val defaultTolerance = 1e-12 - private implicit val reactivePowerTolerance: ReactivePower = Megavars(1e-12) - private implicit val tolerance: squants.Dimensionless = Each(1e-12) + given reactivePowerTolerance: ReactivePower = Megavars(1e-12) + given tolerance: squants.Dimensionless = Each(1e-12) val validCosPhiPInput: characteristic.CosPhiP = new CosPhiPInput( "cosPhiP:{(0.0,-1.0),(0.5,-0.8),(1.0,-0.2)}" @@ -48,9 +48,8 @@ class QControlSpec extends UnitSpec with TableDrivenPropertyChecks { def createXYPair( d1: Double, d2: Double - ): XYPair[squants.Dimensionless, squants.Dimensionless] = { + ): XYPair[squants.Dimensionless, squants.Dimensionless] = XYPair(Each(d1), Each(d2)) - } "A valid QControl object" should { "throw an exception, if the provided fixed power factor input has more than one coordinate" in { diff --git a/src/test/scala/edu/ie3/simona/model/grid/GridSpec.scala b/src/test/scala/edu/ie3/simona/model/grid/GridSpec.scala index 3b73c59dfd..871d26d87c 100644 --- a/src/test/scala/edu/ie3/simona/model/grid/GridSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/grid/GridSpec.scala @@ -27,22 +27,20 @@ class GridSpec extends UnitSpec with LineInputTestData with DefaultTestData { private val _printAdmittanceMatrixOnMismatch : (DenseMatrix[Complex], DenseMatrix[Complex]) => Unit = { (actualMatrix, expectedMatrix) => - if (!actualMatrix.equals(expectedMatrix)) { - for ( - rowIdx <- 0 until expectedMatrix.rows; + if !actualMatrix.equals(expectedMatrix) then { + for + rowIdx <- 0 until expectedMatrix.rows colIdx <- 0 until expectedMatrix.rows - ) { - if ( - abs( + do + if abs( actualMatrix.valueAt(rowIdx, colIdx) - expectedMatrix .valueAt(rowIdx, colIdx) ) > 1e-12 - ) + then logger.debug( s"Mismatch in ($rowIdx, $colIdx): Actual = ${actualMatrix .valueAt(rowIdx, colIdx)}, expected = ${expectedMatrix.valueAt(rowIdx, colIdx)}" ) - } } } @@ -69,17 +67,21 @@ class GridSpec extends UnitSpec with LineInputTestData with DefaultTestData { LineModel ) => (Int, Int, Complex, Complex, Complex) = (nodeUuidToIndexMap, line) => - GridModel invokePrivate getLinesAdmittanceMethod( - nodeUuidToIndexMap, - line + GridModel.invokePrivate( + getLinesAdmittanceMethod( + nodeUuidToIndexMap, + line + ) ) // result of method call val actualResult: DenseMatrix[Complex] = - GridModel invokePrivate buildAssetAdmittanceMatrix( - nodeUuidToIndexMap, - lines, - getLinesAdmittance + GridModel.invokePrivate( + buildAssetAdmittanceMatrix( + nodeUuidToIndexMap, + lines, + getLinesAdmittance + ) ) _printAdmittanceMatrixOnMismatch(actualResult, lineAdmittanceMatrix) @@ -166,11 +168,13 @@ class GridSpec extends UnitSpec with LineInputTestData with DefaultTestData { .reduceOption(_ + _) .getOrElse(Complex.zero) - admittanceMatixClosed.valueAt( + (admittanceMatixClosed.valueAt( iClosed, jClosed - ) shouldBe sumOfAdmittancesOpenSwitches withClue s" at \n\tposition ($iClosed, $jClosed) of the grid with closed switches/" + - s"\n\tpositions (${iOpenAll.mkString(",")}) x (${jOpenAll.mkString(",")}) of the grid with open switches" + ) shouldBe sumOfAdmittancesOpenSwitches).withClue( + s" at \n\tposition ($iClosed, $jClosed) of the grid with closed switches/" + + s"\n\tpositions (${iOpenAll.mkString(",")}) x (${jOpenAll.mkString(",")}) of the grid with open switches" + ) } } @@ -210,7 +214,7 @@ class GridSpec extends UnitSpec with LineInputTestData with DefaultTestData { val validateConnectivity: PrivateMethod[Unit] = PrivateMethod[Unit](Symbol("validateConnectivity")) - GridModel invokePrivate validateConnectivity(gridModel) + GridModel.invokePrivate(validateConnectivity(gridModel)) } @@ -241,7 +245,7 @@ class GridSpec extends UnitSpec with LineInputTestData with DefaultTestData { val exception: GridInconsistencyException = intercept[GridInconsistencyException] { - GridModel invokePrivate validateConnectivity(gridModel) + GridModel.invokePrivate(validateConnectivity(gridModel)) } exception.getMessage shouldBe "The grid with subnetNo 1 is not connected! Please ensure that all elements are connected correctly and inOperation is set to true!" @@ -286,7 +290,7 @@ class GridSpec extends UnitSpec with LineInputTestData with DefaultTestData { // call the validation method val exception: InvalidGridException = intercept[InvalidGridException] { - GridModel invokePrivate validateConsistency(gridModel) + GridModel.invokePrivate(validateConsistency(gridModel)) } // expect an exception for node 13 diff --git a/src/test/scala/edu/ie3/simona/model/grid/LineSpec.scala b/src/test/scala/edu/ie3/simona/model/grid/LineSpec.scala index baebd2efe3..661f18bbd1 100644 --- a/src/test/scala/edu/ie3/simona/model/grid/LineSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/grid/LineSpec.scala @@ -11,12 +11,12 @@ import edu.ie3.datamodel.exceptions.InvalidGridException import edu.ie3.simona.test.common.UnitSpec import edu.ie3.simona.test.common.input.LineInputTestData import edu.ie3.simona.test.common.model.grid.FiveLinesWithNodes -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.OperationInterval import squants.Each import squants.electro.{Amperes, Kilovolts} import squants.energy.Kilowatts -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.util.UUID @@ -24,8 +24,8 @@ import java.util.UUID */ class LineSpec extends UnitSpec with LineInputTestData { - implicit val dimensionlessTolerance: squants.Dimensionless = Each(1e-12) - implicit val electricCurrentTolerance: squants.electro.ElectricCurrent = + given dimensionlessTolerance: squants.Dimensionless = Each(1e-12) + given electricCurrentTolerance: squants.electro.ElectricCurrent = Amperes(1e-12) sealed trait ValidLineModel { diff --git a/src/test/scala/edu/ie3/simona/model/grid/NodeInputModelSpec.scala b/src/test/scala/edu/ie3/simona/model/grid/NodeInputModelSpec.scala index 4f6f89a0a8..579eb96aa8 100644 --- a/src/test/scala/edu/ie3/simona/model/grid/NodeInputModelSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/grid/NodeInputModelSpec.scala @@ -13,7 +13,7 @@ import edu.ie3.simona.test.common.model.grid.FiveLinesWithNodes import squants.Each class NodeInputModelSpec extends UnitSpec with NodeInputTestData { - implicit val dimensionlessTolerance: squants.Dimensionless = Each(1e-12) + given dimensionlessTolerance: squants.Dimensionless = Each(1e-12) "A valid NodeInputModel" should { diff --git a/src/test/scala/edu/ie3/simona/model/grid/Transformer3wModelSpec.scala b/src/test/scala/edu/ie3/simona/model/grid/Transformer3wModelSpec.scala index e5082e6a3b..035912228a 100644 --- a/src/test/scala/edu/ie3/simona/model/grid/Transformer3wModelSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/grid/Transformer3wModelSpec.scala @@ -15,7 +15,7 @@ import edu.ie3.simona.model.grid.Transformer3wPowerFlowCase.{ } import edu.ie3.simona.test.common.UnitSpec import edu.ie3.simona.test.common.input.Transformer3wTestData -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor4} import squants.Each import tech.units.indriya.quantity.Quantities @@ -27,7 +27,7 @@ class Transformer3wModelSpec with TableDrivenPropertyChecks with Transformer3wTestData { val testingTolerance = 1e-5 - implicit val dimensionlessTolerance: squants.Dimensionless = Each(1e-8) + given dimensionlessTolerance: squants.Dimensionless = Each(1e-8) "A three winding transformer input model" should { "be validated without an exception from a valid input model" in { @@ -101,7 +101,7 @@ class Transformer3wModelSpec transformerModel, Transformer3wModel.Transformer3wPort.INTERNAL ) - implicit val doubleTolerance: Double = 1e-11 + given doubleTolerance: Double = 1e-11 yjj.real shouldBe 1.874312e-6 +- doubleTolerance yjj.imag shouldBe -75.012912e-6 +- doubleTolerance val yij: Complex = Transformer3wModel.yij(transformerModel) @@ -179,7 +179,7 @@ class Transformer3wModelSpec yjj shouldBe Complex.zero val yij: Complex = Transformer3wModel.yij(transformerModel) - implicit val doubleTolerance: Double = testingTolerance + given doubleTolerance: Double = testingTolerance yij.real shouldBe 385.773e-3 +- doubleTolerance yij.imag shouldBe -40.007364 +- doubleTolerance } @@ -253,7 +253,7 @@ class Transformer3wModelSpec ) yjj shouldBe Complex.zero val yij: Complex = Transformer3wModel.yij(transformerModel) - implicit val doubleTolerance: Double = testingTolerance + given doubleTolerance: Double = testingTolerance yij.real shouldBe 10.301007 +- doubleTolerance yij.imag shouldBe -1798.197528 +- doubleTolerance } @@ -349,9 +349,9 @@ class Transformer3wModelSpec defaultSimulationEnd ) - transformerModelEhvTemp invokePrivate tapRatio() shouldBe 1.15 - transformerModelHvTemp invokePrivate tapRatio() shouldBe 1.0 - transformerModelLvTemp invokePrivate tapRatio() shouldBe 1.0 + transformerModelEhvTemp.invokePrivate(tapRatio()) shouldBe 1.15 + transformerModelHvTemp.invokePrivate(tapRatio()) shouldBe 1.0 + transformerModelLvTemp.invokePrivate(tapRatio()) shouldBe 1.0 } } @@ -385,32 +385,32 @@ class Transformer3wModelSpec PrivateMethod[Double](Symbol("tapRatio")) transformerModel.currentTapPos shouldBe 0 - transformerModel invokePrivate tapRatio() shouldBe 1.0 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.0 transformerModel.incrTapPos() transformerModel.currentTapPos shouldBe 1 - transformerModel invokePrivate tapRatio() shouldBe 1.015 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.015 transformerModel.incrTapPos(4) transformerModel.currentTapPos shouldBe 5 - transformerModel invokePrivate tapRatio() shouldBe 1.075 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.075 transformerModel.updateTapPos(6) transformerModel.currentTapPos shouldBe 6 - transformerModel invokePrivate tapRatio() shouldBe 1.09 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.09 transformerModel.decrTapPos() transformerModel.currentTapPos shouldBe 5 - transformerModel invokePrivate tapRatio() shouldBe 1.075 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.075 transformerModel.decrTapPos(3) transformerModel.currentTapPos shouldBe 2 - transformerModel invokePrivate tapRatio() shouldBe 1.03 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.03 } "dislike altering the tap position in power flow case B" in new Transformer3wTestData { @@ -419,7 +419,7 @@ class Transformer3wModelSpec PrivateMethod[Double](Symbol("tapRatio")) transformerModel.currentTapPos shouldBe 0 - transformerModel invokePrivate tapRatio() shouldBe 1.0 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.0 val thrownOnIncrease: InvalidActionRequestException = intercept[InvalidActionRequestException] { @@ -427,7 +427,7 @@ class Transformer3wModelSpec } thrownOnIncrease.getMessage shouldBe s"Increasing tap position for transformer3w ${transformerModel.uuid} is not allowed in power flow case B and C." transformerModel.currentTapPos shouldBe 0 - transformerModel invokePrivate tapRatio() shouldBe 1.0 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.0 val thrownOnDecrease: InvalidActionRequestException = intercept[InvalidActionRequestException] { @@ -435,7 +435,7 @@ class Transformer3wModelSpec } thrownOnDecrease.getMessage shouldBe s"Decreasing tap position for transformer3w ${transformerModel.uuid} is not allowed in power flow case B and C." transformerModel.currentTapPos shouldBe 0 - transformerModel invokePrivate tapRatio() shouldBe 1.0 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.0 val thrownOnUpdate: InvalidActionRequestException = intercept[InvalidActionRequestException] { @@ -443,7 +443,7 @@ class Transformer3wModelSpec } thrownOnUpdate.getMessage shouldBe s"Updating tap position for transformer3w ${transformerModel.uuid} is not allowed in power flow case B and C." transformerModel.currentTapPos shouldBe 0 - transformerModel invokePrivate tapRatio() shouldBe 1.0 + transformerModel.invokePrivate(tapRatio()) shouldBe 1.0 } "should compute valid delta tap positions" in new Transformer3wTestData { @@ -475,14 +475,12 @@ class Transformer3wModelSpec deadBandVal: Double, expected: Int ) => - { - val vChange = Quantities.getQuantity(vChangeVal, PU) - val deadBand = Quantities.getQuantity(deadBandVal, PU) - - transformerModel.updateTapPos(currentTapPos) - val actual = transformerModel.computeDeltaTap(vChange, deadBand) - actual should be(expected) - } + val vChange = Quantities.getQuantity(vChangeVal, PU) + val deadBand = Quantities.getQuantity(deadBandVal, PU) + + transformerModel.updateTapPos(currentTapPos) + val actual = transformerModel.computeDeltaTap(vChange, deadBand) + actual should be(expected) } } @@ -495,31 +493,29 @@ class Transformer3wModelSpec yiiExpected: Complex, yjjExpected: Complex ) => - { - transformer.updateTapPos(tapPos) - val yijActual = Transformer3wModel.yij(transformer) - val yiiActual = Transformer3wModel.y0( + transformer.updateTapPos(tapPos) + val yijActual = Transformer3wModel.yij(transformer) + val yiiActual = Transformer3wModel.y0( + transformer, + Transformer3wModel.Transformer3wPort.A + ) + val yjjActual = + Transformer3wModel.y0( transformer, - Transformer3wModel.Transformer3wPort.A + Transformer3wModel.Transformer3wPort.INTERNAL ) - val yjjActual = - Transformer3wModel.y0( - transformer, - Transformer3wModel.Transformer3wPort.INTERNAL - ) - - /* Remark: This is not really precise. At the moment, double-based calculations do - * hinder us from being more precise. Maybe it is advisory to switch over to BigDecimal */ - implicit val doubleTolerance: Double = 1e-4 - yijActual.real shouldBe yijExpected.real +- doubleTolerance - yijActual.imag shouldBe yijExpected.imag +- doubleTolerance - - yiiActual.real shouldBe yiiExpected.real +- doubleTolerance - yiiActual.imag shouldBe yiiExpected.imag +- doubleTolerance - - yjjActual.real shouldBe yjjExpected.real +- doubleTolerance - yjjActual.imag shouldBe yjjExpected.imag +- doubleTolerance - } + + /* Remark: This is not really precise. At the moment, double-based calculations do + * hinder us from being more precise. Maybe it is advisory to switch over to BigDecimal */ + given doubleTolerance: Double = 1e-4 + yijActual.real shouldBe yijExpected.real +- doubleTolerance + yijActual.imag shouldBe yijExpected.imag +- doubleTolerance + + yiiActual.real shouldBe yiiExpected.real +- doubleTolerance + yiiActual.imag shouldBe yiiExpected.imag +- doubleTolerance + + yjjActual.real shouldBe yjjExpected.real +- doubleTolerance + yjjActual.imag shouldBe yjjExpected.imag +- doubleTolerance } } diff --git a/src/test/scala/edu/ie3/simona/model/grid/TransformerModelSpec.scala b/src/test/scala/edu/ie3/simona/model/grid/TransformerModelSpec.scala index f69c0e4fb3..7a2ad595d7 100644 --- a/src/test/scala/edu/ie3/simona/model/grid/TransformerModelSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/grid/TransformerModelSpec.scala @@ -24,13 +24,13 @@ import edu.ie3.simona.test.common.model.grid.{ TransformerTestData, TransformerTestGrid } -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor4} import squants.Each import squants.electro.{Amperes, Kilovolts} import squants.energy.Kilowatts import tech.units.indriya.quantity.Quantities -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.time.ZonedDateTime import java.time.temporal.ChronoUnit @@ -39,9 +39,9 @@ import java.util.UUID class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { val quantityTolerance: Double = 1e-5 val testingTolerancePf = 1e-9 - implicit val electricCurrentTolerance: squants.electro.ElectricCurrent = + given electricCurrentTolerance: squants.electro.ElectricCurrent = Amperes(1e-9) - implicit val dimensionlessTolerance: squants.Dimensionless = Each(1e-9) + given dimensionlessTolerance: squants.Dimensionless = Each(1e-9) def mainRefSystem: RefSystem = { val nominalPower = Kilowatts(400d) @@ -72,12 +72,9 @@ class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { inputModel.getType.getTapMax, inputModel.getType.getTapMin, inputModel.getType.getTapNeutr, - inputModel.isAutoTap, { - if (inputModel.getType.isTapSide) - ConnectorPort.B - else - ConnectorPort.A - } + inputModel.isAutoTap, + if inputModel.getType.isTapSide then ConnectorPort.B + else ConnectorPort.A ) val dut: TransformerModel = @@ -143,21 +140,21 @@ class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { case Complex(g, b) => (g, b) } (abs(gii - 0.0) < quantityTolerance) shouldBe true - (abs(bii - (-1.875e-3)) < quantityTolerance) shouldBe true + (abs(bii - -1.875e-3) < quantityTolerance) shouldBe true val (gjj, bjj) = TransformerModel.y0(dut, ConnectorPort.B) match { case Complex(g, b) => (g, b) } (abs(gjj - 0.0) < quantityTolerance) shouldBe true - (abs(bjj - (-1.875e-3)) < quantityTolerance) shouldBe true + (abs(bjj - -1.875e-3) < quantityTolerance) shouldBe true val (gij, bij) = TransformerModel.yij(dut) match { case Complex(g, b) => (g, b) } (abs(gij - 11.40619406) < quantityTolerance) shouldBe true - (abs(bij - (-37.68667292)) < quantityTolerance) shouldBe true + (abs(bij - -37.68667292) < quantityTolerance) shouldBe true } "result in an enabled TransformerModel if the TransformerInputModel is enabled" in new TransformerTestData { @@ -198,7 +195,7 @@ class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { defaultSimulationEnd ) - dut invokePrivate tapRatio() shouldBe 1.0 + dut.invokePrivate(tapRatio()) shouldBe 1.0 } } @@ -223,32 +220,32 @@ class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { PrivateMethod[Double](Symbol("tapRatio")) transformerModelTapHv.currentTapPos shouldBe 0 - transformerModelTapHv invokePrivate tapRatio() shouldBe 1.0 + transformerModelTapHv.invokePrivate(tapRatio()) shouldBe 1.0 transformerModelTapHv.incrTapPos() transformerModelTapHv.currentTapPos shouldBe 1 - transformerModelTapHv invokePrivate tapRatio() shouldBe 1.025 + transformerModelTapHv.invokePrivate(tapRatio()) shouldBe 1.025 transformerModelTapHv.incrTapPos(4) transformerModelTapHv.currentTapPos shouldBe 5 - transformerModelTapHv invokePrivate tapRatio() shouldBe 1.125 + transformerModelTapHv.invokePrivate(tapRatio()) shouldBe 1.125 transformerModelTapHv.updateTapPos(6) transformerModelTapHv.currentTapPos shouldBe 6 - transformerModelTapHv invokePrivate tapRatio() shouldBe 1.15 + transformerModelTapHv.invokePrivate(tapRatio()) shouldBe 1.15 transformerModelTapHv.decrTapPos() transformerModelTapHv.currentTapPos shouldBe 5 - transformerModelTapHv invokePrivate tapRatio() shouldBe 1.125 + transformerModelTapHv.invokePrivate(tapRatio()) shouldBe 1.125 transformerModelTapHv.decrTapPos(3) transformerModelTapHv.currentTapPos shouldBe 2 - transformerModelTapHv invokePrivate tapRatio() shouldBe 1.05 + transformerModelTapHv.invokePrivate(tapRatio()) shouldBe 1.05 } "should compute valid delta tap positions" in new TransformerTestGrid { @@ -278,16 +275,14 @@ class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { deadBandVal: Double, expected: Int ) => - { - val vChange = Quantities.getQuantity(vChangeVal, PU) - val deadBand = Quantities.getQuantity(deadBandVal, PU) - - transformerModelTapHv.updateTapPos(currentTapPos) - transformerModelTapHv.computeDeltaTap( - vChange, - deadBand - ) shouldBe expected - } + val vChange = Quantities.getQuantity(vChangeVal, PU) + val deadBand = Quantities.getQuantity(deadBandVal, PU) + + transformerModelTapHv.updateTapPos(currentTapPos) + transformerModelTapHv.computeDeltaTap( + vChange, + deadBand + ) shouldBe expected } } @@ -300,49 +295,47 @@ class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { yiiExpected: Complex, yjjExpected: Complex ) => - { - val transformer = tapSide match { - case ConnectorPort.A => transformerModelTapHv - case ConnectorPort.B => transformerModelTapLv - case _ => - throw new InvalidGridException( - s"Cannot find a transformer for tap side $tapSide in the basic grid" - ) + val transformer = tapSide match { + case ConnectorPort.A => transformerModelTapHv + case ConnectorPort.B => transformerModelTapLv + case _ => + throw new InvalidGridException( + s"Cannot find a transformer for tap side $tapSide in the basic grid" + ) + } + + transformer.updateTapPos(tapPos) + val (gijActual, bijActual) = + TransformerModel.yij(transformer) match { + case Complex(g, b) => (g, b) + } + val (giiActual, biiActual) = + TransformerModel.y0(transformer, ConnectorPort.A) match { + case Complex(g, b) => (g, b) + } + val (gjjActual, bjjActual) = + TransformerModel.y0(transformer, ConnectorPort.B) match { + case Complex(g, b) => (g, b) } - transformer.updateTapPos(tapPos) - val (gijActual, bijActual) = - TransformerModel.yij(transformer) match { - case Complex(g, b) => (g, b) - } - val (giiActual, biiActual) = - TransformerModel.y0(transformer, ConnectorPort.A) match { - case Complex(g, b) => (g, b) - } - val (gjjActual, bjjActual) = - TransformerModel.y0(transformer, ConnectorPort.B) match { - case Complex(g, b) => (g, b) - } - - (abs( - gijActual - yijExpected.real - ) < quantityTolerance) shouldBe true - (abs( - bijActual - yijExpected.imag - ) < quantityTolerance) shouldBe true - (abs( - giiActual - yiiExpected.real - ) < quantityTolerance) shouldBe true - (abs( - biiActual - yiiExpected.imag - ) < quantityTolerance) shouldBe true - (abs( - gjjActual - yjjExpected.real - ) < quantityTolerance) shouldBe true - (abs( - bjjActual - yjjExpected.imag - ) < quantityTolerance) shouldBe true - } + (abs( + gijActual - yijExpected.real + ) < quantityTolerance) shouldBe true + (abs( + bijActual - yijExpected.imag + ) < quantityTolerance) shouldBe true + (abs( + giiActual - yiiExpected.real + ) < quantityTolerance) shouldBe true + (abs( + biiActual - yiiExpected.imag + ) < quantityTolerance) shouldBe true + (abs( + gjjActual - yjjExpected.real + ) < quantityTolerance) shouldBe true + (abs( + bjjActual - yjjExpected.imag + ) < quantityTolerance) shouldBe true } } } @@ -364,67 +357,65 @@ class TransformerModelSpec extends UnitSpec with TableDrivenPropertyChecks { e: Double, f: Double ) => - { - logger.debug( - if (tapSide == ConnectorPort.A) - s"Test grid with transformer tap changer hat HV side at tapPos $tapPos and active power of $p p.u." - else - s"Test grid with transformer tap changer hat LV side at tapPos $tapPos and active power of $p p.u." + logger.debug( + if tapSide == ConnectorPort.A then + s"Test grid with transformer tap changer hat HV side at tapPos $tapPos and active power of $p p.u." + else + s"Test grid with transformer tap changer hat LV side at tapPos $tapPos and active power of $p p.u." + ) + + val grid = tapSide match { + case ConnectorPort.A => gridTapHv + case ConnectorPort.B => gridTapLv + case unknown => + throw new InvalidGridException( + s"Cannot test a transformer with tap changer at $unknown" + ) + } + val gridModel = GridModel( + grid, + refSystem, + defaultSimulationStart, + defaultSimulationEnd + ) + + gridModel.gridComponents.transformers + .toVector(0) + .updateTapPos(tapPos) + val admittanceMatrix = + GridModel.composeAdmittanceMatrix( + nodeUuidToIndexMap, + gridModel.gridComponents ) - val grid = tapSide match { - case ConnectorPort.A => gridTapHv - case ConnectorPort.B => gridTapLv - case unknown => - throw new InvalidGridException( - s"Cannot test a transformer with tap changer at $unknown" - ) - } - val gridModel = GridModel( - grid, - refSystem, - defaultSimulationStart, - defaultSimulationEnd + val operationPoint = + Array( + PresetData(0, NodeType.SL, Complex.zero), + PresetData(1, NodeType.PQ, Complex(p.doubleValue, 0d)) ) - gridModel.gridComponents.transformers - .toVector(0) - .updateTapPos(tapPos) - val admittanceMatrix = - GridModel.composeAdmittanceMatrix( - nodeUuidToIndexMap, - gridModel.gridComponents + val powerFlow = new NewtonRaphsonPF( + epsilon, + maxIterations, + admittanceMatrix, + Option.apply(Vector(0, 1)) + ) + val result = powerFlow.calculate(operationPoint, startData) + + result match { + case success: PowerFlowResult.SuccessFullPowerFlowResult => + val v = NodeData + .getByIndex(success.nodeData, 1) + .voltage + abs(v.real - e) < testingTolerancePf shouldBe true + abs(v.imag - f) < testingTolerancePf shouldBe true + case _: PowerFlowResult.FailedPowerFlowResult => + fail( + if tapSide == ConnectorPort.A then + s"Unable to calculate the power flow on transformer tap position $tapPos (tap changer on HV side) and active power of $p p.u." + else + s"Unable to calculate the power flow on transformer tap position $tapPos (tap changer on LV side) and active power of $p p.u." ) - - val operationPoint = - Array( - PresetData(0, NodeType.SL, Complex.zero), - PresetData(1, NodeType.PQ, Complex(p.doubleValue, 0d)) - ) - - val powerFlow = new NewtonRaphsonPF( - epsilon, - maxIterations, - admittanceMatrix, - Option.apply(Vector(0, 1)) - ) - val result = powerFlow.calculate(operationPoint, startData) - - result match { - case success: PowerFlowResult.SuccessFullPowerFlowResult => - val v = NodeData - .getByIndex(success.nodeData, 1) - .voltage - abs(v.real - e) < testingTolerancePf shouldBe true - abs(v.imag - f) < testingTolerancePf shouldBe true - case _: PowerFlowResult.FailedPowerFlowResult => - fail( - if (tapSide == ConnectorPort.A) - s"Unable to calculate the power flow on transformer tap position $tapPos (tap changer on HV side) and active power of $p p.u." - else - s"Unable to calculate the power flow on transformer tap position $tapPos (tap changer on LV side) and active power of $p p.u." - ) - } } } } diff --git a/src/test/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatSpec.scala b/src/test/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatSpec.scala index e3788071bd..3226bb1ab2 100644 --- a/src/test/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/participant/ApparentPowerAndHeatSpec.scala @@ -20,8 +20,8 @@ import squants.energy.{Power, Megawatts, Watts} import java.util.UUID class ApparentPowerAndHeatSpec extends UnitSpec { - implicit val powerTolerance: Power = Watts(1e-3) - implicit val reactivePowerTolerance: ReactivePower = Vars(1e-3) + given powerTolerance: Power = Watts(1e-3) + given reactivePowerTolerance: ReactivePower = Vars(1e-3) "Mixing in the trait for apparent power and heat participants" when { "requesting a result outside of the operation interval" should { "return zero result" in { diff --git a/src/test/scala/edu/ie3/simona/model/participant/CharacteristicSpec.scala b/src/test/scala/edu/ie3/simona/model/participant/CharacteristicSpec.scala index 0a5aa02595..ded42b1358 100644 --- a/src/test/scala/edu/ie3/simona/model/participant/CharacteristicSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/participant/CharacteristicSpec.scala @@ -12,7 +12,7 @@ import squants.Each class CharacteristicSpec extends UnitSpec with CharacteristicTestData { - private implicit val puTolerance: squants.Dimensionless = Each(1e-12) + given puTolerance: squants.Dimensionless = Each(1e-12) "The XYPair class" should { diff --git a/src/test/scala/edu/ie3/simona/model/participant/FixedFeedInModelSpec.scala b/src/test/scala/edu/ie3/simona/model/participant/FixedFeedInModelSpec.scala index 8f1698f7be..5faf96a03f 100644 --- a/src/test/scala/edu/ie3/simona/model/participant/FixedFeedInModelSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/participant/FixedFeedInModelSpec.scala @@ -23,7 +23,7 @@ class FixedFeedInModelSpec with DefaultTestData with PrivateMethodTester { - private implicit val powerTolerance: squants.Power = Watts( + given powerTolerance: squants.Power = Watts( 1.0 ) // Equals to 1 W power diff --git a/src/test/scala/edu/ie3/simona/model/participant/load/LoadModelSpec.scala b/src/test/scala/edu/ie3/simona/model/participant/load/LoadModelSpec.scala index b5317a8b71..4a8859c21c 100644 --- a/src/test/scala/edu/ie3/simona/model/participant/load/LoadModelSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/participant/load/LoadModelSpec.scala @@ -21,7 +21,7 @@ class LoadModelSpec with PrivateMethodTester with TableDrivenPropertyChecks { - private implicit val powerTolerance: squants.Power = Watts(1) + given powerTolerance: squants.Power = Watts(1) "The load model object" should { @@ -43,35 +43,33 @@ class LoadModelSpec forAll(params) { (foreSeenReference: LoadReference, expsRated: squants.Power) => - { - val actual = ProfileLoadModel( - loadInput, - defaultOperationInterval, - foreSeenScalingFactor, - foreSeenReference - ) - inside(actual) { - case ProfileLoadModel( - uuid, - id, - operationInterval, - scalingFactor, - qControl, - sRated, - cosPhiRated, - loadProfile, - reference - ) => - uuid shouldBe loadInput.getUuid - id shouldBe loadInput.getId - operationInterval shouldBe defaultOperationInterval - scalingFactor shouldBe foreSeenScalingFactor - qControl shouldBe QControl(loadInput.getqCharacteristics) - (sRated ~= expsRated) shouldBe true - cosPhiRated shouldBe loadInput.getCosPhiRated - loadProfile shouldBe loadInput.getLoadProfile - reference shouldBe foreSeenReference - } + val actual = ProfileLoadModel( + loadInput, + defaultOperationInterval, + foreSeenScalingFactor, + foreSeenReference + ) + inside(actual) { + case ProfileLoadModel( + uuid, + id, + operationInterval, + scalingFactor, + qControl, + sRated, + cosPhiRated, + loadProfile, + reference + ) => + uuid shouldBe loadInput.getUuid + id shouldBe loadInput.getId + operationInterval shouldBe defaultOperationInterval + scalingFactor shouldBe foreSeenScalingFactor + qControl shouldBe QControl(loadInput.getqCharacteristics) + (sRated ~= expsRated) shouldBe true + cosPhiRated shouldBe loadInput.getCosPhiRated + loadProfile shouldBe loadInput.getLoadProfile + reference shouldBe foreSeenReference } } } @@ -92,33 +90,31 @@ class LoadModelSpec forAll(params) { (foreSeenReference: LoadReference, expsRated: squants.Power) => - { - val actual = RandomLoadModel( - loadInput, - defaultOperationInterval, - foreSeenScalingFactor, - foreSeenReference - ) - inside(actual) { - case RandomLoadModel( - uuid, - id, - operationInterval, - scalingFactor, - qControl, - sRated, - cosPhiRated, - reference - ) => - uuid shouldBe loadInput.getUuid - id shouldBe loadInput.getId - operationInterval shouldBe defaultOperationInterval - scalingFactor shouldBe foreSeenScalingFactor - qControl shouldBe QControl(loadInput.getqCharacteristics) - (sRated ~= expsRated) shouldBe true - cosPhiRated shouldBe loadInput.getCosPhiRated - reference shouldBe foreSeenReference - } + val actual = RandomLoadModel( + loadInput, + defaultOperationInterval, + foreSeenScalingFactor, + foreSeenReference + ) + inside(actual) { + case RandomLoadModel( + uuid, + id, + operationInterval, + scalingFactor, + qControl, + sRated, + cosPhiRated, + reference + ) => + uuid shouldBe loadInput.getUuid + id shouldBe loadInput.getId + operationInterval shouldBe defaultOperationInterval + scalingFactor shouldBe foreSeenScalingFactor + qControl shouldBe QControl(loadInput.getqCharacteristics) + (sRated ~= expsRated) shouldBe true + cosPhiRated shouldBe loadInput.getCosPhiRated + reference shouldBe foreSeenReference } } } diff --git a/src/test/scala/edu/ie3/simona/model/participant/load/LoadProfileStoreSpec.scala b/src/test/scala/edu/ie3/simona/model/participant/load/LoadProfileStoreSpec.scala index dd66916cb1..e845492bb5 100644 --- a/src/test/scala/edu/ie3/simona/model/participant/load/LoadProfileStoreSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/participant/load/LoadProfileStoreSpec.scala @@ -7,7 +7,7 @@ package edu.ie3.simona.model.participant.load import com.typesafe.scalalogging.LazyLogging -import edu.ie3.datamodel.models.profile.BdewStandardLoadProfile._ +import edu.ie3.datamodel.models.profile.BdewStandardLoadProfile.* import edu.ie3.datamodel.models.profile.StandardLoadProfile import edu.ie3.simona.model.participant.load.profile.{ LoadProfileKey, @@ -100,9 +100,14 @@ class LoadProfileStoreSpec "have values, that lead to correct annual energy consumption" in { /* Collect all available load profiles */ val availableLoadProfiles: Set[StandardLoadProfile] = - (customStore invokePrivate PrivateMethod[ - Map[LoadProfileKey, TypeDayProfile] - ](Symbol("profileMap"))()).keySet.map(_.standardLoadProfile) + customStore + .invokePrivate( + PrivateMethod[ + Map[LoadProfileKey, TypeDayProfile] + ](Symbol("profileMap"))() + ) + .keySet + .map(_.standardLoadProfile) /* List the expected annual energy consumption */ val expectedEnergyConsumption: Map[StandardLoadProfile, squants.Energy] = @@ -120,7 +125,7 @@ class LoadProfileStoreSpec Range(0, 35136).map(cnt => startDate.plus(cnt * 15, ChronoUnit.MINUTES)) /* Check every load profile */ - availableLoadProfiles.foreach(profile => { + availableLoadProfiles.foreach { profile => /* Get expected value */ val expected = expectedEnergyConsumption.get(profile) match { case Some(expectedValue) => expectedValue @@ -134,17 +139,17 @@ class LoadProfileStoreSpec val annualEnergy: squants.Energy = testDates .foldLeft( KilowattHours(0.0) - )((integrationState, dateTime) => { + ) { (integrationState, dateTime) => val currentEnergy = customStore .entry(dateTime, profile) * Minutes(15.0) integrationState + currentEnergy - }) + } - implicit val powerTolerance: squants.Energy = KilowattHours(1.0) + given powerTolerance: squants.Energy = KilowattHours(1.0) /* Check the deviation against the expected value (deviation should be smaller than 1 kWh) */ (annualEnergy ~= expected) shouldBe true - }) + } } } } diff --git a/src/test/scala/edu/ie3/simona/model/participant/load/RandomLoadParamStoreSpec.scala b/src/test/scala/edu/ie3/simona/model/participant/load/RandomLoadParamStoreSpec.scala index 2bbe997702..f58f9f6df8 100644 --- a/src/test/scala/edu/ie3/simona/model/participant/load/RandomLoadParamStoreSpec.scala +++ b/src/test/scala/edu/ie3/simona/model/participant/load/RandomLoadParamStoreSpec.scala @@ -29,18 +29,20 @@ class RandomLoadParamStoreSpec PrivateMethod[Map[DayType.Value, Map[RandomLoadParameters.Value, Int]]]( Symbol("buildDescriptorTree") ) - val actual = RandomLoadParamStore invokePrivate buildDescriptorTree( - List( - "kSa", - "kSu", - "kWd", - "mySa", - "mySu", - "myWd", - "sigmaSa", - "sigmaSu", - "sigmaWd", - "quarterHour" + val actual = RandomLoadParamStore.invokePrivate( + buildDescriptorTree( + List( + "kSa", + "kSu", + "kWd", + "mySa", + "mySu", + "myWd", + "sigmaSa", + "sigmaSu", + "sigmaWd", + "quarterHour" + ) ) ) val expected = Map( @@ -70,9 +72,11 @@ class RandomLoadParamStoreSpec .getResourceAsStream("random_load_parameters_test.csv") ) val parameterMap = - RandomLoadParamStore(reader) invokePrivate PrivateMethod[ - Map[DayType.Value, TypeDayParameters] - ](Symbol("parameterMap"))() + RandomLoadParamStore(reader).invokePrivate( + PrivateMethod[ + Map[DayType.Value, TypeDayParameters] + ](Symbol("parameterMap"))() + ) parameterMap.size shouldBe 3 } diff --git a/src/test/scala/edu/ie3/simona/scheduler/SchedulerSpec.scala b/src/test/scala/edu/ie3/simona/scheduler/SchedulerSpec.scala index 60f7fede2d..46359cff56 100644 --- a/src/test/scala/edu/ie3/simona/scheduler/SchedulerSpec.scala +++ b/src/test/scala/edu/ie3/simona/scheduler/SchedulerSpec.scala @@ -226,7 +226,7 @@ class SchedulerSpec sa1.tick shouldBe INIT_SIM_TICK val schedulerActivation = sa1.actor - for (tick <- -1 to 8) { + for tick <- -1 to 8 do { schedulerActivation ! Activation(tick) triggeredAgents.foreach { diff --git a/src/test/scala/edu/ie3/simona/scheduler/TimeAdvancerSpec.scala b/src/test/scala/edu/ie3/simona/scheduler/TimeAdvancerSpec.scala index 21edf2210f..9543d8f6fe 100644 --- a/src/test/scala/edu/ie3/simona/scheduler/TimeAdvancerSpec.scala +++ b/src/test/scala/edu/ie3/simona/scheduler/TimeAdvancerSpec.scala @@ -12,7 +12,7 @@ import org.apache.pekko.actor.testkit.typed.scaladsl.{ } import org.apache.pekko.actor.typed.scaladsl.adapter.TypedActorRefOps import edu.ie3.simona.event.RuntimeEvent -import edu.ie3.simona.event.RuntimeEvent._ +import edu.ie3.simona.event.RuntimeEvent.* import edu.ie3.simona.ontology.messages.Activation import edu.ie3.simona.ontology.messages.SchedulerMessage.{ Completion, diff --git a/src/test/scala/edu/ie3/simona/service/ev/ExtEvDataServiceSpec.scala b/src/test/scala/edu/ie3/simona/service/ev/ExtEvDataServiceSpec.scala index 3326252b6d..9766ae3687 100644 --- a/src/test/scala/edu/ie3/simona/service/ev/ExtEvDataServiceSpec.scala +++ b/src/test/scala/edu/ie3/simona/service/ev/ExtEvDataServiceSpec.scala @@ -12,7 +12,7 @@ import org.apache.pekko.testkit.{TestActorRef, TestProbe} import com.typesafe.config.ConfigFactory import edu.ie3.simona.api.data.ev.ExtEvData import edu.ie3.simona.api.data.ev.model.EvModel -import edu.ie3.simona.api.data.ev.ontology._ +import edu.ie3.simona.api.data.ev.ontology.* import edu.ie3.simona.api.data.ontology.ScheduleDataServiceMessage import edu.ie3.simona.exceptions.ServiceException import edu.ie3.simona.ontology.messages.Activation @@ -20,7 +20,7 @@ import edu.ie3.simona.ontology.messages.SchedulerMessage.{ Completion, ScheduleActivation } -import edu.ie3.simona.ontology.messages.services.EvMessage._ +import edu.ie3.simona.ontology.messages.services.EvMessage.* import edu.ie3.simona.ontology.messages.services.ServiceMessage.RegistrationResponseMessage.RegistrationSuccessfulMessage import edu.ie3.simona.scheduler.ScheduleLock import edu.ie3.simona.service.SimonaService @@ -37,7 +37,7 @@ import tech.units.indriya.quantity.Quantities import java.util.UUID import scala.concurrent.duration.DurationInt -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* class ExtEvDataServiceSpec extends TestKitWithShutdown( diff --git a/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceProxySpec.scala b/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceProxySpec.scala index 25f32e4c46..a784fedb05 100644 --- a/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceProxySpec.scala +++ b/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceProxySpec.scala @@ -22,9 +22,7 @@ import edu.ie3.simona.config.SimonaConfig.Simona.Input.Primary.{ CouchbaseParams, InfluxDb1xParams } -import edu.ie3.simona.config.SimonaConfig.Simona.Input.{ - Primary => PrimaryConfig -} +import edu.ie3.simona.config.SimonaConfig.Simona.Input.Primary as PrimaryConfig import edu.ie3.simona.exceptions.{ InitializationException, InvalidConfigParameterException @@ -257,9 +255,11 @@ class PrimaryServiceProxySpec None ) - proxy invokePrivate prepareStateData( - maliciousConfig, - simulationStart + proxy.invokePrivate( + prepareStateData( + maliciousConfig, + simulationStart + ) ) match { case Success(_) => fail("Building state data with missing config should fail") @@ -277,9 +277,11 @@ class PrimaryServiceProxySpec None ) - proxy invokePrivate prepareStateData( - maliciousConfig, - simulationStart + proxy.invokePrivate( + prepareStateData( + maliciousConfig, + simulationStart + ) ) match { case Success(_) => fail("Building state data with missing config should fail") @@ -290,9 +292,11 @@ class PrimaryServiceProxySpec } "result in correct data" in { - proxy invokePrivate prepareStateData( - validPrimaryConfig, - simulationStart + proxy.invokePrivate( + prepareStateData( + validPrimaryConfig, + simulationStart + ) ) match { case Success( PrimaryServiceStateData( @@ -361,9 +365,11 @@ class PrimaryServiceProxySpec SValue ] // The class has to be child of edu.ie3.datamodel.models.value.Value - val workerRef = proxy invokePrivate classToWorkerRef( - testClass, - workerId + val workerRef = proxy.invokePrivate( + classToWorkerRef( + testClass, + workerId + ) ) Objects.nonNull(workerRef) shouldBe true @@ -380,10 +386,12 @@ class PrimaryServiceProxySpec Paths.get("its_pq_" + uuidPq) ) - proxy invokePrivate toInitData( - metaInformation, - simulationStart, - validPrimaryConfig + proxy.invokePrivate( + toInitData( + metaInformation, + simulationStart, + validPrimaryConfig + ) ) match { case Success( CsvInitPrimaryServiceStateData( @@ -422,10 +430,12 @@ class PrimaryServiceProxySpec None, None ) - proxy invokePrivate initializeWorker( - metaPq, - simulationStart, - maliciousPrimaryConfig + proxy.invokePrivate( + initializeWorker( + metaPq, + simulationStart, + maliciousPrimaryConfig + ) ) match { case Failure(exception) => /* Check the exception */ @@ -434,7 +444,7 @@ class PrimaryServiceProxySpec exception.getCause.getMessage shouldBe s"Cannot build initialization data for a worker due to unsupported source config '$maliciousPrimaryConfig'." /* Check, if the worker has been killed, yet. */ - implicit val timeout: Timeout = Timeout(2, TimeUnit.SECONDS) + given timeout: Timeout = Timeout(2, TimeUnit.SECONDS) system.actorSelection("/user/" + workerId).resolveOne().onComplete { case Failure(exception) => logger @@ -488,16 +498,18 @@ class PrimaryServiceProxySpec scheduler.expectNoMessage() - fakeProxy invokePrivate initializeWorker( - metaInformation, - simulationStart, - validPrimaryConfig + fakeProxy.invokePrivate( + initializeWorker( + metaInformation, + simulationStart, + validPrimaryConfig + ) ) match { case Success(workerRef) => /* Check, if expected init message has been sent */ workerRef shouldBe worker.ref - inside(worker.expectMsgType[SimonaService.Create[_]]) { + inside(worker.expectMsgType[SimonaService.Create[?]]) { case SimonaService.Create( CsvInitPrimaryServiceStateData( actualTimeSeriesUuid, @@ -541,20 +553,24 @@ class PrimaryServiceProxySpec PrivateMethod[PrimaryServiceStateData](Symbol("updateStateData")) "not work, if time series hasn't been covered before" in { val exception = intercept[IllegalArgumentException] { - proxy invokePrivate updateStateData( - proxyStateData, - UUID.fromString("394fd072-832c-4c36-869b-c574ee37afe1"), - self + proxy.invokePrivate( + updateStateData( + proxyStateData, + UUID.fromString("394fd072-832c-4c36-869b-c574ee37afe1"), + self + ) ) } exception.getMessage shouldBe "Cannot update entry for time series '394fd072-832c-4c36-869b-c574ee37afe1', as it hasn't been part of it before." } "work otherwise" in { - proxy invokePrivate updateStateData( - proxyStateData, - uuidPq, - self + proxy.invokePrivate( + updateStateData( + proxyStateData, + uuidPq, + self + ) ) match { case PrimaryServiceStateData( modelToTimeSeries, @@ -582,11 +598,13 @@ class PrimaryServiceProxySpec val maliciousStateData = proxyStateData.copy(timeSeriesToSourceRef = Map.empty[UUID, SourceRef]) - proxy invokePrivate handleCoveredModel( - modelUuid, - uuidPq, - maliciousStateData, - self + proxy.invokePrivate( + handleCoveredModel( + modelUuid, + uuidPq, + maliciousStateData, + self + ) ) expectMsg(RegistrationFailedMessage) } @@ -598,11 +616,13 @@ class PrimaryServiceProxySpec ) ) - proxy invokePrivate handleCoveredModel( - modelUuid, - uuidPq, - adaptedStateData, - self + proxy.invokePrivate( + handleCoveredModel( + modelUuid, + uuidPq, + adaptedStateData, + self + ) ) expectMsg(WorkerRegistrationMessage(self)) } @@ -617,11 +637,13 @@ class PrimaryServiceProxySpec ) ) - proxy invokePrivate handleCoveredModel( - modelUuid, - uuidPq, - maliciousStateData, - self + proxy.invokePrivate( + handleCoveredModel( + modelUuid, + uuidPq, + maliciousStateData, + self + ) ) expectMsg(RegistrationFailedMessage) } @@ -660,11 +682,13 @@ class PrimaryServiceProxySpec ) val fakeProxy = fakeProxyRef.underlyingActor - fakeProxy invokePrivate handleCoveredModel( - modelUuid, - uuidPq, - proxyStateData, - self + fakeProxy.invokePrivate( + handleCoveredModel( + modelUuid, + uuidPq, + proxyStateData, + self + ) ) worker.expectMsg(WorkerRegistrationMessage(self)) } diff --git a/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceWorkerSpec.scala b/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceWorkerSpec.scala index 6f1aa171a6..65d94de83e 100644 --- a/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceWorkerSpec.scala +++ b/src/test/scala/edu/ie3/simona/service/primary/PrimaryServiceWorkerSpec.scala @@ -81,7 +81,7 @@ class PrimaryServiceWorkerSpec timePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'" ) - private implicit val powerTolerance: squants.Power = Watts(0.1) + given powerTolerance: squants.Power = Watts(0.1) "A primary service actor" should { val scheduler = TestProbe("scheduler") @@ -218,10 +218,12 @@ class PrimaryServiceWorkerSpec val primaryData = ActivePower(Kilowatts(50.0)) val serviceStateData = validStateData.copy() - service invokePrivate announcePrimaryData( - tick, - primaryData, - serviceStateData + service.invokePrivate( + announcePrimaryData( + tick, + primaryData, + serviceStateData + ) ) match { case (updatedStateData, maybeNextTick) => /* Check updated state data */ @@ -270,10 +272,12 @@ class PrimaryServiceWorkerSpec activationTicks = SortedDistinctSeq(Seq(900L)) ) - service invokePrivate processDataAndAnnounce( - tick, - maliciousValue, - stateData + service.invokePrivate( + processDataAndAnnounce( + tick, + maliciousValue, + stateData + ) ) match { case ( PrimaryServiceInitializedStateData( @@ -299,10 +303,12 @@ class PrimaryServiceWorkerSpec activationTicks = SortedDistinctSeq(Seq(900L)) ) - service invokePrivate processDataAndAnnounce( - tick, - value, - serviceStateData + service.invokePrivate( + processDataAndAnnounce( + tick, + value, + serviceStateData + ) ) match { case (updatedStateData, _) => inside(updatedStateData) { diff --git a/src/test/scala/edu/ie3/simona/service/weather/SampleWeatherSourceSpec.scala b/src/test/scala/edu/ie3/simona/service/weather/SampleWeatherSourceSpec.scala index e94aaf6a1c..a8b1e7093b 100644 --- a/src/test/scala/edu/ie3/simona/service/weather/SampleWeatherSourceSpec.scala +++ b/src/test/scala/edu/ie3/simona/service/weather/SampleWeatherSourceSpec.scala @@ -13,7 +13,7 @@ import edu.ie3.simona.service.weather.WeatherSource.{ WeightedCoordinates } import edu.ie3.simona.test.common.UnitSpec -import edu.ie3.simona.util.TickUtil._ +import edu.ie3.simona.util.TickUtil.* import edu.ie3.util.TimeUtil import edu.ie3.util.scala.quantities.{Irradiance, WattsPerSquareMeter} import org.scalatest.prop.TableDrivenPropertyChecks @@ -29,11 +29,11 @@ class SampleWeatherSourceSpec extends UnitSpec with MockitoSugar with TableDrivenPropertyChecks { - implicit val simulationStart: ZonedDateTime = + given simulationStart: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2011-01-01 00:00:00") - implicit val toleranceIrradiance: Irradiance = WattsPerSquareMeter(0.1) - implicit val toleranceVelocity: Velocity = MetersPerSecond(0.01) - implicit val toleranceTemperature: Temperature = Celsius(0.01) + given toleranceIrradiance: Irradiance = WattsPerSquareMeter(0.1) + given toleranceVelocity: Velocity = MetersPerSecond(0.01) + given toleranceTemperature: Temperature = Celsius(0.01) val source: SampleWeatherSource = new SampleWeatherSource() "The sample weather source" should { @@ -83,7 +83,7 @@ class SampleWeatherSourceSpec TimeUtil.withDefaults.toZonedDateTime("2011-02-01 15:00:00").toTick "return correct weather data in value and unit" in { - val actual = source invokePrivate getWeatherPrivate(tick) + val actual = source.invokePrivate(getWeatherPrivate(tick)) /* Units meet expectation */ actual.diffIrr.unit shouldBe WattsPerSquareMeter diff --git a/src/test/scala/edu/ie3/simona/service/weather/WeatherServiceSpec.scala b/src/test/scala/edu/ie3/simona/service/weather/WeatherServiceSpec.scala index 8830f6c2ec..7d08fdac41 100644 --- a/src/test/scala/edu/ie3/simona/service/weather/WeatherServiceSpec.scala +++ b/src/test/scala/edu/ie3/simona/service/weather/WeatherServiceSpec.scala @@ -26,7 +26,7 @@ import edu.ie3.simona.ontology.messages.services.ServiceMessage.RegistrationResp RegistrationFailedMessage, RegistrationSuccessfulMessage } -import edu.ie3.simona.ontology.messages.services.WeatherMessage._ +import edu.ie3.simona.ontology.messages.services.WeatherMessage.* import edu.ie3.simona.scheduler.ScheduleLock import edu.ie3.simona.service.SimonaService import edu.ie3.simona.service.weather.WeatherService.InitWeatherServiceStateData @@ -99,13 +99,14 @@ class WeatherServiceSpec private val weatherActor: TestActorRef[WeatherService] = TestActorRef( new WeatherService( scheduler.ref, - TimeUtil.withDefaults.toZonedDateTime( - simonaConfig.simona.time.startDateTime - ), TimeUtil.withDefaults.toZonedDateTime( simonaConfig.simona.time.endDateTime ), 4 + )(using + TimeUtil.withDefaults.toZonedDateTime( + simonaConfig.simona.time.startDateTime + ) ) ) diff --git a/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceSpec.scala b/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceSpec.scala index 063e46d1f7..41e2571d82 100644 --- a/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceSpec.scala +++ b/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceSpec.scala @@ -21,7 +21,7 @@ import edu.ie3.simona.service.weather.WeatherSource.{ AgentCoordinates, WeightedCoordinates } -import edu.ie3.simona.service.weather.WeatherSourceSpec._ +import edu.ie3.simona.service.weather.WeatherSourceSpec.* import edu.ie3.simona.test.common.UnitSpec import edu.ie3.util.geo.{CoordinateDistance, GeoUtils} import edu.ie3.util.quantities.QuantityUtil @@ -33,8 +33,8 @@ import tech.units.indriya.unit.Units import java.util import java.util.Optional import javax.measure.quantity.Length -import scala.jdk.CollectionConverters._ -import scala.jdk.OptionConverters._ +import scala.jdk.CollectionConverters.* +import scala.jdk.OptionConverters.* import scala.util.{Failure, Success, Try} class WeatherSourceSpec extends UnitSpec { @@ -322,7 +322,7 @@ class WeatherSourceSpec extends UnitSpec { forAll(cases) { (gridModel, expectedClass, failureMessage) => val actual = - Try(WeatherSource invokePrivate checkCoordinateFactory(gridModel)) + Try(WeatherSource.invokePrivate(checkCoordinateFactory(gridModel))) actual match { case Success(factory) => @@ -430,7 +430,7 @@ case object WeatherSourceSpec { GeoUtils.calculateBoundingBox(coordinate, distance) val reducedPoints: Set[Point] = points.flatMap { point => - if (envelope.contains(point.getCoordinate)) { + if envelope.contains(point.getCoordinate) then { Some(point) } else { None @@ -443,8 +443,7 @@ case object WeatherSourceSpec { override def getNearestCoordinates( coordinate: Point, n: Int - ): util.List[CoordinateDistance] = { + ): util.List[CoordinateDistance] = calculateCoordinateDistances(coordinate, n, coordinateToId.keySet.asJava) - } } } diff --git a/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceWrapperSpec.scala b/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceWrapperSpec.scala index 5d76f0b3e3..aea6fcd1e4 100644 --- a/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceWrapperSpec.scala +++ b/src/test/scala/edu/ie3/simona/service/weather/WeatherSourceWrapperSpec.scala @@ -9,7 +9,7 @@ package edu.ie3.simona.service.weather import edu.ie3.datamodel.io.factory.timeseries.IconTimeBasedWeatherValueFactory import edu.ie3.datamodel.io.source.{ IdCoordinateSource, - WeatherSource => PsdmWeatherSource + WeatherSource as PsdmWeatherSource } import edu.ie3.datamodel.models.StandardUnits import edu.ie3.datamodel.models.timeseries.individual.{ @@ -24,7 +24,7 @@ import edu.ie3.simona.service.weather.WeatherSource.{ } import edu.ie3.simona.service.weather.WeatherSourceSpec.DummyIdCoordinateSource import edu.ie3.simona.service.weather.WeatherSourceWrapper.WeightSum -import edu.ie3.simona.service.weather.WeatherSourceWrapperSpec._ +import edu.ie3.simona.service.weather.WeatherSourceWrapperSpec.* import edu.ie3.simona.test.common.UnitSpec import edu.ie3.util.geo.GeoUtils import edu.ie3.util.interval.ClosedInterval @@ -45,9 +45,9 @@ import scala.jdk.CollectionConverters.{MapHasAsJava, SetHasAsJava} class WeatherSourceWrapperSpec extends UnitSpec { - implicit val toleranceIrradiance: Irradiance = WattsPerSquareMeter(0.1d) - implicit val toleranceVelocity: Velocity = MetersPerSecond(0.01d) - implicit val tolerance: Temperature = Celsius(0.01d) + given toleranceIrradiance: Irradiance = WattsPerSquareMeter(0.1d) + given toleranceVelocity: Velocity = MetersPerSecond(0.01d) + given tolerance: Temperature = Celsius(0.01d) "A weather source wrapper" should { val actor = classOf[WeatherSourceWrapper].getDeclaredConstructor( @@ -362,12 +362,11 @@ object WeatherSourceWrapperSpec { override def getWeather( date: ZonedDateTime, coordinate: Point - ): Optional[TimeBasedValue[WeatherValue]] = { + ): Optional[TimeBasedValue[WeatherValue]] = dummyValues.get(coordinate) match { case Some(value) => Optional.of(new TimeBasedValue(date, value)) case None => Optional.empty() } - } } /** Prepare test data for WeightSum-related tests diff --git a/src/test/scala/edu/ie3/simona/sim/setup/ExtSimLoaderSpec.scala b/src/test/scala/edu/ie3/simona/sim/setup/ExtSimLoaderSpec.scala index 49851d1ab4..6eaf90f3a8 100644 --- a/src/test/scala/edu/ie3/simona/sim/setup/ExtSimLoaderSpec.scala +++ b/src/test/scala/edu/ie3/simona/sim/setup/ExtSimLoaderSpec.scala @@ -143,8 +143,7 @@ class ExtSimLoaderSpec extends UnitSpec { } private def fileSuffix(fileName: String): String = - if (fileName.contains(".")) + if fileName.contains(".") then fileName.substring(fileName.lastIndexOf('.') + 1) - else - fileName + else fileName } diff --git a/src/test/scala/edu/ie3/simona/sim/setup/SetupHelperSpec.scala b/src/test/scala/edu/ie3/simona/sim/setup/SetupHelperSpec.scala index 93ae23d06b..758b80c10d 100644 --- a/src/test/scala/edu/ie3/simona/sim/setup/SetupHelperSpec.scala +++ b/src/test/scala/edu/ie3/simona/sim/setup/SetupHelperSpec.scala @@ -22,11 +22,11 @@ import edu.ie3.datamodel.models.input.container.{ import edu.ie3.simona.test.common.UnitSpec import edu.ie3.simona.test.common.input.GridInputTestData -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* class SetupHelperSpec extends UnitSpec with GridInputTestData { - private final object SetupHelperInstance extends SetupHelper + final private object SetupHelperInstance extends SetupHelper "A setup helper" should { "reduce multiple SubGridGates between the same superior and inferior nodes to one unique SubGridGate" in { diff --git a/src/test/scala/edu/ie3/simona/test/KafkaSpecLike.scala b/src/test/scala/edu/ie3/simona/test/KafkaSpecLike.scala index d228185517..89d7355411 100644 --- a/src/test/scala/edu/ie3/simona/test/KafkaSpecLike.scala +++ b/src/test/scala/edu/ie3/simona/test/KafkaSpecLike.scala @@ -13,7 +13,7 @@ import org.scalatest.{BeforeAndAfterAll, TestSuite} import org.testcontainers.utility.DockerImageName import java.util.concurrent.TimeUnit -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Adapted from * https://kafka-tutorials.confluent.io/produce-consume-lang/scala.html diff --git a/src/test/scala/edu/ie3/simona/test/common/ThreeWindingTestData.scala b/src/test/scala/edu/ie3/simona/test/common/ThreeWindingTestData.scala index 075ad05670..aab188d83b 100644 --- a/src/test/scala/edu/ie3/simona/test/common/ThreeWindingTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/ThreeWindingTestData.scala @@ -25,12 +25,12 @@ import edu.ie3.datamodel.models.input.{ } import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils import edu.ie3.simona.util.TestGridFactory -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import tech.units.indriya.quantity.Quantities -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Simple grid structure with only one three winding transformer */ diff --git a/src/test/scala/edu/ie3/simona/test/common/UnitSpec.scala b/src/test/scala/edu/ie3/simona/test/common/UnitSpec.scala index ab6b1752bf..c6707c12ed 100644 --- a/src/test/scala/edu/ie3/simona/test/common/UnitSpec.scala +++ b/src/test/scala/edu/ie3/simona/test/common/UnitSpec.scala @@ -9,8 +9,8 @@ package edu.ie3.simona.test.common import java.util.Locale import com.typesafe.scalalogging.LazyLogging import edu.ie3.simona.test.matchers.QuantityMatchers -import edu.ie3.util.scala.quantities.{QuantityUtil => PSQuantityUtil} -import org.scalatest._ +import edu.ie3.util.scala.quantities.QuantityUtil as PSQuantityUtil +import org.scalatest.* import org.scalatest.matchers.should import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.wordspec.AnyWordSpecLike diff --git a/src/test/scala/edu/ie3/simona/test/common/exceptions/InvalidTestDataException.scala b/src/test/scala/edu/ie3/simona/test/common/exceptions/InvalidTestDataException.scala index 96a6ec2f95..c144b0b84e 100644 --- a/src/test/scala/edu/ie3/simona/test/common/exceptions/InvalidTestDataException.scala +++ b/src/test/scala/edu/ie3/simona/test/common/exceptions/InvalidTestDataException.scala @@ -19,12 +19,10 @@ final case class InvalidTestDataException(message: String) initCause(cause) } - def this(cause: Throwable) = { + def this(cause: Throwable) = this(Option(cause).map(_.toString).orNull, cause) - } - def this() = { + def this() = this(null: String) - } } diff --git a/src/test/scala/edu/ie3/simona/test/common/input/EvcsInputTestData.scala b/src/test/scala/edu/ie3/simona/test/common/input/EvcsInputTestData.scala index 3fd0600aa4..37f18c166f 100644 --- a/src/test/scala/edu/ie3/simona/test/common/input/EvcsInputTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/input/EvcsInputTestData.scala @@ -60,7 +60,7 @@ trait EvcsInputTestData extends DefaultTestData with NodeInputTestData { evcsInputModel.getUuid ) - protected implicit val simulationStartDate: ZonedDateTime = + implicit protected val simulationStartDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 00:00:00") protected val simulationEndDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 02:00:00") diff --git a/src/test/scala/edu/ie3/simona/test/common/input/GridInputTestData.scala b/src/test/scala/edu/ie3/simona/test/common/input/GridInputTestData.scala index 5095730cba..aa5ef24fbb 100644 --- a/src/test/scala/edu/ie3/simona/test/common/input/GridInputTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/input/GridInputTestData.scala @@ -27,7 +27,7 @@ import edu.ie3.simona.util.TestGridFactory import testutils.TestObjectFactory import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Contains a valid GridInputModel with the following structure * diff --git a/src/test/scala/edu/ie3/simona/test/common/input/PvInputTestData.scala b/src/test/scala/edu/ie3/simona/test/common/input/PvInputTestData.scala index f92c0cff86..e6a2dab7f9 100644 --- a/src/test/scala/edu/ie3/simona/test/common/input/PvInputTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/input/PvInputTestData.scala @@ -26,7 +26,7 @@ trait PvInputTestData extends DefaultTestData with NodeInputTestData with MockitoSugar { - protected implicit val simulationStartDate: ZonedDateTime = + given simulationStartDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 00:00:00") protected val simulationEndDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 01:00:00") diff --git a/src/test/scala/edu/ie3/simona/test/common/input/Transformer3wTestData.scala b/src/test/scala/edu/ie3/simona/test/common/input/Transformer3wTestData.scala index 91da9daba4..36dfaaa3fa 100644 --- a/src/test/scala/edu/ie3/simona/test/common/input/Transformer3wTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/input/Transformer3wTestData.scala @@ -27,8 +27,8 @@ import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils import edu.ie3.simona.model.grid.{RefSystem, Transformer3wModel} import edu.ie3.simona.test.common.DefaultTestData import edu.ie3.simona.util.TestGridFactory -import edu.ie3.util.quantities.PowerSystemUnits._ -import org.scalatest.prop.TableDrivenPropertyChecks._ +import edu.ie3.util.quantities.PowerSystemUnits.* +import org.scalatest.prop.TableDrivenPropertyChecks.* import org.scalatest.prop.{TableFor2, TableFor4} import squants.electro.Kilovolts import squants.energy.{Kilowatts, Megawatts} @@ -36,7 +36,7 @@ import tech.units.indriya.quantity.Quantities import tech.units.indriya.unit.Units.{OHM, PERCENT} import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Test data for a [[Transformer3WInput]] */ trait Transformer3wTestData extends DefaultTestData { diff --git a/src/test/scala/edu/ie3/simona/test/common/input/TransformerInputTestData.scala b/src/test/scala/edu/ie3/simona/test/common/input/TransformerInputTestData.scala index a99035aaca..616448e778 100644 --- a/src/test/scala/edu/ie3/simona/test/common/input/TransformerInputTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/input/TransformerInputTestData.scala @@ -26,12 +26,12 @@ import edu.ie3.datamodel.models.input.{ import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils import edu.ie3.simona.test.common.DefaultTestData import edu.ie3.simona.util.TestGridFactory -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import tech.units.indriya.quantity.Quantities import tech.units.indriya.unit.Units.{OHM, PERCENT} import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Test data for a [[Transformer2WInput]]. * diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGrid.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGrid.scala index dc05ed3cda..681bb8c4eb 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGrid.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGrid.scala @@ -12,11 +12,11 @@ import edu.ie3.simona.model.grid.{ TransformerTappingModel } import edu.ie3.simona.test.common.DefaultTestData -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import squants.{Amperes, Each} import tech.units.indriya.ComparableQuantity import tech.units.indriya.quantity.Quantities -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.util.UUID import javax.measure.quantity.ElectricPotential diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGridWithSwitches.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGridWithSwitches.scala index c9270e0888..662502e301 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGridWithSwitches.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/BasicGridWithSwitches.scala @@ -14,7 +14,7 @@ import edu.ie3.simona.model.grid.{ SwitchModel, Transformer3wModel } -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import tech.units.indriya.quantity.Quantities import java.util.UUID @@ -214,11 +214,13 @@ trait BasicGridWithSwitches extends BasicGrid { // copy components because they are mutable and are altered by some tests // also enable components, otherwise they are not considered in building admittance matrices val gridNodes = nodes - gridNodes.foreach(node => if (!node.isInOperation) node.enable()) + gridNodes.foreach(node => if !node.isInOperation then node.enable()) val gridLines = lines gridLines.foreach(_.enable()) val gridSwitches = switches.map(_.copy()) - gridSwitches.foreach(switch => if (!switch.isInOperation) switch.enable()) + gridSwitches.foreach(switch => + if !switch.isInOperation then switch.enable() + ) new GridModel( 1, @@ -233,16 +235,14 @@ trait BasicGridWithSwitches extends BasicGrid { ) } - def openSwitches(gridModel: GridModel): Unit = { + def openSwitches(gridModel: GridModel): Unit = gridModel.gridComponents.switches.foreach(switch => - if (!switch.isOpen) switch.open() + if !switch.isOpen then switch.open() ) - } - def closeSwitches(gridModel: GridModel): Unit = { + def closeSwitches(gridModel: GridModel): Unit = gridModel.gridComponents.switches.foreach(switch => - if (!switch.isClosed) switch.close() + if !switch.isClosed then switch.close() ) - } } diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGrid.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGrid.scala index 6a91877773..6f8973ea4e 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGrid.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGrid.scala @@ -8,7 +8,7 @@ package edu.ie3.simona.test.common.model.grid import edu.ie3.datamodel.graph.SubGridGate import edu.ie3.datamodel.models.OperationTime -import edu.ie3.datamodel.models.input.connector._ +import edu.ie3.datamodel.models.input.connector.* import edu.ie3.datamodel.models.input.connector.`type`.{ LineTypeInput, Transformer2WTypeInput @@ -23,13 +23,13 @@ import edu.ie3.datamodel.models.input.{ import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils import edu.ie3.datamodel.utils.GridAndGeoUtils import edu.ie3.simona.util.TestGridFactory -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import tech.units.indriya.quantity.Quantities -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.util.UUID import scala.collection.mutable -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Provides the high voltage level of SIMONA's test grid. Only consists of * lines, nodes and transformers. diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGridWithParticipants.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGridWithParticipants.scala index eb0208adbd..38c56c891e 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGridWithParticipants.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/DbfsTestGridWithParticipants.scala @@ -8,14 +8,14 @@ package edu.ie3.simona.test.common.model.grid import edu.ie3.datamodel.graph.SubGridGate import edu.ie3.datamodel.models.OperationTime -import edu.ie3.datamodel.models.input.connector._ +import edu.ie3.datamodel.models.input.connector.* import edu.ie3.datamodel.models.input.connector.`type`.Transformer2WTypeInput import edu.ie3.datamodel.models.input.container.{ RawGridElements, SystemParticipants } import edu.ie3.datamodel.models.input.system.characteristic.CosPhiFixed -import edu.ie3.datamodel.models.input.system._ +import edu.ie3.datamodel.models.input.system.* import edu.ie3.datamodel.models.input.{ MeasurementUnitInput, NodeInput, @@ -24,15 +24,15 @@ import edu.ie3.datamodel.models.input.{ import edu.ie3.datamodel.models.profile.LoadProfile import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils import edu.ie3.simona.util.TestGridFactory -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import tech.units.indriya.ComparableQuantity import tech.units.indriya.quantity.Quantities -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.util.UUID import javax.measure.quantity.{Energy, Power} import scala.collection.mutable -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Provides the high voltage level of SIMONA's test grid. Only consists of * lines, nodes and transformers. diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/FiveLinesWithNodes.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/FiveLinesWithNodes.scala index d76bd254fe..75dbe76564 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/FiveLinesWithNodes.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/FiveLinesWithNodes.scala @@ -7,10 +7,10 @@ package edu.ie3.simona.test.common.model.grid import breeze.linalg.DenseMatrix -import breeze.math.{Complex => C} +import breeze.math.Complex as C import edu.ie3.datamodel.models.voltagelevels.GermanVoltageLevelUtils import edu.ie3.simona.model.grid.{LineModel, NodeModel} -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.OperationInterval import squants.{Amperes, Each} import tech.units.indriya.ComparableQuantity diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/SubGridGateMokka.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/SubGridGateMokka.scala index 19f3966a23..500fd5244b 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/SubGridGateMokka.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/SubGridGateMokka.scala @@ -14,7 +14,7 @@ import edu.ie3.datamodel.models.input.connector.{ Transformer2WInput, Transformer3WInput } -import org.mockito.Mockito._ +import org.mockito.Mockito.* import org.scalatestplus.mockito.MockitoSugar /** Hold my cup of coffee and let me mock you some models. diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestData.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestData.scala index c5211f1b19..2399d01013 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestData.scala @@ -9,14 +9,14 @@ package edu.ie3.simona.test.common.model.grid import breeze.math.Complex import edu.ie3.datamodel.models.input.connector.ConnectorPort import edu.ie3.simona.model.grid.RefSystem -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import org.scalatest.prop.TableDrivenPropertyChecks.Table import org.scalatest.prop.{TableFor5, TableFor9} import squants.electro.Kilovolts import squants.energy.Kilowatts import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** This test data refers to a life-like transformer, the SGB Smit DTTH 630 kVA * transformer. For details refer to diff --git a/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestGrid.scala b/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestGrid.scala index 9f0fc77394..f69feecd06 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestGrid.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/grid/TransformerTestGrid.scala @@ -28,16 +28,16 @@ import edu.ie3.simona.model.SystemComponent import edu.ie3.simona.model.grid.{RefSystem, TransformerModel} import edu.ie3.simona.util.TestGridFactory import edu.ie3.util.TimeUtil -import edu.ie3.util.quantities.PowerSystemUnits._ +import edu.ie3.util.quantities.PowerSystemUnits.* import edu.ie3.util.scala.OperationInterval import squants.electro.Kilovolts import squants.energy.Kilowatts import tech.units.indriya.quantity.Quantities -import tech.units.indriya.unit.Units._ +import tech.units.indriya.unit.Units.* import java.time.ZonedDateTime import java.util.UUID -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* /** Represents a simple test grid, consisting of one transformer connecting two * nodes. It is a representation of a real SGB Smit DTTH 630 kVA transformer diff --git a/src/test/scala/edu/ie3/simona/test/common/model/participant/LoadTestData.scala b/src/test/scala/edu/ie3/simona/test/common/model/participant/LoadTestData.scala index 1aeb8adc5e..6c5a06f758 100644 --- a/src/test/scala/edu/ie3/simona/test/common/model/participant/LoadTestData.scala +++ b/src/test/scala/edu/ie3/simona/test/common/model/participant/LoadTestData.scala @@ -17,7 +17,7 @@ import edu.ie3.util.scala.OperationInterval /** Trait to supply different test data environments for testing a load agent */ trait LoadTestData extends LoadInputTestData { - protected implicit val simulationStartDate: ZonedDateTime = + given simulationStartDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 00:00:00") protected val simulationEndDate: ZonedDateTime = TimeUtil.withDefaults.toZonedDateTime("2020-01-01 01:00:00") diff --git a/src/test/scala/edu/ie3/simona/test/helper/TestContainerHelper.scala b/src/test/scala/edu/ie3/simona/test/helper/TestContainerHelper.scala index 2e71d8d21b..e627089633 100644 --- a/src/test/scala/edu/ie3/simona/test/helper/TestContainerHelper.scala +++ b/src/test/scala/edu/ie3/simona/test/helper/TestContainerHelper.scala @@ -22,7 +22,7 @@ trait TestContainerHelper { * @return * a MountableFile to use with test containers */ - def getMountableFile(resource: String): MountableFile = { + def getMountableFile(resource: String): MountableFile = Option(getClass.getResource(resource)) .map(url => Paths.get(url.toURI)) .map(MountableFile.forHostPath) @@ -31,5 +31,4 @@ trait TestContainerHelper { "Resource '" + resource + "' was not found from " + getClass.toString ) ) - } } diff --git a/src/test/scala/edu/ie3/simona/util/ActorUtils.scala b/src/test/scala/edu/ie3/simona/util/ActorUtils.scala index dce3a38dc1..34fa72d335 100644 --- a/src/test/scala/edu/ie3/simona/util/ActorUtils.scala +++ b/src/test/scala/edu/ie3/simona/util/ActorUtils.scala @@ -13,10 +13,7 @@ import edu.ie3.simona.ontology.messages.{Activation, SchedulerMessage} import org.scalatest.matchers.should.Matchers.convertToAnyShouldWrapper object ActorUtils { - implicit class RichTriggeredAgent( - private val triggeredAgent: TestProbe[Activation] - ) { - + extension (triggeredAgent: TestProbe[Activation]) def expectTriggerAndComplete( scheduler: ActorRef[SchedulerMessage], expectedTick: Long, @@ -32,6 +29,4 @@ object ActorUtils { newTick ) } - - } } diff --git a/src/test/scala/edu/ie3/simona/util/CollectionUtilsSpec.scala b/src/test/scala/edu/ie3/simona/util/CollectionUtilsSpec.scala index 2553818567..4ff5b26ee7 100644 --- a/src/test/scala/edu/ie3/simona/util/CollectionUtilsSpec.scala +++ b/src/test/scala/edu/ie3/simona/util/CollectionUtilsSpec.scala @@ -7,7 +7,7 @@ package edu.ie3.simona.util import edu.ie3.simona.test.common.UnitSpec -import edu.ie3.simona.util.CollectionUtils._ +import edu.ie3.simona.util.CollectionUtils.* import squants.Each import squants.Dimensionless diff --git a/src/test/scala/edu/ie3/simona/util/ConfigUtilSpec.scala b/src/test/scala/edu/ie3/simona/util/ConfigUtilSpec.scala index 931ae996c5..b7551ff879 100644 --- a/src/test/scala/edu/ie3/simona/util/ConfigUtilSpec.scala +++ b/src/test/scala/edu/ie3/simona/util/ConfigUtilSpec.scala @@ -16,11 +16,11 @@ import edu.ie3.datamodel.models.result.connector.{ import edu.ie3.datamodel.models.result.system.{ChpResult, LoadResult} import edu.ie3.datamodel.models.result.{NodeResult, ResultEntity} import edu.ie3.simona.config.SimonaConfig -import edu.ie3.simona.config.SimonaConfig.{apply => _, _} +import edu.ie3.simona.config.SimonaConfig.{apply as _, *} import edu.ie3.simona.event.notifier.NotifierConfig import edu.ie3.simona.exceptions.InvalidConfigParameterException import edu.ie3.simona.test.common.{ConfigTestData, UnitSpec} -import edu.ie3.simona.util.ConfigUtil.NotifierIdentifier._ +import edu.ie3.simona.util.ConfigUtil.NotifierIdentifier.* import edu.ie3.simona.util.ConfigUtil.{ GridOutputConfigUtil, NotifierIdentifier, @@ -567,12 +567,12 @@ class ConfigUtilSpec "The grid output config util" should { "return the correct result entity classes to consider" in { - val ddt: TableFor2[GridOutputConfig, Set[Class[_ <: ResultEntity]]] = + val ddt: TableFor2[GridOutputConfig, Set[Class[? <: ResultEntity]]] = Table( ("config", "expected"), ( new GridOutputConfig(false, false, "grid", false, false, false), - Set.empty[Class[_ <: ResultEntity]] + Set.empty[Class[? <: ResultEntity]] ), ( new GridOutputConfig(true, false, "grid", false, false, false), @@ -607,7 +607,7 @@ class ConfigUtilSpec ) forAll(ddt) { - (config: GridOutputConfig, expected: Set[Class[_ <: ResultEntity]]) => + (config: GridOutputConfig, expected: Set[Class[? <: ResultEntity]]) => val actual = GridOutputConfigUtil(config).simulationResultEntitiesToConsider actual shouldBe expected @@ -772,8 +772,8 @@ class ConfigUtilSpec ) ) val configUtil = OutputConfigUtil(inputConfig) - val expectedResult: Set[Class[_ <: ResultEntity]] = - Set[Class[_ <: ResultEntity]](classOf[LoadResult], classOf[ChpResult]) + val expectedResult: Set[Class[? <: ResultEntity]] = + Set[Class[? <: ResultEntity]](classOf[LoadResult], classOf[ChpResult]) configUtil.simulationResultEntitiesToConsider shouldBe expectedResult } diff --git a/src/test/scala/edu/ie3/simona/util/TestGridFactory.scala b/src/test/scala/edu/ie3/simona/util/TestGridFactory.scala index 89f0cdf57e..bfc4212fd8 100644 --- a/src/test/scala/edu/ie3/simona/util/TestGridFactory.scala +++ b/src/test/scala/edu/ie3/simona/util/TestGridFactory.scala @@ -24,9 +24,9 @@ import edu.ie3.datamodel.models.input.graphics.{ LineGraphicInput, NodeGraphicInput } -import edu.ie3.datamodel.models.input.system._ +import edu.ie3.datamodel.models.input.system.* -import scala.jdk.CollectionConverters._ +import scala.jdk.CollectionConverters.* object TestGridFactory { diff --git a/src/test/scala/edu/ie3/util/quantities/EnergyDensitySpec.scala b/src/test/scala/edu/ie3/util/quantities/EnergyDensitySpec.scala index cfb158bf0a..52a77e1429 100644 --- a/src/test/scala/edu/ie3/util/quantities/EnergyDensitySpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/EnergyDensitySpec.scala @@ -14,7 +14,7 @@ import squants.space.CubicMeters class EnergyDensitySpec extends AnyFlatSpec with Matchers { - behavior of "EnergyDensityCapacity and its Units of Measure" + behavior.of("EnergyDensityCapacity and its Units of Measure") it should "create values using UOM factories" in { KilowattHoursPerCubicMeter( diff --git a/src/test/scala/edu/ie3/util/quantities/EnergyPriceSpec.scala b/src/test/scala/edu/ie3/util/quantities/EnergyPriceSpec.scala index b0139f40a9..158e5d0160 100644 --- a/src/test/scala/edu/ie3/util/quantities/EnergyPriceSpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/EnergyPriceSpec.scala @@ -14,7 +14,7 @@ import squants.market.EUR class EnergyPriceSpec extends AnyFlatSpec with Matchers { - behavior of "EnergyPrice and its Units of Measure" + behavior.of("EnergyPrice and its Units of Measure") it should "create values using UOM factories" in { EuroPerKilowatthour( diff --git a/src/test/scala/edu/ie3/util/quantities/IrradianceSpec.scala b/src/test/scala/edu/ie3/util/quantities/IrradianceSpec.scala index 37759008e5..970da1c7d9 100644 --- a/src/test/scala/edu/ie3/util/quantities/IrradianceSpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/IrradianceSpec.scala @@ -19,7 +19,7 @@ import squants.time.Seconds class IrradianceSpec extends AnyFlatSpec with Matchers { - behavior of "Irradiance and its Units of Measure" + behavior.of("Irradiance and its Units of Measure") it should "create values using UOM factories" in { WattsPerSquareMeter( diff --git a/src/test/scala/edu/ie3/util/quantities/IrradiationSpec.scala b/src/test/scala/edu/ie3/util/quantities/IrradiationSpec.scala index a2e7663864..b8201b8c70 100644 --- a/src/test/scala/edu/ie3/util/quantities/IrradiationSpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/IrradiationSpec.scala @@ -18,7 +18,7 @@ import squants.time.Hours class IrradiationSpec extends AnyFlatSpec with Matchers { - behavior of "Irradiation and its Units of Measure" + behavior.of("Irradiation and its Units of Measure") it should "create values using UOM factories" in { WattHoursPerSquareMeter( diff --git a/src/test/scala/edu/ie3/util/quantities/QuantityUtilSpec.scala b/src/test/scala/edu/ie3/util/quantities/QuantityUtilSpec.scala index 549b76a826..b012e4282c 100644 --- a/src/test/scala/edu/ie3/util/quantities/QuantityUtilSpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/QuantityUtilSpec.scala @@ -16,8 +16,8 @@ import squants.{Energy, Power} import scala.util.{Failure, Success} class QuantityUtilSpec extends UnitSpec with TableDrivenPropertyChecks { - implicit val powerTolerance: Power = Watts(1e-3) - implicit val energyTolerance: Energy = WattHours(1e-6) + given powerTolerance: Power = Watts(1e-3) + given energyTolerance: Energy = WattHours(1e-6) private val unit = Kilowatts private val integrationUnit = Kilojoules private val values = Map( @@ -34,26 +34,32 @@ class QuantityUtilSpec extends UnitSpec with TableDrivenPropertyChecks { "throw an exception, if values are empty and unit of \"empty\" quantity cannot be determined" in { intercept[QuantityException] { - QuantityUtil invokePrivate startingValue( - Map.empty[Long, Power], - 1L + QuantityUtil.invokePrivate( + startingValue( + Map.empty[Long, Power], + 1L + ) ) }.getMessage shouldBe "Unable to determine unit for dummy starting value." } "bring default value, if there is nothing before window starts" in { - QuantityUtil invokePrivate startingValue( - values, - 1L + QuantityUtil.invokePrivate( + startingValue( + values, + 1L + ) ) should be unit(0d) } "bring correct value, if there is something before window starts" in { - QuantityUtil invokePrivate startingValue( - values, - 2L + QuantityUtil.invokePrivate( + startingValue( + values, + 2L + ) ) should be unit(5d) @@ -66,12 +72,12 @@ class QuantityUtilSpec extends UnitSpec with TableDrivenPropertyChecks { "throw and exception, if there is no value before the window ends" in { intercept[QuantityException] { - QuantityUtil invokePrivate endingValue(values, 1L) + QuantityUtil.invokePrivate(endingValue(values, 1L)) }.getMessage shouldBe "Cannot integrate over an empty set of values." } "bring correct value, if there is something before window ends" in { - QuantityUtil invokePrivate endingValue(values, 2L) match { + QuantityUtil.invokePrivate(endingValue(values, 2L)) match { case (tick, value) => tick shouldBe 2L (value =~ unit(5d)) shouldBe true diff --git a/src/test/scala/edu/ie3/util/quantities/ReactivePowerSpec.scala b/src/test/scala/edu/ie3/util/quantities/ReactivePowerSpec.scala index f922047eb0..a430e90225 100644 --- a/src/test/scala/edu/ie3/util/quantities/ReactivePowerSpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/ReactivePowerSpec.scala @@ -14,7 +14,7 @@ import squants.energy.Watts class ReactivePowerSpec extends AnyFlatSpec with Matchers { - behavior of "ReactivePower and its Units of Measure" + behavior.of("ReactivePower and its Units of Measure") it should "create values using UOM factories" in { Vars( diff --git a/src/test/scala/edu/ie3/util/quantities/SpecificHeatCapacitySpec.scala b/src/test/scala/edu/ie3/util/quantities/SpecificHeatCapacitySpec.scala index d2a5aef2f8..c1238f3493 100644 --- a/src/test/scala/edu/ie3/util/quantities/SpecificHeatCapacitySpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/SpecificHeatCapacitySpec.scala @@ -15,7 +15,7 @@ import squants.thermal.{Celsius, Kelvin} class SpecificHeatCapacitySpec extends AnyFlatSpec with Matchers { - behavior of "SpecificHeatCapacity and its Units of Measure" + behavior.of("SpecificHeatCapacity and its Units of Measure") it should "create values using UOM factories" in { KilowattHoursPerKelvinCubicMeters( diff --git a/src/test/scala/edu/ie3/util/quantities/ThermalConductanceSpec.scala b/src/test/scala/edu/ie3/util/quantities/ThermalConductanceSpec.scala index fd2e290f16..63f8811922 100644 --- a/src/test/scala/edu/ie3/util/quantities/ThermalConductanceSpec.scala +++ b/src/test/scala/edu/ie3/util/quantities/ThermalConductanceSpec.scala @@ -16,7 +16,7 @@ import squants.time.Hours class ThermalConductanceSpec extends AnyFlatSpec with Matchers { - behavior of "ThermalConductance and its Units of Measure" + behavior.of("ThermalConductance and its Units of Measure") it should "create values using UOM factories" in { WattsPerKelvin(1).toWattsPerKelvin should be(1)