Clover icon

jalviewX

  1. Project Clover database Wed Oct 31 2018 15:13:58 GMT
  2. Package jalview.ext.ensembl

File EnsemblSeqProxy.java

 

Coverage histogram

../../../img/srcFileCovDistChart3.png
47% of files have more coverage

Code metrics

92
213
27
2
926
527
85
0.4
7.89
13.5
3.15

Classes

Class Line # Actions
EnsemblSeqProxy 59 211 83 248
0.2439024424.4%
EnsemblSeqProxy.EnsemblSeqType 68 2 2 4
0.00%
 

Contributing tests

This file is covered by 27 tests. .

Source view

1    /*
2    * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3    * Copyright (C) $$Year-Rel$$ The Jalview Authors
4    *
5    * This file is part of Jalview.
6    *
7    * Jalview is free software: you can redistribute it and/or
8    * modify it under the terms of the GNU General Public License
9    * as published by the Free Software Foundation, either version 3
10    * of the License, or (at your option) any later version.
11    *
12    * Jalview is distributed in the hope that it will be useful, but
13    * WITHOUT ANY WARRANTY; without even the implied warranty
14    * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15    * PURPOSE. See the GNU General Public License for more details.
16    *
17    * You should have received a copy of the GNU General Public License
18    * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19    * The Jalview Authors are detailed in the 'AUTHORS' file.
20    */
21    package jalview.ext.ensembl;
22   
23    import jalview.analysis.AlignmentUtils;
24    import jalview.analysis.Dna;
25    import jalview.bin.Cache;
26    import jalview.datamodel.Alignment;
27    import jalview.datamodel.AlignmentI;
28    import jalview.datamodel.DBRefEntry;
29    import jalview.datamodel.DBRefSource;
30    import jalview.datamodel.Mapping;
31    import jalview.datamodel.SequenceFeature;
32    import jalview.datamodel.SequenceI;
33    import jalview.datamodel.features.SequenceFeatures;
34    import jalview.exceptions.JalviewException;
35    import jalview.io.FastaFile;
36    import jalview.io.FileParse;
37    import jalview.io.gff.Gff3Helper;
38    import jalview.io.gff.SequenceOntologyFactory;
39    import jalview.io.gff.SequenceOntologyI;
40    import jalview.util.Comparison;
41    import jalview.util.DBRefUtils;
42    import jalview.util.IntRangeComparator;
43    import jalview.util.MapList;
44   
45    import java.io.IOException;
46    import java.net.MalformedURLException;
47    import java.net.URL;
48    import java.util.ArrayList;
49    import java.util.Arrays;
50    import java.util.Collections;
51    import java.util.List;
52   
53    /**
54    * Base class for Ensembl sequence fetchers
55    *
56    * @see http://rest.ensembl.org/documentation/info/sequence_id
57    * @author gmcarstairs
58    */
 
