rustkmer 0.5.2

High-performance k-mer counting tool in Rust
Documentation
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
# Basic Usage

This guide provides basic usage examples for both the Rust CLI and Python API. Learn the fundamental operations of RustKmer through practical examples.

## Prerequisites

### For Rust CLI
- Rust 1.80+ installed
- Cargo package manager

### For Python API
- Python 3.8+ installed
- RustKmer Python package: `pip install rustkmer`

## Quick Start

### Option 1: Using the Python API (Recommended for beginners)

```python
from pyrustkmer import PyCounter, LoadMode, PyDatabase, PyFuzzyQuery

# Create k-mer database from FASTA file
counter = PyCounter(31, canonical=True)
counter.add_from_fasta("sequences.fasta")
counter.save_database("output.rkdb")

# Query database
db = PyDatabase("output.rkdb", LoadMode.Preload)
result = db.query_exact("ATCGATCGATCGATCGATCGATCGATCGATCGATCG")
print(f"Count: {result.count}")
```

### Option 2: Using the Rust CLI

```bash
# Count k-mers from FASTA file
rustkmer count -k 31 -o output.rkdb sequences.fasta

# Query k-mers
rustkmer query output.rkdb ATCGATCGATCGATCGATCGATCGATCGATCGATCG

# Get database statistics
rustkmer stats output.rkdb
```

## 1. Creating a K-mer Database

### Python API

```python
from pyrustkmer import PyCounter, LoadMode, PyFuzzyQuery

# Method 1: From single file
counter = PyCounter(31, canonical=True)
counter.add_from_fasta("input.fasta")
counter.save_database("database.rkdb")

# Method 2: From multiple files
file_list = ["file1.fasta", "file2.fasta", "file3.fasta"]
counter = PyCounter(25)
counter.count_file_list(file_list)
counter.save_database("combined.rkdb")

# Method 3: From sequence strings
sequences = [
    "ATCGATCGATCGATCGATCGATCGATCGATCGATCGATCG",
    "GCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAG"
]
counter = PyCounter(21)
for seq in sequences:
    counter.add_sequence(seq)
counter.save_database("from_strings.rkdb")
```

### Rust CLI

```bash
# Basic counting
rustkmer count -k 31 input.fasta -o database.rkdb

# Multiple files
rustkmer count -k 25 file1.fasta file2.fasta file3.fasta -o combined.rkdb

# With progress reporting
rustkmer count -k 31 input.fasta -o database.rkdb --progress

# Non-canonical (store both strands)
rustkmer count -k 31 input.fasta -o database_stranded.rkdb --no-canonical
```

## 2. Querying K-mers

### Python API

```python
from pyrustkmer import PyDatabase, LoadMode, PyFuzzyQuery

# Single query
db = PyDatabase("database.rkdb", LoadMode.Preload)
result = db.query_exact("ATCGATCGATCGATCGATCGATCGATCGATCGATCG")
print(f"Found: {result.found}")
print(f"Count: {result.count}")
print(f"Canonical: {result.canonical}")

# Multiple queries
kmer_list = ["ATCGATCG...", "GCTAGCTA...", "TTTTTTTT..."]
db = PyDatabase("database.rkdb", LoadMode.Preload)
    for kmer in kmer_list:
        result = db.query_exact(kmer)
        status = "✓" if result.found else "✗"
        print(f"{kmer[:10]}... {status} {result.count}")
```

### Rust CLI

```bash
# Single query
rustkmer query database.rkdb ATCGATCGATCGATCGATCGATCGATCGATCGATCG

# Multiple queries from file
echo -e "ATCGATCGATCGATCGATCGATCGATCGATCGATCG\nGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAG" > queries.txt
rustkmer query database.rkdb --file queries.txt

# Query with specific k-mer size
rustkmer query database.rkdb ATCGATCGATCGATCGATCGATCGATCGATCGATCG -k 31
```

## 3. Fuzzy Searching

### Python API

