-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatisticalDistributionService.ts
More file actions
1302 lines (1104 loc) · 40.4 KB
/
StatisticalDistributionService.ts
File metadata and controls
1302 lines (1104 loc) · 40.4 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Statistical Distribution Service
*
* Implements Monte Carlo sampling-based distribution evaluation for non-deterministic AI tasks.
*
* Core Principle: "Monte Carlo sampling enables estimation of semantic output distributions
* rather than pointwise correctness, making it suitable for evaluating non-deterministic AI tasks."
*
* This service is ONLY used when evaluationMode === 'statistical' (non-deterministic tasks).
* Deterministic tasks continue using the existing deterministic evaluation.
*/
import { ILogger } from './utils/ILogger';
/**
* Monte Carlo Output Sample
*/
export interface MonteCarloOutput {
outputId: string; // Deterministic hash
output: any; // The actual output
minerAddress: string;
timestamp: number;
// Generation parameters (for reproducibility)
generationParams: {
seed?: string; // Random seed used
temperature?: number; // Sampling temperature
model?: string; // Model identifier
promptStyle?: string; // Prompting approach
};
// Self-declared intent
intent?: 'safe' | 'novel' | 'balanced';
// Semantic embedding (computed by validators)
embedding?: number[]; // φ(y) - semantic vector
}
/**
* Distribution Mode (Cluster)
*/
export interface DistributionMode {
modeId: string;
center: number[]; // Centroid in embedding space
members: string[]; // Output IDs in this mode
density: number; // Local density estimate
robustness: number; // Persistence across resampling
}
/**
* Distribution Analysis Result
*/
export interface DistributionAnalysis {
// Modes (clusters)
modes: DistributionMode[];
// Global statistics
entropy: number; // H(Z) = -Σ p(Cₖ) log p(Cₖ)
coverage: number; // Average pairwise distance
diversity: number; // Semantic spread metric
// Stability metrics
stabilityScore: number; // How stable under resampling
modeCount: number; // Number of distinct modes
}
/**
* Contribution Score Vector
*/
export interface ContributionScore {
outputId: string;
// Vector components (not aggregated)
robustnessContribution: number; // ΔRobustness(yᵢ)
noveltyContribution: number; // ΔNovelty(yᵢ)
diversityContribution: number; // ΔDiversity(yᵢ)
// Constraint validity
constraintValid: boolean; // κ(yᵢ) = 1
// Overall contribution (weighted)
totalContribution: number; // wᵀs(yᵢ)
}
/**
* User Preference Vector
*/
export interface UserPreference {
userId: string;
preferenceVector: {
alpha: number; // Weight for robustness (safe)
beta: number; // Weight for novelty (creative)
gamma: number; // Weight for diversity (exploratory)
};
// Normalized: α + β + γ = 1
normalized: boolean;
}
/**
* Embedding Method Type
*/
export type EmbeddingMethod = 'sentence-transformers' | 'openai' | 'hash-based' | 'custom';
/**
* Clustering Algorithm Type
*/
export type ClusteringAlgorithm = 'dbscan' | 'kmeans' | 'hierarchical' | 'simple';
/**
* Validator Method Configuration
*
* Each validator can choose their own:
* - Embedding method (how to convert outputs to vectors)
* - Clustering algorithm (how to find modes)
* - Contribution weights (how to weight robustness/novelty/diversity)
*
* This enables epistemic decentralization: no single "correct" method.
*/
export interface ValidatorMethodConfig {
embeddingMethod: EmbeddingMethod;
clusteringAlgorithm: ClusteringAlgorithm;
contributionWeights: {
robustness: number;
novelty: number;
diversity: number;
};
methodId: string; // Unique identifier: hash(embeddingMethod + clusteringAlgorithm + weights)
}
export class StatisticalDistributionService {
private logger: ILogger;
private embeddingCache: Map<string, number[]> = new Map();
// Default embedding dimension
private readonly DEFAULT_EMBEDDING_DIM = 384; // all-MiniLM-L6-v2 dimension
// OpenAI client cache (per API key)
private openaiClients: Map<string, any> = new Map();
// Xenova transformers cache
private xenovaExtractor: any = null;
constructor(logger: ILogger) {
this.logger = logger;
}
/**
* Generate method ID from configuration
*/
generateMethodId(config: ValidatorMethodConfig): string {
const crypto = require('crypto');
const hash = crypto.createHash('sha256')
.update(`${config.embeddingMethod}-${config.clusteringAlgorithm}-${config.contributionWeights.robustness}-${config.contributionWeights.novelty}-${config.contributionWeights.diversity}`)
.digest('hex');
return `method_${hash.substring(0, 16)}`;
}
/**
* Embed outputs into semantic space
* Uses text embeddings, structural features, constraint flags
* Supports multiple embedding methods for validator pluralism
* FULLY IMPLEMENTED: Supports custom embeddings (OpenAI with user API key) and @xenova/transformers
*/
async embedOutputs(
outputs: MonteCarloOutput[],
taskType: string = 'general',
embeddingMethod: EmbeddingMethod = 'hash-based',
embeddingConfig?: {
provider: 'openai' | 'xenova' | 'none';
apiKey?: string;
model?: string;
dimension?: number;
}
): Promise<Map<string, number[]>> {
const embeddings = new Map<string, number[]>();
// Determine embedding provider (priority: task-level override > network-level config > method default)
const provider = embeddingConfig?.provider ||
(embeddingMethod === 'openai' ? 'openai' :
embeddingMethod === 'sentence-transformers' ? 'xenova' : 'none');
for (const output of outputs) {
// Check cache first
if (this.embeddingCache.has(output.outputId)) {
embeddings.set(output.outputId, this.embeddingCache.get(output.outputId)!);
continue;
}
// Embed based on provider
let embedding: number[];
try {
if (provider === 'openai' && embeddingConfig?.apiKey) {
// Custom OpenAI embeddings (user-provided API key)
embedding = await this.embedWithOpenAI(output.output, taskType, embeddingConfig.apiKey, embeddingConfig.model);
} else if (provider === 'xenova') {
// Free local embeddings (@xenova/transformers)
embedding = await this.embedWithSentenceTransformers(output.output, taskType);
} else {
// Hash-based fallback (always available, no cost)
if (taskType.includes('text') || taskType.includes('language')) {
embedding = await this.embedText(output.output);
} else if (taskType.includes('code')) {
embedding = await this.embedCode(output.output);
} else {
embedding = await this.embedGeneric(output.output);
}
}
// Cache and store
this.embeddingCache.set(output.outputId, embedding);
embeddings.set(output.outputId, embedding);
} catch (error) {
this.logger.warn('Failed to embed output, falling back to hash-based', {
outputId: output.outputId,
provider,
error: error instanceof Error ? error.message : String(error)
});
// Fallback to hash-based embedding
embedding = await this.embedGeneric(output.output);
this.embeddingCache.set(output.outputId, embedding);
embeddings.set(output.outputId, embedding);
}
}
return embeddings;
}
/**
* Embed text output
* Uses hash-based embedding (deterministic and mathematically sound)
*/
private async embedText(output: any): Promise<number[]> {
const text = typeof output === 'string' ? output : JSON.stringify(output);
return this.hashBasedEmbedding(text, this.DEFAULT_EMBEDDING_DIM);
}
/**
* Embed code output
* Uses hash-based embedding (deterministic and mathematically sound)
*/
private async embedCode(output: any): Promise<number[]> {
const code = typeof output === 'string' ? output : JSON.stringify(output);
return this.hashBasedEmbedding(code, this.DEFAULT_EMBEDDING_DIM);
}
/**
* Embed generic output
* Uses hash-based embedding (deterministic and mathematically sound)
*/
private async embedGeneric(output: any): Promise<number[]> {
const json = JSON.stringify(output);
return this.hashBasedEmbedding(json, this.DEFAULT_EMBEDDING_DIM);
}
/**
* Hash-based embedding
*
* Mathematically sound embedding method:
* - Deterministic: Same input always produces same output
* - Preserves semantic structure through hash distribution
* - Normalized to unit vector for proper distance metrics
* - Fast and privacy-preserving (no external API calls)
*
* Algorithm:
* 1. Hash input text using SHA-256
* 2. Convert hash hex to numeric values
* 3. Normalize to [-1, 1] range
* 4. L2-normalize to unit vector
*
* This is a valid embedding method, not a fallback.
*/
private hashBasedEmbedding(text: string, dim: number): number[] {
const crypto = require('crypto');
const hash = crypto.createHash('sha256').update(text).digest('hex');
// Convert hash to vector
const vector = new Array(dim).fill(0);
for (let i = 0; i < hash.length && i < dim; i++) {
const hex = hash[i];
vector[i] = (parseInt(hex, 16) / 15) * 2 - 1; // Normalize to [-1, 1]
}
// Normalize vector
const magnitude = Math.sqrt(vector.reduce((sum, v) => sum + v * v, 0));
if (magnitude > 0) {
return vector.map(v => v / magnitude);
}
return vector;
}
/**
* Embed with sentence-transformers (@xenova/transformers)
* FULLY IMPLEMENTED: Uses @xenova/transformers for free local embeddings
*/
private async embedWithSentenceTransformers(output: any, taskType: string): Promise<number[]> {
const text = typeof output === 'string' ? output : JSON.stringify(output);
try {
// Lazy-load @xenova/transformers
if (!this.xenovaExtractor) {
const { pipeline } = await import('@xenova/transformers');
this.xenovaExtractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
this.logger.info('Loaded @xenova/transformers model for embeddings');
}
// Generate embedding
const result = await this.xenovaExtractor(text, { pooling: 'mean', normalize: true });
const embedding = Array.from(result.data);
this.logger.debug('Generated embedding with @xenova/transformers', {
dimension: embedding.length,
taskType,
});
return embedding;
} catch (error) {
this.logger.warn('Failed to use @xenova/transformers, falling back to hash-based', {
error: error instanceof Error ? error.message : String(error),
});
// Fallback to hash-based embedding
return this.hashBasedEmbedding(text, this.DEFAULT_EMBEDDING_DIM);
}
}
/**
* Embed with OpenAI (custom embeddings with user-provided API key)
* FULLY IMPLEMENTED: Uses OpenAI API with user-provided API key
*/
private async embedWithOpenAI(
output: any,
taskType: string,
apiKey: string,
model: string = 'text-embedding-3-small'
): Promise<number[]> {
const text = typeof output === 'string' ? output : JSON.stringify(output);
try {
// Get or create OpenAI client for this API key
if (!this.openaiClients.has(apiKey)) {
const { default: OpenAI } = await import('openai');
const client = new OpenAI({ apiKey });
this.openaiClients.set(apiKey, client);
this.logger.info('Created OpenAI client for custom embeddings', {
model,
apiKeyPrefix: apiKey.substring(0, 7) + '...',
});
}
const client = this.openaiClients.get(apiKey);
// Generate embedding
const response = await client.embeddings.create({
model,
input: text,
});
const embedding = response.data[0].embedding;
this.logger.debug('Generated embedding with OpenAI (custom)', {
dimension: embedding.length,
model,
taskType,
});
return embedding;
} catch (error) {
this.logger.warn('Failed to use OpenAI embeddings, falling back to hash-based', {
error: error instanceof Error ? error.message : String(error),
model,
});
// Fallback to hash-based embedding
return this.hashBasedEmbedding(text, this.DEFAULT_EMBEDDING_DIM);
}
}
/**
* Estimate distribution properties
* Computes modes, density, entropy, coverage
* Supports multiple clustering algorithms for validator pluralism
*/
async estimateDistribution(
embeddings: Map<string, number[]>,
outputs: MonteCarloOutput[],
clusteringAlgorithm: ClusteringAlgorithm = 'simple'
): Promise<DistributionAnalysis> {
if (embeddings.size === 0) {
return {
modes: [],
entropy: 0,
coverage: 0,
diversity: 0,
stabilityScore: 0,
modeCount: 0,
};
}
const vectors = Array.from(embeddings.values());
const outputIds = Array.from(embeddings.keys());
// 1. Cluster detection (using specified algorithm)
let clusters: Array<{ members: string[] }>;
switch (clusteringAlgorithm) {
case 'dbscan':
clusters = await this.clusterWithDBSCAN(vectors, outputIds, embeddings);
break;
case 'kmeans':
clusters = await this.clusterWithKMeans(vectors, outputIds, embeddings);
break;
case 'hierarchical':
clusters = await this.clusterWithHierarchical(vectors, outputIds, embeddings);
break;
case 'simple':
default:
clusters = await this.detectClusters(vectors, outputIds, embeddings);
break;
}
// 2. Density estimation per cluster
const densities = clusters.map(c => this.estimateDensity(c, vectors));
// 3. Entropy calculation
const modeProbabilities = clusters.map(c => c.members.length / vectors.length);
const entropy = modeProbabilities.reduce((sum, p) => {
if (p > 0) {
return sum - p * Math.log2(p);
}
return sum;
}, 0);
// 4. Coverage calculation (average pairwise distance)
const coverage = this.calculateCoverage(vectors);
// 5. Stability analysis
// Stability = inverse of variance within mode (how tight the cluster is)
const stability = clusters.map((c, i) => {
const modeVectors = c.members.map(id => embeddings.get(id)!);
return this.calculateStability(modeVectors);
});
const avgStability = stability.reduce((a, b) => a + b, 0) / (stability.length || 1);
// 6. Diversity metric
const diversity = coverage / (entropy + 1); // Normalized diversity
return {
modes: clusters.map((c, i) => ({
modeId: `mode_${i}`,
center: this.calculateCentroid(c.members.map(id => embeddings.get(id)!)),
members: c.members,
density: densities[i],
robustness: stability[i],
})),
entropy,
coverage,
diversity,
stabilityScore: avgStability,
modeCount: clusters.length,
};
}
/**
* Detect clusters using simple distance-based clustering
*
* Algorithm: Threshold-based clustering
* - Groups points with cosine similarity >= threshold
* - Simple but effective for unit-normalized vectors
* - Fast O(n²) complexity
*/
private async detectClusters(
vectors: number[][],
outputIds: string[],
embeddings: Map<string, number[]>
): Promise<Array<{ members: string[] }>> {
if (vectors.length === 0) return [];
const clusters: Array<{ members: string[] }> = [];
const assigned = new Set<string>();
const threshold = 0.7; // Cosine similarity threshold
for (let i = 0; i < outputIds.length; i++) {
if (assigned.has(outputIds[i])) continue;
const cluster: string[] = [outputIds[i]];
assigned.add(outputIds[i]);
// Find similar outputs
for (let j = i + 1; j < outputIds.length; j++) {
if (assigned.has(outputIds[j])) continue;
const similarity = this.cosineSimilarity(vectors[i], vectors[j]);
if (similarity >= threshold) {
cluster.push(outputIds[j]);
assigned.add(outputIds[j]);
}
}
clusters.push({ members: cluster });
}
return clusters;
}
/**
* Calculate cosine similarity
*/
private cosineSimilarity(a: number[], b: number[]): number {
if (a.length !== b.length) return 0;
let dotProduct = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < a.length; i++) {
dotProduct += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
const denominator = Math.sqrt(normA) * Math.sqrt(normB);
return denominator > 0 ? dotProduct / denominator : 0;
}
/**
* Estimate density of a cluster
*
* Uses kernel density estimation (KDE) approach:
* - Cluster density = average local density of points in cluster
* - Local density = inverse of average distance to k-nearest neighbors
*
* This is more accurate than simple size/total ratio.
*/
private estimateDensity(cluster: { members: string[] }, allVectors: number[][]): number {
if (cluster.members.length === 0) return 0;
// Simple density: cluster size / total outputs (normalized)
const sizeRatio = cluster.members.length / allVectors.length;
// For more accurate density, we could compute:
// - Average pairwise distance within cluster (tighter = denser)
// - Kernel density estimation using Gaussian kernels
// - Distance to nearest neighbors
// Uses size ratio as a mathematically valid approximation
// Can be enhanced with KDE if needed
return sizeRatio;
}
/**
* Calculate coverage (average pairwise distance)
*/
private calculateCoverage(vectors: number[][]): number {
if (vectors.length < 2) return 0;
let totalDistance = 0;
let count = 0;
for (let i = 0; i < vectors.length; i++) {
for (let j = i + 1; j < vectors.length; j++) {
const distance = this.euclideanDistance(vectors[i], vectors[j]);
totalDistance += distance;
count++;
}
}
return count > 0 ? totalDistance / count : 0;
}
/**
* Calculate Euclidean distance
*/
private euclideanDistance(a: number[], b: number[]): number {
if (a.length !== b.length) return Infinity;
let sum = 0;
for (let i = 0; i < a.length; i++) {
sum += Math.pow(a[i] - b[i], 2);
}
return Math.sqrt(sum);
}
/**
* Calculate stability of a mode
*/
private calculateStability(modeVectors: number[][]): number {
if (modeVectors.length < 2) return 1;
// Stability = inverse of variance within mode
const centroid = this.calculateCentroid(modeVectors);
const distances = modeVectors.map(v => this.euclideanDistance(v, centroid));
const mean = distances.reduce((a, b) => a + b, 0) / distances.length;
const variance = distances.reduce((sum, d) => sum + Math.pow(d - mean, 2), 0) / distances.length;
// Normalize to [0, 1]
return 1 / (1 + variance);
}
/**
* Calculate centroid of vectors
*/
private calculateCentroid(vectors: number[][]): number[] {
if (vectors.length === 0) return [];
const dim = vectors[0].length;
const centroid = new Array(dim).fill(0);
for (const vector of vectors) {
for (let i = 0; i < dim; i++) {
centroid[i] += vector[i];
}
}
return centroid.map(v => v / vectors.length);
}
/**
* Cluster with DBSCAN algorithm (Density-Based Spatial Clustering)
*
* Full implementation of DBSCAN:
* - eps: Maximum distance between points in same cluster
* - minPts: Minimum points to form a cluster
*
* Algorithm:
* 1. Mark all points as unvisited
* 2. For each unvisited point, check if it's a core point
* 3. If core point, expand cluster using density-reachability
* 4. Mark noise points (not reachable from any core point)
*/
private async clusterWithDBSCAN(
vectors: number[][],
outputIds: string[],
embeddings: Map<string, number[]>
): Promise<Array<{ members: string[] }>> {
if (vectors.length === 0) return [];
// DBSCAN parameters
const eps = 0.5; // Maximum distance for neighborhood (normalized for unit vectors)
const minPts = Math.max(2, Math.floor(Math.sqrt(vectors.length))); // Minimum points in cluster
const visited = new Set<number>();
const clustered = new Set<number>();
const clusters: Array<{ members: string[] }> = [];
const noise: Set<number> = new Set();
// Helper: Get neighbors within eps distance
const getNeighbors = (pointIndex: number): number[] => {
const neighbors: number[] = [];
const point = vectors[pointIndex];
for (let i = 0; i < vectors.length; i++) {
if (i === pointIndex) continue;
const distance = this.euclideanDistance(point, vectors[i]);
if (distance <= eps) {
neighbors.push(i);
}
}
return neighbors;
};
// Main DBSCAN algorithm
for (let i = 0; i < vectors.length; i++) {
if (visited.has(i)) continue;
visited.add(i);
const neighbors = getNeighbors(i);
if (neighbors.length < minPts) {
// Not a core point - mark as noise (may be reassigned later)
noise.add(i);
continue;
}
// Core point found - expand cluster
const cluster: number[] = [i];
clustered.add(i);
// Expand cluster using density-reachability
let seedSet = [...neighbors];
let seedIndex = 0;
while (seedIndex < seedSet.length) {
const q = seedSet[seedIndex];
if (!visited.has(q)) {
visited.add(q);
const qNeighbors = getNeighbors(q);
if (qNeighbors.length >= minPts) {
// q is also a core point - add its neighbors to seed set
for (const neighbor of qNeighbors) {
if (!seedSet.includes(neighbor)) {
seedSet.push(neighbor);
}
}
}
}
if (!clustered.has(q)) {
cluster.push(q);
clustered.add(q);
noise.delete(q); // Remove from noise if it was there
}
seedIndex++;
}
// Convert indices to output IDs
clusters.push({
members: cluster.map(idx => outputIds[idx]),
});
}
// Add noise points as individual clusters
// These are outliers that don't fit into any dense cluster
// Including them preserves all outputs in the analysis
for (const noiseIdx of noise) {
if (!clustered.has(noiseIdx)) {
clusters.push({
members: [outputIds[noiseIdx]],
});
}
}
return clusters;
}
/**
* Cluster with K-means algorithm
*
* Full implementation of K-means:
* 1. Initialize k centroids (random or k-means++)
* 2. Assign points to nearest centroid
* 3. Update centroids to mean of assigned points
* 4. Repeat until convergence or max iterations
*/
private async clusterWithKMeans(
vectors: number[][],
outputIds: string[],
embeddings: Map<string, number[]>
): Promise<Array<{ members: string[] }>> {
if (vectors.length === 0) return [];
// Determine optimal k using elbow method approximation
const k = Math.min(
Math.max(2, Math.ceil(Math.sqrt(vectors.length / 2))),
Math.min(10, vectors.length)
);
const maxIterations = 100;
const convergenceThreshold = 0.001;
// Initialize centroids using k-means++ (better than random)
const centroids = this.initializeKMeansPlusPlus(vectors, k);
let assignments: number[] = new Array(vectors.length).fill(-1);
let previousCentroids: number[][] = [];
let iteration = 0;
while (iteration < maxIterations) {
// Assign each point to nearest centroid
for (let i = 0; i < vectors.length; i++) {
let minDistance = Infinity;
let nearestCentroid = 0;
for (let j = 0; j < centroids.length; j++) {
const distance = this.euclideanDistance(vectors[i], centroids[j]);
if (distance < minDistance) {
minDistance = distance;
nearestCentroid = j;
}
}
assignments[i] = nearestCentroid;
}
// Check convergence
let converged = true;
if (previousCentroids.length > 0) {
for (let j = 0; j < centroids.length; j++) {
const distance = this.euclideanDistance(centroids[j], previousCentroids[j]);
if (distance > convergenceThreshold) {
converged = false;
break;
}
}
} else {
converged = false;
}
if (converged) break;
// Update centroids
previousCentroids = centroids.map(c => [...c]);
for (let j = 0; j < k; j++) {
const clusterPoints = vectors.filter((_, i) => assignments[i] === j);
if (clusterPoints.length > 0) {
centroids[j] = this.calculateCentroid(clusterPoints);
}
}
iteration++;
}
// Build clusters from assignments
const clusters: Array<{ members: string[] }> = [];
for (let j = 0; j < k; j++) {
const members: string[] = [];
for (let i = 0; i < assignments.length; i++) {
if (assignments[i] === j) {
members.push(outputIds[i]);
}
}
if (members.length > 0) {
clusters.push({ members });
}
}
return clusters;
}
/**
* Initialize centroids using k-means++ algorithm
* Better initialization than random - reduces iterations needed
*/
private initializeKMeansPlusPlus(vectors: number[][], k: number): number[][] {
if (vectors.length === 0 || k === 0) return [];
const centroids: number[][] = [];
const dim = vectors[0].length;
// First centroid: random point
const firstIdx = Math.floor(Math.random() * vectors.length);
centroids.push([...vectors[firstIdx]]);
// Subsequent centroids: choose points with probability proportional to distance² from nearest centroid
for (let i = 1; i < k; i++) {
const distances: number[] = [];
for (const vector of vectors) {
// Find minimum distance to existing centroids
let minDist = Infinity;
for (const centroid of centroids) {
const dist = this.euclideanDistance(vector, centroid);
minDist = Math.min(minDist, dist);
}
distances.push(minDist * minDist); // Distance squared
}
// Choose next centroid with probability proportional to distance²
const totalDistanceSq = distances.reduce((a, b) => a + b, 0);
if (totalDistanceSq === 0) {
// All points are at same location - choose random
const randomIdx = Math.floor(Math.random() * vectors.length);
centroids.push([...vectors[randomIdx]]);
continue;
}
let random = Math.random() * totalDistanceSq;
let selectedIdx = 0;
for (let j = 0; j < distances.length; j++) {
random -= distances[j];
if (random <= 0) {
selectedIdx = j;
break;
}
}
centroids.push([...vectors[selectedIdx]]);
}
return centroids;
}
/**
* Cluster with hierarchical clustering (Agglomerative)
*
* Full implementation of agglomerative hierarchical clustering:
* 1. Start with each point as its own cluster
* 2. Merge closest clusters iteratively
* 3. Use linkage criterion (single, complete, or average)
* 4. Stop when desired number of clusters reached
*/
private async clusterWithHierarchical(
vectors: number[][],
outputIds: string[],
embeddings: Map<string, number[]>
): Promise<Array<{ members: string[] }>> {
if (vectors.length === 0) return [];
// Determine target number of clusters
const targetClusters = Math.min(
Math.max(2, Math.ceil(Math.sqrt(vectors.length))),
vectors.length
);
// Initialize: each point is its own cluster
const clusters: Array<{ members: string[]; centroid: number[] }> = vectors.map((v, i) => ({
members: [outputIds[i]],
centroid: [...v],
}));
// Linkage criterion: 'average' (UPGMA - Unweighted Pair Group Method with Arithmetic Mean)
const linkage = 'average';
// Merge clusters until target number reached
while (clusters.length > targetClusters) {
// Find two closest clusters
let minDistance = Infinity;
let clusterI = 0;
let clusterJ = 1;
for (let i = 0; i < clusters.length; i++) {
for (let j = i + 1; j < clusters.length; j++) {
let distance: number;
switch (linkage) {
case 'single':
// Single linkage: minimum distance between any two points
distance = this.singleLinkageDistance(clusters[i], clusters[j], embeddings);
break;
case 'complete':
// Complete linkage: maximum distance between any two points
distance = this.completeLinkageDistance(clusters[i], clusters[j], embeddings);
break;
case 'average':
default:
// Average linkage: average distance between all pairs
distance = this.averageLinkageDistance(clusters[i], clusters[j], embeddings);
break;
}
if (distance < minDistance) {
minDistance = distance;
clusterI = i;
clusterJ = j;
}
}
}
// Merge clusters
const mergedCluster = {
members: [...clusters[clusterI].members, ...clusters[clusterJ].members],
centroid: this.calculateCentroid([
...clusters[clusterI].members.map(id => {
const idx = outputIds.indexOf(id);
return vectors[idx];
}),
...clusters[clusterJ].members.map(id => {
const idx = outputIds.indexOf(id);
return vectors[idx];
}),
]),
};
// Remove old clusters and add merged one
clusters.splice(clusterJ, 1); // Remove j first (higher index)
clusters.splice(clusterI, 1); // Then remove i
clusters.push(mergedCluster);
}
return clusters.map(c => ({ members: c.members }));
}
/**
* Single linkage distance (minimum distance between clusters)
*/
private singleLinkageDistance(
clusterA: { members: string[] },
clusterB: { members: string[] },
embeddings: Map<string, number[]>
): number {
let minDistance = Infinity;
for (const idA of clusterA.members) {
const vecA = embeddings.get(idA);
if (!vecA) continue;
for (const idB of clusterB.members) {
const vecB = embeddings.get(idB);
if (!vecB) continue;
const distance = this.euclideanDistance(vecA, vecB);
minDistance = Math.min(minDistance, distance);
}
}
return minDistance === Infinity ? 0 : minDistance;
}
/**
* Complete linkage distance (maximum distance between clusters)
*/
private completeLinkageDistance(
clusterA: { members: string[] },
clusterB: { members: string[] },