59    public abstract class EnsemblSeqProxy extends EnsemblRestClient
60    {
61    protected static final String NAME = "Name";
62   
63    protected static final String DESCRIPTION = "description";
64   
65    /*
66    * enum for 'type' parameter to the /sequence REST service
67    */
 
68    public enum EnsemblSeqType
69    {
70    /**
71    * type=genomic to fetch full dna including introns
72    */
73    GENOMIC("genomic"),
74   
75    /**
76    * type=cdna to fetch coding dna including UTRs
77    */
78    CDNA("cdna"),
79   
80    /**
81    * type=cds to fetch coding dna excluding UTRs
82    */
83    CDS("cds"),
84   
85    /**
86    * type=protein to fetch peptide product sequence
87    */
88    PROTEIN("protein");
89   
90    /*
91    * the value of the 'type' parameter to fetch this version of
92    * an Ensembl sequence
93    */
94    private String type;
95   
 
96  0 toggle EnsemblSeqType(String t)
97    {
98  0 type = t;
99    }
100   
 
101  0 toggle public String getType()
102    {
103  0 return type;
104    }
105   
106    }
107   
108    /**
109    * Default constructor (to use rest.ensembl.org)
110    */
 
111  36 toggle public EnsemblSeqProxy()
112    {
113  36 super();
114    }
115   
116    /**
117    * Constructor given the target domain to fetch data from
118    */
 
119  0 toggle public EnsemblSeqProxy(String d)
120    {
121  0 super(d);
122    }
123   
124    /**
125    * Makes the sequence queries to Ensembl's REST service and returns an
126    * alignment consisting of the returned sequences.
127    */
 
128  0 toggle @Override
129    public AlignmentI getSequenceRecords(String query) throws Exception
130    {
131    // TODO use a String... query vararg instead?
132   
133    // danger: accession separator used as a regex here, a string elsewhere
134    // in this case it is ok (it is just a space), but (e.g.) '\' would not be
135  0 List<String> allIds = Arrays
136    .asList(query.split(getAccessionSeparator()));
137  0 AlignmentI alignment = null;
138  0 inProgress = true;
139   
140    /*
141    * execute queries, if necessary in batches of the
142    * maximum allowed number of ids
143    */
144  0 int maxQueryCount = getMaximumQueryCount();
145  0 for (int v = 0, vSize = allIds.size(); v < vSize; v += maxQueryCount)
146    {
147  0 int p = Math.min(vSize, v + maxQueryCount);
148  0 List<String> ids = allIds.subList(v, p);
149  0 try
150    {
151  0 alignment = fetchSequences(ids, alignment);
152    } catch (Throwable r)
153    {
154  0 inProgress = false;
155  0 String msg = "Aborting ID retrieval after " + v
156    + " chunks. Unexpected problem (" + r.getLocalizedMessage()
157    + ")";
158  0 System.err.println(msg);
159  0 r.printStackTrace();
160  0 break;
161    }
162    }
163   
164  0 if (alignment == null)
165    {
166  0 return null;
167    }
168   
169    /*
170    * fetch and transfer genomic sequence features,
171    * fetch protein product and add as cross-reference
172    */
173  0 for (String accId : allIds)
174    {
175  0 addFeaturesAndProduct(accId, alignment);
176    }
177   
178  0 for (SequenceI seq : alignment.getSequences())
179    {
180  0 getCrossReferences(seq);
181    }
182   
183  0 return alignment;
184    }
185   
186    /**
187    * Fetches Ensembl features using the /overlap REST endpoint, and adds them to
188    * the sequence in the alignment. Also fetches the protein product, maps it
189    * from the CDS features of the sequence, and saves it as a cross-reference of
190    * the dna sequence.
191    *
192    * @param accId
193    * @param alignment
194    */
 
195  0 toggle protected void addFeaturesAndProduct(String accId, AlignmentI alignment)
196    {
197  0 if (alignment == null)
198    {
199  0 return;
200    }
201   
202  0 try
203    {
204    /*
205    * get 'dummy' genomic sequence with gene, transcript,
206    * exon, cds and variation features
207    */
208  0 SequenceI genomicSequence = null;
209  0 EnsemblFeatures gffFetcher = new EnsemblFeatures(getDomain());
210  0 EnsemblFeatureType[] features = getFeaturesToFetch();
211  0 AlignmentI geneFeatures = gffFetcher.getSequenceRecords(accId,
212    features);
213  0 if (geneFeatures != null && geneFeatures.getHeight() > 0)
214    {
215  0 genomicSequence = geneFeatures.getSequenceAt(0);
216    }
217  0 if (genomicSequence != null)
218    {
219    /*
220    * transfer features to the query sequence
221    */
222  0 SequenceI querySeq = alignment.findName(accId, true);
223  0 if (transferFeatures(accId, genomicSequence, querySeq))
224    {
225   
226    /*
227    * fetch and map protein product, and add it as a cross-reference
228    * of the retrieved sequence
229    */
230  0 addProteinProduct(querySeq);
231    }
232    }
233    } catch (IOException e)
234    {
235  0 System.err.println(
236    "Error transferring Ensembl features: " + e.getMessage());
237    }
238    }
239   
240    /**
241    * Returns those sequence feature types to fetch from Ensembl. We may want
242    * features either because they are of interest to the user, or as means to
243    * identify the locations of the sequence on the genomic sequence (CDS
244    * features identify CDS, exon features identify cDNA etc).
245    *
246    * @return
247    */
248    protected abstract EnsemblFeatureType[] getFeaturesToFetch();
249   
250    /**
251    * Fetches and maps the protein product, and adds it as a cross-reference of
252    * the retrieved sequence
253    */
 
254  0 toggle protected void addProteinProduct(SequenceI querySeq)
255    {
256  0 String accId = querySeq.getName();
257  0 try
258    {
259  0 AlignmentI protein = new EnsemblProtein(getDomain())
260    .getSequenceRecords(accId);
261  0 if (protein == null || protein.getHeight() == 0)
262    {
263  0 System.out.println("No protein product found for " + accId);
264  0 return;
265    }
266  0 SequenceI proteinSeq = protein.getSequenceAt(0);
267   
268    /*
269    * need dataset sequences (to be the subject of mappings)
270    */
271  0 proteinSeq.createDatasetSequence();
272  0 querySeq.createDatasetSequence();
273   
274  0 MapList mapList = AlignmentUtils.mapCdsToProtein(querySeq,
275    proteinSeq);
276  0 if (mapList != null)
277    {
278    // clunky: ensure Uniprot xref if we have one is on mapped sequence
279  0 SequenceI ds = proteinSeq.getDatasetSequence();
280    // TODO: Verify ensp primary ref is on proteinSeq.getDatasetSequence()
281  0 Mapping map = new Mapping(ds, mapList);
282  0 DBRefEntry dbr = new DBRefEntry(getDbSource(),
283    getEnsemblDataVersion(), proteinSeq.getName(), map);
284  0 querySeq.getDatasetSequence().addDBRef(dbr);
285  0 DBRefEntry[] uprots = DBRefUtils.selectRefs(ds.getDBRefs(),
286    new String[]
287    { DBRefSource.UNIPROT });
288  0 DBRefEntry[] upxrefs = DBRefUtils.selectRefs(querySeq.getDBRefs(),
289    new String[]
290    { DBRefSource.UNIPROT });
291  0 if (uprots != null)
292    {
293  0 for (DBRefEntry up : uprots)
294    {
295    // locate local uniprot ref and map
296  0 List<DBRefEntry> upx = DBRefUtils.searchRefs(upxrefs,
297    up.getAccessionId());
298  0 DBRefEntry upxref;
299  0 if (upx.size() != 0)
300    {
301  0 upxref = upx.get(0);
302   
303  0 if (upx.size() > 1)
304    {
305  0 Cache.log.warn(
306    "Implementation issue - multiple uniprot acc on product sequence.");
307    }
308    }
309    else
310    {
311  0 upxref = new DBRefEntry(DBRefSource.UNIPROT,
312    getEnsemblDataVersion(), up.getAccessionId());
313    }
314   
315  0 Mapping newMap = new Mapping(ds, mapList);
316  0 upxref.setVersion(getEnsemblDataVersion());
317  0 upxref.setMap(newMap);
318  0 if (upx.size() == 0)
319    {
320    // add the new uniprot ref
321  0 querySeq.getDatasetSequence().addDBRef(upxref);
322    }
323   
324    }
325    }
326   
327    /*
328    * copy exon features to protein, compute peptide variants from dna
329    * variants and add as features on the protein sequence ta-da
330    */
331  0 AlignmentUtils.computeProteinFeatures(querySeq, proteinSeq,
332    mapList);
333    }
334    } catch (Exception e)
335    {
336  0 System.err
337    .println(String.format("Error retrieving protein for %s: %s",
338    accId, e.getMessage()));
339    }
340    }
341   
342    /**
343    * Get database xrefs from Ensembl, and attach them to the sequence
344    *
345    * @param seq
346    */
 
347  0 toggle protected void getCrossReferences(SequenceI seq)
348    {
349  0 while (seq.getDatasetSequence() != null)
350    {
351  0 seq = seq.getDatasetSequence();
352    }
353   
354  0 EnsemblXref xrefFetcher = new EnsemblXref(getDomain(), getDbSource(),
355    getEnsemblDataVersion());
356  0 List<DBRefEntry> xrefs = xrefFetcher.getCrossReferences(seq.getName());
357  0 for (DBRefEntry xref : xrefs)
358    {
359  0 seq.addDBRef(xref);
360    }
361   
362    /*
363    * and add a reference to itself
364    */
365  0 DBRefEntry self = new DBRefEntry(getDbSource(), getEnsemblDataVersion(),
366    seq.getName());
367  0 seq.addDBRef(self);
368    }
369   
370    /**
371    * Fetches sequences for the list of accession ids and adds them to the
372    * alignment. Returns the extended (or created) alignment.
373    *
374    * @param ids
375    * @param alignment
376    * @return
377    * @throws JalviewException
378    * @throws IOException
379    */
 
380  0 toggle protected AlignmentI fetchSequences(List<String> ids,
381    AlignmentI alignment) throws JalviewException, IOException
382    {
383  0 if (!isEnsemblAvailable())
384    {
385  0 inProgress = false;
386  0 throw new JalviewException("ENSEMBL Rest API not available.");
387    }
388  0 FileParse fp = getSequenceReader(ids);
389  0 if (fp == null)
390    {
391  0 return alignment;
392    }
393   
394  0 FastaFile fr = new FastaFile(fp);
395  0 if (fr.hasWarningMessage())
396    {
397  0 System.out.println(
398    String.format("Warning when retrieving %d ids %s\n%s",
399    ids.size(), ids.toString(), fr.getWarningMessage()));
400    }
401  0 else if (fr.getSeqs().size() != ids.size())
402    {
403  0 System.out.println(String.format(
404    "Only retrieved %d sequences for %d query strings",
405    fr.getSeqs().size(), ids.size()));
406    }
407   
408  0 if (fr.getSeqs().size() == 1 && fr.getSeqs().get(0).getLength() == 0)
409    {
410    /*
411    * POST request has returned an empty FASTA file e.g. for invalid id
412    */
413  0 throw new IOException("No data returned for " + ids);
414    }
415   
416  0 if (fr.getSeqs().size() > 0)
417    {
418  0 AlignmentI seqal = new Alignment(fr.getSeqsAsArray());
419  0 for (SequenceI sq : seqal.getSequences())
420    {
421  0 if (sq.getDescription() == null)
422    {
423  0 sq.setDescription(getDbName());
424    }
425  0 String name = sq.getName();
426  0 if (ids.contains(name)
427    || ids.contains(name.replace("ENSP", "ENST")))
428    {
429  0 DBRefEntry dbref = DBRefUtils.parseToDbRef(sq, getDbSource(),
430    getEnsemblDataVersion(), name);
431  0 sq.addDBRef(dbref);
432    }
433    }
434  0 if (alignment == null)
435    {
436  0 alignment = seqal;
437    }
438    else
439    {
440  0 alignment.append(seqal);
441    }
442    }
443  0 return alignment;
444    }
445   
446    /**
447    * Returns the URL for the REST call
448    *
449    * @return
450    * @throws MalformedURLException
451    */
 
452  0 toggle @Override
453    protected URL getUrl(List<String> ids) throws MalformedURLException
454    {
455    /*
456    * a single id is included in the URL path
457    * multiple ids go in the POST body instead
458    */
459  0 StringBuffer urlstring = new StringBuffer(128);
460  0 urlstring.append(getDomain() + "/sequence/id");
461  0 if (ids.size() == 1)
462    {
463  0 urlstring.append("/").append(ids.get(0));
464    }
465    // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
466  0 urlstring.append("?type=").append(getSourceEnsemblType().getType());
467  0 urlstring.append(("&Accept=text/x-fasta"));
468   
469  0 String objectType = getObjectType();
470  0 if (objectType != null)
471    {
472  0 urlstring.append("&").append(OBJECT_TYPE).append("=")
473    .append(objectType);
474    }
475   
476  0 URL url = new URL(urlstring.toString());
477  0 return url;
478    }
479   
480    /**
481    * Override this method to specify object_type request parameter
482    *
483    * @return
484    */
 
485  0 toggle protected String getObjectType()
486    {
487  0 return null;
488    }
489   
490    /**
491    * A sequence/id POST request currently allows up to 50 queries
492    *
493    * @see http://rest.ensembl.org/documentation/info/sequence_id_post
494    */
 
495  0 toggle @Override
496    public int getMaximumQueryCount()
497    {
498  0 return 50;
499    }
500   
 
501  0 toggle @Override
502    protected boolean useGetRequest()
503    {
504  0 return false;
505    }
506   
 
507  0 toggle @Override
508    protected String getRequestMimeType(boolean multipleIds)
509    {
510  0 return multipleIds ? "application/json" : "text/x-fasta";
511    }
512   
 
513  0 toggle @Override
514    protected String getResponseMimeType()
515    {
516  0 return "text/x-fasta";
517    }
518   
519    /**
520    *
521    * @return the configured sequence return type for this source
522    */
523    protected abstract EnsemblSeqType getSourceEnsemblType();
524   
525    /**
526    * Returns a list of [start, end] genomic ranges corresponding to the sequence
527    * being retrieved.
528    *
529    * The correspondence between the frames of reference is made by locating
530    * those features on the genomic sequence which identify the retrieved
531    * sequence. Specifically
532    * <ul>
533    * <li>genomic sequence is identified by "transcript" features with
534    * ID=transcript:transcriptId</li>
535    * <li>cdna sequence is identified by "exon" features with
536    * Parent=transcript:transcriptId</li>
537    * <li>cds sequence is identified by "CDS" features with
538    * Parent=transcript:transcriptId</li>
539    * </ul>
540    *
541    * The returned ranges are sorted to run forwards (for positive strand) or
542    * backwards (for negative strand). Aborts and returns null if both positive
543    * and negative strand are found (this should not normally happen).
544    *
545    * @param sourceSequence
546    * @param accId
547    * @param start
548    * the start position of the sequence we are mapping to
549    * @return
550    */
 
551  7 toggle protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
552    String accId, int start)
553    {
554  7 List<SequenceFeature> sfs = sourceSequence.getFeatures()
555    .getPositionalFeatures();
556  7 if (sfs.isEmpty())
557    {
558  0 return null;
559    }
560   
561    /*
562    * generously initial size for number of cds regions
563    * (worst case titin Q8WZ42 has c. 313 exons)
564    */
565  7 List<int[]> regions = new ArrayList<>(100);
566  7 int mappedLength = 0;
567  7 int direction = 1; // forward
568  7 boolean directionSet = false;
569   
570  7 for (SequenceFeature sf : sfs)
571    {
572    /*
573    * accept the target feature type or a specialisation of it
574    * (e.g. coding_exon for exon)
575    */
576  22 if (identifiesSequence(sf, accId))
577    {
578  13 int strand = sf.getStrand();
579  13 strand = strand == 0 ? 1 : strand; // treat unknown as forward
580   
581  13 if (directionSet && strand != direction)
582    {
583    // abort - mix of forward and backward
584  1 System.err.println(
585    "Error: forward and backward strand for " + accId);
586  1 return null;
587    }
588  12 direction = strand;
589  12 directionSet = true;
590   
591    /*
592    * add to CDS ranges, semi-sorted forwards/backwards
593    */
594  12 if (strand < 0)
595    {
596  2 regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
597    }
598    else
599    {
600  10 regions.add(new int[] { sf.getBegin(), sf.getEnd() });
601    }
602  12 mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
603   
604  12 if (!isSpliceable())
605    {
606    /*
607    * 'gene' sequence is contiguous so we can stop as soon as its
608    * identifying feature has been found
609    */
610  2 break;
611    }
612    }
613    }
614   
615  6 if (regions.isEmpty())
616    {
617  0 System.out.println("Failed to identify target sequence for " + accId
618    + " from genomic features");
619  0 return null;
620    }
621   
622    /*
623    * a final sort is needed since Ensembl returns CDS sorted within source
624    * (havana / ensembl_havana)
625    */
626  6 Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
627    : IntRangeComparator.DESCENDING);
628   
629  6 List<int[]> to = Arrays
630    .asList(new int[]
631    { start, start + mappedLength - 1 });
632   
633  6 return new MapList(regions, to, 1, 1);
634    }
635   
636    /**
637    * Answers true if the sequence being retrieved may occupy discontiguous
638    * regions on the genomic sequence.
639    */
 
