mehari 0.42.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
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
//! Implementation of `hgvs` Provider interface based on protobuf.

use crate::annotate::cli::{TranscriptPickMode, TranscriptPickType};
use crate::annotate::seqvars::reference::{
    InMemoryFastaAccess, ReferenceReader, UnbufferedIndexedFastaAccess,
};
use crate::common::contig::ContigManager;
use crate::db::TranscriptDatabase;
use crate::db::create::models::Reason;
use crate::{
    annotate::seqvars::csq::ALT_ALN_METHOD,
    pbs::txs::{GeneToTxId, Strand, Transcript, TranscriptTag, TxSeqDatabase},
};
use bio::data_structures::interval_tree::ArrayBackedIntervalTree;
use enumflags2::BitFlags;
use hgvs::{
    data::error::Error,
    data::{
        cdot::json::NCBI_ALN_METHOD,
        interface::{
            Provider as ProviderInterface, TxExonsRecord, TxForRegionRecord, TxIdentityInfo,
            TxInfoRecord, TxMappingOptionsRecord,
        },
    },
    sequences::{TranslationTable, seq_md5},
};
use indexmap::IndexMap;
use itertools::Itertools;
use rustc_hash::FxHashMap;
use std::path::Path;
use std::sync::Arc;

type IntervalTree = ArrayBackedIntervalTree<i32, u32>;

pub struct TxIntervalTrees {
    /// Mapping from contig accession to index in `trees`.
    pub contig_to_idx: FxHashMap<String, usize>,
    /// Interval tree to index in `TxSeqDatabase::tx_db::transcripts`, for each contig.
    pub trees: Vec<IntervalTree>,
}

impl TxIntervalTrees {
    pub fn new(db: &TxSeqDatabase) -> Self {
        let (contig_to_idx, trees) = Self::build_indices(db);
        Self {
            contig_to_idx,
            trees,
        }
    }

    fn build_indices(db: &TxSeqDatabase) -> (FxHashMap<String, usize>, Vec<IntervalTree>) {
        let assembly_name = db.assembly();
        let mut contig_to_idx = FxHashMap::default();
        let mut trees: Vec<IntervalTree> = Vec::new();

        let tx_db = db.tx_db.as_ref().expect("no tx_db?");
        let mut txs_counted = 0;

        for (tx_id, tx) in tx_db.transcripts.iter().enumerate() {
            for genome_alignment in &tx.genome_alignments {
                // Only index alignments matching the current assembly/build
                if genome_alignment
                    .genome_build
                    .eq_ignore_ascii_case(&assembly_name)
                {
                    let contig = &genome_alignment.contig;

                    let contig_idx = *contig_to_idx.entry(contig.clone()).or_insert_with(|| {
                        let idx = trees.len();
                        trees.push(IntervalTree::new());
                        idx
                    });

                    let mut start = i32::MAX;
                    let mut stop = i32::MIN;
                    for exon in &genome_alignment.exons {
                        start = std::cmp::min(start, exon.alt_start_i);
                        stop = std::cmp::max(stop, exon.alt_end_i);
                    }

                    if start <= stop {
                        trees[contig_idx].insert(start..stop, tx_id as u32);
                    }
                }
            }
            txs_counted += 1;
        }

        tracing::debug!(
            "Indexed {} transcripts across {} contigs for assembly {}",
            txs_counted,
            trees.len(),
            assembly_name
        );

        trees.iter_mut().for_each(|t| t.index());

        (contig_to_idx, trees)
    }

    pub fn get_tx_for_region(
        &self,
        tx_seq_db: &TxSeqDatabase,
        alt_ac: &str,
        _alt_aln_method: &str,
        start_i: i32,
        end_i: i32,
    ) -> Result<Vec<TxForRegionRecord>, Error> {
        let contig_idx = match self.contig_to_idx.get(alt_ac) {
            Some(idx) => *idx,
            None => return Ok(Vec::new()),
        };
        let query = start_i..end_i;
        let tx_idxs = self.trees[contig_idx].find(query);

        Ok(tx_idxs
            .iter()
            .map(|entry| {
                let tx = &tx_seq_db.tx_db.as_ref().expect("no tx_db?").transcripts
                    [*entry.data() as usize];
                assert_eq!(
                    tx.genome_alignments.len(),
                    1,
                    "Can only have one alignment in Mehari"
                );
                let alt_strand = tx.genome_alignments.first().unwrap().strand;
                TxForRegionRecord {
                    tx_ac: tx.id.clone(),
                    alt_ac: alt_ac.to_string(),
                    alt_strand: match Strand::try_from(alt_strand).expect("invalid strand") {
                        Strand::Plus => 1,
                        Strand::Minus => -1,
                        _ => unreachable!("invalid strand {}", alt_strand),
                    },
                    alt_aln_method: ALT_ALN_METHOD.to_string(),
                    start_i,
                    end_i,
                }
            })
            .collect())
    }
}

