+ /**
+ *
+ * @return the configured sequence return type for this source
+ */
+ protected abstract EnsemblSeqType getSourceEnsemblType();
+
+ /**
+ * Returns a list of [start, end] genomic ranges corresponding to the sequence
+ * being retrieved.
+ *
+ * The correspondence between the frames of reference is made by locating
+ * those features on the genomic sequence which identify the retrieved
+ * sequence. Specifically
+ * <ul>
+ * <li>genomic sequence is identified by "transcript" features with
+ * ID=transcript:transcriptId</li>
+ * <li>cdna sequence is identified by "exon" features with
+ * Parent=transcript:transcriptId</li>
+ * <li>cds sequence is identified by "CDS" features with
+ * Parent=transcript:transcriptId</li>
+ * </ul>
+ *
+ * The returned ranges are sorted to run forwards (for positive strand) or
+ * backwards (for negative strand). Aborts and returns null if both positive
+ * and negative strand are found (this should not normally happen).
+ *
+ * @param sourceSequence
+ * @param accId
+ * @param start
+ * the start position of the sequence we are mapping to
+ * @return
+ */
+ protected MapList getGenomicRangesFromFeatures(SequenceI sourceSequence,
+ String accId, int start)
+ {
+ List<SequenceFeature> sfs = getIdentifyingFeatures(sourceSequence,
+ accId);
+ if (sfs.isEmpty())
+ {
+ return null;
+ }
+
+ /*
+ * generously initial size for number of cds regions
+ * (worst case titin Q8WZ42 has c. 313 exons)
+ */
+ List<int[]> regions = new ArrayList<>(100);
+ int mappedLength = 0;
+ int direction = 1; // forward
+ boolean directionSet = false;
+
+ for (SequenceFeature sf : sfs)
+ {
+ int strand = sf.getStrand();
+ strand = strand == 0 ? 1 : strand; // treat unknown as forward
+
+ if (directionSet && strand != direction)
+ {
+ // abort - mix of forward and backward
+ System.err
+ .println("Error: forward and backward strand for " + accId);
+ return null;
+ }
+ direction = strand;
+ directionSet = true;
+
+ /*
+ * add to CDS ranges, semi-sorted forwards/backwards
+ */
+ if (strand < 0)
+ {
+ regions.add(0, new int[] { sf.getEnd(), sf.getBegin() });
+ }
+ else
+ {
+ regions.add(new int[] { sf.getBegin(), sf.getEnd() });
+ }
+ mappedLength += Math.abs(sf.getEnd() - sf.getBegin() + 1);
+ }
+
+ if (regions.isEmpty())
+ {
+ System.out.println("Failed to identify target sequence for " + accId
+ + " from genomic features");
+ return null;
+ }
+
+ /*
+ * a final sort is needed since Ensembl returns CDS sorted within source
+ * (havana / ensembl_havana)
+ */
+ Collections.sort(regions, direction == 1 ? IntRangeComparator.ASCENDING
+ : IntRangeComparator.DESCENDING);
+
+ List<int[]> to = Arrays
+ .asList(new int[]
+ { start, start + mappedLength - 1 });
+
+ return new MapList(regions, to, 1, 1);
+ }
+
+ /**
+ * Answers a list of sequence features that mark positions of the genomic
+ * sequence feature which are within the sequence being retrieved. For
+ * example, an 'exon' feature whose parent is the target transcript marks the
+ * cdna positions of the transcript. For a gene sequence, this is trivially
+ * just the 'gene' feature with matching gene id.
+ *
+ * @param seq
+ * @param accId
+ * @return
+ */
+ protected abstract List<SequenceFeature> getIdentifyingFeatures(
+ SequenceI seq, String accId);
+
+ /**
+ * Transfers the sequence feature to the target sequence, locating its start
+ * and end range based on the mapping. Features which do not overlap the
+ * target sequence are ignored.
+ *
+ * @param sf
+ * @param targetSequence
+ * @param mapping
+ * mapping from the sequence feature's coordinates to the target
+ * sequence
+ * @param forwardStrand
+ */
+ protected void transferFeature(SequenceFeature sf,
+ SequenceI targetSequence, MapList mapping, boolean forwardStrand)
+ {
+ int start = sf.getBegin();
+ int end = sf.getEnd();
+ int[] mappedRange = mapping.locateInTo(start, end);
+
+ if (mappedRange != null)
+ {
+ String group = sf.getFeatureGroup();
+ if (".".equals(group))
+ {
+ group = getDbSource();
+ }
+ int newBegin = Math.min(mappedRange[0], mappedRange[1]);
+ int newEnd = Math.max(mappedRange[0], mappedRange[1]);
+ SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
+ group, sf.getScore());
+ targetSequence.addSequenceFeature(copy);
+
+ /*
+ * for sequence_variant on reverse strand, have to convert the allele
+ * values to their complements
+ */
+ if (!forwardStrand && SequenceOntologyFactory.getInstance()
+ .isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
+ {
+ reverseComplementAlleles(copy);
+ }
+ }
+ }
+
+ /**
+ * Change the 'alleles' value of a feature by converting to complementary
+ * bases, and also update the feature description to match
+ *
+ * @param sf
+ */
+ static void reverseComplementAlleles(SequenceFeature sf)
+ {
+ final String alleles = (String) sf.getValue(Gff3Helper.ALLELES);
+ if (alleles == null)
+ {
+ return;
+ }
+ StringBuilder complement = new StringBuilder(alleles.length());
+ for (String allele : alleles.split(","))
+ {
+ reverseComplementAllele(complement, allele);
+ }
+ String comp = complement.toString();
+ sf.setValue(Gff3Helper.ALLELES, comp);
+ sf.setDescription(comp);
+
+ /*
+ * replace value of "alleles=" in sf.ATTRIBUTES as well
+ * so 'output as GFF' shows reverse complement alleles
+ */
+ String atts = sf.getAttributes();
+ if (atts != null)
+ {
+ atts = atts.replace(Gff3Helper.ALLELES + "=" + alleles,
+ Gff3Helper.ALLELES + "=" + comp);
+ sf.setAttributes(atts);
+ }
+ }
+
+ /**
+ * Makes the 'reverse complement' of the given allele and appends it to the
+ * buffer, after a comma separator if not the first
+ *
+ * @param complement
+ * @param allele
+ */
+ static void reverseComplementAllele(StringBuilder complement,
+ String allele)
+ {
+ if (complement.length() > 0)
+ {
+ complement.append(",");
+ }
+
+ /*
+ * some 'alleles' are actually descriptive terms
+ * e.g. HGMD_MUTATION, PhenCode_variation
+ * - we don't want to 'reverse complement' these
+ */
+ if (!Comparison.isNucleotideSequence(allele, true))
+ {
+ complement.append(allele);
+ }
+ else
+ {
+ for (int i = allele.length() - 1; i >= 0; i--)
+ {
+ complement.append(Dna.getComplement(allele.charAt(i)));
+ }
+ }
+ }
+
+ /**
+ * Transfers features from sourceSequence to targetSequence
+ *
+ * @param accessionId
+ * @param sourceSequence
+ * @param targetSequence
+ * @return true if any features were transferred, else false
+ */
+ protected boolean transferFeatures(String accessionId,
+ SequenceI sourceSequence, SequenceI targetSequence)
+ {
+ if (sourceSequence == null || targetSequence == null)
+ {
+ return false;
+ }
+
+// long start = System.currentTimeMillis();
+ List<SequenceFeature> sfs = sourceSequence.getFeatures()
+ .getPositionalFeatures();
+ MapList mapping = getGenomicRangesFromFeatures(sourceSequence,
+ accessionId, targetSequence.getStart());
+ if (mapping == null)
+ {
+ return false;
+ }
+
+ boolean result = transferFeatures(sfs, targetSequence, mapping,
+ accessionId);
+// System.out.println("transferFeatures (" + (sfs.size()) + " --> "
+// + targetSequence.getFeatures().getFeatureCount(true) + ") to "
+// + targetSequence.getName() + " took "
+// + (System.currentTimeMillis() - start) + "ms");
+ return result;
+ }
+
+ /**
+ * Transfer features to the target sequence. The start/end positions are
+ * converted using the mapping. Features which do not overlap are ignored.
+ * Features whose parent is not the specified identifier are also ignored.
+ *
+ * @param sfs
+ * @param targetSequence
+ * @param mapping
+ * @param parentId
+ * @return
+ */
+ protected boolean transferFeatures(List<SequenceFeature> sfs,
+ SequenceI targetSequence, MapList mapping, String parentId)
+ {
+ final boolean forwardStrand = mapping.isFromForwardStrand();
+
+ /*
+ * sort features by start position (which corresponds to end
+ * position descending if reverse strand) so as to add them in
+ * 'forwards' order to the target sequence
+ */
+ SequenceFeatures.sortFeatures(sfs, forwardStrand);
+
+ boolean transferred = false;
+ for (SequenceFeature sf : sfs)
+ {
+ if (retainFeature(sf, parentId))
+ {
+ transferFeature(sf, targetSequence, mapping, forwardStrand);
+ transferred = true;
+ }
+ }
+ return transferred;
+ }
+
+ /**
+ * Answers true if the feature type is one we want to keep for the sequence.
+ * Some features are only retrieved in order to identify the sequence range,
+ * and may then be discarded as redundant information (e.g. "CDS" feature for
+ * a CDS sequence).
+ */
+ @SuppressWarnings("unused")
+ protected boolean retainFeature(SequenceFeature sf, String accessionId)
+ {
+ return true; // override as required
+ }
+
+ /**
+ * Answers true if the feature has a Parent which refers to the given
+ * accession id, or if the feature has no parent. Answers false if the
+ * feature's Parent is for a different accession id.
+ *
+ * @param sf
+ * @param identifier
+ * @return
+ */
+ protected boolean featureMayBelong(SequenceFeature sf, String identifier)
+ {
+ String parent = (String) sf.getValue(PARENT);
+ if (parent != null
+ && !parent.equalsIgnoreCase(identifier))
+ {
+ // this genomic feature belongs to a different transcript
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Answers a short description of the sequence fetcher
+ */