ruvector-data-framework 0.3.0

Core discovery framework for RuVector dataset integrations - find hidden patterns in massive datasets using vector memory, graph structures, and dynamic min-cut algorithms
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
# Genomics and DNA Data API Clients

Comprehensive genomics data integration for RuVector's discovery framework, enabling cross-domain pattern detection between genomics, climate, medical, and economic data.

## Overview

The genomics clients module (`genomics_clients.rs`) provides four specialized API clients for accessing the world's largest genomics databases:

1. **NcbiClient** - NCBI Entrez APIs (genes, proteins, nucleotides, SNPs)
2. **UniProtClient** - UniProt protein knowledge base
3. **EnsemblClient** - Ensembl genomic annotations
4. **GwasClient** - GWAS Catalog (genome-wide association studies)

All data is automatically converted to `SemanticVector` format with `Domain::Genomics` for seamless integration with RuVector's vector database and coherence analysis.

## Features

- **Rate limiting** with exponential backoff (NCBI: 3 req/s without key, 10 req/s with key)
-**Retry logic** with configurable attempts
-**NCBI API key support** for higher rate limits
-**Automatic embedding generation** using SimpleEmbedder (384 dimensions)
-**Semantic vector conversion** with rich metadata
-**Cross-domain discovery** enabled (Genomics ↔ Climate, Medical, Economic)
-**Unit tests** for all clients

## Installation

The genomics clients are included in the `ruvector-data-framework` crate:

```toml
[dependencies]
ruvector-data-framework = "0.1.0"
```

## Quick Start

```rust
use ruvector_data_framework::{
    NcbiClient, UniProtClient, EnsemblClient, GwasClient,
    NativeDiscoveryEngine, NativeEngineConfig,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize discovery engine
    let mut engine = NativeDiscoveryEngine::new(NativeEngineConfig::default());

    // 1. Search for genes related to climate adaptation
    let ncbi = NcbiClient::new(None)?;
    let heat_shock_genes = ncbi.search_genes("heat shock protein", Some("human")).await?;

    for gene in heat_shock_genes {
        engine.add_vector(gene);
    }

    // 2. Search for disease-associated proteins
    let uniprot = UniProtClient::new()?;
    let apoe_proteins = uniprot.search_proteins("APOE", 10).await?;

    for protein in apoe_proteins {
        engine.add_vector(protein);
    }

    // 3. Get genetic variants
    let ensembl = EnsemblClient::new()?;
    if let Some(gene) = ensembl.get_gene_info("ENSG00000157764").await? {
        engine.add_vector(gene);
        let variants = ensembl.get_variants("ENSG00000157764").await?;
        for variant in variants {
            engine.add_vector(variant);
        }
    }

    // 4. Search GWAS for disease associations
    let gwas = GwasClient::new()?;
    let diabetes_assocs = gwas.search_associations("diabetes").await?;

    for assoc in diabetes_assocs {
        engine.add_vector(assoc);
    }

    // Detect cross-domain patterns
    let patterns = engine.detect_patterns();
    println!("Discovered {} patterns", patterns.len());

    Ok(())
}
```

## API Clients

### 1. NcbiClient - NCBI Entrez APIs

Access genes, proteins, nucleotides, and SNPs from NCBI databases.

#### Initialization

```rust
// Without API key (3 requests/second)
let client = NcbiClient::new(None)?;

// With API key (10 requests/second) - recommended
let client = NcbiClient::new(Some("YOUR_API_KEY".to_string()))?;
```

Get your API key at: https://www.ncbi.nlm.nih.gov/account/

#### Methods

```rust
// Search gene database
let genes = client.search_genes("BRCA1", Some("human")).await?;

// Get specific gene by ID
let gene = client.get_gene("672").await?;

// Search proteins
let proteins = client.search_proteins("kinase").await?;

// Search nucleotide sequences
let sequences = client.search_nucleotide("mitochondrial genome").await?;

// Get SNP information by rsID
let snp = client.get_snp("rs429358").await?; // APOE4 variant
```

