mehari 0.47.0

Variant effect prediction all in Rust
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
//! Implementation of endpoint `/api/v1/genes/transcripts`.
//!
//! Also includes the implementation of the `/genes/txs` endpoint (deprecated).

use crate::pbs;
use crate::pbs::server::{GeneTranscriptsQuery, GeneTranscriptsResponse};

use super::versions::Assembly;
use crate::pbs::txs::GenomeBuild;
use crate::server::run::actix_server::CustomError;
use actix_web::{
    get,
    web::{self, Data, Json, Path},
};
use hgvs::data::interface::Provider as _;

/// Maximal page size.
static PAGE_SIZE_MAX: i32 = 1000;
/// Default page size.
static PAGE_SIZE_DEFAULT: i32 = 100;

/// Core implementation of the `/genes/txs` and `/api/v1/genes/transcripts` endpoints.
///
/// For now takes the `GeneTranscriptsQuery` as the argument and returns
/// the `GeneTranscriptsResponse` as the result.
fn genes_tx_impl(
    data: Data<super::WebServerData>,
    query: GeneTranscriptsQuery,
) -> Result<GeneTranscriptsResponse, CustomError> {
    let GeneTranscriptsQuery {
        genome_build,
        hgnc_id,
        page_size,
        next_page_token,
        ..
    } = query;
    let genome_build = genome_build.unwrap_or_else(|| String::from("grch37"));
    let hgnc_id = hgnc_id
        .as_ref()
        .ok_or_else(|| CustomError::new(anyhow::anyhow!("No HGNC ID provided.")))?;
    let page_size = page_size
        .unwrap_or(PAGE_SIZE_DEFAULT)
        .min(PAGE_SIZE_MAX)
        .max(1);

    let provider = data
        .provider
        .get(&genome_build)
        .ok_or_else(|| CustomError::new(anyhow::anyhow!("No provider available.")))?;
    let tx_acs = provider
        .get_tx_for_gene(hgnc_id)
        .map_err(|e| CustomError::new(anyhow::anyhow!("No transcripts found: {}", e)))?
        .into_iter()
        .map(|tx| tx.tx_ac)
        .collect::<Vec<_>>();
    let first = next_page_token
        .as_ref()
        .and_then(|next_page_token| tx_acs.iter().position(|tx_ac| tx_ac == next_page_token))
        .unwrap_or(0);
    let last = (first + page_size as usize).min(tx_acs.len());

    Ok(GeneTranscriptsResponse {
        transcripts: tx_acs[first..last]
            .iter()
            .filter_map(|tx_ac| provider.get_tx(tx_ac))
            .cloned()
            .collect::<Vec<_>>(),
        next_page_token: if last < tx_acs.len() {
            Some(tx_acs[last].clone())
        } else {
            None
        },
    })
}

/// Query for transcripts of a gene.
#[allow(clippy::unused_async)]
#[get("/genes/txs")]
async fn handle(
    data: Data<super::WebServerData>,
    _path: Path<()>,
    query: web::Query<GeneTranscriptsQuery>,
) -> actix_web::Result<Json<GeneTranscriptsResponse>, CustomError> {
    Ok(Json(genes_tx_impl(data, query.into_inner())?))
}

/// Query arguments for the `/api/v1/genes/transcripts` endpoint.
#[derive(Debug, Clone, serde::Deserialize, utoipa::ToSchema, utoipa::IntoParams)]
pub(crate) struct GenesTranscriptsListQuery {
    /// HGNC gene ID.
    pub hgnc_id: String,
    /// Genome build.
    pub genome_build: Assembly,
    /// Page size.
    pub page_size: Option<i32>,
    /// Next page token.
    pub next_page_token: Option<String>,
}

impl From<GenesTranscriptsListQuery> for GeneTranscriptsQuery {
    fn from(val: GenesTranscriptsListQuery) -> Self {
        GeneTranscriptsQuery {
            genome_build: Some(match val.genome_build {
                Assembly::Grch38 => String::from("grch38"),
                Assembly::Grch37 => String::from("grch37"),
            }),
            hgnc_id: Some(val.hgnc_id),
            #[allow(deprecated)]
            genome_build_enum: Some(
                match val.genome_build {
                    Assembly::Grch37 => GenomeBuild::Grch37,
                    Assembly::Grch38 => GenomeBuild::Grch38,
                }
                .into(),
            ),
            page_size: val.page_size,
            next_page_token: val.next_page_token,
        }
    }
}

/// Enumeration for `Transcript::biotype`.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TranscriptBiotype {
    /// Coding transcript.
    Coding,
    /// Non-coding transcript.
    NonCoding,
}