/// Extension trait to easily check the filter status of a transcript.
pub trait PbsTranscriptExt {
    /// Returns true if the transcript has absolutely no filter flags (hard or soft).
    fn is_clean(&self) -> bool;

    /// Returns true if the transcript is incomplete (e.g. missing stop codon).
    fn is_incomplete_3p(&self) -> bool;

    /// Computes the available CDS length. If the stop codon is missing,
    /// it uses the provided transcript length to bound the remaining sequence.
    fn available_cds_len(&self, tx_len: i32) -> Option<i32>;
}

impl PbsTranscriptExt for Transcript {
    fn is_clean(&self) -> bool {
        self.filter_reason.unwrap_or(0) == 0
    }

    fn is_incomplete_3p(&self) -> bool {
        let flags = BitFlags::<Reason>::from_bits_truncate(self.filter_reason.unwrap_or(0));
        flags.intersects(Reason::MissingStopCodon | Reason::ThreePrimeEndTruncated)
    }

    fn available_cds_len(&self, tx_len: i32) -> Option<i32> {
        self.start_codon
            .map(|start| self.stop_codon.unwrap_or(tx_len) - start)
    }
}

/// Configuration for constructing the `Provider`.
#[derive(Debug, Clone, Default, derive_builder::Builder)]
#[builder(pattern = "immutable")]
pub struct Config {
    /// Which kind of transcript to pick / restrict to. Default is not to pick at all.
    ///
    /// Depending on `--pick-transcript-mode`, if multiple transcripts match the selection,
    /// either the first one is kept or all are kept.
    #[builder(default)]
    pub pick_transcript: Vec<TranscriptPickType>,

    /// Determines how to handle multiple transcripts. Default is to keep all.
    ///
    /// When transcript picking is enabled via `--pick-transcript`,
    /// either keep the first one found or keep all that match.
    #[builder(default)]
    pub pick_transcript_mode: TranscriptPickMode,
}

/// Provider based on the protobuf `TxSeqDatabase`.
pub struct Provider {
    /// Database of transcripts and sequences as deserialized from protobuf.
    pub tx_seq_db: TxSeqDatabase,

    /// Interval trees for the tanscripts.
    pub tx_trees: TxIntervalTrees,

    /// The contig name manager.
    pub contig_manager: Arc<ContigManager>,

    /// Mapping from gene identifier to index in `TxSeqDatabase::tx_db::gene_to_tx`.
    gene_map: FxHashMap<String, u32>,

    /// Mapping from transcript accession to index in `TxSeqDatabase::tx_db::transcripts`.
    tx_map: FxHashMap<String, u32>,

    /// Mapping from sequence accession to index in `TxSeqDatabase::seq_db::seqs`.
    seq_map: FxHashMap<String, u32>,

    /// Map from contig accession to common name (e.g., "NC_000001.11" -> "1")
    assembly_map: IndexMap<String, String>,

    /// Maps any known contig alias (e.g. "chr1", "NC_000001.11") to the exact
    /// string used in the database (e.g. "1")
    contig_alias_map: FxHashMap<String, String>,

    /// When transcript picking is enabled, contains the `GeneToTxIdx` entries
    /// for each gene; the order matches the one of `tx_seq_db.gene_to_tx`.
    picked_gene_to_tx_id: Option<Vec<GeneToTxId>>,

    /// for reading parts of reference sequences
    reference_reader: Option<ReferenceReaderImpl>,

    /// The data version.
    data_version: String,

    /// The schema version.
    schema_version: String,
}

enum ReferenceReaderImpl {
    InMemory(InMemoryFastaAccess),
    Unbuffered(UnbufferedIndexedFastaAccess),
}

impl ReferenceReader for ReferenceReaderImpl {
    fn get(
        &self,
        ac: &str,
        start: Option<u64>,
        end: Option<u64>,
    ) -> anyhow::Result<Option<Vec<u8>>> {
        match self {
            ReferenceReaderImpl::InMemory(v) => v.get(ac, start, end),
            ReferenceReaderImpl::Unbuffered(v) => v.get(ac, start, end),
        }
    }
}

fn transcript_length(tx: &Transcript) -> i32 {
    let mut max_tx_length = 0;
    for genome_alignment in tx.genome_alignments.iter() {
        // We just count length in reference so we don't have to look
        // into the CIGAR string.
        let mut tx_length = 0;
        for exon_alignment in genome_alignment.exons.iter() {
            tx_length += exon_alignment.alt_cds_end_i() - exon_alignment.alt_cds_start_i();
        }
        if tx_length > max_tx_length {
            max_tx_length = tx_length;
        }
    }
    max_tx_length
}

