Weighted rotation rollout proposal for Tots, ToonZ, Odyssey, Wild and Orbit X (read-only replay, nothing in the app)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The rollout proposal after Orbit Three (4 November 2026): read-only, nothing here is used by the app. For Tots, ToonZ,
|
||||
* Odyssey, Wild and Orbit X, four weeks of new bookings after each committed plan, from copies of the box's files, both
|
||||
* the rule each channel has today and weighted rotation with the tiers proposed from its own brief:
|
||||
* ORBIT_REPLAY_DIR=<copies of the box's files> ./gradlew :app:testDebugUnitTest --tests '*RolloutProposalReplayTest*'
|
||||
* Writes rollout-proposal-replay.txt there.
|
||||
*/
|
||||
class RolloutProposalReplayTest {
|
||||
private val dir = System.getenv("ORBIT_REPLAY_DIR")?.let(::File)
|
||||
private val zone = java.time.ZoneId.of("Europe/London")
|
||||
private val day = 24 * 60 * 60_000L
|
||||
private val hour = 60 * 60_000L
|
||||
|
||||
private class Proposal(val number: Int, val name: String, val tiers: Map<String, Double>, val note: String, val alternatives: List<Pair<String, Map<String, Double>>> = emptyList())
|
||||
private fun tiers(core: List<String>, surprise: List<String> = emptyList(), other: Map<String, Double> = emptyMap()) =
|
||||
core.associate { seriesKey(it) to TIER_CORE } + surprise.associate { seriesKey(it) to TIER_SURPRISE } + other.mapKeys { seriesKey(it.key) }
|
||||
|
||||
// Each channel's tiers, from its own brief in docs/channels. Anything not named is supporting (2).
|
||||
private val proposals = listOf(
|
||||
Proposal(614, "Tots", emptyMap(), "No tiers in the brief: every show equal (2), so airtime is shared by minutes, not by episode count.",
|
||||
listOf("Night Garden anchors bedtime (3), Clangers and BeddyByes light (1)" to tiers(listOf("In The Night Garden"), surprise = listOf("Clangers", "BeddyByes")))),
|
||||
Proposal(605, "ToonZ", tiers(listOf("Looney Tunes", "Tom and Jerry", "Scooby-Doo, Where Are You!", "The Flintstones", "The Jetsons", "The Yogi Bear Show", "Popeye the Sailor", "Popeye")),
|
||||
"Core 3 and supporting 2 from the brief. The British teatime trio counts as supporting (2), not surprise: teatime is their block.",
|
||||
listOf("teatime trio at 3, level with the core" to tiers(listOf("Looney Tunes", "Tom and Jerry", "Scooby-Doo, Where Are You!", "The Flintstones", "The Jetsons", "The Yogi Bear Show",
|
||||
"Popeye the Sailor", "Popeye", "Danger Mouse", "Count Duckula", "Bananaman")))),
|
||||
Proposal(202, "Odyssey", tiers(listOf("The Universe", "How the Universe Works", "Cosmos", "Cosmos: A Spacetime Odyssey", "Wonders of the Universe", "Wonders of the Solar System",
|
||||
"Horizon", "Through the Wormhole", "The Sky at Night", "The Planets (2019)", "Wonders of Life", "Human Universe", "Forces of Nature with Brian Cox",
|
||||
"Brian Cox's Adventures in Space and Time", "When We Left Earth: The NASA Missions", "Impossible Engineering", "Extreme Engineering", "Megastructures")),
|
||||
"Core 3 and supporting 2 from the brief. The Journeys titles are equal (2) within their weekend block."),
|
||||
Proposal(203, "Wild", tiers(listOf("Man vs. Wild", "Running Wild with Bear Grylls", "Survivorman", "Dual Survival", "Naked and Afraid", "Alone", "Survival with Ray Mears",
|
||||
"Bear Grylls: Mission Survive", "The Crocodile Hunter", "River Monsters"), surprise = listOf("Dirty Jobs")),
|
||||
"Core 3, supporting 2 and Dirty Jobs as the surprise (1), all from the brief."),
|
||||
Proposal(603, "Orbit X", tiers(listOf("Biker Mice from Mars", "Digimon: Digital Monsters", "Teenage Mutant Ninja Turtles", "The Transformers", "He-Man and the Masters of the Universe",
|
||||
"ThunderCats", "Gargoyles", "The Real Ghostbusters", "Power Rangers", "G.I. Joe", "Digimon Adventure", "Mighty Morphin Power Rangers", "G.I. Joe: A Real American Hero")),
|
||||
"Core 3 (with the earlier names of the same shows) and supporting 2 from the brief, X-Men and Spider-Man included as the brief lists them."))
|
||||
|
||||
private fun plan(file: File): ChannelPlan {
|
||||
val root = JSONObject(file.readText()); val rows = root.getJSONArray("entries"); val t = root.getJSONObject("tail"); val marks = t.getJSONObject("marks")
|
||||
val entries = (0 until rows.length()).map { i ->
|
||||
val o = rows.getJSONObject(i); val d = o.getLong("d"); val n = o.getJSONArray("n")
|
||||
ScheduleEntry(o.getString("s"), EpisodeMark(n.getInt(0), n.getInt(1)), ScheduledMedia(SampleItem(o.getString("t"), o.optString("k", "Episode"), d / 60_000, "", o.getString("i"), d), o.getString("c"), d),
|
||||
o.getLong("a"), o.optString("w"), o.optString("p"))
|
||||
}
|
||||
return ChannelPlan(entries, ScheduleCursor(if (t.isNull("last")) null else t.getString("last"),
|
||||
marks.keys().asSequence().associateWith { id -> marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } },
|
||||
t.optJSONObject("shown")?.let { s -> s.keys().asSequence().associateWith { s.getLong(it) } }.orEmpty(),
|
||||
t.optJSONObject("blocks")?.let { b -> b.keys().asSequence().associateWith { b.getString(it) } }.orEmpty()))
|
||||
}
|
||||
|
||||
private fun pool(file: File): List<PoolSeries> {
|
||||
val rows = JSONObject(file.readText()).getJSONArray("series")
|
||||
return (0 until rows.length()).map { i ->
|
||||
val o = rows.getJSONObject(i); val eps = o.getJSONArray("episodes")
|
||||
PoolSeries(o.getString("id"), o.getString("title"), (0 until eps.length()).map { j ->
|
||||
val e = eps.getJSONArray(j); PoolEpisode(e.getString(0), e.getString(1), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), e.getLong(5))
|
||||
}, o.optString("group"))
|
||||
}
|
||||
}
|
||||
|
||||
private fun replay(committed: ChannelPlan, series: List<PoolSeries>, programming: ChannelProgramming, weightOf: ((PoolSeries) -> Double)?): List<ScheduleEntry> {
|
||||
var current = committed
|
||||
var now = committed.entries.first().startMs + SCHEDULE_KEEP_PAST_MS
|
||||
val end = committed.endMs + 28 * day
|
||||
val all = committed.entries.toMutableList()
|
||||
while (now < end) {
|
||||
current = topUpPlan(current, current.tail, series, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, zone,
|
||||
shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = weightOf) ?: break
|
||||
current.entries.filter { e -> all.none { it.startMs == e.startMs } }.forEach { all += it }
|
||||
now += 6 * hour
|
||||
}
|
||||
all.sortBy { it.startMs }
|
||||
assertEquals("${programming.name}: committed programmes kept", committed.entries, all.take(committed.entries.size))
|
||||
return all.filter { it.startMs >= committed.endMs && it.startMs < end }
|
||||
}
|
||||
|
||||
private fun pct(x: Double) = "%.0f%%".format(100 * x)
|
||||
|
||||
private fun report(label: String, entries: List<ScheduleEntry>, series: List<PoolSeries>, programming: ChannelProgramming, weightOf: (PoolSeries) -> Double, out: StringBuilder) {
|
||||
val byId = series.associateBy { it.id }
|
||||
fun tier(id: String) = when (weightOf(byId.getValue(id))) { TIER_CORE -> "core"; TIER_SURPRISE -> "surprise"; else -> "supporting" }
|
||||
fun minutes(es: List<ScheduleEntry>) = es.groupBy { it.seriesId }.mapValues { (_, x) -> x.sumOf { it.media.durationMs } / 60_000.0 }
|
||||
val m = minutes(entries); val total = m.values.sum()
|
||||
val inBlocks = series.filter { s -> programming.dayParts.any { p -> p.titles.any { seriesKey(it) == seriesKey(s.title) } } }
|
||||
out.appendLine(" $label: ${entries.size} programmes")
|
||||
out.appendLine(" airtime by tier: " + listOf("core", "supporting", "surprise").joinToString { t -> "$t ${pct(m.filterKeys { tier(it) == t }.values.sum() / total)}" })
|
||||
entries.groupBy { dayPartFor(series, programming.dayParts, it.startMs, zone).second }.toSortedMap().forEach { (b, es) ->
|
||||
val bm = minutes(es); val bt = bm.values.sum()
|
||||
val effective = 1 / bm.values.sumOf { (it / bt) * (it / bt) }
|
||||
out.appendLine(" $b: core ${pct(bm.filterKeys { tier(it) == "core" }.values.sum() / bt)}, ${bm.size} shows, effectively ${"%.1f".format(effective)} equal shows; top " +
|
||||
bm.entries.sortedByDescending { it.value }.take(3).joinToString { "${byId.getValue(it.key).title} ${pct(it.value / bt)}" })
|
||||
}
|
||||
// Repeats: the same file again, within a day and within a week.
|
||||
val gapsByFile = entries.groupBy { it.media.item.id }.values.flatMap { es -> es.zipWithNext().map { (a, b) -> b.startMs - a.startMs } }
|
||||
val sameDay = gapsByFile.count { it < day }; val sameWeek = gapsByFile.count { it < 7 * day }
|
||||
out.appendLine(" repeats: ${entries.map { it.media.item.id }.distinct().size} different episodes; same file again within 24 h $sameDay, within 7 days $sameWeek" +
|
||||
(if (gapsByFile.isNotEmpty()) ", median ${"%.1f".format(gapsByFile.sorted()[gapsByFile.size / 2] / day.toDouble())} days between repeats" else ""))
|
||||
val first = entries.first().startMs; val last = entries.last().endMs
|
||||
val waits = inBlocks.associate { s -> s.title to (listOf(first) + entries.filter { it.seriesId == s.id }.map { it.startMs } + listOf(last)).zipWithNext().maxOf { (a, b) -> b - a } / day.toDouble() }
|
||||
val never = inBlocks.filter { s -> entries.none { it.seriesId == s.id } }.map { it.title }
|
||||
out.appendLine(" starvation: never aired ${never.ifEmpty { listOf("none") }.joinToString()}; longest waits " + waits.entries.sortedByDescending { it.value }.take(4).joinToString { "${it.key} ${"%.1f".format(it.value)} d" })
|
||||
val twice = entries.zipWithNext().count { (a, b) -> a.seriesId == b.seriesId }
|
||||
val ordered = series.filter { !(programming.shuffleEpisodes || programming.mixes(it)) }.associateBy { it.id }
|
||||
val back = entries.filter { it.seriesId in ordered }.groupBy { it.seriesId }.values.sumOf { es -> es.zipWithNext().count { (a, b) -> b.mark <= a.mark && b.mark != ordered.getValue(a.seriesId).episodes.first().mark } }
|
||||
val decks = series.filter { programming.shuffleEpisodes || programming.mixes(it) }.associate { s -> s.id to shuffledEpisodes(s).map { it.mark } }
|
||||
val offDeck = entries.filter { it.seriesId in decks }.groupBy { it.seriesId }.entries.sumOf { (id, es) -> val d = decks.getValue(id); es.zipWithNext().count { (a, b) -> d[(d.indexOf(a.mark) + 1) % d.size] != b.mark } }
|
||||
val gaps = entries.zipWithNext().count { (a, b) -> a.endMs != b.startMs }
|
||||
val outside = entries.count { e -> dayPartFor(series, programming.dayParts, e.startMs, zone).first.none { it.id == e.seriesId } }
|
||||
val bursts = entries.indices.count { i -> val w = entries.drop(i).takeWhile { it.startMs < entries[i].startMs + 3 * hour }; w.size >= 4 && w.count { it.seriesId == entries[i].seriesId } * 2 > w.size }
|
||||
out.appendLine(" rules: same show twice running $twice; three-hour stretches over half one show $bursts; in-order stepping back $back; shuffled off its deck $offDeck; gaps $gaps; outside its block $outside")
|
||||
}
|
||||
|
||||
@Test fun rolloutChannels() {
|
||||
assumeTrue(dir != null && dir.isDirectory)
|
||||
val out = StringBuilder("Rollout proposal replays: four weeks of new bookings after each committed plan, today's rule against weighted rotation with the proposed tiers.\n" +
|
||||
"Read-only: the tiers below are proposals, defined only in this test.\n\n")
|
||||
for (p in proposals) {
|
||||
val programming = SmartChannels.first { it.number == p.number }
|
||||
val committedFile = File(dir, "schedule-${p.number}.json"); val poolFile = File(dir, "episodes-${p.number}.json")
|
||||
if (!committedFile.exists() || !poolFile.exists()) { out.appendLine("== ${p.name}: no files"); continue }
|
||||
val committed = plan(committedFile); val series = pool(poolFile)
|
||||
val weightOf = { s: PoolSeries -> p.tiers[seriesKey(s.title)] ?: TIER_SUPPORTING }
|
||||
out.appendLine("== ${p.name} (${p.number}), committed plan ends ${java.time.Instant.ofEpochMilli(committed.endMs).atZone(zone).toLocalDateTime().withNano(0)}")
|
||||
out.appendLine(" ${p.note}")
|
||||
if (p.tiers.isNotEmpty()) out.appendLine(" in the pool: ${series.size} shows; core ${series.count { weightOf(it) == TIER_CORE }}, supporting ${series.count { weightOf(it) == TIER_SUPPORTING }}, surprise ${series.count { weightOf(it) == TIER_SURPRISE }}")
|
||||
report("Today", replay(committed, series, programming, null), series, programming, weightOf, out)
|
||||
report("Weighted", replay(committed, series, programming, weightOf), series, programming, weightOf, out)
|
||||
for ((label, alt) in p.alternatives) {
|
||||
val altWeight = { s: PoolSeries -> alt[seriesKey(s.title)] ?: TIER_SUPPORTING }
|
||||
report("Alternative, $label", replay(committed, series, programming, altWeight), series, programming, altWeight, out)
|
||||
}
|
||||
out.appendLine()
|
||||
}
|
||||
File(dir, "rollout-proposal-replay.txt").writeText(out.toString())
|
||||
println(out)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user