/
FeatureService.groovy
3616 lines (3241 loc) · 179 KB
/
FeatureService.groovy
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
package org.bbop.apollo
import grails.converters.JSON
import grails.transaction.Transactional
import org.bbop.apollo.alteration.SequenceAlterationInContext
import org.bbop.apollo.geneProduct.GeneProduct
import org.bbop.apollo.go.GoAnnotation
import org.bbop.apollo.gwt.shared.FeatureStringEnum
import org.bbop.apollo.history.FeatureOperation
import org.bbop.apollo.sequence.SequenceTranslationHandler
import org.bbop.apollo.sequence.Strand
import org.bbop.apollo.sequence.TranslationTable
import org.codehaus.groovy.grails.web.json.JSONArray
import org.codehaus.groovy.grails.web.json.JSONException
import org.codehaus.groovy.grails.web.json.JSONObject
import org.grails.plugins.metrics.groovy.Timed
import org.hibernate.FlushMode
@Transactional(readOnly = true)
class FeatureService {
def nameService
def configWrapperService
def featureService
def transcriptService
def exonService
def cdsService
def nonCanonicalSplitSiteService
def featureRelationshipService
def featurePropertyService
def sequenceService
def permissionService
def overlapperService
def organismService
def sessionFactory
def goAnnotationService
def geneProductService
def provenanceService
public static final String MANUALLY_ASSOCIATE_TRANSCRIPT_TO_GENE = "Manually associate transcript to gene"
public static final String MANUALLY_DISSOCIATE_TRANSCRIPT_FROM_GENE = "Manually dissociate transcript from gene"
public static final String MANUALLY_ASSOCIATE_FEATURE_TO_GENE = "Manually associate feature to gene"
public static final String MANUALLY_DISSOCIATE_FEATURE_FROM_GENE = "Manually dissociate feature from gene"
public static final def SINGLETON_FEATURE_TYPES = [RepeatRegion.cvTerm, TransposableElement.cvTerm, Terminator.cvTerm, ShineDalgarnoSequence.cvTerm]
public static final RNA_FEATURE_TYPES = [
MRNA.cvTerm, MiRNA.cvTerm, NcRNA.cvTerm, RRNA.cvTerm, SnRNA.cvTerm, SnoRNA.cvTerm,
TRNA.cvTerm, Transcript.cvTerm,
GuideRNA.cvTerm, RNaseMRPRNA.cvTerm, TelomeraseRNA.cvTerm, SrpRNA.cvTerm, LncRNA.cvTerm,
RNasePRNA.cvTerm, ScRNA.cvTerm, PiRNA.cvTerm, TmRNA.cvTerm, EnzymaticRNA.cvTerm,
]
public static final PSEUDOGENIC_FEATURE_TYPES = [Pseudogene.cvTerm, PseudogenicRegion.cvTerm, ProcessedPseudogene.cvTerm]
@Timed
@Transactional
FeatureLocation convertJSONToFeatureLocation(JSONObject jsonLocation, Sequence sequence, int defaultStrand = Strand.POSITIVE.value) throws JSONException {
FeatureLocation gsolLocation = new FeatureLocation()
if (jsonLocation.has(FeatureStringEnum.ID.value)) {
gsolLocation.setId(jsonLocation.getLong(FeatureStringEnum.ID.value))
}
gsolLocation.setFmin(jsonLocation.getInt(FeatureStringEnum.FMIN.value))
gsolLocation.setFmax(jsonLocation.getInt(FeatureStringEnum.FMAX.value))
if (jsonLocation.getInt(FeatureStringEnum.STRAND.value) == Strand.POSITIVE.value || jsonLocation.getInt(FeatureStringEnum.STRAND.value) == Strand.NEGATIVE.value) {
gsolLocation.setStrand(jsonLocation.getInt(FeatureStringEnum.STRAND.value))
} else {
gsolLocation.setStrand(defaultStrand)
}
gsolLocation.setSequence(sequence)
return gsolLocation
}
/** Get features that overlap a given location.
*
* @param location - FeatureLocation that the features overlap
* @param compareStrands - Whether to compare strands in overlap
* @return Collection of Feature objects that overlap the FeatureLocation
*/
Collection<Transcript> getOverlappingTranscripts(FeatureLocation location, boolean compareStrands = true) {
List<Transcript> transcriptList = new ArrayList<>()
List<Transcript> overlappingFeaturesList = getOverlappingFeatures(location, compareStrands)
for (Feature eachFeature : overlappingFeaturesList) {
Feature feature = Feature.get(eachFeature.id)
if (feature instanceof Transcript) {
transcriptList.add((Transcript) feature)
}
}
return transcriptList
}
/** Get features that overlap a given location.
*
* @param location - FeatureLocation that the features overlap
* @param compareStrands - Whether to compare strands in overlap
* @return Collection of Feature objects that overlap the FeatureLocation
*/
Collection<Feature> getOverlappingFeatures(FeatureLocation location, boolean compareStrands = true) {
if (compareStrands) {
//Feature.executeQuery("select distinct f from Feature f join f.featureLocations fl where fl.sequence = :sequence and fl.strand = :strand and ((fl.fmin <= :fmin and fl.fmax > :fmin) or (fl.fmin <= :fmax and fl.fmax >= :fmax ))",[fmin:location.fmin,fmax:location.fmax,strand:location.strand,sequence:location.sequence])
Feature.executeQuery("select distinct f from Feature f join f.featureLocations fl where fl.sequence = :sequence and fl.strand = :strand and ((fl.fmin <= :fmin and fl.fmax > :fmin) or (fl.fmin <= :fmax and fl.fmax >= :fmax) or (fl.fmin >= :fmin and fl.fmax <= :fmax))", [fmin: location.fmin, fmax: location.fmax, strand: location.strand, sequence: location.sequence])
} else {
//Feature.executeQuery("select distinct f from Feature f join f.featureLocations fl where fl.sequence = :sequence and ((fl.fmin <= :fmin and fl.fmax > :fmin) or (fl.fmin <= :fmax and fl.fmax >= :fmax ))",[fmin:location.fmin,fmax:location.fmax,sequence:location.sequence])
Feature.executeQuery("select distinct f from Feature f join f.featureLocations fl where fl.sequence = :sequence and ((fl.fmin <= :fmin and fl.fmax > :fmin) or (fl.fmin <= :fmax and fl.fmax >= :fmax) or (fl.fmin >= :fmin and fl.fmax <= :fmax))", [fmin: location.fmin, fmax: location.fmax, sequence: location.sequence])
}
}
/**
* See if there is overlapping sequence alteration for a range
*
* Case 1:
* - fmin / fmax on either side of alteration
*
* Case 2:
* - fmin / fmax both within the alteration
*
* Case 3:
* - fmin / fmax stradles min side of alteration
*
* Case 4:
* - fmin / fmax stradles max side of alteration
*
* @param sequence
* @param fmin Inclusive fmin
* @param fmax Exclusive fmax
* @return
*/
def getOverlappingSequenceAlterations(Sequence sequence, int fmin, int fmax) {
def alterations = Feature.executeQuery(
"SELECT DISTINCT sa FROM SequenceAlterationArtifact sa JOIN sa.featureLocations fl WHERE fl.sequence = :sequence AND ((fl.fmin <= :fmin AND fl.fmax > :fmin) OR (fl.fmin <= :fmax AND fl.fmax >= :fmax) OR (fl.fmin >= :fmin AND fl.fmax <= :fmax))",
[fmin: fmin, fmax: fmax, sequence: sequence]
)
if (alterations) {
for (a in alterations) {
log.debug "locations: ${a.fmin}->${a.fmax} for ${fmin}->${fmax}"
}
}
return alterations
}
@Transactional
void updateNewGsolFeatureAttributes(Feature gsolFeature, Sequence sequence = null) {
gsolFeature.setIsAnalysis(false)
gsolFeature.setIsObsolete(false)
if (sequence) {
gsolFeature.getFeatureLocations().iterator().next().sequence = sequence
}
// TODO: this may be a mistake, is different than the original code
// you are iterating through all of the children in order to set the SourceFeature and analysis
// for (FeatureRelationship fr : gsolFeature.getChildFeatureRelationships()) {
for (FeatureRelationship fr : gsolFeature.getParentFeatureRelationships()) {
updateNewGsolFeatureAttributes(fr.getChildFeature(), sequence)
}
}
@Transactional
def setOwner(Feature feature, User owner) {
if (owner && feature) {
log.debug "setting owner for feature ${feature} to ${owner}"
feature.addToOwners(owner)
} else {
log.warn "user ${owner} or feature ${feature} is null so not setting"
}
}
@Transactional
def addOwnersByString(def username, Feature... features) {
User owner = User.findByUsername(username as String)
if (owner && features) {
log.debug "setting owner for feature ${features} to ${owner}"
features.each {
it.addToOwners(owner)
}
} else {
log.warn "user ${owner} or feature ${features} is null so not setting"
}
}
/**
* From Gene.addTranscript
* @return
*/
@Timed
@Transactional
def generateTranscript(JSONObject jsonTranscript, Sequence sequence, boolean suppressHistory, boolean useCDS = configWrapperService.useCDS(), boolean useName = false) {
log.debug "jsonTranscript: ${jsonTranscript.toString()}"
Gene gene = jsonTranscript.has(FeatureStringEnum.PARENT_ID.value) ? (Gene) Feature.findByUniqueName(jsonTranscript.getString(FeatureStringEnum.PARENT_ID.value)) : null
Transcript transcript = null
boolean readThroughStopCodon = false
User owner = permissionService.getCurrentUser(jsonTranscript)
// if the gene is set, then don't process, just set the transcript for the found gene
if (gene) {
// Scenario I - if 'parent_id' attribute is given then find the gene
transcript = (Transcript) convertJSONToFeature(jsonTranscript, sequence)
if (transcript.getFmin() < 0 || transcript.getFmax() < 0) {
throw new AnnotationException("Feature cannot have negative coordinates")
}
setOwner(transcript, owner)
CDS cds = transcriptService.getCDS(transcript)
if (cds) {
readThroughStopCodon = cdsService.getStopCodonReadThrough(cds) ? true : false
}
if (!useCDS || cds == null) {
calculateCDS(transcript, readThroughStopCodon)
} else {
// if there are any sequence alterations that overlaps this transcript then
// recalculate the CDS to account for these changes
def sequenceAlterations = getSequenceAlterationsForFeature(transcript)
if (sequenceAlterations.size() > 0) {
calculateCDS(transcript)
}
}
addTranscriptToGene(gene, transcript)
nonCanonicalSplitSiteService.findNonCanonicalAcceptorDonorSpliceSites(transcript)
if (!suppressHistory) {
transcript.name = nameService.generateUniqueName(transcript)
}
// setting back the original name for transcript
if (useName && jsonTranscript.has(FeatureStringEnum.NAME.value)) {
transcript.name = jsonTranscript.get(FeatureStringEnum.NAME.value)
}
} else {
boolean createGeneFromJSON = false
if (jsonTranscript.containsKey(FeatureStringEnum.PARENT.value) && jsonTranscript.containsKey(FeatureStringEnum.PROPERTIES.value)) {
for (JSONObject property : jsonTranscript.getJSONArray(FeatureStringEnum.PROPERTIES.value)) {
if (property.containsKey(FeatureStringEnum.NAME.value)
&& property.get(FeatureStringEnum.NAME.value) == FeatureStringEnum.COMMENT.value
&& property.get(FeatureStringEnum.VALUE.value) == MANUALLY_DISSOCIATE_TRANSCRIPT_FROM_GENE) {
createGeneFromJSON = true
break
}
}
}
if (!createGeneFromJSON) {
log.debug "Gene from parent_id doesn't exist; trying to find overlapping isoform"
// Scenario II - find an overlapping isoform and if present, add current transcript to its gene
FeatureLocation featureLocation = convertJSONToFeatureLocation(jsonTranscript.getJSONObject(FeatureStringEnum.LOCATION.value), sequence)
Collection<Feature> overlappingFeatures = getOverlappingFeatures(featureLocation).findAll() {
it = Feature.get(it.id)
it instanceof Gene
}
log.debug "overlapping genes: ${overlappingFeatures.name}"
List<Feature> overlappingFeaturesToCheck = new ArrayList<Feature>()
overlappingFeatures.each {
if (!checkForComment(it, MANUALLY_ASSOCIATE_TRANSCRIPT_TO_GENE) && !checkForComment(it, MANUALLY_DISSOCIATE_TRANSCRIPT_FROM_GENE)) {
overlappingFeaturesToCheck.add(it)
}
}
for (Feature eachFeature : overlappingFeaturesToCheck) {
// get the proper object instead of its proxy, due to lazy loading
Feature feature = Feature.get(eachFeature.id)
log.debug "evaluating overlap of feature ${feature.name} of class ${feature.class.name}"
if (!gene && feature instanceof Gene && !(feature instanceof Pseudogene)) {
Gene tmpGene = (Gene) feature
log.debug "found an overlapping gene ${tmpGene}"
// removing name from transcript JSON since its naming will be based off of the overlapping gene
Transcript tmpTranscript
if (jsonTranscript.has(FeatureStringEnum.NAME.value)) {
String originalName = jsonTranscript.get(FeatureStringEnum.NAME.value)
jsonTranscript.remove(FeatureStringEnum.NAME.value)
tmpTranscript = (Transcript) convertJSONToFeature(jsonTranscript, sequence)
jsonTranscript.put(FeatureStringEnum.NAME.value, originalName)
updateNewGsolFeatureAttributes(tmpTranscript)
} else {
tmpTranscript = (Transcript) convertJSONToFeature(jsonTranscript, sequence)
updateNewGsolFeatureAttributes(tmpTranscript)
}
if (tmpTranscript.getFmin() < 0 || tmpTranscript.getFmax() < 0) {
throw new AnnotationException("Feature cannot have negative coordinates")
}
//this one is working, but was marked as needing improvement
setOwner(tmpTranscript, owner)
CDS cds = transcriptService.getCDS(tmpTranscript)
if (cds) {
readThroughStopCodon = cdsService.getStopCodonReadThrough(cds) ? true : false
}
if (!useCDS || cds == null) {
calculateCDS(tmpTranscript, readThroughStopCodon)
} else {
// if there are any sequence alterations that overlaps this transcript then
// recalculate the CDS to account for these changes
def sequenceAlterations = getSequenceAlterationsForFeature(tmpTranscript)
if (sequenceAlterations.size() > 0) {
calculateCDS(tmpTranscript)
}
}
if (!suppressHistory) {
tmpTranscript.name = nameService.generateUniqueName(tmpTranscript, tmpGene?.name)
}
// setting back the original name for transcript
if (useName && jsonTranscript.has(FeatureStringEnum.NAME.value)) {
tmpTranscript.name = jsonTranscript.get(FeatureStringEnum.NAME.value)
}
if (tmpTranscript && tmpGene && overlapperService.overlaps(tmpTranscript, tmpGene)) {
log.debug "There is an overlap, adding to an existing gene"
transcript = tmpTranscript
gene = tmpGene
addTranscriptToGene(gene, transcript)
nonCanonicalSplitSiteService.findNonCanonicalAcceptorDonorSpliceSites(transcript)
transcript.save()
if (jsonTranscript.has(FeatureStringEnum.PARENT.value)) {
// use metadata of incoming transcript's gene
JSONObject jsonGene = jsonTranscript.getJSONObject(FeatureStringEnum.PARENT.value)
if (jsonGene.has(FeatureStringEnum.DBXREFS.value)) {
// parse dbxrefs
JSONArray dbxrefs = jsonGene.getJSONArray(FeatureStringEnum.DBXREFS.value)
for (JSONObject dbxref : dbxrefs) {
String dbString = dbxref.get(FeatureStringEnum.DB.value).name
String accessionString = dbxref.get(FeatureStringEnum.ACCESSION.value)
// TODO: needs improvement
boolean exists = false
tmpGene.featureDBXrefs.each {
if (it.db.name == dbString && it.accession == accessionString) {
exists = true
}
}
if (!exists) {
addNonPrimaryDbxrefs(tmpGene, dbString, accessionString)
}
}
}
tmpGene.save()
if (jsonGene.has(FeatureStringEnum.PROPERTIES.value)) {
// parse properties
JSONArray featureProperties = jsonGene.getJSONArray(FeatureStringEnum.PROPERTIES.value)
for (JSONObject featureProperty : featureProperties) {
String tagString = featureProperty.get(FeatureStringEnum.TYPE.value).name
String valueString = featureProperty.get(FeatureStringEnum.VALUE.value)
// TODO: needs improvement
boolean exists = false
tmpGene.featureProperties.each {
if (it instanceof Comment) {
exists = true
} else if (it.tag == tagString && it.value == valueString) {
exists = true
}
}
if (!exists) {
if (tagString == FeatureStringEnum.COMMENT.value) {
// if FeatureProperty is a comment
featurePropertyService.addComment(tmpGene, valueString)
} else {
addNonReservedProperties(tmpGene, tagString, valueString)
}
}
}
}
tmpGene.save()
}
gene.save(insert: false, flush: true)
break
} else {
featureRelationshipService.deleteFeatureAndChildren(tmpTranscript)
log.debug "There is no overlap, we are going to return a NULL gene and a NULL transcript "
}
} else {
log.error "Feature is not an instance of a gene or is a pseudogene"
}
}
}
}
if (gene == null) {
log.debug "gene is null"
// Scenario III - create a de-novo gene
JSONObject jsonGene = new JSONObject()
if (jsonTranscript.has(FeatureStringEnum.PARENT.value)) {
// Scenario IIIa - use the 'parent' attribute, if provided, from transcript JSON
jsonGene = JSON.parse(jsonTranscript.getString(FeatureStringEnum.PARENT.value)) as JSONObject
jsonGene.put(FeatureStringEnum.CHILDREN.value, new JSONArray().put(jsonTranscript))
} else {
// Scenario IIIb - use the current mRNA's featurelocation for gene
jsonGene.put(FeatureStringEnum.CHILDREN.value, new JSONArray().put(jsonTranscript))
jsonGene.put(FeatureStringEnum.LOCATION.value, jsonTranscript.getJSONObject(FeatureStringEnum.LOCATION.value))
String cvTermString = FeatureStringEnum.GENE.value
jsonGene.put(FeatureStringEnum.TYPE.value, convertCVTermToJSON(FeatureStringEnum.CV.value, cvTermString))
}
String geneName = null
if (jsonGene.has(FeatureStringEnum.NAME.value)) {
geneName = jsonGene.get(FeatureStringEnum.NAME.value)
} else if (jsonTranscript.has(FeatureStringEnum.NAME.value)) {
geneName = jsonTranscript.getString(FeatureStringEnum.NAME.value)
} else {
// geneName = nameService.makeUniqueFeatureName(sequence.organism, sequence.name, new LetterPaddingStrategy(), false)
geneName = nameService.makeUniqueGeneName(sequence.organism, sequence.name, false)
}
if (!suppressHistory) {
// geneName = nameService.makeUniqueFeatureName(sequence.organism, geneName, new LetterPaddingStrategy(), true)
geneName = nameService.makeUniqueGeneName(sequence.organism, geneName, true)
}
// set back to the original gene name
if (jsonTranscript.has(FeatureStringEnum.GENE_NAME.value)) {
geneName = jsonTranscript.getString(FeatureStringEnum.GENE_NAME.value)
}
jsonGene.put(FeatureStringEnum.NAME.value, geneName)
gene = (Gene) convertJSONToFeature(jsonGene, sequence)
updateNewGsolFeatureAttributes(gene, sequence)
if (gene.getFmin() < 0 || gene.getFmax() < 0) {
throw new AnnotationException("Feature cannot have negative coordinates")
}
transcript = transcriptService.getTranscripts(gene).iterator().next()
CDS cds = transcriptService.getCDS(transcript)
if (cds) {
readThroughStopCodon = cdsService.getStopCodonReadThrough(cds) ? true : false
}
if (!useCDS || cds == null) {
calculateCDS(transcript, readThroughStopCodon)
} else {
// if there are any sequence alterations that overlaps this transcript then
// recalculate the CDS to account for these changes
def sequenceAlterations = getSequenceAlterationsForFeature(transcript)
if (sequenceAlterations.size() > 0) {
calculateCDS(transcript)
}
}
removeExonOverlapsAndAdjacenciesForFeature(gene)
if (!suppressHistory) {
transcript.name = nameService.generateUniqueName(transcript)
}
// set back the original transcript name
if (useName && jsonTranscript.has(FeatureStringEnum.NAME.value)) {
transcript.name = jsonTranscript.getString(FeatureStringEnum.NAME.value)
}
nonCanonicalSplitSiteService.findNonCanonicalAcceptorDonorSpliceSites(transcript)
gene.save(insert: true)
transcript.save(flush: true)
// doesn't work well for testing
setOwner(gene, owner)
setOwner(transcript, owner)
}
return transcript
}
// TODO: this is kind of a hack for now
JSONObject convertCVTermToJSON(String cv, String cvTerm) {
JSONObject jsonCVTerm = new JSONObject()
JSONObject jsonCV = new JSONObject()
jsonCVTerm.put(FeatureStringEnum.CV.value, jsonCV)
jsonCV.put(FeatureStringEnum.NAME.value, cv)
jsonCVTerm.put(FeatureStringEnum.NAME.value, cvTerm)
return jsonCVTerm
}
/**
* TODO: Should be the same result as the older method, need to check:
*
* if (transcript.getGene() != null) {return transcript.getGene();}return transcript;
* @param feature
* @return
*/
@Timed
Feature getTopLevelFeature(Feature feature) {
Collection<Feature> parents = feature?.childFeatureRelationships*.parentFeature
if (parents) {
return getTopLevelFeature(parents.iterator().next())
} else {
return feature
}
}
@Timed
@Transactional
def removeExonOverlapsAndAdjacenciesForFeature(Feature feature) {
if (feature instanceof Gene) {
for (Transcript transcript : transcriptService.getTranscripts((Gene) feature)) {
removeExonOverlapsAndAdjacencies(transcript)
}
} else if (feature instanceof Transcript) {
removeExonOverlapsAndAdjacencies((Transcript) feature)
}
}
@Transactional
def addTranscriptToGene(Gene gene, Transcript transcript) {
removeExonOverlapsAndAdjacencies(transcript)
// no feature location, set location to transcript's
if (gene.getFeatureLocation() == null) {
FeatureLocation transcriptFeatureLocation = transcript.getFeatureLocation()
FeatureLocation featureLocation = new FeatureLocation()
featureLocation.properties = transcriptFeatureLocation.properties
featureLocation.id = null
featureLocation.save()
gene.addToFeatureLocations(featureLocation)
} else {
// if the transcript's bounds are beyond the gene's bounds, need to adjust the gene's bounds
if (transcript.getFeatureLocation().getFmin() < gene.getFeatureLocation().getFmin()) {
gene.getFeatureLocation().setFmin(transcript.getFeatureLocation().getFmin())
}
if (transcript.getFeatureLocation().getFmax() > gene.getFeatureLocation().getFmax()) {
gene.getFeatureLocation().setFmax(transcript.getFeatureLocation().getFmax())
}
}
// add transcript
FeatureRelationship featureRelationship = new FeatureRelationship(
parentFeature: gene
, childFeature: transcript
).save(failOnError: true)
gene.addToParentFeatureRelationships(featureRelationship)
transcript.addToChildFeatureRelationships(featureRelationship)
updateGeneBoundaries(gene)
// getSession().indexFeature(transcript);
// event fire
// TODO: determine event model?
// fireAnnotationChangeEvent(transcript, gene, AnnotationChangeEvent.Operation.ADD);
}
/**
* TODO: this is an N^2 search of overlapping exons
* @param transcript
* @return
*/
@Transactional
def removeExonOverlapsAndAdjacencies(Transcript transcript) throws AnnotationException {
List<Exon> sortedExons = transcriptService.getSortedExons(transcript, false)
if (!sortedExons || sortedExons?.size() <= 1) {
return
}
Collections.sort(sortedExons, new FeaturePositionComparator<Exon>(false))
int inc = 1
for (int i = 0; i < sortedExons.size() - 1; i += inc) {
inc = 1
Exon leftExon = sortedExons.get(i)
for (int j = i + 1; j < sortedExons.size(); ++j) {
Exon rightExon = sortedExons.get(j)
if (overlapperService.overlaps(leftExon, rightExon) || isAdjacentTo(leftExon.getFeatureLocation(), rightExon.getFeatureLocation())) {
try {
exonService.mergeExons(leftExon, rightExon)
sortedExons = transcriptService.getSortedExons(transcript, false)
// we have to reload the sortedExons again and start over
++inc
} catch (AnnotationException e) {
// we should probably just re-throw this
log.error(e)
throw e
}
}
}
}
}
/** Checks whether this AbstractSimpleLocationBioFeature is adjacent to the FeatureLocation.
*
* @param location - FeatureLocation to check adjacency against
* @return true if there is adjacency
*/
boolean isAdjacentTo(FeatureLocation leftLocation, FeatureLocation location) {
return isAdjacentTo(leftLocation, location, true)
}
boolean isAdjacentTo(FeatureLocation leftFeatureLocation, FeatureLocation rightFeatureLocation, boolean compareStrands) {
if (leftFeatureLocation.sequence != rightFeatureLocation.sequence) {
return false
}
int thisFmin = leftFeatureLocation.getFmin()
int thisFmax = leftFeatureLocation.getFmax()
int thisStrand = leftFeatureLocation.getStrand()
int otherFmin = rightFeatureLocation.getFmin()
int otherFmax = rightFeatureLocation.getFmax()
int otherStrand = rightFeatureLocation.getStrand()
boolean strandsOverlap = compareStrands ? thisStrand == otherStrand : true
if (strandsOverlap &&
(thisFmax == otherFmin ||
thisFmin == otherFmax)) {
return true
}
return false
}
@Transactional
def calculateCDS(Transcript transcript) {
// NOTE: isPseudogene call seemed redundant with isProtenCoding
CDS cds = transcriptService.getCDS(transcript)
calculateCDS(transcript, cdsService.hasStopCodonReadThrough(cds))
// if (transcriptService.isProteinCoding(transcript) && (transcriptService.getGene(transcript) == null)) {
//// calculateCDS(editor, transcript, transcript.getCDS() != null ? transcript.getCDS().getStopCodonReadThrough() != null : false);
//// calculateCDS(transcript, transcript.getCDS() != null ? transcript.getCDS().getStopCodonReadThrough() != null : false);
// calculateCDS(transcript, transcriptService.getCDS(transcript) != null ? transcriptService.getStopCodonReadThrough(transcript) != null : false);
// }
}
@Timed
@Transactional
def calculateCDS(Transcript transcript, boolean readThroughStopCodon) {
CDS cds = transcriptService.getCDS(transcript)
log.info "calculateCDS"
if (cds == null) {
log.debug "CDS is null, so setting longest ORF"
setLongestORF(transcript, readThroughStopCodon)
return
}
log.debug "CDS found $cds, checking for manual start and end"
boolean manuallySetStart = cdsService.isManuallySetTranslationStart(cds)
boolean manuallySetEnd = cdsService.isManuallySetTranslationEnd(cds)
log.debug "CDS found $cds, manual start $manuallySetStart end $manuallySetEnd"
if (manuallySetStart && manuallySetEnd) {
return
}
if (!manuallySetStart && !manuallySetEnd) {
log.debug "neither start or end is set manually so calculating ORF"
setLongestORF(transcript, readThroughStopCodon)
} else if (manuallySetStart) {
setTranslationStart(transcript, cds.getFeatureLocation().getStrand().equals(-1) ? cds.getFmax() - 1 : cds.getFmin(), true, readThroughStopCodon)
} else {
setTranslationEnd(transcript, cds.getFeatureLocation().getStrand().equals(-1) ? cds.getFmin() : cds.getFmax() - 1, true)
}
}
/**
* Set the translation start in the transcript. Sets the translation start in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation start in
* @param translationStart - Coordinate of the start of translation
*/
@Transactional
void setTranslationStart(Transcript transcript, int translationStart) {
log.debug "setTranslationStart"
setTranslationStart(transcript, translationStart, false)
}
/**
* Set the translation start in the transcript. Sets the translation start in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation start in
* @param translationStart - Coordinate of the start of translation
* @param setTranslationEnd - if set to true, will search for the nearest in frame stop codon
*/
@Transactional
void setTranslationStart(Transcript transcript, int translationStart, boolean setTranslationEnd) throws AnnotationException {
log.debug "setTranslationStart(transcript,translationStart,translationEnd)"
setTranslationStart(transcript, translationStart, setTranslationEnd, false)
}
/**
* Set the translation start in the transcript. Sets the translation start in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation start in
* @param translationStart - Coordinate of the start of translation
* @param setTranslationEnd - if set to true, will search for the nearest in frame stop codon
* @param readThroughStopCodon - if set to true, will read through the first stop codon to the next
*/
@Transactional
void setTranslationStart(Transcript transcript, int translationStart, boolean setTranslationEnd, boolean readThroughStopCodon) throws AnnotationException {
log.debug "setTranslationStart(transcript,translationStart,translationEnd,readThroughStopCodon)"
setTranslationStart(transcript, translationStart, setTranslationEnd, setTranslationEnd ? organismService.getTranslationTable(transcript.featureLocation.sequence.organism) : null, readThroughStopCodon)
}
/** Convert local coordinate to source feature coordinate.
*
* @param localCoordinate - Coordinate to convert to source coordinate
* @return Source feature coordinate, -1 if local coordinate is longer than feature's length or negative
*/
int convertLocalCoordinateToSourceCoordinate(Feature feature, int localCoordinate) {
log.debug "convertLocalCoordinateToSourceCoordinate"
if (localCoordinate < 0 || localCoordinate > feature.getLength()) {
return -1
}
if (feature.getFeatureLocation().getStrand() == -1) {
return feature.getFeatureLocation().getFmax() - localCoordinate - 1
} else {
return feature.getFeatureLocation().getFmin() + localCoordinate
}
}
int convertLocalCoordinateToSourceCoordinateForTranscript(Transcript transcript, int localCoordinate) {
// Method converts localCoordinate to sourceCoordinate in reference to the Transcript
List<Exon> exons = transcriptService.getSortedExons(transcript, true)
int sourceCoordinate = -1
if (exons.size() == 0) {
return convertLocalCoordinateToSourceCoordinate(transcript, localCoordinate)
}
int currentLength = 0
int currentCoordinate = localCoordinate
for (Exon exon : exons) {
int exonLength = exon.getLength()
if (currentLength + exonLength >= localCoordinate) {
if (transcript.getFeatureLocation().getStrand() == Strand.NEGATIVE.value) {
sourceCoordinate = exon.getFeatureLocation().getFmax() - currentCoordinate - 1
} else {
sourceCoordinate = exon.getFeatureLocation().getFmin() + currentCoordinate
}
break
}
currentLength += exonLength
currentCoordinate -= exonLength
}
return sourceCoordinate
}
int convertLocalCoordinateToSourceCoordinateForCDS(CDS cds, int localCoordinate) {
// Method converts localCoordinate to sourceCoordinate in reference to the CDS
Transcript transcript = transcriptService.getTranscript(cds)
if (!transcript) {
return convertLocalCoordinateToSourceCoordinate(cds, localCoordinate)
}
int offset = 0
List<Exon> exons = transcriptService.getSortedExons(transcript, true)
if (exons.size() == 0) {
log.debug "FS::convertLocalCoordinateToSourceCoordinateForCDS() - No exons for given transcript"
return convertLocalCoordinateToSourceCoordinate(cds, localCoordinate)
}
if (transcript.strand == Strand.NEGATIVE.value) {
exons.reverse()
}
for (Exon exon : exons) {
if (!overlapperService.overlaps(cds, exon)) {
offset += exon.getLength()
continue
} else if (overlapperService.overlaps(cds, exon)) {
if (exon.fmin >= cds.fmin && exon.fmax <= cds.fmax) {
// exon falls within the boundaries of the CDS
continue
} else {
// exon doesn't overlap completely with the CDS
if (exon.fmin < cds.fmin && exon.strand == Strand.POSITIVE.value) {
offset += cds.fmin - exon.fmin
} else if (exon.fmax > cds.fmax && exon.strand == Strand.NEGATIVE.value) {
offset += exon.fmax - cds.fmax
}
}
}
if (exon.getFeatureLocation().getStrand() == Strand.NEGATIVE.value) {
offset += exon.getFeatureLocation().getFmax() - exon.getFeatureLocation().getFmax()
} else {
offset += exon.getFeatureLocation().getFmin() - exon.getFeatureLocation().getFmin()
}
break
}
return convertLocalCoordinateToSourceCoordinateForTranscript(transcript, localCoordinate + offset)
}
/**
* Set the translation start in the transcript. Sets the translation start in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation start in
* @param translationStart - Coordinate of the start of translation
* @param setTranslationEnd - if set to true, will search for the nearest in frame stop codon
* @param translationTable - Translation table that defines the codon translation
* @param readThroughStopCodon - if set to true, will read through the first stop codon to the next
*/
@Transactional
void setTranslationStart(Transcript transcript, int translationStart, boolean setTranslationEnd, TranslationTable translationTable, boolean readThroughStopCodon) throws AnnotationException {
CDS cds = transcriptService.getCDS(transcript)
if (cds == null) {
cds = transcriptService.createCDS(transcript)
featureRelationshipService.addChildFeature(transcript, cds)
// transcript.setCDS(cds);
}
// if the end is set, then we make sure we are going to set a legal coordinate
if (cdsService.isManuallySetTranslationEnd(cds)) {
if (transcript.strand == Strand.NEGATIVE.value) {
if (translationStart <= cds.featureLocation.fmin) {
throw new AnnotationException("Translation start ${translationStart} must be upstream of the end ${cds.featureLocation.fmin} (larger)")
}
} else {
if (translationStart >= cds.featureLocation.fmax) {
throw new AnnotationException("Translation start ${translationStart} must be upstream of the end ${cds.featureLocation.fmax} (smaller) ")
}
}
}
FeatureLocation transcriptFeatureLocation = FeatureLocation.findByFeature(transcript)
if (transcriptFeatureLocation.strand == Strand.NEGATIVE.value) {
setFmax(cds, translationStart + 1)
} else {
setFmin(cds, translationStart)
}
cdsService.setManuallySetTranslationStart(cds, true)
// cds.deleteStopCodonReadThrough();
cdsService.deleteStopCodonReadThrough(cds)
// featureRelationshipService.deleteRelationships()
if (setTranslationEnd && translationTable != null) {
String mrna = getResiduesWithAlterationsAndFrameshifts(transcript)
if (mrna == null || mrna.equals("null")) {
return
}
int stopCodonCount = 0
for (int i = convertSourceCoordinateToLocalCoordinateForTranscript(transcript, translationStart); i < transcript.getLength(); i += 3) {
if (i < 0 || i + 3 > mrna.length()) {
break
}
String codon = mrna.substring(i, i + 3)
if (translationTable.getStopCodons().contains(codon)) {
if (readThroughStopCodon && ++stopCodonCount < 2) {
// StopCodonReadThrough stopCodonReadThrough = cdsService.getStopCodonReadThrough(cds);
StopCodonReadThrough stopCodonReadThrough = (StopCodonReadThrough) featureRelationshipService.getChildForFeature(cds, StopCodonReadThrough.ontologyId)
if (stopCodonReadThrough == null) {
stopCodonReadThrough = cdsService.createStopCodonReadThrough(cds)
cdsService.setStopCodonReadThrough(cds, stopCodonReadThrough)
// cds.setStopCodonReadThrough(stopCodonReadThrough);
if (cds.strand == Strand.NEGATIVE.value) {
stopCodonReadThrough.featureLocation.setFmin(convertModifiedLocalCoordinateToSourceCoordinate(transcript, i + 2))
stopCodonReadThrough.featureLocation.setFmax(convertModifiedLocalCoordinateToSourceCoordinate(transcript, i) + 1)
} else {
stopCodonReadThrough.featureLocation.setFmin(convertModifiedLocalCoordinateToSourceCoordinate(transcript, i))
stopCodonReadThrough.featureLocation.setFmax(convertModifiedLocalCoordinateToSourceCoordinate(transcript, i + 2) + 1)
}
}
continue
}
if (transcript.strand == Strand.NEGATIVE.value) {
cds.featureLocation.setFmin(convertLocalCoordinateToSourceCoordinateForTranscript(transcript, i + 2))
} else {
cds.featureLocation.setFmax(convertLocalCoordinateToSourceCoordinateForTranscript(transcript, i + 3))
}
return
}
}
if (transcript.strand == Strand.NEGATIVE.value) {
cds.featureLocation.setFmin(transcript.getFmin())
cds.featureLocation.setIsFminPartial(true)
} else {
cds.featureLocation.setFmax(transcript.getFmax())
cds.featureLocation.setIsFmaxPartial(true)
}
}
Date date = new Date()
cds.setLastUpdated(date)
transcript.setLastUpdated(date)
// event fire
// fireAnnotationChangeEvent(transcript, transcript.getGene(), AnnotationChangeEvent.Operation.UPDATE);
}
/** Set the translation end in the transcript. Sets the translation end in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation start in
* @param translationEnd - Coordinate of the end of translation
*/
/*
public void setTranslationEnd(Transcript transcript, int translationEnd) {
CDS cds = transcript.getCDS();
if (cds == null) {
cds = createCDS(transcript);
transcript.setCDS(cds);
}
if (transcript.getStrand() == -1) {
cds.setFmin(translationEnd + 1);
}
else {
cds.setFmax(translationEnd);
}
setManuallySetTranslationEnd(cds, true);
cds.deleteStopCodonReadThrough();
// event fire
fireAnnotationChangeEvent(transcript, transcript.getGene(), AnnotationChangeEvent.Operation.UPDATE);
}
*/
/**
* Set the translation end in the transcript. Sets the translation end in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation end in
* @param translationEnd - Coordinate of the end of translation
*/
@Transactional
void setTranslationEnd(Transcript transcript, int translationEnd) throws AnnotationException {
setTranslationEnd(transcript, translationEnd, false)
}
/**
* Set the translation end in the transcript. Sets the translation end in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation end in
* @param translationEnd - Coordinate of the end of translation
* @param setTranslationStart - if set to true, will search for the nearest in frame start
*/
@Transactional
void setTranslationEnd(Transcript transcript, int translationEnd, boolean setTranslationStart) throws AnnotationException {
setTranslationEnd(transcript, translationEnd, setTranslationStart,
setTranslationStart ? organismService.getTranslationTable(transcript.featureLocation.sequence.organism) : null
)
}
/**
* Set the translation end in the transcript. Sets the translation end in the underlying CDS feature.
* Instantiates the CDS object for the transcript if it doesn't already exist.
*
* @param transcript - Transcript to set the translation end in
* @param translationEnd - Coordinate of the end of translation
* @param setTranslationStart - if set to true, will search for the nearest in frame start codon
* @param translationTable - Translation table that defines the codon translation
*/
@Transactional
void setTranslationEnd(Transcript transcript, int translationEnd, boolean setTranslationStart, TranslationTable translationTable) throws AnnotationException {
CDS cds = transcriptService.getCDS(transcript)
if (cds == null) {
cds = transcriptService.createCDS(transcript)
transcriptService.setCDS(transcript, cds)
}
// if the start is set, then we make sure we are going to set a legal coordinate
if (cdsService.isManuallySetTranslationStart(cds)) {
log.info "${transcript.strand} min ${cds.featureLocation.fmin} vs transl end ${translationEnd}"
if (transcript.strand == Strand.NEGATIVE.value) {
if (translationEnd >= cds.featureLocation.fmax) {
throw new AnnotationException("Translation end ${translationEnd} must be downstream of the start ${cds.featureLocation.fmax} (smaller)")
}
} else {
if (translationEnd <= cds.featureLocation.fmin) {
throw new AnnotationException("Translation end ${translationEnd} must be downstream of the start ${cds.featureLocation.fmin} (larger)")
}
}
}
if (transcript.strand == Strand.NEGATIVE.value) {
cds.featureLocation.setFmin(translationEnd)
} else {
cds.featureLocation.setFmax(translationEnd + 1)
}
cdsService.setManuallySetTranslationEnd(cds, true)
cdsService.deleteStopCodonReadThrough(cds)
if (setTranslationStart && translationTable != null) {
String mrna = getResiduesWithAlterationsAndFrameshifts(transcript)
if (mrna == null || mrna.equals("null")) {
return
}
for (int i = convertSourceCoordinateToLocalCoordinateForTranscript(transcript, translationEnd) - 3; i >= 0; i -= 3) {
if (i - 3 < 0) {
break
}
String codon = mrna.substring(i, i + 3)
if (translationTable.getStartCodons().contains(codon)) {
if (transcript.strand == Strand.NEGATIVE.value) {
cds.featureLocation.setFmax(convertLocalCoordinateToSourceCoordinateForTranscript(transcript, i + 3))
} else {
cds.featureLocation.setFmin(convertLocalCoordinateToSourceCoordinateForTranscript(transcript, i + 2))
}
return
}
}
if (transcript.strand == Strand.NEGATIVE.value) {
cds.featureLocation.setFmin(transcript.getFmin())
cds.featureLocation.setIsFminPartial(true)
} else {
cds.featureLocation.setFmax(transcript.getFmax())
cds.featureLocation.setIsFmaxPartial(true)
}
}
Date date = new Date()
cds.setLastUpdated(date)
transcript.setLastUpdated(date)
// event fire TODO: ??
// fireAnnotationChangeEvent(transcript, transcript.getGene(), AnnotationChangeEvent.Operation.UPDATE);