annonars 0.42.0

Genome annotation based on Rust and RocksDB
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
//! Code for `/genes/clinvar`.

use actix_web::{
    get,
    web::{self, Data, Json, Path},
};
use prost::Message;

use crate::pbs::clinvar::per_gene::ClinvarPerGeneRecord;

use super::error::CustomError;
use serde_with::{formats::CommaSeparator, StringWithSeparator};

/// Parameters for `handle`.
#[serde_with::skip_serializing_none]
#[serde_with::serde_as]
#[derive(
    Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema, utoipa::IntoParams,
)]
#[serde(rename_all = "snake_case")]
pub struct GenesClinvarQuery {
    /// The HGNC IDs to search for.
    #[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, String>>")]
    pub hgnc_id: Option<Vec<String>>,
}

/// Result for `handle`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde_with::skip_serializing_none]
struct Container {
    // TODO: add data version
    /// The resulting per-gene ClinVar information.
    pub genes: indexmap::IndexMap<String, ClinvarPerGeneRecord>,
}

/// Implementation of both endpoints.
async fn handle_impl(
    data: Data<crate::server::run::WebServerData>,
    _path: Path<()>,
    query: web::Query<GenesClinvarQuery>,
) -> actix_web::Result<Container, CustomError> {
    let genes_db = data.genes.as_ref().ok_or(CustomError::new(anyhow::anyhow!(
        "genes database not available"
    )))?;
    let db_clinvar = genes_db
        .data
        .db_clinvar
        .as_ref()
        .ok_or(CustomError::new(anyhow::anyhow!(
            "clinvar-genes database not available"
        )))?;
    let cf_genes = db_clinvar
        .cf_handle("clinvar-genes")
        .expect("no 'clinvar-genes' column family");
    let mut genes = indexmap::IndexMap::new();
    if let Some(hgnc_id) = query.hgnc_id.as_ref() {
        for hgnc_id in hgnc_id {
            if let Some(raw_buf) = db_clinvar.get_cf(&cf_genes, hgnc_id).map_err(|e| {
                CustomError::new(anyhow::anyhow!("problem querying database: {}", e))
            })? {
                let record = crate::pbs::clinvar::per_gene::ClinvarPerGeneRecord::decode(
                    std::io::Cursor::new(raw_buf),
                )
                .map_err(|e| CustomError::new(anyhow::anyhow!("problem decoding value: {}", e)))?;
                genes.insert(hgnc_id.to_string(), record);
            } else {
                tracing::debug!("no such gene: {}", hgnc_id);
            }
        }
    }

    let cf_meta = db_clinvar
        .cf_handle("meta")
        .expect("no 'meta' column family");
    let raw_builder_version = &db_clinvar
        .get_cf(&cf_meta, "annonars-version")
        .map_err(|e| CustomError::new(anyhow::anyhow!("problem querying database: {}", e)))?
        .expect("database missing 'annonars-version' key?");
    let _builder_version = std::str::from_utf8(raw_builder_version)
        .map_err(|e| CustomError::new(anyhow::anyhow!("problem decoding value: {}", e)))?
        .to_string();

    Ok(Container { genes })
}

/// Query for ClinVar information for one or more genes.
#[get("/genes/clinvar")]
async fn handle(
    data: Data<crate::server::run::WebServerData>,
    _path: Path<()>,
    query: web::Query<GenesClinvarQuery>,
) -> actix_web::Result<Json<Container>, CustomError> {
    Ok(Json(handle_impl(data, _path, query).await?))
}

/// Types used in the response.
pub(crate) mod response {
    use crate::pbs;
    use crate::server::run::clinvar_data::ClinvarExtractedVcvRecord;

    /// Extracted variants per release.
    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
    pub struct GenesExtractedVariantsPerRelease {
        /// Release version.
        pub release: Option<String>,
        /// Variants per gene.
        pub variants: Vec<ClinvarExtractedVcvRecord>,
    }

