Add timeline insight metrics

This commit is contained in:
dahyeon committed 2026-07-03 00:29:51 -07:00
1 parent a69e86f2bc
commit 1a7a1cca68
5 files changed
+1328 -5

No files matched your search

@@ -119,6 +119,7 @@ describe('FeatureExtractorService', () => {
includeInVector: true,
},
];
const vectorMetrics = metrics.filter((metric) => metric.includeInVector);
let feature:
| ReturnType<FeatureExtractorService['extractPlayerMatchFeature']>
@@ -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<typeof import('./feature-extractor.service')>(
@@ -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);
});
@@ -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);
});
});
@@ -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<string, number>;
normalized: Record<string, number>;
@@ -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<string, unknown> {
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<string, unknown>,
participants: MatchParticipant[],
): 100 | 200 | undefined {
return (
participantTeamId(participants, asParticipantId(event.killerId)) ??
opposingTeamId(asTeamId(event.teamId))
);
}
function eventInvolvesParticipant(
event: Record<string, unknown>,
participantId: number,
@@ -285,10 +329,94 @@ function isObjectiveMonsterEvent(event: Record<string, unknown>): boolean {
);
}
function isTowerBuildingKillEvent(event: Record<string, unknown>): 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<string, unknown>[] {
return context.frames.flatMap((frame) => frame.events);
}
function eventTimestamp(event: Record<string, unknown>): number | undefined {
return asNumber(event.timestamp);
}
function objectiveBountyStartTimestamp(
event: Record<string, unknown>,
): number | undefined {
return asNumber(event.actualStartTime) ?? eventTimestamp(event);
}
function isEnemyVictim(
event: Record<string, unknown>,
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<string, number>,
normalized: Record<string, number>,
): 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<string, number>,
normalized: Record<string, number>,
): 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<string, number>,
normalized: Record<string, number>,
): 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<string, number>,
normalized: Record<string, number>,
): 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<string, number>,
normalized: Record<string, number>,
): 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<string, number>,
normalized: Record<string, number>,
): 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<string, number>,
normalized: Record<string, number>,
): 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<string, number>,
normalized: Record<string, number>,
): 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<TimelineRoamEpisode[]>((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;
}
}