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;
24 import java.util.Collection;
25 import java.util.Comparator;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Locale;
31 import jalview.api.FeatureColourI;
32 import jalview.datamodel.DBRefEntry;
33 import jalview.datamodel.DBRefSource;
34 import jalview.datamodel.GeneLociI;
35 import jalview.datamodel.MappedFeatures;
36 import jalview.datamodel.SequenceFeature;
37 import jalview.datamodel.SequenceI;
38 import jalview.util.MessageManager;
39 import jalview.util.StringUtils;
40 import jalview.util.UrlLink;
41 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
44 * generate HTML reports for a sequence
48 public class SequenceAnnotationReport
50 private static final int MAX_DESCRIPTION_LENGTH = 40;
52 private static final String COMMA = ",";
54 private static final String ELLIPSIS = "...";
56 private static final int MAX_REFS_PER_SOURCE = 4;
58 private static final int MAX_SOURCES = 5;
60 private static String linkImageURL;
62 // public static final String[][] PRIMARY_SOURCES moved to DBRefSource.java
65 * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
66 * with 'Primary' sources placed before others, and 'chromosome' first of all
68 private static Comparator<DBRefEntry> comparator = new Comparator<DBRefEntry>()
72 public int compare(DBRefEntry ref1, DBRefEntry ref2)
74 if (ref1 instanceof GeneLociI)
78 if (ref2 instanceof GeneLociI)
83 String s1 = ref1.getSource();
84 String s2 = ref2.getSource();
85 boolean s1Primary = DBRefSource.isPrimarySource(s1);
86 boolean s2Primary = DBRefSource.isPrimarySource(s2);
87 if (ref1.isCanonical() && !ref2.isCanonical())
91 if (!ref1.isCanonical() && ref2.isCanonical())
95 if (s1Primary && !s2Primary)
99 if (!s1Primary && s2Primary)
103 int comp = s1 == null ? -1
104 : (s2 == null ? 1 : s1.compareToIgnoreCase(s2));
107 String a1 = ref1.getAccessionId();
108 String a2 = ref2.getAccessionId();
109 comp = a1 == null ? -1
110 : (a2 == null ? 1 : a1.compareToIgnoreCase(a2));
115 // private boolean isPrimarySource(String source)
117 // for (String[] primary : DBRefSource.PRIMARY_SOURCES)
119 // for (String s : primary)
121 // if (source.equals(s))
131 private boolean forTooltip;
134 * Constructor given a flag which affects behaviour
136 * <li>if true, generates feature details suitable to show in a tooltip</li>
137 * <li>if false, generates feature details in a form suitable for the sequence
138 * details report</li>
141 * @param isForTooltip
143 public SequenceAnnotationReport(boolean isForTooltip)
145 this.forTooltip = isForTooltip;
146 if (linkImageURL == null)
148 linkImageURL = getClass().getResource("/images/link.gif").toString();
153 * Append text for the list of features to the tooltip. Returns the number of
154 * features not added if maxlength limit is (or would have been) reached.
162 public int appendFeatures(final StringBuilder sb, int residuePos,
163 List<SequenceFeature> features, FeatureRendererModel fr,
166 for (int i = 0; i < features.size(); i++)
168 SequenceFeature feature = features.get(i);
169 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
171 return features.size() - i;
178 * Appends text for mapped features (e.g. CDS feature for peptide or vice
179 * versa) Returns number of features left if maxlength limit is (or would have
188 public int appendFeatures(StringBuilder sb, int residuePos,
189 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
191 for (int i = 0; i < mf.features.size(); i++)
193 SequenceFeature feature = mf.features.get(i);
194 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
196 return mf.features.size() - i;
203 * Appends the feature at rpos to the given buffer
210 boolean appendFeature(final StringBuilder sb0, int rpos,
211 FeatureRendererModel fr, SequenceFeature feature,
212 MappedFeatures mf, int maxlength)
214 int begin = feature.getBegin();
215 int end = feature.getEnd();
218 * if this is a virtual features, convert begin/end to the
219 * coordinates of the sequence it is mapped to
221 int[] beginRange = null; // feature start in local coordinates
222 int[] endRange = null; // feature end in local coordinates
225 if (feature.isContactFeature())
228 * map start and end points individually
230 beginRange = mf.getMappedPositions(begin, begin);
231 endRange = begin == end ? beginRange
232 : mf.getMappedPositions(end, end);
237 * map the feature extent
239 beginRange = mf.getMappedPositions(begin, end);
240 endRange = beginRange;
242 if (beginRange == null || endRange == null)
244 // something went wrong
247 begin = beginRange[0];
248 end = endRange[endRange.length - 1];
251 StringBuilder sb = new StringBuilder();
252 if (feature.isContactFeature())
255 * include if rpos is at start or end position of [mapped] feature
257 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
258 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
259 && rpos <= beginRange[beginRange.length - 1])
260 || (rpos >= endRange[0]
261 && rpos <= endRange[endRange.length - 1]));
262 if (showContact || showMappedContact)
264 if (sb0.length() > 6)
268 sb.append(feature.getType()).append(" ").append(begin).append(":")
271 return appendText(sb0, sb, maxlength);
274 if (sb0.length() > 6)
278 // TODO: remove this hack to display link only features
279 boolean linkOnly = feature.getValue("linkonly") != null;
282 sb.append(feature.getType()).append(" ");
285 // we are marking a positional feature
289 sb.append(" ").append(end);
293 String description = feature.getDescription();
294 if (description != null && !description.equals(feature.getType()))
296 description = StringUtils.stripHtmlTags(description);
299 * truncate overlong descriptions unless they contain an href
300 * before the truncation point (as truncation could leave corrupted html)
302 int linkindex = description.toLowerCase(Locale.ROOT).indexOf("<a ");
303 boolean hasLink = linkindex > -1
304 && linkindex < MAX_DESCRIPTION_LENGTH;
305 if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
307 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
311 sb.append("; ").append(description);
314 if (showScore(feature, fr))
316 sb.append(" Score=").append(String.valueOf(feature.getScore()));
318 String status = (String) feature.getValue("status");
319 if (status != null && status.length() > 0)
321 sb.append("; (").append(status).append(")");
325 * add attribute value if coloured by attribute
329 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
330 if (fc != null && fc.isColourByAttribute())
332 String[] attName = fc.getAttributeName();
333 String attVal = feature.getValueAsString(attName);
336 sb.append("; ").append(String.join(":", attName)).append("=")
344 String variants = mf.findProteinVariants(feature);
345 if (!variants.isEmpty())
347 sb.append(" ").append(variants);
351 return appendText(sb0, sb, maxlength);
355 * Appends sb to sb0, and returns false, unless maxlength is not zero and
356 * appending would make the result longer than or equal to maxlength, in which
357 * case the append is not done and returns true
364 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
367 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
376 * Answers true if score should be shown, else false. Score is shown if it is
377 * not NaN, and the feature type has a non-trivial min-max score range
379 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
381 if (Float.isNaN(feature.getScore()))
389 float[][] minMax = fr.getMinMax().get(feature.getType());
392 * minMax[0] is the [min, max] score range for positional features
394 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
402 * Format and appends any hyperlinks for the sequence feature to the string
408 void appendLinks(final StringBuffer sb, SequenceFeature feature)
410 if (feature.links != null)
412 if (linkImageURL != null)
414 sb.append(" <img src=\"" + linkImageURL + "\">");
418 for (String urlstring : feature.links)
422 for (List<String> urllink : createLinksFrom(null, urlstring))
424 sb.append("<br/> <a href=\"" + urllink.get(3) + "\" target=\""
425 + urllink.get(0) + "\">"
426 + (urllink.get(0).toLowerCase(Locale.ROOT).equals(
427 urllink.get(1).toLowerCase(Locale.ROOT))
429 : (urllink.get(0) + ":"
433 } catch (Exception x)
435 jalview.bin.Console.errPrintln(
436 "problem when creating links from " + urlstring);
449 * @return Collection< List<String> > { List<String> { link target, link
450 * label, dynamic component inserted (if any), url }}
452 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
454 Map<String, List<String>> urlSets = new LinkedHashMap<>();
455 UrlLink urlLink = new UrlLink(link);
456 if (!urlLink.isValid())
458 jalview.bin.Console.errPrintln(urlLink.getInvalidMessage());
462 urlLink.createLinksFromSeq(seq, urlSets);
464 return urlSets.values();
467 public void createSequenceAnnotationReport(final StringBuilder tip,
468 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
469 FeatureRendererModel fr)
471 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
476 * Builds an html formatted report of sequence details and appends it to the
480 * buffer to append report to
482 * the sequence the report is for
484 * whether to include database references for the sequence
486 * whether to include non-positional sequence features
491 int createSequenceAnnotationReport(final StringBuilder sb,
492 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
493 FeatureRendererModel fr, boolean summary)
499 if (sequence.getDescription() != null)
501 tmp = sequence.getDescription();
503 maxWidth = Math.max(maxWidth, tmp.length());
506 SequenceI ds = sequence;
507 while (ds.getDatasetSequence() != null)
509 ds = ds.getDatasetSequence();
514 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
519 * add non-positional features if wanted
523 for (SequenceFeature sf : sequence.getFeatures()
524 .getNonPositionalFeatures())
526 int sz = -sb.length();
527 appendFeature(sb, 0, fr, sf, null, 0);
529 maxWidth = Math.max(maxWidth, sz);
537 * A helper method that appends any DBRefs, returning the maximum line length
545 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
548 List<DBRefEntry> dbrefs, dbrefset = ds.getDBRefs();
550 if (dbrefset == null)
555 // PATCH for JAL-3980 defensive copy
557 dbrefs = new ArrayList<DBRefEntry>();
559 dbrefs.addAll(dbrefset);
561 // note this sorts the refs held on the sequence!
562 dbrefs.sort(comparator);
563 boolean ellipsis = false;
564 String source = null;
565 String lastSource = null;
566 int countForSource = 0;
568 boolean moreSources = false;
569 int maxLineLength = 0;
572 for (DBRefEntry ref : dbrefs)
574 source = ref.getSource();
580 boolean sourceChanged = !source.equals(lastSource);
587 if (sourceCount > MAX_SOURCES && summary)
595 if (countForSource == 1 || !summary)
597 sb.append("<br/>\n");
599 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
601 String accessionId = ref.getAccessionId();
602 lineLength += accessionId.length() + 1;
603 if (countForSource > 1 && summary)
605 sb.append(",\n ").append(accessionId);
610 sb.append(source).append(" ").append(accessionId);
611 lineLength += source.length();
613 maxLineLength = Math.max(maxLineLength, lineLength);
615 if (countForSource == MAX_REFS_PER_SOURCE && summary)
617 sb.append(COMMA).append(ELLIPSIS);
623 sb.append("<br/>\n").append(source).append(COMMA).append(ELLIPSIS);
627 sb.append("<br/>\n(");
628 sb.append(MessageManager.getString("label.output_seq_details"));
632 return maxLineLength;
635 public void createTooltipAnnotationReport(final StringBuilder tip,
636 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
637 FeatureRendererModel fr)
639 int maxWidth = createSequenceAnnotationReport(tip, sequence, showDbRefs,
640 showNpFeats, fr, true);
644 // ? not sure this serves any useful purpose
645 // tip.insert(0, "<table width=350 border=0><tr><td>");
646 // tip.append("</td></tr></table>");