#### Vector Format

```rust
SemanticVector {
    id: "GENE:672",
    domain: Domain::Genomics,
    embedding: [384-dimensional vector],
    metadata: {
        "gene_id": "672",
        "symbol": "BRCA1",
        "description": "BRCA1 DNA repair associated",
        "organism": "Homo sapiens",
        "common_name": "human",
        "chromosome": "17",
        "location": "17q21.31",
        "source": "ncbi_gene"
    }
}
```

### 2. UniProtClient - Protein Database

Access comprehensive protein information including function, structure, and pathways.

#### Initialization

```rust
let client = UniProtClient::new()?;
```

#### Methods

```rust
// Search proteins
let proteins = client.search_proteins("p53", 100).await?;

// Get protein by accession
let protein = client.get_protein("P04637").await?; // TP53

// Search by organism
let human_proteins = client.search_by_organism("human").await?;

// Search by function (GO term)
let kinases = client.search_by_function("kinase").await?;
```

#### Vector Format

```rust
SemanticVector {
    id: "UNIPROT:P04637",
    domain: Domain::Genomics,
    embedding: [384-dimensional vector],
    metadata: {
        "accession": "P04637",
        "protein_name": "Cellular tumor antigen p53",
        "organism": "Homo sapiens",
        "genes": "TP53",
        "function": "Acts as a tumor suppressor...",
        "source": "uniprot"
    }
}
```

### 3. EnsemblClient - Genomic Annotations

Access gene information, variants, and homology across species.

#### Initialization

```rust
let client = EnsemblClient::new()?;
```

#### Methods

```rust
// Get gene information
let gene = client.get_gene_info("ENSG00000157764").await?; // BRAF

// Get genetic variants for a gene
let variants = client.get_variants("ENSG00000157764").await?;

// Get homologous genes across species
let homologs = client.get_homologs("ENSG00000157764").await?;
```

#### Vector Format

```rust
SemanticVector {
    id: "ENSEMBL:ENSG00000157764",
    domain: Domain::Genomics,
    embedding: [384-dimensional vector],
    metadata: {
        "ensembl_id": "ENSG00000157764",
        "symbol": "BRAF",
        "description": "B-Raf proto-oncogene, serine/threonine kinase",
        "species": "homo_sapiens",
        "biotype": "protein_coding",
        "chromosome": "7",
        "start": "140719327",
        "end": "140924929",
        "source": "ensembl"
    }
}
```

### 4. GwasClient - GWAS Catalog

Access genome-wide association studies linking genes to diseases and traits.

#### Initialization

```rust
let client = GwasClient::new()?;
```

#### Methods

```rust
// Search trait-gene associations
let associations = client.search_associations("diabetes").await?;

// Get study details
let study = client.get_study("GCST001937").await?;

// Search associations by gene
let gene_assocs = client.search_by_gene("APOE").await?;
```

#### Vector Format

```rust
SemanticVector {
    id: "GWAS:7_140753336_5.0e-8",
    domain: Domain::Genomics,
    embedding: [384-dimensional vector],
    metadata: {
        "trait": "Type 2 diabetes",
        "genes": "BRAF, KIAA1549",
        "risk_allele": "rs7578597-T",
        "pvalue": "5.0e-8",
        "chromosome": "7",
        "position": "140753336",
        "source": "gwas_catalog"
    }
}
```

## Rate Limits

| API | Default Rate | With API Key | Notes |
|-----|-------------|--------------|-------|
| NCBI | 3 req/sec | 10 req/sec | API key recommended for production |
| UniProt | 10 req/sec | - | Conservative limit |
| Ensembl | 15 req/sec | - | Per their guidelines |
| GWAS | 10 req/sec | - | Conservative limit |

All clients implement:
- Automatic rate limiting with delays
- Exponential backoff on 429 errors
- Configurable retry attempts (default: 3)

## Cross-Domain Discovery Examples

### 1. Climate ↔ Genomics

Discover how environmental factors correlate with gene expression:

```rust
// Fetch heat shock proteins (climate stress response)
let hsp_genes = ncbi.search_genes("heat shock protein", Some("human")).await?;

// Fetch temperature data from NOAA
let climate_data = noaa_client.fetch_temperature_data("2020-01-01", "2024-01-01").await?;

// Add to discovery engine
for gene in hsp_genes {
    engine.add_vector(gene);
}
for record in climate_data {
    engine.add_vector(record);
}

// Detect cross-domain patterns
let patterns = engine.detect_patterns();
// May discover: "Heat shock protein expression correlates with extreme temperature events"
```

### 2. Medical ↔ Genomics

Link genetic variants to disease outcomes:

```rust
// Get APOE4 variant (Alzheimer's risk)
let apoe4 = ncbi.get_snp("rs429358").await?;

// Search PubMed for Alzheimer's research
let papers = pubmed.search_articles("Alzheimer's disease APOE", 100).await?;

// Detect gene-disease associations
let patterns = engine.detect_patterns();
```

### 3. Economic ↔ Genomics

Correlate biotech market trends with genomic research:

```rust
// Fetch CRISPR-related genes
let crispr_genes = ncbi.search_genes("CRISPR", None).await?;

// Fetch biotech stock data
let biotech_stocks = alpha_vantage.fetch_stock("CRSP", "monthly").await?;

// Discover market-science correlations
let patterns = engine.detect_patterns();
```

## Error Handling

All clients return `Result<T, FrameworkError>`:

```rust
match ncbi.search_genes("BRCA1", Some("human")).await {
    Ok(genes) => {
        println!("Found {} genes", genes.len());
        for gene in genes {
            engine.add_vector(gene);
        }
    }
    Err(FrameworkError::Network(e)) => {
        eprintln!("Network error: {}", e);
    }
    Err(FrameworkError::Serialization(e)) => {
        eprintln!("JSON parsing error: {}", e);
    }
    Err(e) => {
        eprintln!("Other error: {}", e);
    }
}
```

## Testing

Run the unit tests:

```bash
cargo test --lib genomics
```

Run the example:

```bash
cargo run --example genomics_discovery
```

## Performance Tips

1. **Use NCBI API key** for production workloads (10x rate limit)
2. **Batch operations** when possible (e.g., fetch 200 genes at once)
3. **Cache results** to avoid redundant API calls
4. **Use async/await** for concurrent requests across different APIs

```rust
// Concurrent fetching
let (genes, proteins, variants) = tokio::join!(
    ncbi.search_genes("BRCA1", Some("human")),
    uniprot.search_proteins("BRCA1", 10),
    ensembl.get_variants("ENSG00000012048")
);
```

## Real-World Use Cases

### 1. Pharmacogenomics

Discover drug-gene interactions:
- Fetch CYP450 genes from NCBI
- Get protein structures from UniProt
- Find drug adverse events from FDA
- Detect patterns linking gene variants to drug response

### 2. Climate Adaptation Research

Study genetic adaptation to climate change:
- Fetch stress response genes (heat shock, cold tolerance)
- Get climate data (temperature, precipitation)
- Find GWAS associations for environmental traits
- Discover gene-environment correlations

### 3. Disease Risk Assessment

Build genetic risk profiles:
- Get disease-associated SNPs from GWAS
- Fetch gene function from UniProt
- Find variants from Ensembl
- Compute polygenic risk scores

## Contributing

When adding new genomics data sources:

1. Follow the existing client pattern (rate limiting, retry logic)
2. Convert to `SemanticVector` with `Domain::Genomics`
3. Include rich metadata for discovery
4. Add unit tests
5. Update this documentation

## References

- [NCBI Entrez API]https://www.ncbi.nlm.nih.gov/books/NBK25501/
- [UniProt REST API]https://www.uniprot.org/help/api
- [Ensembl REST API]https://rest.ensembl.org/
- [GWAS Catalog API]https://www.ebi.ac.uk/gwas/rest/docs/api

## License

Part of the RuVector project. See root LICENSE file.