impl Provider {
    /// Create a new `MehariProvider` from a `TxSeqDatabase`.
    ///
    /// # Arguments
    ///
    /// * `tx_seq_db` - The `TxSeqDatabase` to use.
    pub fn new(
        mut tx_seq_db: TxSeqDatabase,
        reference: Option<impl AsRef<Path>>,
        in_memory_reference: bool,
        config: Config,
    ) -> Self {
        let assembly_name = tx_seq_db.assembly().clone();

        // ContigManager is still useful for name resolution (e.g. NC -> chr name)
        // If it's a custom assembly, it might just return the accession.
        let contig_manager = Arc::new(ContigManager::new(&assembly_name));

        // Build the assembly map from alignments in the DB
        let mut assembly_map = IndexMap::new();
        if let Some(tx_db) = &tx_seq_db.tx_db {
            for tx in &tx_db.transcripts {
                for aln in &tx.genome_alignments {
                    if aln.genome_build.eq_ignore_ascii_case(&assembly_name)
                        && !assembly_map.contains_key(&aln.contig)
                    {
                        let common_name = contig_manager
                            .get_primary_name(&aln.contig)
                            .cloned()
                            .unwrap_or_else(|| aln.contig.clone());

                        assembly_map.insert(aln.contig.clone(), common_name);
                    }
                }
            }
        }

        let tx_trees = TxIntervalTrees::new(&tx_seq_db);

        let mut contig_alias_map = FxHashMap::default();
        if let Some(tx_db) = &tx_seq_db.tx_db {
            for tx in &tx_db.transcripts {
                for aln in &tx.genome_alignments {
                    let db_contig = aln.contig.clone();
                    contig_alias_map.insert(db_contig.clone(), db_contig.clone());

                    if let Some(primary) = contig_manager.get_primary_name(&db_contig) {
                        contig_alias_map.insert(primary.to_string(), db_contig.clone());
                    }
                    if let Some(acc) = contig_manager.get_accession(&db_contig) {
                        contig_alias_map.insert(acc.to_string(), db_contig.clone());
                    }
                    if let Some(info) = contig_manager.get_contig_info(&db_contig) {
                        contig_alias_map.insert(info.name_with_chr.clone(), db_contig.clone());
                        contig_alias_map.insert(info.name_without_chr.clone(), db_contig.clone());
                    }
                }
            }
        }

        let gene_map = FxHashMap::from_iter(
            tx_seq_db
                .tx_db
                .as_ref()
                .expect("no tx_db?")
                .gene_to_tx
                .iter()
                // .filter(|gene| !gene.filtered.unwrap_or(false))
                .enumerate()
                .map(|(idx, entry)| (entry.gene_id.clone(), idx as u32)),
        );
        let tx_map = FxHashMap::from_iter(
            tx_seq_db
                .tx_db
                .as_ref()
                .expect("no tx_db?")
                .transcripts
                .iter()
                // .filter(|tx| !tx.filtered.unwrap_or(false))
                .enumerate()
                .map(|(idx, tx)| (tx.id.clone(), idx as u32)),
        );
        let seq_map = FxHashMap::from_iter(
            tx_seq_db
                .seq_db
                .as_ref()
                .expect("no seq_db?")
                .aliases
                .iter()
                .zip(
                    tx_seq_db
                        .seq_db
                        .as_ref()
                        .expect("no seq_db?")
                        .aliases_idx
                        .iter(),
                )
                .map(|(alias, idx)| (alias.clone(), *idx)),
        );

        let picked_gene_to_tx_id = Self::picked_genes_to_tx_map(&mut tx_seq_db, &config, &tx_map);

        // TODO obtain or construct data_version and schema_version somehow
        // for now, these are just set to a combination of things that make this provider instance
        // unique, such that `data_version` and `schema_version` can be used as keys for
        // caching.
        let data_version = format!(
            "{}{}{:?}",
            tx_seq_db.version.as_ref().unwrap_or(&"".to_string()),
            tx_seq_db
                .source_version
                .iter()
                .map(|v| format!("{:#?}", v))
                .join(","),
            config
        );
        let schema_version = data_version.clone();

        let reference_reader = match (reference, in_memory_reference) {
            (Some(path), false) => Some(ReferenceReaderImpl::Unbuffered(
                UnbufferedIndexedFastaAccess::from_path(path, contig_manager.clone())
                    .expect("Failed to open reference FASTA file"),
            )),
            (Some(path), true) => Some(ReferenceReaderImpl::InMemory(
                InMemoryFastaAccess::from_path(path, contig_manager.clone())
                    .expect("Failed to open reference FASTA file"),
            )),
            (None, _) => None,
        };

        Self {
            tx_seq_db,
            tx_trees,
            contig_manager,
            contig_alias_map,
            gene_map,
            tx_map,
            seq_map,
            assembly_map,
            picked_gene_to_tx_id,
            reference_reader,
            data_version,
            schema_version,
        }
    }

