summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/algorithm/AbstractAlgorithm.java
blob: 61a695eb260f07bde4d0920fc826272176bacc3f (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
package de.lmu.ifi.dbs.elki.algorithm;

/*
 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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.utilities.exceptions.APIViolationException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectParameter;

/**
 * <p>
 * This class serves also as a model of implementing an algorithm within this
 * framework. Any Algorithm that makes use of these flags may extend this class.
 * </p>
 * 
 * @author Arthur Zimek
 * 
 * @apiviz.landmark
 * @apiviz.excludeSubtypes
 * 
 * @param <R> the result type
 */
public abstract class AbstractAlgorithm<R extends Result> implements Algorithm {
  /**
   * Constructor.
   */
  protected AbstractAlgorithm() {
    super();
  }

  @SuppressWarnings("unchecked")
  @Override
  public R run(Database database) {
    final Object[] relations1;
    final Class<?>[] signature1;
    final Object[] relations2;
    final Class<?>[] signature2;
    // Build candidate method signatures
    {
      final TypeInformation[] inputs = getInputTypeRestriction();
      relations1 = new Object[inputs.length + 1];
      signature1 = new Class<?>[inputs.length + 1];
      relations2 = new Object[inputs.length];
      signature2 = new Class<?>[inputs.length];
      // First parameter is the database
      relations1[0] = database;
      signature1[0] = Database.class;
      // Other parameters are the bound relations
      for(int i = 0; i < inputs.length; i++) {
        // TODO: don't bind the same relation twice?
        // But sometimes this is wanted (e.g. using projected distances)
        relations1[i + 1] = database.getRelation(inputs[i]);
        signature1[i + 1] = Relation.class;
        relations2[i] = database.getRelation(inputs[i]);
        signature2[i] = Relation.class;
      }
    }

    // Find appropriate run method.
    Method runmethod1 = null;
    Method runmethod2 = null;
    try {
      runmethod1 = this.getClass().getMethod("run", signature1);
      runmethod2 = null;
    }
    catch(SecurityException e) {
      throw new APIViolationException("Security exception finding an appropriate 'run' method.", e);
    }
    catch(NoSuchMethodException e) {
      runmethod1 = null;
      // Try without "database" parameter.
      try {
        runmethod2 = this.getClass().getMethod("run", signature2);
      }
      catch(NoSuchMethodException e2) {
        runmethod2 = null;
      }
      catch(SecurityException e2) {
        throw new APIViolationException("Security exception finding an appropriate 'run' method.", e2);
      }
    }

    if(runmethod1 != null) {
      try {
        StringBuffer buf = new StringBuffer();
        for(Class<?> cls : signature1) {
          buf.append(cls.toString()).append(",");
        }
        return (R) runmethod1.invoke(this, relations1);
      }
      catch(IllegalArgumentException e) {
        throw new APIViolationException("Invoking the real 'run' method failed.", e);
      }
      catch(IllegalAccessException e) {
        throw new APIViolationException("Invoking the real 'run' method failed.", e);
      }
      catch(InvocationTargetException e) {
        if(e.getTargetException() instanceof RuntimeException) {
          throw (RuntimeException) e.getTargetException();
        }
        throw new APIViolationException("Invoking the real 'run' method failed: " + e.getTargetException().toString(), e.getTargetException());
      }
    }
    else if(runmethod2 != null) {
      try {
        StringBuffer buf = new StringBuffer();
        for(Class<?> cls : signature1) {
          buf.append(cls.toString()).append(",");
        }
        return (R) runmethod2.invoke(this, relations2);
      }
      catch(IllegalArgumentException e) {
        throw new APIViolationException("Invoking the real 'run' method failed.", e);
      }
      catch(IllegalAccessException e) {
        throw new APIViolationException("Invoking the real 'run' method failed.", e);
      }
      catch(InvocationTargetException e) {
        if(e.getTargetException() instanceof RuntimeException) {
          throw (RuntimeException) e.getTargetException();
        }
        throw new APIViolationException("Invoking the real 'run' method failed: " + e.getTargetException().toString(), e.getTargetException());
      }
    }
    else {
      throw new APIViolationException("No appropriate 'run' method found.");
    }
  }

  /**
   * Get the input type restriction used for negotiating the data query.
   * 
   * @return Type restriction
   */
  @Override
  public abstract TypeInformation[] getInputTypeRestriction();

  /**
   * Get the (STATIC) logger for this class.
   * 
   * @return the static logger
   */
  abstract protected Logging getLogger();

  /**
   * Make a default distance function configuration option
   * 
   * @param <F> Distance function type
   * @param defaultDistanceFunction Default value
   * @param restriction Restriction class
   * @return Parameter object
   */
  public static <F extends DistanceFunction<?, ?>> ObjectParameter<F> makeParameterDistanceFunction(Class<?> defaultDistanceFunction, Class<?> restriction) {
    return new ObjectParameter<F>(AbstractDistanceBasedAlgorithm.DISTANCE_FUNCTION_ID, restriction, defaultDistanceFunction);
  }
}