2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import java.util.Collection;
24 import java.util.Comparator;
25 import java.util.LinkedHashMap;
26 import java.util.List;
29 import jalview.api.FeatureColourI;
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.DBRefEntry;
32 import jalview.datamodel.DBRefSource;
33 import jalview.datamodel.GeneLociI;
34 import jalview.datamodel.MappedFeatures;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceI;
37 import jalview.util.MessageManager;
38 import jalview.util.StringUtils;
39 import jalview.util.UrlLink;
40 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
43 * generate HTML reports for a sequence
47 public class SequenceAnnotationReport
49 private static final int MAX_DESCRIPTION_LENGTH = 40;
51 private static final String COMMA = ",";
53 private static final String ELLIPSIS = "...";
55 private static final int MAX_REFS_PER_SOURCE = 4;
57 private static final int MAX_SOURCES = 40;
59 private static String linkImageURL;
61 // public static final String[][] PRIMARY_SOURCES moved to DBRefSource.java
64 * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
65 * with 'Primary' sources placed before others, and 'chromosome' first of all
67 private static Comparator<DBRefEntry> comparator = new Comparator<DBRefEntry>()
71 public int compare(DBRefEntry ref1, DBRefEntry ref2)
73 if (ref1 instanceof GeneLociI)
77 if (ref2 instanceof GeneLociI)
81 String s1 = ref1.getSource();
82 String s2 = ref2.getSource();
83 boolean s1Primary = DBRefSource.isPrimarySource(s1);
84 boolean s2Primary = DBRefSource.isPrimarySource(s2);
85 if (s1Primary && !s2Primary)
89 if (!s1Primary && s2Primary)
93 int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
94 .compareToIgnoreCase(s2));
97 String a1 = ref1.getAccessionId();
98 String a2 = ref2.getAccessionId();
99 comp = a1 == null ? -1 : (a2 == null ? 1 : a1
100 .compareToIgnoreCase(a2));
105 // private boolean isPrimarySource(String source)
107 // for (String[] primary : DBRefSource.PRIMARY_SOURCES)
109 // for (String s : primary)
111 // if (source.equals(s))
121 private boolean forTooltip;
124 * Constructor given a flag which affects behaviour
126 * <li>if true, generates feature details suitable to show in a tooltip</li>
127 * <li>if false, generates feature details in a form suitable for the sequence
128 * details report</li>
131 * @param isForTooltip
133 public SequenceAnnotationReport(boolean isForTooltip)
135 this.forTooltip = isForTooltip;
136 if (linkImageURL == null)
138 linkImageURL = getClass().getResource("/images/link.gif").toString();
143 * Append text for the list of features to the tooltip. Returns the number of
144 * features not added if maxlength limit is (or would have been) reached.
152 public int appendFeatures(final StringBuilder sb,
153 int residuePos, List<SequenceFeature> features,
154 FeatureRendererModel fr, int maxlength)
156 for (int i = 0; i < features.size(); i++)
158 SequenceFeature feature = features.get(i);
159 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
161 return features.size() - i;
168 * Appends text for mapped features (e.g. CDS feature for peptide or vice
169 * versa) Returns number of features left if maxlength limit is (or would have
178 public int appendFeatures(StringBuilder sb, int residuePos,
179 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
181 for (int i = 0; i < mf.features.size(); i++)
183 SequenceFeature feature = mf.features.get(i);
184 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
186 return mf.features.size() - i;
193 * Appends the feature at rpos to the given buffer
200 boolean appendFeature(final StringBuilder sb0, int rpos,
201 FeatureRendererModel fr, SequenceFeature feature,
202 MappedFeatures mf, int maxlength)
204 int begin = feature.getBegin();
205 int end = feature.getEnd();
208 * if this is a virtual features, convert begin/end to the
209 * coordinates of the sequence it is mapped to
211 int[] beginRange = null;
212 int[] endRange = null;
215 beginRange = mf.getMappedPositions(begin, begin);
216 endRange = mf.getMappedPositions(end, end);
217 if (beginRange == null || endRange == null)
219 // something went wrong
222 begin = beginRange[0];
223 end = endRange[endRange.length - 1];
226 StringBuilder sb = new StringBuilder();
227 if (feature.isContactFeature())
230 * include if rpos is at start or end position of [mapped] feature
232 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
233 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
234 && rpos <= beginRange[beginRange.length - 1])
235 || (rpos >= endRange[0]
236 && rpos <= endRange[endRange.length - 1]));
237 if (showContact || showMappedContact)
239 if (sb0.length() > 6)
243 sb.append(feature.getType()).append(" ").append(begin).append(":")
246 return appendText(sb0, sb, maxlength);
249 if (sb0.length() > 6)
253 // TODO: remove this hack to display link only features
254 boolean linkOnly = feature.getValue("linkonly") != null;
257 sb.append(feature.getType()).append(" ");
260 // we are marking a positional feature
264 sb.append(" ").append(end);
268 String description = feature.getDescription();
269 if (description != null && !description.equals(feature.getType()))
271 description = StringUtils.stripHtmlTags(description);
274 * truncate overlong descriptions unless they contain an href
275 * before the truncation point (as truncation could leave corrupted html)
277 int linkindex = description.toLowerCase().indexOf("<a ");
278 boolean hasLink = linkindex > -1
279 && linkindex < MAX_DESCRIPTION_LENGTH;
281 // BH suggestion maxlength == 0 &&
282 description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
284 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
288 sb.append("; ").append(description);
291 if (showScore(feature, fr))
293 sb.append(" Score=").append(String.valueOf(feature.getScore()));
295 String status = (String) feature.getValue("status");
296 if (status != null && status.length() > 0)
298 sb.append("; (").append(status).append(")");
302 * add attribute value if coloured by attribute
306 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
307 if (fc != null && fc.isColourByAttribute())
309 String[] attName = fc.getAttributeName();
310 String attVal = feature.getValueAsString(attName);
313 sb.append("; ").append(String.join(":", attName)).append("=")
321 String variants = mf.findProteinVariants(feature);
322 if (!variants.isEmpty())
324 sb.append(" ").append(variants);
328 return appendText(sb0, sb, maxlength);
332 * Appends sb to sb0, and returns false, unless maxlength is not zero and
333 * appending would make the result longer than or equal to maxlength, in which
334 * case the append is not done and returns true
341 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
344 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
353 * Answers true if score should be shown, else false. Score is shown if it is
354 * not NaN, and the feature type has a non-trivial min-max score range
356 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
358 if (Float.isNaN(feature.getScore()))
366 float[][] minMax = fr.getMinMax().get(feature.getType());
369 * minMax[0] is the [min, max] score range for positional features
371 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
379 * Format and appends any hyperlinks for the sequence feature to the string
385 void appendLinks(final StringBuffer sb, SequenceFeature feature)
387 if (feature.links != null)
389 if (linkImageURL != null)
391 sb.append(" <img src=\"" + linkImageURL + "\">");
395 for (String urlstring : feature.links)
399 for (List<String> urllink : createLinksFrom(null, urlstring))
401 sb.append("<br> <a href=\""
406 + (urllink.get(0).toLowerCase()
407 .equals(urllink.get(1).toLowerCase()) ? urllink
408 .get(0) : (urllink.get(0) + ":" + urllink
412 } catch (Exception x)
414 System.err.println("problem when creating links from "
428 * @return Collection< List<String> > { List<String> { link target, link
429 * label, dynamic component inserted (if any), url }}
431 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
433 Map<String, List<String>> urlSets = new LinkedHashMap<>();
434 UrlLink urlLink = new UrlLink(link);
435 if (!urlLink.isValid())
437 System.err.println(urlLink.getInvalidMessage());
441 urlLink.createLinksFromSeq(seq, urlSets);
443 return urlSets.values();
446 public void createSequenceAnnotationReport(final StringBuilder tip,
447 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
448 FeatureRendererModel fr)
450 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
455 * Builds an html formatted report of sequence details and appends it to the
459 * buffer to append report to
461 * the sequence the report is for
463 * whether to include database references for the sequence
465 * whether to include non-positional sequence features
470 int createSequenceAnnotationReport(final StringBuilder sb,
471 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
472 FeatureRendererModel fr, boolean summary)
478 if (sequence.getDescription() != null)
480 tmp = sequence.getDescription();
482 maxWidth = Math.max(maxWidth, tmp.length());
485 SequenceI ds = sequence;
486 while (ds.getDatasetSequence() != null)
488 ds = ds.getDatasetSequence();
493 * add any annotation scores
495 AlignmentAnnotation[] anns = ds.getAnnotation();
496 if (anns!=null && anns.length>0) {
498 for (int i = 0; anns != null && i < anns.length; i++)
500 AlignmentAnnotation aa = anns[i];
501 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
504 sb.append("<br>").append("Annotation Scores<br>");
507 sb.append("<br>").append(aa.label).append(": ")
508 .append(aa.getScore());
514 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
518 * add non-positional features if wanted
522 for (SequenceFeature sf : sequence.getFeatures()
523 .getNonPositionalFeatures())
525 int sz = -sb.length();
526 appendFeature(sb, 0, fr, sf, null, 0);
528 maxWidth = Math.max(maxWidth, sz);
533 if (sequence.getAnnotation("Search Scores") != null)
536 String eValue = " E-Value: "
537 + sequence.getAnnotation("Search Scores")[0].getEValue();
538 String bitScore = " Bit Score: "
539 + sequence.getAnnotation("Search Scores")[0].getBitScore();
543 maxWidth = Math.max(maxWidth, eValue.length());
544 maxWidth = Math.max(maxWidth, bitScore.length());
553 * A helper method that appends any DBRefs, returning the maximum line length
561 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
564 List<DBRefEntry> dbrefs = ds.getDBRefs();
570 // note this sorts the refs held on the sequence!
571 dbrefs.sort(comparator);
572 boolean ellipsis = false;
573 String source = null;
574 String lastSource = null;
575 int countForSource = 0;
577 boolean moreSources = false;
578 int maxLineLength = 0;
581 for (DBRefEntry ref : dbrefs)
583 source = ref.getSource();
589 boolean sourceChanged = !source.equals(lastSource);
596 if (sourceCount > MAX_SOURCES && summary)
604 if (countForSource == 1 || !summary)
608 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
610 String accessionId = ref.getAccessionId();
611 lineLength += accessionId.length() + 1;
612 if (countForSource > 1 && summary)
614 sb.append(", ").append(accessionId);
619 sb.append(source).append(" ").append(accessionId);
620 lineLength += source.length();
622 maxLineLength = Math.max(maxLineLength, lineLength);
624 if (countForSource == MAX_REFS_PER_SOURCE && summary)
626 sb.append(COMMA).append(ELLIPSIS);
632 sb.append("<br>").append(source).append(COMMA).append(ELLIPSIS);
637 sb.append(MessageManager.getString("label.output_seq_details"));
641 return maxLineLength;
644 public void createTooltipAnnotationReport(final StringBuilder tip,
645 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
646 FeatureRendererModel fr)
648 int maxWidth = createSequenceAnnotationReport(tip, sequence,
649 showDbRefs, showNpFeats, fr, true);
653 // ? not sure this serves any useful purpose
654 // tip.insert(0, "<table width=350 border=0><tr><td>");
655 // tip.append("</td></tr></table>");