640  10 toggle protected boolean isSpliceable()
641    {
642  10 return true;
643    }
644   
645    /**
646    * Returns true if the sequence feature marks positions of the genomic
647    * sequence feature which are within the sequence being retrieved. For
648    * example, an 'exon' feature whose parent is the target transcript marks the
649    * cdna positions of the transcript.
650    *
651    * @param sf
652    * @param accId
653    * @return
654    */
655    protected abstract boolean identifiesSequence(SequenceFeature sf,
656    String accId);
657   
658    /**
659    * Transfers the sequence feature to the target sequence, locating its start
660    * and end range based on the mapping. Features which do not overlap the
661    * target sequence are ignored.
662    *
663    * @param sf
664    * @param targetSequence
665    * @param mapping
666    * mapping from the sequence feature's coordinates to the target
667    * sequence
668    * @param forwardStrand
669    */
 
670  0 toggle protected void transferFeature(SequenceFeature sf,
671    SequenceI targetSequence, MapList mapping, boolean forwardStrand)
672    {
673  0 int start = sf.getBegin();
674  0 int end = sf.getEnd();
675  0 int[] mappedRange = mapping.locateInTo(start, end);
676   
677  0 if (mappedRange != null)
678    {
679  0 String group = sf.getFeatureGroup();
680  0 if (".".equals(group))
681    {
682  0 group = getDbSource();
683    }
684  0 int newBegin = Math.min(mappedRange[0], mappedRange[1]);
685  0 int newEnd = Math.max(mappedRange[0], mappedRange[1]);
686  0 SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
687    group, sf.getScore());
688  0 targetSequence.addSequenceFeature(copy);
689   
690    /*
691    * for sequence_variant on reverse strand, have to convert the allele
692    * values to their complements
693    */
694  0 if (!forwardStrand && SequenceOntologyFactory.getInstance()
695    .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
696    {
697  0 reverseComplementAlleles(copy);
698    }
699    }
700    }
701   
702    /**
703    * Change the 'alleles' value of a feature by converting to complementary
704    * bases, and also update the feature description to match
705    *
706    * @param sf
707    */
 
