浏览代码

apply Rider suggestions to API code (#3847)

/release_1_branch
GitHub 5 年前
当前提交
d4bbecc1
共有 21 个文件被更改,包括 50 次插入57 次删除
  1. 10
      com.unity.ml-agents/Runtime/Academy.cs
  2. 2
      com.unity.ml-agents/Runtime/Agent.cs
  3. 1
      com.unity.ml-agents/Runtime/Communicator/ICommunicator.cs
  4. 1
      com.unity.ml-agents/Runtime/Demonstrations/DemonstrationMetaData.cs
  5. 2
      com.unity.ml-agents/Runtime/Demonstrations/DemonstrationWriter.cs
  6. 1
      com.unity.ml-agents/Runtime/Inference/BarracudaModelParamLoader.cs
  7. 4
      com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs
  8. 4
      com.unity.ml-agents/Runtime/Sensors/CameraSensor.cs
  9. 4
      com.unity.ml-agents/Runtime/Sensors/RenderTextureSensor.cs
  10. 2
      com.unity.ml-agents/Runtime/SideChannels/EngineConfigurationChannel.cs
  11. 2
      com.unity.ml-agents/Runtime/SideChannels/FloatPropertiesChannel.cs
  12. 34
      com.unity.ml-agents/Runtime/SideChannels/SideChannelsManager.cs
  13. 4
      com.unity.ml-agents/Runtime/Timer.cs
  14. 2
      com.unity.ml-agents/Tests/Editor/AcademyTests.cs
  15. 1
      com.unity.ml-agents/Tests/Editor/BehaviorParameterTests.cs
  16. 1
      com.unity.ml-agents/Tests/Editor/Communicator/RpcCommunicatorTests.cs
  17. 2
      com.unity.ml-agents/Tests/Editor/DemonstrationTests.cs
  18. 1
      com.unity.ml-agents/Tests/Editor/MLAgentsEditModeTest.cs
  19. 12
      com.unity.ml-agents/Tests/Editor/ModelRunnerTest.cs
  20. 14
      com.unity.ml-agents/Tests/Editor/ParameterLoaderTest.cs
  21. 3
      com.unity.ml-agents/Tests/Editor/PublicAPI/PublicApiValidation.cs

10
com.unity.ml-agents/Runtime/Academy.cs


///
/// At initialization, the Academy attempts to connect to the Python training process through
/// the external communicator. If successful, the training process can train <see cref="Agent"/>
/// instances. When you set an agent's <see cref="BehaviorParameters.behaviorType"/> setting
/// instances. When you set an agent's <see cref="BehaviorParameters.BehaviorType"/> setting
/// to <see cref="BehaviorType.Default"/>, the agent exchanges data with the training process
/// to make decisions. If no training process is available, agents with the default behavior
/// fall back to inference or heuristic decisions. (You can also set agents to always use

const int k_EditorTrainingPort = 5004;
const string k_portCommandLineFlag = "--mlagents-port";
const string k_PortCommandLineFlag = "--mlagents-port";
// Lazy initializer pattern, see https://csharpindepth.com/articles/singleton#lazy
static Lazy<Academy> s_Lazy = new Lazy<Academy>(() => new Academy());

var inputPort = "";
for (var i = 0; i < args.Length; i++)
{
if (args[i] == k_portCommandLineFlag)
if (args[i] == k_PortCommandLineFlag)
{
inputPort = args[i + 1];
}

}
}
private EnvironmentParameters m_EnvironmentParameters;
private StatsRecorder m_StatsRecorder;
EnvironmentParameters m_EnvironmentParameters;
StatsRecorder m_StatsRecorder;
/// <summary>
/// Returns the <see cref="EnvironmentParameters"/> instance. If training

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


/// Use the <see cref="OnActionReceived"/> function to implement the actions your agent can take,
/// such as moving to reach a goal or interacting with its environment.
///
/// When you call <see cref="EndEpisode"/> on an agent or the agent reaches its <see cref="maxStep"/> count,
/// When you call <see cref="EndEpisode"/> on an agent or the agent reaches its <see cref="MaxStep"/> count,
/// its current episode ends. You can reset the agent -- or remove it from the
/// environment -- by implementing the <see cref="OnEpisodeBegin"/> function. An agent also
/// becomes done when the <see cref="Academy"/> resets the environment, which only happens when

1
com.unity.ml-agents/Runtime/Communicator/ICommunicator.cs