    impl TryFrom<pbs::clinvar::per_gene::ExtractedVariantsPerRelease>
        for GenesExtractedVariantsPerRelease
    {
        type Error = anyhow::Error;

        fn try_from(
            value: pbs::clinvar::per_gene::ExtractedVariantsPerRelease,
        ) -> Result<Self, Self::Error> {
            let variants = value
                .variants
                .into_iter()
                .map(ClinvarExtractedVcvRecord::try_from)
                .collect::<Result<Vec<_>, _>>()?;
            Ok(GenesExtractedVariantsPerRelease {
                release: value.release,
                variants,
            })
        }
    }

    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
    pub struct GenesCoarseClinsigFrequencyCounts {
        /// The gene HGNC ID.
        pub hgnc_id: String,
        /// The counts for (likely) pathogenic.
        pub pathogenic_counts: Vec<u32>,
        /// The counts for uncertain significance.
        pub uncertain_counts: Vec<u32>,
        /// The counts for (likely) benign.
        pub benign_counts: Vec<u32>,
    }

    impl From<pbs::clinvar_data::class_by_freq::GeneCoarseClinsigFrequencyCounts>
        for GenesCoarseClinsigFrequencyCounts
    {
        fn from(value: pbs::clinvar_data::class_by_freq::GeneCoarseClinsigFrequencyCounts) -> Self {
            Self {
                hgnc_id: value.hgnc_id,
                pathogenic_counts: value.pathogenic_counts,
                uncertain_counts: value.uncertain_counts,
                benign_counts: value.benign_counts,
            }
        }
    }