708  1 toggle static void reverseComplementAlleles(SequenceFeature sf)
709    {
710  1 final String alleles = (String) sf.getValue(Gff3Helper.ALLELES);
711  1 if (alleles == null)
712    {
713  0 return;
714    }
715  1 StringBuilder complement = new StringBuilder(alleles.length());
716  1 for (String allele : alleles.split(","))
717    {
718  5 reverseComplementAllele(complement, allele);
719    }
720  1 String comp = complement.toString();
721  1 sf.setValue(Gff3Helper.ALLELES, comp);
722  1 sf.setDescription(comp);
723   
724    /*
725    * replace value of "alleles=" in sf.ATTRIBUTES as well
726    * so 'output as GFF' shows reverse complement alleles
727    */
728  1 String atts = sf.getAttributes();
729  1 if (atts != null)
730    {
731  1 atts = atts.replace(Gff3Helper.ALLELES + "=" + alleles,
732    Gff3Helper.ALLELES + "=" + comp);
733  1 sf.setAttributes(atts);
734    }
735    }
736   
737    /**
738    * Makes the 'reverse complement' of the given allele and appends it to the
739    * buffer, after a comma separator if not the first
740    *
741    * @param complement
742    * @param allele
743    */
 
744  13 toggle static void reverseComplementAllele(StringBuilder complement,
745    String allele)
746    {
747  13 if (complement.length() > 0)
748    {
749  10 complement.append(",");
750    }
751   
752    /*
753    * some 'alleles' are actually descriptive terms
754    * e.g. HGMD_MUTATION, PhenCode_variation
755    * - we don't want to 'reverse complement' these
756    */
757  13 if (!Comparison.isNucleotideSequence(allele, true))
758    {
759  3 complement.append(allele);
760    }
761    else
762    {
763  29 for (int i = allele.length() - 1; i >= 0; i--)
764    {
765  19 complement.append(Dna.getComplement(allele.charAt(i)));
766    }
767    }
768    }
769   
770    /**
771    * Transfers features from sourceSequence to targetSequence
772    *
773    * @param accessionId
774    * @param sourceSequence
775    * @param targetSequence
776    * @return true if any features were transferred, else false
777    */
 
