"""Vote engine for DebateMind parliamentary simulation.""" from __future__ import annotations import random from dataclasses import dataclass from debatemind.models.bill import Bill from debatemind.models.faction import Faction @dataclass class FactionVote: """Vote details for a single faction.""" faction_id: str base_probability: float noise: float final_probability: float # clamped to [0.0, 1.0] seats_yes: int seats_no: int @dataclass class VoteResult: """Aggregated vote result across all factions.""" faction_votes: dict[str, FactionVote] # faction_id -> vote details total_yes: int total_no: int threshold: float passed: bool class VoteEngine: """Computes vote outcomes with stochastic noise per faction. Each reading has an increasing majority threshold: Reading 1: >50% Reading 2: >=60% Reading 3: >=66% """ THRESHOLDS: dict[int, float] = {1: 0.50, 2: 0.60, 3: 0.66} def required_majority(self, reading: int) -> float: """Return the majority threshold for the given reading.""" return self.THRESHOLDS[reading] def calculate_votes( self, factions: list[Faction], bill: Bill, rng: random.Random | None = None, ) -> VoteResult: """Compute vote totals with ±0.1 stochastic noise per faction. For each faction: 1. Compute base_probability from evaluate_offer against the bill. 2. Add uniform noise in [-0.1, +0.1]. 3. Clamp to [0.0, 1.0] -> final_probability. 4. seats_yes = round(final_probability * seat_count). 5. Sum all seats_yes, compare against required_majority(reading) * 100. """ if rng is None: rng = random.Random() offer = _bill_to_offer(bill) reading = bill.reading threshold = self.required_majority(reading) if reading in self.THRESHOLDS else 0.50 faction_votes: dict[str, FactionVote] = {} total_yes = 0 total_no = 0 for faction in factions: base_probability = faction.evaluate_offer(offer) noise = rng.uniform(-0.1, 0.1) final_probability = max(0.0, min(1.0, base_probability + noise)) seats_yes = round(final_probability * faction.seat_count) seats_no = faction.seat_count - seats_yes faction_votes[faction.faction_id] = FactionVote( faction_id=faction.faction_id, base_probability=base_probability, noise=noise, final_probability=final_probability, seats_yes=seats_yes, seats_no=seats_no, ) total_yes += seats_yes total_no += seats_no passed = total_yes > threshold * 100 return VoteResult( faction_votes=faction_votes, total_yes=total_yes, total_no=total_no, threshold=threshold, passed=passed, ) def _bill_to_offer(bill: Bill) -> dict: """Convert a bill's current state into an offer dict for evaluate_offer. Maps bill clauses to 'priorities_addressed' keywords so that faction.evaluate_offer can score the bill. """ return { "priorities_addressed": list(bill.clauses), "concessions": {}, }