Initial commit
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/// <summary>
|
||||
/// Signals when a sample should be taken from a stream of data to select a
|
||||
/// uniformly distributed fraction of the data.
|
||||
/// </summary>
|
||||
public class FixedRatioSampler
|
||||
{
|
||||
/// <summary>
|
||||
/// Sampling occurs if the proportion of samples to pulses drops below this number.
|
||||
/// </summary>
|
||||
private readonly double _ratio;
|
||||
|
||||
private long _numPulses = 0;
|
||||
private long _numSamples = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a fixed ratio sampler with the given ratio.
|
||||
/// </summary>
|
||||
/// <param name="ratio">Ratio between 0.0 and 1.0. Sampling occurs if the proportion of samples to pulses drops below this number.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if this pulse should result in a sample.
|
||||
/// </summary>
|
||||
public bool Pulse()
|
||||
{
|
||||
_numPulses++;
|
||||
if (_numSamples / _numPulses < _ratio)
|
||||
{
|
||||
_numSamples++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a debug string describing the current ratio of samples to pulses.
|
||||
/// </summary>
|
||||
public string DebugString()
|
||||
{
|
||||
var percentage = _numPulses > 0 ? 100.0 * _numSamples / _numPulses : 0.0;
|
||||
return $"{_numSamples} ({percentage:F2}%)";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user