pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / facet / src / java / org / apache / lucene / facet / search / sampling / RandomSampler.java
1 package org.apache.lucene.facet.search.sampling;
2
3 import java.io.IOException;
4 import java.util.Random;
5
6 import org.apache.lucene.facet.search.ScoredDocIDs;
7 import org.apache.lucene.facet.search.ScoredDocIDsIterator;
8 import org.apache.lucene.facet.util.ScoredDocIdsUtils;
9
10 /**
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
17  *
18  *     http://www.apache.org/licenses/LICENSE-2.0
19  *
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.
25  */
26
27 /**
28  * Simple random sampler
29  */
30 public class RandomSampler extends Sampler {
31   
32   private final Random random;
33
34   public RandomSampler() {
35     super();
36     this.random = new Random();
37   }
38
39   public RandomSampler(SamplingParams params, Random random) throws IllegalArgumentException {
40     super(params);
41     this.random = random;
42   }
43
44   @Override
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();
50     int i = 0;
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++) {
56         it.next();
57         -- remaining;
58       }
59       sample[i++] = it.getDocID();
60     }
61     // Add leftover documents to the sample set
62     while (i<sample.length) {
63       it.next();
64       sample[i++] = it.getDocID();
65     }
66     ScoredDocIDs sampleRes = ScoredDocIdsUtils.createScoredDocIDsSubset(docids, sample);
67     SampleResult res = new SampleResult(sampleRes, sampleSetSize/(double)actualSize);
68     return res;
69   }
70   
71 }