From 1a7a1cca681dbd2603c19370e4c87812e16d85f8 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Fri, 3 Jul 2026 00:29:51 -0700 Subject: [PATCH] Add timeline insight metrics --- .../feature-extractor.service.spec.ts | 5 +- .../analysis/timeline-metric.service.spec.ts | 376 +++++++++ .../analysis/timeline-metric.service.ts | 718 ++++++++++++++++++ apps/api/src/shared-contract.spec.ts | 115 ++- packages/shared/src/feature-registry.ts | 119 +++ 5 files changed, 1328 insertions(+), 5 deletions(-) diff --git a/apps/api/src/modules/analysis/feature-extractor.service.spec.ts b/apps/api/src/modules/analysis/feature-extractor.service.spec.ts index c9cd315..f151250 100644 --- a/apps/api/src/modules/analysis/feature-extractor.service.spec.ts +++ b/apps/api/src/modules/analysis/feature-extractor.service.spec.ts @@ -119,6 +119,7 @@ describe('FeatureExtractorService', () => { includeInVector: true, }, ]; + const vectorMetrics = metrics.filter((metric) => metric.includeInVector); let feature: | ReturnType @@ -129,7 +130,7 @@ describe('FeatureExtractorService', () => { ...actualShared, FEATURE_SCHEMA_VERSION: 99, METRICS: metrics, - VECTOR_METRICS: metrics.filter((metric) => metric.includeInVector), + VECTOR_METRICS: vectorMetrics, })); const { FeatureExtractorService: MockedFeatureExtractorService } = jest.requireActual( @@ -146,7 +147,7 @@ describe('FeatureExtractorService', () => { expect(feature?.features.futureTimelineMetric).toBeUndefined(); expect(feature?.normalized.futureTimelineMetric).toBeUndefined(); - expect(feature?.vector).toHaveLength(metrics.length); + expect(feature?.vector).toHaveLength(vectorMetrics.length); expect(feature?.vector.at(-1)).toBe(0); expect(feature?.featureSchemaVersion).toBe(99); }); diff --git a/apps/api/src/modules/analysis/timeline-metric.service.spec.ts b/apps/api/src/modules/analysis/timeline-metric.service.spec.ts index 9d35c32..5818d5e 100644 --- a/apps/api/src/modules/analysis/timeline-metric.service.spec.ts +++ b/apps/api/src/modules/analysis/timeline-metric.service.spec.ts @@ -222,6 +222,178 @@ function createTimeline() { }; } +function createInsightTimeline() { + return { + info: { + frames: [ + { + timestamp: 10 * 60_000, + events: [ + { + actualStartTime: 640_000, + type: 'OBJECTIVE_BOUNTY_PRESTART', + timestamp: 590_000, + teamId: 100, + }, + ], + participantFrames: { + '1': participantFrame({ + minionsKilled: 80, + position: { x: 7_500, y: 7_500 }, + totalGold: 4_000, + xp: 5_000, + }), + '6': participantFrame({ + minionsKilled: 72, + totalGold: 3_400, + xp: 4_700, + }), + }, + }, + { + timestamp: 11 * 60_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 650_000, + killerId: 1, + victimId: 6, + shutdownBounty: 450, + assistingParticipantIds: [], + }, + ], + participantFrames: { + '1': participantFrame({ position: { x: 7_800, y: 9_000 } }), + }, + }, + { + timestamp: 12 * 60_000, + events: [ + { + type: 'TURRET_PLATE_DESTROYED', + timestamp: 700_000, + teamId: 200, + laneType: 'MID_LANE', + }, + { + type: 'OBJECTIVE_BOUNTY_FINISH', + timestamp: 700_000, + teamId: 100, + }, + ], + participantFrames: { + '1': participantFrame({ position: { x: 7_800, y: 7_800 } }), + }, + }, + { + timestamp: 800_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 800_000, + killerId: 1, + victimId: 7, + assistingParticipantIds: [], + }, + ], + participantFrames: { + '1': participantFrame({ position: { x: 9_866, y: 4_414 } }), + }, + }, + { + timestamp: 14 * 60_000, + events: [], + participantFrames: { + '1': participantFrame({ + position: { x: 9_866, y: 4_414 }, + totalGold: 5_800, + }), + '2': participantFrame({ position: { x: 8_800, y: 4_600 } }), + '3': participantFrame({ position: { x: 1_000, y: 13_000 } }), + '6': participantFrame({ totalGold: 5_500 }), + }, + }, + { + timestamp: 15 * 60_000, + events: [ + { + type: 'ELITE_MONSTER_KILL', + timestamp: 900_000, + killerId: 2, + killerTeamId: 100, + monsterType: 'DRAGON', + assistingParticipantIds: [1], + position: { x: 9_866, y: 4_414 }, + }, + ], + participantFrames: { + '1': participantFrame({ position: { x: 9_866, y: 4_414 } }), + }, + }, + { + timestamp: 20 * 60_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 1_030_000, + killerId: 6, + victimId: 1, + assistingParticipantIds: [], + }, + { + type: 'CHAMPION_KILL', + timestamp: 1_215_000, + killerId: 2, + victimId: 7, + assistingParticipantIds: [], + }, + ], + participantFrames: { + '1': participantFrame({ + position: { x: 7_500, y: 7_500 }, + totalGold: 8_000, + }), + '6': participantFrame({ totalGold: 7_700 }), + }, + }, + ], + }, + }; +} + +function createDeficitRecoveryTimeline() { + return { + info: { + frames: [ + { + timestamp: 10 * 60_000, + events: [], + participantFrames: { + '1': participantFrame({ + minionsKilled: 65, + totalGold: 3_200, + xp: 4_200, + }), + '6': participantFrame({ + minionsKilled: 75, + totalGold: 3_900, + xp: 4_600, + }), + }, + }, + { + timestamp: 20 * 60_000, + events: [], + participantFrames: { + '1': participantFrame({ totalGold: 7_500 }), + '6': participantFrame({ totalGold: 7_300 }), + }, + }, + ], + }, + }; +} + describe('TimelineMetricService', () => { const service = new TimelineMetricService(); @@ -339,4 +511,208 @@ describe('TimelineMetricService', () => { result.normalized.ccTimePerMinute, ); }); + + it('extracts timeline insight metrics outside the vector', () => { + const feature = createBaseFeature(); + const result = service.extractTimelineMetrics( + feature, + createRawMatch(), + createInsightTimeline(), + { + advantageEvents: [ + { + timestampMs: 600_000, + teamId: 100, + type: 'championKill', + score: 1, + participantIds: [1], + }, + { + timestampMs: 650_000, + teamId: 100, + type: 'championKill', + score: 1, + participantIds: [1], + }, + { + timestampMs: 1_030_000, + teamId: 200, + type: 'championKill', + score: 1, + participantIds: [6], + }, + { + timestampMs: 1_215_000, + teamId: 100, + type: 'championKill', + score: 1, + participantIds: [2], + }, + ], + deathEvents: [ + { + t: 1_000_000, + victimParticipantId: 1, + x: 7_500, + y: 7_500, + zone: 'middleLane', + shutdownBountyGiven: 0, + nearestAllyDistanceApprox: 5_000, + }, + { + t: 1_200_000, + victimParticipantId: 1, + x: 7_500, + y: 7_500, + zone: 'middleLane', + shutdownBountyGiven: 0, + nearestAllyDistanceApprox: 1_000, + }, + ], + fightClusters: [ + { + startTimeMs: 850_000, + endTimeMs: 870_000, + killCount: 2, + participantIds: [1, 2, 6, 7], + openerParticipantIds: [1], + cleanupParticipantIds: [2], + isTeamfight: false, + }, + ], + objectiveWindows: [ + { + objectiveTimeMs: 900_000, + startTimeMs: 780_000, + endTimeMs: 930_000, + killerParticipantId: 2, + killerTeamId: 100, + monsterType: 'DRAGON', + position: { x: 9_866, y: 4_414 }, + }, + ], + roamFrames: [ + { + t: 600_000, + participantId: 1, + teamId: 100, + x: 7_500, + y: 7_500, + zone: 'river', + assignedLaneZone: 'middleLane', + }, + { + t: 660_000, + participantId: 1, + teamId: 100, + x: 8_000, + y: 7_000, + zone: 'river', + assignedLaneZone: 'middleLane', + }, + ], + }, + ); + + expect(result.features).toMatchObject({ + objectiveFightOpeningParticipationRateNumerator: 1, + objectiveFightOpeningParticipationRateDenominator: 1, + objectiveFightOpeningConvertedToObjectiveRateNumerator: 1, + objectiveFightOpeningConvertedToObjectiveRateDenominator: 1, + preObjectivePitPresenceRateNumerator: 1, + preObjectivePitPresenceRateDenominator: 1, + preObjectivePickParticipationRateNumerator: 1, + preObjectivePickParticipationRateDenominator: 1, + deathFollowedByTeamLossRateNumerator: 1, + deathFollowedByTeamLossRateDenominator: 2, + deathTradedForTeamAdvantageRateNumerator: 1, + deathTradedForTeamAdvantageRateDenominator: 2, + deathWhileIsolatedFromNearestAllyRateNumerator: 1, + deathWhileIsolatedFromNearestAllyRateDenominator: 2, + laneLeadConversionRateNumerator: 1, + laneLeadConversionRateDenominator: 1, + roamConvertedToTeamAdvantageRateNumerator: 1, + roamConvertedToTeamAdvantageRateDenominator: 1, + shutdownGoldCollectedPerGame: 450, + platePresenceParticipationRateNumerator: 1, + platePresenceParticipationRateDenominator: 1, + objectiveBountyComebackParticipationRateNumerator: 1, + objectiveBountyComebackParticipationRateDenominator: 1, + }); + expect(result.normalized.objectiveFightOpeningParticipationRate).toBe(1); + expect(result.normalized.deathFollowedByTeamLossRate).toBe(0.5); + expect(result.normalized.deathTradedForTeamAdvantageRate).toBe(0.5); + expect(result.normalized.deathWhileIsolatedFromNearestAllyRate).toBe(0.5); + expect(result.vector).toHaveLength(VECTOR_METRICS.length); + expect( + VECTOR_METRICS.some( + (metric) => metric.id === 'shutdownGoldCollectedPerGame', + ), + ).toBe(false); + }); + + it('extracts early deficit recovery as a sparse ratio metric', () => { + const feature = createBaseFeature(); + const result = service.extractTimelineMetrics( + feature, + createRawMatch(), + createDeficitRecoveryTimeline(), + { + advantageEvents: [], + deathEvents: [], + fightClusters: [], + objectiveWindows: [], + roamFrames: [], + }, + ); + + expect(result.features).toMatchObject({ + goldDiffAt10: -700, + earlyDeficitRecoveryRateNumerator: 1, + earlyDeficitRecoveryRateDenominator: 1, + laneLeadConversionRateNumerator: 0, + laneLeadConversionRateDenominator: 0, + }); + expect(result.normalized.earlyDeficitRecoveryRate).toBe(1); + }); + + it('does not count the death kill event as a follow-up team loss', () => { + const feature = createBaseFeature(); + const result = service.extractTimelineMetrics( + feature, + createRawMatch(), + createTimeline(), + { + advantageEvents: [ + { + timestampMs: 400_000, + teamId: 200, + type: 'championKill', + score: 1, + participantIds: [6], + }, + ], + deathEvents: [ + { + t: 400_000, + victimParticipantId: 1, + x: 4_000, + y: 4_000, + zone: 'middleLane', + shutdownBountyGiven: 0, + nearestAllyDistanceApprox: 1_500, + }, + ], + fightClusters: [], + objectiveWindows: [], + roamFrames: [], + }, + ); + + expect(result.features).toMatchObject({ + deathFollowedByTeamLossRateNumerator: 0, + deathFollowedByTeamLossRateDenominator: 1, + }); + expect(result.normalized.deathFollowedByTeamLossRate).toBe(0); + }); }); diff --git a/apps/api/src/modules/analysis/timeline-metric.service.ts b/apps/api/src/modules/analysis/timeline-metric.service.ts index f8be343..5755adb 100644 --- a/apps/api/src/modules/analysis/timeline-metric.service.ts +++ b/apps/api/src/modules/analysis/timeline-metric.service.ts @@ -1,8 +1,10 @@ import { METRICS, + SUMMONERS_RIFT_MAP, VECTOR_METRICS, type MetricDefinition, type Role, + type SummonersRiftMapZone, } from '@persona-lenz/shared'; import { Injectable } from '@nestjs/common'; import type { ExtractedPlayerMatchFeature } from './analysis.types'; @@ -53,6 +55,11 @@ interface TimelineMetricContext { teamId: 100 | 200; } +interface TimelineRoamEpisode { + startTimeMs: number; + endTimeMs: number; +} + export interface TimelineMetricExtractionResult { features: Record; normalized: Record; @@ -64,11 +71,28 @@ const FOURTEEN_MINUTES_MS = 14 * 60_000; const TWENTY_MINUTES_MS = 20 * 60_000; const FRAME_MATCH_TOLERANCE_MS = 30_000; const OBJECTIVE_PRE_WARD_WINDOW_MS = 60_000; +const OBJECTIVE_FIGHT_CONVERSION_WINDOW_MS = 90_000; +const PRE_OBJECTIVE_PRESENCE_WINDOW_MS = 90_000; +const PRE_OBJECTIVE_PICK_WINDOW_MS = 120_000; +const DEATH_FOLLOWUP_WINDOW_MS = 60_000; +const DEATH_TRADE_WINDOW_MS = 30_000; +const ROAM_EPISODE_MAX_GAP_MS = 90_000; +const ROAM_CONVERSION_WINDOW_MS = 90_000; +const ISOLATED_DEATH_DISTANCE = 4_000; +const LANE_LEAD_THRESHOLD_GOLD = 500; const OBJECTIVE_MONSTER_TYPES = new Set([ 'DRAGON', 'RIFTHERALD', 'BARON_NASHOR', ]); +const OBJECTIVE_BOUNTY_START_EVENT_TYPES = new Set([ + 'OBJECTIVE_BOUNTY_PRESTART', + 'OBJECTIVE_BOUNTY_START', +]); +const OBJECTIVE_BOUNTY_END_EVENT_TYPES = new Set([ + 'OBJECTIVE_BOUNTY_FINISH', + 'OBJECTIVE_BOUNTY_END', +]); function asRecord(value: unknown): Record { if (typeof value === 'object' && value !== null && !Array.isArray(value)) { @@ -257,6 +281,26 @@ function eventTeamId( ); } +function opposingTeamId(teamId: 100 | 200 | undefined): 100 | 200 | undefined { + if (teamId === 100) { + return 200; + } + if (teamId === 200) { + return 100; + } + return undefined; +} + +function structureScoringTeamId( + event: Record, + participants: MatchParticipant[], +): 100 | 200 | undefined { + return ( + participantTeamId(participants, asParticipantId(event.killerId)) ?? + opposingTeamId(asTeamId(event.teamId)) + ); +} + function eventInvolvesParticipant( event: Record, participantId: number, @@ -285,10 +329,94 @@ function isObjectiveMonsterEvent(event: Record): boolean { ); } +function isTowerBuildingKillEvent(event: Record): boolean { + return ( + asString(event.type) === 'BUILDING_KILL' && + (asString(event.buildingType) === 'TOWER_BUILDING' || + asString(event.towerType) !== undefined) + ); +} + function distance(left: TimelinePosition, right: TimelinePosition): number { return Math.hypot(left.x - right.x, left.y - right.y); } +function isWithinRadius( + position: TimelinePosition, + center: TimelinePosition, + radius: number, +): boolean { + return distance(position, center) <= radius; +} + +function classifySummonersRiftPosition( + position: TimelinePosition | undefined, +): SummonersRiftMapZone { + if (!position) { + return 'unknown'; + } + + const { + baronPit, + baseRadius, + coordinateMax, + coordinateMin, + dragonPit, + jungleMidline, + laneAxisHalfWidth, + objectivePitRadius, + riverBandHalfWidth, + } = SUMMONERS_RIFT_MAP; + const { x, y } = position; + + if ( + x < coordinateMin || + y < coordinateMin || + x > coordinateMax || + y > coordinateMax + ) { + return 'unknown'; + } + if (isWithinRadius(position, dragonPit, objectivePitRadius)) { + return 'dragonPit'; + } + if (isWithinRadius(position, baronPit, objectivePitRadius)) { + return 'baronPit'; + } + if (x <= baseRadius && y <= baseRadius) { + return 'blueBase'; + } + if (x >= coordinateMax - baseRadius && y >= coordinateMax - baseRadius) { + return 'redBase'; + } + if (Math.abs(x + y - coordinateMax) <= riverBandHalfWidth) { + return 'river'; + } + if (x <= laneAxisHalfWidth || y >= coordinateMax - laneAxisHalfWidth) { + return 'topLane'; + } + if (Math.abs(x - y) <= laneAxisHalfWidth) { + return 'middleLane'; + } + if (y <= laneAxisHalfWidth || x >= coordinateMax - laneAxisHalfWidth) { + return 'bottomLane'; + } + if (x < jungleMidline && y >= jungleMidline) { + return 'northWestJungle'; + } + if (x >= jungleMidline && y >= jungleMidline) { + return 'northEastJungle'; + } + if (x < jungleMidline && y < jungleMidline) { + return 'southWestJungle'; + } + if (x >= jungleMidline && y < jungleMidline) { + return 'southEastJungle'; + } + + return 'unknown'; +} + function csAt(frame: TimelineParticipantFrame | undefined): number | undefined { if (!frame) { return undefined; @@ -323,6 +451,100 @@ function finalParticipantFrame( return undefined; } +function findFrameAtOrBefore( + frames: TimelineFrame[], + timestampMs: number, +): TimelineFrame | undefined { + let selected: TimelineFrame | undefined; + for (const frame of frames) { + if (frame.timestamp > timestampMs) { + break; + } + selected = frame; + } + return selected; +} + +function timelineEvents( + context: TimelineMetricContext, +): Record[] { + return context.frames.flatMap((frame) => frame.events); +} + +function eventTimestamp(event: Record): number | undefined { + return asNumber(event.timestamp); +} + +function objectiveBountyStartTimestamp( + event: Record, +): number | undefined { + return asNumber(event.actualStartTime) ?? eventTimestamp(event); +} + +function isEnemyVictim( + event: Record, + context: TimelineMetricContext, +): boolean { + const victimTeamId = participantTeamId( + context.participants, + asParticipantId(event.victimId), + ); + return victimTeamId !== undefined && victimTeamId !== context.teamId; +} + +function objectivePosition( + window: TimelineObjectiveWindow, +): TimelinePosition | undefined { + if (window.position) { + return window.position; + } + switch (window.monsterType) { + case 'DRAGON': + return SUMMONERS_RIFT_MAP.dragonPit; + case 'RIFTHERALD': + case 'BARON_NASHOR': + return SUMMONERS_RIFT_MAP.baronPit; + default: + return undefined; + } +} + +function isObjectivePresencePosition( + position: TimelinePosition, + window: TimelineObjectiveWindow, +): boolean { + const objectiveCenter = objectivePosition(window); + if ( + objectiveCenter && + isWithinRadius( + position, + objectiveCenter, + SUMMONERS_RIFT_MAP.objectivePitRadius, + ) + ) { + return true; + } + + return ['river', 'dragonPit', 'baronPit'].includes( + classifySummonersRiftPosition(position), + ); +} + +function plateLaneZone( + laneType: string | undefined, +): SummonersRiftMapZone | undefined { + switch (laneType) { + case 'TOP_LANE': + return 'topLane'; + case 'MID_LANE': + return 'middleLane'; + case 'BOT_LANE': + return 'bottomLane'; + default: + return undefined; + } +} + @Injectable() export class TimelineMetricService { public extractTimelineMetrics( @@ -371,6 +593,14 @@ export class TimelineMetricService { this.addTeamfightMetrics(context, features, normalized); this.addDeathRiskMetric(context, features, normalized); this.addCrowdControlMetric(context, features, normalized); + this.addObjectiveFightInsightMetrics(context, features, normalized); + this.addObjectivePreparationInsightMetrics(context, features, normalized); + this.addDeathInsightMetrics(context, features, normalized); + this.addLaneLeadAndRecoveryInsightMetrics(context, features, normalized); + this.addRoamConversionInsightMetric(context, features, normalized); + this.addShutdownGoldInsightMetric(context, features, normalized); + this.addPlatePresenceInsightMetric(context, features, normalized); + this.addObjectiveBountyInsightMetric(context, features, normalized); const mergedNormalized = { ...feature.normalized, ...normalized }; return { @@ -732,4 +962,492 @@ export class TimelineMetricService { : controlledMs / 1_000 / context.gameMinutes, ); } + + private addObjectiveFightInsightMetrics( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const objectiveFights = context.derived.objectiveWindows.flatMap( + (window) => { + const firstCluster = context.derived.fightClusters.find( + (cluster) => + cluster.startTimeMs >= window.startTimeMs && + cluster.startTimeMs <= window.endTimeMs, + ); + return firstCluster ? [{ window, cluster: firstCluster }] : []; + }, + ); + const playerOpenedObjectiveFights = objectiveFights.filter(({ cluster }) => + cluster.openerParticipantIds.includes(context.participantId), + ); + const convertedObjectiveFights = playerOpenedObjectiveFights.filter( + ({ window, cluster }) => + objectiveWindowTeamId(window, context.participants) === + context.teamId && + window.objectiveTimeMs >= cluster.startTimeMs && + window.objectiveTimeMs <= + cluster.startTimeMs + OBJECTIVE_FIGHT_CONVERSION_WINDOW_MS, + ); + + this.addRatioMetric( + context, + features, + normalized, + 'objectiveFightOpeningParticipationRate', + playerOpenedObjectiveFights.length, + objectiveFights.length, + ); + this.addRatioMetric( + context, + features, + normalized, + 'objectiveFightOpeningConvertedToObjectiveRate', + convertedObjectiveFights.length, + playerOpenedObjectiveFights.length, + ); + } + + private addObjectivePreparationInsightMetrics( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const events = timelineEvents(context); + const ownObjectiveWindows = context.derived.objectiveWindows.filter( + (window) => + objectiveWindowTeamId(window, context.participants) === context.teamId, + ); + const pitPresenceCount = ownObjectiveWindows.filter((window) => + context.frames.some((frame) => { + if ( + frame.timestamp < + window.objectiveTimeMs - PRE_OBJECTIVE_PRESENCE_WINDOW_MS || + frame.timestamp > window.objectiveTimeMs + ) { + return false; + } + + const position = frame.participantFrames.get( + context.participantId, + )?.position; + return position ? isObjectivePresencePosition(position, window) : false; + }), + ).length; + const preObjectivePickCount = ownObjectiveWindows.filter((window) => + events.some((event) => { + const timestamp = eventTimestamp(event); + return ( + asString(event.type) === 'CHAMPION_KILL' && + timestamp !== undefined && + timestamp >= window.objectiveTimeMs - PRE_OBJECTIVE_PICK_WINDOW_MS && + timestamp <= window.objectiveTimeMs && + eventTeamId(event, context.participants) === context.teamId && + isEnemyVictim(event, context) && + eventInvolvesParticipant(event, context.participantId) + ); + }), + ).length; + + this.addRatioMetric( + context, + features, + normalized, + 'preObjectivePitPresenceRate', + pitPresenceCount, + ownObjectiveWindows.length, + ); + this.addRatioMetric( + context, + features, + normalized, + 'preObjectivePickParticipationRate', + preObjectivePickCount, + ownObjectiveWindows.length, + ); + } + + private addDeathInsightMetrics( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const ownDeaths = context.derived.deathEvents.filter( + (event) => event.victimParticipantId === context.participantId, + ); + const opponentTeamId = opposingTeamId(context.teamId); + const deathFollowedByTeamLossCount = ownDeaths.filter((death) => { + const ownScore = this.advantageScoreInWindow( + context, + context.teamId, + death.t + 1, + death.t + DEATH_FOLLOWUP_WINDOW_MS, + ); + const opponentScore = this.advantageScoreInWindow( + context, + opponentTeamId, + death.t + 1, + death.t + DEATH_FOLLOWUP_WINDOW_MS, + ); + return opponentScore > ownScore; + }).length; + const deathTradedForTeamAdvantageCount = ownDeaths.filter((death) => { + const ownScore = this.advantageScoreInWindow( + context, + context.teamId, + death.t - DEATH_TRADE_WINDOW_MS, + death.t + DEATH_TRADE_WINDOW_MS, + ); + const opponentScore = this.advantageScoreInWindow( + context, + opponentTeamId, + death.t - DEATH_TRADE_WINDOW_MS, + death.t + DEATH_TRADE_WINDOW_MS, + ); + return ownScore > opponentScore; + }).length; + const isolatedDeathCount = ownDeaths.filter( + (death) => + death.nearestAllyDistanceApprox !== null && + death.nearestAllyDistanceApprox > ISOLATED_DEATH_DISTANCE, + ).length; + + this.addRatioMetric( + context, + features, + normalized, + 'deathFollowedByTeamLossRate', + deathFollowedByTeamLossCount, + ownDeaths.length, + ); + this.addRatioMetric( + context, + features, + normalized, + 'deathTradedForTeamAdvantageRate', + deathTradedForTeamAdvantageCount, + ownDeaths.length, + ); + this.addRatioMetric( + context, + features, + normalized, + 'deathWhileIsolatedFromNearestAllyRate', + isolatedDeathCount, + ownDeaths.length, + ); + } + + private addLaneLeadAndRecoveryInsightMetrics( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const goldDiffAt10 = + features.goldDiffAt10 ?? this.goldDiffAt(context, TEN_MINUTES_MS); + const goldDiffAt20 = this.goldDiffAt(context, TWENTY_MINUTES_MS); + const earlyDeficitDenominator = + goldDiffAt10 !== undefined && + goldDiffAt20 !== undefined && + goldDiffAt10 < -LANE_LEAD_THRESHOLD_GOLD + ? 1 + : 0; + const earlyDeficitRecovered = + earlyDeficitDenominator === 1 && + goldDiffAt20 !== undefined && + goldDiffAt20 >= 0 + ? 1 + : 0; + const laneLeadDenominator = + goldDiffAt10 !== undefined && goldDiffAt10 > LANE_LEAD_THRESHOLD_GOLD + ? 1 + : 0; + const laneLeadConverted = + laneLeadDenominator === 1 && this.hasLaneLeadConversion(context) ? 1 : 0; + + this.addRatioMetric( + context, + features, + normalized, + 'earlyDeficitRecoveryRate', + earlyDeficitRecovered, + earlyDeficitDenominator, + ); + this.addRatioMetric( + context, + features, + normalized, + 'laneLeadConversionRate', + laneLeadConverted, + laneLeadDenominator, + ); + } + + private addRoamConversionInsightMetric( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const playerRoamEpisodes = this.playerRoamEpisodes(context); + const convertedRoamCount = playerRoamEpisodes.filter((episode) => + context.derived.advantageEvents.some( + (event) => + event.teamId === context.teamId && + event.timestampMs >= episode.startTimeMs && + event.timestampMs <= episode.endTimeMs + ROAM_CONVERSION_WINDOW_MS && + event.participantIds.includes(context.participantId), + ), + ).length; + + this.addRatioMetric( + context, + features, + normalized, + 'roamConvertedToTeamAdvantageRate', + convertedRoamCount, + playerRoamEpisodes.length, + ); + } + + private addShutdownGoldInsightMetric( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const shutdownGoldCollected = timelineEvents(context) + .filter( + (event) => + asString(event.type) === 'CHAMPION_KILL' && + asParticipantId(event.killerId) === context.participantId, + ) + .reduce( + (sum, event) => sum + Math.max(asNumber(event.shutdownBounty) ?? 0, 0), + 0, + ); + + this.addScalarMetric( + context, + features, + normalized, + 'shutdownGoldCollectedPerGame', + shutdownGoldCollected, + ); + } + + private addPlatePresenceInsightMetric( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const ownPlateEvents = timelineEvents(context).filter( + (event) => + asString(event.type) === 'TURRET_PLATE_DESTROYED' && + structureScoringTeamId(event, context.participants) === context.teamId, + ); + const platePresenceCount = ownPlateEvents.filter((event) => { + const timestamp = eventTimestamp(event); + const targetLaneZone = plateLaneZone(asString(event.laneType)); + if (timestamp === undefined || targetLaneZone === undefined) { + return false; + } + + const previousFrame = findFrameAtOrBefore(context.frames, timestamp); + const position = previousFrame?.participantFrames.get( + context.participantId, + )?.position; + return classifySummonersRiftPosition(position) === targetLaneZone; + }).length; + + this.addRatioMetric( + context, + features, + normalized, + 'platePresenceParticipationRate', + platePresenceCount, + ownPlateEvents.length, + ); + } + + private addObjectiveBountyInsightMetric( + context: TimelineMetricContext, + features: Record, + normalized: Record, + ): void { + const activeIntervals = this.objectiveBountyIntervals(context); + const ownAdvantageEventsDuringBounty = + context.derived.advantageEvents.filter( + (event) => + event.teamId === context.teamId && + activeIntervals.some( + (interval) => + event.timestampMs >= interval.startTimeMs && + event.timestampMs <= interval.endTimeMs, + ), + ); + const participantAdvantageEvents = ownAdvantageEventsDuringBounty.filter( + (event) => event.participantIds.includes(context.participantId), + ); + + this.addRatioMetric( + context, + features, + normalized, + 'objectiveBountyComebackParticipationRate', + participantAdvantageEvents.length, + ownAdvantageEventsDuringBounty.length, + ); + } + + private advantageScoreInWindow( + context: TimelineMetricContext, + teamId: 100 | 200 | undefined, + startTimeMs: number, + endTimeMs: number, + ): number { + if (teamId === undefined) { + return 0; + } + + return context.derived.advantageEvents + .filter( + (event) => + event.teamId === teamId && + event.timestampMs >= startTimeMs && + event.timestampMs <= endTimeMs, + ) + .reduce((sum, event) => sum + event.score, 0); + } + + private playerRoamEpisodes( + context: TimelineMetricContext, + ): TimelineRoamEpisode[] { + return context.derived.roamFrames + .filter( + (frame) => + frame.participantId === context.participantId && + frame.teamId === context.teamId, + ) + .sort((left, right) => left.t - right.t) + .reduce((episodes, frame) => { + const previousEpisode = episodes.at(-1); + if ( + previousEpisode && + frame.t - previousEpisode.endTimeMs <= ROAM_EPISODE_MAX_GAP_MS + ) { + previousEpisode.endTimeMs = frame.t; + return episodes; + } + + episodes.push({ + startTimeMs: frame.t, + endTimeMs: frame.t, + }); + return episodes; + }, []); + } + + private goldDiffAt( + context: TimelineMetricContext, + timestampMs: number, + ): number | undefined { + if (!context.laneOpponentParticipantId) { + return undefined; + } + + const frame = findClosestFrame(context.frames, timestampMs); + const participantFrame = frame?.participantFrames.get( + context.participantId, + ); + const opponentFrame = frame?.participantFrames.get( + context.laneOpponentParticipantId, + ); + return participantFrame?.totalGold !== undefined && + opponentFrame?.totalGold !== undefined + ? participantFrame.totalGold - opponentFrame.totalGold + : undefined; + } + + private hasLaneLeadConversion(context: TimelineMetricContext): boolean { + const events = timelineEvents(context).filter((event) => { + const timestamp = eventTimestamp(event); + return ( + timestamp !== undefined && + timestamp >= TEN_MINUTES_MS && + timestamp <= TWENTY_MINUTES_MS + ); + }); + const firstOwnTowerEvent = events + .filter( + (event) => + isTowerBuildingKillEvent(event) && + structureScoringTeamId(event, context.participants) === + context.teamId, + ) + .sort( + (left, right) => + (eventTimestamp(left) ?? 0) - (eventTimestamp(right) ?? 0), + )[0]; + const firstOwnObjectiveEvent = events + .filter( + (event) => + isObjectiveMonsterEvent(event) && + eventTeamId(event, context.participants) === context.teamId, + ) + .sort( + (left, right) => + (eventTimestamp(left) ?? 0) - (eventTimestamp(right) ?? 0), + )[0]; + + return [firstOwnTowerEvent, firstOwnObjectiveEvent].some( + (event) => + event !== undefined && + eventInvolvesParticipant(event, context.participantId), + ); + } + + private objectiveBountyIntervals( + context: TimelineMetricContext, + ): Array<{ startTimeMs: number; endTimeMs: number }> { + const intervals: Array<{ startTimeMs: number; endTimeMs: number }> = []; + let activeStartTimeMs: number | undefined; + const events = [...timelineEvents(context)].sort( + (left, right) => + (eventTimestamp(left) ?? 0) - (eventTimestamp(right) ?? 0), + ); + + for (const event of events) { + if (asTeamId(event.teamId) !== context.teamId) { + continue; + } + + const type = asString(event.type); + if (type && OBJECTIVE_BOUNTY_START_EVENT_TYPES.has(type)) { + activeStartTimeMs ??= objectiveBountyStartTimestamp(event); + } else if ( + type && + OBJECTIVE_BOUNTY_END_EVENT_TYPES.has(type) && + activeStartTimeMs !== undefined + ) { + const timestamp = eventTimestamp(event); + if (timestamp === undefined) { + continue; + } + + intervals.push({ + startTimeMs: activeStartTimeMs, + endTimeMs: timestamp, + }); + activeStartTimeMs = undefined; + } + } + + if (activeStartTimeMs !== undefined) { + intervals.push({ + startTimeMs: activeStartTimeMs, + endTimeMs: Number.POSITIVE_INFINITY, + }); + } + + return intervals; + } } diff --git a/apps/api/src/shared-contract.spec.ts b/apps/api/src/shared-contract.spec.ts index d853300..be10a1c 100644 --- a/apps/api/src/shared-contract.spec.ts +++ b/apps/api/src/shared-contract.spec.ts @@ -41,7 +41,26 @@ const MVP_2_TIMELINE_METRIC_IDS = [ 'deathWithShutdownBountyGivenRate', 'ccTimePerMinute', ]; -const MVP_2_METRIC_IDS = [...MVP_1_METRIC_IDS, ...MVP_2_TIMELINE_METRIC_IDS]; +const MVP_2_INSIGHT_METRIC_IDS = [ + 'objectiveFightOpeningParticipationRate', + 'objectiveFightOpeningConvertedToObjectiveRate', + 'preObjectivePitPresenceRate', + 'preObjectivePickParticipationRate', + 'deathFollowedByTeamLossRate', + 'deathTradedForTeamAdvantageRate', + 'deathWhileIsolatedFromNearestAllyRate', + 'earlyDeficitRecoveryRate', + 'laneLeadConversionRate', + 'roamConvertedToTeamAdvantageRate', + 'shutdownGoldCollectedPerGame', + 'platePresenceParticipationRate', + 'objectiveBountyComebackParticipationRate', +]; +const MVP_2_METRIC_IDS = [ + ...MVP_1_METRIC_IDS, + ...MVP_2_TIMELINE_METRIC_IDS, + ...MVP_2_INSIGHT_METRIC_IDS, +]; const MVP_2_TIMELINE_METRIC_CONTRACTS = [ { id: 'goldDiffAt10', kind: 'scalar', direction: 'higherIsBetter' }, { id: 'goldDiffAt14', kind: 'scalar', direction: 'higherIsBetter' }, @@ -78,24 +97,95 @@ const MVP_2_TIMELINE_METRIC_CONTRACTS = [ }, { id: 'ccTimePerMinute', kind: 'scalar', direction: 'higherIsBetter' }, ] as const; +const MVP_2_INSIGHT_METRIC_CONTRACTS = [ + { + id: 'objectiveFightOpeningParticipationRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'objectiveFightOpeningConvertedToObjectiveRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'preObjectivePitPresenceRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'preObjectivePickParticipationRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'deathFollowedByTeamLossRate', + kind: 'ratio', + direction: 'lowerIsBetter', + }, + { + id: 'deathTradedForTeamAdvantageRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'deathWhileIsolatedFromNearestAllyRate', + kind: 'ratio', + direction: 'lowerIsBetter', + }, + { + id: 'earlyDeficitRecoveryRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'laneLeadConversionRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'roamConvertedToTeamAdvantageRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'shutdownGoldCollectedPerGame', + kind: 'scalar', + direction: 'higherIsBetter', + }, + { + id: 'platePresenceParticipationRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, + { + id: 'objectiveBountyComebackParticipationRate', + kind: 'ratio', + direction: 'higherIsBetter', + }, +] as const; describe('shared feature registry', () => { it('defines MVP 2 vector metrics in the documented order', () => { expect(FEATURE_SCHEMA_VERSION).toBe(2); expect(METRICS.map((metric) => metric.id)).toEqual(MVP_2_METRIC_IDS); expect(VECTOR_DIMENSION).toBe(26); + expect( + METRICS.filter((metric) => metric.includeInVector).map( + (metric) => metric.id, + ), + ).toEqual([...MVP_1_METRIC_IDS, ...MVP_2_TIMELINE_METRIC_IDS]); expect(METRICS.filter((metric) => metric.includeInVector)).toHaveLength( VECTOR_DIMENSION, ); }); - it('keeps metric ids unique and every vector metric normalizable by role', () => { + it('keeps metric ids unique and every metric normalizable by role', () => { const metricIds = METRICS.map((metric) => metric.id); expect(new Set(metricIds).size).toBe(metricIds.length); for (const metric of METRICS) { expect(metric.label).toBeTruthy(); - expect(metric.includeInVector).toBe(true); expect(metric.baseline).toBeDefined(); expect(Object.keys(metric.baseline ?? {}).sort()).toEqual([ 'BOTTOM', @@ -140,6 +230,25 @@ describe('shared feature registry', () => { ); }); + it('defines MVP 2 insight metric aggregation contracts outside the vector', () => { + expect( + MVP_2_INSIGHT_METRIC_IDS.map((metricId) => { + const metric = METRICS.find((candidate) => candidate.id === metricId); + return { + id: metric?.id, + kind: metric?.kind, + direction: metric?.direction, + includeInVector: metric?.includeInVector, + }; + }), + ).toEqual( + MVP_2_INSIGHT_METRIC_CONTRACTS.map((metric) => ({ + ...metric, + includeInVector: false, + })), + ); + }); + it('defines shared advantage event weights for timeline-derived metrics', () => { expect(ADVANTAGE_EVENT_WEIGHTS).toEqual({ championKill: 1, diff --git a/packages/shared/src/feature-registry.ts b/packages/shared/src/feature-registry.ts index 46d63f2..51c1b52 100644 --- a/packages/shared/src/feature-registry.ts +++ b/packages/shared/src/feature-registry.ts @@ -29,6 +29,14 @@ const allRoles = ( baseline: Record, ): Record => baseline; +const rateBaseline = allRoles({ + TOP: { min: 0, max: 1 }, + JUNGLE: { min: 0, max: 1 }, + MIDDLE: { min: 0, max: 1 }, + BOTTOM: { min: 0, max: 1 }, + UTILITY: { min: 0, max: 1 }, +}); + export const METRICS = [ { id: 'kda', @@ -415,6 +423,117 @@ export const METRICS = [ UTILITY: { min: 0, max: 15 }, }), }, + { + id: 'objectiveFightOpeningParticipationRate', + label: '오브젝트 교전 개시 관여율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'objectiveFightOpeningConvertedToObjectiveRate', + label: '오브젝트 교전 개시 전환율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'preObjectivePitPresenceRate', + label: '오브젝트 전 강가 선점률', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'preObjectivePickParticipationRate', + label: '오브젝트 전 픽 관여율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'deathFollowedByTeamLossRate', + label: '사망 후 팀 손실률', + direction: 'lowerIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'deathTradedForTeamAdvantageRate', + label: '이득 교환 사망률', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'deathWhileIsolatedFromNearestAllyRate', + label: '고립 사망률', + direction: 'lowerIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'earlyDeficitRecoveryRate', + label: '초반 열세 복구율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'laneLeadConversionRate', + label: '라인 리드 전환율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'roamConvertedToTeamAdvantageRate', + label: '로밍 이득 전환율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'shutdownGoldCollectedPerGame', + label: '게임당 현상금 획득 골드', + direction: 'higherIsBetter', + kind: 'scalar', + includeInVector: false, + // TODO: MVP 3에서 인구 percentile baseline으로 교체. + baseline: allRoles({ + TOP: { min: 0, max: 1_500 }, + JUNGLE: { min: 0, max: 1_500 }, + MIDDLE: { min: 0, max: 1_500 }, + BOTTOM: { min: 0, max: 1_500 }, + UTILITY: { min: 0, max: 1_000 }, + }), + }, + { + id: 'platePresenceParticipationRate', + label: '플레이트 위치 관여율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, + { + id: 'objectiveBountyComebackParticipationRate', + label: '오브젝트 현상금 역전 관여율', + direction: 'higherIsBetter', + kind: 'ratio', + includeInVector: false, + baseline: rateBaseline, + }, ] as const satisfies readonly MetricDefinition[]; export type MetricId = (typeof METRICS)[number]['id'];