/* * Copyright 2016 The Cartographer Authors * * Licensed 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. */ namespace CartographerSharp.Common; /// /// Signals when a sample should be taken from a stream of data to select a /// uniformly distributed fraction of the data. /// public class FixedRatioSampler { /// /// Sampling occurs if the proportion of samples to pulses drops below this number. /// private readonly double _ratio; private long _numPulses = 0; private long _numSamples = 0; /// /// Creates a fixed ratio sampler with the given ratio. /// /// Ratio between 0.0 and 1.0. Sampling occurs if the proportion of samples to pulses drops below this number. public FixedRatioSampler(double ratio) { if (ratio < 0.0 || ratio > 1.0) { throw new ArgumentException($"Ratio must be between 0.0 and 1.0, got {ratio}", nameof(ratio)); } if (ratio == 0.0) { // Warning: FixedRatioSampler is dropping all data } _ratio = ratio; } /// /// Returns true if this pulse should result in a sample. /// public bool Pulse() { _numPulses++; if (_numSamples / _numPulses < _ratio) { _numSamples++; return true; } return false; } /// /// Returns a debug string describing the current ratio of samples to pulses. /// public string DebugString() { var percentage = _numPulses > 0 ? 100.0 * _numSamples / _numPulses : 0.0; return $"{_numSamples} ({percentage:F2}%)"; } }