libgrammstein 0.1.0

Hybrid language model (N-gram + Embeddings) for WFST text correction
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
# API Pattern Mining

libgrammstein includes an API pattern mining system that discovers common sequences of API calls using the PrefixSpan algorithm.

## What is API Pattern Mining?

API pattern mining identifies frequently occurring sequences of function or method calls in codebases. These patterns reveal:

- Common usage patterns for libraries and frameworks
- Idiomatic code sequences
- Potential API design issues
- Opportunities for abstraction

```
┌─────────────────────────────────────────────────────────────────────────┐
│                    API Pattern Mining Pipeline                           │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│   Source Code                                                            │
│       │                                                                  │
│       ▼                                                                  │
│   ┌─────────────────────────────────────────────────────────────────┐   │
│   │  1. Sequence Extraction                                          │   │
│   │     • Parse function bodies                                      │   │
│   │     • Extract API call sequences                                 │   │
│   │     • Build sequence database                                    │   │
│   └───────────────────────────────┬─────────────────────────────────┘   │
│                                   │                                      │
│                                   ▼                                      │
│   ┌─────────────────────────────────────────────────────────────────┐   │
│   │  Sequence Database                                               │   │
│   │  ["db.connect", "db.query", "db.close"]                         │   │
│   │  ["db.connect", "db.beginTransaction", "db.query", "db.commit"] │   │
│   │  ["fs.open", "fs.read", "fs.close"]                             │   │
│   │  ...                                                             │   │
│   └───────────────────────────────┬─────────────────────────────────┘   │
│                                   │                                      │
│                                   ▼                                      │
│   ┌─────────────────────────────────────────────────────────────────┐   │
│   │  2. PrefixSpan Mining                                            │   │
│   │     • Find frequent subsequences                                 │   │
│   │     • Apply minimum support threshold                            │   │
│   │     • Grow patterns prefix by prefix                             │   │
│   └───────────────────────────────┬─────────────────────────────────┘   │
│                                   │                                      │
│                                   ▼                                      │
│   ┌─────────────────────────────────────────────────────────────────┐   │
│   │  Frequent Patterns                                               │   │
│   │  ["db.connect", "db.query"] (support: 0.85)                     │   │
│   │  ["db.beginTransaction", "db.commit"] (support: 0.72)           │   │
│   │  ["db.connect", ..., "db.close"] (support: 0.68)                │   │
│   └─────────────────────────────────────────────────────────────────┘   │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘
```

## Core Types

### ApiPatternMiner

The main mining interface:

```rust
pub struct ApiPatternMiner {
    config: ApiPatternConfig,
}

impl ApiPatternMiner {
    /// Create a new miner with configuration
    pub fn new(config: ApiPatternConfig) -> Self;

    /// Mine patterns from a sequence database
    pub fn mine(&self, sequences: &[Vec<String>]) -> Vec<ApiPattern>;
}
```

### ApiPatternConfig

Configuration for the mining process:

```rust
pub struct ApiPatternConfig {
    /// Minimum support threshold (0.0 to 1.0)
    /// Patterns must appear in at least this fraction of sequences
    pub min_support: f64,

    /// Maximum pattern length
    pub max_length: usize,

    /// Minimum pattern length
    pub min_length: usize,

    /// Whether to allow gaps in patterns
    pub allow_gaps: bool,

    /// Maximum gap size (if gaps allowed)
    pub max_gap: usize,
}

impl Default for ApiPatternConfig {
    fn default() -> Self {
        Self {
            min_support: 0.1,    // 10% of sequences
            max_length: 10,
            min_length: 2,
            allow_gaps: true,
            max_gap: 3,
        }
    }
}
```

### ApiPattern

A discovered frequent pattern:

```rust
pub struct ApiPattern {
    /// The sequence of API calls
    pub sequence: Vec<String>,

    /// Support: fraction of sequences containing this pattern
    pub support: f64,

    /// Absolute count of occurrences
    pub count: usize,

    /// Positions where pattern occurs (sequence index, start position)
    pub occurrences: Vec<(usize, usize)>,
}
```

## Quick Start

### Basic Pattern Mining

```rust
use libgrammstein::topic::paradigm::{ApiPatternMiner, ApiPatternConfig};

// Create miner with default configuration
let miner = ApiPatternMiner::new(ApiPatternConfig::default());

// Build sequence database from code analysis
let sequences = vec![
    vec!["db.connect", "db.query", "db.close"].into_iter().map(String::from).collect(),
    vec!["db.connect", "db.beginTransaction", "db.query", "db.commit", "db.close"].into_iter().map(String::from).collect(),
    vec!["db.connect", "db.query", "db.query", "db.close"].into_iter().map(String::from).collect(),
    vec!["fs.open", "fs.read", "fs.close"].into_iter().map(String::from).collect(),
];

// Mine frequent patterns
let patterns = miner.mine(&sequences);

for pattern in patterns {
    println!("Pattern: {:?}", pattern.sequence);
    println!("  Support: {:.1}%", pattern.support * 100.0);
    println!("  Count: {}", pattern.count);
}
```