    /// When transcript picking is enabled, restrict to ManeSelect and ManePlusClinical if we have any such transcript.
    /// Otherwise, fall back to the longest transcript.
    fn picked_genes_to_tx_map(
        tx_seq_db: &mut TxSeqDatabase,
        config: &Config,
        tx_map: &FxHashMap<String, u32>,
    ) -> Option<Vec<GeneToTxId>> {
        if config.pick_transcript.is_empty() || tx_seq_db.tx_db.is_none() {
            return None;
        }
        let tx_db = tx_seq_db.tx_db.as_mut().unwrap();
        let mut new_gene_to_tx = Vec::new();

        fn tag_to_picktype(tag: &i32) -> Option<TranscriptPickType> {
            match TranscriptTag::try_from(*tag).unwrap() {
                TranscriptTag::Unknown | TranscriptTag::Other | TranscriptTag::OtherBackport => {
                    None
                }
                TranscriptTag::Basic => Some(TranscriptPickType::Basic),
                TranscriptTag::EnsemblCanonical => Some(TranscriptPickType::EnsemblCanonical),
                TranscriptTag::ManeSelect => Some(TranscriptPickType::ManeSelect),
                TranscriptTag::ManePlusClinical => Some(TranscriptPickType::ManePlusClinical),
                TranscriptTag::RefSeqSelect => Some(TranscriptPickType::RefSeqSelect),
                TranscriptTag::Selenoprotein => None,
                TranscriptTag::GencodePrimary => Some(TranscriptPickType::GencodePrimary),
                TranscriptTag::EnsemblGraft => None,
                TranscriptTag::BasicBackport => Some(TranscriptPickType::BasicBackport),
                TranscriptTag::EnsemblCanonicalBackport => {
                    Some(TranscriptPickType::EnsemblCanonicalBackport)
                }
                TranscriptTag::ManeSelectBackport => Some(TranscriptPickType::ManeSelectBackport),
                TranscriptTag::ManePlusClinicalBackport => {
                    Some(TranscriptPickType::ManePlusClinicalBackport)
                }
                TranscriptTag::RefSeqSelectBackport => {
                    Some(TranscriptPickType::RefSeqSelectBackport)
                }
                TranscriptTag::SelenoproteinBackport => None,
                TranscriptTag::GencodePrimaryBackport => {
                    Some(TranscriptPickType::GencodePrimaryBackport)
                }
            }
        }

        // FIXME: This source classification is a legacy artifact for VarFish TSV compatibility.
        //   It should be removed once the varfish tsv export/import is updated.
        let transcript_id_to_source = |tx_id: &str| -> String {
            if tx_id.starts_with("ENST") {
                "Ensembl".to_string()
            } else if tx_id.starts_with('N') || tx_id.starts_with('X') {
                "RefSeq".to_string()
            } else {
                // Safe fallback for arbitrary databases (e.g., TAIR10, custom assemblies)
                "Other".to_string()
            }
        };

        // Process each gene.
        for entry in tx_db.gene_to_tx.iter() {
            let mut longest_tx_per_source: FxHashMap<String, (bool, usize, i32)> =
                FxHashMap::default();
            let mut tx_tags = entry
                .tx_ids
                .iter()
                .filter_map(|tx_id| {
                    tx_map.get(tx_id).map(|tx_idx| {
                        let tx = &tx_db.transcripts[*tx_idx as usize];
                        let tags = tx.tags.iter().filter_map(tag_to_picktype).collect_vec();
                        let length = transcript_length(tx);
                        let source = transcript_id_to_source(tx_id);
                        let is_clean = tx.is_clean();
                        (tx_id, tags, length, source, is_clean)
                    })
                })
                .enumerate()
                .map(|(i, (tx_id, tags, length, source, is_clean))| {
                    longest_tx_per_source
                        .entry(source)
                        .and_modify(|(prev_clean, prev_i, prev_length)| {
                            if (is_clean, length) > (*prev_clean, *prev_length) {
                                *prev_clean = is_clean;
                                *prev_i = i;
                                *prev_length = length;
                            }
                        })
                        .or_insert((is_clean, i, length));
                    (tx_id, tags, length)
                })
                .collect_vec();

            for (_, (_, i, _)) in longest_tx_per_source.iter() {
                tx_tags[*i].1.push(TranscriptPickType::Length);
            }

            let tx_ids = match config.pick_transcript_mode {
                TranscriptPickMode::First => {
                    // only keep the first transcript that fulfills the transcript picking strategy,
                    // if any
                    let tx_id = config
                        .pick_transcript
                        .iter()
                        .filter_map(|pick| {
                            tx_tags
                                .iter()
                                .find(|(_, tags, _)| tags.contains(pick))
                                .map(|(tx_id, _, _)| tx_id)
                        })
                        .next();
                    if let Some(tx_id) = tx_id {
                        vec![tx_id.to_string()]
                    } else {
                        vec![]
                    }
                }
                TranscriptPickMode::All => {
                    // keep all transcripts that fulfill the transcript picking strategy
                    tx_tags
                        .iter()
                        .filter_map(|(tx_id, tags, _)| {
                            tags.iter()
                                .any(|tag| config.pick_transcript.contains(tag))
                                .then_some(tx_id.to_string())
                        })
                        .collect()
                }
            };

            let new_entry = if !tx_ids.is_empty() {
                GeneToTxId {
                    gene_id: entry.gene_id.clone(),
                    tx_ids,
                    filtered: Some(false),
                    filter_reason: None,
                }
            } else {
                tracing::trace!(
                    "no transcript found for gene {} with the chosen transcript picking strategy: {:?}",
                    &entry.gene_id,
                    &config.pick_transcript
                );
                GeneToTxId {
                    gene_id: entry.gene_id.clone(),
                    tx_ids: vec![],
                    filtered: Some(true),
                    filter_reason: Some(Reason::NoTranscriptLeft as u32),
                }
            };

            tracing::trace!(
                "picked transcripts {:?} for gene {}",
                new_entry.tx_ids,
                new_entry.gene_id
            );
            new_gene_to_tx.push(new_entry);
        }

        Some(new_gene_to_tx)
    }