impl TryFrom<pbs::txs::TranscriptBiotype> for TranscriptBiotype {
    type Error = anyhow::Error;

    fn try_from(value: pbs::txs::TranscriptBiotype) -> Result<Self, Self::Error> {
        match value {
            pbs::txs::TranscriptBiotype::Coding => Ok(TranscriptBiotype::Coding),
            pbs::txs::TranscriptBiotype::NonCoding => Ok(TranscriptBiotype::NonCoding),
            _ => Err(anyhow::anyhow!("Invalid biotype: {:?}", value)),
        }
    }
}

// Bit values for the transcript tags.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TranscriptTag {
    /// Member of Ensembl basic.
    Basic,
    /// Member of Ensembl canonical.
    EnsemblCanonical,
    /// Member of MANE Select.
    ManeSelect,
    /// Member of MANE Plus Clinical.
    ManePlusClinical,
    /// Member of RefSeq Select.
    RefSeqSelect,
    /// Flagged as being a selenoprotein (UGA => selenon).
    Selenoprotein,
    /// Member of GENCODE Primary
    GencodePrimary,
    /// Catchall for other tags.
    Other,
    /// Member of Ensembl basic (Backport).
    BasicBackport,
    /// Member of Ensembl canonical (Backport).
    EnsemblCanonicalBackport,
    /// Member of MANE Select (Backport).
    ManeSelectBackport,
    /// Member of MANE Plus Clinical (Backport).
    ManePlusClinicalBackport,
    /// Member of RefSeq Select (Backport).
    RefSeqSelectBackport,
    /// Flagged as being a selenoprotein (UGA => selenon) (Backport).
    SelenoproteinBackport,
    /// Member of GENCODE Primary (Backport)
    GencodePrimaryBackport,
    /// Catchall for other tags (Backport).
    OtherBackport,
}

impl TryFrom<pbs::txs::TranscriptTag> for TranscriptTag {
    type Error = anyhow::Error;

    fn try_from(value: pbs::txs::TranscriptTag) -> Result<Self, Self::Error> {
        match value {
            pbs::txs::TranscriptTag::Basic => Ok(TranscriptTag::Basic),
            pbs::txs::TranscriptTag::EnsemblCanonical => Ok(TranscriptTag::EnsemblCanonical),
            pbs::txs::TranscriptTag::ManeSelect => Ok(TranscriptTag::ManeSelect),
            pbs::txs::TranscriptTag::ManePlusClinical => Ok(TranscriptTag::ManePlusClinical),
            pbs::txs::TranscriptTag::RefSeqSelect => Ok(TranscriptTag::RefSeqSelect),
            pbs::txs::TranscriptTag::Selenoprotein => Ok(TranscriptTag::Selenoprotein),
            pbs::txs::TranscriptTag::GencodePrimary => Ok(TranscriptTag::GencodePrimary),
            pbs::txs::TranscriptTag::Other => Ok(TranscriptTag::Other),
            pbs::txs::TranscriptTag::BasicBackport => Ok(TranscriptTag::BasicBackport),
            pbs::txs::TranscriptTag::EnsemblCanonicalBackport => {
                Ok(TranscriptTag::EnsemblCanonicalBackport)
            }
            pbs::txs::TranscriptTag::ManeSelectBackport => Ok(TranscriptTag::ManeSelectBackport),
            pbs::txs::TranscriptTag::ManePlusClinicalBackport => {
                Ok(TranscriptTag::ManePlusClinicalBackport)
            }
            pbs::txs::TranscriptTag::RefSeqSelectBackport => {
                Ok(TranscriptTag::RefSeqSelectBackport)
            }
            pbs::txs::TranscriptTag::SelenoproteinBackport => {
                Ok(TranscriptTag::SelenoproteinBackport)
            }
            pbs::txs::TranscriptTag::GencodePrimaryBackport => {
                Ok(TranscriptTag::GencodePrimaryBackport)
            }
            pbs::txs::TranscriptTag::OtherBackport => Ok(TranscriptTag::OtherBackport),
            _ => Err(anyhow::anyhow!("Invalid transcript tag: {:?}", value)),
        }
    }
}

/// Enumeration for the two strands of the genome.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Strand {
    /// unknown
    Unknown,
    /// Forward / plus
    Plus,
    /// Reverse / minus
    Minus,
}

impl From<pbs::txs::Strand> for Strand {
    fn from(value: pbs::txs::Strand) -> Self {
        match value {
            pbs::txs::Strand::Unknown => Strand::Unknown,
            pbs::txs::Strand::Plus => Strand::Plus,
            pbs::txs::Strand::Minus => Strand::Minus,
        }
    }
}

