comparison src/edu/unc/genomics/visualization/KMeansRow.java @ 2:e16016635b2a

Uploaded
author timpalpant
date Mon, 13 Feb 2012 22:12:06 -0500
parents
children
comparison
equal deleted inserted replaced
1:a54db233ee3d 2:e16016635b2a
1 package edu.unc.genomics.visualization;
2
3 import java.io.Serializable;
4 import java.util.Collection;
5
6 import org.apache.commons.math.stat.clustering.Clusterable;
7
8 /**
9 * @author timpalpant
10 * Holds a row of data for the KMeans program
11 */
12 class KMeansRow implements Clusterable<KMeansRow>, Serializable {
13
14 private static final long serialVersionUID = -323598431692368500L;
15
16 private final String id;
17 /** Point coordinates. */
18 private final float[] point;
19
20 /**
21 * Build an instance wrapping an float array.
22 * <p>The wrapped array is referenced, it is <em>not</em> copied.</p>
23 * @param point the n-dimensional point in integer space
24 */
25 public KMeansRow(final String id, final float[] point) {
26 this.point = point;
27 this.id = id;
28 }
29
30 /**
31 * Get the n-dimensional point in float space.
32 * @return a reference (not a copy!) to the wrapped array
33 */
34 public float[] getPoint() {
35 return point;
36 }
37
38 /** {@inheritDoc} */
39 public double distanceFrom(final KMeansRow p) {
40 double sumSquares = 0;
41 float[] otherPoint = p.getPoint();
42 for (int i = 0; i < point.length; i++) {
43 sumSquares += Math.pow(point[i]-otherPoint[i], 2);
44 }
45 return Math.sqrt(sumSquares);
46 }
47
48 /** {@inheritDoc} */
49 public KMeansRow centroidOf(final Collection<KMeansRow> points) {
50 float[] centroid = new float[getPoint().length];
51 for (KMeansRow p : points) {
52 for (int i = 0; i < centroid.length; i++) {
53 centroid[i] += p.getPoint()[i];
54 }
55 }
56 for (int i = 0; i < centroid.length; i++) {
57 centroid[i] /= points.size();
58 }
59 return new KMeansRow(id, centroid);
60 }
61
62 /** {@inheritDoc} */
63 @Override
64 public boolean equals(final Object other) {
65 if (!(other instanceof KMeansRow)) {
66 return false;
67 }
68 final float[] otherPoint = ((KMeansRow) other).getPoint();
69 if (point.length != otherPoint.length) {
70 return false;
71 }
72 for (int i = 0; i < point.length; i++) {
73 if (point[i] != otherPoint[i]) {
74 return false;
75 }
76 }
77 return true;
78 }
79
80 /** {@inheritDoc} */
81 @Override
82 public int hashCode() {
83 int hashCode = 0;
84 for (Float i : point) {
85 hashCode += i.hashCode() * 13 + 7;
86 }
87 return hashCode;
88 }
89
90 /**
91 * {@inheritDoc}
92 * @since 2.1
93 */
94 @Override
95 public String toString() {
96 final StringBuilder buff = new StringBuilder(id);
97 for (float value : getPoint()) {
98 buff.append("\t").append(value);
99 }
100 return buff.toString();
101 }
102
103 /**
104 * @return the id
105 */
106 public String getId() {
107 return id;
108 }
109
110 }