    /// Return the assembly of the provider.
    ///
    /// # Returns
    ///
    /// The assembly of the provider.
    pub fn assembly(&self) -> String {
        self.tx_seq_db.assembly().clone()
    }

    /// Return whether transcript picking is enabled.
    pub fn transcript_picking(&self) -> bool {
        self.picked_gene_to_tx_id.is_some()
    }

    /// Return the picked transcript IDs for a gene.
    ///
    /// # Args
    ///
    /// * `gene_name` - The gene HGNC ID.
    ///
    /// # Returns
    ///
    /// The picked transcript IDs, or None if the gene is not found.
    pub fn get_picked_transcripts(&self, hgnc_id: &str) -> Option<Vec<String>> {
        self.gene_map.get(hgnc_id).and_then(|gene_idx| {
            let gene_to_tx = if let Some(picked_gene_to_tx_id) = self.picked_gene_to_tx_id.as_ref()
            {
                picked_gene_to_tx_id
            } else {
                &self.tx_seq_db.tx_db.as_ref().expect("no tx_db?").gene_to_tx
            };

            // tracing::trace!(
            //     "get_picked_transcripts({}) = {:?}",
            //     hgnc_id,
            //     &gene_to_tx[*gene_idx as usize].tx_ids
            // );
            let gene = &gene_to_tx[*gene_idx as usize];
            if let Some(true) = gene.filtered {
                None
            } else {
                Some(gene.tx_ids.clone())
            }
        })
    }

    /// Return `Transcript` for the given transcript accession.
    ///
    /// # Args
    ///
    /// * `tx_id` - The transcript accession.
    ///
    /// # Returns
    ///
    /// The `Transcript` for the given accession, or None if the accession was not found.
    pub fn get_tx(&self, tx_id: &str) -> Option<&Transcript> {
        self.tx_map.get(tx_id).and_then(|idx| {
            let tx = &self
                .tx_seq_db
                .tx_db
                .as_ref()
                .expect("no tx_db?")
                .transcripts[*idx as usize];
            if let Some(true) = tx.filtered {
                None
            } else {
                Some(tx)
            }
        })
    }

    pub fn reference_available(&self) -> bool {
        self.reference_reader.is_some()
    }
}

impl ProviderInterface for Provider {
    fn data_version(&self) -> &str {
        // TODO replace with proper data_version (see comment in `Provider::new`)
        &self.data_version
    }

    fn schema_version(&self) -> &str {
        // TODO replace with proper schema_version (see comment in `Provider::new`)
        &self.schema_version
    }

    fn get_assembly_map(
        &self,
        _assembly: &str,
    ) -> Result<IndexMap<String, String>, hgvs::data::error::Error> {
        // We ignore the `assembly` argument because this provider
        // is bound to a specific build during construction anyway.
        Ok(self.assembly_map.clone())
    }

    fn get_gene_info(&self, _hgnc: &str) -> Result<hgvs::data::interface::GeneInfoRecord, Error> {
        panic!("not implemented");
    }

    fn get_pro_ac_for_tx_ac(&self, tx_ac: &str) -> Result<Option<String>, Error> {
        let tx_idx = *self
            .tx_map
            .get(tx_ac)
            .ok_or(Error::NoTranscriptFound(tx_ac.to_string()))?;
        let tx_idx = tx_idx as usize;
        let tx = &self
            .tx_seq_db
            .tx_db
            .as_ref()
            .expect("no tx_db?")
            .transcripts[tx_idx];
        Ok(tx.protein.clone())
    }

