浏览代码

Make most property setters public. (#3602)

/bug-failed-api-check
GitHub 5 年前
当前提交
eeeb09b3
共有 18 个文件被更改,包括 298 次插入71 次删除
  1. 18
      com.unity.ml-agents/Editor/BehaviorParametersEditor.cs
  2. 2
      com.unity.ml-agents/Editor/CameraSensorComponentEditor.cs
  3. 4
      com.unity.ml-agents/Editor/RayPerceptionSensorComponentBaseEditor.cs
  4. 2
      com.unity.ml-agents/Editor/RenderTextureSensorComponentEditor.cs
  5. 20
      com.unity.ml-agents/Runtime/Agent.cs
  6. 35
      com.unity.ml-agents/Runtime/Policies/BehaviorParameters.cs
  7. 12
      com.unity.ml-agents/Runtime/Sensors/CameraSensorComponent.cs
  8. 29
      com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensor.cs
  9. 26
      com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensorComponentBase.cs
  10. 6
      com.unity.ml-agents/Runtime/Sensors/RenderTextureSensorComponent.cs
  11. 16
      com.unity.ml-agents/Editor/EditorUtilities.cs
  12. 11
      com.unity.ml-agents/Editor/EditorUtilities.cs.meta
  13. 8
      com.unity.ml-agents/Tests/Editor/PublicAPI.meta
  14. 144
      com.unity.ml-agents/Tests/Editor/PublicAPI/PublicApiValidation.cs
  15. 3
      com.unity.ml-agents/Tests/Editor/PublicAPI/PublicApiValidation.cs.meta
  16. 26
      com.unity.ml-agents/Tests/Editor/PublicAPI/Unity.ML-Agents.Editor.Tests.PublicAPI.asmdef
  17. 7
      com.unity.ml-agents/Tests/Editor/PublicAPI/Unity.ML-Agents.Editor.Tests.PublicAPI.asmdef.meta

18
com.unity.ml-agents/Editor/BehaviorParametersEditor.cs


}
needPolicyUpdate = EditorGUI.EndChangeCheck();
EditorGUI.BeginDisabledGroup(Application.isPlaying);
EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties());
{
EditorGUILayout.PropertyField(so.FindProperty("m_BrainParameters"), true);
}

needPolicyUpdate = needPolicyUpdate || EditorGUI.EndChangeCheck();
EditorGUILayout.PropertyField(so.FindProperty("TeamId"));
EditorGUI.BeginDisabledGroup(Application.isPlaying);
EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties());
{
EditorGUILayout.PropertyField(so.FindProperty("m_UseChildSensors"), true);
}

void UpdateAgentPolicy()
{
if (Application.isPlaying)
{
var behaviorParameters = (BehaviorParameters)target;
var agent = behaviorParameters.GetComponent<Agent>();
if (agent == null)
{
return;
}
agent.ReloadPolicy();
}
var behaviorParameters = (BehaviorParameters)target;
behaviorParameters.UpdateAgentPolicy();
}
}
}

2
com.unity.ml-agents/Editor/CameraSensorComponentEditor.cs


EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(so.FindProperty("m_Camera"), true);
EditorGUI.BeginDisabledGroup(Application.isPlaying);
EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties());
{
// These fields affect the sensor order or observation size,
// So can't be changed at runtime.

4
com.unity.ml-agents/Editor/RayPerceptionSensorComponentBaseEditor.cs


// Don't allow certain fields to be modified during play mode.
// * SensorName affects the ordering of the Agent's observations
// * The number of tags and rays affects the size of the observations.
EditorGUI.BeginDisabledGroup(Application.isPlaying);
EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties());
{
EditorGUILayout.PropertyField(so.FindProperty("m_SensorName"), true);
EditorGUILayout.PropertyField(so.FindProperty("m_DetectableTags"), true);

// Because the number of observation stacks affects the observation shape,
// it is not editable during play mode.
EditorGUI.BeginDisabledGroup(Application.isPlaying);
EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties());
{
EditorGUILayout.PropertyField(so.FindProperty("m_ObservationStacks"), true);
}