/// Store the alignment of one exon to the reference.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
pub(crate) struct ExonAlignment {
    /// Start position on reference.
    pub alt_start_i: i32,
    /// End position on reference.
    pub alt_end_i: i32,
    /// Exon number.
    pub ord: i32,
    /// CDS start coordinate.
    pub alt_cds_start_i: Option<i32>,
    /// CDS end coordinate.
    pub alt_cds_end_i: Option<i32>,
    /// CIGAR string of alignment, empty indicates full matches.
    pub cigar: String,
}

impl From<pbs::txs::ExonAlignment> for ExonAlignment {
    fn from(value: pbs::txs::ExonAlignment) -> Self {
        ExonAlignment {
            alt_start_i: value.alt_start_i,
            alt_end_i: value.alt_end_i,
            ord: value.ord,
            alt_cds_start_i: value.alt_cds_start_i,
            alt_cds_end_i: value.alt_cds_end_i,
            cigar: value.cigar.clone(),
        }
    }
}

/// Store information about a transcript aligning to a genome.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
pub(crate) struct GenomeAlignment {
    /// The genome build identifier.
    pub genome_build: Assembly,
    /// Accession of the contig sequence.
    pub contig: String,
    /// CDS end position, `-1` to indicate `None`.
    pub cds_start: Option<i32>,
    /// CDS end position, `-1` to indicate `None`.
    pub cds_end: Option<i32>,
    /// The strand.
    pub strand: Strand,
    /// Exons of the alignment.
    pub exons: Vec<ExonAlignment>,
}

impl TryFrom<pbs::txs::GenomeAlignment> for GenomeAlignment {
    type Error = anyhow::Error;

    fn try_from(value: pbs::txs::GenomeAlignment) -> Result<Self, Self::Error> {
        Ok(GenomeAlignment {
            genome_build: super::versions::Assembly::try_from(value.genome_build.as_str())?,
            contig: value.contig.clone(),
            cds_start: value.cds_start,
            cds_end: value.cds_end,
            strand: Strand::from(pbs::txs::Strand::try_from(value.strand)?),
            exons: value.exons.into_iter().map(Into::into).collect(),
        })
    }
}

/// Transcript information.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
pub(crate) struct Transcript {
    /// Transcript accession with version, e.g., `"NM_007294.3"` or `"ENST00000461574.1"` for BRCA1.
    pub id: String,
    /// HGNC symbol, e.g., `"BRCA1"`
    pub gene_symbol: String,
    /// Gene ID of the annotation, e.g., `"672"` for BRCA1 in RefSeq.
    pub gene_id: String,
    /// HGNC ID of the gene, e.g., `"HGNC:1100"` for BRCA1; unset for a gene without one.
    pub hgnc_id: Option<String>,
    /// Transcript biotype.
    pub biotype: TranscriptBiotype,
    /// Transcript flags.
    pub tags: Vec<TranscriptTag>,
    /// Identifier of the corresponding protein.
    pub protein: Option<String>,
    /// CDS start codon.
    pub start_codon: Option<i32>,
    /// CDS stop codon. If the poly-A tail completes the stop codon, it ends 1 or 2 bases after the last exon.
    pub stop_codon: Option<i32>,
    /// Alignments on the different genome builds.
    pub genome_alignments: Vec<GenomeAlignment>,
    /// Whether this transcript has an issue (e.g. MissingStopCodon), cf. `mehari::db::create::mod::Reason`.
    pub filtered: Option<bool>,
    /// Reason for filtering.
    pub filter_reason: ::core::option::Option<u32>,
}

impl TryFrom<pbs::txs::Transcript> for Transcript {
    type Error = anyhow::Error;

    fn try_from(value: pbs::txs::Transcript) -> Result<Self, Self::Error> {
        Ok(Transcript {
            id: value.id.clone(),
            gene_symbol: value.gene_symbol.clone(),
            gene_id: value.gene_id.clone(),
            hgnc_id: value.hgnc_id.clone(),
            biotype: TranscriptBiotype::try_from(pbs::txs::TranscriptBiotype::try_from(
                value.biotype,
            )?)?,
            tags: value
                .tags
                .into_iter()
                .map(|i32_tag| -> Result<_, anyhow::Error> {
                    TranscriptTag::try_from(pbs::txs::TranscriptTag::try_from(i32_tag)?)
                })
                .collect::<Result<Vec<_>, _>>()?,
            protein: value.protein.clone(),
            start_codon: value.start_codon,
            stop_codon: value.stop_codon,
            genome_alignments: value
                .genome_alignments
                .into_iter()
                .map(TryInto::try_into)
                .collect::<Result<_, _>>()?,
            filtered: value.filtered,
            filter_reason: value.filter_reason,
        })
    }
}

