-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvariant-effect-report.py
3415 lines (2829 loc) · 143 KB
/
variant-effect-report.py
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
#!/usr/bin/env python3
"""
GFA Variant Effect Analyzer
Analyzes variants in GFA files with sample haplotype information and reports their effects
on genomic features defined in GFF3 files.
Usage:
python gfa_variant_analyzer.py out.gfa test.gff3 --output variant_report.txt
"""
import argparse
import sys
import os
import logging
import time
import re
from collections import defaultdict, Counter
from Bio import SeqIO
from Bio.Seq import Seq
from Bio import pairwise2
from Bio import Align
import json
import rdflib
from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef, XSD
from rdflib.namespace import FOAF, RDFS, SKOS
import uuid
from datetime import datetime
# Define namespaces for genomic data and sequence features
class GenomicNamespaces:
"""Provides standard namespaces for genomic data in RDF."""
def __init__(self, base_uri="http://example.org/genomics/"):
# Base namespace for our data
self.base = Namespace(base_uri)
# Standard ontologies
self.rdf = RDF
self.rdfs = RDFS
self.xsd = XSD
self.skos = SKOS
# Genomic ontologies
self.faldo = Namespace("http://biohackathon.org/resource/faldo#")
self.so = Namespace("http://purl.obolibrary.org/obo/SO_") # Sequence Ontology
self.obo = Namespace("http://purl.obolibrary.org/obo/")
self.dc = Namespace("http://purl.org/dc/terms/")
self.sio = Namespace("http://semanticscience.org/resource/") # Semantic Science Integrated Ontology
self.gff = Namespace("http://www.sequenceontology.org/gff3/1.0/") # GFF3 terms
# VCF/Variant specific terms
self.variant = Namespace(f"{base_uri}variant/")
self.sample = Namespace(f"{base_uri}sample/")
self.feature = Namespace(f"{base_uri}feature/")
self.effect = Namespace(f"{base_uri}effect/")
self.position = Namespace(f"{base_uri}position/")
def bind_to_graph(self, g):
"""Bind all namespaces to a graph."""
g.bind("rdf", self.rdf)
g.bind("rdfs", self.rdfs)
g.bind("xsd", self.xsd)
g.bind("skos", self.skos)
g.bind("faldo", self.faldo)
g.bind("so", self.so)
g.bind("obo", self.obo)
g.bind("dc", self.dc)
g.bind("sio", self.sio)
g.bind("gff", self.gff)
g.bind("variant", self.variant)
g.bind("sample", self.sample)
g.bind("feature", self.feature)
g.bind("effect", self.effect)
g.bind("position", self.position)
g.bind("base", self.base)
def get_so_term(self, variant_type):
"""Map variant types to Sequence Ontology terms."""
# Map common variant types to SO terms
so_mapping = {
"SNP": "0001483", # SNV - single nucleotide variant
"SNV": "0001483", # SNV - single nucleotide variant
"DEL": "0000159", # deletion
"INS": "0000667", # insertion
"INV": "1000036", # inversion
"DUP": "1000035", # duplication
"UNKNOWN": "0001059" # sequence_alteration
}
# Return the mapped SO term or the default term for unknown types
return self.so[so_mapping.get(variant_type, "0001059")]
def get_effect_term(self, effect_type):
"""Map effect types to Sequence Ontology terms."""
# Map effect types to SO terms
effect_mapping = {
"no_change": "0000992", # silent_mutation
"amino_acid_change": "0001583", # missense_variant
"frame_shift": "0001589", # frameshift_variant
"in_frame_change": "0001650", # inframe_variant
"premature_stop_codon": "0001587", # stop_gained
"start_codon_disruption": "0002012", # start_lost
"promoter_affected": "0001566", # regulatory_region_variant
"terminator_affected": "0001566", # regulatory_region_variant
"splicing_affected": "0001568", # splicing_variant
"length_change": "0001059", # sequence_alteration
"sequence_change": "0001059", # sequence_alteration
"compound_heterozygous": "0001034" # compound_heterozygous
}
# Return the mapped SO term or a generic term for unknown effects
return self.so[effect_mapping.get(effect_type, "0001564")] # gene_variant as default
def create_rdf_variant_report(variants, features, feature_effects=None, sample_name=None, sample_effects=None, base_uri="http://example.org/genomics/"):
"""
Create an RDF graph of variant effects.
Args:
variants: List of variant dictionaries
features: List of feature dictionaries
feature_effects: List of feature effect dictionaries (optional)
sample_name: Name of the sample being analyzed (optional)
sample_effects: Dictionary of sample-specific effects (optional)
base_uri: Base URI for the RDF graph
Returns:
RDF graph object
"""
# Initialize graph and namespaces
g = Graph()
ns = GenomicNamespaces(base_uri)
ns.bind_to_graph(g)
# Create report node
report_id = str(uuid.uuid4())
report_uri = URIRef(f"{base_uri}report/{report_id}")
g.add((report_uri, RDF.type, ns.sio["SequenceVariantAnalysisReport"]))
g.add((report_uri, ns.dc.created, Literal(datetime.now().isoformat(), datatype=XSD.dateTime)))
# Add sample information if available
if sample_name:
sample_uri = URIRef(f"{ns.sample}{sample_name.replace(' ', '_')}")
g.add((sample_uri, RDF.type, ns.sio.Sample))
g.add((sample_uri, RDFS.label, Literal(sample_name)))
g.add((report_uri, ns.sio.refersTo, sample_uri))
# Process variants
for variant in variants:
var_id = variant.get('id', f"unknown_{str(uuid.uuid4())}")
var_type = variant.get('type', 'UNKNOWN')
# Create variant node
var_uri = URIRef(f"{ns.variant}{var_id}")
g.add((var_uri, RDF.type, ns.so.sequence_variant))
g.add((var_uri, RDFS.label, Literal(var_id)))
g.add((var_uri, ns.variant.variantType, ns.get_so_term(var_type)))
g.add((var_uri, ns.variant.lengthChange, Literal(variant.get('length_change', 0), datatype=XSD.integer)))
# Add variant to report
g.add((report_uri, ns.variant.hasVariant, var_uri))
# Add position information if available
if 'pos' in variant and variant.get('pos', 0) > 0:
pos_uri = URIRef(f"{ns.position}{var_id}")
g.add((pos_uri, RDF.type, ns.faldo.Region))
g.add((var_uri, ns.faldo.location, pos_uri))
# Add start position
start_uri = URIRef(f"{ns.position}{var_id}_start")
g.add((start_uri, RDF.type, ns.faldo.ExactPosition))
g.add((start_uri, ns.faldo.position, Literal(variant.get('pos', 0), datatype=XSD.integer)))
g.add((pos_uri, ns.faldo.begin, start_uri))
# Add end position
end_uri = URIRef(f"{ns.position}{var_id}_end")
g.add((end_uri, RDF.type, ns.faldo.ExactPosition))
g.add((end_uri, ns.faldo.position, Literal(variant.get('end', variant.get('pos', 0)), datatype=XSD.integer)))
g.add((pos_uri, ns.faldo.end, end_uri))
# Add affected segments
if 'segments' in variant and variant['segments']:
for seg_id in variant['segments']:
seg_uri = URIRef(f"{ns.base}segment/{seg_id}")
g.add((seg_uri, RDF.type, ns.base.Segment))
g.add((seg_uri, RDFS.label, Literal(seg_id)))
g.add((var_uri, ns.variant.affectsSegment, seg_uri))
# Process features
for feature in features:
feature_id = feature['attributes'].get('ID', f"unknown_{str(uuid.uuid4())}")
feature_name = feature['attributes'].get('Name', feature_id)
feature_type = feature['type']
# Create feature node
feature_uri = URIRef(f"{ns.feature}{feature_id}")
g.add((feature_uri, RDF.type, URIRef(f"{ns.gff}{feature_type}")))
g.add((feature_uri, RDFS.label, Literal(feature_name)))
# Add feature to report
g.add((report_uri, ns.feature.hasFeature, feature_uri))
# Add location information
loc_uri = URIRef(f"{ns.position}feature_{feature_id}")
g.add((loc_uri, RDF.type, ns.faldo.Region))
g.add((feature_uri, ns.faldo.location, loc_uri))
# Add start position
start_uri = URIRef(f"{ns.position}feature_{feature_id}_start")
g.add((start_uri, RDF.type, ns.faldo.ExactPosition))
g.add((start_uri, ns.faldo.position, Literal(feature['start'], datatype=XSD.integer)))
g.add((loc_uri, ns.faldo.begin, start_uri))
# Add end position
end_uri = URIRef(f"{ns.position}feature_{feature_id}_end")
g.add((end_uri, RDF.type, ns.faldo.ExactPosition))
g.add((end_uri, ns.faldo.position, Literal(feature['end'], datatype=XSD.integer)))
g.add((loc_uri, ns.faldo.end, end_uri))
# Add strand information
if feature['strand'] == '+':
g.add((feature_uri, ns.faldo.strand, ns.faldo.ForwardStrand))
elif feature['strand'] == '-':
g.add((feature_uri, ns.faldo.strand, ns.faldo.ReverseStrand))
else:
g.add((feature_uri, ns.faldo.strand, ns.faldo.BothStrand))
# Process effects
# Use sample_effects if provided, otherwise use feature_effects
effects_to_process = []
if sample_name and sample_effects and not sample_effects.get('incomplete'):
effects_to_process.extend(sample_effects.get('homozygous', []))
effects_to_process.extend(sample_effects.get('heterozygous', []))
# Add compound heterozygous effects
if 'gene_compound_heterozygous' in sample_effects:
for comp_het in sample_effects['gene_compound_heterozygous']:
# Create a synthetic effect entry
comp_effect = {
'feature': comp_het['feature'],
'feature_type': 'gene',
'effects': ['compound_heterozygous'],
'variants': comp_het['variants'],
'zygosity': 'compound_heterozygous',
'details': comp_het['details']
}
effects_to_process.append(comp_effect)
# Add feature-level compound heterozygous effects
if 'feature_compound_heterozygous' in sample_effects:
for comp_het in sample_effects['feature_compound_heterozygous']:
# Create a synthetic effect entry
comp_effect = {
'feature': comp_het['feature'],
'feature_type': comp_het['feature_type'],
'effects': ['compound_heterozygous'],
'variants': comp_het['variants'],
'zygosity': 'compound_heterozygous',
'details': comp_het['details']
}
effects_to_process.append(comp_effect)
else:
effects_to_process = feature_effects if feature_effects else []
# Process each effect
for effect in effects_to_process:
if not effect.get('effects') or effect['effects'] == ['no_change']:
continue # Skip effects with no change
feature = effect['feature']
feature_id = feature['attributes'].get('ID', 'unknown')
feature_type = feature['type']
feature_uri = URIRef(f"{ns.feature}{feature_id}")
# For each effect type
for effect_type in effect['effects']:
if effect_type == 'no_change':
continue
effect_id = f"{feature_id}_{effect_type}_{str(uuid.uuid4())}"
effect_uri = URIRef(f"{ns.effect}{effect_id}")
# Create effect node
g.add((effect_uri, RDF.type, ns.effect.VariantEffect))
g.add((effect_uri, ns.effect.effectType, ns.get_effect_term(effect_type)))
g.add((effect_uri, ns.effect.affectsFeature, feature_uri))
# Add effect to report
g.add((report_uri, ns.effect.hasEffect, effect_uri))
# Add detailed description if available
if effect_type in effect.get('details', {}):
detail = effect['details'][effect_type]
if isinstance(detail, dict):
desc = ", ".join(f"{k}={v}" for k, v in detail.items())
elif isinstance(detail, list):
desc = ", ".join(str(d) for d in detail)
else:
desc = str(detail)
g.add((effect_uri, ns.dc.description, Literal(desc)))
# Add zygosity if available
if 'zygosity' in effect:
g.add((effect_uri, ns.variant.zygosity, Literal(effect['zygosity'])))
# Add sequence information
if 'ref_feature_seq' in effect and 'alt_feature_seq' in effect:
g.add((effect_uri, ns.variant.referenceSequence, Literal(effect['ref_feature_seq'])))
g.add((effect_uri, ns.variant.alternateSequence, Literal(effect['alt_feature_seq'])))
# Add variants causing this effect
if 'variants' in effect and effect['variants']:
for var in effect['variants']:
var_id = var.get('id', 'unknown')
var_uri = URIRef(f"{ns.variant}{var_id}")
g.add((effect_uri, ns.effect.causedBy, var_uri))
return g
def output_rdf_report(graph, output=None, format='turtle'):
"""
Output an RDF graph in the specified format.
Args:
graph: RDF graph object
output: Output file (default: stdout)
format: RDF serialization format (default: turtle)
Returns:
None
"""
# Map format names to rdflib serialization format names
format_map = {
'turtle': 'turtle',
'ttl': 'turtle',
'n3': 'n3',
'xml': 'xml',
'rdf': 'xml',
'rdfxml': 'xml',
'jsonld': 'json-ld',
'json-ld': 'json-ld',
'nt': 'nt',
'ntriples': 'nt'
}
# Get the serialization format
rdf_format = format_map.get(format.lower(), 'turtle')
# Output to file or stdout
if output:
graph.serialize(destination=output, format=rdf_format)
else:
# Serialize to string and print to stdout
output_str = graph.serialize(format=rdf_format)
sys.stdout.write(output_str.decode('utf-8') if isinstance(output_str, bytes) else output_str)
def create_consolidated_rdf_report(variants, features, samples, haplotypes, paths, segments,
feature_by_id, children_by_parent, base_uri="http://example.org/genomics/"):
"""
Create a consolidated RDF graph with variant effects for all samples.
Args:
variants: List of variant dictionaries
features: List of feature dictionaries
samples: Dictionary of sample names and their paths
haplotypes: Dictionary of samples and their haplotypes
paths: Dictionary of path names and their data
segments: Dictionary of segment names and their data
feature_by_id: Dictionary of features indexed by their ID
children_by_parent: Dictionary of child features indexed by parent ID
base_uri: Base URI for the RDF graph
Returns:
RDF graph object with all sample data
"""
# Initialize graph and namespaces
g = Graph()
ns = GenomicNamespaces(base_uri)
ns.bind_to_graph(g)
# Create report node
report_id = str(uuid.uuid4())
report_uri = URIRef(f"{base_uri}report/{report_id}")
g.add((report_uri, RDF.type, ns.sio["SequenceVariantAnalysisReport"]))
g.add((report_uri, ns.dc.created, Literal(datetime.now().isoformat(), datatype=XSD.dateTime)))
g.add((report_uri, RDFS.label, Literal("Consolidated Variant Effect Report")))
# Get reference path
ref_path_name = 'REF'
if ref_path_name in paths:
ref_path_segments = paths[ref_path_name]['segments']
ref_seq, _ = build_path_sequence(segments, ref_path_segments)
else:
logging.error("REF path not found in GFA")
return g
# Collect variant segments
variant_segments = {}
for seg_id, seg_data in segments.items():
if seg_data.get('variant_id'):
variant_segments[seg_id] = seg_data
# Process variants (just once for all samples)
processed_variants = {}
for variant in variants:
var_id = variant.get('id', f"unknown_{str(uuid.uuid4())}")
var_type = variant.get('type', 'UNKNOWN')
# Create variant node
var_uri = URIRef(f"{ns.variant}{var_id}")
g.add((var_uri, RDF.type, ns.so.sequence_variant))
g.add((var_uri, RDFS.label, Literal(var_id)))
g.add((var_uri, ns.variant.variantType, ns.get_so_term(var_type)))
g.add((var_uri, ns.variant.lengthChange, Literal(variant.get('length_change', 0), datatype=XSD.integer)))
# Add variant to report
g.add((report_uri, ns.variant.hasVariant, var_uri))
# Add position information if available
if 'pos' in variant and variant.get('pos', 0) > 0:
pos_uri = URIRef(f"{ns.position}{var_id}")
g.add((pos_uri, RDF.type, ns.faldo.Region))
g.add((var_uri, ns.faldo.location, pos_uri))
# Add start position
start_uri = URIRef(f"{ns.position}{var_id}_start")
g.add((start_uri, RDF.type, ns.faldo.ExactPosition))
g.add((start_uri, ns.faldo.position, Literal(variant.get('pos', 0), datatype=XSD.integer)))
g.add((pos_uri, ns.faldo.begin, start_uri))
# Add end position
end_uri = URIRef(f"{ns.position}{var_id}_end")
g.add((end_uri, RDF.type, ns.faldo.ExactPosition))
g.add((end_uri, ns.faldo.position, Literal(variant.get('end', variant.get('pos', 0)), datatype=XSD.integer)))
g.add((pos_uri, ns.faldo.end, end_uri))
# Add affected segments
if 'segments' in variant and variant['segments']:
for seg_id in variant['segments']:
seg_uri = URIRef(f"{ns.base}segment/{seg_id}")
g.add((seg_uri, RDF.type, ns.base.Segment))
g.add((seg_uri, RDFS.label, Literal(seg_id)))
g.add((var_uri, ns.variant.affectsSegment, seg_uri))
# Store the variant URI for later reference
processed_variants[var_id] = var_uri
# Process features (just once for all samples)
processed_features = {}
for feature in features:
feature_id = feature['attributes'].get('ID', f"unknown_{str(uuid.uuid4())}")
feature_name = feature['attributes'].get('Name', feature_id)
feature_type = feature['type']
# Create feature node
feature_uri = URIRef(f"{ns.feature}{feature_id}")
g.add((feature_uri, RDF.type, URIRef(f"{ns.gff}{feature_type}")))
g.add((feature_uri, RDFS.label, Literal(feature_name)))
# Add feature to report
g.add((report_uri, ns.feature.hasFeature, feature_uri))
# Add location information
loc_uri = URIRef(f"{ns.position}feature_{feature_id}")
g.add((loc_uri, RDF.type, ns.faldo.Region))
g.add((feature_uri, ns.faldo.location, loc_uri))
# Add start position
start_uri = URIRef(f"{ns.position}feature_{feature_id}_start")
g.add((start_uri, RDF.type, ns.faldo.ExactPosition))
g.add((start_uri, ns.faldo.position, Literal(feature['start'], datatype=XSD.integer)))
g.add((loc_uri, ns.faldo.begin, start_uri))
# Add end position
end_uri = URIRef(f"{ns.position}feature_{feature_id}_end")
g.add((end_uri, RDF.type, ns.faldo.ExactPosition))
g.add((end_uri, ns.faldo.position, Literal(feature['end'], datatype=XSD.integer)))
g.add((loc_uri, ns.faldo.end, end_uri))
# Add strand information
if feature['strand'] == '+':
g.add((feature_uri, ns.faldo.strand, ns.faldo.ForwardStrand))
elif feature['strand'] == '-':
g.add((feature_uri, ns.faldo.strand, ns.faldo.ReverseStrand))
else:
g.add((feature_uri, ns.faldo.strand, ns.faldo.BothStrand))
# Store the feature URI for later reference
processed_features[feature_id] = feature_uri
# Process each sample
for sample_name, sample_paths in samples.items():
logging.info(f"Adding sample {sample_name} to consolidated report")
# Create sample node
sample_uri = URIRef(f"{ns.sample}{sample_name.replace(' ', '_')}")
g.add((sample_uri, RDF.type, ns.sio.Sample))
g.add((sample_uri, RDFS.label, Literal(sample_name)))
g.add((report_uri, ns.sio.refersTo, sample_uri))
# Determine if we have phased haplotypes for this sample
sample_haplotypes = haplotypes.get(sample_name, {})
has_phased_haplotypes = len(sample_haplotypes) >= 2
if has_phased_haplotypes:
# Process each haplotype
feature_effects_by_haplotype = {}
for hap_name, path_name in sample_haplotypes.items():
# Create haplotype node
hap_uri = URIRef(f"{ns.sample}{sample_name.replace(' ', '_')}/haplotype/{hap_name.replace(' ', '_')}")
g.add((hap_uri, RDF.type, ns.base.Haplotype))
g.add((hap_uri, RDFS.label, Literal(f"{sample_name} - {hap_name}")))
g.add((sample_uri, ns.base.hasHaplotype, hap_uri))
# Build path sequence
path_segments = paths[path_name]['segments']
hap_seq, segment_offsets = build_path_sequence(segments, path_segments)
# Analyze differences
hap_effects = analyze_haplotype_differences(
ref_seq,
hap_seq,
features,
segment_offsets,
variant_segments,
segments
)
feature_effects_by_haplotype[hap_name] = hap_effects
# Analyze homozygous vs heterozygous effects
zygosity_effects = analyze_sample_haplotypes(
feature_effects_by_haplotype,
features,
feature_by_id,
children_by_parent
)
# Add effects to graph
effect_counter = 0
# Process homozygous effects
for effect in zygosity_effects.get('homozygous', []):
if not effect.get('effects') or effect['effects'] == ['no_change']:
continue # Skip effects with no change
feature = effect['feature']
feature_id = feature['attributes'].get('ID', 'unknown')
feature_uri = processed_features.get(feature_id)
if not feature_uri:
continue
# For each effect type
for effect_type in effect['effects']:
if effect_type == 'no_change':
continue
effect_counter += 1
effect_id = f"{sample_name}_{feature_id}_{effect_type}_{effect_counter}"
effect_uri = URIRef(f"{ns.effect}{effect_id}")
# Create effect node
g.add((effect_uri, RDF.type, ns.effect.VariantEffect))
g.add((effect_uri, ns.effect.effectType, ns.get_effect_term(effect_type)))
g.add((effect_uri, ns.effect.affectsFeature, feature_uri))
g.add((effect_uri, ns.variant.zygosity, Literal("homozygous")))
g.add((effect_uri, ns.effect.inSample, sample_uri))
# Add effect to report
g.add((report_uri, ns.effect.hasEffect, effect_uri))
# Add detailed description if available
if effect_type in effect.get('details', {}):
detail = effect['details'][effect_type]
if isinstance(detail, dict):
desc = ", ".join(f"{k}={v}" for k, v in detail.items())
elif isinstance(detail, list):
desc = ", ".join(str(d) for d in detail)
else:
desc = str(detail)
g.add((effect_uri, ns.dc.description, Literal(desc)))
# Add sequence information
if 'ref_feature_seq' in effect and 'alt_feature_seq' in effect:
g.add((effect_uri, ns.variant.referenceSequence, Literal(effect['ref_feature_seq'])))
g.add((effect_uri, ns.variant.alternateSequence, Literal(effect['alt_feature_seq'])))
# Add variants causing this effect
if 'variants' in effect and effect['variants']:
for var in effect['variants']:
var_id = var.get('id', 'unknown')
var_uri = processed_variants.get(var_id)
if var_uri:
g.add((effect_uri, ns.effect.causedBy, var_uri))
# Process heterozygous effects
for effect in zygosity_effects.get('heterozygous', []):
if not effect.get('effects') or effect['effects'] == ['no_change']:
continue # Skip effects with no change
feature = effect['feature']
feature_id = feature['attributes'].get('ID', 'unknown')
feature_uri = processed_features.get(feature_id)
if not feature_uri:
continue
# For each effect type
effect_list = effect.get('combined_effects', effect['effects'])
for effect_type in effect_list:
if effect_type == 'no_change':
continue
effect_counter += 1
effect_id = f"{sample_name}_{feature_id}_{effect_type}_{effect_counter}"
effect_uri = URIRef(f"{ns.effect}{effect_id}")
# Create effect node
g.add((effect_uri, RDF.type, ns.effect.VariantEffect))
g.add((effect_uri, ns.effect.effectType, ns.get_effect_term(effect_type)))
g.add((effect_uri, ns.effect.affectsFeature, feature_uri))
g.add((effect_uri, ns.variant.zygosity, Literal("heterozygous")))
g.add((effect_uri, ns.effect.inSample, sample_uri))
# Add effect to report
g.add((report_uri, ns.effect.hasEffect, effect_uri))
# Add detailed description if available
if effect_type in effect.get('details', {}):
detail = effect['details'][effect_type]
if isinstance(detail, dict):
desc = ", ".join(f"{k}={v}" for k, v in detail.items())
elif isinstance(detail, list):
desc = ", ".join(str(d) for d in detail)
else:
desc = str(detail)
g.add((effect_uri, ns.dc.description, Literal(desc)))
# Add sequence information
if 'ref_feature_seq' in effect and 'alt_feature_seq' in effect:
g.add((effect_uri, ns.variant.referenceSequence, Literal(effect['ref_feature_seq'])))
g.add((effect_uri, ns.variant.alternateSequence, Literal(effect['alt_feature_seq'])))
# Add variants causing this effect
if 'variants' in effect and effect['variants']:
for var in effect['variants']:
var_id = var.get('id', 'unknown')
var_uri = processed_variants.get(var_id)
if var_uri:
g.add((effect_uri, ns.effect.causedBy, var_uri))
# For heterozygous effects, add haplotype-specific information
if 'haplotype_effects' in effect:
for hap_name, hap_effect in effect['haplotype_effects'].items():
hap_uri = URIRef(f"{ns.sample}{sample_name.replace(' ', '_')}/haplotype/{hap_name.replace(' ', '_')}")
g.add((effect_uri, ns.effect.inHaplotype, hap_uri))
# Process compound heterozygous effects
if 'gene_compound_heterozygous' in zygosity_effects:
for comp_het in zygosity_effects['gene_compound_heterozygous']:
gene_id = comp_het.get('gene_id', 'unknown')
gene_uri = processed_features.get(gene_id)
if not gene_uri:
continue
effect_counter += 1
effect_id = f"{sample_name}_{gene_id}_compound_heterozygous_{effect_counter}"
effect_uri = URIRef(f"{ns.effect}{effect_id}")
# Create effect node
g.add((effect_uri, RDF.type, ns.effect.VariantEffect))
g.add((effect_uri, ns.effect.effectType, ns.get_effect_term('compound_heterozygous')))
g.add((effect_uri, ns.effect.affectsFeature, gene_uri))
g.add((effect_uri, ns.variant.zygosity, Literal("compound_heterozygous")))
g.add((effect_uri, ns.effect.inSample, sample_uri))
# Add effect to report
g.add((report_uri, ns.effect.hasEffect, effect_uri))
# Add description
g.add((effect_uri, ns.dc.description, Literal("Different variants affecting the same gene on different haplotypes")))
# Add variants by haplotype
for hap_name, hap_variants in comp_het.get('haplotype_variants', {}).items():
hap_uri = URIRef(f"{ns.sample}{sample_name.replace(' ', '_')}/haplotype/{hap_name.replace(' ', '_')}")
g.add((effect_uri, ns.effect.inHaplotype, hap_uri))
for var in hap_variants:
var_id = var.get('id', 'unknown')
var_uri = processed_variants.get(var_id)
if var_uri:
# Create a blank node for the haplotype-variant association
bnode = BNode()
g.add((bnode, RDF.type, ns.effect.HaplotypeVariantAssociation))
g.add((bnode, ns.effect.haplotype, hap_uri))
g.add((bnode, ns.effect.variant, var_uri))
g.add((effect_uri, ns.effect.variantInHaplotype, bnode))
# Process feature-level compound heterozygous effects
if 'feature_compound_heterozygous' in zygosity_effects:
for comp_het in zygosity_effects['feature_compound_heterozygous']:
feature_id = comp_het.get('feature_id', 'unknown')
feature_uri = processed_features.get(feature_id)
if not feature_uri:
continue
effect_counter += 1
effect_id = f"{sample_name}_{feature_id}_compound_heterozygous_{effect_counter}"
effect_uri = URIRef(f"{ns.effect}{effect_id}")
# Create effect node
g.add((effect_uri, RDF.type, ns.effect.VariantEffect))
g.add((effect_uri, ns.effect.effectType, ns.get_effect_term('compound_heterozygous')))
g.add((effect_uri, ns.effect.affectsFeature, feature_uri))
g.add((effect_uri, ns.variant.zygosity, Literal("compound_heterozygous")))
g.add((effect_uri, ns.effect.inSample, sample_uri))
# Add effect to report
g.add((report_uri, ns.effect.hasEffect, effect_uri))
# Add description
feature_type = comp_het.get('feature_type', 'feature')
g.add((effect_uri, ns.dc.description, Literal(f"Different variants affecting the same {feature_type} on different haplotypes")))
# Add variants by haplotype
for hap_name, hap_variants in comp_het.get('haplotype_variants', {}).items():
hap_uri = URIRef(f"{ns.sample}{sample_name.replace(' ', '_')}/haplotype/{hap_name.replace(' ', '_')}")
g.add((effect_uri, ns.effect.inHaplotype, hap_uri))
for var in hap_variants:
var_id = var.get('id', 'unknown')
var_uri = processed_variants.get(var_id)
if var_uri:
# Create a blank node for the haplotype-variant association
bnode = BNode()
g.add((bnode, RDF.type, ns.effect.HaplotypeVariantAssociation))
g.add((bnode, ns.effect.haplotype, hap_uri))
g.add((bnode, ns.effect.variant, var_uri))
g.add((effect_uri, ns.effect.variantInHaplotype, bnode))
else:
# Process single haplotype
path_name = sample_paths[0]
path_segments = paths[path_name]['segments']
# Build path sequence
alt_seq, segment_offsets = build_path_sequence(segments, path_segments)
# Analyze differences
feature_effects = analyze_haplotype_differences(
ref_seq,
alt_seq,
features,
segment_offsets,
variant_segments,
segments
)
# Add effects to graph
effect_counter = 0
for effect in feature_effects:
if not effect.get('effects') or effect['effects'] == ['no_change']:
continue # Skip effects with no change
feature = effect['feature']
feature_id = feature['attributes'].get('ID', 'unknown')
feature_uri = processed_features.get(feature_id)
if not feature_uri:
continue
# For each effect type
for effect_type in effect['effects']:
if effect_type == 'no_change':
continue
effect_counter += 1
effect_id = f"{sample_name}_{feature_id}_{effect_type}_{effect_counter}"
effect_uri = URIRef(f"{ns.effect}{effect_id}")
# Create effect node
g.add((effect_uri, RDF.type, ns.effect.VariantEffect))
g.add((effect_uri, ns.effect.effectType, ns.get_effect_term(effect_type)))
g.add((effect_uri, ns.effect.affectsFeature, feature_uri))
g.add((effect_uri, ns.effect.inSample, sample_uri))
# Add effect to report
g.add((report_uri, ns.effect.hasEffect, effect_uri))
# Add detailed description if available
if effect_type in effect.get('details', {}):
detail = effect['details'][effect_type]
if isinstance(detail, dict):
desc = ", ".join(f"{k}={v}" for k, v in detail.items())
elif isinstance(detail, list):
desc = ", ".join(str(d) for d in detail)
else:
desc = str(detail)
g.add((effect_uri, ns.dc.description, Literal(desc)))
# Add sequence information
if 'ref_feature_seq' in effect and 'alt_feature_seq' in effect:
g.add((effect_uri, ns.variant.referenceSequence, Literal(effect['ref_feature_seq'])))
g.add((effect_uri, ns.variant.alternateSequence, Literal(effect['alt_feature_seq'])))
# Add variants causing this effect
if 'variants' in effect and effect['variants']:
for var in effect['variants']:
var_id = var.get('id', 'unknown')
var_uri = processed_variants.get(var_id)
if var_uri:
g.add((effect_uri, ns.effect.causedBy, var_uri))
return g
def analyze_sequence_alignment(ref_seq, alt_seq, gap_open=-10, gap_extend=-0.5, match=2, mismatch=-1):
"""
Perform global sequence alignment to identify differences between reference and alternate sequences.
Uses Bio.Align.PairwiseAligner instead of the deprecated Bio.pairwise2
Args:
ref_seq: Reference sequence string
alt_seq: Alternate sequence string
gap_open: Gap opening penalty (default: -10)
gap_extend: Gap extension penalty (default: -0.5)
match: Match score (default: 2)
mismatch: Mismatch score (default: -1)
Returns:
Dictionary with alignment information and identified changes
"""
# Create aligner
aligner = Align.PairwiseAligner()
aligner.mode = 'global'
aligner.match_score = match
aligner.mismatch_score = mismatch
aligner.open_gap_score = gap_open
aligner.extend_gap_score = gap_extend
# Perform alignment
alignments = aligner.align(ref_seq, alt_seq)
# Get the best alignment
if not alignments:
return {
'alignment_score': 0,
'changes': 'complete_replacement',
'ref_aligned': ref_seq,
'alt_aligned': alt_seq,
'insertions': [],
'deletions': [],
'substitutions': [],
'inversions': [],
'length_change': len(alt_seq) - len(ref_seq)
}
best_alignment = alignments[0]
score = best_alignment.score
# Convert alignment to string representation
alignment_strings = str(best_alignment).split('\n')
# The alignment output format is:
# Line 0: reference sequence with gaps
# Line 1: alignment characters (| for match, space for mismatch)
# Line 2: query sequence with gaps
if len(alignment_strings) >= 3:
ref_aligned = alignment_strings[0]
alt_aligned = alignment_strings[2]
else:
# Fallback if alignment string format is different
ref_aligned = ref_seq
alt_aligned = alt_seq
# Identify changes from the alignment
changes = analyze_alignment_changes(ref_aligned, alt_aligned)
return {
'alignment_score': score,
'ref_aligned': ref_aligned,
'alt_aligned': alt_aligned,
'insertions': changes['insertions'],
'deletions': changes['deletions'],
'substitutions': changes['substitutions'],
'inversions': changes['inversions'],
'complex_regions': changes['complex_regions'],
'length_change': len(alt_seq) - len(ref_seq)
}
def analyze_alignment_changes(ref_aligned, alt_aligned):
"""
Analyze an alignment to identify mutations, insertions, deletions, and potential inversions.
Args:
ref_aligned: Reference sequence with alignment gaps
alt_aligned: Alternate sequence with alignment gaps
Returns:
Dictionary with lists of detected changes
"""
insertions = []
deletions = []
substitutions = []
complex_regions = []
# Find simple insertions, deletions, and substitutions
current_ins = None
current_del = None
for i in range(len(ref_aligned)):
ref_base = ref_aligned[i]
alt_base = alt_aligned[i]
if ref_base == '-' and alt_base != '-':
# Insertion in alternate sequence
if current_ins is None:
current_ins = {'start': i, 'sequence': alt_base}
else:
current_ins['sequence'] += alt_base
elif ref_base != '-' and alt_base == '-':
# Deletion in alternate sequence
if current_del is None:
current_del = {'start': i, 'sequence': ref_base}
else:
current_del['sequence'] += ref_base
elif ref_base != alt_base:
# Substitution
substitutions.append({'position': i, 'ref': ref_base, 'alt': alt_base})
# Close any open indels
if current_ins:
insertions.append(current_ins)
current_ins = None
if current_del:
deletions.append(current_del)
current_del = None
else:
# Matching position
# Close any open indels
if current_ins:
insertions.append(current_ins)
current_ins = None
if current_del:
deletions.append(current_del)
current_del = None
# Close any open indels at the end
if current_ins:
insertions.append(current_ins)
if current_del:
deletions.append(current_del)
# Look for potential inversions
inversions = detect_inversions(ref_aligned, alt_aligned)
# Identify complex regions (potential rearrangements)
complex_regions = identify_complex_regions(ref_aligned, alt_aligned)
return {
'insertions': insertions,
'deletions': deletions,
'substitutions': substitutions,
'inversions': inversions,
'complex_regions': complex_regions
}
def detect_inversions(ref_aligned, alt_aligned):
"""
Detect potential inversions by looking for regions where the alternate sequence
matches the reverse complement of the reference.
Args:
ref_aligned: Reference sequence with alignment gaps
alt_aligned: Alternate sequence with alignment gaps
Returns:
List of detected inversions
"""
inversions = []
# Strip gaps for sequence comparison
ref_seq = ref_aligned.replace('-', '')
alt_seq = alt_aligned.replace('-', '')
# Minimum inversion size to consider (to avoid random matches)
min_inversion_size = 10
# Look for potential inversions of various sizes