Skip to content

Commit db46ba6

Browse files
authored
Added Kotlin implementation of the PI extraction simulation (#112)
1 parent e64c1b5 commit db46ba6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

snippets/formulae/pi-extraction.kt

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.time.Duration
2+
import kotlin.math.*
3+
4+
private const val SEC = 10000000L
5+
6+
/**
7+
* @param baseValue This is the "qty_per_cycle" value as returned by ESI
8+
* @param cycleDuration Cycle duration, e.g. 2 hours
9+
* @param length The number of cycles in this extraction
10+
*/
11+
fun calculateExtractorValues(baseValue: Int, cycleDuration: Duration, length: Int): List<Long> {
12+
return buildList {
13+
val startTime = 0L
14+
val cycleTime = cycleDuration.toSeconds() * SEC
15+
for (i in 0 until length) {
16+
val currentTime = (i + 1) * cycleTime
17+
add(calculateExtractorValue(baseValue, startTime, currentTime, cycleTime))
18+
}
19+
}
20+
}
21+
22+
private fun calculateExtractorValue(baseValue: Int, startTime: Long, currentTime: Long, cycleTime: Long): Long {
23+
val decayFactor = 0.012
24+
val noiseFactor = 0.8
25+
val cycleNum = max((currentTime - startTime + SEC) / cycleTime - 1, 0)
26+
val barWidth = cycleTime / SEC / 900.0
27+
val t = (cycleNum + 0.5) * barWidth
28+
val decayValue = baseValue / (1 + t * decayFactor)
29+
val phaseShift = baseValue.toDouble().pow(0.7)
30+
val sinA = cos(phaseShift + t * (1.0 / 12.0))
31+
val sinB = cos(phaseShift / 2.0 + t * (1.0 / 5.0))
32+
val sinC = cos(t * (1.0 / 2.0))
33+
val sinStuff = max(0.0, (sinA + sinB + sinC) / 3.0)
34+
val barHeight = decayValue * (1 + noiseFactor * sinStuff)
35+
36+
val output = barWidth * barHeight
37+
// Round down, with integers also rounded down (123.0 -> 122)
38+
return if (output - output.toLong() == 0.0) output.toLong() - 1 else output.toLong()
39+
}

0 commit comments

Comments
 (0)