1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.math4.neuralnet;
19
20 import java.util.List;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24
25 import org.apache.commons.math4.neuralnet.internal.NeuralNetException;
26
27
28
29
30
31
32 public class MapRanking {
33
34 private final List<Neuron> map = new ArrayList<>();
35
36 private final DistanceMeasure distance;
37
38
39
40
41
42
43
44
45 public MapRanking(Iterable<Neuron> neurons,
46 DistanceMeasure distance) {
47 this.distance = distance;
48
49 for (final Neuron n : neurons) {
50 map.add(n);
51 }
52 }
53
54
55
56
57
58
59
60
61
62
63
64 public List<Neuron> rank(double[] features) {
65 return rank(features, map.size());
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79 public List<Neuron> rank(double[] features,
80 int max) {
81 if (max <= 0) {
82 throw new NeuralNetException(NeuralNetException.NOT_STRICTLY_POSITIVE, max);
83 }
84 final int m = max <= map.size() ?
85 max :
86 map.size();
87 final List<PairNeuronDouble> list = new ArrayList<>(m);
88
89 for (final Neuron n : map) {
90 final double d = distance.applyAsDouble(n.getFeatures(), features);
91 final PairNeuronDouble p = new PairNeuronDouble(n, d);
92
93 if (list.size() < m) {
94 list.add(p);
95 if (list.size() > 1) {
96
97 Collections.sort(list, PairNeuronDouble.COMPARATOR);
98 }
99 } else {
100 final int last = list.size() - 1;
101 if (PairNeuronDouble.COMPARATOR.compare(p, list.get(last)) < 0) {
102 list.set(last, p);
103 if (last > 0) {
104
105 Collections.sort(list, PairNeuronDouble.COMPARATOR);
106 }
107 }
108 }
109 }
110
111 final List<Neuron> result = new ArrayList<>(m);
112 for (final PairNeuronDouble p : list) {
113 result.add(p.getNeuron());
114 }
115
116 return result;
117 }
118
119
120
121
122 private static class PairNeuronDouble {
123
124 static final Comparator<PairNeuronDouble> COMPARATOR
125 = new Comparator<PairNeuronDouble>() {
126
127 @Override
128 public int compare(PairNeuronDouble o1,
129 PairNeuronDouble o2) {
130 return Double.compare(o1.value, o2.value);
131 }
132 };
133
134 private final Neuron neuron;
135
136 private final double value;
137
138
139
140
141
142 PairNeuronDouble(Neuron neuron, double value) {
143 this.neuron = neuron;
144 this.value = value;
145 }
146
147
148 public Neuron getNeuron() {
149 return neuron;
150 }
151 }
152 }