Output:
```
Pattern: ["db.connect", "db.close"]
  Support: 75.0%
  Count: 3

Pattern: ["db.connect", "db.query"]
  Support: 75.0%
  Count: 3

Pattern: ["db.connect", "db.query", "db.close"]
  Support: 75.0%
  Count: 3
```

### Extracting Sequences from Code

```rust
use libcpg::{CodePropertyGraph, TreeSitterCpgBuilder, Language};

fn extract_api_sequences(cpg: &CodePropertyGraph) -> Vec<Vec<String>> {
    let mut sequences = Vec::new();

    for func in cpg.functions() {
        let mut calls = Vec::new();

        // Get all call nodes in function
        for node_id in cpg.ast_descendants(func.id()) {
            if let Some(node) = cpg.node(node_id) {
                if matches!(node.kind(), CpgNodeKind::Call) {
                    if let Some(name) = node.name() {
                        calls.push(name.to_string());
                    }
                }
            }
        }

        if calls.len() >= 2 {
            sequences.push(calls);
        }
    }

    sequences
}

// Usage
let builder = TreeSitterCpgBuilder::new();
let cpg = builder.build(source_code, Language::Rust)?;
let sequences = extract_api_sequences(&cpg);
let patterns = miner.mine(&sequences);
```

## The PrefixSpan Algorithm

PrefixSpan (Prefix-projected Sequential pattern mining) efficiently finds frequent subsequences by:

1. **Finding frequent items**: Scan database for items meeting min_support
2. **Prefix projection**: For each frequent item, project the database
3. **Recursive mining**: Mine projected databases for extensions
4. **Pattern growth**: Grow patterns prefix by prefix

### Algorithm Walkthrough

```
Initial Database:
  S1: [a, b, c, d]
  S2: [a, c, d]
  S3: [a, b, d]
  S4: [b, c, d]

Step 1: Find frequent 1-sequences (min_support = 0.5)
  a: 3/4 = 0.75 ✓
  b: 3/4 = 0.75 ✓
  c: 3/4 = 0.75 ✓
  d: 4/4 = 1.00 ✓

Step 2: Project database by prefix 'a'
  S1|a: [b, c, d]  (suffix after first 'a')
  S2|a: [c, d]
  S3|a: [b, d]

Step 3: Mine projected database for prefix 'a'
  Find frequent items in S|a: b(2/3), c(2/3), d(3/3)
  Pattern [a, d] has support 3/4 = 0.75

Step 4: Continue recursively...
  [a, b, d]: support 2/4 = 0.50 ✓
  [a, c, d]: support 2/4 = 0.50 ✓
```

### Implementation Details

```rust
impl ApiPatternMiner {
    pub fn mine(&self, sequences: &[Vec<String>]) -> Vec<ApiPattern> {
        let n = sequences.len();
        if n == 0 {
            return Vec::new();
        }

        let min_count = (n as f64 * self.config.min_support).ceil() as usize;
        let mut patterns = Vec::new();

        // Find frequent 1-sequences
        let freq_items = self.find_frequent_items(sequences, min_count);

        // Mine patterns starting from each frequent item
        for item in freq_items {
            let prefix = vec![item.clone()];
            let projected = self.project_database(sequences, &prefix);

            if projected.len() >= min_count {
                patterns.push(ApiPattern {
                    sequence: prefix.clone(),
                    support: projected.len() as f64 / n as f64,
                    count: projected.len(),
                    occurrences: projected,
                });

                // Recursively extend prefix
                self.extend_pattern(
                    sequences,
                    &prefix,
                    &projected,
                    min_count,
                    &mut patterns,
                );
            }
        }

        patterns
    }

    fn extend_pattern(
        &self,
        sequences: &[Vec<String>],
        prefix: &[String],
        projected: &[(usize, usize)],
        min_count: usize,
        patterns: &mut Vec<ApiPattern>,
    ) {
        if prefix.len() >= self.config.max_length {
            return;
        }

        // Find frequent extensions
        let extensions = self.find_extensions(sequences, projected);

        for (item, new_projected) in extensions {
            if new_projected.len() >= min_count {
                let mut new_prefix = prefix.to_vec();
                new_prefix.push(item);

                patterns.push(ApiPattern {
                    sequence: new_prefix.clone(),
                    support: new_projected.len() as f64 / sequences.len() as f64,
                    count: new_projected.len(),
                    occurrences: new_projected.clone(),
                });

                // Continue extending
                self.extend_pattern(
                    sequences,
                    &new_prefix,
                    &new_projected,
                    min_count,
                    patterns,
                );
            }
        }
    }
}
```

## Configuration Options

### Support Threshold

The minimum fraction of sequences that must contain a pattern:

```rust
// High support: common patterns only
let config = ApiPatternConfig {
    min_support: 0.5,  // Pattern must appear in 50% of sequences
    ..Default::default()
};

// Low support: rare patterns too
let config = ApiPatternConfig {
    min_support: 0.05, // Pattern in 5% of sequences
    ..Default::default()
};
```

### Pattern Length

Control the size of discovered patterns:

