浏览代码

Parameters are now stateful when sampling values

/usim-randomization
Steven Leal 4 年前
当前提交
a72ab433
共有 53 个文件被更改,包括 466 次插入411 次删除
  1. 27
      com.unity.perception/Documentation~/Randomization/Parameters.md
  2. 22
      com.unity.perception/Documentation~/Randomization/Tutorial.md
  3. 32
      com.unity.perception/Editor/Randomization/CategoricalOptionElement.cs
  4. 5
      com.unity.perception/Editor/Randomization/ParameterConfigurationEditor.cs
  5. 24
      com.unity.perception/Editor/Randomization/ParameterElement.cs
  6. 2
      com.unity.perception/Editor/Randomization/RandomSeedField.cs
  7. 15
      com.unity.perception/Editor/Randomization/SamplerElement.cs
  8. 6
      com.unity.perception/Editor/Randomization/Uxml/CategoricalParameterTemplate.uxml
  9. 16
      com.unity.perception/Runtime/Randomization/Configuration/ParameterConfiguration.cs
  10. 86
      com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameter.cs
  11. 4
      com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameterBase.cs
  12. 20
      com.unity.perception/Runtime/Randomization/Parameters/NumericParameter.cs
  13. 14
      com.unity.perception/Runtime/Randomization/Parameters/Parameter.cs
  14. 19
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/BooleanParameter.cs
  15. 48
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorHsvaParameter.cs
  16. 15
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/FloatParameter.cs
  17. 17
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/IntegerParameter.cs
  18. 24
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector2Parameter.cs
  19. 28
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector3Parameter.cs
  20. 32
      com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector4Parameter.cs
  21. 22
      com.unity.perception/Runtime/Randomization/Samplers/ISampler.cs
  22. 23
      com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/ConstantSampler.cs
  23. 39
      com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/NormalSampler.cs
  24. 38
      com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/UniformSampler.cs
  25. 12
      com.unity.perception/Runtime/Randomization/Samplers/SamplerUtility.cs
  26. 2
      com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs
  27. 16
      com.unity.perception/Tests/Runtime/Randomization/ParameterConfigurationTests.cs
  28. 6
      com.unity.perception/Tests/Runtime/Randomization/ScenarioTests.cs
  29. 1
      com.unity.perception/Tests/Runtime/Randomization/TestValues.cs
  30. 9
      com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs
  31. 10
      com.unity.perception/Tests/Runtime/Randomization/ParameterTests/GenericParameterTests.cs
  32. 7
      com.unity.perception/Tests/Runtime/Randomization/ParameterTests/StructParameterTests.cs
  33. 9
      com.unity.perception/Runtime/Randomization/Samplers/IRandomRangedSampler.cs
  34. 3
      com.unity.perception/Runtime/Randomization/Samplers/IRandomRangedSampler.cs.meta
  35. 3
      com.unity.perception/Tests/Runtime/Randomization/ParameterTests.meta
  36. 3
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests.meta
  37. 19
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests/ConstantSamplerTests.cs
  38. 3
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests/ConstantSamplerTests.cs.meta
  39. 14
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests/NormalSamplerTests.cs
  40. 3
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests/NormalSamplerTests.cs.meta
  41. 88
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests/RangedSamplerTests.cs
  42. 14
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests/UniformSamplerTests.cs
  43. 3
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests/UniformSamplerTests.cs.meta
  44. 74
      com.unity.perception/Tests/Runtime/Randomization/SamplerTests.cs
  45. 0
      /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs.meta
  46. 0
      /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/GenericParameterTests.cs.meta
  47. 0
      /com.unity.perception/Tests/Runtime/Randomization/SamplerTests/RangedSamplerTests.cs.meta
  48. 0
      /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/StructParameterTests.cs.meta
  49. 0
      /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs
  50. 0
      /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/GenericParameterTests.cs
  51. 0
      /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/StructParameterTests.cs

27
com.unity.perception/Documentation~/Randomization/Parameters.md


# Parameters
# Custom Parameters
All parameters are derived from one of three abstract classes:
1. `Categorical parameters`
2. `Struct parameters`
3. `Typed parameters`
All parameters derive from the Parameter abstract class, but all included perception package parameter types derive from two specialized Parameter base classes:
1. `CategoricalParameter`
2. `NumericParameter`
Categorical parameters by definition choose a value from a list of options that have no intrinsic ordering. For example, a material paramater randomly chooses from a list of material options, but the list of material options itself can be rearranged into any particular order without affecting the distribution of materials selected.
Categorical parameters choose a value from a list of options that have no intrinsic ordering. For example, a material paramater randomly chooses from a list of material options, but the list of material options itself can be rearranged into any particular order without affecting the distribution of materials selected.
If your custom parameter is a categorical in nature, take a look at the [StringParameter]() class included in the perception package as a reference for how to derive the `CategoricalParameter` class:
If your custom parameter is a categorical in nature, take a look at the [StringParameter]() class included in the perception package as a reference for how to derive the `CategoricalParameter` class.
```
using UnityEngine.Perception.Randomization.Parameters.Attributes;

**Note:** the AddComponentMenu attribute with an empty string prevents parameters from appearing in the Add Component GameObject menu. Randomization parameters should only be created with by a `ParameterConfiguration`
### Struct Parameters
### Numeric Parameters
If the intended output type of a parameter is a struct instead of a class, deriving the `StructParameter` class will create new parameter with access to the JobHandle overload of the Samples() method for increased sampling performance. Take a look at the [ColorHsvaParameter]() class included in the perception package for an example on how to implement a struct parameter.
### Typed Parameters
Typed parameters are the most generic form of parameter. To implement a typed parameter, derive the TypedParameter class and implement the Sample() and Samples() methods.
Numeric parameters use samplers to generate randomized structs. Take a look at the [ColorHsvaParameter]() class included in the perception package for an example on how to implement a numeric parameter.
It is recommended to use the JobHandle overload of the Samples() method when generating a large number of samples. The JobHandle overload will utilize the Unity Burst Compiler and Job System to automatically optimize and multithread parameter sampling jobs. The code block below is an example of how to use this overload to sample two parameters in parallel:
For numeric parameters, it is recommended to use the JobHandle overload of the Samples() method when generating a large number of samples. The JobHandle overload will utilize the Unity Burst Compiler and Job System to automatically optimize and multithread parameter sampling jobs. The code block below is an example of how to use this overload to sample two parameters in parallel:
var cubeColors = ObjectColor.Samples(currentIteration, constants.objectCount, out var colorHandle);
var cubePositions = ObjectPosition.Samples(currentIteration, constants.objectCount, out var positionHandle);
var cubeColors = ObjectColor.Samples(constants.objectCount, out var colorHandle);
var cubePositions = ObjectPosition.Samples(constants.objectCount, out var positionHandle);
// Combine job handles
var handles = JobHandle.CombineDependencies(colorHandle, positionHandle);

22
com.unity.perception/Documentation~/Randomization/Tutorial.md


## Step 4: Configure Scenario
1. Right click on the *Scripts* folder in the project hierarchy and select `Create -> C# Script`. Name the script "CubeScenario" and press enter.
2. Double click on the new "CubeScenario" script to open it for edit
3. In your code editor, paste the following C# code in the CubeScenario script:
3. In your code editor, paste the following C# code into the CubeScenario script:
using UnityEngine.Perception.Randomization.Configuration;
using UnityEngine.Perception.Randomization.Parameters;
using UnityEngine.Perception.Randomization.Scenarios;

