[add][fix] added numberUtil and behaviourUtil to library
- numberUtil adds functions to Double - behaviourUtil adds functions to Option[FunctionArgs] - [add] getParam function to FunctionArgs case class - [fix] fixed typo in config
This commit is contained in:
@@ -117,7 +117,12 @@ case class Group(name: String, sensorParent: Option[String] = None){
|
||||
}
|
||||
|
||||
case class Truth() extends Result[Option[Double]]
|
||||
case class FunctionArgs(args: Map[String, Any])
|
||||
case class FunctionArgs(args: Map[String, Any]) {
|
||||
def getParam[A](param: String, fallback: A): A = {
|
||||
// just bruteforce try to get the param, otherwise use fallback
|
||||
try { args(param).asInstanceOf[A] } catch { case _: Throwable => fallback }
|
||||
}
|
||||
}
|
||||
|
||||
case class BehaviourVector(function: Vector[Option[(SimulationBehaviour, Option[FunctionArgs])]],
|
||||
defaultFunc: SimulationBehaviour = (_: Cell, _: Time, v: Option[Double], _: Option[FunctionArgs]) => v,
|
||||
|
||||
@@ -313,6 +313,53 @@ package object mapUtil {
|
||||
|
||||
}
|
||||
|
||||
package object behaviourUtil {
|
||||
implicit class FunctionArgsOption(optional: Option[FunctionArgs]) {
|
||||
def getParam[B](param: String, fallback: B): B = {
|
||||
if(optional.isEmpty) {
|
||||
fallback
|
||||
} else {
|
||||
optional.get.getParam(param, fallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
package object numberUtil {
|
||||
implicit class ExtendedDouble(number: Double) {
|
||||
def truncate(decimals: Int): Double = {
|
||||
val n = Math.pow(10, decimals)
|
||||
(number * n).toLong.toDouble / n
|
||||
}
|
||||
|
||||
def range(min: Double, max: Double): Double = {
|
||||
if(number < min) return min
|
||||
if(number > max) return max
|
||||
number
|
||||
}
|
||||
|
||||
// this is not perfect if the number has accuracy problems
|
||||
def getNumOfDecimals: Int = {
|
||||
val limit = 1000 // just a safeguard
|
||||
def recursiveDecimals(n: Double, run: Int): Int = {
|
||||
if (n % 1d == 0 || run >= limit) {
|
||||
0
|
||||
} else {
|
||||
1 + recursiveDecimals(n * 10, run + 1)
|
||||
}
|
||||
}
|
||||
recursiveDecimals(number, 1)
|
||||
}
|
||||
|
||||
def resolution(res: Double): Double = {
|
||||
val result = (number / res).toLong.toDouble * res
|
||||
// remove any accuracy artifacts by truncating (if resolution does not have problems)
|
||||
result.truncate(res.getNumOfDecimals)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
package object yml {
|
||||
val yaml = new Yaml
|
||||
// TODO: handle errors (invalid file/format)
|
||||
|
||||
Reference in New Issue
Block a user