    fn get_seq_part(
        &self,
        ac: &str,
        begin: Option<usize>,
        end: Option<usize>,
    ) -> Result<String, Error> {
        let is_contig = self.contig_alias_map.contains_key(ac);
        let seq = if is_contig && self.reference_available() {
            let reader = self.reference_reader.as_ref().unwrap();
            let seq = reader
                .get(ac, begin.map(|x| x as u64), end.map(|x| x as u64))
                .map_err(|e| {
                    tracing::error!("Failed to fetch sequence for {}: {}", ac, e);
                    Error::NoSequenceRecord(format!("{} - {}", ac, e))
                })?
                .ok_or_else(|| Error::NoSequenceRecord(ac.to_string()))?;

            return String::from_utf8(seq).map_err(|_| {
                Error::NoSequenceRecord("Failed converting seq to UTF-8.".to_string())
            });
        } else {
            let seq_idx = *self
                .seq_map
                .get(ac)
                .ok_or_else(|| Error::NoSequenceRecord(ac.to_string()))?;
            let seq_idx = seq_idx as usize;
            self.tx_seq_db.seq_db.as_ref().expect("no seq_db?").seqs[seq_idx].as_bytes()
        };

        let slice = match (begin, end) {
            (Some(begin), Some(end)) => {
                let begin = std::cmp::min(begin, seq.len());
                let end = std::cmp::min(end, seq.len());
                &seq[begin..end]
            }
            (Some(begin), None) => {
                let begin = std::cmp::min(begin, seq.len());
                &seq[begin..]
            }
            (None, Some(end)) => &seq[..end],
            (None, None) => seq,
        };
        Ok(String::from_utf8_lossy(slice).to_string())
    }

    fn get_acs_for_protein_seq(&self, seq: &str) -> Result<Vec<String>, Error> {
        Ok(vec![format!("MD5_{}", seq_md5(seq, true)?)])
    }

    fn get_similar_transcripts(
        &self,
        _tx_ac: &str,
    ) -> Result<Vec<hgvs::data::interface::TxSimilarityRecord>, Error> {
        panic!("not implemented");
    }

    fn get_tx_exons(
        &self,
        tx_ac: &str,
        alt_ac: &str,
        _alt_aln_method: &str,
    ) -> Result<Vec<TxExonsRecord>, Error> {
        let db_contig = self
            .contig_alias_map
            .get(alt_ac)
            .map(String::as_str)
            .unwrap_or(alt_ac);
        let tx_idx = *self
            .tx_map
            .get(tx_ac)
            .ok_or(Error::NoTranscriptFound(tx_ac.to_string()))?;
        let tx_idx = tx_idx as usize;

        let tx = &self
            .tx_seq_db
            .tx_db
            .as_ref()
            .expect("no tx_db?")
            .transcripts[tx_idx];

        let hgnc = tx.gene_id.clone();
        let tx_ac_str = tx_ac.to_string();
        let alt_ac_str = db_contig.to_string();
        let alt_aln_method_str = ALT_ALN_METHOD.to_string();

        for genome_alignment in &tx.genome_alignments {
            if genome_alignment.contig == db_contig {
                let alt_strand =
                    match Strand::try_from(genome_alignment.strand).expect("invalid strand") {
                        Strand::Plus => 1,
                        Strand::Minus => -1,
                        _ => unreachable!("invalid strand {}", &genome_alignment.strand),
                    };

                let mut exons = Vec::with_capacity(genome_alignment.exons.len());

                for exon in &genome_alignment.exons {
                    exons.push(TxExonsRecord {
                        hgnc: hgnc.clone(),
                        tx_ac: tx_ac_str.clone(),
                        alt_ac: alt_ac_str.clone(),
                        alt_aln_method: alt_aln_method_str.clone(),
                        alt_strand,
                        ord: exon.ord,
                        tx_start_i: exon.alt_cds_start_i.map(|val| val - 1).unwrap_or(-1),
                        tx_end_i: exon.alt_cds_end_i.unwrap_or(-1),
                        alt_start_i: exon.alt_start_i,
                        alt_end_i: exon.alt_end_i,
                        cigar: exon.cigar.clone(),
                        tx_aseq: None,
                        alt_aseq: None,
                        tx_exon_set_id: i32::MAX,
                        alt_exon_set_id: i32::MAX,
                        tx_exon_id: i32::MAX,
                        alt_exon_id: i32::MAX,
                        exon_aln_id: i32::MAX,
                    });
                }

                exons.sort_unstable_by_key(|e| e.alt_start_i);
                return Ok(exons);
            }
        }

        Err(Error::NoAlignmentFound(
            tx_ac.to_string(),
            alt_ac.to_string(),
        ))
    }

