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.
21 package jalview.viewmodel.seqfeatures;
23 import jalview.api.AlignViewportI;
24 import jalview.api.FeatureColourI;
25 import jalview.api.FeaturesDisplayedI;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.datamodel.features.SequenceFeatures;
30 import jalview.renderer.seqfeatures.FeatureRenderer;
31 import jalview.schemes.FeatureColour;
32 import jalview.util.ColorUtils;
33 import jalview.util.matcher.KeyedMatcherSetI;
35 import java.awt.Color;
36 import java.beans.PropertyChangeListener;
37 import java.beans.PropertyChangeSupport;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Hashtable;
43 import java.util.Iterator;
44 import java.util.List;
47 import java.util.concurrent.ConcurrentHashMap;
49 public abstract class FeatureRendererModel
50 implements jalview.api.FeatureRenderer
54 * global transparency for feature
56 protected float transparency = 1.0f;
59 * colour scheme for each feature type
61 protected Map<String, FeatureColourI> featureColours = new ConcurrentHashMap<>();
64 * visibility flag for each feature group
66 protected Map<String, Boolean> featureGroups = new ConcurrentHashMap<>();
69 * filters for each feature type
71 protected Map<String, KeyedMatcherSetI> featureFilters = new HashMap<>();
73 protected String[] renderOrder;
75 Map<String, Float> featureOrder = null;
77 protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
80 protected AlignViewportI av;
83 public AlignViewportI getViewport()
88 public FeatureRendererSettings getSettings()
90 return new FeatureRendererSettings(this);
93 public void transferSettings(FeatureRendererSettings fr)
95 this.renderOrder = fr.renderOrder;
96 this.featureGroups = fr.featureGroups;
97 this.featureColours = fr.featureColours;
98 this.transparency = fr.transparency;
99 this.featureOrder = fr.featureOrder;
103 * update from another feature renderer
108 public void transferSettings(jalview.api.FeatureRenderer _fr)
110 FeatureRenderer fr = (FeatureRenderer) _fr;
111 FeatureRendererSettings frs = new FeatureRendererSettings(fr);
112 this.renderOrder = frs.renderOrder;
113 this.featureGroups = frs.featureGroups;
114 this.featureColours = frs.featureColours;
115 this.featureFilters = frs.featureFilters;
116 this.transparency = frs.transparency;
117 this.featureOrder = frs.featureOrder;
118 if (av != null && av != fr.getViewport())
120 // copy over the displayed feature settings
121 if (_fr.getFeaturesDisplayed() != null)
123 FeaturesDisplayedI fd = getFeaturesDisplayed();
126 setFeaturesDisplayedFrom(_fr.getFeaturesDisplayed());
133 for (String type : _fr.getFeaturesDisplayed()
134 .getVisibleFeatures())
144 public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
146 av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
150 public void setVisible(String featureType)
152 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
155 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
157 if (!fdi.isRegistered(featureType))
159 pushFeatureType(Arrays.asList(new String[] { featureType }));
161 fdi.setVisible(featureType);
165 public void setAllVisible(List<String> featureTypes)
167 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
170 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
172 List<String> nft = new ArrayList<String>();
173 for (String featureType : featureTypes)
175 if (!fdi.isRegistered(featureType))
177 nft.add(featureType);
182 pushFeatureType(nft);
184 fdi.setAllVisible(featureTypes);
188 * push a set of new types onto the render order stack. Note - this is a
189 * direct mechanism rather than the one employed in updateRenderOrder
193 private void pushFeatureType(List<String> types)
196 int ts = types.size();
197 String neworder[] = new String[(renderOrder == null ? 0
198 : renderOrder.length) + ts];
199 types.toArray(neworder);
200 if (renderOrder != null)
202 System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
203 System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
205 renderOrder = neworder;
208 protected Map<String, float[][]> minmax = new Hashtable<String, float[][]>();
210 public Map<String, float[][]> getMinMax()
216 * normalise a score against the max/min bounds for the feature type.
218 * @param sequenceFeature
219 * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
222 protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
224 float[] mm = minmax.get(sequenceFeature.type)[0];
225 final byte[] r = new byte[] { 0, (byte) 255 };
228 if (r[0] != 0 || mm[0] < 0.0)
231 r[1] = (byte) ((int) 128.0
232 + 127.0 * (sequenceFeature.score / mm[1]));
236 r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
242 boolean newFeatureAdded = false;
244 boolean findingFeatures = false;
246 protected boolean updateFeatures()
248 if (av.getFeaturesDisplayed() == null || renderOrder == null
252 if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
257 // TODO: decide if we should check for the visible feature count first
262 * search the alignment for all new features, give them a colour and display
263 * them. Then fires a PropertyChangeEvent on the changeSupport object.
266 protected void findAllFeatures()
268 synchronized (firing)
270 if (firing.equals(Boolean.FALSE))
272 firing = Boolean.TRUE;
273 findAllFeatures(true); // add all new features as visible
274 changeSupport.firePropertyChange("changeSupport", null, null);
275 firing = Boolean.FALSE;
281 public List<SequenceFeature> findFeaturesAtColumn(SequenceI sequence, int column)
284 * include features at the position provided their feature type is
285 * displayed, and feature group is null or marked for display
287 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
288 if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
293 Set<String> visibleFeatures = getFeaturesDisplayed()
294 .getVisibleFeatures();
295 String[] visibleTypes = visibleFeatures
296 .toArray(new String[visibleFeatures.size()]);
297 List<SequenceFeature> features = sequence.findFeatures(column, column,
300 for (SequenceFeature sf : features)
302 if (!featureGroupNotShown(sf))
311 * Searches alignment for all features and updates colours
313 * @param newMadeVisible
314 * if true newly added feature types will be rendered immediately
315 * TODO: check to see if this method should actually be proxied so
316 * repaint events can be propagated by the renderer code
319 public synchronized void findAllFeatures(boolean newMadeVisible)
321 newFeatureAdded = false;
325 newFeatureAdded = true;
329 findingFeatures = true;
330 if (av.getFeaturesDisplayed() == null)
332 av.setFeaturesDisplayed(new FeaturesDisplayed());
334 FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
336 Set<String> oldfeatures = new HashSet<String>();
337 if (renderOrder != null)
339 for (int i = 0; i < renderOrder.length; i++)
341 if (renderOrder[i] != null)
343 oldfeatures.add(renderOrder[i]);
348 AlignmentI alignment = av.getAlignment();
349 List<String> allfeatures = new ArrayList<String>();
351 for (int i = 0; i < alignment.getHeight(); i++)
353 SequenceI asq = alignment.getSequenceAt(i);
354 for (String group : asq.getFeatures().getFeatureGroups(true))
356 boolean groupDisplayed = true;
359 if (featureGroups.containsKey(group))
361 groupDisplayed = featureGroups.get(group);
365 groupDisplayed = newMadeVisible;
366 featureGroups.put(group, groupDisplayed);
371 Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
373 for (String type : types)
375 if (!allfeatures.contains(type)) // or use HashSet and no test?
377 allfeatures.add(type);
379 updateMinMax(asq, type, true); // todo: for all features?
385 // uncomment to add new features in alphebetical order (but JAL-2575)
386 // Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
389 for (String type : allfeatures)
391 if (!oldfeatures.contains(type))
393 featuresDisplayed.setVisible(type);
399 updateRenderOrder(allfeatures);
400 findingFeatures = false;
404 * Updates the global (alignment) min and max values for a feature type from
405 * the score for a sequence, if the score is not NaN. Values are stored
406 * separately for positional and non-positional features.
412 protected void updateMinMax(SequenceI seq, String featureType,
415 float min = seq.getFeatures().getMinimumScore(featureType, positional);
416 if (Float.isNaN(min))
421 float max = seq.getFeatures().getMaximumScore(featureType, positional);
425 * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
429 minmax = new Hashtable<String, float[][]>();
431 synchronized (minmax)
433 float[][] mm = minmax.get(featureType);
434 int index = positional ? 0 : 1;
437 mm = new float[][] { null, null };
438 minmax.put(featureType, mm);
440 if (mm[index] == null)
442 mm[index] = new float[] { min, max };
446 mm[index][0] = Math.min(mm[index][0], min);
447 mm[index][1] = Math.max(mm[index][1], max);
451 protected Boolean firing = Boolean.FALSE;
454 * replaces the current renderOrder with the unordered features in
455 * allfeatures. The ordering of any types in both renderOrder and allfeatures
456 * is preserved, and all new feature types are rendered on top of the existing
457 * types, in the order given by getOrder or the order given in allFeatures.
458 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
459 * eliminate the float storage for computing/recalling the persistent ordering
460 * New Cability: updates min/max for colourscheme range if its dynamic
464 private void updateRenderOrder(List<String> allFeatures)
466 List<String> allfeatures = new ArrayList<String>(allFeatures);
467 String[] oldRender = renderOrder;
468 renderOrder = new String[allfeatures.size()];
469 boolean initOrders = (featureOrder == null);
471 if (oldRender != null && oldRender.length > 0)
473 for (int j = 0; j < oldRender.length; j++)
475 if (oldRender[j] != null)
479 setOrder(oldRender[j],
480 (1 - (1 + (float) j) / oldRender.length));
482 if (allfeatures.contains(oldRender[j]))
484 renderOrder[opos++] = oldRender[j]; // existing features always
485 // appear below new features
486 allfeatures.remove(oldRender[j]);
489 float[][] mmrange = minmax.get(oldRender[j]);
492 FeatureColourI fc = featureColours.get(oldRender[j]);
493 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
494 && !fc.isColourByAttribute())
496 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
504 if (allfeatures.size() == 0)
506 // no new features - leave order unchanged.
509 int i = allfeatures.size() - 1;
511 boolean sort = false;
512 String[] newf = new String[allfeatures.size()];
513 float[] sortOrder = new float[allfeatures.size()];
514 for (String newfeat : allfeatures)
519 // update from new features minmax if necessary
520 float[][] mmrange = minmax.get(newf[i]);
523 FeatureColourI fc = featureColours.get(newf[i]);
524 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
525 && !fc.isColourByAttribute())
527 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
531 if (initOrders || !featureOrder.containsKey(newf[i]))
533 int denom = initOrders ? allfeatures.size() : featureOrder.size();
534 // new unordered feature - compute persistent ordering at head of
535 // existing features.
536 setOrder(newf[i], i / (float) denom);
538 // set order from newly found feature from persisted ordering.
539 sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
542 // only sort if we need to
543 sort = sort || sortOrder[i] > sortOrder[i + 1];
547 if (iSize > 1 && sort)
549 jalview.util.QuickSort.sort(sortOrder, newf);
552 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
556 * get a feature style object for the given type string. Creates a
557 * java.awt.Color for a featureType with no existing colourscheme.
563 public FeatureColourI getFeatureStyle(String featureType)
565 FeatureColourI fc = featureColours.get(featureType);
568 Color col = ColorUtils.createColourFromName(featureType);
569 fc = new FeatureColour(col);
570 featureColours.put(featureType, fc);
576 public Color getColour(SequenceFeature feature)
578 FeatureColourI fc = getFeatureStyle(feature.getType());
579 return getColor(feature, fc);
583 * Answers true if the feature type is currently selected to be displayed,
589 protected boolean showFeatureOfType(String type)
591 return type == null ? false : (av.getFeaturesDisplayed() == null ? true
592 : av.getFeaturesDisplayed().isVisible(type));
596 public void setColour(String featureType, FeatureColourI col)
598 featureColours.put(featureType, col);
602 public void setTransparency(float value)
604 transparency = value;
608 public float getTransparency()
614 * analogous to colour - store a normalized ordering for all feature types in
615 * this rendering context.
618 * Feature type string
620 * normalized priority - 0 means always appears on top, 1 means
623 public float setOrder(String type, float position)
625 if (featureOrder == null)
627 featureOrder = new Hashtable<String, Float>();
629 featureOrder.put(type, new Float(position));
634 * get the global priority (0 (top) to 1 (bottom))
637 * @return [0,1] or -1 for a type without a priority
639 public float getOrder(String type)
641 if (featureOrder != null)
643 if (featureOrder.containsKey(type))
645 return featureOrder.get(type).floatValue();
652 public Map<String, FeatureColourI> getFeatureColours()
654 return featureColours;
658 * Replace current ordering with new ordering
661 * { String(Type), Colour(Type), Boolean(Displayed) }
662 * @return true if any visible features have been reordered, else false
664 public boolean setFeaturePriority(Object[][] data)
666 return setFeaturePriority(data, true);
670 * Sets the priority order for features, with the highest priority (displayed
671 * on top) at the start of the data array
674 * { String(Type), Colour(Type), Boolean(Displayed) }
676 * when true current featureDisplay list will be cleared
677 * @return true if any visible features have been reordered or recoloured,
678 * else false (i.e. no need to repaint)
680 public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
683 * note visible feature ordering and colours before update
685 List<String> visibleFeatures = getDisplayedFeatureTypes();
686 Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
687 getFeatureColours());
689 FeaturesDisplayedI av_featuresdisplayed = null;
692 if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
694 av.getFeaturesDisplayed().clear();
698 av.setFeaturesDisplayed(
699 av_featuresdisplayed = new FeaturesDisplayed());
704 av_featuresdisplayed = av.getFeaturesDisplayed();
710 // The feature table will display high priority
711 // features at the top, but these are the ones
712 // we need to render last, so invert the data
713 renderOrder = new String[data.length];
717 for (int i = 0; i < data.length; i++)
719 String type = data[i][0].toString();
720 setColour(type, (FeatureColourI) data[i][1]);
721 if (((Boolean) data[i][2]).booleanValue())
723 av_featuresdisplayed.setVisible(type);
726 renderOrder[data.length - i - 1] = type;
731 * get the new visible ordering and return true if it has changed
732 * order or any colour has changed
734 List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
735 if (!visibleFeatures.equals(reorderedVisibleFeatures))
738 * the list of ordered visible features has changed
744 * return true if any feature colour has changed
746 for (String feature : visibleFeatures)
748 if (visibleColours.get(feature) != getFeatureStyle(feature))
758 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
760 public void addPropertyChangeListener(PropertyChangeListener listener)
762 changeSupport.addPropertyChangeListener(listener);
767 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
769 public void removePropertyChangeListener(PropertyChangeListener listener)
771 changeSupport.removePropertyChangeListener(listener);
774 public Set<String> getAllFeatureColours()
776 return featureColours.keySet();
779 public void clearRenderOrder()
784 public boolean hasRenderOrder()
786 return renderOrder != null;
790 * Returns feature types in ordering of rendering, where last means on top
792 public List<String> getRenderOrder()
794 if (renderOrder == null)
796 return Arrays.asList(new String[] {});
798 return Arrays.asList(renderOrder);
801 public int getFeatureGroupsSize()
803 return featureGroups != null ? 0 : featureGroups.size();
807 public List<String> getFeatureGroups()
809 // conflict between applet and desktop - featureGroups returns the map in
810 // the desktop featureRenderer
811 return (featureGroups == null) ? Arrays.asList(new String[0])
812 : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
815 public boolean checkGroupVisibility(String group,
816 boolean newGroupsVisible)
818 if (featureGroups == null)
820 // then an exception happens next..
822 if (featureGroups.containsKey(group))
824 return featureGroups.get(group).booleanValue();
826 if (newGroupsVisible)
828 featureGroups.put(group, new Boolean(true));
835 * get visible or invisible groups
838 * true to return visible groups, false to return hidden ones.
839 * @return list of groups
842 public List<String> getGroups(boolean visible)
844 if (featureGroups != null)
846 List<String> gp = new ArrayList<String>();
848 for (String grp : featureGroups.keySet())
850 Boolean state = featureGroups.get(grp);
851 if (state.booleanValue() == visible)
862 public void setGroupVisibility(String group, boolean visible)
864 featureGroups.put(group, new Boolean(visible));
868 public void setGroupVisibility(List<String> toset, boolean visible)
870 if (toset != null && toset.size() > 0 && featureGroups != null)
872 boolean rdrw = false;
873 for (String gst : toset)
875 Boolean st = featureGroups.get(gst);
876 featureGroups.put(gst, new Boolean(visible));
879 rdrw = rdrw || (visible != st.booleanValue());
884 // set local flag indicating redraw needed ?
890 public Map<String, FeatureColourI> getDisplayedFeatureCols()
892 Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
893 if (getViewport().getFeaturesDisplayed() == null)
897 Set<String> features = getViewport().getFeaturesDisplayed()
898 .getVisibleFeatures();
899 for (String feature : features)
901 fcols.put(feature, getFeatureStyle(feature));
907 public FeaturesDisplayedI getFeaturesDisplayed()
909 return av.getFeaturesDisplayed();
913 * Returns a (possibly empty) list of visible feature types, in render order
917 public List<String> getDisplayedFeatureTypes()
919 List<String> typ = getRenderOrder();
920 List<String> displayed = new ArrayList<String>();
921 FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
922 if (feature_disp != null)
924 synchronized (feature_disp)
926 for (String type : typ)
928 if (feature_disp.isVisible(type))
939 public List<String> getDisplayedFeatureGroups()
941 List<String> _gps = new ArrayList<String>();
942 for (String gp : getFeatureGroups())
944 if (checkGroupVisibility(gp, false))
953 * Answers true if the feature belongs to a feature group which is not
954 * currently displayed, else false
956 * @param sequenceFeature
959 protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
961 return featureGroups != null
962 && sequenceFeature.featureGroup != null
963 && sequenceFeature.featureGroup.length() != 0
964 && featureGroups.containsKey(sequenceFeature.featureGroup)
965 && !featureGroups.get(sequenceFeature.featureGroup)
973 public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
976 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
977 if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
983 * include features at the position provided their feature type is
984 * displayed, and feature group is null or the empty string
985 * or marked for display
987 Set<String> visibleFeatures = getFeaturesDisplayed()
988 .getVisibleFeatures();
989 String[] visibleTypes = visibleFeatures
990 .toArray(new String[visibleFeatures.size()]);
991 List<SequenceFeature> features = sequence.getFeatures().findFeatures(
992 resNo, resNo, visibleTypes);
994 for (SequenceFeature sf : features)
996 if (!featureGroupNotShown(sf))
1005 * Removes from the list of features any that duplicate the location of a
1006 * feature of the same type. Should be used only for features of the same,
1007 * simple, feature colour (which normally implies the same feature type). Does
1008 * not check visibility settings for feature type or feature group.
1012 public void filterFeaturesForDisplay(List<SequenceFeature> features)
1014 if (features.isEmpty())
1018 SequenceFeatures.sortFeatures(features, true);
1019 SequenceFeature lastFeature = null;
1021 Iterator<SequenceFeature> it = features.iterator();
1022 while (it.hasNext())
1024 SequenceFeature sf = it.next();
1027 * a feature is redundant for rendering purposes if it has the
1028 * same extent as another (so would just redraw the same colour);
1029 * (checking type and isContactFeature as a fail-safe here, although
1030 * currently they are guaranteed to match in this context)
1032 if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1033 && sf.getEnd() == lastFeature.getEnd()
1034 && sf.isContactFeature() == lastFeature.isContactFeature()
1035 && sf.getType().equals(lastFeature.getType()))
1044 public Map<String, KeyedMatcherSetI> getFeatureFilters()
1046 return new HashMap<>(featureFilters);
1050 public void setFeatureFilters(Map<String, KeyedMatcherSetI> filters)
1052 featureFilters = filters;
1056 public KeyedMatcherSetI getFeatureFilter(String featureType)
1058 return featureFilters.get(featureType);
1062 public void setFeatureFilter(String featureType, KeyedMatcherSetI filter)
1064 if (filter == null || filter.isEmpty())
1066 featureFilters.remove(featureType);
1070 featureFilters.put(featureType, filter);
1075 * Answers the colour for the feature, or null if the feature is excluded by
1076 * feature type or group visibility, by filters, or by colour threshold
1083 public Color getColor(SequenceFeature sf, FeatureColourI fc)
1086 * is the feature type displayed?
1088 if (!showFeatureOfType(sf.getType()))
1094 * is the feature group displayed?
1096 if (featureGroupNotShown(sf))
1102 * does the feature pass filters?
1104 if (!featureMatchesFilters(sf))
1109 return fc.getColor(sf);
1113 * Answers true if there no are filters defined for the feature type, or this
1114 * feature matches the filters. Answers false if the feature fails to match
1120 protected boolean featureMatchesFilters(SequenceFeature sf)
1122 KeyedMatcherSetI filter = featureFilters.get(sf.getType());
1123 return filter == null ? true : filter.matches(key -> sf
1124 .getValueAsString(key));