2
com.unity.ml-agents/Editor/RenderTextureSensorComponentEditor.cs


// Drawing the RenderTextureComponent
EditorGUI.BeginChangeCheck();
EditorGUI.BeginDisabledGroup(Application.isPlaying);
EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties());
{
EditorGUILayout.PropertyField(so.FindProperty("m_RenderTexture"), true);
EditorGUILayout.PropertyField(so.FindProperty("m_SensorName"), true);

20
com.unity.ml-agents/Runtime/Agent.cs


/// value takes precedence (since the agent max step will never be reached).
///
/// Lastly, note that at any step the policy to the agent is allowed to
/// change model with <see cref="GiveModel"/>.
/// change model with <see cref="SetModel"/>.
///
/// Implementation-wise, it is required that this class is extended and the
/// virtual methods overridden. For sample implementations of agent behavior,

ReloadPolicy();
}
/// <summary>
/// Updates the type of behavior for the agent.
/// </summary>
/// <param name="behaviorType"> The new behaviorType for the Agent.</param>
public void SetBehaviorType(BehaviorType behaviorType)
internal void ReloadPolicy()
if (m_PolicyFactory.behaviorType == behaviorType)
if (!m_Initialized)
// If we haven't initialized yet, no need to make any changes now; they'll
// happen in LazyInitialize later.
m_PolicyFactory.behaviorType = behaviorType;
ReloadPolicy();
}
internal void ReloadPolicy()
{
}
/// <summary>

{
m_RequestAction = false;
OnActionReceived(m_Action.vectorActions);
}
if ((m_StepCount >= maxStep) && (maxStep > 0))

35
com.unity.ml-agents/Runtime/Policies/BehaviorParameters.cs


/// <summary>
/// The neural network model used when in inference mode.
/// This cannot be set directly; use <see cref="Agent.GiveModel(string,NNModel,InferenceDevice)"/>
/// to set it.
/// This should not be set at runtime; use <see cref="Agent.SetModel(string,NNModel,InferenceDevice)"/>
/// to set it instead.
internal set { m_Model = value; }
set { m_Model = value; UpdateAgentPolicy(); }
}
[HideInInspector, SerializeField]

/// How inference is performed for this Agent's model.
/// This cannot be set directly; use <see cref="Agent.GiveModel(string,NNModel,InferenceDevice)"/>
/// to set it.
/// This should not be set at runtime; use <see cref="Agent.SetModel(string,NNModel,InferenceDevice)"/>
/// to set it instead.
internal set { m_InferenceDevice = value; }
set { m_InferenceDevice = value; UpdateAgentPolicy();}
}
[HideInInspector, SerializeField]

/// The BehaviorType for the Agent.
/// This cannot be set directly; use <see cref="Agent.SetBehaviorType(BehaviorType)"/>
/// to set it.
internal set { m_BehaviorType = value; }
set { m_BehaviorType = value; UpdateAgentPolicy(); }
}
[HideInInspector, SerializeField]

/// The name of this behavior, which is used as a base name. See
/// <see cref="fullyQualifiedBehaviorName"/> for the full name.
/// This cannot be set directly; use <see cref="Agent.GiveModel(string,NNModel,InferenceDevice)"/>
/// to set it.
/// This should not be set at runtime; use <see cref="Agent.SetModel(string,NNModel,InferenceDevice)"/>
/// to set it instead.
internal set { m_BehaviorName = value; }
set { m_BehaviorName = value; UpdateAgentPolicy(); }
}
/// <summary>

/// <summary>
/// Whether or not to use all the sensor components attached to child GameObjects of the agent.
/// Note that changing this after the Agent has been initialized will not have any effect.
internal set { m_UseChildSensors = value; } // TODO make public, don't allow changes at runtime
set { m_UseChildSensors = value; }
}
/// <summary>

default:
return new HeuristicPolicy(heuristic);
}
}
internal void UpdateAgentPolicy()
{
var agent = GetComponent<Agent>();
if (agent == null)
{
return;
}
agent.ReloadPolicy();
}
}
}

