-
Notifications
You must be signed in to change notification settings - Fork 117
/
Paralogues.pm
1362 lines (1133 loc) · 44.7 KB
/
Paralogues.pm
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
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2024] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=head1 CONTACT
Ensembl <http://www.ensembl.org/info/about/contact/index.html>
=cut
=head1 NAME
Paralogues
=head1 SYNOPSIS
mv Paralogues.pm ~/.vep/Plugins
# Find paralogue regions of all input variants using Ensembl paralogue annotation
# (automatically created if not in current directory) and fetch variants within
# those regions from VEP cache and whose clinical significance partially
# matches 'pathogenic'
./vep -i variations.vcf --cache --plugin Paralogues
# Find paralogue regions of input variants using Ensembl paralogue annotation
# (automatically created if not in current directory) and fetch variants within
# those regions from a custom VCF file (regardless of their clinical significance)
./vep -i variations.vcf --cache --plugin Paralogues,vcf=/path/to/file.vcf,clnsig=ignore
# Same using a custom VCF file but filtering for 'pathogenic' variants
./vep -i variations.vcf --cache --plugin Paralogues,vcf=/path/to/file.vcf,clnsig_col=CLNSIG
# Same but output different fields
./vep -i variations.vcf --cache --plugin Paralogues,vcf=/path/to/file.vcf.gz,clnsig_col=CLNSIG,fields=identifier:alleles:CLNSIG:CLNVI:GENEINFO
# Use a file with regions matched to paralogue variants -- fastest method;
# download 'matches' files from https://ftp.ensembl.org/pub/current_variation/Paralogues
./vep -i variations.vcf --cache --plugin Paralogues,matches=Paralogues.pm_homo_sapiens_113_GRCh38_clinvar_20240107.tsv.gz,clnsig=ignore
# Same using a 'matches' file but filtering for 'pathogenic' variants (default)
./vep -i variations.vcf --cache --plugin Paralogues,matches=Paralogues.pm_homo_sapiens_113_GRCh38_clinvar_20240107.tsv.gz
# Fetch all Ensembl variants in paralogue proteins using only the Ensembl API
# (requires database access)
./vep -i variations.vcf --database --plugin Paralogues,mode=remote,clnsig=ignore
=head1 DESCRIPTION
A VEP plugin that fetches variants overlapping the genomic coordinates of amino
acids aligned between paralogue proteins. This is useful to predict the
pathogenicity of variants in paralogue positions.
This plugin can determine paralogue regions for a variant based on:
1. Pre-computed matches between genomic regions and paralogue variants.
For this approach, either download the file calculated using ClinVar variants and respective TBI from
https://ftp.ensembl.org/pub/current_variation/Paralogues or create such matches file yourself. Details on how
to create such 'matches' file can be found below.
2. Ensembl paralogue annotation. These versatile annotations can look up
paralogue regions for all variants from any species with Ensembl
paralogues, but take longer to process.
After retrieving the paralogue regions, this plugin fetches variants
overlapping those regions from one of the following sources (by this order):
1. Custom VCF via the 'vcf' parameter
2. VEP cache (in cache/offline mode)
3. Ensembl API (in database mode)
To create a 'matches' file based on a custom set of variants, run VEP using
`--plugin Paralogues,regions=1,min_perc_cov=0,min_perc_pos=0,clnsig=ignore`
and the `--vcf` option. Afterwards, process the output of the VEP command:
`perl -e "use Paralogues; Paralogues::prepare_matches_file('variant_effect_output.txt')"`
Options are passed to the plugin as key=value pairs:
matches : Tabix-indexed TSV file with pre-computed matches between
genomic regions and paralogue variants (fastest method); this
option is incompatible with the `paralogues` and `vcf` options
dir : Directory with paralogue annotation (the annotation is created
in this folder if the paralogue annotation files do not exist)
paralogues : Tabix-indexed TSV file with paralogue annotation (if the file
does not exist, the annotation is automatically created); if
set to 'remote', the annotation is fetched but not stored
vcf : Tabix-indexed VCF file to fetch variant information (if not
used, variants are fetched from VEP cache in cache/offline
mode or Ensembl API in database mode)
fields : Colon-separated list of information from paralogue variants to
output (default: 'identifier:alleles:clinical_significance');
keyword 'all' can be used to print all fields; available
fields include 'identifier', 'chromosome', 'start', 'alleles',
'perc_cov', 'perc_pos', and 'clinical_significance' (if
`clnsig_col` is defined for custom VCF); additional fields
are available depending on variant source:
- VEP cache: 'end' and 'strand'
- Ensembl API: 'end', 'strand', 'source', 'consequence' and
'gene_symbol'
- Custom VCF: 'quality', 'filter' and name of INFO fields
- Matches file: check column names in file header
clnsig : Clinical significance term to filter variants (default:
'pathogenic'); use 'ignore' to fetch all paralogue variants,
regardless of clinical significance
clnsig_match : Type of match when filtering variants based on option
`clnsig`: 'partial' (default), 'exact' or 'regex'
clnsig_col : Column name containing clinical significance in custom VCF
(required with `vcf` option and if `clnsig` is not 'ignore')
min_perc_cov : Minimum alignment percentage of the peptide associated with
the input variant (default: 0)
min_perc_pos : Minimum percentage of positivity (similarity) between both
homologues (default: 50)
regions : Boolean value to return regions used to look up paralogue
variants (default: 1)
The tabix utility must be installed in your path to read the paralogue
annotation, the custom VCF file and the matches file.
=cut
package Paralogues;
@EXPORT_OK = qw(&process_data);
use strict;
use warnings;
use List::Util qw(any);
use File::Basename;
use Compress::Zlib;
use File::Spec;
use Bio::SimpleAlign;
use Bio::EnsEMBL::Utils::Sequence qw(reverse_comp);
use Bio::EnsEMBL::Variation::VariationFeature;
use Bio::EnsEMBL::Variation::Utils::Sequence qw(get_matched_variant_alleles);
use Bio::EnsEMBL::Variation::Utils::VariationEffect qw(overlap);
use Bio::EnsEMBL::IO::Parser::VCF4Tabix;
use Bio::EnsEMBL::Variation::Utils::BaseVepTabixPlugin;
use base qw(Bio::EnsEMBL::Variation::Utils::BaseVepTabixPlugin);
our @MATCHES_FIELDS = (
'identifier',
'chromosome',
'start',
'end',
'alleles',
'clinical_significance',
'perc_cov',
'perc_pos',
);
our @VCF_FIELDS = (
'identifier',
'chromosome',
'start',
'alleles',
'quality',
'filter',
'clinical_significance',
'perc_cov',
'perc_pos',
);
our @CACHE_FIELDS = (
'identifier',
'chromosome',
'start',
'end',
'strand',
'alleles',
'clinical_significance',
'perc_cov',
'perc_pos',
);
our @API_FIELDS = (
@CACHE_FIELDS,
'source',
'consequence',
'gene_symbol',
);
our @MATCHES_HEADER = qw/chr start end feature perc_cov perc_pos var_id var_chr var_start var_end var_ref var_alt var_feature/;
## FETCH VARIANTS --------------------------------------------------------------
=head2 _create_vf
Arg[1] : hash
Description: Create variant feature from a variant hash
Returntype : Bio::EnsEMBL::Variation::VariationFeature
Status : Experimental
=cut
sub _create_vf {
my ($self, $var) = @_;
my $slice = Bio::EnsEMBL::Slice->new(
-seq_region_name => $var->{chr},
-start => $var->{start},
-end => $var->{end},
-strand => $var->{strand},
);
my $vf = Bio::EnsEMBL::Variation::VariationFeature->new(
-variation_name => $var->{variation_name},
-seq_region_name => $var->{chr},
-start => $var->{start},
-end => $var->{end},
-slice => $slice,
-strand => $var->{strand},
-allele_string => $var->{allele_string},
-is_somatic => $var->{somatic},
-clinical_significance => $var->{clin_sig} ? [split /,/, $var->{clin_sig}] : []
);
return $vf;
}
=head2 _fetch_cache_vars
Arg[1] : $seq_region_name
Arg[2] : $start
Arg[3] : $end
Description: Fetch variant features within a given genomic region from VEP
cache; supports indexed (faster) and non-indexed (slower) cache
Returntype : arrayref of Bio::EnsEMBL::Variation::VariationFeature
Status : Experimental
=cut
sub _fetch_cache_vars {
my ($self, $chr, $start, $end) = @_;
my ($as, $variants);
if (defined($as = $self->_get_AnnotationSource('VariationTabix'))) {
# code based on AnnotationSource::Cache::VariationTabix
my $source_chr = $as->get_source_chr_name($chr);
my $tabix_obj = $as->_get_tabix_obj($source_chr);
return unless $tabix_obj;
my $iter = $tabix_obj->query(sprintf("%s:%i-%i", $source_chr, $start - 1, $end + 1));
return unless $iter;
while(my $line = $iter->next) {
chomp $line;
my $var = $as->parse_variation($line);
push @$variants, $self->_create_vf($var);
}
} elsif (defined($as = $self->_get_AnnotationSource('Variation'))) {
warn("Using non-indexed VEP cache is slow; for optimal performance, please use indexed VEP cache\n")
unless $self->{skip_slow_warning};
$self->{skip_slow_warning} = 1;
# code based on AnnotationSource::Cache::Variation and AnnotationSource
my $cache_region_size = $as->{cache_region_size};
my ($source_chr, $min, $max, $seen, @regions) = $as->get_regions_from_coords(
$chr, $start, $end, undef, $cache_region_size, $as->up_down_size());
for my $region (@regions) {
my ($c, $s) = @$region;
my $file = $as->get_dump_file_name(
$c,
($s * $cache_region_size) + 1,
($s + 1) * $cache_region_size
);
next unless -e $file;
my $gz = gzopen($file, 'rb');
my $line;
while($gz->gzreadline($line)) {
chomp $line;
# ignore non-overlapping variants
my $var = $as->parse_variation($line);
$var->{chr} = $c;
next unless overlap($start, $end, $var->{start}, $var->{end});
push @$variants, $self->_create_vf($var);
}
}
} else {
die "ERROR: could not get variants from VEP cache";
}
return $variants;
}
=head2 _fetch_database_vars
Arg[1] : $seq_region_name
Arg[2] : $start
Arg[3] : $end
Description: Fetch variant features within a given genomic region from Ensembl
database (requires database connection)
Returntype : arrayref of Bio::EnsEMBL::Variation::VariationFeature
Status : Experimental
=cut
sub _fetch_database_vars {
my ($self, $chr, $start, $end) = @_;
my $config = $self->{config};
my $reg = $config->{reg};
my $species = $config->{species};
$self->{slice_adaptor} ||= $reg->get_adaptor($species, 'core', 'slice');
$self->{vf_adaptor} ||= $reg->get_adaptor($species, 'variation', 'variationfeature');
my $slice = $self->{slice_adaptor}->fetch_by_region('chromosome', $chr, $start, $end);
next unless defined $slice;
return $self->{vf_adaptor}->fetch_all_by_Slice($slice);
}
=head2 _fetch_database_vars
Arg[1] : $seq_region_name
Arg[2] : $start
Arg[3] : $end
Description: Fetch variant features within a given genomic region from:
- VEP cache (indexed or non-indexed) if --cache is enabled
- Ensembl database if --database is enabled
Throws error if --cache and --database are not enabled
Returntype : arrayref of Bio::EnsEMBL::Variation::VariationFeature
Status : Experimental
=cut
sub fetch_variants {
my ($self, $chr, $start, $end) = @_;
my $variants;
if ($self->config->{cache}) {
$variants = $self->_fetch_cache_vars($chr, $start, $end);
} elsif ($self->config->{database}) {
$variants = $self->_fetch_database_vars($chr, $start, $end);
} else {
die("ERROR: cannot fetch variants from cache (no cache available?) neither from Ensembl API (database mode must be enabled)");
}
return $variants;
}
## GENERATE PARALOGUE ANNOTATION -----------------------------------------------
sub _prepare_filename {
my $self = shift;
my $config = $self->{config};
# Prepare file name based on species, database version and assembly
my $pkg = __PACKAGE__.'.pm';
my $species = $config->{species};
my $version = $config->{db_version} || 'Bio::EnsEMBL::Registry'->software_version;
my @name = ($pkg, $species, $version);
if( $species eq 'homo_sapiens' || $species eq 'human'){
my $assembly = $config->{assembly} || $config->{human_assembly};
die "specify assembly using --assembly [assembly]\n" unless defined $assembly;
push(@name, $assembly) if defined $assembly;
}
return join("_", @name) . ".tsv.gz";
}
sub _get_homology_adaptor {
my $self = shift;
my $config = $self->{config};
my $reg = $config->{reg};
if (!defined $self->{ha}) {
$self->{ha} = $reg->get_adaptor( "multi", "compara", "homology" );
}
if (!defined $self->{ha}) {
# reconnect to DB without species param
if ($config->{host}) {
$reg->load_registry_from_db(
-host => $config->{host},
-user => $config->{user},
-pass => $config->{password},
-port => $config->{port},
-db_version => $config->{db_version},
-no_cache => $config->{no_slice_cache},
);
}
$self->{ha} = $reg->get_adaptor( "multi", "compara", "homology" );
}
return $self->{ha};
}
sub _get_method_link_species_set_id {
my $ha = shift;
my $species = shift;
my $type = shift;
# Get ID corresponding to species and paralogues
my @query = qq/
SELECT method_link_species_set_id
FROM method_link_species_set
JOIN method_link USING (method_link_id)
JOIN species_set ss USING (species_set_id)
JOIN genome_db gdb ON ss.genome_db_id = gdb.genome_db_id
WHERE gdb.name = "$species" AND type = "$type";
/;
my $sth = $ha->db->dbc->prepare(@query, { mysql_use_result => 1 });
$sth->execute();
my $id = @{$sth->fetchrow_arrayref}[0];
$sth->finish();
return $id;
}
sub _write_paralogue_annotation {
my ($sth, $file) = @_;
# Open lock
my $lock = "$file\.lock";
open LOCK, ">$lock" or
die "ERROR: $file not found and cannot write to lock file $lock\n";
print LOCK "1\n";
close LOCK;
open OUT, " | bgzip -c > $file" or die "ERROR: cannot write to file $file\n";
# write header
my @header = qw(homology_id chr start end strand stable_id version
perc_cov perc_id perc_pos cigar_line
paralogue_chr paralogue_start paralogue_end paralogue_strand
paralogue_stable_id paralogue_version paralogue_cigar_line);
print OUT "#", join("\t", @header), "\n";
while (my $line = $sth->fetchrow_arrayref()) {
print OUT join("\t", @$line), "\n";
}
close OUT;
unlink($lock);
return $file;
}
sub _generate_paralogue_annotation {
my $self = shift;
my $file = shift;
my $config = $self->{config};
my $species = $config->{species};
my $reg = $config->{reg};
die("ERROR: Cannot generate paralogue annotation in offline mode\n") if $config->{offline};
die("ERROR: Cannot generate paralogue annotation in REST mode\n") if $config->{rest};
print "### Paralogues plugin: Querying Ensembl compara database (this may take a few minutes)\n" unless $config->{quiet};
my $mlss_id = _get_method_link_species_set_id($self->_get_homology_adaptor, $species, 'ENSEMBL_PARALOGUES');
# Create paralogue annotation
my @query = qq/
SELECT
hm.homology_id,
df.name AS chr,
sm.dnafrag_start AS start,
sm.dnafrag_end AS end,
sm.dnafrag_strand AS strand,
sm.stable_id,
sm.version,
hm.perc_cov,
hm.perc_id,
hm.perc_pos,
hm.cigar_line,
df2.name AS paralogue_chr,
sm2.dnafrag_start AS paralogue_start,
sm2.dnafrag_end AS paralogue_end,
sm2.dnafrag_strand AS paralogue_strand,
sm2.stable_id AS paralogue_id,
sm2.version AS paralogue_version,
hm2.cigar_line AS paralogue_cigar_line
-- Reference proteins
FROM homology_member hm
JOIN homology h USING (homology_id)
JOIN seq_member sm USING (seq_member_id)
JOIN dnafrag df USING (dnafrag_id)
-- Paralogue proteins
JOIN homology_member hm2 ON hm.homology_id = hm2.homology_id
JOIN seq_member sm2 ON hm2.seq_member_id = sm2.seq_member_id
JOIN dnafrag df2 ON sm2.dnafrag_id = df2.dnafrag_id
WHERE method_link_species_set_id = ${mlss_id} AND
sm.source_name = 'ENSEMBLPEP' AND
sm2.stable_id != sm.stable_id
ORDER BY df.name, sm.dnafrag_start, sm.dnafrag_end;
/;
my $sth = $self->{ha}->db->dbc->prepare(@query, { mysql_use_result => 1});
$sth->execute();
print "### Paralogues plugin: Writing to file\n" unless $config->{quiet};
_write_paralogue_annotation($sth, $file);
$sth->finish();
print "### Paralogues plugin: Creating tabix index\n" unless $config->{quiet};
system "tabix -s2 -b3 -e4 $file" and die "ERROR: tabix index creation failed\n";
print "### Paralogues plugin: file ready at $file\n" unless $config->{quiet};
return 1;
}
sub _get_database_homologies {
my $self = shift;
my $transcript = shift;
my $config = $self->{config};
my $species = $config->{species};
my $reg = $config->{reg};
$self->{ga} ||= $reg->get_adaptor($species, 'core', 'gene');
my $gene = $self->{ga}->fetch_by_stable_id( $transcript->{_gene_stable_id} );
my $homologies = $self->_get_homology_adaptor->fetch_all_by_Gene(
$gene, -METHOD_LINK_TYPE => 'ENSEMBL_PARALOGUES', -TARGET_SPECIES => $species);
return $homologies;
}
## RETRIEVE PARALOGUES FROM ANNOTATION -----------------------------------------
sub _compose_alignment_from_cigar {
my $seq = shift;
my $cigar = shift;
die "Unsupported characters found in CIGAR line: $cigar\n"
unless $cigar =~ /^[0-9MD]+$/;
my $aln_str = $seq;
my $index = 0;
while ($cigar =~ /(\d*)([MD])/g) {
my $num = $1 || 1;
my $letter = $2;
substr($aln_str, $index, 0) = '-' x $num if $letter =~ /D/;
$index += $num;
}
return $aln_str;
}
sub _create_SimpleAlign {
my ($self, $homology_id, $protein, $ref_cigar, $paralogue, $par_cigar,
$perc_cov, $perc_pos) = @_;
my $par = $paralogue->translation;
my $par_id = $par->stable_id;
my $par_seq = $par->seq;
my $ref_id = $protein->stable_id;
my $ref_seq = $protein->seq;
my $aln = Bio::SimpleAlign->new();
$aln->id($homology_id);
$aln->add_seq(Bio::LocatableSeq->new(
-SEQ => _compose_alignment_from_cigar($ref_seq, $ref_cigar),
-ALPHABET => 'protein',
-START => 1,
-END => length($ref_seq),
-ID => $ref_id,
-STRAND => 0
));
$aln->add_seq(Bio::LocatableSeq->new(
-SEQ => _compose_alignment_from_cigar($par_seq, $par_cigar),
-ALPHABET => 'protein',
-START => 1,
-END => length($par_seq),
-ID => $par_id,
-STRAND => 0
));
# add alignment stats
$aln->{_stats}->{ref_perc_cov} = $perc_cov;
$aln->{_stats}->{ref_perc_pos} = $perc_pos;
# add paralogue information to retrieve from cache later on
my $key = $par_id . '_info';
$aln->{$key}->{_chr} = $paralogue->seq_region_name;
$aln->{$key}->{_start} = $par->genomic_start;
$aln->{$key}->{_strand} = $paralogue->strand;
return $aln;
}
sub _get_paralogues {
my ($self, $vf, $translation) = @_;
my $var_chr = $vf->seq_region_name || $vf->{chr};
my $var_start = $vf->start - 2;
my $var_end = $vf->end;
# get translation info
my $translation_id = $translation->stable_id;
my $translation_seq = $translation->seq;
# get paralogues for this variant region
my $file = $self->{paralogues};
my @data = @{$self->get_data($var_chr, $var_start, $var_end, $file)};
my $paralogues = [];
for (@data) {
my (
$homology_id, $chr, $start, $end, $strand, $protein_id, $version,
$perc_cov, $perc_id, $perc_pos, $cigar,
$para_chr, $para_start, $para_end, $para_strand, $para_id, $para_version,
$para_cigar
) = split /\t/, $_;
next unless $translation_id eq $protein_id;
next unless $perc_cov >= $self->{min_perc_cov};
next unless $perc_pos >= $self->{min_perc_pos};
my $paralogue = $self->_get_transcript_from_translation(
$para_id, $para_chr, $para_start, $para_end);
my $aln = $self->_create_SimpleAlign($homology_id, $translation, $cigar,
$paralogue, $para_cigar,
$perc_cov, $perc_pos);
push @$paralogues, $aln;
}
return $paralogues;
}
sub _get_paralogue_coords {
my $self = shift;
my $tva = shift;
my $aln = shift;
my $translation_id = $tva->transcript->translation->stable_id;
my $translation_start = $tva->base_variation_feature_overlap->translation_start;
# avoid cases where $translation_start is located in stop codon
return unless $translation_start <= $tva->transcript->translation->length;
# identify paralogue protein
my @proteins = keys %{ $aln->{'_start_end_lists'} };
my $paralogue;
if ($translation_id eq $proteins[0]) {
$paralogue = $proteins[1];
} elsif ($translation_id eq $proteins[1]) {
$paralogue = $proteins[0];
} else {
return;
}
# get genomic coordinates for aligned residue in paralogue
my $col = $aln->column_from_residue_number($translation_id, $translation_start);
my $coords = $aln->get_seq_by_id($paralogue)->location_from_column($col);
return unless defined $coords and $coords->location_type eq 'EXACT';
my $tr_info = $aln->{$paralogue . '_info'};
my $tr_chr = $tr_info->{_chr} if defined $tr_info;
my $tr_genomic_start = $tr_info->{_start} if defined $tr_info;
my $tr_strand = $tr_info->{_strand} if defined $tr_info;
my $para_tr = $self->_get_transcript_from_translation(
$paralogue, $tr_chr, $tr_genomic_start, $tr_strand);
my ($para_coords) = $para_tr->pep2genomic($coords->start, $coords->start);
my $chr = $para_tr->seq_region_name;
my $start = $para_coords->start;
my $end = $para_coords->end;
my $transcript_id = $para_tr->stable_id || '';
return ($chr, $start, $end, $transcript_id);
}
## GET DATA FROM ANNOTATION ----------------------------------------------------
sub _get_config {
my $self = shift;
if (!defined $self->{config_obj}) {
$self->{config_obj} = Bio::EnsEMBL::VEP::Config->new( $self->{config} );
}
return $self->{config_obj};
}
sub _get_AnnotationSource {
my $self = shift;
my $filter = shift;
my %match = (
'Transcript' => 'Bio::EnsEMBL::VEP::AnnotationSource::Cache::Transcript',
'Variation' => 'Bio::EnsEMBL::VEP::AnnotationSource::Cache::Variation',
'VariationTabix' => 'Bio::EnsEMBL::VEP::AnnotationSource::Cache::VariationTabix',
);
if (!defined $self->{asa}) {
# Cache all annotation sources
my $cfg = $self->_get_config;
$cfg->{_params}->{check_existing} = 1; # enable to fetch variants from VEP cache
$self->{asa} = Bio::EnsEMBL::VEP::AnnotationSourceAdaptor->new({config => $cfg});
}
my $asa = $self->{asa};
if (defined $asa && $asa->can('get_all_from_cache')) {
for (@{$self->{asa}->get_all_from_cache}) {
return $_ if ref $_ eq $match{$filter};
}
}
return undef;
}
sub _get_transcript_from_translation {
my $self = shift;
my $protein_id = shift;
my $chr = shift;
my $start = shift;
my $strand = shift;
die "No protein identifier given\n" unless defined $protein_id;
return $self->{_cache}->{$protein_id} if $self->{_cache}->{$protein_id};
# try to get transcript from cache if enabled
if ($self->{config}->{cache} && defined $chr && defined $start && defined $strand) {
my $as = $self->_get_AnnotationSource('Transcript');
die "ERROR: could not get transcripts from VEP cache" unless defined $as;
my (@regions, $seen, $min_max, $min, $max);
my $cache_region_size = $as->{cache_region_size};
my $up_down_size = defined $as->{up_down_size} ? $as->{up_down_size} : $as->up_down_size;
($chr, $min, $max, $seen, @regions) = $as->get_regions_from_coords(
$chr, $start, $start, $min_max, $cache_region_size, $up_down_size, $seen);
foreach my $region (@regions) {
my ($chr, $range) = @$region;
my $file = $as->get_dump_file_name(
$chr,
($range * $cache_region_size) + 1,
($range + 1) * $cache_region_size
);
my @features = @{
$as->deserialized_obj_to_features( $as->deserialize_from_file($file) )
} if -e $file;
for my $transcript (@features) {
my $translation = $transcript->translation;
if ($translation && $translation->stable_id eq $protein_id) {
$self->{_cache}->{$protein_id} = $transcript;
return $transcript;
}
}
}
}
# get transcript from database if not returned yet
if ($self->{config}->{offline}) {
die "Translation $protein_id not cached; avoid using --offline to allow to connect to database\n";
}
my $config = $self->_get_config;
my $species = $config->species;
my $reg = $config->registry;
$self->{ta} ||= $reg->get_adaptor($species, 'core', 'translation');
my $transcript = $self->{ta}->fetch_by_stable_id($protein_id)->transcript;
$self->{_cache}->{$protein_id} = $transcript;
return $transcript;
}
## GET PARALOGUE VARIANTS BASED ON MATCHES OR ANNOTATION -----------------------
sub _get_paralogue_vars_from_matches {
my ($self, $tva) = @_;
my $vf = $tva->variation_feature;
my $allele = $tva->base_variation_feature->alt_alleles;
# get transcript for this feature (skip if not available)
return {} unless $tva->can('transcript');
my $feat = $tva->transcript->stable_id;
my $file = $self->{matches};
my $chr = $vf->{chr};
my ($start, $end) = $vf->{start} < $vf->{end} ?
($vf->{start}, $vf->{end}) :
($vf->{end}, $vf->{start});
# get paralogue variants for this region
my @data = @{$self->get_data($chr, $start, $end, $file)};
my $all_results = {};
foreach (@data) {
next unless $feat eq $_->{feature};
my $var = $_->{var};
$all_results = $self->_prepare_paralogue_vars_output(
$var->{chr}, $var->{start}, $var->{end}, $var->{feature},
$_->{perc_cov}, $_->{perc_pos}, [ $var ], $all_results);
}
return $all_results;
}
sub _get_paralogue_vars_from_annotation {
my ($self, $tva) = @_;
my $vf = $tva->variation_feature;
my $homologies = [];
if ($self->{remote}) {
$homologies = $self->_get_database_homologies($tva->transcript);
} else {
my $translation = $tva->transcript->translation;
$homologies = $self->{_cache_homologies}->{$translation->stable_id} ||=
$self->_get_paralogues($vf, $translation);
}
return {} unless @$homologies;
my $all_results = {};
for my $aln (@$homologies) {
my ($perc_cov, $perc_pos);
if ($aln->isa('Bio::EnsEMBL::Compara::Homology')) {
my $ref = $aln->get_all_Members->[0];
$perc_cov = $ref->perc_cov;
$perc_pos = $ref->perc_pos;
$aln = $aln->get_SimpleAlign;
} elsif ($aln->isa('Bio::SimpleAlign')) {
$perc_cov = $aln->{_stats}->{ref_perc_cov};
$perc_pos = $aln->{_stats}->{ref_perc_pos};
} else {
next;
}
my ($chr, $start, $end, $transcript_id) = $self->_get_paralogue_coords($tva, $aln);
next unless defined $chr and defined $start and defined $end;
my $variants;
if (defined $self->{vcf}) {
# get variants from custom VCF file
$variants = $self->get_data($chr, $start, $end, $self->{vcf});
} else {
# get Ensembl variants from mapped genomic coordinates
$variants = $self->fetch_variants($chr, $start, $end);
}
$all_results = $self->_prepare_paralogue_vars_output(
$chr, $start, $end, $transcript_id, $perc_cov, $perc_pos,
$variants, $all_results);
}
return $all_results;
}
sub _prepare_paralogue_vars_output {
my ($self, $chr, $start, $end, $transcript_id, $perc_cov, $perc_pos,
$variants, $all_results) = @_;
my $is_rest = $self->{config}->{output_format} eq 'json' || $self->{config}->{rest};
foreach my $var (@$variants) {
# check clinical significance (if set)
my $cln_sig = $var->{clinical_significance};
$cln_sig = [ $cln_sig ] if defined $self->{vcf} or defined $self->{matches};
next unless $self->_is_clinically_significant($cln_sig);
my $FUN = (defined $self->{matches} or defined $self->{vcf}) ?
'_prepare_vcf_info' : '_summarise_vf';
my $res = $self->$FUN($var, $perc_cov, $perc_pos);
if ($is_rest) {
my %res_hash;
@res_hash{ @{$self->{fields}} } = @{$res};
$res = \%res_hash;
} else {
$res = join(':', @{$res});
}
$all_results = $self->_join_results($all_results, { PARALOGUE_VARIANTS => $res });
}
if ($self->{regions}) {
my @keys = qw/chromosome start end transcript_id perc_cov perc_pos/;
my @values = ($chr, $start, $end, $transcript_id, $perc_cov, $perc_pos);
my $regions;
if ($is_rest) {
my %regions_hash;
@regions_hash{@keys} = @values;
$regions = \%regions_hash;
} else {
$regions = join(':', @values);
}
$all_results = $self->_join_results($all_results, { PARALOGUE_REGIONS => $regions });
}
return $all_results;
}
## PLUGIN ----------------------------------------------------------------------
sub _get_valid_fields {
my $selected = shift;
my $available = shift;
# return all available fields when using 'all'
return $available if $selected eq 'all';
my @fields = split(/:/, $selected);
# check if the selected fields exist
my @valid;
my @invalid;
for my $field (@fields) {
if ( grep { $_ eq $field } @$available ) {
push(@valid, $field);
} else {
push(@invalid, $field);
}
}
die "ERROR: all fields given are invalid. Available fields are:\n" .
join(", ", @$available)."\n" unless @valid;
warn "Paralogues plugin: WARNING: the following fields are not valid and were ignored: ",
join(", ", @invalid), "\n" if @invalid;
return \@valid;
}
sub _validate_matches_file {
my ($self, $params) = @_;
die "ERROR: options 'matches' and 'paralogues' are incompatible\n"
if defined $params->{paralogues};
die "ERROR: options 'matches' and 'vcf' are incompatible\n"
if defined $params->{vcf};
die "ERROR: 'matches=$self->{matches}': file not found\n"
unless -e $self->{matches};
die "ERROR: 'matches=$self->{matches}': respective TBI file not found\n"
unless -e $self->{matches} . ".tbi" || -e $self->{matches} . ".csi";
return $self;
}
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
$self->expand_left(0);
$self->expand_right(0);
$self->get_user_params();
my $params = $self->params_to_hash();
my $config = $self->{config};
# Thresholds for minimum percentage of homology similarity and coverage
$self->{min_perc_cov} = defined $params->{min_perc_cov} ? $params->{min_perc_cov} : 0;
$self->{min_perc_pos} = defined $params->{min_perc_pos} ? $params->{min_perc_pos} : 50;
$self->{regions} = defined $params->{regions} ? $params->{regions} : 1;
# Prepare clinical significance parameters
my $no_clnsig = defined $params->{clnsig} && $params->{clnsig} eq 'ignore';
$self->{clnsig_term} = $params->{clnsig} || 'pathogenic' unless $no_clnsig;
if (defined $self->{clnsig_term}) {
$self->{clnsig_match} = $params->{clnsig_match} || 'partial';
die "ERROR: clnsig_match only accepts 'exact', 'partial' or 'regex'\n"
unless grep { $self->{clnsig_match} eq $_ } ('exact', 'partial', 'regex');
}
# Check information to retrieve from paralogue variants
my $vcf = $params->{vcf};
my @fields= ('identifier', 'alleles', 'clinical_significance'); # default
if (defined $params->{matches}) {
# File with matches between variants and their paralogues regions
my $file = $params->{matches};
$self->{matches} = $file;
$self->{clnsig_col} ||= 'CLNSIG';
$self->add_file($file);
$self->_validate_matches_file($params);
# Read column names from matches file
$self->{matches_col} = `tabix -H ${file}` or die $!;
chomp $self->{matches_col};
$self->{matches_col} = [ split /\t/, $self->{matches_col} ];
# Remove basic columns from user-selectable columns
for my $elem (@MATCHES_HEADER) {
$elem = '#' . $elem if $elem eq 'chr'; # Add hash to first column name
$self->{matches_col} = [ grep { $elem ne $_ } @{ $self->{matches_col} } ];
}
my $valid_fields = [ @MATCHES_FIELDS, @{$self->{matches_col}} ];
@fields = @{ _get_valid_fields($params->{fields}, $valid_fields) }
if defined $params->{fields};;
} elsif (defined $vcf) {
$self->{vcf} = $vcf;
$self->add_file($vcf);
# get INFO fields names from VCF
my $vcf_file = Bio::EnsEMBL::IO::Parser::VCF4Tabix->open($vcf);
my $info = $vcf_file->get_metadata_by_pragma('INFO');
my $info_ids = [ map { $_->{ID} } @$info ];
@fields = @{ _get_valid_fields($params->{fields}, [@VCF_FIELDS, @$info_ids]) }
if defined $params->{fields};
# check if clinical significance column exists
if (defined $self->{clnsig_term} || defined $params->{clnsig_col}) {
$self->{clnsig_col} = $params->{clnsig_col};
die "ERROR: clnsig_col must be set when using a custom VCF unless clnsig=ignore\n"
unless defined $self->{clnsig_col} or $no_clnsig;
my $filename = basename $vcf;
die "ERROR: clnsig_col $self->{clnsig_col} not found in $filename. Available INFO fields are:\n" .
join(", ", @$info_ids)."\n" unless grep { $self->{clnsig_col} eq $_ } @$info_ids;
}
# warn if trying to return clinical significance when the user does not input its VCF field
warn("WARNING: clnsig_col not defined; clinical significance of paralogue variants will be empty\n")