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.Locale;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.LinkedHashMap;
28 import java.util.List;
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 = 40;
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)
82 String s1 = ref1.getSource();
83 String s2 = ref2.getSource();
84 boolean s1Primary = DBRefSource.isPrimarySource(s1);
85 boolean s2Primary = DBRefSource.isPrimarySource(s2);
86 if (s1Primary && !s2Primary)
90 if (!s1Primary && s2Primary)
94 int comp = s1 == null ? -1 : (s2 == null ? 1 : s1
95 .compareToIgnoreCase(s2));
98 String a1 = ref1.getAccessionId();
99 String a2 = ref2.getAccessionId();
100 comp = a1 == null ? -1 : (a2 == null ? 1 : a1
101 .compareToIgnoreCase(a2));
106 // private boolean isPrimarySource(String source)
108 // for (String[] primary : DBRefSource.PRIMARY_SOURCES)
110 // for (String s : primary)
112 // if (source.equals(s))
122 private boolean forTooltip;
125 * Constructor given a flag which affects behaviour
127 * <li>if true, generates feature details suitable to show in a tooltip</li>
128 * <li>if false, generates feature details in a form suitable for the sequence
129 * details report</li>
132 * @param isForTooltip
134 public SequenceAnnotationReport(boolean isForTooltip)
136 this.forTooltip = isForTooltip;
137 if (linkImageURL == null)
139 linkImageURL = getClass().getResource("/images/link.gif").toString();
144 * Append text for the list of features to the tooltip. Returns the number of
145 * features not added if maxlength limit is (or would have been) reached.
153 public int appendFeatures(final StringBuilder sb,
154 int residuePos, List<SequenceFeature> features,
155 FeatureRendererModel fr, int maxlength)
157 for (int i = 0; i < features.size(); i++)
159 SequenceFeature feature = features.get(i);
160 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
162 return features.size() - i;
169 * Appends text for mapped features (e.g. CDS feature for peptide or vice
170 * versa) Returns number of features left if maxlength limit is (or would have
179 public int appendFeatures(StringBuilder sb, int residuePos,
180 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
182 for (int i = 0; i < mf.features.size(); i++)
184 SequenceFeature feature = mf.features.get(i);
185 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
187 return mf.features.size() - i;
194 * Appends the feature at rpos to the given buffer
201 boolean appendFeature(final StringBuilder sb0, int rpos,
202 FeatureRendererModel fr, SequenceFeature feature,
203 MappedFeatures mf, int maxlength)
205 int begin = feature.getBegin();
206 int end = feature.getEnd();
209 * if this is a virtual features, convert begin/end to the
210 * coordinates of the sequence it is mapped to
212 int[] beginRange = null;
213 int[] endRange = null;
216 beginRange = mf.getMappedPositions(begin, begin);
217 endRange = mf.getMappedPositions(end, end);
218 if (beginRange == null || endRange == null)
220 // something went wrong
223 begin = beginRange[0];
224 end = endRange[endRange.length - 1];
227 StringBuilder sb = new StringBuilder();
228 if (feature.isContactFeature())
231 * include if rpos is at start or end position of [mapped] feature
233 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
234 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
235 && rpos <= beginRange[beginRange.length - 1])
236 || (rpos >= endRange[0]
237 && rpos <= endRange[endRange.length - 1]));
238 if (showContact || showMappedContact)
240 if (sb0.length() > 6)
244 sb.append(feature.getType()).append(" ").append(begin).append(":")
247 return appendText(sb0, sb, maxlength);
250 if (sb0.length() > 6)
254 // TODO: remove this hack to display link only features
255 boolean linkOnly = feature.getValue("linkonly") != null;
258 sb.append(feature.getType()).append(" ");
261 // we are marking a positional feature
265 sb.append(" ").append(end);
269 String description = feature.getDescription();
270 if (description != null && !description.equals(feature.getType()))
272 description = StringUtils.stripHtmlTags(description);
275 * truncate overlong descriptions unless they contain an href
276 * before the truncation point (as truncation could leave corrupted html)
278 int linkindex = description.toLowerCase(Locale.ROOT).indexOf("<a ");
279 boolean hasLink = linkindex > -1
280 && linkindex < MAX_DESCRIPTION_LENGTH;
281 if (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(Locale.ROOT)
406 .equals(urllink.get(1).toLowerCase(Locale.ROOT)) ? 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>");