12
com.unity.ml-agents/Runtime/Sensors/CameraSensorComponent.cs


/// <summary>
/// Name of the generated <see cref="CameraSensor"/> object.
/// Note that changing this at runtime does not affect how the Agent sorts the sensors.
internal set { m_SensorName = value; }
set { m_SensorName = value; }
}
[HideInInspector, SerializeField, FormerlySerializedAs("width")]

/// Width of the generated observation.
/// Note that changing this after the sensor is created has no effect.
internal set { m_Width = value; }
set { m_Width = value; }
}
[HideInInspector, SerializeField, FormerlySerializedAs("height")]

/// Height of the generated observation.
/// Note that changing this after the sensor is created has no effect.
internal set { m_Height = value; }
set { m_Height = value; }
}
[HideInInspector, SerializeField, FormerlySerializedAs("grayscale")]

/// Whether to generate grayscale images or color.
/// Note that changing this after the sensor is created has no effect.
internal set { m_Grayscale = value; }
set { m_Grayscale = value; }
}
[HideInInspector, SerializeField, FormerlySerializedAs("compression")]

29
com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensor.cs


var startPositionWorld = transform.TransformPoint(startPositionLocal);
var endPositionWorld = transform.TransformPoint(endPositionLocal);
return (StartPositionWorld: startPositionWorld, EndPositionWorld: endPositionWorld);
return (StartPositionWorld : startPositionWorld, EndPositionWorld : endPositionWorld);
}
/// <summary>

/// <param name="rayInput">The inputs for the sensor.</param>
public RayPerceptionSensor(string name, RayPerceptionInput rayInput)
{
var numObservations = rayInput.OutputSize();
m_Shape = new[] { numObservations };
m_Observations = new float[numObservations];
SetNumObservations(rayInput.OutputSize());
if (Application.isEditor)
{

internal void SetRayPerceptionInput(RayPerceptionInput input)
void SetNumObservations(int numObservations)
// TODO make sure that number of rays and tags don't change
m_RayPerceptionInput = input;
m_Shape = new[] { numObservations };
m_Observations = new float[numObservations];
}
internal void SetRayPerceptionInput(RayPerceptionInput rayInput)
{
// Note that change the number of rays or tags doesn't directly call this,
// but changing them and then changing another field will.
if (m_RayPerceptionInput.OutputSize() != rayInput.OutputSize())
{
Debug.Log(
"Changing the number of tags or rays at runtime is not " +
"supported and may cause errors in training or inference."
);
// Changing the shape will probably break things downstream, but we can at least
// keep this consistent.
SetNumObservations(rayInput.OutputSize());
}
m_RayPerceptionInput = rayInput;
}
/// <summary>

26
com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensorComponentBase.cs


/// <summary>
/// The name of the Sensor that this component wraps.
/// Note that changing this at runtime does not affect how the Agent sorts the sensors.
get => m_SensorName;
// Restrict the access on the name, since changing it a runtime doesn't re-sort the Agent sensors.
internal set => m_SensorName = value;
get { return m_SensorName; }
set { m_SensorName = value; }
}
[SerializeField, FormerlySerializedAs("detectableTags")]

/// <summary>
/// List of tags in the scene to compare against.
/// Note that this should not be changed at runtime.
get => m_DetectableTags;
// Note: can't change at runtime
internal set => m_DetectableTags = value;
get { return m_DetectableTags; }
set { m_DetectableTags = value; }
}
[HideInInspector, SerializeField, FormerlySerializedAs("raysPerDirection")]

/// <summary>
/// Number of rays to the left and right of center.
/// Note that this should not be changed at runtime.
get => m_RaysPerDirection;
get { return m_RaysPerDirection; }
internal set => m_RaysPerDirection = value;
set { m_RaysPerDirection = value;}
}
[HideInInspector, SerializeField, FormerlySerializedAs("maxRayDegrees")]