```python
from pyrustkmer import Database, PyFuzzyQuery

db = PyDatabase("database.rkdb", LoadMode.Preload)
    # Basic fuzzy query
    reference_kmer = "ATCGATCGATCGATCGATCGATCGATCGATCGATCG"
    result = fuzzy.query_fuzzy(reference_kmer, mutations=2)

    print(f"Total matches: {result.total_matches}")
    print(f"Exact matches: {result.exact_matches}")
    print(f"Fuzzy matches: {result.fuzzy_matches}")

    # Show fuzzy matches
    for match in result.get_fuzzy_matches():
        print(f"  {match.kmer}: {match.count} (distance={match.distance})")

    # Position-specific mutations
    result = fuzzy.query_fuzzy(
        reference_kmer,
        mutations=2,
        position_mutations="10,15:1;20,25:2"
    )
```

### Rust CLI

```bash
# Basic fuzzy query
rustkmer fuzzy-query database.rkdb ATCGATCGATCGATCGATCGATCGATCGATCGATCG -m 2

# Position mutations
rustkmer fuzzy-query database.rkdb ATCGATCGATCGATCGATCGATCGATCGATCGATCG \
    -m 3 \
    --position-mutations "10,15:1;20,25:2"

# Multiple fuzzy queries
echo -e "ATCGATCGATCGATCGATCGATCGATCGATCGATCG\nGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAG" > fuzzy_queries.txt
rustkmer fuzzy-query database.rkdb --file fuzzy_queries.txt -m 2
```

## 4. Database Statistics

### Python API

```python
from pyrustkmer import Database, PyFuzzyQuery

db = PyDatabase("database.rkdb", LoadMode.Preload)
    stats = db.get_stats()

    print("Database Statistics:")
    print(f"  K-mer size: {stats.kmer_size}")
    print(f"  Unique k-mers: {stats.unique_kmers:,}")
    print(f"  Total counts: {stats.total_counts:,}")
    print(f"  File size: {stats.file_size:,} bytes")
    print(f"  Format version: {stats.format_version}")

    # Calculate derived statistics
    if stats.unique_kmers > 0:
        avg_count = stats.total_counts / stats.unique_kmers
        compression_ratio = stats.file_size / (stats.unique_kmers * 8)
        print(f"  Average count: {avg_count:.2f}")
        print(f"  Compression ratio: {compression_ratio:.3f}")
```

### Rust CLI

```bash
# Basic statistics
rustkmer stats database.rkdb

# Detailed statistics
rustkmer stats database.rkdb --verbose

# CSV format output
rustkmer stats database.rkdb --format csv > stats.csv

# JSON format output
rustkmer stats database.rkdb --format json > stats.json
```

## 5. Exporting Database Content

### Python API

```python
import csv
from pyrustkmer import Database, PyFuzzyQuery

# Export to CSV
db = PyDatabase("database.rkdb", LoadMode.Preload)
    with open("kmer_export.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["kmer", "count", "canonical"])

        for result in db.dump(limit=10000):
            writer.writerow([result.kmer, result.count, result.canonical])

# Export canonical k-mers only
db = PyDatabase("database.rkdb", LoadMode.Preload)
    canonical_kmers = []
    for result in db.dump(limit=5000, canonical_only=True):
        canonical_kmers.append((result.kmer, result.count))

print(f"Exported {len(canonical_kmers)} canonical k-mers")
```

### Rust CLI

```bash
# Export to stdout
rustkmer dump database.rkdb

# Export with limit
rustkmer dump database.rkdb --limit 10000

# Export canonical only
rustkmer dump database.rkdb --canonical-only

# Export to file
rustkmer dump database.rkdb > kmer_export.txt

# TSV format
rustkmer dump database.rkdb --format tsv > kmer_export.tsv
```

## 6. Batch Operations

### Python API

```python
from pyrustkmer import Database, PyFuzzyQuery

# Batch exact queries
kmer_list = ["ATCGATCG...", "GCTAGCTA...", "TTTTTTTT..."]

db = PyDatabase("database.rkdb", LoadMode.Preload)
    results = {}
    for kmer in kmer_list:
        result = db.query_exact(kmer)
        results[kmer] = result.count

# Batch fuzzy queries
db = PyDatabase("database.rkdb", LoadMode.Preload)
    batch_result = db.fuzzy_query_batch(
        kmer_list,
        mutations=2,
        max_workers=4
    )

    for kmer, result in batch_result.successes.items():
        print(f"{kmer}: {result.total_matches} matches")
```

### Rust CLI

