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;
279 if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
281 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
285 sb.append("; ").append(description);
288 if (showScore(feature, fr))
290 sb.append(" Score=").append(String.valueOf(feature.getScore()));
292 String status = (String) feature.getValue("status");
293 if (status != null && status.length() > 0)
295 sb.append("; (").append(status).append(")");
299 * add attribute value if coloured by attribute
303 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
304 if (fc != null && fc.isColourByAttribute())
306 String[] attName = fc.getAttributeName();
307 String attVal = feature.getValueAsString(attName);
310 sb.append("; ").append(String.join(":", attName)).append("=")
318 String variants = mf.findProteinVariants(feature);
319 if (!variants.isEmpty())
321 sb.append(" ").append(variants);
325 return appendText(sb0, sb, maxlength);
329 * Appends sb to sb0, and returns false, unless maxlength is not zero and
330 * appending would make the result longer than or equal to maxlength, in which
331 * case the append is not done and returns true
338 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
341 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
350 * Answers true if score should be shown, else false. Score is shown if it is
351 * not NaN, and the feature type has a non-trivial min-max score range
353 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
355 if (Float.isNaN(feature.getScore()))
363 float[][] minMax = fr.getMinMax().get(feature.getType());
366 * minMax[0] is the [min, max] score range for positional features
368 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
376 * Format and appends any hyperlinks for the sequence feature to the string
382 void appendLinks(final StringBuffer sb, SequenceFeature feature)
384 if (feature.links != null)
386 if (linkImageURL != null)
388 sb.append(" <img src=\"" + linkImageURL + "\">");
392 for (String urlstring : feature.links)
396 for (List<String> urllink : createLinksFrom(null, urlstring))
398 sb.append("<br/> <a href=\""
403 + (urllink.get(0).toLowerCase()
404 .equals(urllink.get(1).toLowerCase()) ? urllink
405 .get(0) : (urllink.get(0) + ":" + urllink
409 } catch (Exception x)
411 System.err.println("problem when creating links from "
425 * @return Collection< List<String> > { List<String> { link target, link
426 * label, dynamic component inserted (if any), url }}
428 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
430 Map<String, List<String>> urlSets = new LinkedHashMap<>();
431 UrlLink urlLink = new UrlLink(link);
432 if (!urlLink.isValid())
434 System.err.println(urlLink.getInvalidMessage());
438 urlLink.createLinksFromSeq(seq, urlSets);
440 return urlSets.values();
443 public void createSequenceAnnotationReport(final StringBuilder tip,
444 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
445 FeatureRendererModel fr)
447 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
452 * Builds an html formatted report of sequence details and appends it to the
456 * buffer to append report to
458 * the sequence the report is for
460 * whether to include database references for the sequence
462 * whether to include non-positional sequence features
467 int createSequenceAnnotationReport(final StringBuilder sb,
468 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
469 FeatureRendererModel fr, boolean summary)
475 if (sequence.getDescription() != null)
477 tmp = sequence.getDescription();
479 maxWidth = Math.max(maxWidth, tmp.length());
481 SequenceI ds = sequence;
482 while (ds.getDatasetSequence() != null)
484 ds = ds.getDatasetSequence();
489 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
493 * add non-positional features if wanted
497 for (SequenceFeature sf : sequence.getFeatures()
498 .getNonPositionalFeatures())
500 int sz = -sb.length();
501 appendFeature(sb, 0, fr, sf, null, 0);
503 maxWidth = Math.max(maxWidth, sz);
511 * A helper method that appends any DBRefs, returning the maximum line length
519 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
522 List<DBRefEntry> dbrefs = ds.getDBRefs();
528 // note this sorts the refs held on the sequence!
529 dbrefs.sort(comparator);
530 boolean ellipsis = false;
531 String source = null;
532 String lastSource = null;
533 int countForSource = 0;
535 boolean moreSources = false;
536 int maxLineLength = 0;
539 for (DBRefEntry ref : dbrefs)
541 source = ref.getSource();
547 boolean sourceChanged = !source.equals(lastSource);
554 if (sourceCount > MAX_SOURCES && summary)
562 if (countForSource == 1 || !summary)
566 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
568 String accessionId = ref.getAccessionId();
569 lineLength += accessionId.length() + 1;
570 if (countForSource > 1 && summary)
572 sb.append(", ").append(accessionId);
577 sb.append(source).append(" ").append(accessionId);
578 lineLength += source.length();
580 maxLineLength = Math.max(maxLineLength, lineLength);
582 if (countForSource == MAX_REFS_PER_SOURCE && summary)
584 sb.append(COMMA).append(ELLIPSIS);
590 sb.append("<br/>").append(source).append(COMMA).append(ELLIPSIS);
595 sb.append(MessageManager.getString("label.output_seq_details"));
599 return maxLineLength;
602 public void createTooltipAnnotationReport(final StringBuilder tip,
603 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
604 FeatureRendererModel fr)
606 int maxWidth = createSequenceAnnotationReport(tip, sequence,
607 showDbRefs, showNpFeats, fr, true);
611 // ? not sure this serves any useful purpose
612 // tip.insert(0, "<table width=350 border=0><tr><td>");
613 // tip.append("</td></tr></table>");