public LayerMask rayLayerMask
{
get => m_RayLayerMask;
set { m_RayLayerMask = value; UpdateSensor();}
set { m_RayLayerMask = value; UpdateSensor(); }
}
[HideInInspector, SerializeField, FormerlySerializedAs("observationStacks")]

/// <summary>
/// Whether to stack previous observations. Using 1 means no previous observations.
/// Note that changing this after the sensor is created has no effect.
internal int observationStacks
public int observationStacks
get => m_ObservationStacks;
set => m_ObservationStacks = value; // Note: can't change at runtime
get { return m_ObservationStacks; }
set { m_ObservationStacks = value; }
}
/// <summary>

6
com.unity.ml-agents/Runtime/Sensors/RenderTextureSensorComponent.cs


/// <summary>
/// Name of the generated <see cref="RenderTextureSensor"/>.
/// Note that changing this at runtime does not affect how the Agent sorts the sensors.
internal set { m_SensorName = value; }
set { m_SensorName = value; }
}
[HideInInspector, SerializeField, FormerlySerializedAs("grayscale")]

/// Whether the RenderTexture observation should be converted to grayscale or not.
/// Note that changing this after the sensor is created has no effect.
internal set { m_Grayscale = value; }
set { m_Grayscale = value; }
}
[HideInInspector, SerializeField, FormerlySerializedAs("compression")]

16
com.unity.ml-agents/Editor/EditorUtilities.cs


using UnityEngine;
namespace MLAgents.Editor
{
public static class EditorUtilities
{
/// <summary>
/// Whether or not properties that affect the model can be updated at the current time.
/// </summary>
/// <returns></returns>
public static bool CanUpdateModelProperties()
{
return !Application.isPlaying;
}
}
}

11
com.unity.ml-agents/Editor/EditorUtilities.cs.meta


fileFormatVersion: 2
guid: 840f5a76642c24b789ee312f0aa8e33b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

8
com.unity.ml-agents/Tests/Editor/PublicAPI.meta


fileFormatVersion: 2
guid: f5aa894d83ebc411581c8475cd2f9ae0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

144
com.unity.ml-agents/Tests/Editor/PublicAPI/PublicApiValidation.cs


