3.1 KiB
Samplers
Samplers in the perception package are classes that deterministically generate random float values from bounded probability distributions. Although samplers are often used in conjunction with parameters to generate arrays of typed random values, samplers can be instantiated and used from any ordinary script:
var sampler = new NormalSampler();
sampler.mean = 3;
sampler.stdDev = 2;
sampler.range = new FloatRange(-10, 10);
// Generate a sample
var sample = sampler.NextSample();
Three Samplers are included with the perception package:
- Constant Sampler
- Uniform Sampler
- Normal Sampler
Constant Sampler
Generates constant valued samples
Uniform Sampler
Samples uniformly from a specified range
Normal Sampler
Generates random samples from a truncated normal distribution bounded by a specified range
Random Seeding
Samplers generate random values that are seeded by the active scenario's current random state. Changing the scenario's random seed will result in samplers generating different values. Changing the order of samplers, parameters, or randomizers will also result in different values being sampled during a simulation.
It is recommended that users do not generate random values using the UnityEngine.Random() class or the System.Random() class within a simulation since both of these classes can potentially generate non-determinisitic or improperly seeded random values. Using only Perception Samplers to generate random values will help ensure that Perception simulations generate consistent results during local execution and on Unity Simulation in the cloud.
Custom Samplers
Take a look at the UniformSampler and NormalSampler structs as references for implementing your own ISampler. Note that the NativeSamples() method in the ISampler interface requires the usage of the Unity Job System. Take a look here to learn more about how to create jobs using the Unity Job System.
Performance
Samplers have a NativeSamples() method that can schedule a ready-made multi-threaded job intended for generating a large array of samples. Below is an example of how to combine two job handles returned by NativeSamples() to generate two arrays of samples simultaneously:
// Create samplers
var uniformSampler = new UniformSampler
{
range = new FloatRange(0, 1),
seed = 123456789u
};
var normalSampler = new NormalSampler
{
range = new FloatRange(0, 1),
mean = 0,
stdDev = 1,
seed = 987654321u
};
// Create sample jobs
var uniformSamples = uniformSampler.NativeSamples(1000, out var uniformHandle);
var normalSamples = normalSampler.NativeSamples(1000, out var normalHandle);
// Combine job handles
var combinedJobHandles = JobHandle.CombineDependencies(uniformHandle, normalHandle);
// Wait for jobs to complete
combinedJobHandles.Complete();
//...
// Use samples
//...
// Dispose of sample arrays
uniformSamples.Dispose();
normalSamples.Dispose();