    fn get_tx_exon_coords(
        &self,
        tx_ac: &str,
        alt_ac: &str,
        _alt_aln_method: &str,
    ) -> Result<Vec<(i32, i32)>, Error> {
        let db_contig = self
            .contig_alias_map
            .get(alt_ac)
            .map(String::as_str)
            .unwrap_or(alt_ac);
        let tx_idx = *self
            .tx_map
            .get(tx_ac)
            .ok_or(Error::NoTranscriptFound(tx_ac.to_string()))?;
        let tx = &self
            .tx_seq_db
            .tx_db
            .as_ref()
            .expect("no tx_db?")
            .transcripts[tx_idx as usize];

        for genome_alignment in &tx.genome_alignments {
            if genome_alignment.contig == db_contig {
                let mut coords = Vec::with_capacity(genome_alignment.exons.len());
                for exon in &genome_alignment.exons {
                    let tx_start = exon.alt_cds_start_i.map(|val| val - 1).unwrap_or(-1);
                    let tx_end = exon.alt_cds_end_i.unwrap_or(-1);
                    coords.push((exon.alt_start_i, tx_start, tx_end));
                }
                coords.sort_unstable_by_key(|c| c.0);
                return Ok(coords.into_iter().map(|(_, s, e)| (s, e)).collect());
            }
        }
        Err(Error::NoAlignmentFound(
            tx_ac.to_string(),
            db_contig.to_string(),
        ))
    }

    fn get_cds_start_end(
        &self,
        tx_ac: &str,
        alt_ac: &str,
        _alt_aln_method: &str,
    ) -> Result<(Option<i32>, Option<i32>), Error> {
        let db_contig = self
            .contig_alias_map
            .get(alt_ac)
            .map(String::as_str)
            .unwrap_or(alt_ac);
        let tx_idx = *self
            .tx_map
            .get(tx_ac)
            .ok_or(Error::NoTranscriptFound(tx_ac.to_string()))?;
        let tx = &self
            .tx_seq_db
            .tx_db
            .as_ref()
            .expect("no tx_db?")
            .transcripts[tx_idx as usize];

        for genome_alignment in &tx.genome_alignments {
            if genome_alignment.contig == db_contig {
                return Ok((tx.start_codon, tx.stop_codon));
            }
        }
        Err(Error::NoAlignmentFound(
            tx_ac.to_string(),
            db_contig.to_string(),
        ))
    }

    fn get_tx_for_gene(&self, gene: &str) -> Result<Vec<TxInfoRecord>, Error> {
        let tx_acs = if let Some(tx_acs) = self.get_picked_transcripts(gene) {
            tx_acs
        } else {
            tracing::warn!("no transcripts found for gene: {}", gene);
            return Ok(Vec::default());
        };

        tx_acs
            .iter()
            .filter_map(|tx_ac| -> Option<Result<TxInfoRecord, Error>> {
                if let Some(tx_idx) = self.tx_map.get(tx_ac) {
                    let tx_idx = *tx_idx as usize;
                    let tx = &self
                        .tx_seq_db
                        .tx_db
                        .as_ref()
                        .expect("no tx_db?")
                        .transcripts[tx_idx];

                    if let Some(genome_alignment) = tx.genome_alignments.first() {
                        Some(Ok(TxInfoRecord {
                            hgnc: tx.gene_id.clone(),
                            cds_start_i: tx.start_codon,
                            cds_end_i: tx.stop_codon,
                            tx_ac: tx.id.clone(),
                            alt_ac: genome_alignment.contig.to_string(),
                            alt_aln_method: "splign".into(),
                        }))
                    } else {
                        Some(Err(Error::NoAlignmentFound(
                            tx_ac.to_string(),
                            format!("{:?}", self.assembly()),
                        )))
                    }
                } else {
                    tracing::warn!("transcript ID not found {} for gene {}", tx_ac, gene);
                    None
                }
            })
            .collect::<Result<Vec<_>, _>>()
    }

    fn get_tx_for_region(
        &self,
        alt_ac: &str,
        _alt_aln_method: &str,
        start_i: i32,
        end_i: i32,
    ) -> Result<Vec<TxForRegionRecord>, Error> {
        let db_contig = self
            .contig_alias_map
            .get(alt_ac)
            .map(String::as_str)
            .unwrap_or(alt_ac);
        let contig_idx = match self.tx_trees.contig_to_idx.get(db_contig) {
            Some(idx) => *idx,
            None => return Ok(Vec::new()),
        };
        let query = start_i..end_i;
        let tx_idxs = self.tx_trees.trees[contig_idx].find(query);

        Ok(tx_idxs
            .iter()
            .map(|entry| {
                let tx = &self
                    .tx_seq_db
                    .tx_db
                    .as_ref()
                    .expect("no tx_db?")
                    .transcripts[*entry.data() as usize];
                assert_eq!(
                    tx.genome_alignments.len(),
                    1,
                    "Can only have one alignment in Mehari"
                );
                let alt_strand = tx.genome_alignments.first().unwrap().strand;
                TxForRegionRecord {
                    tx_ac: tx.id.clone(),
                    alt_ac: alt_ac.to_string(),
                    alt_strand: match Strand::try_from(alt_strand).expect("invalid strand") {
                        Strand::Plus => 1,
                        Strand::Minus => -1,
                        _ => unreachable!("invalid strand {}", alt_strand),
                    },
                    alt_aln_method: ALT_ALN_METHOD.to_string(),
                    start_i,
                    end_i,
                }
            })
            .collect())
    }

