Compare commits

...
Author SHA1 Message Date
Louis 65ab9d59b9 Timeline: Add cosine similarity clustering
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-09 00:21:08 +02:00
2 changed files with 210 additions and 27 deletions
@@ -225,6 +225,26 @@
</ng-container>
<ng-template #compactTimeline>
<div class="view-toggle" aria-label="Clusteringmethode wechseln">
<button
type="button"
[class.active]="compactClusteringMethod === 'primary-topic'"
[attr.aria-pressed]="compactClusteringMethod === 'primary-topic'"
(click)="setCompactClusteringMethod('primary-topic')"
>
Primary Topic
</button>
<button
type="button"
[class.active]="compactClusteringMethod === 'cosine-similarity'"
[attr.aria-pressed]="compactClusteringMethod === 'cosine-similarity'"
(click)="setCompactClusteringMethod('cosine-similarity')"
>
Cosine Similarity
</button>
</div>
<div class="compact-phase-list">
<article
*ngFor="let phase of compactPhases; let index = index; trackBy: trackByPhase"
@@ -26,6 +26,7 @@ export interface TopicTimelineElement {
}
export type TimelineViewMode = 'years' | 'compact';
export type CompactClusteringMethod = 'primary-topic' | 'cosine-similarity';
export interface TimelineYearRange {
startYear: number;
@@ -90,6 +91,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
@Output() loadEarlierYears = new EventEmitter<void>();
timelineViewMode: TimelineViewMode = 'years';
compactClusteringMethod: CompactClusteringMethod = 'primary-topic';
minYear = 0;
maxYear = 0;
@@ -100,6 +102,8 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
private readonly columnWidth = 240;
private readonly displayedTopicLimit = 3;
private readonly displayedPhaseTopicLimit = 4;
private readonly compactPhaseSimilarityThreshold = 0.55;
private readonly primaryTopicSimilarityWeight = 1.5;
private readonly scrollRestoreThreshold = 24;
private readonly expandedPhaseIds = new Set<string>();
@@ -148,7 +152,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
}
get compactPhases(): ResearchTimelinePhase[] {
return this.buildCompactPhases(this.timelineItems);
return this.buildCompactPhases(
this.timelineItems,
this.compactClusteringMethod,
);
}
get hasYearRange(): boolean {
@@ -218,6 +225,10 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
this.viewModeChange.emit(mode);
}
setCompactClusteringMethod(method: CompactClusteringMethod): void {
this.compactClusteringMethod = method;
}
onStartYearInput(event: Event): void {
const nextStartYear = this.parseYearInput(event);
@@ -475,45 +486,37 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
this.selectedEndYear = Math.max(clampedStartYear, clampedEndYear);
}
private buildCompactPhases(items: TopicTimelineElement[]): ResearchTimelinePhase[] {
private buildCompactPhases(
items: TopicTimelineElement[],
method: CompactClusteringMethod,
): ResearchTimelinePhase[] {
const phases: ResearchTimelinePhase[] = [];
let currentPhase: WorkingResearchTimelinePhase | undefined;
for (const item of items) {
const candidates = this.getDominantPrimaryTopicCandidates(item);
const primaryTopic = this.getMainTopicItem(item) ?? { name: 'Keine Topics', count: 0 };
if (candidates.length === 0) {
this.pushWorkingPhase(phases, currentPhase);
currentPhase = this.createWorkingPhase(
item,
this.getMainTopicItem(item) ?? { name: 'Keine Topics', count: 0 },
);
if (!currentPhase) {
currentPhase = this.createWorkingPhase(item, primaryTopic);
continue;
}
const matchingCandidate = currentPhase
? candidates.find((candidate) =>
this.isSameTopic(candidate.name, currentPhase?.primaryTopicName),
)
: undefined;
const canExtendCurrentPhase = method === 'cosine-similarity'
? this.canExtendPhaseByTopicSimilarity(currentPhase, item)
: this.canExtendPhaseByPrimaryTopic(currentPhase, item);
const canExtendCurrentPhase =
Boolean(currentPhase) &&
Boolean(matchingCandidate) &&
item.year === currentPhase!.endYear + 1;
if (currentPhase && canExtendCurrentPhase) {
if (canExtendCurrentPhase) {
currentPhase.endYear = item.year;
currentPhase.publication_count += item.publication_count;
currentPhase.years.push(item);
continue;
}
this.pushWorkingPhase(phases, currentPhase);
currentPhase = this.createWorkingPhase(item, candidates[0]);
this.pushWorkingPhase(phases, currentPhase, method);
currentPhase = this.createWorkingPhase(item, primaryTopic);
}
this.pushWorkingPhase(phases, currentPhase);
this.pushWorkingPhase(phases, currentPhase, method);
return phases;
}
@@ -535,15 +538,21 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
private pushWorkingPhase(
phases: ResearchTimelinePhase[],
workingPhase: WorkingResearchTimelinePhase | undefined,
method: CompactClusteringMethod,
): void {
if (!workingPhase) {
return;
}
const primaryTopic = this.aggregatePhasePrimaryTopic(
workingPhase.years,
workingPhase.primaryTopic,
);
const primaryTopic = method === 'cosine-similarity'
? this.aggregateDominantPhasePrimaryTopic(
workingPhase.years,
workingPhase.primaryTopic,
)
: this.aggregatePhasePrimaryTopic(
workingPhase.years,
workingPhase.primaryTopic,
);
phases.push({
...workingPhase,
@@ -585,6 +594,17 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
};
}
private aggregateDominantPhasePrimaryTopic(
years: TopicTimelineElement[],
fallbackPrimaryTopic: TopicTimelineTopic,
): TopicTimelineTopic {
const primaryTopics = this.aggregateTopicsByName(
years.flatMap((year) => year.primary_topics ?? []),
);
return primaryTopics[0] ?? fallbackPrimaryTopic;
}
private aggregatePhaseTopics(
years: TopicTimelineElement[],
primaryTopicName: string,
@@ -627,6 +647,149 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
.slice(0, this.displayedPhaseTopicLimit);
}
private canExtendPhaseByPrimaryTopic(
phase: WorkingResearchTimelinePhase,
item: TopicTimelineElement,
): boolean {
if (item.year !== phase.endYear + 1) {
return false;
}
return this.getDominantPrimaryTopicCandidates(item).some((candidate) =>
this.isSameTopic(candidate.name, phase.primaryTopicName),
);
}
private canExtendPhaseByTopicSimilarity(
phase: WorkingResearchTimelinePhase,
item: TopicTimelineElement,
): boolean {
if (item.year !== phase.endYear + 1) {
return false;
}
const phaseVector = this.createTopicVectorForYears(phase.years);
const itemVector = this.createTopicVector(item);
const similarity = this.calculateCosineSimilarity(phaseVector, itemVector);
return similarity >= this.compactPhaseSimilarityThreshold;
}
private createTopicVectorForYears(
years: TopicTimelineElement[],
): Map<string, number> {
const vector = new Map<string, number>();
for (const year of years) {
this.addTopicsToVector(vector, year.topics, 1);
this.addTopicsToVector(
vector,
year.primary_topics,
this.primaryTopicSimilarityWeight,
);
}
return vector;
}
private createTopicVector(item: TopicTimelineElement): Map<string, number> {
const vector = new Map<string, number>();
this.addTopicsToVector(vector, item.topics, 1);
this.addTopicsToVector(
vector,
item.primary_topics,
this.primaryTopicSimilarityWeight,
);
return vector;
}
private addTopicsToVector(
vector: Map<string, number>,
topics: TopicTimelineTopic[] | undefined,
weight: number,
): void {
for (const topic of topics ?? []) {
const name = this.normalizeTopicName(topic.name);
if (!name) {
continue;
}
vector.set(name, (vector.get(name) ?? 0) + topic.count * weight);
}
}
private calculateCosineSimilarity(
left: Map<string, number>,
right: Map<string, number>,
): number {
const leftNorm = this.calculateVectorNorm(left);
const rightNorm = this.calculateVectorNorm(right);
if (leftNorm === 0 || rightNorm === 0) {
return 0;
}
let dotProduct = 0;
const [smallerVector, largerVector] = left.size < right.size
? [left, right]
: [right, left];
for (const [name, count] of smallerVector.entries()) {
dotProduct += count * (largerVector.get(name) ?? 0);
}
return dotProduct / (leftNorm * rightNorm);
}
private calculateVectorNorm(vector: Map<string, number>): number {
let sumOfSquares = 0;
for (const count of vector.values()) {
sumOfSquares += count * count;
}
return Math.sqrt(sumOfSquares);
}
private aggregateTopicsByName(topics: TopicTimelineTopic[]): TopicTimelineTopic[] {
const counts = new Map<string, number>();
const originalNames = new Map<string, string>();
const ids = new Map<string, string>();
for (const topic of topics) {
const normalizedName = this.normalizeTopicName(topic.name);
if (!normalizedName) {
continue;
}
originalNames.set(normalizedName, topic.name);
if (topic.id) {
ids.set(normalizedName, topic.id);
}
counts.set(normalizedName, (counts.get(normalizedName) ?? 0) + topic.count);
}
return Array.from(counts.entries())
.map(([normalizedName, count]) => ({
id: ids.get(normalizedName),
name: originalNames.get(normalizedName) ?? normalizedName,
count,
}))
.sort((left, right) => {
if (right.count !== left.count) {
return right.count - left.count;
}
return left.name.localeCompare(right.name);
});
}
private normalizeSelectedYears(years: number[]): number[] {
return Array.from(new Set(years))
.filter((year) => Number.isFinite(year))