778  0 toggle protected boolean transferFeatures(String accessionId,
779    SequenceI sourceSequence, SequenceI targetSequence)
780    {
781  0 if (sourceSequence == null || targetSequence == null)
782    {
783  0 return false;
784    }
785   
786    // long start = System.currentTimeMillis();
787  0 List<SequenceFeature> sfs = sourceSequence.getFeatures()
788    .getPositionalFeatures();
789  0 MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
790    accessionId, targetSequence.getStart());
791  0 if (mapping == null)
792    {
793  0 return false;
794    }
795   
796  0 boolean result = transferFeatures(sfs, targetSequence, mapping,
797    accessionId);
798    // System.out.println("transferFeatures (" + (sfs.size()) + " --> "
799    // + targetSequence.getFeatures().getFeatureCount(true) + ") to "
800    // + targetSequence.getName() + " took "
801    // + (System.currentTimeMillis() - start) + "ms");
802  0 return result;
803    }
804   
805    /**
806    * Transfer features to the target sequence. The start/end positions are
807    * converted using the mapping. Features which do not overlap are ignored.
808    * Features whose parent is not the specified identifier are also ignored.
809    *
810    * @param sfs
811    * @param targetSequence
812    * @param mapping
813    * @param parentId
814    * @return
815    */
 