public override bool isIterationComplete => currentIterationFrame >= 1;
public override bool isScenarioComplete => currentIteration >= constants.totalIterations;
public ColorHsvaParameter backgroundColorParameter;
public ColorHsvaParameter cubeColorParameter;
public ParameterConfiguration config;
ColorHsvaParameter m_BackgroundColorParameter;
ColorHsvaParameter m_CubeColorParameter;
Material m_BackgroundMaterial;
Material m_CubeMaterial;
static readonly int k_BaseColor = Shader.PropertyToID("_BaseColor");

m_BackgroundColorParameter = config.GetParameter<ColorHsvaParameter>("BackgroundColor");
m_CubeColorParameter = config.GetParameter<ColorHsvaParameter>("CubeColor");
m_BackgroundMaterial = background.GetComponent<MeshRenderer>().material;
m_CubeMaterial = cube.GetComponent<MeshRenderer>().material;
}

m_BackgroundMaterial.SetColor(k_BaseColor, backgroundColorParameter.Sample(currentIteration));
m_CubeMaterial.SetColor(k_BaseColor, cubeColorParameter.Sample(currentIteration));
m_BackgroundMaterial.SetColor(k_BaseColor, m_BackgroundColorParameter.Sample());
m_CubeMaterial.SetColor(k_BaseColor, m_CubeColorParameter.Sample());
}
}
```

3. In Unity, manipulating the color of a material is a shader specific task that cannot be accomplished directly from a color parameter's target GameObject setting. Instead we:
1. Expose references to the cube and background color parameters in this scenario's inspector as the public script variables *backgroundColorParameter* and *cubeColorParameter*
2. Lookup the ID of the *_BaseColor* shader property
3. Override the OnInitialize() method to cache references to the materials attached to the cube and background GameObjects when the simulation starts
1. Expose a reference to the parameter configuration this scenario's inspector as the public script variable
2. Cache the ID of the *_BaseColor* shader property
3. Override the OnInitialize() method to cache a few references. First, we lookup the parameters *BackgroundColor* and *CubeColor* by name from the the parameter configuration. Second, we grab the references to the materials attached to the cube and background GameObjects when the simulation starts.
4. Override the OnIterationSetup() method to apply randomly sampled color values to the shaders of the cached materials at the beginning of each scenario iteration
4. Back in the Unity editor, navigate to the inspector of the *Config* GameObject and use `Add Component -> CubeScenario` to add the new CubeScenario component to your parameter configuration.
5. Open the constants dropdown and confirm how many iterations the scenario should run (the default is 1000)

32
com.unity.perception/Editor/Randomization/CategoricalOptionElement.cs


var indexLabel = this.Q<Label>("index-label");
indexLabel.text = $"[{m_Index}]";
var probabilityProperty = m_ProbabilitiesProperty.GetArrayElementAtIndex(i);
var probability = this.Q<FloatField>("probability");
probability.RegisterValueChangedCallback((evt) =>
{
if (evt.newValue < 0f)
probability.value = 0f;
});
probability.labelElement.style.minWidth = 0;
probability.labelElement.style.marginRight = 4;
probability.BindProperty(probabilityProperty);
var probabilityProperty = m_ProbabilitiesProperty.GetArrayElementAtIndex(i);
var probability = this.Q<FloatField>("probability");
probability.isDelayed = true;
probability.labelElement.style.minWidth = 0;
probability.labelElement.style.marginRight = 4;
if (Application.isPlaying)
{
probability.value = probabilityProperty.floatValue;
probability.SetEnabled(false);
}
else
{
probability.SetEnabled(true);
probability.RegisterValueChangedCallback((evt) =>
{
if (evt.newValue < 0f)
probability.value = 0f;
});
probability.BindProperty(probabilityProperty);
}
}
}
}

5
com.unity.perception/Editor/Randomization/ParameterConfigurationEditor.cs


void AddParameter(Type parameterType)
{
var parameter = config.AddParameter(parameterType);
foreach (var sampler in parameter.Samplers)
sampler.seed = SamplerUtility.GenerateRandomSeed();
foreach (var sampler in parameter.samplers)
if (sampler is IRandomRangedSampler rangedSampler)
rangedSampler.baseSeed = SamplerUtility.GenerateRandomSeed();
serializedObject.Update();
m_ParameterContainer.Add(CreateParameterElement(config.parameters.Count - 1));

24
com.unity.perception/Editor/Randomization/ParameterElement.cs


parameterTypeLabel.text = parameter.MetaData.typeDisplayName;
var parameterNameField = this.Q<TextField>("name");
parameterNameField.isDelayed = true;
parameterNameField.BindProperty(m_SerializedProperty.FindPropertyRelative("name"));
m_TargetContainer = this.Q<VisualElement>("target-container");

void CreateCategoricalParameterFields()
{
var categoricalParameterTemplate = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(
$"{StaticData.uxmlDir}/CategoricalParameterTemplate.uxml").CloneTree();
var optionsProperty = m_SerializedProperty.FindPropertyRelative("m_Options");

var listView = categoricalParameterTemplate.Q<ListView>("options");
var listView = template.Q<ListView>("options");
listView.itemsSource = probabilities;
listView.itemHeight = 22;
listView.selectionType = SelectionType.None;

}
listView.bindItem = BindItem;
var addOptionButton = categoricalParameterTemplate.Q<Button>("add-option");
var addOptionButton = template.Q<Button>("add-option");
addOptionButton.clicked += () =>
{
probabilitiesProperty.arraySize++;

listView.ScrollToItem(probabilitiesProperty.arraySize);
};
var clearOptionsButton = template.Q<Button>("clear-options");
clearOptionsButton.clicked += () =>
{
probabilitiesProperty.arraySize = 0;
optionsProperty.arraySize = 0;
m_SerializedProperty.serializedObject.ApplyModifiedProperties();
listView.itemsSource = categoricalParameter.probabilities;
listView.Refresh();
};
var scrollView = listView.Q<ScrollView>();
listView.RegisterCallback<WheelEvent>(evt =>
{

evt.StopImmediatePropagation();
});
var uniformToggle = categoricalParameterTemplate.Q<Toggle>("uniform");
var uniformToggle = template.Q<Toggle>("uniform");
var uniformProperty = m_SerializedProperty.FindPropertyRelative("uniform");
uniformToggle.BindProperty(uniformProperty);
void ToggleProbabilityFields(bool toggle)

});
ToggleProbabilityFields(uniformToggle.value);
m_ExtraProperties.Add(categoricalParameterTemplate);
var seedField = template.Q<IntegerField>("seed");
seedField.BindProperty(m_SerializedProperty.FindPropertyRelative("m_Sampler.<baseSeed>k__BackingField"));
m_ExtraProperties.Add(template);
}
}
}

2
com.unity.perception/Editor/Randomization/RandomSeedField.cs


public RandomSeedField(SerializedProperty property)
{
label = "Seed";
this.BindProperty(property.FindPropertyRelative("state"));
this.BindProperty(property);
}
}
}

15
com.unity.perception/Editor/Randomization/SamplerElement.cs


void CreateSampler(Type samplerType)
{
var newSampler = (ISampler)Activator.CreateInstance(samplerType);
newSampler.seed = SamplerUtility.GenerateRandomSeed();
if (newSampler is IRandomRangedSampler rangedSampler)
{
rangedSampler.baseSeed = SamplerUtility.GenerateRandomSeed();
if (m_RangeProperty != null)
newSampler.range = new FloatRange(
m_RangeProperty.FindPropertyRelative("minimum").floatValue,
m_RangeProperty.FindPropertyRelative("maximum").floatValue);
if (m_RangeProperty != null)
rangedSampler.range = new FloatRange(
m_RangeProperty.FindPropertyRelative("minimum").floatValue,
m_RangeProperty.FindPropertyRelative("maximum").floatValue);
}
m_Sampler = newSampler;
m_Property.managedReferenceValue = newSampler;

{
if (SerializedProperty.EqualContents(currentProperty, nextSiblingProperty))
break;
if (currentProperty.type == "Random")
if (currentProperty.name == "<baseSeed>k__BackingField")
{
m_Properties.Add(new RandomSeedField(currentProperty.Copy()));
}

6
com.unity.perception/Editor/Randomization/Uxml/CategoricalParameterTemplate.uxml


<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements">
<Toggle label="Uniform" name="uniform"/>
<editor:IntegerField label="Seed" name="seed"/>
<Button name="add-option" text="+ Add New Option" class="add-option-button"/>
<VisualElement style="flex-direction: row; justify-content: flex-end;">
<Button name="add-option" text="Add New Option" class="add-option-button"/>
<Button name="clear-options" text="Clear Options" class="add-option-button"/>
</VisualElement>
</UXML>

16
com.unity.perception/Runtime/Randomization/Configuration/ParameterConfiguration.cs


using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine.SceneManagement;
namespace UnityEngine.Perception.Randomization.Configuration
{

public class ParameterConfiguration : MonoBehaviour
{
public static HashSet<ParameterConfiguration> configurations = new HashSet<ParameterConfiguration>();
[SerializeReference]
public List<Parameter> parameters = new List<Parameter>();
[SerializeReference] internal List<Parameter> parameters = new List<Parameter>();
/// <summary>
/// Find a parameter in this configuration by name

foreach (var parameter in parameters)
if (parameter.target.applicationFrequency == frequency)
parameter.ApplyToTarget(seedOffset);
}
/// <summary>
/// Resets sampler states to their baseSeed then offsets using the current scenario iteration
/// </summary>
public void ResetParameterStates(int scenarioIteration)
{
foreach (var parameter in parameters)
foreach (var sampler in parameter.samplers)
sampler.ResetState(scenarioIteration);
}
/// <summary>

86
com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameter.cs


[Serializable]
public abstract class CategoricalParameter<T> : CategoricalParameterBase
{
public bool uniform;
public uint seed;
[SerializeField]
List<T> m_Options = new List<T>();
[SerializeField] internal bool uniform;
[SerializeField] UniformSampler m_Sampler = new UniformSampler(0f, 1f);
[SerializeField] List<T> m_Options = new List<T>();
public override ISampler[] Samplers => new ISampler[0];
public override ISampler[] samplers => new ISampler[] { m_Sampler };
internal CategoricalParameter() { }
/// <summary>
/// Create a new categorical parameter from a list of categories with uniform probabilities
/// </summary>
/// <param name="categoricalOptions">List of categorical options</param>
public CategoricalParameter(IEnumerable<T> categoricalOptions)
{
if (options.Count == 0)
throw new ArgumentException("List of options is empty");
uniform = true;
foreach (var option in categoricalOptions)
AddOption(option, 1f);
}
/// <summary>
/// Create a new categorical parameter from a list of categories and their associated probabilities
/// </summary>
/// <param name="categoricalOptions">List of options and their associated probabilities</param>
public CategoricalParameter(IEnumerable<(T, float)> categoricalOptions)
{
if (options.Count == 0)
throw new ArgumentException("List of options is empty");
foreach (var (category, probability) in categoricalOptions)
AddOption(category, probability);
NormalizeProbabilities();
}
internal override void AddOption()
{
m_Options.Add(default);

public void AddOption(T option, float probability)
internal void AddOption(T option, float probability)
public override void RemoveOption(int index)
internal override void RemoveOption(int index)
public override void ClearOptions()
internal override void ClearOptions()
{
m_Options.Clear();
probabilities.Clear();

if (probabilities.Count != m_Options.Count)
throw new ParameterValidationException(
"Number of options must be equal to the number of probabilities");
NormalizeProbabilities();
void NormalizeProbabilities()
internal void NormalizeProbabilities()
{
var totalProbability = 0f;
for (var i = 0; i < probabilities.Count; i++)

return minNum;
}
T Sample(ref Unity.Mathematics.Random rng)
/// <summary>
/// Generates one parameter sample
/// </summary>
public T Sample()
var randomValue = rng.NextFloat();
var randomValue = m_Sampler.Sample();
/// <summary>
/// Generates one parameter sample
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
public T Sample(int index)
{
NormalizeProbabilities();
var iteratedSeed = SamplerUtility.IterateSeed((uint)index, seed);
var rng = new Unity.Mathematics.Random(iteratedSeed);
return Sample(ref rng);
}
/// <summary>
/// Generates an array of parameter samples
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
/// <param name="sampleCount">Number of parameter samples to generate</param>
public T[] Samples(int index, int sampleCount)
{
NormalizeProbabilities();
var samples = new T[sampleCount];
var iteratedSeed = SamplerUtility.IterateSeed((uint)index, seed);
var rng = new Unity.Mathematics.Random(iteratedSeed);
for (var i = 0; i < sampleCount; i++)
samples[i] = Sample(ref rng);
return samples;
}
target.ApplyValueToTarget(Sample(seedOffset));
target.ApplyValueToTarget(Sample());
}
}
}

4
com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameterBase.cs


[SerializeField] internal List<float> probabilities = new List<float>();
internal abstract void AddOption();
public abstract void RemoveOption(int index);
public abstract void ClearOptions();
internal abstract void RemoveOption(int index);
internal abstract void ClearOptions();
}
}

20
com.unity.perception/Runtime/Randomization/Parameters/NumericParameter.cs


/// <summary>
/// Generates one parameter sample
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
public abstract T Sample(int index);
/// <summary>
/// Generates an array of parameter samples
/// </summary>
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
/// <param name="sampleCount">Number of parameter samples to generate</param>
public abstract T[] Samples(int index, int sampleCount);
public abstract T Sample();
/// <param name="index">Often the current scenario iteration or a scenario's framesSinceInitialization</param>
public abstract NativeArray<T> Samples(int index, int sampleCount, out JobHandle jobHandle);
public abstract NativeArray<T> Samples(int sampleCount, out JobHandle jobHandle);
target.ApplyValueToTarget(Sample(seedOffset));
target.ApplyValueToTarget(Sample());
foreach (var sampler in Samplers)
SamplerUtility.ValidateRange(sampler.range);
foreach (var sampler in samplers)
if (sampler is IRandomRangedSampler rangedSampler)
SamplerUtility.ValidateRange(rangedSampler);
}
}
}

14
com.unity.perception/Runtime/Randomization/Parameters/Parameter.cs


[Serializable]
public abstract class Parameter
{
internal bool collapsed;
[SerializeField] internal bool collapsed;
[HideInInspector] public ParameterTarget target = new ParameterTarget();
public bool hasTarget => target.gameObject != null;

/// <summary>
/// An array containing a reference to each sampler field in this parameter
/// </summary>
public abstract ISampler[] Samplers { get; }
public abstract ISampler[] samplers { get; }
/// <summary>
/// Resets sampler states and then offsets those states using the current scenario iteration
/// </summary>
/// <param name="scenarioIteration">The current scenario iteration</param>
public void ResetState(int scenarioIteration)
{
foreach (var sampler in samplers)
sampler.ResetState(scenarioIteration);
}
/// <summary>
/// The sample type generated by this parameter

19
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/BooleanParameter.cs


{
[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
public override ISampler[] Samplers => new[] { value };
public override ISampler[] samplers => new[] { value };
public override bool Sample(int index)
public override bool Sample()
return Sample(value.CopyAndIterate(index).NextSample());
return Sample(value.Sample());
public override bool[] Samples(int index, int sampleCount)
{
var samples = new bool[sampleCount];
var sampler = value.CopyAndIterate(index);
for (var i = 0; i < sampleCount; i++)
samples[i] = Sample(sampler.NextSample());
return samples;
}
public override NativeArray<bool> Samples(int index, int sampleCount, out JobHandle jobHandle)
public override NativeArray<bool> Samples(int sampleCount, out JobHandle jobHandle)
var rngSamples = value.CopyAndIterate(index).Samples(sampleCount, out jobHandle);
var rngSamples = value.Samples(sampleCount, out jobHandle);
jobHandle = new SamplesJob
{
rngSamples = rngSamples,

48
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/ColorHsvaParameter.cs


[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler alpha = new ConstantSampler(1f);
public override ISampler[] Samplers => new []{ hue, saturation, value, alpha };
static Color CreateColorHsva(float h, float s, float v, float a)
{
var color = Color.HSVToRGB(h, s, v);
color.a = a;
return color;
}
public override ISampler[] samplers => new []{ hue, saturation, value, alpha };
public override Color Sample(int index)
public override Color Sample()
var color = Color.HSVToRGB(
hue.CopyAndIterate(index).NextSample(),
saturation.CopyAndIterate(index).NextSample(),
value.CopyAndIterate(index).NextSample());
color.a = alpha.CopyAndIterate(index).NextSample();
var color = Color.HSVToRGB(hue.Sample(), saturation.Sample(), value.Sample());
color.a = alpha.Sample();
public override Color[] Samples(int index, int sampleCount)
{
var samples = new Color[sampleCount];
var hueRng = hue.CopyAndIterate(index);
var satRng = saturation.CopyAndIterate(index);
var valRng = value.CopyAndIterate(index);
var alphaRng = alpha.CopyAndIterate(index);
for (var i = 0; i < sampleCount; i++)
samples[i] = CreateColorHsva(
hueRng.NextSample(), satRng.NextSample(), valRng.NextSample(), alphaRng.NextSample());
return samples;
}
public override NativeArray<Color> Samples(int index, int sampleCount, out JobHandle jobHandle)
public override NativeArray<Color> Samples(int sampleCount, out JobHandle jobHandle)
var hueRng = hue.CopyAndIterate(index).Samples(sampleCount, out var hueHandle);
var satRng = saturation.CopyAndIterate(index).Samples(sampleCount, out var satHandle);
var valRng = value.CopyAndIterate(index).Samples(sampleCount, out var valHandle);
var alphaRng = alpha.CopyAndIterate(index).Samples(sampleCount, out var alphaHandle);
var hueRng = hue.Samples(sampleCount, out var hueHandle);
var satRng = saturation.Samples(sampleCount, out var satHandle);
var valRng = value.Samples(sampleCount, out var valHandle);
var alphaRng = alpha.Samples(sampleCount, out var alphaHandle);
var handles = new NativeArray<JobHandle>(4, Allocator.TempJob)
{

[DeallocateOnJobCompletion] public NativeArray<float> valRng;
[DeallocateOnJobCompletion] public NativeArray<float> alphaRng;
public NativeArray<Color> samples;
static Color CreateColorHsva(float h, float s, float v, float a)
{
var color = Color.HSVToRGB(h, s, v);
color.a = a;
return color;
}
public void Execute()
{

15
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/FloatParameter.cs


{
[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
public override ISampler[] Samplers => new []{ value };
public override ISampler[] samplers => new []{ value };
public override float Sample(int index)
public override float Sample()
return value.CopyAndIterate(index).NextSample();
return value.Sample();
public override float[] Samples(int index, int sampleCount)
public override NativeArray<float> Samples(int sampleCount, out JobHandle jobHandle)
return SamplerUtility.GenerateSamples(value.CopyAndIterate(index), sampleCount);
}
public override NativeArray<float> Samples(int index, int sampleCount, out JobHandle jobHandle)
{
return value.CopyAndIterate(index).Samples(sampleCount, out jobHandle);
return value.Samples(sampleCount, out jobHandle);
}
}
}

17
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/IntegerParameter.cs


public class IntegerParameter : NumericParameter<int>
{
[SerializeReference] public ISampler value = new UniformSampler(0f, 1f);
public override ISampler[] Samplers => new[] { value };
public override ISampler[] samplers => new[] { value };
public override int Sample(int index) => (int)value.CopyAndIterate(index).NextSample();
public override int Sample() => (int)value.Sample();
public override int[] Samples(int index, int sampleCount)
{
var samples = new int[sampleCount];
var sampler = value.CopyAndIterate(index);
for (var i = 0; i < sampleCount; i++)
samples[i] = (int)sampler.NextSample();
return samples;
}
public override NativeArray<int> Samples(int index, int totalSamples, out JobHandle jobHandle)
public override NativeArray<int> Samples(int totalSamples, out JobHandle jobHandle)
var rngSamples = value.CopyAndIterate(index).Samples(totalSamples, out jobHandle);
var rngSamples = value.Samples(totalSamples, out jobHandle);
jobHandle = new SamplesJob
{
rngSamples = rngSamples,

24
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector2Parameter.cs


[SerializeReference] public ISampler x = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler y = new UniformSampler(0f, 1f);
public override ISampler[] Samplers => new []{ x, y };
public override Vector2 Sample(int index)
{
return new Vector2(
x.CopyAndIterate(index).NextSample(),
y.CopyAndIterate(index).NextSample());
}
public override ISampler[] samplers => new []{ x, y };
public override Vector2[] Samples(int index, int sampleCount)
public override Vector2 Sample()
var samples = new Vector2[sampleCount];
var xRng = x.CopyAndIterate(index);
var yRng = y.CopyAndIterate(index);
for (var i = 0; i < sampleCount; i++)
samples[i] = new Vector2(xRng.NextSample(), yRng.NextSample());
return samples;
return new Vector2(x.Sample(), y.Sample());
public override NativeArray<Vector2> Samples(int index, int totalSamples, out JobHandle jobHandle)
public override NativeArray<Vector2> Samples(int totalSamples, out JobHandle jobHandle)
var xRng = x.CopyAndIterate(index).Samples(totalSamples, out var xHandle);
var yRng = y.CopyAndIterate(index).Samples(totalSamples, out var yHandle);
var xRng = x.Samples(totalSamples, out var xHandle);
var yRng = y.Samples(totalSamples, out var yHandle);
var combinedJobHandles = JobHandle.CombineDependencies(xHandle, yHandle);
jobHandle = new SamplesJob
{

28
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector3Parameter.cs


[SerializeReference] public ISampler y = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler z = new UniformSampler(0f, 1f);
public override ISampler[] Samplers => new []{ x, y, z };
public override Vector3 Sample(int index)
{
return new Vector3(
x.CopyAndIterate(index).NextSample(),
y.CopyAndIterate(index).NextSample(),
z.CopyAndIterate(index).NextSample());
}
public override ISampler[] samplers => new []{ x, y, z };
public override Vector3[] Samples(int index, int sampleCount)
public override Vector3 Sample()
var samples = new Vector3[sampleCount];
var xRng = x.CopyAndIterate(index);
var yRng = y.CopyAndIterate(index);
var zRng = z.CopyAndIterate(index);
for (var i = 0; i < sampleCount; i++)
samples[i] = new Vector3(xRng.NextSample(), yRng.NextSample(), zRng.NextSample());
return samples;
return new Vector3(x.Sample(), y.Sample(), z.Sample());
public override NativeArray<Vector3> Samples(int index, int totalSamples, out JobHandle jobHandle)
public override NativeArray<Vector3> Samples(int totalSamples, out JobHandle jobHandle)
var xRng = x.CopyAndIterate(index).Samples(totalSamples, out var xHandle);
var yRng = y.CopyAndIterate(index).Samples(totalSamples, out var yHandle);
var zRng = z.CopyAndIterate(index).Samples(totalSamples, out var zHandle);
var xRng = x.Samples(totalSamples, out var xHandle);
var yRng = y.Samples(totalSamples, out var yHandle);
var zRng = z.Samples(totalSamples, out var zHandle);
var combinedJobHandles = JobHandle.CombineDependencies(xHandle, yHandle, zHandle);
jobHandle = new SamplesJob
{

32
com.unity.perception/Runtime/Randomization/Parameters/ParameterTypes/Vector4Parameter.cs


[SerializeReference] public ISampler z = new UniformSampler(0f, 1f);
[SerializeReference] public ISampler w = new UniformSampler(0f, 1f);
public override ISampler[] Samplers => new []{ x, y, z, w };
public override Vector4 Sample(int index)
{
return new Vector4(
x.CopyAndIterate(index).NextSample(),
y.CopyAndIterate(index).NextSample(),
z.CopyAndIterate(index).NextSample(),
w.CopyAndIterate(index).NextSample());
}
public override ISampler[] samplers => new []{ x, y, z, w };
public override Vector4[] Samples(int index, int sampleCount)
public override Vector4 Sample()
var samples = new Vector4[sampleCount];
var xRng = x.CopyAndIterate(index);
var yRng = y.CopyAndIterate(index);
var zRng = z.CopyAndIterate(index);
var wRng = w.CopyAndIterate(index);
for (var i = 0; i < sampleCount; i++)
samples[i] = new Vector4(xRng.NextSample(), yRng.NextSample(), zRng.NextSample(), wRng.NextSample());
return samples;
return new Vector4(x.Sample(), y.Sample(), z.Sample(), w.Sample());
public override NativeArray<Vector4> Samples(int index, int totalSamples, out JobHandle jobHandle)
public override NativeArray<Vector4> Samples(int totalSamples, out JobHandle jobHandle)
var xRng = x.CopyAndIterate(index).Samples(totalSamples, out var xHandle);
var yRng = y.CopyAndIterate(index).Samples(totalSamples, out var yHandle);
var zRng = z.CopyAndIterate(index).Samples(totalSamples, out var zHandle);
var wRng = w.CopyAndIterate(index).Samples(totalSamples, out var wHandle);
var xRng = x.Samples(totalSamples, out var xHandle);
var yRng = y.Samples(totalSamples, out var yHandle);
var zRng = z.Samples(totalSamples, out var zHandle);
var wRng = w.Samples(totalSamples, out var wHandle);
var handles = new NativeArray<JobHandle>(4, Allocator.Temp)
{

22
com.unity.perception/Runtime/Randomization/Samplers/ISampler.cs


/// </summary>
public interface ISampler
{
uint seed { get; set; }
FloatRange range { get; set; }
/// <summary>
/// Resets a sampler's state to its base random seed
/// </summary>
void ResetState();
/// Returns a duplicate sampler with an iterated seed
/// Resets a sampler's state to its base random seed and then offsets said seed using an index value
/// Offset value is often a the active scenario's currentIteration or framesSinceInitialization.
/// Often a the active scenario's currentIteration
ISampler CopyAndIterate(int index);
void ResetState(int index);
/// <summary>
/// Deterministically offsets a sampler's state when generating values within a batched job
/// </summary>
/// <param name="batchIndex">
/// The current job index
/// </param>
void IterateState(int batchIndex);
float NextSample();
float Sample();
/// <summary>
/// Schedule a job to generate multiple samples

23
com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/ConstantSampler.cs


{
public float value;
public uint seed
public ConstantSampler(float value)
get => 0;
set { }
this.value = value;
public FloatRange range
{
get => new FloatRange(value, value);
set { }
}
public void ResetState() { }
public ConstantSampler(float value)
{
this.value = value;
}
public void ResetState(int index) { }
public ISampler CopyAndIterate(int index)
{
return new ConstantSampler(value);
}
public void IterateState(int batchIndex) { }
public float NextSample()
public float Sample()
{
return value;
}

39
com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/NormalSampler.cs


/// </summary>
[Serializable]
[SamplerMetaData("Normal")]
public struct NormalSampler : ISampler
public struct NormalSampler : ISampler, IRandomRangedSampler
Unity.Mathematics.Random m_Random;
[SerializeField] Unity.Mathematics.Random m_Random;
[field: SerializeField]
public uint baseSeed { get; set; }
public uint seed
public uint state
public NormalSampler(float min, float max, float mean, float standardDeviation)
public NormalSampler(float min, float max, float mean, float standardDeviation, uint seed=SamplerUtility.largePrime)
m_Random = new Unity.Mathematics.Random();
m_Random.InitState();
baseSeed = seed;
m_Random.state = baseSeed;
}
public void ResetState()
{
state = baseSeed;
}
public void ResetState(int index)
{
ResetState();
IterateState(index);
public ISampler CopyAndIterate(int index)
public void IterateState(int batchIndex)
var newSampler = this;
newSampler.seed = SamplerUtility.IterateSeed((uint)index, seed);
return newSampler;
state = SamplerUtility.IterateSeed((uint)batchIndex, state);
public float NextSample()
public float Sample()
{
return SamplerUtility.TruncatedNormalSample(
m_Random.NextFloat(), range.minimum, range.maximum, mean, standardDeviation);

{
return SamplerUtility.GenerateSamples(this, sampleCount, out jobHandle);
var samples = SamplerUtility.GenerateSamples(this, sampleCount, out jobHandle);
IterateState(sampleCount);
return samples;
}
}
}

38
com.unity.perception/Runtime/Randomization/Samplers/SamplerTypes/UniformSampler.cs


/// </summary>
[Serializable]
[SamplerMetaData("Uniform")]
public struct UniformSampler : ISampler
public struct UniformSampler : ISampler, IRandomRangedSampler
[SerializeField] Unity.Mathematics.Random m_Random;
Unity.Mathematics.Random m_Random;
public uint seed
[field: SerializeField]
public uint baseSeed { get; set; }
public uint state
public UniformSampler(float min, float max)
public UniformSampler(float min, float max, uint seed=SamplerUtility.largePrime)
m_Random = new Unity.Mathematics.Random();
m_Random.InitState();
baseSeed = seed;
m_Random.state = baseSeed;
public ISampler CopyAndIterate(int index)
public void ResetState()
var newSampler = this;
newSampler.seed = SamplerUtility.IterateSeed((uint)index, seed);
return newSampler;
state = baseSeed;
}
public void ResetState(int index)
{
ResetState();
IterateState(index);
}
public void IterateState(int batchIndex)
{
state = SamplerUtility.IterateSeed((uint)batchIndex, state);
public float NextSample()
public float Sample()
{
return math.lerp(range.minimum, range.maximum, m_Random.NextFloat());
}

return SamplerUtility.GenerateSamples(this, sampleCount, out jobHandle);
var samples = SamplerUtility.GenerateSamples(this, sampleCount, out jobHandle);
IterateState(sampleCount);
return samples;
}
}
}

12
com.unity.perception/Runtime/Randomization/Samplers/SamplerUtility.cs


/// <summary>
/// Throws an exception if a sampler has an invalid range
/// </summary>
public static void ValidateRange(FloatRange range)
public static void ValidateRange(IRandomRangedSampler rangedSampler)
if (range.minimum > range.maximum)
if (rangedSampler.range.minimum > rangedSampler.range.maximum)
throw new ArgumentException("Invalid sampling range");
}

{
var samples = new float[totalSamples];
for (var i = 0; i < totalSamples; i++)
samples[i] = sampler.NextSample();
samples[i] = sampler.Sample();
return samples;
}

public void Execute(int startIndex, int count)
{
var endIndex = startIndex + count;
var batchIndex = (uint)startIndex / samplingBatchSize;
sampler.seed = IterateSeed(batchIndex, sampler.seed);
var batchIndex = startIndex / samplingBatchSize;
sampler.IterateState(batchIndex);
samples[i] = sampler.NextSample();
samples[i] = sampler.Sample();
}
}

2
com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs


{
DatasetCapture.StartNewSequence();
foreach (var config in ParameterConfiguration.configurations)
config.ResetParameterStates(currentIteration);
foreach (var config in ParameterConfiguration.configurations)
config.ApplyParameters(currentIteration, ParameterApplicationFrequency.OnIterationSetup);
OnIterationSetup();
while (!isIterationComplete)

16
com.unity.perception/Tests/Runtime/Randomization/ParameterConfigurationTests.cs


Assert.DoesNotThrow(() => config.AddParameter(typeof(FloatParameter)));
Assert.Throws<ParameterConfigurationException>(() => config.AddParameter(typeof(Rigidbody)));
}
[UnityTest]
public IEnumerator CleansUpParametersOnDestroy()
{
var config = m_TestObject.AddComponent<ParameterConfiguration>();
var parameter1 = config.AddParameter<FloatParameter>();
var parameter2 = config.AddParameter<FloatParameter>();
Object.DestroyImmediate(config);
// Wait for next frame, at which point OnDestroy() has been called for both parameters
yield return null;
Assert.True(config == null);
Assert.True(parameter1 == null);
Assert.True(parameter2 == null);
}
}
}

6
com.unity.perception/Tests/Runtime/Randomization/ScenarioTests.cs


}
[UnityTest]
public IEnumerator SerializationTest()
public IEnumerator OverwritesConstantsOnSerialization()
{
yield return CreateNewScenario();
m_Scenario.serializedConstantsFileName = "perception_serialization_test";

}
[UnityTest]
public IEnumerator MultipleFrameIterationTest()
public IEnumerator IterationsCanLastMultipleFrames()
{
yield return CreateNewScenario();
const int testIterationFrameCount = 5;

}
[UnityTest]
public IEnumerator ScenarioCompletionTest()
public IEnumerator CompletesWhenIsScenarioCompleteIsTrue()
{
yield return CreateNewScenario();
const int testIterationTotal = 5;

1
com.unity.perception/Tests/Runtime/Randomization/TestValues.cs


{
public static class TestValues
{
public const int ScenarioIteration = 0;
public const int TestSampleCount = 30;
}
}

9
com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs


using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace RandomizationTests
namespace RandomizationTests.ParameterTests
{
[TestFixture]
public class CategoricalParameterTests

}
[Test]
public void NegativeProbabilitiesTest()
public void NegativeProbabilities()
{
var parameter = new StringParameter();
parameter.AddOption("option1", 1f);

10
com.unity.perception/Tests/Runtime/Randomization/ParameterTests/GenericParameterTests.cs


using System.Collections;
using NUnit.Framework;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace RandomizationTests
namespace RandomizationTests.ParameterTests
public class ParameterTests
public class GenericParameterTests
{
GameObject m_TestObject;

{
foreach (var parameter in m_Parameters)
{
foreach (var sampler in parameter.Samplers)
foreach (var sampler in parameter.samplers)
Assert.NotNull(sampler);
}
}

7
com.unity.perception/Tests/Runtime/Randomization/ParameterTests/StructParameterTests.cs


using System;
using System.Collections;
using UnityEngine.TestTools;
namespace RandomizationTests
namespace RandomizationTests.ParameterTests
{
[TestFixture]
public class StructParameterTests

public override void GeneratesNativeSamples()
{
var nativeSamples = m_Parameter.Samples(
TestValues.ScenarioIteration, TestValues.TestSampleCount, out var handle);
var nativeSamples = m_Parameter.Samples(TestValues.TestSampleCount, out var handle);
handle.Complete();
Assert.AreEqual(nativeSamples.Length, TestValues.TestSampleCount);
nativeSamples.Dispose();

9
com.unity.perception/Runtime/Randomization/Samplers/IRandomRangedSampler.cs


namespace UnityEngine.Perception.Randomization.Samplers
{
public interface IRandomRangedSampler
{
uint baseSeed { get; set; }
uint state { get; set; }
FloatRange range { get; set; }
}
}

3
com.unity.perception/Runtime/Randomization/Samplers/IRandomRangedSampler.cs.meta


fileFormatVersion: 2
guid: 0f406605b3cb4d55b84b5955196c4911
timeCreated: 1597419465

3
com.unity.perception/Tests/Runtime/Randomization/ParameterTests.meta


fileFormatVersion: 2
guid: d863105e5fa641dc893c604e733af0a0
timeCreated: 1597426995

3
com.unity.perception/Tests/Runtime/Randomization/SamplerTests.meta


fileFormatVersion: 2
guid: f7c237ffad664023b7b65452426ea129
timeCreated: 1597426125

19
com.unity.perception/Tests/Runtime/Randomization/SamplerTests/ConstantSamplerTests.cs


using NUnit.Framework;
using UnityEngine.Perception.Randomization.Samplers;
namespace RandomizationTests.SamplerTests
{
[TestFixture]
public class ConstantSamplerTests
{
[Test]
public void ConstantSamplerGeneratesConstantValues()
{
var constantSampler = new ConstantSampler();
var samples = SamplerUtility.GenerateSamples(constantSampler, TestValues.TestSampleCount);
Assert.AreEqual(samples.Length, TestValues.TestSampleCount);
foreach (var sample in samples)
Assert.AreEqual(sample, constantSampler.value);
}
}
}

3
com.unity.perception/Tests/Runtime/Randomization/SamplerTests/ConstantSamplerTests.cs.meta


fileFormatVersion: 2
guid: 1e969bf8899c46ce8bb9d5d1e32b3bb4
timeCreated: 1597426149

14
com.unity.perception/Tests/Runtime/Randomization/SamplerTests/NormalSamplerTests.cs


using NUnit.Framework;
using UnityEngine.Perception.Randomization.Samplers;
namespace RandomizationTests.SamplerTests
{
[TestFixture]
public class NormalSamplerTests : RangedSamplerTests<NormalSampler>
{
public NormalSamplerTests()
{
m_BaseSampler = new NormalSampler(-10f, 10f, 0f, 1f);
}
}
}

3
com.unity.perception/Tests/Runtime/Randomization/SamplerTests/NormalSamplerTests.cs.meta


fileFormatVersion: 2
guid: 8a4f678200ff4198af8d7a7f0c2e2766
timeCreated: 1597426955

88
com.unity.perception/Tests/Runtime/Randomization/SamplerTests/RangedSamplerTests.cs


using System;
using NUnit.Framework;
using Unity.Jobs;
using UnityEngine.Perception.Randomization.Samplers;
namespace RandomizationTests.SamplerTests
{
public abstract class RangedSamplerTests<T> where T : struct, ISampler, IRandomRangedSampler
{
const int k_TestSampleCount = 30;
protected T m_BaseSampler;
T m_Sampler;
[SetUp]
public void Setup()
{
m_Sampler = m_BaseSampler;
}
[Test]
public void SamplesInRange()
{
var samples = SamplerUtility.GenerateSamples(m_Sampler, k_TestSampleCount);
Assert.AreEqual(samples.Length, k_TestSampleCount);
foreach (var sample in samples)
{
Assert.GreaterOrEqual(sample, m_Sampler.range.minimum);
Assert.LessOrEqual(sample, m_Sampler.range.maximum);
}
}
[Test]
public void NativeSamplesInRange()
{
var samples = m_Sampler.Samples(k_TestSampleCount, out var handle);
handle.Complete();
Assert.AreEqual(samples.Length, k_TestSampleCount);
foreach (var sample in samples)
{
Assert.GreaterOrEqual(sample, m_Sampler.range.minimum);
Assert.LessOrEqual(sample, m_Sampler.range.maximum);
}
samples.Dispose();
}
[Test]
public void ConsecutiveSamplesChangesState()
{
var state0 = m_Sampler.state;
m_Sampler.Sample();
var state1 = m_Sampler.state;
m_Sampler.Sample();
var state2 = m_Sampler.state;
Assert.AreNotEqual(state0, state1);
Assert.AreNotEqual(state1, state2);
}
[Test]
public void ConsecutiveSampleBatchesChangesState()
{
var state0 = m_Sampler.state;
var samples1 = m_Sampler.Samples(k_TestSampleCount, out var handle1);
var state1 = m_Sampler.state;
var samples2 = m_Sampler.Samples(k_TestSampleCount, out var handle2);
var state2 = m_Sampler.state;
JobHandle.CombineDependencies(handle1, handle2).Complete();
Assert.AreEqual(samples1.Length, samples2.Length);
Assert.AreNotEqual(state0, state1);
Assert.AreNotEqual(state1, state2);
Assert.AreNotEqual(samples1[0], samples2[0]);
samples1.Dispose();
samples2.Dispose();
}
[Test]
public void InvalidRange()
{
m_Sampler.range = new FloatRange(1, -1);
Assert.Throws<ArgumentException>(() => SamplerUtility.ValidateRange(m_Sampler));
}
}
}

14
com.unity.perception/Tests/Runtime/Randomization/SamplerTests/UniformSamplerTests.cs


using NUnit.Framework;
using UnityEngine.Perception.Randomization.Samplers;
namespace RandomizationTests.SamplerTests
{
[TestFixture]
public class UniformSamplerTests : RangedSamplerTests<UniformSampler>
{
public UniformSamplerTests()
{
m_BaseSampler = new UniformSampler(0f, 1f);
}
}
}

3
com.unity.perception/Tests/Runtime/Randomization/SamplerTests/UniformSamplerTests.cs.meta


fileFormatVersion: 2
guid: 812592bf8d9f4243a88e209575bb6922
timeCreated: 1597426939

74
com.unity.perception/Tests/Runtime/Randomization/SamplerTests.cs


using System;
using NUnit.Framework;
using UnityEngine.Perception.Randomization.Samplers;
namespace RandomizationTests
{
[TestFixture]
public class SamplerTests
{
const int k_ScenarioIteration = 0;
const int k_TestSampleCount = 30;
static void SamplesInRange(ISampler sampler)
{
var offsetSampler = sampler.CopyAndIterate(k_ScenarioIteration);
var samples = SamplerUtility.GenerateSamples(offsetSampler, k_TestSampleCount);
Assert.AreEqual(samples.Length, k_TestSampleCount);
foreach (var sample in samples)
{
Assert.GreaterOrEqual(sample, sampler.range.minimum);
Assert.LessOrEqual(sample, sampler.range.maximum);
}
}
static void NativeSamplesInRange(ISampler sampler)
{
var samples = sampler.CopyAndIterate(k_ScenarioIteration).Samples(k_TestSampleCount, out var handle);
handle.Complete();
Assert.AreEqual(samples.Length, k_TestSampleCount);
foreach (var sample in samples)
{
Assert.GreaterOrEqual(sample, sampler.range.minimum);
Assert.LessOrEqual(sample, sampler.range.maximum);
}
samples.Dispose();
}
static void TestSamples(ISampler sampler)
{
SamplesInRange(sampler);
NativeSamplesInRange(sampler);
}
[Test]
public void UniformSamplesInRangeTest()
{
TestSamples(new UniformSampler(0, 1));
}
[Test]
public void NormalSamplesInRangeTest()
{
TestSamples(new NormalSampler(-1, 1, 0, 1));
}
[Test]
public void ConstantSamplerTest()
{
var constantSampler = new ConstantSampler();
var samples = SamplerUtility.GenerateSamples(constantSampler, k_TestSampleCount);
Assert.AreEqual(samples.Length, k_TestSampleCount);
foreach (var sample in samples)
Assert.AreEqual(sample, constantSampler.value);
}
[Test]
public void CatchInvalidSamplerRangeTest()
{
Assert.Throws<ArgumentException>(() => SamplerUtility.ValidateRange(new FloatRange(1, -1)));
}
}
}

/com.unity.perception/Tests/Runtime/Randomization/CategoricalParameterTests.cs.meta → /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs.meta

/com.unity.perception/Tests/Runtime/Randomization/ParameterTests.cs.meta → /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/GenericParameterTests.cs.meta

/com.unity.perception/Tests/Runtime/Randomization/SamplerTests.cs.meta → /com.unity.perception/Tests/Runtime/Randomization/SamplerTests/RangedSamplerTests.cs.meta

/com.unity.perception/Tests/Runtime/Randomization/StructParameterTests.cs.meta → /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/StructParameterTests.cs.meta

/com.unity.perception/Tests/Runtime/Randomization/CategoricalParameterTests.cs → /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/CategoricalParameterTests.cs

/com.unity.perception/Tests/Runtime/Randomization/ParameterTests.cs → /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/GenericParameterTests.cs

/com.unity.perception/Tests/Runtime/Randomization/StructParameterTests.cs → /com.unity.perception/Tests/Runtime/Randomization/ParameterTests/StructParameterTests.cs

正在加载...
取消
保存