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; // 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=\""
420 + (urllink.get(0).toLowerCase(Locale.ROOT)
421 .equals(urllink.get(1).toLowerCase(Locale.ROOT)) ? urllink
422 .get(0) : (urllink.get(0) + ":" + urllink
426 } catch (Exception x)
428 System.err.println("problem when creating links from "
442 * @return Collection< List<String> > { List<String> { link target, link
443 * label, dynamic component inserted (if any), url }}
445 Collection<List<String>> createLinksFrom(SequenceI seq, String link)
447 Map<String, List<String>> urlSets = new LinkedHashMap<>();
448 UrlLink urlLink = new UrlLink(link);
449 if (!urlLink.isValid())
451 System.err.println(urlLink.getInvalidMessage());
455 urlLink.createLinksFromSeq(seq, urlSets);
457 return urlSets.values();
460 public void createSequenceAnnotationReport(final StringBuilder tip,
461 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
462 FeatureRendererModel fr)
464 createSequenceAnnotationReport(tip, sequence, showDbRefs, showNpFeats,
469 * Builds an html formatted report of sequence details and appends it to the
473 * buffer to append report to
475 * the sequence the report is for
477 * whether to include database references for the sequence
479 * whether to include non-positional sequence features
484 int createSequenceAnnotationReport(final StringBuilder sb,
485 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
486 FeatureRendererModel fr, boolean summary)
492 if (sequence.getDescription() != null)
494 tmp = sequence.getDescription();
496 maxWidth = Math.max(maxWidth, tmp.length());
498 SequenceI ds = sequence;
499 while (ds.getDatasetSequence() != null)
501 ds = ds.getDatasetSequence();
506 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 = ds.getDBRefs();
545 // note this sorts the refs held on the sequence!
546 dbrefs.sort(comparator);
547 boolean ellipsis = false;
548 String source = null;
549 String lastSource = null;
550 int countForSource = 0;
552 boolean moreSources = false;
553 int maxLineLength = 0;
556 for (DBRefEntry ref : dbrefs)
558 source = ref.getSource();
564 boolean sourceChanged = !source.equals(lastSource);
571 if (sourceCount > MAX_SOURCES && summary)
579 if (countForSource == 1 || !summary)
583 if (countForSource <= MAX_REFS_PER_SOURCE || !summary)
585 String accessionId = ref.getAccessionId();
586 lineLength += accessionId.length() + 1;
587 if (countForSource > 1 && summary)
589 sb.append(", ").append(accessionId);
594 sb.append(source).append(" ").append(accessionId);
595 lineLength += source.length();
597 maxLineLength = Math.max(maxLineLength, lineLength);
599 if (countForSource == MAX_REFS_PER_SOURCE && summary)
601 sb.append(COMMA).append(ELLIPSIS);
607 sb.append("<br/>").append(source).append(COMMA).append(ELLIPSIS);
612 sb.append(MessageManager.getString("label.output_seq_details"));
616 return maxLineLength;
619 public void createTooltipAnnotationReport(final StringBuilder tip,
620 SequenceI sequence, boolean showDbRefs, boolean showNpFeats,
621 FeatureRendererModel fr)
623 int maxWidth = createSequenceAnnotationReport(tip, sequence,
624 showDbRefs, showNpFeats, fr, true);
628 // ? not sure this serves any useful purpose
629 // tip.insert(0, "<table width=350 border=0><tr><td>");
630 // tip.append("</td></tr></table>");