Multicore Thermal Simulation with Adaptive Cooling Selection
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests discrete-event simulation skills: delayed load semantics, proportional passive cooling with vibration penalties, fixed-point active cooling selection, and transition-only status reporting.
Problem
You are building a firmware simulator for a multicore processor's thermal management unit. The processor has a fixed set of cores that share a passive cooling budget. Each core can also be assigned its own dedicated active cooling channel, but running multiple active channels introduces mechanical vibration that reduces passive cooling efficiency for everyone.
Implement the following function:
thermal_controller_sim(
passive_capacity,
active_capacity_per_core,
core_ids,
operations
) -> list of tick results
Operations arrive in one of two forms:
["set", timestamp, core_id, load_watts]
["tick", timestamp]
Return one list per tick operation. Each list contains strings of the form "core_id=status", sorted alphabetically by core_id, covering only the cores whose status changed at that tick. A status is one of:
idle— the core is running and was not assigned active cooling for the coming intervalcooling— the core is running and was assigned active cooling for the coming intervalshutdown— the core has been switched off due to overheating
Initial State
Every core begins at 20.0 °C, running with a load of 0 watts, active cooling off, and status idle.
Handling set Operations
A set records a pending load for a core but does not advance time or change temperatures. If multiple set operations target the same core before the next tick, only the last one is kept.
- For a running core, the pending load is applied after temperature advancement and shutdown checks at the next
tick. - For a shutdown core, the
setacts as a one-time restart request. At the nexttick, after advancement, the core restarts with that load if and only if its temperature is strictly below50.0 °C. Otherwise the request is silently discarded and the core remains shutdown with load0.
Handling tick Operations
Each tick runs the following five phases in order.
Phase 1 — Advance temperatures.
The first tick establishes the time origin; it advances by zero seconds. Every subsequent tick advances by the elapsed seconds since the previous tick. The interval uses the loads and active-cooling assignments established at the previous tick.
For each core, its passive demand is load + 2 watts. If k cores were assigned active cooling during this interval, the effective passive capacity is:
effective_capacity = passive_capacity × (1 − vibration_penalty(k) / 100)
where:
vibration_penalty(0) = 0
vibration_penalty(k) = sum(10 / F[i] for i = 1 to k)
F = [1, 2, 3, 5, 8, 13, ...] (Fibonacci, starting at F[1] = 1)
If the sum of all cores' passive demands is at most effective_capacity, every core receives its full demand. Otherwise every core receives the same proportional fraction:
passive_for_core = effective_capacity × core_demand / total_demand
A core that was assigned active cooling also receives active_capacity_per_core additional watts of cooling. Net heat for a core is:
net_heat = load − passive_for_core − active_cooling_for_core
Temperature changes at 0.02 °C per second per watt of net heat, and never falls below 20.0 °C. A shutdown core contributes its 2-watt passive demand to the total but has load 0 and no active cooling.
Phase 2 — Shutdown check.
After advancement, any running core whose temperature is at or above 80.0 °C shuts down. Its load is set to 0, its active-cooling flag is cleared, and any pending load for it is discarded.
Phase 3 — Apply pending loads and restart requests.
For each core with a pending entry (in any order):
- Running cores adopt the pending load immediately.
- Shutdown cores attempt a restart as described above.
All pending entries are cleared after this phase, regardless of outcome.
Phase 4 — Recompute active cooling.
Active-cooling assignment is rebuilt from scratch. Shutdown cores are never assigned cooling. Use the following monotone fixed-point procedure:
- Seed the selected set with every running core whose current temperature is strictly above
60.0 °C. - With the current selected-set size
k, recomputeeffective_capacityand the passive allocation using the current loads. - For each running core not yet in the selected set, compute its temperature rate without active cooling:
rate = 0.02 × (load − passive_for_core). Ifrate > 0.5 °C/s, add it to the selected set. - Repeat from step 2 until no new core is added.
The resulting set is applied for the interval ending at the next tick.
Phase 5 — Report status changes.
Each core's new status is shutdown, cooling, or idle. Compare it to the status recorded after the previous tick (or the initial idle before the first tick). Emit one "core_id=status" string for every core whose status changed, sorted alphabetically. A tick where no core changes status returns an empty list.
Constraints
1 ≤ len(core_ids) < 1024; all identifiers are unique, non-empty strings.passive_capacity > 0andactive_capacity_per_core > 0.1 < len(operations) < 1024.- All operation timestamps are strictly increasing positive values with millisecond precision.
0 ≤ load_watts ≤ 32768, with at most three decimal places.- Test values are designed to stay safely away from the exact boundary values
50.0,60.0,80.0, and0.5except when the problem intentionally tests strict vs. non-strict behavior. - Temperature values are never returned; only status strings appear in the output.
Examples
Example 1
Input: thermal_controller_sim(100, 30, ['core1', 'core2'], [['tick', 1], ['set', 2, 'core1', 20], ['tick', 3], ['tick', 8]])
Output: [[], [], []]
Example 2
Input: thermal_controller_sim(8, 10, ['b', 'a'], [['set', 1, 'a', 40], ['tick', 2], ['set', 3, 'b', 5], ['tick', 5], ['tick', 10]])
Output: [['a=cooling'], [], []]
Hints
Hint 1
A `set` never changes temperature or status on its own — it only writes into a pending map. Repeated sets to the same core before a tick are naturally handled by overwriting the same key.
Hint 2
The vibration penalty depends only on how many cores have active cooling, not which ones. This means effective passive capacity is a monotone non-increasing function of the selected-set size, so once a core's uncooled rate crosses the threshold it stays above it for any larger selected set — the fixed point is guaranteed to terminate.
Hint 3
Keep two clearly separated snapshots: the loads and active-cooling set from the *previous* tick (used for thermal advancement) and the updated state being built for the *next* interval. Mixing them up — especially applying new loads before advancing temperature, or using the new cooling set for the current interval — is the most common source of wrong answers.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a discrete-event simulation. Because loads and cooling assignments are constant between ticks, every core's net heat is constant within an interval and temperature changes linearly. There is no need to step second by second — you only need to evaluate state at tick boundaries.
The core discipline is maintaining two clearly separated snapshots:
- The previous-interval snapshot (loads + active set chosen at the last tick) drives thermal advancement for the current tick.
- The next-interval snapshot (post-shutdown loads, applied pending loads, new cooling set) only takes effect starting from the current tick onward.
Conflating these — for example, using updated loads before advancing, or applying the new cooling set to the current interval — is the single most common error.
Each tick runs five phases in strict order:
- Advance. Compute elapsed time (zero on the first tick). Apply the previous interval's loads and active set to linearly update every core's temperature, clamping at
20.0 °C. - Shutdown. Any running core at or above
80.0 °Cshuts down; its load and active flag are cleared and any pending load is discarded. - Pending loads. Running cores adopt their pending load. Shutdown cores attempt a restart if their temperature is strictly below
50.0 °C; otherwise the request is silently dropped. All pending entries are cleared either way. - Cooling selection. Rebuild the selected set from scratch using the monotone fixed-point procedure. Seed with running cores strictly above
60.0 °C, then iteratively add any running unselected core whose uncooled temperature rate exceeds0.5 °C/s, repeating until no new core is added. - Report. Compare each core's new status against its status from the previous tick and emit only the changed ones, sorted alphabetically.
Why the fixed point terminates and is correct
The vibration penalty increases with the number of selected cores, so effective passive capacity is non-increasing in |selected|. Consequently, each unselected core's uncooled rate is non-decreasing as the selected set grows. Once a core crosses the 0.5 °C/s threshold it stays above it for every larger selected set. This means:
- The selected set only ever grows, never shrinks.
- The loop terminates after at most
ngrowth rounds. - Adding all newly qualifying cores in one batch gives the same minimal stable result as adding them one at a time.
Because passive allocation depends only on the count of selected cores (not which ones), the unselected cores can be sorted by load once, and binary search finds the threshold load in each round — reducing each round from O(n) linear scan to O(log n).
Complexity
set: O(1) — writes into a dict.tick: advancement and shutdown are O(n); cooling selection runs at mostn + 1rounds, each O(log n) with the sorted + binary-search approach, so O(n log n) per tick worst case; reporting is O(n) with pre-sorted IDs.- Overall: O(n log n + T · n log n) where T is the number of operations.
- Space: O(n) for per-core state and the penalty prefix table.
Key edge cases
- First tick: elapsed time is zero, so temperatures do not change. Pending loads and cooling selection still run normally, so a core can appear as
coolingon the very first tick. setbefore first tick: the load does not heat the zero-length first interval; it only takes effect after that tick.- Shutdown and
setin the same tick: if a core shuts down during phase 2, its pending load (if any) is discarded in that same phase — it is not treated as a restart request. - Failed restart: the core stays
shutdownwith load0. A newsetis required for a future attempt. - Shutdown cores and passive demand: a shutdown core still contributes its
2-watt demand to the passive allocation total, cooling it passively while it waits for a restart condition. - No changes: a tick where no core's status changes returns an empty list
[].
Reference solution
from typing import List
def thermal_controller_sim(passive_capacity: float, active_capacity_per_core: float, core_ids: List[str], operations: List[List]) -> List[List[str]]:
n = len(core_ids)
# Precompute cumulative vibration penalties: penalty[k] for k active cores.
fib = [1, 2]
while len(fib) < n:
fib.append(fib[-1] + fib[-2])
penalties = [0.0]
running_penalty = 0.0
for fib_val in fib[:n]:
running_penalty += 10.0 / fib_val
penalties.append(running_penalty)
# Per-core state
temps = {c: 20.0 for c in core_ids}
loads = {c: 0.0 for c in core_ids}
running = {c: True for c in core_ids}
active = set() # cores with active cooling this interval
prev_status = {c: "idle" for c in core_ids}
pending = {} # last-write-wins pending loads
prev_tick_ts = None
results = []
def passive_scale_factor(total_demand: float, active_count: int) -> float:
"""Return the fraction of demand each core receives from passive cooling."""
capacity = passive_capacity * (1.0 - penalties[active_count] / 100.0)
if total_demand <= capacity:
return 1.0
return capacity / total_demand
for op in operations:
if op[0] == "set":
_, _ts, core, watts = op
pending[core] = float(watts) # later set overwrites earlier one
continue
# ---- tick ----
_, ts = op
elapsed = 0.0 if prev_tick_ts is None else ts - prev_tick_ts
prev_tick_ts = ts
# Phase 1: Advance temperatures using previous interval's state.
demands = {c: loads[c] + 2.0 for c in core_ids}
total_demand = sum(demands.values())
factor = passive_scale_factor(total_demand, len(active))
for c in core_ids:
passive_share = demands[c] * factor
active_cooling = active_capacity_per_core if c in active else 0.0
net_heat = loads[c] - passive_share - active_cooling
temps[c] = max(20.0, temps[c] + 0.02 * net_heat * elapsed)
# Phase 2: Shut down every running core at or above 80 °C.
for c in core_ids:
if running[c] and temps[c] >= 80.0:
running[c] = False
loads[c] = 0.0
active.discard(c)
pending.pop(c, None) # discard pending load for newly-downed core
# Phase 3: Apply pending loads; attempt restarts for shutdown cores.
for c, watts in pending.items():
if running[c]:
loads[c] = watts
elif temps[c] < 50.0: # strict: restart only if strictly below 50
running[c] = True
loads[c] = watts
# else: request silently discarded; core stays down with load 0
pending.clear()
# Phase 4: Recompute active-cooling assignment from scratch.
# Seed with running cores strictly above 60 °C.
selected = {c for c in core_ids if running[c] and temps[c] > 60.0}
# Monotone fixed-point: add cores whose uncooled rate exceeds 0.5 °C/s.
# Rate for an unselected core = 0.02 * (load - passive_share).
# Passive share depends only on how many cores are selected (not which),
# so sorting by load lets binary search find the threshold each round.
unselected = sorted(
(loads[c], c)
for c in core_ids
if running[c] and c not in selected
)
end = len(unselected)
while end:
current_total = sum(loads[c] + 2.0 for c in core_ids)
factor = passive_scale_factor(current_total, len(selected))
# Binary search: find leftmost index where rate > 0.5.
# rate = 0.02 * (load - factor * (load + 2))
lo, hi = 0, end
while lo < hi:
mid = (lo + hi) // 2
load_val = unselected[mid][0]
rate = 0.02 * (load_val - factor * (load_val + 2.0))
if rate > 0.5:
hi = mid
else:
lo = mid + 1
first_over = lo
if first_over == end:
break # no new cores qualify; fixed point reached
# Add all newly qualifying cores in one batch.
for _, c in unselected[first_over:end]:
selected.add(c)
end = first_over # remaining unselected are all below threshold
active = selected
# Phase 5: Derive current status and report changes.
curr_status = {}
for c in core_ids:
if not running[c]:
curr_status[c] = "shutdown"
elif c in active:
curr_status[c] = "cooling"
else:
curr_status[c] = "idle"
changes = [
f"{c}={curr_status[c]}"
for c in sorted(core_ids)
if curr_status[c] != prev_status[c]
]
results.append(changes)
prev_status = curr_status
return results