1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package de.fu_berlin.ties.classify;
23
24 import java.util.Comparator;
25
26 import org.apache.commons.lang.builder.ToStringBuilder;
27
28 import de.fu_berlin.ties.classify.winnow.WinnowPrediction;
29
30 /***
31 * A comparison function that compares
32 * {@link de.fu_berlin.ties.classify.Prediction}s based on their
33 * {@linkplain de.fu_berlin.ties.classify.Prediction#getProbability()
34 * probabilities}.
35 *
36 * @author Christian Siefkes
37 * @version $Revision: 1.6 $, $Date: 2004/11/19 14:04:19 $, $Author: siefkes $
38 */
39 public class PredictionComparator implements Comparator<Prediction> {
40
41 /***
42 * Creates a new instance.
43 */
44 public PredictionComparator() {
45 super();
46 }
47
48 /***
49 * Compares two {@link Prediction}s. This method checks whether the
50 * {@linkplain Probability#getPR() pR} values of both predictions are given
51 * and compares them if they are. Otherwise the
52 * {@linkplain Probability#getProb() probabilities} are compared.
53 * In case of a tie the {@linkplain WinnowPrediction#getRawScore() raw
54 * scores} are compared if both are {@link WinnowPrediction}s.
55 * Otherwise the {@linkplain Prediction#getType() types} are compared
56 * lexicographically (but in inverted order, so in case of a tie the
57 * alphabetically first prediction "wins").
58 *
59 * @param pred1 the first prediction to be compared
60 * @param pred2 the second prediction to be compared
61 * @return a negative integer, zero, or a positive integer if the first
62 * argument is less than, equal to, or greater than of the second
63 * @throws ClassCastException if either of the arguments is not a
64 * {@link Prediction}
65 */
66 public int compare(final Prediction pred1, final Prediction pred2)
67 throws ClassCastException {
68 final Probability prob1= pred1.getProbability();
69 final Probability prob2 = pred2.getProbability();
70 final double pR1 = prob1.getPR();
71 final double pR2 = prob2.getPR();
72 int result = 0;
73
74
75 if (!Double.isNaN(pR1) && !Double.isNaN(pR2)) {
76 result = Double.compare(pR1, pR2);
77 }
78
79
80 if (result == 0) {
81 result = Double.compare(prob1.getProb(),
82 prob2.getProb());
83 }
84
85
86 if ((result == 0) && (pred1 instanceof WinnowPrediction)
87 && (pred2 instanceof WinnowPrediction)) {
88 result = Float.compare(((WinnowPrediction) pred1).getRawScore(),
89 ((WinnowPrediction) pred2).getRawScore());
90 }
91
92
93 if (result == 0) {
94 result = -pred1.getType().compareTo(pred2.getType());
95 }
96
97 return result;
98 }
99
100 /***
101 * Returns a string representation of this object.
102 *
103 * @return a textual representation
104 */
105 public String toString() {
106 return new ToStringBuilder(this).toString();
107 }
108
109 }