Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | 27x 11x 1x 1x 27x 23x 1x 28x 1x 27x 27x 83x 83x 27x 81x 28x 28x 28x 28x 28x 28x 28x 28x 28x 30x 30x 29x 29x 7x 29x 16x 29x 7x 29x 88x 88x 14x 29x 29x 60x 60x 59x 29x 19x 1x 18x 19x 19x 19x 85x 30x 55x 40x 19x 19x 19x 19x 19x 19x 19x 72x 52x 44x 11x 19x 19x 19x 19x 19x 19x 19x 19x 2x 16x 16x 11x 5x 18x 15x 18x 16x 85x 30x 16x 11x 18x | /**
* @module data-transformers/risk-analysis
* @description Political risk analysis for parliamentary intelligence.
* Provides coalition risk scoring, anomalous pattern detection, and
* trend comparison capabilities for the Riksdagsmonitor platform.
*
* @author Hack23 AB
* @license Apache-2.0
*/
import type { CIAContext } from './types.js';
/** Risk level categories for coalition stability assessment */
export type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
/** Component scores for coalition risk index */
export interface CoalitionRiskComponents {
/** Voting discipline score (0-100, higher = more disciplined = lower risk) */
votingDiscipline: number;
/** Party defection risk (0-100, higher = more defections = higher risk) */
defectionRisk: number;
/** Confidence threshold proximity (0-100, higher = closer to losing majority = higher risk) */
majorityMarginRisk: number;
}
/** Coalition risk index result */
export interface CoalitionRiskIndex {
/** Composite risk score 0-100 (higher = more risk) */
score: number;
/** Categorical risk level */
level: RiskLevel;
/** Individual component scores */
components: CoalitionRiskComponents;
/** Human-readable summary */
summary: string;
}
/** Anomaly flag detected in parliamentary data */
export interface AnomalyFlag {
/** Type of anomaly detected */
type: 'CROSS_PARTY_VOTE' | 'LOW_COHESION' | 'HIGH_DEFECTION' | 'NARROW_MAJORITY' | 'UNSTABLE_COALITION';
/** Severity level */
severity: RiskLevel;
/** Human-readable description */
description: string;
/** Party or issue involved (if applicable) */
subject?: string;
}
/** Trend direction indicator */
export type TrendDirection = 'IMPROVING' | 'STABLE' | 'DECLINING' | 'VOLATILE';
/** Trend data point */
export interface TrendDataPoint {
/** Time window label */
window: '30d' | '90d' | '365d';
/** Score or value at this window */
value: number;
/** Direction of trend relative to current */
direction: TrendDirection;
/** Percentage change */
changePercent: number;
}
/** Trend comparison result */
export interface TrendComparison {
/** Trend data across time windows */
trends: TrendDataPoint[];
/** Overall trajectory */
overallDirection: TrendDirection;
/** Key insights from trend analysis */
insights: string[];
}
/**
* Map a numeric stability score to a risk level.
* Higher stability = lower risk.
*/
function stabilityToRiskLevel(stabilityScore: number): RiskLevel {
if (stabilityScore >= 75) return 'LOW';
if (stabilityScore >= 50) return 'MEDIUM';
Iif (stabilityScore >= 25) return 'HIGH';
return 'CRITICAL';
}
/**
* Determine categorical risk level from composite score.
*/
function scoreToRiskLevel(score: number): RiskLevel {
if (score < 25) return 'LOW';
if (score < 50) return 'MEDIUM';
Eif (score < 75) return 'HIGH';
return 'CRITICAL';
}
/**
* Calculate the Coalition Risk Index from CIA intelligence context.
*
* Combines three components:
* - Voting discipline: derived from party cohesion scores
* - Defection risk: derived from defection probability
* - Majority margin risk: derived from the coalition's majority margin
*
* @param data - CIA intelligence context (may be undefined for safe fallback)
* @returns Structured coalition risk index
*/
export function calculateCoalitionRiskIndex(data: CIAContext | undefined): CoalitionRiskIndex {
if (!data) {
return {
score: 50,
level: 'MEDIUM',
components: {
votingDiscipline: 50,
defectionRisk: 50,
majorityMarginRisk: 50,
},
summary: 'Insufficient data to assess coalition risk.',
};
}
const { coalitionStability, partyPerformance } = data;
// Component 1: Voting discipline (average cohesion score across parties, inverted to risk)
const cohesionScores = partyPerformance
.map(p => p.metrics.cohesionScore ?? 0)
.filter(s => s > 0);
const avgCohesion = cohesionScores.length > 0
? cohesionScores.reduce((a, b) => a + b, 0) / cohesionScores.length
: 50;
// Lower cohesion = higher discipline risk (invert)
const votingDiscipline = Math.max(0, Math.min(100, 100 - avgCohesion));
// Component 2: Defection risk (directly from defection probability, scaled 0-100)
const defectionRisk = Math.max(0, Math.min(100,
(coalitionStability.defectionProbability ?? 0) * 100
));
// Component 3: Majority margin risk (lower margin = higher risk)
// majorityMargin of 0 = critical (50 point risk), margin of 50+ = low risk
const margin = coalitionStability.majorityMargin ?? 0;
const majorityMarginRisk = Math.max(0, Math.min(100,
margin <= 0 ? 90 : Math.max(5, 50 - margin * 2)
));
// Composite score: weighted average (defection 40%, discipline 30%, margin 30%)
const score = Math.round(
defectionRisk * 0.4 +
votingDiscipline * 0.3 +
majorityMarginRisk * 0.3
);
const level = scoreToRiskLevel(score);
const stabilityLevel = stabilityToRiskLevel(coalitionStability.stabilityScore ?? 50);
const summary = level === 'CRITICAL'
? `Coalition faces critical stability risk. Defection probability is elevated and majority margin is dangerously thin.`
: level === 'HIGH'
? `Coalition stability is under strain. Voting discipline issues and defection risk require monitoring.`
: level === 'MEDIUM'
? `Coalition shows moderate risk indicators. Stability score is ${coalitionStability.stabilityScore ?? 'unknown'} (${stabilityLevel}).`
: `Coalition demonstrates low risk. Voting discipline is strong and majority margin is adequate.`;
return {
score,
level,
components: {
votingDiscipline,
defectionRisk,
majorityMarginRisk,
},
summary,
};
}
/**
* Detect anomalous patterns in parliamentary voting and coalition data.
*
* Flags:
* - Cross-party voting alignments where opposition aligns with coalition
* - Low party cohesion scores
* - High defection probability
* - Narrow majority margins
* - General coalition instability
*
* @param data - CIA intelligence context (may be undefined)
* @returns Array of anomaly flags (empty if no anomalies detected)
*/
export function detectAnomalousPatterns(data: CIAContext | undefined): AnomalyFlag[] {
const flags: AnomalyFlag[] = [];
if (!data) return flags;
const { coalitionStability, partyPerformance, votingPatterns } = data;
// Check for coalition instability
if (coalitionStability.stabilityScore < 40) {
flags.push({
type: 'UNSTABLE_COALITION',
severity: coalitionStability.stabilityScore < 20 ? 'CRITICAL' : 'HIGH',
description: `Coalition stability score is critically low at ${coalitionStability.stabilityScore}.`,
});
}
// Check for narrow majority
if (coalitionStability.majorityMargin <= 2) {
flags.push({
type: 'NARROW_MAJORITY',
severity: coalitionStability.majorityMargin <= 0 ? 'CRITICAL' : 'HIGH',
description: `Coalition majority margin is only ${coalitionStability.majorityMargin} seat(s) — any defection risks government defeat.`,
});
}
// Check for high defection probability
if (coalitionStability.defectionProbability > 0.3) {
flags.push({
type: 'HIGH_DEFECTION',
severity: coalitionStability.defectionProbability > 0.6 ? 'CRITICAL' : 'HIGH',
description: `Defection probability is elevated at ${(coalitionStability.defectionProbability * 100).toFixed(0)}%.`,
});
}
// Check for low party cohesion
partyPerformance.forEach(party => {
const cohesion = party.metrics.cohesionScore ?? 100;
if (cohesion < 60) {
flags.push({
type: 'LOW_COHESION',
severity: cohesion < 40 ? 'HIGH' : 'MEDIUM',
description: `${party.partyName} shows low voting cohesion at ${cohesion.toFixed(0)}% — internal divisions are likely.`,
subject: party.partyName,
});
}
});
// Check for cross-party voting patterns (opposition aligning with coalition on key issues)
Eif (votingPatterns?.keyIssues) {
votingPatterns.keyIssues.forEach(issue => {
const crossPartyRate = issue.crossPartyVotes ?? 0;
if (crossPartyRate > 30) {
flags.push({
type: 'CROSS_PARTY_VOTE',
severity: crossPartyRate > 60 ? 'HIGH' : 'MEDIUM',
description: `Unusually high cross-party voting (${crossPartyRate}%) detected on topic: ${issue.topic}.`,
subject: issue.topic,
});
}
});
}
return flags;
}
/**
* Generate 30/90/365-day trend comparison for coalition stability.
*
* Uses the stability score and party performance trends to project
* historical trajectory. Since actual historical data is aggregated
* in the CIA context, this function derives directional trends from
* available trend indicators.
*
* @param data - CIA intelligence context (may be undefined)
* @returns Trend comparison with direction indicators and insights
*/
export function generateTrendComparison(data: CIAContext | undefined): TrendComparison {
if (!data) {
return {
trends: [
{ window: '30d', value: 50, direction: 'STABLE', changePercent: 0 },
{ window: '90d', value: 50, direction: 'STABLE', changePercent: 0 },
{ window: '365d', value: 50, direction: 'STABLE', changePercent: 0 },
],
overallDirection: 'STABLE',
insights: ['Insufficient data for trend analysis.'],
};
}
const currentScore = data.coalitionStability.stabilityScore ?? 50;
// Derive trend from party-level support trends
let improvingCount = 0;
let decliningCount = 0;
data.partyPerformance.forEach(party => {
if (party.trends.supportTrend === 'improving' || party.trends.activityTrend === 'increasing') {
improvingCount++;
} else if (party.trends.supportTrend === 'declining' || party.trends.activityTrend === 'decreasing') {
decliningCount++;
}
});
const netTrendBias = improvingCount - decliningCount;
// Estimate past values based on current + trend bias
// These are derived estimates, not historical data points
const shortTermDelta = netTrendBias > 0 ? -3 : netTrendBias < 0 ? 3 : 0;
const medTermDelta = netTrendBias > 0 ? -6 : netTrendBias < 0 ? 6 : 0;
const longTermDelta = netTrendBias > 0 ? -10 : netTrendBias < 0 ? 10 : 0;
const score30d = Math.max(0, Math.min(100, currentScore + shortTermDelta));
const score90d = Math.max(0, Math.min(100, currentScore + medTermDelta));
const score365d = Math.max(0, Math.min(100, currentScore + longTermDelta));
function directionFromChange(change: number): TrendDirection {
if (Math.abs(change) < 2) return 'STABLE';
if (change > 0) return 'IMPROVING';
if (change < -5) return 'VOLATILE';
return 'DECLINING';
}
const change30d = currentScore - score30d;
const change90d = currentScore - score90d;
const change365d = currentScore - score365d;
const trends: TrendDataPoint[] = [
{
window: '30d',
value: score30d,
direction: directionFromChange(change30d),
changePercent: score30d > 0 ? Math.round((change30d / score30d) * 100) : 0,
},
{
window: '90d',
value: score90d,
direction: directionFromChange(change90d),
changePercent: score90d > 0 ? Math.round((change90d / score90d) * 100) : 0,
},
{
window: '365d',
value: score365d,
direction: directionFromChange(change365d),
changePercent: score365d > 0 ? Math.round((change365d / score365d) * 100) : 0,
},
];
// Determine overall direction
const overallChange = change365d;
const overallDirection: TrendDirection = directionFromChange(overallChange);
// Generate insights
const insights: string[] = [];
if (overallDirection === 'IMPROVING') {
insights.push('Coalition stability has been trending upward over the past year.');
I} else if (overallDirection === 'DECLINING') {
insights.push('Coalition stability shows a declining trend over the past year — monitor closely.');
} else if (overallDirection === 'VOLATILE') {
insights.push('Coalition stability is highly volatile — significant shifts detected in trajectory.');
} else {
insights.push('Coalition stability has remained broadly stable over the observed period.');
}
if (data.coalitionStability.majorityMargin <= 5) {
insights.push(`Thin majority margin of ${data.coalitionStability.majorityMargin} amplifies trend sensitivity.`);
}
if (data.partyPerformance.length > 0) {
const highActivity = data.partyPerformance
.filter(p => p.trends.activityTrend === 'increasing')
.map(p => p.partyName);
if (highActivity.length > 0) {
insights.push(`Increasing legislative activity from: ${highActivity.join(', ')}.`);
}
}
return {
trends,
overallDirection,
insights,
};
}
|