|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | +# coding: utf-8 |
| 19 | +# pylint: disable= |
| 20 | +"""Dataset sampler.""" |
| 21 | +__all__ = ['IntervalSampler'] |
| 22 | + |
| 23 | +from ...data import sampler |
| 24 | + |
| 25 | +class IntervalSampler(sampler.Sampler): |
| 26 | + """Samples elements from [0, length) at fixed intervals. |
| 27 | +
|
| 28 | + Parameters |
| 29 | + ---------- |
| 30 | + length : int |
| 31 | + Length of the sequence. |
| 32 | + interval : int |
| 33 | + The number of items to skip between two samples. |
| 34 | + rollover : bool, default True |
| 35 | + Whether to start again from the first skipped item after reaching the end. |
| 36 | + If true, this sampler would start again from the first skipped item until all items |
| 37 | + are visited. |
| 38 | + Otherwise, iteration stops when end is reached and skipped items are ignored. |
| 39 | +
|
| 40 | + Examples |
| 41 | + -------- |
| 42 | + >>> sampler = contrib.data.IntervalSampler(13, interval=3) |
| 43 | + >>> list(sampler) |
| 44 | + [0, 3, 6, 9, 12, 1, 4, 7, 10, 2, 5, 8, 11] |
| 45 | + >>> sampler = contrib.data.IntervalSampler(13, interval=3, rollover=False) |
| 46 | + >>> list(sampler) |
| 47 | + [0, 3, 6, 9, 12] |
| 48 | + """ |
| 49 | + def __init__(self, length, interval, rollover=True): |
| 50 | + assert interval < length, \ |
| 51 | + "Interval {} must be smaller than length {}".format(interval, length) |
| 52 | + self._length = length |
| 53 | + self._interval = interval |
| 54 | + self._rollover = rollover |
| 55 | + |
| 56 | + def __iter__(self): |
| 57 | + for i in range(self._interval if self._rollover else 1): |
| 58 | + for j in range(i, self._length, self._interval): |
| 59 | + yield j |
| 60 | + |
| 61 | + def __len__(self): |
| 62 | + return self._length |
0 commit comments