-
Notifications
You must be signed in to change notification settings - Fork 40
/
ListSamplerTest.java
309 lines (265 loc) · 11.8 KB
/
ListSamplerTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.sampling;
import java.util.Set;
import java.util.function.Supplier;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.apache.commons.math3.stat.inference.ChiSquareTest;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
/**
* Tests for {@link ListSampler}.
*/
public class ListSamplerTest {
private final UniformRandomProvider rng = RandomSource.ISAAC.create(6543432321L);
private final ChiSquareTest chiSquareTest = new ChiSquareTest();
@Test
public void testSample() {
final String[][] c = {{"0", "1"}, {"0", "2"}, {"0", "3"}, {"0", "4"},
{"1", "2"}, {"1", "3"}, {"1", "4"},
{"2", "3"}, {"2", "4"},
{"3", "4"}};
final long[] observed = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
final double[] expected = {100, 100, 100, 100, 100, 100, 100, 100, 100, 100};
final HashSet<String> cPop = new HashSet<>(); // {0, 1, 2, 3, 4}.
for (int i = 0; i < 5; i++) {
cPop.add(Integer.toString(i));
}
final List<Set<String>> sets = new ArrayList<>(); // 2-sets from 5.
for (int i = 0; i < 10; i++) {
final HashSet<String> hs = new HashSet<>();
hs.add(c[i][0]);
hs.add(c[i][1]);
sets.add(hs);
}
for (int i = 0; i < 1000; i++) {
observed[findSample(sets, ListSampler.sample(rng, new ArrayList<>(cPop), 2))]++;
}
// Pass if we cannot reject null hypothesis that distributions are the same.
Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001));
}
@Test
public void testSampleWhole() {
// Sample of size = size of collection must return the same collection.
final List<String> list = new ArrayList<>();
list.add("one");
final List<String> one = ListSampler.sample(rng, list, 1);
Assertions.assertEquals(1, one.size());
Assertions.assertTrue(one.contains("one"));
}
@Test
public void testSamplePrecondition1() {
// Must fail for sample size > collection size.
final List<String> list = new ArrayList<>();
list.add("one");
Assertions.assertThrows(IllegalArgumentException.class,
() -> ListSampler.sample(rng, list, 2));
}
@Test
public void testSamplePrecondition2() {
// Must fail for empty collection.
final List<String> list = new ArrayList<>();
Assertions.assertThrows(IllegalArgumentException.class,
() -> ListSampler.sample(rng, list, 1));
}
@Test
public void testShuffle() {
final List<Integer> orig = new ArrayList<>();
for (int i = 0; i < 10; i++) {
orig.add((i + 1) * rng.nextInt());
}
final List<Integer> arrayList = new ArrayList<>(orig);
ListSampler.shuffle(rng, arrayList);
// Ensure that at least one entry has moved.
Assertions.assertTrue(compare(orig, arrayList, 0, orig.size(), false), "ArrayList");
final List<Integer> linkedList = new LinkedList<>(orig);
ListSampler.shuffle(rng, linkedList);
// Ensure that at least one entry has moved.
Assertions.assertTrue(compare(orig, linkedList, 0, orig.size(), false), "LinkedList");
}
@Test
public void testShuffleTail() {
final List<Integer> orig = new ArrayList<>();
for (int i = 0; i < 10; i++) {
orig.add((i + 1) * rng.nextInt());
}
final List<Integer> list = new ArrayList<>(orig);
final int start = 4;
ListSampler.shuffle(rng, list, start, false);
// Ensure that all entries below index "start" did not move.
Assertions.assertTrue(compare(orig, list, 0, start, true));
// Ensure that at least one entry has moved.
Assertions.assertTrue(compare(orig, list, start, orig.size(), false));
}
@Test
public void testShuffleHead() {
final List<Integer> orig = new ArrayList<>();
for (int i = 0; i < 10; i++) {
orig.add((i + 1) * rng.nextInt());
}
final List<Integer> list = new ArrayList<>(orig);
final int start = 4;
ListSampler.shuffle(rng, list, start, true);
// Ensure that all entries above index "start" did not move.
Assertions.assertTrue(compare(orig, list, start + 1, orig.size(), true));
// Ensure that at least one entry has moved.
Assertions.assertTrue(compare(orig, list, 0, start + 1, false));
}
/**
* Test shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[])}.
* The implementation may be different but the result is a Fisher-Yates shuffle so the
* output order should match.
*/
@Test
public void testShuffleMatchesPermutationSamplerShuffle() {
final List<Integer> orig = new ArrayList<>();
for (int i = 0; i < 10; i++) {
orig.add((i + 1) * rng.nextInt());
}
assertShuffleMatchesPermutationSamplerShuffle(new ArrayList<>(orig));
assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig));
}
/**
* Test shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[], int, boolean)}.
* The implementation may be different but the result is a Fisher-Yates shuffle so the
* output order should match.
*/
@Test
public void testShuffleMatchesPermutationSamplerShuffleDirectional() {
final List<Integer> orig = new ArrayList<>();
for (int i = 0; i < 10; i++) {
orig.add((i + 1) * rng.nextInt());
}
assertShuffleMatchesPermutationSamplerShuffle(new ArrayList<>(orig), 4, true);
assertShuffleMatchesPermutationSamplerShuffle(new ArrayList<>(orig), 4, false);
assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig), 4, true);
assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig), 4, false);
}
/**
* This test hits the edge case when a LinkedList is small enough that the algorithm
* using a RandomAccess list is faster than the one with an iterator.
*/
@Test
public void testShuffleWithSmallLinkedList() {
final int size = 3;
final List<Integer> orig = new ArrayList<>();
for (int i = 0; i < size; i++) {
orig.add((i + 1) * rng.nextInt());
}
// When the size is small there is a chance that the list has no entries that move.
// E.g. The number of permutations of 3 items is only 6 giving a 1/6 chance of no change.
// So repeat test that the small shuffle matches the PermutationSampler.
// 10 times is (1/6)^10 or 1 in 60,466,176 of no change.
for (int i = 0; i < 10; i++) {
assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig), size - 1, true);
}
}
//// Support methods.
/**
* If {@code same == true}, return {@code true} if all entries are
* the same; if {@code same == false}, return {@code true} if at
* least one entry is different.
*/
private static <T> boolean compare(List<T> orig,
List<T> list,
int start,
int end,
boolean same) {
for (int i = start; i < end; i++) {
if (!orig.get(i).equals(list.get(i))) {
return same ? false : true;
}
}
return same ? true : false;
}
private static <T extends Set<String>> int findSample(List<T> u,
Collection<String> sampList) {
final String[] samp = sampList.toArray(new String[sampList.size()]);
for (int i = 0; i < u.size(); i++) {
final T set = u.get(i);
final HashSet<String> sampSet = new HashSet<>();
for (int j = 0; j < samp.length; j++) {
sampSet.add(samp[j]);
}
if (set.equals(sampSet)) {
return i;
}
}
Assertions.fail("Sample not found: { " + samp[0] + ", " + samp[1] + " }");
return -1;
}
/**
* Assert the shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[])}.
*
* @param list Array whose entries will be shuffled (in-place).
*/
private static void assertShuffleMatchesPermutationSamplerShuffle(List<Integer> list) {
final int[] array = new int[list.size()];
ListIterator<Integer> it = list.listIterator();
for (int i = 0; i < array.length; i++) {
array[i] = it.next();
}
// Identical RNGs
final long seed = RandomSource.createLong();
final UniformRandomProvider rng1 = RandomSource.SPLIT_MIX_64.create(seed);
final UniformRandomProvider rng2 = RandomSource.SPLIT_MIX_64.create(seed);
ListSampler.shuffle(rng1, list);
PermutationSampler.shuffle(rng2, array);
final Supplier<String> msg = () -> "Type=" + list.getClass().getSimpleName();
it = list.listIterator();
for (int i = 0; i < array.length; i++) {
Assertions.assertEquals(array[i], it.next().intValue(), msg);
}
}
/**
* Assert the shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[], int, boolean)}.
*
* @param list Array whose entries will be shuffled (in-place).
* @param start Index at which shuffling begins.
* @param towardHead Shuffling is performed for index positions between
* {@code start} and either the end (if {@code false}) or the beginning
* (if {@code true}) of the array.
*/
private static void assertShuffleMatchesPermutationSamplerShuffle(List<Integer> list,
int start,
boolean towardHead) {
final int[] array = new int[list.size()];
ListIterator<Integer> it = list.listIterator();
for (int i = 0; i < array.length; i++) {
array[i] = it.next();
}
// Identical RNGs
final long seed = RandomSource.createLong();
final UniformRandomProvider rng1 = RandomSource.SPLIT_MIX_64.create(seed);
final UniformRandomProvider rng2 = RandomSource.SPLIT_MIX_64.create(seed);
ListSampler.shuffle(rng1, list, start, towardHead);
PermutationSampler.shuffle(rng2, array, start, towardHead);
final Supplier<String> msg = () -> String.format("Type=%s start=%d towardHead=%b",
list.getClass().getSimpleName(), start, towardHead);
it = list.listIterator();
for (int i = 0; i < array.length; i++) {
Assertions.assertEquals(array[i], it.next().intValue(), msg);
}
}
}