1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.math4.neuralnet.twod.util;
19
20 import org.apache.commons.math4.neuralnet.DistanceMeasure;
21 import org.apache.commons.math4.neuralnet.Neuron;
22 import org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 public class UnifiedDistanceMatrix implements MapVisualization {
40
41 private final DistanceMeasure distance;
42
43
44
45
46 public UnifiedDistanceMatrix(DistanceMeasure distance) {
47 this.distance = distance;
48 }
49
50
51
52
53
54
55
56
57
58
59
60
61 @Override
62 public double[][] computeImage(NeuronSquareMesh2D map) {
63 final int numRows = map.getNumberOfRows();
64 final int numCols = map.getNumberOfColumns();
65
66 final double[][] uMatrix = new double[numRows * 2 + 1][numCols * 2 + 1];
67
68
69
70
71
72 for (int i = 0; i < numRows; i++) {
73
74 final int iR = 2 * i + 1;
75
76 for (int j = 0; j < numCols; j++) {
77
78 final int jR = 2 * j + 1;
79
80 final double[] current = map.getNeuron(i, j).getFeatures();
81 Neuron neighbour;
82
83
84 neighbour = map.getNeuron(i, j,
85 NeuronSquareMesh2D.HorizontalDirection.RIGHT,
86 NeuronSquareMesh2D.VerticalDirection.CENTER);
87 if (neighbour != null) {
88 uMatrix[iR][jR + 1] = distance.applyAsDouble(current,
89 neighbour.getFeatures());
90 }
91
92
93 neighbour = map.getNeuron(i, j,
94 NeuronSquareMesh2D.HorizontalDirection.CENTER,
95 NeuronSquareMesh2D.VerticalDirection.DOWN);
96 if (neighbour != null) {
97 uMatrix[iR + 1][jR] = distance.applyAsDouble(current,
98 neighbour.getFeatures());
99 }
100 }
101 }
102
103
104
105
106
107
108 for (int i = 0; i < numRows; i++) {
109
110 final int iR = 2 * i + 1;
111
112 for (int j = 0; j < numCols; j++) {
113
114 final int jR = 2 * j + 1;
115
116 final Neuron current = map.getNeuron(i, j);
117 final Neuron right = map.getNeuron(i, j,
118 NeuronSquareMesh2D.HorizontalDirection.RIGHT,
119 NeuronSquareMesh2D.VerticalDirection.CENTER);
120 final Neuron bottom = map.getNeuron(i, j,
121 NeuronSquareMesh2D.HorizontalDirection.CENTER,
122 NeuronSquareMesh2D.VerticalDirection.DOWN);
123 final Neuron bottomRight = map.getNeuron(i, j,
124 NeuronSquareMesh2D.HorizontalDirection.RIGHT,
125 NeuronSquareMesh2D.VerticalDirection.DOWN);
126
127 final double current2BottomRight = bottomRight == null ?
128 0 :
129 distance.applyAsDouble(current.getFeatures(),
130 bottomRight.getFeatures());
131 final double right2Bottom = (right == null ||
132 bottom == null) ?
133 0 :
134 distance.applyAsDouble(right.getFeatures(),
135 bottom.getFeatures());
136
137
138 uMatrix[iR + 1][jR + 1] = 0.5 * (current2BottomRight + right2Bottom);
139 }
140 }
141
142
143 final int lastRow = uMatrix.length - 1;
144 uMatrix[0] = uMatrix[lastRow];
145
146
147
148 final int lastCol = uMatrix[0].length - 1;
149 for (int r = 0; r < lastRow; r++) {
150 uMatrix[r][0] = uMatrix[r][lastCol];
151 }
152
153 return uMatrix;
154 }
155 }