using System.Collections.Generic;
using Unity.MLAgents.Policies;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.SideChannels;
namespace Unity.MLAgents
{

1
com.unity.ml-agents/Runtime/Demonstrations/DemonstrationMetaData.cs


using System;
using UnityEngine;
using Unity.MLAgents.Policies;
using UnityEngine.Serialization;
namespace Unity.MLAgents.Demonstrations

2
com.unity.ml-agents/Runtime/Demonstrations/DemonstrationWriter.cs


public class DemonstrationWriter
{
/// <summary>
/// Number of bytes reserved for the <see cref="Demonstration"/> metadata at the start of the demo file.
/// Number of bytes reserved for the <see cref="DemonstrationMetaData"/> at the start of the demo file.
/// </summary>
internal const int MetaDataBytes = 32;

1
com.unity.ml-agents/Runtime/Inference/BarracudaModelParamLoader.cs


/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="sensorComponents">Attached sensor components</param>
/// <param name="behaviorType">BehaviorType or the Agent to check.</param>
/// <returns>The list the error messages of the checks that failed</returns>
public static IEnumerable<string> CheckModel(Model model, BrainParameters brainParameters,
SensorComponent[] sensorComponents, BehaviorType behaviorType = BehaviorType.Default)

4
com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs


public delegate void ActionGenerator(float[] actionsOut);
ActionGenerator m_Heuristic;
float[] m_LastDecision;
int m_numActions;
bool m_Done;
bool m_DecisionRequested;

public HeuristicPolicy(ActionGenerator heuristic, int numActions)
{
m_Heuristic = heuristic;
m_numActions = numActions;
m_LastDecision = new float[m_numActions];
m_LastDecision = new float[numActions];
}
/// <inheritdoc />

4
com.unity.ml-agents/Runtime/Sensors/CameraSensor.cs


{
// Edit Mode tests complain if we use Destroy()
// TODO move to extension methods for UnityEngine.Object?
UnityEngine.Object.DestroyImmediate(texture);
Object.DestroyImmediate(texture);
UnityEngine.Object.Destroy(texture);
Object.Destroy(texture);
}
}
}

4
com.unity.ml-agents/Runtime/Sensors/RenderTextureSensor.cs


{
// Edit Mode tests complain if we use Destroy()
// TODO move to extension methods for UnityEngine.Object?
UnityEngine.Object.DestroyImmediate(texture);
Object.DestroyImmediate(texture);
UnityEngine.Object.Destroy(texture);
Object.Destroy(texture);
}
}
}

2
com.unity.ml-agents/Runtime/SideChannels/EngineConfigurationChannel.cs