```bash
# Create query file
cat > queries.txt << EOF
ATCGATCGATCGATCGATCGATCGATCGATCGATCG
GCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAG
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
EOF

# Batch query
rustkmer query database.rkdb --file queries.txt

# Batch fuzzy query
rustkmer fuzzy-query database.rkdb --file queries.txt -m 2
```

## 7. Error Handling

### Python API

```python
from pyrustkmer import Database, DatabaseNotFoundError, InvalidKmerError, QueryError, PyFuzzyQuery

# Proper error handling
try:
    db = PyDatabase("nonexistent.rkdb", LoadMode.Preload)
        result = db.query_exact("ATCGATCGATCGATCGATCGATCGATCGATCGATCG")
except DatabaseNotFoundError:
    print("Database file not found!")
except InvalidKmerError as e:
    print(f"Invalid k-mer: {e.kmer} - {e.reason}")
except QueryError as e:
    print(f"Query error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

# Validate k-mers before querying
def validate_kmer(kmer):
    """Validate k-mer format."""
    if not kmer:
        raise InvalidKmerError(kmer, "Empty k-mer")
    if not all(base in 'ATCG' for base in kmer.upper()):
        raise InvalidKmerError(kmer, "Invalid nucleotides")
    if len(kmer) < 10:
        raise InvalidKmerError(kmer, "K-mer too short")
    return kmer.upper()

try:
    kmer = validate_kmer("ATCGATCGATCGATCGATCGATCGATCGATCGATCG")
    db = PyDatabase("database.rkdb", LoadMode.Preload)
        result = db.query_exact(kmer)
except InvalidKmerError as e:
    print(f"Validation failed: {e}")
```

### Rust CLI

```bash
# Check if file exists before querying
if [ -f "database.rkdb" ]; then
    rustkmer query database.rkdb ATCGATCGATCGATCGATCGATCGATCGATCGATCG
else
    echo "Database file not found!"
fi

# Validate k-mer format
kmer="ATCGATCGATCGATCGATCGATCGATCGATCGATCG"
if [[ $kmer =~ ^[ATCGatcg]+$ ]]; then
    rustkmer query database.rkdb "$kmer"
else
    echo "Invalid k-mer format!"
fi
```

## 8. Performance Tips

### Python API

```python
from pyrustkmer import KmerCounter, Database, PyFuzzyQuery
import time

# Use appropriate k-mer size
def choose_kmer_size(read_length):
    """Choose optimal k-mer size based on read length."""
    if read_length < 100:
        return 21
    elif read_length < 500:
        return 31
    else:
        return 51

# Use batch operations for better performance
def batch_query(database_path, kmer_list, mutations=2):
    """Perform batch queries for better performance."""
    db = PyDatabase(database_path, LoadMode.Preload)
        return db.fuzzy_query_batch(kmer_list, mutations=mutations, max_workers=4)

# Memory-efficient processing of large databases
def process_large_database(database_path, output_file):
    """Process large database without loading everything into memory."""
    db = PyDatabase(database_path, LoadMode.Preload)
        with open(output_file, 'w') as f:
            for result in db.dump():
                if result.count > 10:  # Filter high-count k-mers
                    f.write(f"{result.kmer}\t{result.count}\n")
```

### Rust CLI

```bash
# Use progress reporting for long operations
rustkmer count -k 31 large_file.fasta -o database.rkdb --progress

# Use compression for large outputs
rustkmer dump database.rkdb | gzip > kmer_export.txt.gz

# Process in parallel (when available)
rustkmer count -k 31 *.fasta -o combined.rkdb --threads 8

# Use streaming mode for very large files
rustkmer query database.rkdb --file huge_query_list.txt --streaming
```

## 9. Real-world Example: K-mer Analysis Pipeline

### Python API