    fn get_tx_identity_info(&self, tx_ac: &str) -> Result<TxIdentityInfo, Error> {
        let tx_idx = *self
            .tx_map
            .get(tx_ac)
            .ok_or(Error::NoTranscriptFound(tx_ac.to_string()))?;
        let tx_idx = tx_idx as usize;
        let tx = &self
            .tx_seq_db
            .tx_db
            .as_ref()
            .expect("no tx_db?")
            .transcripts[tx_idx];
        let is_selenoprotein = tx.tags.contains(&(TranscriptTag::Selenoprotein as i32));

        let hgnc = tx.gene_id.clone();

        let mut tmp = tx
            .genome_alignments
            .first()
            .unwrap()
            .exons
            .iter()
            .map(|exon| {
                (
                    exon.ord,
                    exon.alt_cds_end_i
                        .map(|alt_cds_end_i| alt_cds_end_i + 1 - exon.alt_cds_start_i.unwrap())
                        .unwrap_or_default(),
                )
            })
            .collect::<Vec<(i32, i32)>>();
        tmp.sort();

        let is_mitochondrial = self
            .contig_manager
            .is_mitochondrial_alias(tx.genome_alignments.first().unwrap().contig.as_str());

        let lengths = tmp.into_iter().map(|(_, length)| length).collect();
        Ok(TxIdentityInfo {
            tx_ac: tx_ac.to_string(),
            alt_ac: tx_ac.to_string(), // sic(!)
            alt_aln_method: String::from("transcript"),
            cds_start_i: tx.start_codon,
            cds_end_i: tx.stop_codon,
            lengths,
            hgnc,
            translation_table: if is_mitochondrial {
                TranslationTable::VertebrateMitochondrial
            } else if is_selenoprotein {
                TranslationTable::Selenocysteine
            } else {
                TranslationTable::Standard
            },
        })
    }

    fn get_tx_info(
        &self,
        tx_ac: &str,
        alt_ac: &str,
        _alt_aln_method: &str,
    ) -> Result<TxInfoRecord, Error> {
        let db_contig = self
            .contig_alias_map
            .get(alt_ac)
            .map(String::as_str)
            .unwrap_or(alt_ac);
        let tx_idx = *self
            .tx_map
            .get(tx_ac)
            .ok_or(Error::NoTranscriptFound(tx_ac.to_string()))?;
        let tx_idx = tx_idx as usize;
        let tx = &self
            .tx_seq_db
            .tx_db
            .as_ref()
            .expect("no tx_db?")
            .transcripts[tx_idx];

        for genome_alignment in &tx.genome_alignments {
            if genome_alignment.contig == db_contig {
                return Ok(TxInfoRecord {
                    hgnc: tx.gene_id.clone(),
                    cds_start_i: tx.start_codon,
                    cds_end_i: tx.stop_codon,
                    tx_ac: tx.id.clone(),
                    alt_ac: alt_ac.to_string(),
                    alt_aln_method: ALT_ALN_METHOD.to_string(),
                });
            }
        }

        Err(Error::NoAlignmentFound(
            tx_ac.to_string(),
            alt_ac.to_string(),
        ))
    }

    fn get_tx_mapping_options(&self, tx_ac: &str) -> Result<Vec<TxMappingOptionsRecord>, Error> {
        let tx = self
            .get_tx(tx_ac)
            .ok_or_else(|| Error::NoTranscriptFound(tx_ac.to_string()))?;

        let current_build = self.assembly();

        let options = tx
            .genome_alignments
            .iter()
            .filter(|aln| aln.genome_build.eq_ignore_ascii_case(&current_build))
            .map(|aln| TxMappingOptionsRecord {
                tx_ac: tx_ac.to_string(),
                alt_ac: aln.contig.clone(),
                alt_aln_method: NCBI_ALN_METHOD.to_string(),
            })
            .collect::<Vec<_>>();

        if options.is_empty() {
            return Err(Error::NoAlignmentFound(tx_ac.to_string(), current_build));
        }

        Ok(options)
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn test_sync() {
        fn is_sync<T: Sync>() {}
        is_sync::<super::Provider>();
    }
}