/// </summary>
internal class EngineConfigurationChannel : SideChannel
{
private enum ConfigurationType : int
enum ConfigurationType : int
{
ScreenResolution = 0,
QualityLevel = 1,

2
com.unity.ml-agents/Runtime/SideChannels/FloatPropertiesChannel.cs


{
Dictionary<string, float> m_FloatProperties = new Dictionary<string, float>();
Dictionary<string, Action<float>> m_RegisteredActions = new Dictionary<string, Action<float>>();
private const string k_FloatPropertiesDefaultId = "60ccf7d0-4f7e-11ea-b238-784f4387d1f7";
const string k_FloatPropertiesDefaultId = "60ccf7d0-4f7e-11ea-b238-784f4387d1f7";
/// <summary>
/// Initializes the side channel with the provided channel ID.

34
com.unity.ml-agents/Runtime/SideChannels/SideChannelsManager.cs


/// </summary>
public static class SideChannelsManager
{
private static Dictionary<Guid, SideChannel> RegisteredChannels = new Dictionary<Guid, SideChannel>();
static Dictionary<Guid, SideChannel> s_RegisteredChannels = new Dictionary<Guid, SideChannel>();
private struct CachedSideChannelMessage
struct CachedSideChannelMessage
private static readonly Queue<CachedSideChannelMessage> m_CachedMessages =
static readonly Queue<CachedSideChannelMessage> s_CachedMessages =
new Queue<CachedSideChannelMessage>();
/// <summary>

public static void RegisterSideChannel(SideChannel sideChannel)
{
var channelId = sideChannel.ChannelId;
if (RegisteredChannels.ContainsKey(channelId))
if (s_RegisteredChannels.ContainsKey(channelId))
{
throw new UnityAgentsException(
$"A side channel with id {channelId} is already registered. " +

// Process any messages that we've already received for this channel ID.
var numMessages = m_CachedMessages.Count;
var numMessages = s_CachedMessages.Count;
var cachedMessage = m_CachedMessages.Dequeue();
var cachedMessage = s_CachedMessages.Dequeue();
if (channelId == cachedMessage.ChannelId)
{
sideChannel.ProcessMessage(cachedMessage.Message);

m_CachedMessages.Enqueue(cachedMessage);
s_CachedMessages.Enqueue(cachedMessage);
RegisteredChannels.Add(channelId, sideChannel);
s_RegisteredChannels.Add(channelId, sideChannel);
}
/// <summary>

/// <param name="sideChannel">The side channel to unregister.</param>
public static void UnregisterSideChannel(SideChannel sideChannel)
{
if (RegisteredChannels.ContainsKey(sideChannel.ChannelId))
if (s_RegisteredChannels.ContainsKey(sideChannel.ChannelId))
RegisteredChannels.Remove(sideChannel.ChannelId);
s_RegisteredChannels.Remove(sideChannel.ChannelId);
}
}

internal static void UnregisterAllSideChannels()
{
RegisteredChannels = new Dictionary<Guid, SideChannel>();
s_RegisteredChannels = new Dictionary<Guid, SideChannel>();
}
/// <summary>

/// <returns></returns>
internal static T GetSideChannel<T>() where T: SideChannel
{
foreach (var sc in RegisteredChannels.Values)
foreach (var sc in s_RegisteredChannels.Values)
{
if (sc.GetType() == typeof(T))
{

/// <returns></returns>
internal static byte[] GetSideChannelMessage()
{
return GetSideChannelMessage(RegisteredChannels);
return GetSideChannelMessage(s_RegisteredChannels);
}
/// <summary>

/// <param name="dataReceived">The byte array of data received from Python.</param>
internal static void ProcessSideChannelData(byte[] dataReceived)
{
ProcessSideChannelData(RegisteredChannels, dataReceived);
ProcessSideChannelData(s_RegisteredChannels, dataReceived);
}
/// <summary>

/// <param name="dataReceived">The byte array of data received from Python.</param>
internal static void ProcessSideChannelData(Dictionary<Guid, SideChannel> sideChannels, byte[] dataReceived)
{
while (m_CachedMessages.Count != 0)
while (s_CachedMessages.Count != 0)
var cachedMessage = m_CachedMessages.Dequeue();
var cachedMessage = s_CachedMessages.Dequeue();
if (sideChannels.ContainsKey(cachedMessage.ChannelId))
{
sideChannels[cachedMessage.ChannelId].ProcessMessage(cachedMessage.Message);

{
// Don't recognize this ID, but cache it in case the SideChannel that can handle
// it is registered before the next call to ProcessSideChannelData.
m_CachedMessages.Enqueue(new CachedSideChannelMessage
s_CachedMessages.Enqueue(new CachedSideChannelMessage
{
ChannelId = channelId,
Message = message

4
com.unity.ml-agents/Runtime/Timer.cs


internal class RootNode : TimerNode
{
// Timer output format version
internal const string k_timerFormatVersion = "0.1.0";
internal const string k_TimerFormatVersion = "0.1.0";
[DataMember(Name = "metadata", Order = 0)]
Dictionary<string, string> m_Metadata = new Dictionary<string, string>();

public RootNode(string name="root") : base(name, true)
{
m_Metadata.Add("timer_format_version", k_timerFormatVersion);
m_Metadata.Add("timer_format_version", k_TimerFormatVersion);
m_Metadata.Add("start_time_seconds", $"{DateTimeOffset.Now.ToUnixTimeSeconds()}");
m_Metadata.Add("unity_version", Application.unityVersion);
m_Metadata.Add("command_line_arguments", String.Join(" ", Environment.GetCommandLineArgs()));

2
com.unity.ml-agents/Tests/Editor/AcademyTests.cs


using NUnit.Framework;
using UnityEngine;
#if UNITY_2019_3_OR_NEWER
#endif
namespace Unity.MLAgents.Tests
{

1
com.unity.ml-agents/Tests/Editor/BehaviorParameterTests.cs


using NUnit.Framework;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Policies;
namespace Unity.MLAgents.Tests

1
com.unity.ml-agents/Tests/Editor/Communicator/RpcCommunicatorTests.cs


using System;
using System.Collections;
using System.Text.RegularExpressions;
using NUnit.Framework;
using UnityEngine;

2
com.unity.ml-agents/Tests/Editor/DemonstrationTests.cs


bp.BrainParameters.VectorActionSize = new[] { 2, 2 };
bp.BrainParameters.VectorActionSpaceType = SpaceType.Discrete;
var agent = gameobj.AddComponent<TestAgent>();
gameobj.AddComponent<TestAgent>();
Assert.IsFalse(fileSystem.Directory.Exists(k_DemoDirectory));

1
com.unity.ml-agents/Tests/Editor/MLAgentsEditModeTest.cs


using System.CodeDom;
using System;
using UnityEngine;
using NUnit.Framework;

12
com.unity.ml-agents/Tests/Editor/ModelRunnerTest.cs


Test3DSensorComponent sensor_21_20_3;
Test3DSensorComponent sensor_20_22_3;
private BrainParameters GetContinuous2vis8vec2actionBrainParameters()
BrainParameters GetContinuous2vis8vec2actionBrainParameters()
validBrainParameters.VectorActionSize = new int[] { 2 };
validBrainParameters.VectorActionSize = new [] { 2 };
private BrainParameters GetDiscrete1vis0vec_2_3action_recurrModelBrainParameters()
BrainParameters GetDiscrete1vis0vec_2_3action_recurrModelBrainParameters()
validBrainParameters.VectorActionSize = new int[] { 2, 3 };
validBrainParameters.VectorActionSize = new [] { 2, 3 };
validBrainParameters.NumStackedVectorObservations = 1;
validBrainParameters.VectorActionSpaceType = SpaceType.Discrete;
return validBrainParameters;

var modelRunner = new ModelRunner(discrete1vis0vec_2_3action_recurrModel, brainParameters);
var info1 = new AgentInfo();
info1.episodeId = 1;
modelRunner.PutObservations(info1, new ISensor[] { sensor_21_20_3.CreateSensor() }.ToList());
modelRunner.PutObservations(info1, new [] { sensor_21_20_3.CreateSensor() }.ToList());
modelRunner.PutObservations(info2, new ISensor[] { sensor_21_20_3.CreateSensor() }.ToList());
modelRunner.PutObservations(info2, new [] { sensor_21_20_3.CreateSensor() }.ToList());
modelRunner.DecideBatch();

14
com.unity.ml-agents/Tests/Editor/ParameterLoaderTest.cs


public int[] GetObservationShape()
{
return new int[] {m_Height, m_Width, m_Channels };
return new [] {m_Height, m_Width, m_Channels };
}
public int Write(ObservationWriter writer)

Test3DSensorComponent sensor_21_20_3;
Test3DSensorComponent sensor_20_22_3;
private BrainParameters GetContinuous2vis8vec2actionBrainParameters()
BrainParameters GetContinuous2vis8vec2actionBrainParameters()
validBrainParameters.VectorActionSize = new int[] { 2 };
validBrainParameters.VectorActionSize = new [] { 2 };
private BrainParameters GetDiscrete1vis0vec_2_3action_recurrModelBrainParameters()
BrainParameters GetDiscrete1vis0vec_2_3action_recurrModelBrainParameters()
validBrainParameters.VectorActionSize = new int[] { 2, 3 };
validBrainParameters.VectorActionSize = new [] { 2, 3 };
validBrainParameters.NumStackedVectorObservations = 1;
validBrainParameters.VectorActionSpaceType = SpaceType.Discrete;
return validBrainParameters;

var model = ModelLoader.Load(continuous2vis8vec2actionModel);
var brainParameters = GetContinuous2vis8vec2actionBrainParameters();
brainParameters.VectorActionSize = new int[] { 3 }; // Invalid action
brainParameters.VectorActionSize = new [] { 3 }; // Invalid action
var errors = BarracudaModelParamLoader.CheckModel(model, brainParameters, new SensorComponent[] { sensor_21_20_3, sensor_20_22_3 });
Assert.Greater(errors.Count(), 0);

var model = ModelLoader.Load(discrete1vis0vec_2_3action_recurrModel);
var brainParameters = GetDiscrete1vis0vec_2_3action_recurrModelBrainParameters();
brainParameters.VectorActionSize = new int[] { 3, 3 }; // Invalid action
brainParameters.VectorActionSize = new [] { 3, 3 }; // Invalid action
var errors = BarracudaModelParamLoader.CheckModel(model, brainParameters, new SensorComponent[] { sensor_21_20_3 });
Assert.Greater(errors.Count(), 0);

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


using System.Collections.Generic;
using Unity.MLAgents;
using Unity.MLAgents.Policies;
using UnityEngine.TestTools;
namespace Unity.MLAgentsExamples
{

正在加载...
取消
保存