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.DBRefEntry;
31 import jalview.datamodel.DBRefSource;
32 import jalview.datamodel.GeneLociI;
33 import jalview.datamodel.MappedFeatures;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceI;
36 import jalview.util.MessageManager;
37 import jalview.util.StringUtils;
38 import jalview.util.UrlLink;
39 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
42 * generate HTML reports for a sequence
46 public class SequenceAnnotationReport
48 private static final int MAX_DESCRIPTION_LENGTH = 40;
50 private static final String COMMA = ",";
52 private static final String ELLIPSIS = "...";
54 private static final int MAX_REFS_PER_SOURCE = 4;
56 private static final int MAX_SOURCES = 40;
58 private static String linkImageURL;
60 // public static final String[][] PRIMARY_SOURCES moved to DBRefSource.java
63 * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
64 * with 'Primary' sources placed before others, and 'chromosome' first of all
66 private static Comparator<DBRefEntry> comparator = new Comparator<DBRefEntry>()
70 public int compare(DBRefEntry ref1, DBRefEntry ref2)
72 if (ref1 instanceof GeneLociI)
76 if (ref2 instanceof GeneLociI)
80 String s1 = ref1.getSource();
81 String s2 = ref2.getSource();
82 boolean s1Primary = DBRefSource.isPrimarySource(s1);
83 boolean s2Primary = DBRefSource.isPrimarySource(s2);
84 if (s1Primary && !s2Primary)
88 if (!s1Primary && s2Primary)
92 int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
93 .compareToIgnoreCase(s2));
96 String a1 = ref1.getAccessionId();
97 String a2 = ref2.getAccessionId();
98 comp = a1 == null ? -1 : (a2 == null ? 1 : a1
99 .compareToIgnoreCase(a2));
104 // private boolean isPrimarySource(String source)
106 // for (String[] primary : DBRefSource.PRIMARY_SOURCES)
108 // for (String s : primary)
110 // if (source.equals(s))
120 private boolean forTooltip;
123 * Constructor given a flag which affects behaviour
125 * <li>if true, generates feature details suitable to show in a tooltip</li>
126 * <li>if false, generates feature details in a form suitable for the sequence
127 * details report</li>
130 * @param isForTooltip
132 public SequenceAnnotationReport(boolean isForTooltip)
134 this.forTooltip = isForTooltip;
135 if (linkImageURL == null)
137 linkImageURL = getClass().getResource("/images/link.gif").toString();
142 * Append text for the list of features to the tooltip. Returns the number of
143 * features not added if maxlength limit is (or would have been) reached.
151 public int appendFeatures(final StringBuilder sb,
152 int residuePos, List<SequenceFeature> features,
153 FeatureRendererModel fr, int maxlength)
155 for (int i = 0; i < features.size(); i++)
157 SequenceFeature feature = features.get(i);
158 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
160 return features.size() - i;
167 * Appends text for mapped features (e.g. CDS feature for peptide or vice
168 * versa) Returns number of features left if maxlength limit is (or would have
177 public int appendFeatures(StringBuilder sb, int residuePos,
178 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
180 for (int i = 0; i < mf.features.size(); i++)
182 SequenceFeature feature = mf.features.get(i);
183 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
185 return mf.features.size() - i;
192 * Appends the feature at rpos to the given buffer
199 boolean appendFeature(final StringBuilder sb0, int rpos,
200 FeatureRendererModel fr, SequenceFeature feature,
201 MappedFeatures mf, int maxlength)
203 int begin = feature.getBegin();
204 int end = feature.getEnd();
207 * if this is a virtual features, convert begin/end to the
208 * coordinates of the sequence it is mapped to
210 int[] beginRange = null;
211 int[] endRange = null;
214 beginRange = mf.getMappedPositions(begin, begin);
215 endRange = mf.getMappedPositions(end, end);
216 if (beginRange == null || endRange == null)
218 // something went wrong
221 begin = beginRange[0];
222 end = endRange[endRange.length - 1];
225 StringBuilder sb = new StringBuilder();
226 if (feature.isContactFeature())
229 * include if rpos is at start or end position of [mapped] feature
231 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
232 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
233 && rpos <= beginRange[beginRange.length - 1])
234 || (rpos >= endRange[0]
235 && rpos <= endRange[endRange.length - 1]));
236 if (showContact || showMappedContact)
238 if (sb0.length() > 6)
242 sb.append(feature.getType()).append(" ").append(begin).append(":")
245 return appendText(sb0, sb, maxlength);
248 if (sb0.length() > 6)
252 // TODO: remove this hack to display link only features
253 boolean linkOnly = feature.getValue("linkonly") != null;
256 sb.append(feature.getType()).append(" ");
259 // we are marking a positional feature
263 sb.append(" ").append(end);
267 String description = feature.getDescription();
268 if (description != null && !description.equals(feature.getType()))
270 description = StringUtils.stripHtmlTags(description);
273 * truncate overlong descriptions unless they contain an href
274 * before the truncation point (as truncation could leave corrupted html)
276 int linkindex = description.toLowerCase().indexOf("<a ");
277 boolean hasLink = linkindex > -1
278 && linkindex < MAX_DESCRIPTION_LENGTH;
280 // BH suggestion maxlength == 0 &&
281 description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
283 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
287 sb.append("; ").append(description);
290 if (showScore(feature, fr))
292 sb.append(" Score=").append(String.valueOf(feature.getScore()));
294 String status = (String) feature.getValue("status");
295 if (status != null && status.length() > 0)
297 sb.append("; (").append(status).append(")");
301 * add attribute value if coloured by attribute
305 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
306 if (fc != null && fc.isColourByAttribute())
308 String[] attName = fc.getAttributeName();
309 String attVal = feature.getValueAsString(attName);
312 sb.append("; ").append(String.join(":", attName)).append("=")
320 String variants = mf.findProteinVariants(feature);
321 if (!variants.isEmpty())
323 sb.append(" ").append(variants);
327 return appendText(sb0, sb, maxlength);
331 * Appends sb to sb0, and returns false, unless maxlength is not zero and
332 * appending would make the result longer than or equal to maxlength, in which
333 * case the append is not done and returns true
340 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
343 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
352 * Answers true if score should be shown, else false. Score is shown if it is
353 * not NaN, and the feature type has a non-trivial min-max score range
355 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
357 if (Float.isNaN(feature.getScore()))
365 float[][] minMax = fr.getMinMax().get(feature.getType());
368 * minMax[0] is the [min, max] score range for positional features
370 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
378 * Format and appends any hyperlinks for the sequence feature to the string
384 void appendLinks(final StringBuffer sb, SequenceFeature feature)
386 if (feature.links != null)
388 if (linkImageURL != null)
390 sb.append(" <img src=\"" + linkImageURL + "\">");
394 for (String urlstring : feature.links)
398 for (List<String> urllink : createLinksFrom(null, urlstring))
400 sb.append("<br> <a href=\""
405 + (urllink.get(0).toLowerCase()
406 .equals(urllink.get(1).toLowerCase()) ? urllink
407 .get(0) : (urllink.get(0) + ":" + urllink
411 } catch (Exception x)
413 System.err.println("problem when creating links from "
427 * @return Collection< List<String> > { List<String> { link target, link
428 * label, dynamic component inserted (if any), url }}
430 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
432 Map<String, List<String>> urlSets = new LinkedHashMap<>();
433 UrlLink urlLink = new UrlLink(link);
434 if (!urlLink.isValid())
436 System.err.println(urlLink.getInvalidMessage());
440 urlLink.createLinksFromSeq(seq, urlSets);
442 return urlSets.values();
445 public void createSequenceAnnotationReport(final StringBuilder tip,
446 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
447 FeatureRendererModel fr)
449 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
454 * Builds an html formatted report of sequence details and appends it to the
458 * buffer to append report to
460 * the sequence the report is for
462 * whether to include database references for the sequence
464 * whether to include non-positional sequence features
469 int createSequenceAnnotationReport(final StringBuilder sb,
470 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
471 FeatureRendererModel fr, boolean summary)
477 if (sequence.getDescription() != null)
479 tmp = sequence.getDescription();
481 maxWidth = Math.max(maxWidth, tmp.length());
483 SequenceI ds = sequence;
484 while (ds.getDatasetSequence() != null)
486 ds = ds.getDatasetSequence();
491 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
495 * add non-positional features if wanted
499 for (SequenceFeature sf : sequence.getFeatures()
500 .getNonPositionalFeatures())
502 int sz = -sb.length();
503 appendFeature(sb, 0, fr, sf, null, 0);
505 maxWidth = Math.max(maxWidth, sz);
513 * A helper method that appends any DBRefs, returning the maximum line length
521 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
524 List<DBRefEntry> dbrefs = ds.getDBRefs();
530 // note this sorts the refs held on the sequence!
531 dbrefs.sort(comparator);
532 boolean ellipsis = false;
533 String source = null;
534 String lastSource = null;
535 int countForSource = 0;
537 boolean moreSources = false;
538 int maxLineLength = 0;
541 for (DBRefEntry ref : dbrefs)
543 source = ref.getSource();
549 boolean sourceChanged = !source.equals(lastSource);
556 if (sourceCount > MAX_SOURCES && summary)
564 if (countForSource == 1 || !summary)
568 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
570 String accessionId = ref.getAccessionId();
571 lineLength += accessionId.length() + 1;
572 if (countForSource > 1 && summary)
574 sb.append(", ").append(accessionId);
579 sb.append(source).append(" ").append(accessionId);
580 lineLength += source.length();
582 maxLineLength = Math.max(maxLineLength, lineLength);
584 if (countForSource == MAX_REFS_PER_SOURCE && summary)
586 sb.append(COMMA).append(ELLIPSIS);
592 sb.append("<br>").append(source).append(COMMA).append(ELLIPSIS);
597 sb.append(MessageManager.getString("label.output_seq_details"));
601 return maxLineLength;
604 public void createTooltipAnnotationReport(final StringBuilder tip,
605 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
606 FeatureRendererModel fr)
608 int maxWidth = createSequenceAnnotationReport(tip, sequence,
609 showDbRefs, showNpFeats, fr, true);
613 // ? not sure this serves any useful purpose
614 // tip.insert(0, "<table width=350 border=0><tr><td>");
615 // tip.append("</td></tr></table>");