using System.Collections.Generic;
using MLAgents;
using MLAgents.Policies;
using MLAgents.Sensors;
using NUnit.Framework;
using UnityEngine;
namespace MLAgentsExamples
{
/// <summary>
/// The purpose of these tests is to make sure that we can do basic operations like creating
/// an Agent and adding components from code without requiring access to internal methods.
/// The tests aren't intended to add extra test coverage (although they might) and might
/// not check any conditions.
/// </summary>
[TestFixture]
public class PublicApiValidation
{
[Test]
public void CheckSetupCameraSensorComponent()
{
var gameObject = new GameObject();
var width = 24;
var height = 16;
var sensorComponent = gameObject.AddComponent<CameraSensorComponent>();
sensorComponent.camera = Camera.main;
sensorComponent.sensorName = "camera1";
sensorComponent.width = width;
sensorComponent.height = height;
sensorComponent.grayscale = true;
// Make sure the sets actually applied
Assert.AreEqual("camera1", sensorComponent.sensorName);
Assert.AreEqual(width, sensorComponent.width);
Assert.AreEqual(height, sensorComponent.height);
Assert.IsTrue(sensorComponent.grayscale);
}
[Test]
public void CheckSetupRenderTextureSensorComponent()
{
var gameObject = new GameObject();
var sensorComponent = gameObject.AddComponent<RenderTextureSensorComponent>();
var width = 24;
var height = 16;
var texture = new RenderTexture(width, height, 0);
sensorComponent.renderTexture = texture;
sensorComponent.sensorName = "rtx1";
sensorComponent.grayscale = true;
// Make sure the sets actually applied
Assert.AreEqual("rtx1", sensorComponent.sensorName);
Assert.IsTrue(sensorComponent.grayscale);
}
[Test]
public void CheckSetupRayPerceptionSensorComponent()
{
var gameObject = new GameObject();
var sensorComponent = gameObject.AddComponent<RayPerceptionSensorComponent3D>();
sensorComponent.sensorName = "ray3d";
sensorComponent.detectableTags = new List<string> { "Player", "Respawn" };
sensorComponent.raysPerDirection = 3;
sensorComponent.maxRayDegrees = 30;
sensorComponent.sphereCastRadius = .1f;
sensorComponent.rayLayerMask = 0;
sensorComponent.observationStacks = 2;
sensorComponent.CreateSensor();
}
class PublicApiAgent : Agent
{
public int numHeuristicCalls;
public override float[] Heuristic()
{
numHeuristicCalls++;
return base.Heuristic();
}
}
[Test]
public void CheckSetupAgent()
{
var gameObject = new GameObject();
var behaviorParams = gameObject.AddComponent<BehaviorParameters>();
behaviorParams.brainParameters.vectorObservationSize = 3;
behaviorParams.brainParameters.numStackedVectorObservations = 2;
behaviorParams.brainParameters.vectorActionDescriptions = new[] { "TestActionA", "TestActionB" };
behaviorParams.brainParameters.vectorActionSize = new[] { 2, 2 };
behaviorParams.brainParameters.vectorActionSpaceType = SpaceType.Discrete;
behaviorParams.behaviorName = "TestBehavior";
behaviorParams.TeamId = 42;
behaviorParams.useChildSensors = true;
var agent = gameObject.AddComponent<PublicApiAgent>();
// Make sure we can set the behavior type correctly after the agent is added
behaviorParams.behaviorType = BehaviorType.InferenceOnly;
// TODO - not internal yet
// var decisionRequester = gameObject.AddComponent<DecisionRequester>();
// decisionRequester.DecisionPeriod = 2;
var sensorComponent = gameObject.AddComponent<RayPerceptionSensorComponent3D>();
sensorComponent.sensorName = "ray3d";
sensorComponent.detectableTags = new List<string> { "Player", "Respawn" };
sensorComponent.raysPerDirection = 3;
// ISensor isn't set up yet.
Assert.IsNull(sensorComponent.raySensor);
agent.LazyInitialize();
// Make sure we can set the behavior type correctly after the agent is initialized
// (this creates a new policy).
behaviorParams.behaviorType = BehaviorType.HeuristicOnly;
// Initialization should set up the sensors
Assert.IsNotNull(sensorComponent.raySensor);
// Let's change the inference device
var otherDevice = behaviorParams.inferenceDevice == InferenceDevice.CPU ? InferenceDevice.GPU : InferenceDevice.CPU;
agent.SetModel(behaviorParams.behaviorName, behaviorParams.model, otherDevice);
agent.AddReward(1.0f);
agent.RequestAction();
agent.RequestDecision();
Academy.Instance.AutomaticSteppingEnabled = false;
Academy.Instance.EnvironmentStep();
var actions = agent.GetAction();
// default Heuristic implementation should return zero actions.
Assert.AreEqual(new[] {0.0f, 0.0f}, actions);
Assert.AreEqual(1, agent.numHeuristicCalls);
}
}
}

3
com.unity.ml-agents/Tests/Editor/PublicAPI/PublicApiValidation.cs.meta


fileFormatVersion: 2
guid: 016a3ac45b0345e3ab95f14ecaabdb11
timeCreated: 1583858370

26
com.unity.ml-agents/Tests/Editor/PublicAPI/Unity.ML-Agents.Editor.Tests.PublicAPI.asmdef


{
"name": "Unity.ML-Agents.Editor.Tests.PublicAPI",
"references": [
"Unity.ML-Agents.Editor",
"Unity.ML-Agents",
"Barracuda",
"Unity.ML-Agents.CommunicatorObjects"
],
"optionalUnityReferences": [
"TestAssemblies"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"System.IO.Abstractions.dll",
"System.IO.Abstractions.TestingHelpers.dll"
],
"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
]
}

7
com.unity.ml-agents/Tests/Editor/PublicAPI/Unity.ML-Agents.Editor.Tests.PublicAPI.asmdef.meta


fileFormatVersion: 2
guid: 38254a2538c8f42fb9f2057d17fd0e70
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存