```rust
let config = ApiPatternConfig {
    min_length: 3,  // At least 3 calls
    max_length: 8,  // At most 8 calls
    ..Default::default()
};
```

### Gap Handling

Allow non-contiguous patterns:

```rust
// Contiguous only: [a, b, c] matches "a, b, c" but not "a, x, b, c"
let config = ApiPatternConfig {
    allow_gaps: false,
    ..Default::default()
};

// Allow gaps: [a, b, c] matches "a, x, b, y, z, c"
let config = ApiPatternConfig {
    allow_gaps: true,
    max_gap: 2,  // At most 2 items between pattern elements
    ..Default::default()
};
```

## Use Cases

### Library Usage Analysis

Discover how developers use a library:

```rust
fn analyze_library_usage(codebase: &[SourceFile], library: &str) -> Vec<ApiPattern> {
    let miner = ApiPatternMiner::new(ApiPatternConfig {
        min_support: 0.1,
        min_length: 2,
        max_length: 6,
        ..Default::default()
    });

    let sequences: Vec<Vec<String>> = codebase.iter()
        .flat_map(|file| extract_api_sequences(&file.cpg))
        .filter(|seq| seq.iter().any(|call| call.starts_with(library)))
        .collect();

    miner.mine(&sequences)
}

// Usage
let patterns = analyze_library_usage(&codebase, "React.");
for pattern in patterns {
    println!("{:?} (used in {:.0}% of components)",
             pattern.sequence, pattern.support * 100.0);
}
```

### Anti-Pattern Detection

Find common but problematic patterns:

```rust
// Known anti-patterns
let anti_patterns = vec![
    vec!["db.query", "db.query"],  // Multiple queries without transaction
    vec!["file.open", "file.read"],  // No close after open
];

fn detect_anti_patterns(
    mined: &[ApiPattern],
    anti_patterns: &[Vec<&str>],
) -> Vec<(&ApiPattern, &[&str])> {
    mined.iter()
        .filter_map(|pattern| {
            for anti in anti_patterns {
                if is_subsequence(anti, &pattern.sequence) {
                    return Some((pattern, anti.as_slice()));
                }
            }
            None
        })
        .collect()
}
```

### Framework Idiom Discovery

Learn idiomatic patterns from well-written code:

```rust
fn discover_idioms(exemplar_code: &[SourceFile]) -> Vec<ApiPattern> {
    let miner = ApiPatternMiner::new(ApiPatternConfig {
        min_support: 0.3,  // Common in exemplar code
        min_length: 3,
        ..Default::default()
    });

    let sequences = exemplar_code.iter()
        .flat_map(|f| extract_api_sequences(&f.cpg))
        .collect::<Vec<_>>();

    miner.mine(&sequences)
}

// Document discovered idioms
for pattern in discover_idioms(&exemplar_code) {
    println!("Idiom: {}", pattern.sequence.join(" -> "));
    println!("Usage: {:.0}% of exemplar code", pattern.support * 100.0);
}
```

### API Evolution Tracking

Track how API usage changes across versions:

```rust
fn compare_api_usage(
    old_code: &[SourceFile],
    new_code: &[SourceFile],
) -> ApiEvolution {
    let miner = ApiPatternMiner::new(ApiPatternConfig::default());

    let old_patterns = miner.mine(&extract_all_sequences(old_code));
    let new_patterns = miner.mine(&extract_all_sequences(new_code));

    let old_set: HashSet<_> = old_patterns.iter()
        .map(|p| &p.sequence)
        .collect();
    let new_set: HashSet<_> = new_patterns.iter()
        .map(|p| &p.sequence)
        .collect();

    ApiEvolution {
        deprecated: old_set.difference(&new_set).cloned().collect(),
        new_patterns: new_set.difference(&old_set).cloned().collect(),
        stable: old_set.intersection(&new_set).cloned().collect(),
    }
}
```

## Performance Considerations

### Sequence Database Size

Mining time increases with database size:

```rust
// For large codebases, sample or partition
fn sample_sequences(sequences: &[Vec<String>], sample_rate: f64) -> Vec<Vec<String>> {
    use rand::Rng;
    let mut rng = rand::thread_rng();

    sequences.iter()
        .filter(|_| rng.gen::<f64>() < sample_rate)
        .cloned()
        .collect()
}
```

### Pattern Explosion

Low support thresholds can produce many patterns:

```rust
// Start with high support, lower if needed
let mut config = ApiPatternConfig {
    min_support: 0.5,
    ..Default::default()
};

let patterns = miner.mine(&sequences);

if patterns.len() < 10 {
    config.min_support = 0.2;
    let patterns = miner.mine(&sequences);
}
```

### Memory Usage

Projected databases can be large:

```rust
// Use indices instead of copying sequences
struct ProjectedDb {
    original: Arc<Vec<Vec<String>>>,
    indices: Vec<(usize, usize)>,  // (sequence_idx, position)
}
```

## See Also

- [Overview]overview.md - Paradigm detection introduction
- [Detection]detection.md - Paradigm detector usage
- [Indicators]indicators.md - Indicator types and categories
- [Domain Patterns]domain-patterns.md - Rholang and MeTTa patterns