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.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Locale;
32 import jalview.api.FeatureColourI;
33 import jalview.datamodel.AlignmentAnnotation;
34 import jalview.datamodel.DBRefEntry;
35 import jalview.datamodel.DBRefSource;
36 import jalview.datamodel.GeneLociI;
37 import jalview.datamodel.MappedFeatures;
38 import jalview.datamodel.SequenceFeature;
39 import jalview.datamodel.SequenceI;
40 import jalview.util.MessageManager;
41 import jalview.util.StringUtils;
42 import jalview.util.UrlLink;
43 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
46 * generate HTML reports for a sequence
50 public class SequenceAnnotationReport
52 private static final int MAX_DESCRIPTION_LENGTH = 40;
54 private static final String COMMA = ",";
56 private static final String ELLIPSIS = "...";
58 private static final int MAX_REFS_PER_SOURCE = 4;
60 private static final int MAX_SOURCES = 40;
62 private static String linkImageURL;
64 // public static final String[][] PRIMARY_SOURCES moved to DBRefSource.java
67 * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
68 * with 'Primary' sources placed before others, and 'chromosome' first of all
70 private static Comparator<DBRefEntry> comparator = new Comparator<DBRefEntry>()
74 public int compare(DBRefEntry ref1, DBRefEntry ref2)
76 if (ref1 instanceof GeneLociI)
80 if (ref2 instanceof GeneLociI)
84 String s1 = ref1.getSource();
85 String s2 = ref2.getSource();
86 boolean s1Primary = DBRefSource.isPrimarySource(s1);
87 boolean s2Primary = DBRefSource.isPrimarySource(s2);
88 if (s1Primary && !s2Primary)
92 if (!s1Primary && s2Primary)
96 int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
97 .compareToIgnoreCase(s2));
100 String a1 = ref1.getAccessionId();
101 String a2 = ref2.getAccessionId();
102 comp = a1 == null ? -1 : (a2 == null ? 1 : a1
103 .compareToIgnoreCase(a2));
108 // private boolean isPrimarySource(String source)
110 // for (String[] primary : DBRefSource.PRIMARY_SOURCES)
112 // for (String s : primary)
114 // if (source.equals(s))
124 private boolean forTooltip;
127 * Constructor given a flag which affects behaviour
129 * <li>if true, generates feature details suitable to show in a tooltip</li>
130 * <li>if false, generates feature details in a form suitable for the sequence
131 * details report</li>
134 * @param isForTooltip
136 public SequenceAnnotationReport(boolean isForTooltip)
138 this.forTooltip = isForTooltip;
139 if (linkImageURL == null)
141 linkImageURL = getClass().getResource("/images/link.gif").toString();
146 * Append text for the list of features to the tooltip. Returns the number of
147 * features not added if maxlength limit is (or would have been) reached.
155 public int appendFeatures(final StringBuilder sb,
156 int residuePos, List<SequenceFeature> features,
157 FeatureRendererModel fr, int maxlength)
159 for (int i = 0; i < features.size(); i++)
161 SequenceFeature feature = features.get(i);
162 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
164 return features.size() - i;
171 * Appends text for mapped features (e.g. CDS feature for peptide or vice
172 * versa) Returns number of features left if maxlength limit is (or would have
181 public int appendFeatures(StringBuilder sb, int residuePos,
182 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
184 for (int i = 0; i < mf.features.size(); i++)
186 SequenceFeature feature = mf.features.get(i);
187 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
189 return mf.features.size() - i;
196 * Appends the feature at rpos to the given buffer
203 boolean appendFeature(final StringBuilder sb0, int rpos,
204 FeatureRendererModel fr, SequenceFeature feature,
205 MappedFeatures mf, int maxlength)
207 int begin = feature.getBegin();
208 int end = feature.getEnd();
211 * if this is a virtual features, convert begin/end to the
212 * coordinates of the sequence it is mapped to
214 int[] beginRange = null; // feature start in local coordinates
215 int[] endRange = null; // feature end in local coordinates
218 if (feature.isContactFeature())
221 * map start and end points individually
223 beginRange = mf.getMappedPositions(begin, begin);
224 endRange = begin == end ? beginRange
225 : mf.getMappedPositions(end, end);
230 * map the feature extent
232 beginRange = mf.getMappedPositions(begin, end);
233 endRange = beginRange;
235 if (beginRange == null || endRange == null)
237 // something went wrong
240 begin = beginRange[0];
241 end = endRange[endRange.length - 1];
244 StringBuilder sb = new StringBuilder();
245 if (feature.isContactFeature())
248 * include if rpos is at start or end position of [mapped] feature
250 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
251 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
252 && rpos <= beginRange[beginRange.length - 1])
253 || (rpos >= endRange[0]
254 && rpos <= endRange[endRange.length - 1]));
255 if (showContact || showMappedContact)
257 if (sb0.length() > 6)
261 sb.append(feature.getType()).append(" ").append(begin).append(":")
264 return appendText(sb0, sb, maxlength);
267 if (sb0.length() > 6)
271 // TODO: remove this hack to display link only features
272 boolean linkOnly = feature.getValue("linkonly") != null;
275 sb.append(feature.getType()).append(" ");
278 // we are marking a positional feature
282 sb.append(" ").append(end);
286 String description = feature.getDescription();
287 if (description != null && !description.equals(feature.getType()))
289 description = StringUtils.stripHtmlTags(description);
292 * truncate overlong descriptions unless they contain an href
293 * before the truncation point (as truncation could leave corrupted html)
295 int linkindex = description.toLowerCase(Locale.ROOT).indexOf("<a ");
296 boolean hasLink = linkindex > -1
297 && linkindex < MAX_DESCRIPTION_LENGTH;
299 // BH suggestion maxlength == 0 &&
300 description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
302 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
306 sb.append("; ").append(description);
309 if (showScore(feature, fr))
311 sb.append(" Score=").append(String.valueOf(feature.getScore()));
313 String status = (String) feature.getValue("status");
314 if (status != null && status.length() > 0)
316 sb.append("; (").append(status).append(")");
320 * add attribute value if coloured by attribute
324 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
325 if (fc != null && fc.isColourByAttribute())
327 String[] attName = fc.getAttributeName();
328 String attVal = feature.getValueAsString(attName);
331 sb.append("; ").append(String.join(":", attName)).append("=")
339 String variants = mf.findProteinVariants(feature);
340 if (!variants.isEmpty())
342 sb.append(" ").append(variants);
346 return appendText(sb0, sb, maxlength);
350 * Appends sb to sb0, and returns false, unless maxlength is not zero and
351 * appending would make the result longer than or equal to maxlength, in which
352 * case the append is not done and returns true
359 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
362 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
371 * Answers true if score should be shown, else false. Score is shown if it is
372 * not NaN, and the feature type has a non-trivial min-max score range
374 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
376 if (Float.isNaN(feature.getScore()))
384 float[][] minMax = fr.getMinMax().get(feature.getType());
387 * minMax[0] is the [min, max] score range for positional features
389 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
397 * Format and appends any hyperlinks for the sequence feature to the string
403 void appendLinks(final StringBuffer sb, SequenceFeature feature)
405 if (feature.links != null)
407 if (linkImageURL != null)
409 sb.append(" <img src=\"" + linkImageURL + "\">");
413 for (String urlstring : feature.links)
417 for (List<String> urllink : createLinksFrom(null, urlstring))
419 sb.append("<br> <a href=\""
424 + (urllink.get(0).toLowerCase(Locale.ROOT)
425 .equals(urllink.get(1).toLowerCase(Locale.ROOT)) ? urllink
426 .get(0) : (urllink.get(0) + ":" + urllink
430 } catch (Exception x)
432 System.err.println("problem when creating links from "
446 * @return Collection< List<String> > { List<String> { link target, link
447 * label, dynamic component inserted (if any), url }}
449 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
451 Map<String, List<String>> urlSets = new LinkedHashMap<>();
452 UrlLink urlLink = new UrlLink(link);
453 if (!urlLink.isValid())
455 System.err.println(urlLink.getInvalidMessage());
459 urlLink.createLinksFromSeq(seq, urlSets);
461 return urlSets.values();
464 public void createSequenceAnnotationReport(final StringBuilder tip,
465 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
466 FeatureRendererModel fr)
468 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
473 * Builds an html formatted report of sequence details and appends it to the
477 * buffer to append report to
479 * the sequence the report is for
481 * whether to include database references for the sequence
483 * whether to include non-positional sequence features
488 int createSequenceAnnotationReport(final StringBuilder sb,
489 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
490 FeatureRendererModel fr, boolean summary)
496 if (sequence.getDescription() != null)
498 tmp = sequence.getDescription();
500 maxWidth = Math.max(maxWidth, tmp.length());
503 SequenceI ds = sequence;
504 while (ds.getDatasetSequence() != null)
506 ds = ds.getDatasetSequence();
511 * add any annotation scores
513 AlignmentAnnotation[] anns = ds.getAnnotation();
514 if (anns!=null && anns.length>0) {
516 for (int i = 0; anns != null && i < anns.length; i++)
518 AlignmentAnnotation aa = anns[i];
519 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
522 sb.append("<br>").append("Annotation Scores<br>");
525 sb.append("<br>").append(aa.label).append(": ")
526 .append(aa.getScore());
532 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
537 * add non-positional features if wanted
541 for (SequenceFeature sf : sequence.getFeatures()
542 .getNonPositionalFeatures())
544 int sz = -sb.length();
545 appendFeature(sb, 0, fr, sf, null, 0);
547 maxWidth = Math.max(maxWidth, sz);
550 if (sequence.getAnnotation("Search Scores") != null)
553 String eValue = " E-Value: "
554 + sequence.getAnnotation("Search Scores")[0].getEValue();
555 String bitScore = " Bit Score: "
556 + sequence.getAnnotation("Search Scores")[0].getBitScore();
560 maxWidth = Math.max(maxWidth, eValue.length());
561 maxWidth = Math.max(maxWidth, bitScore.length());
569 * A helper method that appends any DBRefs, returning the maximum line length
577 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
580 List<DBRefEntry> dbrefs, dbrefset = ds.getDBRefs();
582 if (dbrefset == null)
587 // PATCH for JAL-3980 defensive copy
589 dbrefs = new ArrayList<DBRefEntry>();
591 dbrefs.addAll(dbrefset);
592 // note this sorts the refs held on the sequence!
593 dbrefs.sort(comparator);
594 boolean ellipsis = false;
595 String source = null;
596 String lastSource = null;
597 int countForSource = 0;
599 boolean moreSources = false;
600 int maxLineLength = 0;
603 for (DBRefEntry ref : dbrefs)
605 source = ref.getSource();
611 boolean sourceChanged = !source.equals(lastSource);
618 if (sourceCount > MAX_SOURCES && summary)
626 if (countForSource == 1 || !summary)
628 sb.append("<br/>\n");
630 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
632 String accessionId = ref.getAccessionId();
633 lineLength += accessionId.length() + 1;
634 if (countForSource > 1 && summary)
636 sb.append(",\n ").append(accessionId);
641 sb.append(source).append(" ").append(accessionId);
642 lineLength += source.length();
644 maxLineLength = Math.max(maxLineLength, lineLength);
646 if (countForSource == MAX_REFS_PER_SOURCE && summary)
648 sb.append(COMMA).append(ELLIPSIS);
654 sb.append("<br/>\n").append(source).append(COMMA).append(ELLIPSIS);
658 sb.append("<br/>\n(");
659 sb.append(MessageManager.getString("label.output_seq_details"));
663 return maxLineLength;
666 public void createTooltipAnnotationReport(final StringBuilder tip,
667 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
668 FeatureRendererModel fr)
670 int maxWidth = createSequenceAnnotationReport(tip, sequence,
671 showDbRefs, showNpFeats, fr, true);
675 // ? not sure this serves any useful purpose
676 // tip.insert(0, "<table width=350 border=0><tr><td>");
677 // tip.append("</td></tr></table>");