1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 /*
19 * This is not the original file distributed by the Apache Software Foundation
20 * It has been modified by the Hipparchus project
21 */
22 package org.hipparchus.clustering;
23
24 import java.util.Collection;
25 import java.util.List;
26
27 import org.hipparchus.clustering.distance.DistanceMeasure;
28 import org.hipparchus.exception.MathIllegalArgumentException;
29 import org.hipparchus.exception.MathIllegalStateException;
30
31 /**
32 * Base class for clustering algorithms.
33 *
34 * @param <T> the type of points that can be clustered
35 */
36 public abstract class Clusterer<T extends Clusterable> {
37
38 /** The distance measure to use. */
39 private DistanceMeasure measure;
40
41 /**
42 * Build a new clusterer with the given {@link DistanceMeasure}.
43 *
44 * @param measure the distance measure to use
45 */
46 protected Clusterer(final DistanceMeasure measure) {
47 this.measure = measure;
48 }
49
50 /**
51 * Perform a cluster analysis on the given set of {@link Clusterable} instances.
52 *
53 * @param points the set of {@link Clusterable} instances
54 * @return a {@link List} of clusters
55 * @throws MathIllegalArgumentException if points are null or the number of
56 * data points is not compatible with this clusterer
57 * @throws MathIllegalStateException if the algorithm has not yet converged after
58 * the maximum number of iterations has been exceeded
59 */
60 public abstract List<? extends Cluster<T>> cluster(Collection<T> points)
61 throws MathIllegalArgumentException, MathIllegalStateException;
62
63 /**
64 * Returns the {@link DistanceMeasure} instance used by this clusterer.
65 *
66 * @return the distance measure
67 */
68 public DistanceMeasure getDistanceMeasure() {
69 return measure;
70 }
71
72 /**
73 * Calculates the distance between two {@link Clusterable} instances
74 * with the configured {@link DistanceMeasure}.
75 *
76 * @param p1 the first clusterable
77 * @param p2 the second clusterable
78 * @return the distance between the two clusterables
79 */
80 protected double distance(final Clusterable p1, final Clusterable p2) {
81 return measure.compute(p1.getPoint(), p2.getPoint());
82 }
83
84 }