    /// Enumeration with the variant consequence.
    #[derive(
        Clone,
        Copy,
        Debug,
        PartialEq,
        Eq,
        Hash,
        PartialOrd,
        Ord,
        serde::Serialize,
        serde::Deserialize,
        utoipa::ToSchema,
    )]
    pub enum GenesGeneImpact {
        /// unspecified impact
        Unspecified,
        /// Corresponds to "3_prime_UTR_variant"
        ThreePrimeUtrVariant,
        /// Corresponds to "5_prime_UTR_variant"
        FivePrimeUtrVariant,
        /// Corresponds to "downstream_gene_variant"
        DownstreamTranscriptVariant,
        /// Corresponds to "frameshift_variant"
        FrameshiftVariant,
        /// Corresponds to "inframe_indel"
        InframeIndel,
        /// Corresponds to "start_lost"
        StartLost,
        /// Corresponds to "intron_variant"
        IntronVariant,
        /// Corresponds to "missense_variant"
        MissenseVariant,
        /// Corresponds to "non_codnig_transcript_variant"
        NonCodingTranscriptVariant,
        /// Corresponds to "stop_gained"
        StopGained,
        /// Corresponds to "no_sequence_alteration"
        NoSequenceAlteration,
        /// Corresponds to "splice_acceptor_variant"
        SpliceAcceptorVariant,
        /// Corresponds to "splice_donor_variant"
        SpliceDonorVariant,
        /// Corresponds to "stop_lost"
        StopLost,
        /// Corresponds to "synonymous_variant"
        SynonymousVariant,
        /// Corresponds to "upstream_gene_variant"
        UpstreamTranscriptVariant,
    }

    impl TryFrom<pbs::clinvar_data::gene_impact::GeneImpact> for GenesGeneImpact {
        type Error = anyhow::Error;

        fn try_from(
            value: pbs::clinvar_data::gene_impact::GeneImpact,
        ) -> Result<Self, Self::Error> {
            match value {
                pbs::clinvar_data::gene_impact::GeneImpact::Unspecified => {
                    Ok(GenesGeneImpact::Unspecified)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::ThreePrimeUtrVariant => {
                    Ok(GenesGeneImpact::ThreePrimeUtrVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::FivePrimeUtrVariant => {
                    Ok(GenesGeneImpact::FivePrimeUtrVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::DownstreamTranscriptVariant => {
                    Ok(GenesGeneImpact::DownstreamTranscriptVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::FrameshiftVariant => {
                    Ok(GenesGeneImpact::FrameshiftVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::InframeIndel => {
                    Ok(GenesGeneImpact::InframeIndel)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::StartLost => {
                    Ok(GenesGeneImpact::StartLost)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::IntronVariant => {
                    Ok(GenesGeneImpact::IntronVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::MissenseVariant => {
                    Ok(GenesGeneImpact::MissenseVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::NonCodingTranscriptVariant => {
                    Ok(GenesGeneImpact::NonCodingTranscriptVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::StopGained => {
                    Ok(GenesGeneImpact::StopGained)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::NoSequenceAlteration => {
                    Ok(GenesGeneImpact::NoSequenceAlteration)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::SpliceAcceptorVariant => {
                    Ok(GenesGeneImpact::SpliceAcceptorVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::SpliceDonorVariant => {
                    Ok(GenesGeneImpact::SpliceDonorVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::StopLost => {
                    Ok(GenesGeneImpact::StopLost)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::SynonymousVariant => {
                    Ok(GenesGeneImpact::SynonymousVariant)
                }
                pbs::clinvar_data::gene_impact::GeneImpact::UpstreamTranscriptVariant => {
                    Ok(GenesGeneImpact::UpstreamTranscriptVariant)
                }
            }
        }
    }

    /// Stores the counts for a gene impact.
    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
    pub struct GenesImpactCounts {
        /// The gene impact.
        pub gene_impact: GenesGeneImpact,
        /// The counts for the benign impact.
        pub count_benign: u32,
        /// The counts for the likely benign impact.
        pub count_likely_benign: u32,
        /// The counts for the uncertain significance impact.
        pub count_uncertain_significance: u32,
        /// The counts for the likely pathogenic impact.
        pub count_likely_pathogenic: u32,
        /// The counts for the pathogenic impact.
        pub count_pathogenic: u32,
    }

    impl TryFrom<pbs::clinvar_data::gene_impact::gene_impact_counts::ImpactCounts>
        for GenesImpactCounts
    {
        type Error = anyhow::Error;

        fn try_from(
            value: pbs::clinvar_data::gene_impact::gene_impact_counts::ImpactCounts,
        ) -> Result<Self, Self::Error> {
            Ok(GenesImpactCounts {
                gene_impact: GenesGeneImpact::try_from(
                    pbs::clinvar_data::gene_impact::GeneImpact::try_from(value.gene_impact)?,
                )?,
                count_benign: value.count_benign,
                count_likely_benign: value.count_likely_benign,
                count_uncertain_significance: value.count_uncertain_significance,
                count_likely_pathogenic: value.count_likely_pathogenic,
                count_pathogenic: value.count_pathogenic,
            })
        }
    }

    /// Entry for storing counts of `GeneImpact` and `ClinicalSignificance`.
    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
    pub struct GenesGeneImpactCounts {
        /// The gene HGNC ID.
        pub hgnc_id: String,
        /// The impact counts.
        pub impact_counts: Vec<GenesImpactCounts>,
    }

    impl TryFrom<pbs::clinvar_data::gene_impact::GeneImpactCounts> for GenesGeneImpactCounts {
        type Error = anyhow::Error;

        fn try_from(
            value: pbs::clinvar_data::gene_impact::GeneImpactCounts,
        ) -> Result<Self, Self::Error> {
            let impact_counts = value
                .impact_counts
                .into_iter()
                .map(GenesImpactCounts::try_from)
                .collect::<Result<Vec<_>, _>>()?;
            Ok(GenesGeneImpactCounts {
                hgnc_id: value.hgnc_id,
                impact_counts,
            })
        }
    }

    /// ClinVar detailed information per gene.
    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
    pub struct GenesClinvarPerGeneRecord {
        /// Counts of variants per impact
        pub per_impact_counts: Option<GenesGeneImpactCounts>,
        /// Counts of variants per impact / frequency
        pub per_freq_counts: Option<GenesCoarseClinsigFrequencyCounts>,
        /// Variants for the given gene.
        pub per_release_vars: Vec<GenesExtractedVariantsPerRelease>,
    }

    impl TryFrom<pbs::clinvar::per_gene::ClinvarPerGeneRecord> for GenesClinvarPerGeneRecord {
        type Error = anyhow::Error;

        fn try_from(
            value: pbs::clinvar::per_gene::ClinvarPerGeneRecord,
        ) -> Result<Self, Self::Error> {
            let per_impact_counts = value
                .per_impact_counts
                .map(GenesGeneImpactCounts::try_from)
                .transpose()?;
            let per_freq_counts = value
                .per_freq_counts
                .map(GenesCoarseClinsigFrequencyCounts::try_from)
                .transpose()?;
            let per_release_vars = value
                .per_release_vars
                .into_iter()
                .map(GenesExtractedVariantsPerRelease::try_from)
                .collect::<Result<Vec<_>, _>>()?;
            Ok(GenesClinvarPerGeneRecord {
                per_impact_counts,
                per_freq_counts,
                per_release_vars,
            })
        }
    }

    /// One entry in the result.
    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
    pub struct GenesClinvarResponseEntry {
        /// HGNC ID of the gene.
        pub hgnc_id: String,
        /// The resulting per-gene record.
        pub record: GenesClinvarPerGeneRecord,
    }

    impl TryFrom<(String, pbs::clinvar::per_gene::ClinvarPerGeneRecord)> for GenesClinvarResponseEntry {
        type Error = anyhow::Error;

        fn try_from(
            (hgnc_id, record): (String, pbs::clinvar::per_gene::ClinvarPerGeneRecord),
        ) -> Result<Self, Self::Error> {
            let record = GenesClinvarPerGeneRecord::try_from(record)?;
            Ok(GenesClinvarResponseEntry { hgnc_id, record })
        }
    }

    /// Result for `handle_with_openapi`.
    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
    #[serde_with::skip_serializing_none]
    pub struct GenesClinvarResponse {
        /// The resulting per-gene ClinVar information.
        pub genes: Vec<GenesClinvarResponseEntry>,
    }

    impl TryFrom<super::Container> for GenesClinvarResponse {
        type Error = anyhow::Error;

        fn try_from(container: super::Container) -> Result<Self, Self::Error> {
            let genes = container
                .genes
                .into_iter()
                .map(|(hgnc_id, record)| -> Result<_, anyhow::Error> {
                    Ok(GenesClinvarResponseEntry {
                        hgnc_id,
                        record: record.try_into()?,
                    })
                })
                .collect::<Result<Vec<_>, _>>()?;
            Ok(GenesClinvarResponse { genes })
        }
    }
}

use response::*;

/// Query for ClinVar information for one or more genes.
#[utoipa::path(
    get,
    operation_id = "genesClinvar",
    params(GenesClinvarQuery),
    responses(
        (status = 200, description = "Per-gene ClinVar information.", body = GenesClinvarResponse),
        (status = 500, description = "Internal server error.", body = CustomError)
    )
)]
#[get("/api/v1/genes/clinvar")]
async fn handle_with_openapi(
    data: Data<crate::server::run::WebServerData>,
    _path: Path<()>,
    query: web::Query<GenesClinvarQuery>,
) -> actix_web::Result<Json<GenesClinvarResponse>, CustomError> {
    let container = handle_impl(data, _path, query).await?;
    let response = container
        .try_into()
        .map_err(|e| CustomError::new(anyhow::anyhow!("Failed to convert response: {}", e)))?;
    Ok(Json(response))
}