```python
#!/usr/bin/env python3
"""
Complete k-mer analysis pipeline.
"""

from pyrustkmer import KmerCounter, Database, PyFuzzyQuery
import pandas as pd
import matplotlib.pyplot as plt
import argparse
import os

def analyze_fasta(input_fasta, k=31, output_prefix="analysis"):
    """Complete k-mer analysis pipeline."""

    print(f"Analyzing {input_fasta} with k={k}")

    # 1. Count k-mers
    print("1. Counting k-mers...")
    counter = PyCounter(k, canonical=True)
    counter.add_from_fasta(input_fasta)

    # 2. Save database
    db_path = f"{output_prefix}.rkdb"
    counter.save_database(db_path)

    # 3. Get statistics
    print("2. Getting statistics...")
    db = PyDatabase(db_path, LoadMode.Preload)
        stats = db.get_stats()
        print(f"   Unique k-mers: {stats.unique_kmers:,}")
        print(f"   Total counts: {stats.total_counts:,}")

    # 4. Extract top k-mers
    print("3. Extracting top k-mers...")
    db = PyDatabase(db_path, LoadMode.Preload)
        data = []
        for result in db.dump(limit=10000, canonical_only=True):
            data.append({
                'kmer': result.kmer,
                'count': result.count
            })

    df = pd.DataFrame(data)

    # 5. Save results
    print("4. Saving results...")
    df.to_csv(f"{output_prefix}_kmer_counts.csv", index=False)

    # 6. Create visualization
    plt.figure(figsize=(10, 6))
    plt.hist(df['count'], bins=50, alpha=0.7)
    plt.xlabel('K-mer Count')
    plt.ylabel('Frequency')
    plt.title('K-mer Count Distribution')
    plt.savefig(f"{output_prefix}_distribution.png", dpi=150, bbox_inches='tight')

    print(f"Analysis complete! Results saved to {output_prefix}_*")

    # 7. Summary statistics
    print("\nSummary Statistics:")
    print(f"   Mean count: {df['count'].mean():.1f}")
    print(f"   Median count: {df['count'].median():.1f}")
    print(f"   Max count: {df['count'].max()}")
    print(f"   Top 1% threshold: {df['count'].quantile(0.99):.1f}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="K-mer analysis pipeline")
    parser.add_argument("input", help="Input FASTA file")
    parser.add_argument("-k", type=int, default=31, help="K-mer size")
    parser.add_argument("-o", "--output", default="analysis", help="Output prefix")

    args = parser.parse_args()
    analyze_fasta(args.input, args.k, args.output)
```

### Rust CLI Equivalent

```bash
#!/bin/bash
# kmer_analysis.sh - K-mer analysis pipeline

set -euo pipefail

input_file=$1
k=${2:-31}
output_prefix=${3:-analysis}

echo "Analyzing $input_file with k=$k"

# 1. Count k-mers
echo "1. Counting k-mers..."
rustkmer count -k $k "$input_file" -o "${output_prefix}.rkdb" --progress

# 2. Get statistics
echo "2. Getting statistics..."
stats=$(rustkmer stats "${output_prefix}.rkdb" --format json)
echo "   Statistics: $stats"

# 3. Extract top k-mers
echo "3. Extracting top k-mers..."
rustkmer dump "${output_prefix}.rkdb" --limit 10000 --canonical-only > "${output_prefix}_kmer_counts.txt"

# 4. Convert to CSV format
echo "4. Converting to CSV..."
awk 'NR>1 {print $1","$2}' "${output_prefix}_kmer_counts.txt" > "${output_prefix}_kmer_counts.csv"

echo "Analysis complete! Results saved to ${output_prefix}_*"
```

## 10. Choosing Between Python API and CLI

### Use Python API when:
- You need programmatic control
- Integration with other Python libraries (pandas, matplotlib, etc.)
- Complex data processing pipelines
- Custom error handling
- Interactive analysis (Jupyter notebooks)

### Use CLI when:
- Simple, one-off operations
- Shell scripting workflows
- High-performance batch processing
- Integration with other command-line tools
- Minimal setup required

### Example Decision Flow:

```python
# Use Python API for analysis
if need_custom_processing or integrate_with_python_libs:
    use_python_api()

# Use CLI for simple operations
elif simple_oneoff_task or shell_scripting:
    use_cli()

# Use both for complex pipelines
else:
    use_cli_for_heavy_lifting()
    use_python_api_for_analysis()
```

## Next Steps

- Explore [advanced examples]../python/ for specific use cases
- Read the [Python API documentation]../../api-reference/python/
- Check the [tutorials]../../tutorials/ for detailed workflows
- Review the [full API reference]../../api-reference/ for all available features