summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/visualization/visualizers/visunproj/OPTICSClusterVisualization.java
blob: 666d45183ae2652c399eab2adaf167bd3cac9b1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package de.lmu.ifi.dbs.elki.visualization.visualizers.visunproj;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures

Copyright (C) 2011
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.util.Collection;
import java.util.List;

import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;

import de.lmu.ifi.dbs.elki.data.Cluster;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.data.model.OPTICSModel;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.result.HierarchicalResult;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.result.SelectionResult;
import de.lmu.ifi.dbs.elki.result.optics.ClusterOrderResult;
import de.lmu.ifi.dbs.elki.visualization.css.CSSClass;
import de.lmu.ifi.dbs.elki.visualization.opticsplot.OPTICSPlot;
import de.lmu.ifi.dbs.elki.visualization.projections.Projection;
import de.lmu.ifi.dbs.elki.visualization.style.StyleLibrary;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil;
import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisFactory;
import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisualization;
import de.lmu.ifi.dbs.elki.visualization.visualizers.Visualization;
import de.lmu.ifi.dbs.elki.visualization.visualizers.VisualizationTask;

/**
 * Visualize the clusters and cluster hierarchy found by OPTICS on the OPTICS
 * Plot.
 * 
 * @author Erich Schubert
 * 
 * @apiviz.uses ClusterOrderResult
 * @apiviz.uses OPTICSPlot
 */
public class OPTICSClusterVisualization extends AbstractVisualization {
  /**
   * The logger for this class.
   */
  private static final Logging logger = Logging.getLogger(OPTICSClusterVisualization.class);

  /**
   * A short name characterizing this Visualizer.
   */
  private static final String NAME = "OPTICS Cluster Range";

  /**
   * CSS class for markers
   */
  protected static final String CSS_BRACKET = "opticsBracket";

  /**
   * Our cluster order
   */
  private ClusterOrderResult<?> co;

  /**
   * Our clustering
   */
  Clustering<OPTICSModel> clus;

  /**
   * The plot
   */
  private OPTICSPlot<?> opticsplot;

  /**
   * Constructor.
   * 
   * @param task Visualization task
   */
  public OPTICSClusterVisualization(VisualizationTask task) {
    super(task);
    this.co = task.getResult();
    this.clus = findOPTICSClustering(this.co);
    this.opticsplot = OPTICSPlot.plotForClusterOrder(this.co, context);
    context.addResultListener(this);
    incrementalRedraw();
  }

  /**
   * Find the OPTICS clustering child of a cluster order.
   * 
   * @param co Cluster order
   * @return OPTICS clustering
   */
  @SuppressWarnings("unchecked")
  protected static Clustering<OPTICSModel> findOPTICSClustering(ClusterOrderResult<?> co) {
    for(Result r : co.getHierarchy().getChildren(co)) {
      if(!Clustering.class.isInstance(r)) {
        continue;
      }
      Clustering<?> clus = (Clustering<?>) r;
      if(clus.getToplevelClusters().size() == 0) {
        continue;
      }
      Cluster<?> firstcluster = clus.getToplevelClusters().iterator().next();
      if(firstcluster.getModel() instanceof OPTICSModel) {
        return (Clustering<OPTICSModel>) clus;
      }
    }
    return null;
  }

  @Override
  protected void redraw() {
    final double scale = StyleLibrary.SCALE;
    final double sizex = scale;
    final double sizey = scale * task.getHeight() / task.getWidth();
    final double margin = context.getStyleLibrary().getSize(StyleLibrary.MARGIN);
    layer = SVGUtil.svgElement(svgp.getDocument(), SVGConstants.SVG_G_TAG);
    final String transform = SVGUtil.makeMarginTransform(task.getWidth(), task.getHeight(), sizex, sizey, margin);
    SVGUtil.setAtt(layer, SVGConstants.SVG_TRANSFORM_ATTRIBUTE, transform);

    addCSSClasses();

    drawClusters(scale, scale / opticsplot.getRatio(), clus.getToplevelClusters(), 1);
  }

  /**
   * Recursively draw clusters
   * 
   * @param sizex Width
   * @param sizey Height of optics plot
   * @param clusters Current set of clusters
   * @param depth Recursion depth
   */
  private void drawClusters(double sizex, double sizey, List<Cluster<OPTICSModel>> clusters, int depth) {
    final double scale = StyleLibrary.SCALE;
    for(Cluster<OPTICSModel> cluster : clusters) {
      try {
        OPTICSModel model = cluster.getModel();
        final double x1 = sizex * ((model.getStartIndex() + .25) / this.co.getClusterOrder().size());
        final double x2 = sizex * ((model.getEndIndex() + .75) / this.co.getClusterOrder().size());
        final double y = sizey + depth * scale * 0.01;
        Element e = svgp.svgLine(x1, y, x2, y);
        SVGUtil.addCSSClass(e, CSS_BRACKET);
        layer.appendChild(e);
      }
      catch(ClassCastException e) {
        logger.warning("Expected OPTICSModel, got: " + cluster.getModel().getClass().getSimpleName());
      }
      // Descend
      final List<Cluster<OPTICSModel>> children = cluster.getChildren();
      if(children != null) {
        drawClusters(sizex, sizey, children, depth + 1);
      }
    }
  }

  /**
   * Adds the required CSS-Classes
   */
  private void addCSSClasses() {
    // Class for the markers
    if(!svgp.getCSSClassManager().contains(CSS_BRACKET)) {
      final CSSClass cls = new CSSClass(this, CSS_BRACKET);
      cls.setStatement(SVGConstants.CSS_STROKE_PROPERTY, context.getStyleLibrary().getColor(StyleLibrary.PLOT));
      cls.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, context.getStyleLibrary().getLineWidth(StyleLibrary.PLOT));
      svgp.addCSSClassOrLogError(cls);
    }
  }

  @Override
  public void resultChanged(Result current) {
    if(current instanceof SelectionResult || current == co || current == opticsplot) {
      synchronizedRedraw();
      return;
    }
    super.resultChanged(current);
  }

  /**
   * Factory class for OPTICS plot selections.
   * 
   * @author Erich Schubert
   * 
   * @apiviz.stereotype factory
   * @apiviz.uses OPTICSPlotSelectionVisualization oneway - - «create»
   */
  public static class Factory extends AbstractVisFactory {
    /**
     * Constructor, adhering to
     * {@link de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable}
     */
    public Factory() {
      super();
    }

    @Override
    public void processNewResult(HierarchicalResult baseResult, Result result) {
      Collection<OPTICSPlot<?>> plots = ResultUtil.filterResults(result, OPTICSPlot.class);
      for(OPTICSPlot<?> plot : plots) {
        ClusterOrderResult<?> co = plot.getClusterOrder();
        final VisualizationTask task = new VisualizationTask(NAME, co, null, this, plot);
        task.put(VisualizationTask.META_LEVEL, VisualizationTask.LEVEL_INTERACTIVE);
        baseResult.getHierarchy().add(plot, task);
      }
    }

    @Override
    public Visualization makeVisualization(VisualizationTask task) {
      return new OPTICSClusterVisualization(task);
    }

    @Override
    public boolean allowThumbnails(@SuppressWarnings("unused") VisualizationTask task) {
      // Don't use thumbnails
      return false;
    }

    @Override
    public Class<? extends Projection> getProjectionType() {
      return null;
    }
  }
}