1
package org.apache.lucene.facet.search.sampling;
3
import java.io.IOException;
4
import java.util.Random;
6
import org.apache.lucene.facet.search.ScoredDocIDs;
7
import org.apache.lucene.facet.search.ScoredDocIDsIterator;
8
import org.apache.lucene.facet.util.ScoredDocIdsUtils;
11
* Licensed to the Apache Software Foundation (ASF) under one or more
12
* contributor license agreements. See the NOTICE file distributed with
13
* this work for additional information regarding copyright ownership.
14
* The ASF licenses this file to You under the Apache License, Version 2.0
15
* (the "License"); you may not use this file except in compliance with
16
* the License. You may obtain a copy of the License at
18
* http://www.apache.org/licenses/LICENSE-2.0
20
* Unless required by applicable law or agreed to in writing, software
21
* distributed under the License is distributed on an "AS IS" BASIS,
22
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
* See the License for the specific language governing permissions and
24
* limitations under the License.
28
* Simple random sampler
30
public class RandomSampler extends Sampler {
32
private final Random random;
34
public RandomSampler() {
36
this.random = new Random();
39
public RandomSampler(SamplingParams params, Random random) throws IllegalArgumentException {
45
protected SampleResult createSample(ScoredDocIDs docids, int actualSize, int sampleSetSize) throws IOException {
46
final int[] sample = new int[sampleSetSize];
47
final int maxStep = (actualSize * 2 ) / sampleSetSize; //floor
48
int remaining = actualSize;
49
ScoredDocIDsIterator it = docids.iterator();
51
// select sample docs with random skipStep, make sure to leave sufficient #docs for selection after last skip
52
while (i<sample.length && remaining>(sampleSetSize-maxStep-i)) {
53
int skipStep = 1 + random.nextInt(maxStep);
54
// Skip over 'skipStep' documents
55
for (int j=0; j<skipStep; j++) {
59
sample[i++] = it.getDocID();
61
// Add leftover documents to the sample set
62
while (i<sample.length) {
64
sample[i++] = it.getDocID();
66
ScoredDocIDs sampleRes = ScoredDocIdsUtils.createScoredDocIDsSubset(docids, sample);
67
SampleResult res = new SampleResult(sampleRes, sampleSetSize/(double)actualSize);