/// Severity of a `GenesTranscriptsMessage`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
// `Info` and `Error` are part of the API schema but not emitted yet.
#[allow(dead_code)]
pub(crate) enum MessageLevel {
    /// Informational message.
    Info,
    /// Warning, the result may be incomplete.
    Warning,
    /// Error.
    Error,
}

/// Machine-readable code of a `GenesTranscriptsMessage`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub(crate) enum MessageCode {
    /// No transcripts were found for the gene.
    NoTranscripts,
}

/// Message attached to a `GenesTranscriptsListResponse`.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
pub(crate) struct GenesTranscriptsMessage {
    /// Severity of the message.
    pub level: MessageLevel,
    /// Machine-readable code.
    pub code: MessageCode,
    /// Human-readable message.
    pub message: String,
}

/// Response of the `/api/v1/genes/transcripts` endpoint.
#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
pub(crate) struct GenesTranscriptsListResponse {
    /// The transcripts for the gene.
    pub transcripts: Vec<Transcript>,
    /// The token to continue from a previous query.
    pub next_page_token: Option<String>,
    /// Optional list of warnings and error messages.
    pub messages: Option<Vec<GenesTranscriptsMessage>>,
}

impl TryFrom<pbs::server::GeneTranscriptsResponse> for GenesTranscriptsListResponse {
    type Error = anyhow::Error;

    fn try_from(value: pbs::server::GeneTranscriptsResponse) -> Result<Self, Self::Error> {
        Ok(GenesTranscriptsListResponse {
            transcripts: value
                .transcripts
                .into_iter()
                .map(TryInto::try_into)
                .collect::<Result<_, _>>()?,
            next_page_token: value.next_page_token,
            messages: None,
        })
    }
}

/// Query for transcripts of a gene.
#[allow(clippy::unused_async)]
#[utoipa::path(
    get,
    operation_id = "genesTranscriptsList",
    params(GenesTranscriptsListQuery),
    responses(
        (status = 200, description = "Transcripts for the selected gene.", body = GenesTranscriptsListResponse),
        (status = 500, description = "Internal server error.", body = CustomError)
    )
)]
#[get("/api/v1/genes/transcripts")]
async fn handle_with_openapi(
    data: Data<super::WebServerData>,
    _path: Path<()>,
    query: web::Query<GenesTranscriptsListQuery>,
) -> actix_web::Result<Json<GenesTranscriptsListResponse>, CustomError> {
    let query: GeneTranscriptsQuery = query.into_inner().into();
    let hgnc_id = query.hgnc_id.clone().unwrap_or_default();
    let assembly = query.genome_build.clone().unwrap_or_default();
    let result = genes_tx_impl(data, query)?;
    let mut response: GenesTranscriptsListResponse = result
        .try_into()
        .map_err(|e| CustomError::new(anyhow::anyhow!("Conversion error: {}", e)))?;
    if response.transcripts.is_empty() {
        response.messages = Some(vec![GenesTranscriptsMessage {
            level: MessageLevel::Warning,
            code: MessageCode::NoTranscripts,
            message: format!("no transcripts found for gene {hgnc_id} in assembly {assembly}"),
        }]);
    }
    Ok(Json(response))
}

#[cfg(test)]
mod test {
    /// The transcripts of a gene report the gene ID of the annotation and the HGNC ID.
    #[test]
    fn gene_id_of_transcripts() -> Result<(), anyhow::Error> {
        use crate::annotate::seqvars::provider::{Provider, test_db};
        use crate::pbs::server::GeneTranscriptsQuery;
        use crate::server::run::actix_server::WebServerData;
        use std::sync::Arc;

        let provider = Provider::new(test_db::one_gene_db(), None::<&str>, true);
        let data = WebServerData {
            provider: [("grch38".to_string(), Arc::new(provider))].into(),
            ..Default::default()
        };
        let query = GeneTranscriptsQuery {
            genome_build: Some("grch38".into()),
            hgnc_id: Some("HGNC:1".into()),
            ..Default::default()
        };

        let response = super::genes_tx_impl(actix_web::web::Data::new(data), query)
            .map_err(|e| anyhow::anyhow!("{e}"))?;
        let gene_ids: Vec<_> = response
            .transcripts
            .iter()
            .map(|tx| tx.gene_id.clone())
            .collect();
        assert_eq!(gene_ids, ["11"]);

        let response = super::GenesTranscriptsListResponse::try_from(response)?;
        let gene_ids: Vec<_> = response
            .transcripts
            .iter()
            .map(|tx| (tx.gene_id.clone(), tx.hgnc_id.clone()))
            .collect();
        assert_eq!(gene_ids, [("11".to_string(), Some("HGNC:1".to_string()))]);

        Ok(())
    }
}