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;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Comparator;
28 import java.util.LinkedHashMap;
29 import java.util.List;
32 import com.google.common.collect.Lists;
34 import jalview.api.FeatureColourI;
35 import jalview.datamodel.DBRefEntry;
36 import jalview.datamodel.DBRefSource;
37 import jalview.datamodel.GeneLociI;
38 import jalview.datamodel.MappedFeatures;
39 import jalview.datamodel.SequenceFeature;
40 import jalview.datamodel.SequenceI;
41 import jalview.util.MessageManager;
42 import jalview.util.StringUtils;
43 import jalview.util.UrlLink;
44 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
47 * generate HTML reports for a sequence
51 public class SequenceAnnotationReport
53 private static final int MAX_DESCRIPTION_LENGTH = 40;
55 private static final String COMMA = ",";
57 private static final String ELLIPSIS = "...";
59 private static final int MAX_REFS_PER_SOURCE = 4;
61 private static final int MAX_SOURCES = 40;
63 private static String linkImageURL;
65 // public static final String[][] PRIMARY_SOURCES moved to DBRefSource.java
68 * Comparator to order DBRefEntry by Source + accession id (case-insensitive),
69 * with 'Primary' sources placed before others, and 'chromosome' first of all
71 private static Comparator<DBRefEntry> comparator = new Comparator<DBRefEntry>()
75 public int compare(DBRefEntry ref1, DBRefEntry ref2)
77 if (ref1 instanceof GeneLociI)
81 if (ref2 instanceof GeneLociI)
85 String s1 = ref1.getSource();
86 String s2 = ref2.getSource();
87 boolean s1Primary = DBRefSource.isPrimarySource(s1);
88 boolean s2Primary = DBRefSource.isPrimarySource(s2);
89 if (s1Primary && !s2Primary)
93 if (!s1Primary && s2Primary)
97 int comp = s1 == null ? -1
98 : (s2 == null ? 1 : s1.compareToIgnoreCase(s2));
101 String a1 = ref1.getAccessionId();
102 String a2 = ref2.getAccessionId();
103 comp = a1 == null ? -1
104 : (a2 == null ? 1 : a1.compareToIgnoreCase(a2));
109 // private boolean isPrimarySource(String source)
111 // for (String[] primary : DBRefSource.PRIMARY_SOURCES)
113 // for (String s : primary)
115 // if (source.equals(s))
125 private boolean forTooltip;
128 * Constructor given a flag which affects behaviour
130 * <li>if true, generates feature details suitable to show in a tooltip</li>
131 * <li>if false, generates feature details in a form suitable for the sequence
132 * details report</li>
135 * @param isForTooltip
137 public SequenceAnnotationReport(boolean isForTooltip)
139 this.forTooltip = isForTooltip;
140 if (linkImageURL == null)
142 linkImageURL = getClass().getResource("/images/link.gif").toString();
147 * Append text for the list of features to the tooltip. Returns the number of
148 * features not added if maxlength limit is (or would have been) reached.
156 public int appendFeatures(final StringBuilder sb, int residuePos,
157 List<SequenceFeature> features, FeatureRendererModel fr,
160 for (int i = 0; i < features.size(); i++)
162 SequenceFeature feature = features.get(i);
163 if (appendFeature(sb, residuePos, fr, feature, null, maxlength))
165 return features.size() - i;
172 * Appends text for mapped features (e.g. CDS feature for peptide or vice
173 * versa) Returns number of features left if maxlength limit is (or would have
182 public int appendFeatures(StringBuilder sb, int residuePos,
183 MappedFeatures mf, FeatureRendererModel fr, int maxlength)
185 for (int i = 0; i < mf.features.size(); i++)
187 SequenceFeature feature = mf.features.get(i);
188 if (appendFeature(sb, residuePos, fr, feature, mf, maxlength))
190 return mf.features.size() - i;
197 * Appends the feature at rpos to the given buffer
204 boolean appendFeature(final StringBuilder sb0, int rpos,
205 FeatureRendererModel fr, SequenceFeature feature,
206 MappedFeatures mf, int maxlength)
208 int begin = feature.getBegin();
209 int end = feature.getEnd();
212 * if this is a virtual features, convert begin/end to the
213 * coordinates of the sequence it is mapped to
215 int[] beginRange = null; // feature start in local coordinates
216 int[] endRange = null; // feature end in local coordinates
219 if (feature.isContactFeature())
222 * map start and end points individually
224 beginRange = mf.getMappedPositions(begin, begin);
225 endRange = begin == end ? beginRange
226 : mf.getMappedPositions(end, end);
231 * map the feature extent
233 beginRange = mf.getMappedPositions(begin, end);
234 endRange = beginRange;
236 if (beginRange == null || endRange == null)
238 // something went wrong
241 begin = beginRange[0];
242 end = endRange[endRange.length - 1];
245 StringBuilder sb = new StringBuilder();
246 if (feature.isContactFeature())
249 * include if rpos is at start or end position of [mapped] feature
251 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
252 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
253 && rpos <= beginRange[beginRange.length - 1])
254 || (rpos >= endRange[0]
255 && rpos <= endRange[endRange.length - 1]));
256 if (showContact || showMappedContact)
258 if (sb0.length() > 6)
262 sb.append(feature.getType()).append(" ").append(begin).append(":")
265 return appendText(sb0, sb, maxlength);
268 if (sb0.length() > 6)
272 // TODO: remove this hack to display link only features
273 boolean linkOnly = feature.getValue("linkonly") != null;
276 sb.append(feature.getType()).append(" ");
279 // we are marking a positional feature
283 sb.append(" ").append(end);
287 String description = feature.getDescription();
288 if (description != null && !description.equals(feature.getType()))
290 description = StringUtils.stripHtmlTags(description);
293 * truncate overlong descriptions unless they contain an href
294 * before the truncation point (as truncation could leave corrupted html)
296 int linkindex = description.toLowerCase(Locale.ROOT).indexOf("<a ");
297 boolean hasLink = linkindex > -1
298 && linkindex < MAX_DESCRIPTION_LENGTH;
299 if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
301 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
305 sb.append("; ").append(description);
308 if (showScore(feature, fr))
310 sb.append(" Score=").append(String.valueOf(feature.getScore()));
312 String status = (String) feature.getValue("status");
313 if (status != null && status.length() > 0)
315 sb.append("; (").append(status).append(")");
319 * add attribute value if coloured by attribute
323 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
324 if (fc != null && fc.isColourByAttribute())
326 String[] attName = fc.getAttributeName();
327 String attVal = feature.getValueAsString(attName);
330 sb.append("; ").append(String.join(":", attName)).append("=")
338 String variants = mf.findProteinVariants(feature);
339 if (!variants.isEmpty())
341 sb.append(" ").append(variants);
345 return appendText(sb0, sb, maxlength);
349 * Appends sb to sb0, and returns false, unless maxlength is not zero and
350 * appending would make the result longer than or equal to maxlength, in which
351 * case the append is not done and returns true
358 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
361 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
370 * Answers true if score should be shown, else false. Score is shown if it is
371 * not NaN, and the feature type has a non-trivial min-max score range
373 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
375 if (Float.isNaN(feature.getScore()))
383 float[][] minMax = fr.getMinMax().get(feature.getType());
386 * minMax[0] is the [min, max] score range for positional features
388 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
396 * Format and appends any hyperlinks for the sequence feature to the string
402 void appendLinks(final StringBuffer sb, SequenceFeature feature)
404 if (feature.links != null)
406 if (linkImageURL != null)
408 sb.append(" <img src=\"" + linkImageURL + "\">");
412 for (String urlstring : feature.links)
416 for (List<String> urllink : createLinksFrom(null, urlstring))
418 sb.append("<br/> <a href=\"" + urllink.get(3) + "\" target=\""
419 + urllink.get(0) + "\">"
420 + (urllink.get(0).toLowerCase(Locale.ROOT).equals(
421 urllink.get(1).toLowerCase(Locale.ROOT))
423 : (urllink.get(0) + ":"
427 } catch (Exception x)
430 "problem when creating links from " + urlstring);
443 * @return Collection< List<String> > { List<String> { link target, link
444 * label, dynamic component inserted (if any), url }}
446 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
448 Map<String, List<String>> urlSets = new LinkedHashMap<>();
449 UrlLink urlLink = new UrlLink(link);
450 if (!urlLink.isValid())
452 System.err.println(urlLink.getInvalidMessage());
456 urlLink.createLinksFromSeq(seq, urlSets);
458 return urlSets.values();
461 public void createSequenceAnnotationReport(final StringBuilder tip,
462 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
463 FeatureRendererModel fr)
465 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
470 * Builds an html formatted report of sequence details and appends it to the
474 * buffer to append report to
476 * the sequence the report is for
478 * whether to include database references for the sequence
480 * whether to include non-positional sequence features
485 int createSequenceAnnotationReport(final StringBuilder sb,
486 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
487 FeatureRendererModel fr, boolean summary)
493 if (sequence.getDescription() != null)
495 tmp = sequence.getDescription();
497 maxWidth = Math.max(maxWidth, tmp.length());
500 SequenceI ds = sequence;
501 while (ds.getDatasetSequence() != null)
503 ds = ds.getDatasetSequence();
508 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
513 * add non-positional features if wanted
517 for (SequenceFeature sf : sequence.getFeatures()
518 .getNonPositionalFeatures())
520 int sz = -sb.length();
521 appendFeature(sb, 0, fr, sf, null, 0);
523 maxWidth = Math.max(maxWidth, sz);
531 * A helper method that appends any DBRefs, returning the maximum line length
539 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
542 List<DBRefEntry> dbrefs,dbrefset = ds.getDBRefs();
544 if (dbrefset == null)
549 // PATCH for JAL-3980 defensive copy
551 dbrefs = new ArrayList<DBRefEntry>();
553 dbrefs.addAll(dbrefset);
555 // note this sorts the refs held on the sequence!
556 dbrefs.sort(comparator);
557 boolean ellipsis = false;
558 String source = null;
559 String lastSource = null;
560 int countForSource = 0;
562 boolean moreSources = false;
563 int maxLineLength = 0;
566 for (DBRefEntry ref : dbrefs)
568 source = ref.getSource();
574 boolean sourceChanged = !source.equals(lastSource);
581 if (sourceCount > MAX_SOURCES && summary)
589 if (countForSource == 1 || !summary)
591 sb.append("<br/>\n");
593 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
595 String accessionId = ref.getAccessionId();
596 lineLength += accessionId.length() + 1;
597 if (countForSource > 1 && summary)
599 sb.append(",\n ").append(accessionId);
604 sb.append(source).append(" ").append(accessionId);
605 lineLength += source.length();
607 maxLineLength = Math.max(maxLineLength, lineLength);
609 if (countForSource == MAX_REFS_PER_SOURCE && summary)
611 sb.append(COMMA).append(ELLIPSIS);
617 sb.append("<br/>\n").append(source).append(COMMA).append(ELLIPSIS);
621 sb.append("<br/>\n(");
622 sb.append(MessageManager.getString("label.output_seq_details"));
626 return maxLineLength;
629 public void createTooltipAnnotationReport(final StringBuilder tip,
630 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
631 FeatureRendererModel fr)
633 int maxWidth = createSequenceAnnotationReport(tip, sequence, showDbRefs,
634 showNpFeats, fr, true);
638 // ? not sure this serves any useful purpose
639 // tip.insert(0, "<table width=350 border=0><tr><td>");
640 // tip.append("</td></tr></table>");