816  0 toggle protected boolean transferFeatures(List<SequenceFeature> sfs,
817    SequenceI targetSequence, MapList mapping, String parentId)
818    {
819  0 final boolean forwardStrand = mapping.isFromForwardStrand();
820   
821    /*
822    * sort features by start position (which corresponds to end
823    * position descending if reverse strand) so as to add them in
824    * 'forwards' order to the target sequence
825    */
826  0 SequenceFeatures.sortFeatures(sfs, forwardStrand);
827   
828  0 boolean transferred = false;
829  0 for (SequenceFeature sf : sfs)
830    {
831  0 if (retainFeature(sf, parentId))
832    {
833  0 transferFeature(sf, targetSequence, mapping, forwardStrand);
834  0 transferred = true;
835    }
836    }
837  0 return transferred;
838    }
839   
840    /**
841    * Answers true if the feature type is one we want to keep for the sequence.
842    * Some features are only retrieved in order to identify the sequence range,
843    * and may then be discarded as redundant information (e.g. "CDS" feature for
844    * a CDS sequence).
845    */
 
846  0 toggle @SuppressWarnings("unused")
847    protected boolean retainFeature(SequenceFeature sf, String accessionId)
848    {
849  0 return true; // override as required
850    }
851   
852    /**
853    * Answers true if the feature has a Parent which refers to the given
854    * accession id, or if the feature has no parent. Answers false if the
855    * feature's Parent is for a different accession id.
856    *
857    * @param sf
858    * @param identifier
859    * @return
860    */
 
