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 = 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
95 : (s2 == null ? 1 : s1.compareToIgnoreCase(s2));
98 String a1 = ref1.getAccessionId();
99 String a2 = ref2.getAccessionId();
100 comp = a1 == null ? -1
101 : (a2 == null ? 1 : a1.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, int residuePos,
154 List<SequenceFeature> features, FeatureRendererModel fr,
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; // feature start in local coordinates
213 int[] endRange = null; // feature end in local coordinates
216 if (feature.isContactFeature())
219 * map start and end points individually
221 beginRange = mf.getMappedPositions(begin, begin);
222 endRange = begin == end ? beginRange
223 : mf.getMappedPositions(end, end);
228 * map the feature extent
230 beginRange = mf.getMappedPositions(begin, end);
231 endRange = beginRange;
233 if (beginRange == null || endRange == null)
235 // something went wrong
238 begin = beginRange[0];
239 end = endRange[endRange.length - 1];
242 StringBuilder sb = new StringBuilder();
243 if (feature.isContactFeature())
246 * include if rpos is at start or end position of [mapped] feature
248 boolean showContact = (mf == null) && (rpos == begin || rpos == end);
249 boolean showMappedContact = (mf != null) && ((rpos >= beginRange[0]
250 && rpos <= beginRange[beginRange.length - 1])
251 || (rpos >= endRange[0]
252 && rpos <= endRange[endRange.length - 1]));
253 if (showContact || showMappedContact)
255 if (sb0.length() > 6)
259 sb.append(feature.getType()).append(" ").append(begin).append(":")
262 return appendText(sb0, sb, maxlength);
265 if (sb0.length() > 6)
269 // TODO: remove this hack to display link only features
270 boolean linkOnly = feature.getValue("linkonly") != null;
273 sb.append(feature.getType()).append(" ");
276 // we are marking a positional feature
280 sb.append(" ").append(end);
284 String description = feature.getDescription();
285 if (description != null && !description.equals(feature.getType()))
287 description = StringUtils.stripHtmlTags(description);
290 * truncate overlong descriptions unless they contain an href
291 * before the truncation point (as truncation could leave corrupted html)
293 int linkindex = description.toLowerCase(Locale.ROOT).indexOf("<a ");
294 boolean hasLink = linkindex > -1
295 && linkindex < MAX_DESCRIPTION_LENGTH;
296 if (description.length() > MAX_DESCRIPTION_LENGTH && !hasLink)
298 description = description.substring(0, MAX_DESCRIPTION_LENGTH)
302 sb.append("; ").append(description);
305 if (showScore(feature, fr))
307 sb.append(" Score=").append(String.valueOf(feature.getScore()));
309 String status = (String) feature.getValue("status");
310 if (status != null && status.length() > 0)
312 sb.append("; (").append(status).append(")");
316 * add attribute value if coloured by attribute
320 FeatureColourI fc = fr.getFeatureColours().get(feature.getType());
321 if (fc != null && fc.isColourByAttribute())
323 String[] attName = fc.getAttributeName();
324 String attVal = feature.getValueAsString(attName);
327 sb.append("; ").append(String.join(":", attName)).append("=")
335 String variants = mf.findProteinVariants(feature);
336 if (!variants.isEmpty())
338 sb.append(" ").append(variants);
342 return appendText(sb0, sb, maxlength);
346 * Appends sb to sb0, and returns false, unless maxlength is not zero and
347 * appending would make the result longer than or equal to maxlength, in which
348 * case the append is not done and returns true
355 private static boolean appendText(StringBuilder sb0, StringBuilder sb,
358 if (maxlength == 0 || sb0.length() + sb.length() < maxlength)
367 * Answers true if score should be shown, else false. Score is shown if it is
368 * not NaN, and the feature type has a non-trivial min-max score range
370 boolean showScore(SequenceFeature feature, FeatureRendererModel fr)
372 if (Float.isNaN(feature.getScore()))
380 float[][] minMax = fr.getMinMax().get(feature.getType());
383 * minMax[0] is the [min, max] score range for positional features
385 if (minMax == null || minMax[0] == null || minMax[0][0] == minMax[0][1])
393 * Format and appends any hyperlinks for the sequence feature to the string
399 void appendLinks(final StringBuffer sb, SequenceFeature feature)
401 if (feature.links != null)
403 if (linkImageURL != null)
405 sb.append(" <img src=\"" + linkImageURL + "\">");
409 for (String urlstring : feature.links)
413 for (List<String> urllink : createLinksFrom(null, urlstring))
415 sb.append("<br/> <a href=\"" + urllink.get(3) + "\" target=\""
416 + urllink.get(0) + "\">"
417 + (urllink.get(0).toLowerCase(Locale.ROOT).equals(
418 urllink.get(1).toLowerCase(Locale.ROOT))
420 : (urllink.get(0) + ":"
424 } catch (Exception x)
427 "problem when creating links from " + urlstring);
440 * @return Collection< List<String> > { List<String> { link target, link
441 * label, dynamic component inserted (if any), url }}
443 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
445 Map<String, List<String>> urlSets = new LinkedHashMap<>();
446 UrlLink urlLink = new UrlLink(link);
447 if (!urlLink.isValid())
449 System.err.println(urlLink.getInvalidMessage());
453 urlLink.createLinksFromSeq(seq, urlSets);
455 return urlSets.values();
458 public void createSequenceAnnotationReport(final StringBuilder tip,
459 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
460 FeatureRendererModel fr)
462 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
467 * Builds an html formatted report of sequence details and appends it to the
471 * buffer to append report to
473 * the sequence the report is for
475 * whether to include database references for the sequence
477 * whether to include non-positional sequence features
482 int createSequenceAnnotationReport(final StringBuilder sb,
483 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
484 FeatureRendererModel fr, boolean summary)
490 if (sequence.getDescription() != null)
492 tmp = sequence.getDescription();
494 maxWidth = Math.max(maxWidth, tmp.length());
497 SequenceI ds = sequence;
498 while (ds.getDatasetSequence() != null)
500 ds = ds.getDatasetSequence();
505 maxWidth = Math.max(maxWidth, appendDbRefs(sb, ds, summary));
510 * add non-positional features if wanted
514 for (SequenceFeature sf : sequence.getFeatures()
515 .getNonPositionalFeatures())
517 int sz = -sb.length();
518 appendFeature(sb, 0, fr, sf, null, 0);
520 maxWidth = Math.max(maxWidth, sz);
528 * A helper method that appends any DBRefs, returning the maximum line length
536 protected int appendDbRefs(final StringBuilder sb, SequenceI ds,
539 List<DBRefEntry> dbrefs, dbrefset = ds.getDBRefs();
541 if (dbrefset == null)
546 // PATCH for JAL-3980 defensive copy
548 dbrefs = new ArrayList<DBRefEntry>();
550 dbrefs.addAll(dbrefset);
552 // note this sorts the refs held on the sequence!
553 dbrefs.sort(comparator);
554 boolean ellipsis = false;
555 String source = null;
556 String lastSource = null;
557 int countForSource = 0;
559 boolean moreSources = false;
560 int maxLineLength = 0;
563 for (DBRefEntry ref : dbrefs)
565 source = ref.getSource();
571 boolean sourceChanged = !source.equals(lastSource);
578 if (sourceCount > MAX_SOURCES && summary)
586 if (countForSource == 1 || !summary)
588 sb.append("<br/>\n");
590 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
592 String accessionId = ref.getAccessionId();
593 lineLength += accessionId.length() + 1;
594 if (countForSource > 1 && summary)
596 sb.append(",\n ").append(accessionId);
601 sb.append(source).append(" ").append(accessionId);
602 lineLength += source.length();
604 maxLineLength = Math.max(maxLineLength, lineLength);
606 if (countForSource == MAX_REFS_PER_SOURCE && summary)
608 sb.append(COMMA).append(ELLIPSIS);
614 sb.append("<br/>\n").append(source).append(COMMA).append(ELLIPSIS);
618 sb.append("<br/>\n(");
619 sb.append(MessageManager.getString("label.output_seq_details"));
623 return maxLineLength;
626 public void createTooltipAnnotationReport(final StringBuilder tip,
627 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
628 FeatureRendererModel fr)
630 int maxWidth = createSequenceAnnotationReport(tip, sequence, showDbRefs,
631 showNpFeats, fr, true);
635 // ? not sure this serves any useful purpose
636 // tip.insert(0, "<table width=350 border=0><tr><td>");
637 // tip.append("</td></tr></table>");