861  10 toggle protected boolean featureMayBelong(SequenceFeature sf, String identifier)
862    {
863  10 String parent = (String) sf.getValue(PARENT);
864    // using contains to allow for prefix "gene:", "transcript:" etc
865  10 if (parent != null
866    && !parent.toUpperCase().contains(identifier.toUpperCase()))
867    {
868    // this genomic feature belongs to a different transcript
869  3 return false;
870    }
871  7 return true;
872    }
873   
 
874  0 toggle @Override
875    public String getDescription()
876    {
877  0 return "Ensembl " + getSourceEnsemblType().getType()
878    + " sequence with variant features";
879    }
880   
881    /**
882    * Returns a (possibly empty) list of features on the sequence which have the
883    * specified sequence ontology term (or a sub-type of it), and the given
884    * identifier as parent
885    *
886    * @param sequence
887    * @param term
888    * @param parentId
889    * @return
890    */
 
891  0 toggle protected List<SequenceFeature> findFeatures(SequenceI sequence,
892    String term, String parentId)
893    {
894  0 List<SequenceFeature> result = new ArrayList<>();
895   
896  0 List<SequenceFeature> sfs = sequence.getFeatures()
897    .getFeaturesByOntology(term);
898  0 for (SequenceFeature sf : sfs)
899    {
900  0 String parent = (String) sf.getValue(PARENT);
901  0 if (parent != null && parent.equalsIgnoreCase(parentId))
902    {
903  0 result.add(sf);
904    }
905    }
906   
907  0 return result;
908    }
909   
910    /**
911    * Answers true if the feature type is either 'NMD_transcript_variant' or
912    * 'transcript' or one of its sub-types in the Sequence Ontology. This is
913    * needed because NMD_transcript_variant behaves like 'transcript' in Ensembl
914    * although strictly speaking it is not (it is a sub-type of
915    * sequence_variant).
916    *
917    * @param featureType
918    * @return
919    */
 
920  30 toggle public static boolean isTranscript(String featureType)
921    {
922  30 return SequenceOntologyI.NMD_TRANSCRIPT_VARIANT.equals(featureType)
923    || SequenceOntologyFactory.getInstance().isA(featureType,
924    SequenceOntologyI.TRANSCRIPT);
925    }
926    }