浏览代码

Format code and add .editorconfig to our package. (#3305)

/asymm-envs
GitHub 5 年前
当前提交
18fc5131
共有 50 个文件被更改,包括 197 次插入166 次删除
  1. 2
      com.unity.ml-agents/Editor/BehaviorParametersEditor.cs
  2. 2
      com.unity.ml-agents/Editor/BrainParametersDrawer.cs
  3. 1
      com.unity.ml-agents/Editor/DemonstrationDrawer.cs
  4. 14
      com.unity.ml-agents/Runtime/Academy.cs
  5. 15
      com.unity.ml-agents/Runtime/Agent.cs
  6. 4
      com.unity.ml-agents/Runtime/Constants.cs
  7. 5
      com.unity.ml-agents/Runtime/DecisionRequester.cs
  8. 2
      com.unity.ml-agents/Runtime/DemonstrationRecorder.cs
  9. 2
      com.unity.ml-agents/Runtime/EpisodeIdCounter.cs
  10. 2
      com.unity.ml-agents/Runtime/Grpc/GrpcExtensions.cs
  11. 33
      com.unity.ml-agents/Runtime/Grpc/RpcCommunicator.cs
  12. 2
      com.unity.ml-agents/Runtime/InferenceBrain/ApplierImpl.cs
  13. 2
      com.unity.ml-agents/Runtime/InferenceBrain/BarracudaModelParamLoader.cs
  14. 4
      com.unity.ml-agents/Runtime/InferenceBrain/GeneratorImpl.cs
  15. 1
      com.unity.ml-agents/Runtime/InferenceBrain/ModelRunner.cs
  16. 2
      com.unity.ml-agents/Runtime/Monitor.cs
  17. 1
      com.unity.ml-agents/Runtime/Policy/BarracudaPolicy.cs
  18. 8
      com.unity.ml-agents/Runtime/Policy/BehaviorParameters.cs
  19. 2
      com.unity.ml-agents/Runtime/Policy/HeuristicPolicy.cs
  20. 2
      com.unity.ml-agents/Runtime/Policy/IPolicy.cs
  21. 4
      com.unity.ml-agents/Runtime/Sensor/CameraSensor.cs
  22. 2
      com.unity.ml-agents/Runtime/Sensor/CameraSensorComponent.cs
  23. 3
      com.unity.ml-agents/Runtime/Sensor/ISensor.cs
  24. 10
      com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensor.cs
  25. 2
      com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensorComponent2D.cs
  26. 2
      com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensorComponent3D.cs
  27. 7
      com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensorComponentBase.cs
  28. 6
      com.unity.ml-agents/Runtime/Sensor/RenderTextureSensor.cs
  29. 2
      com.unity.ml-agents/Runtime/Sensor/RenderTextureSensorComponent.cs
  30. 2
      com.unity.ml-agents/Runtime/Sensor/SensorBase.cs
  31. 3
      com.unity.ml-agents/Runtime/Sensor/SensorShapeValidator.cs
  32. 1
      com.unity.ml-agents/Runtime/Sensor/StackingSensor.cs
  33. 1
      com.unity.ml-agents/Runtime/Sensor/VectorSensor.cs
  34. 1
      com.unity.ml-agents/Runtime/SideChannel/EngineConfigurationChannel.cs
  35. 2
      com.unity.ml-agents/Runtime/SideChannel/FloatPropertiesChannel.cs
  36. 10
      com.unity.ml-agents/Runtime/SideChannel/RawBytesChannel.cs
  37. 7
      com.unity.ml-agents/Runtime/SideChannel/SideChannel.cs
  38. 4
      com.unity.ml-agents/Runtime/Timer.cs
  39. 1
      com.unity.ml-agents/Runtime/Utilities.cs
  40. 4
      com.unity.ml-agents/Tests/Editor/DemonstrationTests.cs
  41. 8
      com.unity.ml-agents/Tests/Editor/EditModeTestInternalBrainTensorApplier.cs
  42. 14
      com.unity.ml-agents/Tests/Editor/EditModeTestInternalBrainTensorGenerator.cs
  43. 24
      com.unity.ml-agents/Tests/Editor/MLAgentsEditModeTest.cs
  44. 2
      com.unity.ml-agents/Tests/Editor/Sensor/FloatVisualSensorTests.cs
  45. 4
      com.unity.ml-agents/Tests/Editor/Sensor/RayPerceptionSensorTests.cs
  46. 26
      com.unity.ml-agents/Tests/Editor/Sensor/StackingSensorTests.cs
  47. 23
      com.unity.ml-agents/Tests/Editor/Sensor/VectorSensorTests.cs
  48. 6
      com.unity.ml-agents/Tests/Editor/Sensor/WriterAdapterTests.cs
  49. 2
      com.unity.ml-agents/Tests/Editor/SideChannelTests.cs
  50. 74
      com.unity.ml-agents/.editorconfig

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


var model = (NNModel)serializedObject.FindProperty("m_Model").objectReferenceValue;
var behaviorParameters = (BehaviorParameters)target;
SensorComponent[] sensorComponents;
if(behaviorParameters.useChildSensors)
if (behaviorParameters.useChildSensors)
{
sensorComponents = behaviorParameters.GetComponentsInChildren<SensorComponent>();
}

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


{
return GetHeightDrawVectorObservation() +
GetHeightDrawVectorAction(property);
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
position.height = k_LineHeight;

1
com.unity.ml-agents/Editor/DemonstrationDrawer.cs


return actionLabel.ToString();
}
/// <summary>
/// Renders Inspector UI for Brain Parameters of Demonstration.
/// </summary>

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


void ResetActions()
{
DecideAction = () => { };
DestroyAction = () => { };
AgentSetStatus = i => { };
AgentSendState = () => { };
AgentAct = () => { };
AgentForceReset = () => { };
OnEnvironmentReset = () => { };
DecideAction = () => {};
DestroyAction = () => {};
AgentSetStatus = i => {};
AgentSendState = () => {};
AgentAct = () => {};
AgentForceReset = () => {};
OnEnvironmentReset = () => {};
}
static void OnQuitCommandReceived()

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


/// </summary>
public struct AgentInfo
{
/// <summary>
/// Keeps track of the last vector action taken by the Brain.
/// </summary>

{
public float[] vectorActions;
}
/// <summary>

m_Info.maxStepReached = maxStepReached;
// Request the last decision with no callbacks
// We request a decision so Python knows the Agent is done immediately
m_Brain?.RequestDecision(m_Info, sensors, (a) => { });
m_Brain?.RequestDecision(m_Info, sensors, (a) => {});
// The Agent is done, so we give it a new episode Id
m_EpisodeId = EpisodeIdCounter.GetEpisodeId();
m_Reward = 0f;

{
NotifyAgentDone();
_AgentReset();
}
/// <summary>

{
}
/// <summary>
/// When the Agent uses Heuristics, it will call this method every time it
/// needs an action. This can be used for debugging or controlling the agent

public virtual float[] Heuristic()
{
throw new UnityAgentsException(string.Format(
"The Heuristic method was not implemented for the Agent on the " +
"{0} GameObject.",
gameObject.name));
"The Heuristic method was not implemented for the Agent on the " +
"{0} GameObject.",
gameObject.name));
}
/// <summary>

{
m_Recorder.WriteExperience(m_Info, sensors);
}
}
void UpdateSensors()

return rawAction * range + middle;
}
/// <summary>
/// Signals the agent that it must sent its decision to the brain.
/// </summary>

{
NotifyAgentDone(true);
_AgentReset();
}
else
{

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


/// </summary>
public enum MenuGroup
{
Default=0,
Sensors=50
Default = 0,
Sensors = 50
}
}

5
com.unity.ml-agents/Runtime/DecisionRequester.cs


m_Agent = gameObject.GetComponent<Agent>();
Academy.Instance.AgentSetStatus += MakeRequests;
}
void OnDestroy()
{
if (Academy.IsInitialized)

}
void MakeRequests(int count)
{
if ((count + offset) % DecisionPeriod == 0)

m_Agent?.RequestAction();
}
}
}
}

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


/// Demonstration Recorder Component.
/// </summary>
[RequireComponent(typeof(Agent))]
[AddComponentMenu("ML Agents/Demonstration Recorder", (int) MenuGroup.Default)]
[AddComponentMenu("ML Agents/Demonstration Recorder", (int)MenuGroup.Default)]
public class DemonstrationRecorder : MonoBehaviour
{
public bool record;

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


return Counter++;
}
}
}
}

2
com.unity.ml-agents/Runtime/Grpc/GrpcExtensions.cs


{
public static class GrpcExtensions
{
/// <summary>
/// Converts a AgentInfo to a protobuf generated AgentInfoActionPairProto
/// </summary>

};
return bp;
}
internal static UnityRLInitParameters ToUnityRLInitParameters(this UnityRLInitializationInputProto inputProto)
{

33
com.unity.ml-agents/Runtime/Grpc/RpcCommunicator.cs


/// Responsible for communication with External using gRPC.
public class RpcCommunicator : ICommunicator
{
public struct IdCallbackPair
{
public int AgentId;

/// <param name="brainParameters">Brain parameters needed to send to the trainer.</param>
public void SubscribeBrain(string brainKey, BrainParameters brainParameters)
{
if (m_BehaviorNames.Contains(brainKey))
{
return;

{
ProcessSideChannelData(m_SideChannels, rlInput.SideChannel.ToArray());
SendCommandEvent(rlInput.Command);
}
UnityInputProto Initialize(UnityOutputProto unityOutput,

switch (command)
{
case CommandProto.Quit:
{
QuitCommandReceived?.Invoke();
return;
}
{
QuitCommandReceived?.Invoke();
return;
}
{
foreach (var brainName in m_ActionCallbacks.Keys)
foreach (var brainName in m_ActionCallbacks.Keys)
{
m_ActionCallbacks[brainName].Clear();
}
ResetCommandReceived?.Invoke();
return;
m_ActionCallbacks[brainName].Clear();
ResetCommandReceived?.Invoke();
return;
}
{
return;
}
{
return;
}
}
}

if (m_SideChannels.ContainsKey(sideChannel.ChannelType()))
{
throw new UnityAgentsException(string.Format(
"A side channel with type index {} is already registered. You cannot register multiple " +
"side channels of the same type."));
"A side channel with type index {} is already registered. You cannot register multiple " +
"side channels of the same type."));
}
m_SideChannels.Add(sideChannel.ChannelType(), sideChannel);
}

2
com.unity.ml-agents/Runtime/InferenceBrain/ApplierImpl.cs


{
m_Memories = memories;
}
public void Apply(TensorProxy tensorProxy, IEnumerable<AgentIdActionPair> actions)
{
var agentIndex = 0;

}
}
}
}

2
com.unity.ml-agents/Runtime/InferenceBrain/BarracudaModelParamLoader.cs


int memory,
ModelActionType isContinuous,
SensorComponent[] sensorComponents
)
)
{
var failedModelChecks = new List<string>();
var tensorsNames = GetInputTensors(model).Select(x => x.name).ToList();

4
com.unity.ml-agents/Runtime/InferenceBrain/GeneratorImpl.cs


agentIndex++;
}
}
}
/// <summary>

m_MemoryIndex = memoryIndex;
m_Allocator = allocator;
m_Memories = memories;
}
public void Generate(TensorProxy tensorProxy, int batchSize, IEnumerable<AgentInfoSensorsPair> infos)

}
if (!m_Memories.TryGetValue(info.episodeId, out memory))
{
for (var j = 0; j < memorySize; j++)
{
tensorProxy.data[agentIndex, j] = 0;

{
m_WriteAdapter.SetTarget(tensorProxy, agentIndex, 0);
sensor.Write(m_WriteAdapter);
}
agentIndex++;
}

1
com.unity.ml-agents/Runtime/InferenceBrain/ModelRunner.cs


m_ActionFuncs.Add(new AgentIdActionPair { action = action, agentId = info.episodeId });
}
public void DecideBatch()
{
var currentBatchSize = m_Infos.Count;

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


var displayValues = s_DisplayTransformValues[target];
var index = 0;
var orderedKeys = displayValues.Keys.OrderBy(x => -displayValues[x].time);
var orderedKeys = displayValues.Keys.OrderBy(x => - displayValues[x].time);
foreach (var key in orderedKeys)
{
s_KeyStyle.alignment = TextAnchor.MiddleRight;

1
com.unity.ml-agents/Runtime/Policy/BarracudaPolicy.cs


/// </summary>
public class BarracudaPolicy : IPolicy
{
protected ModelRunner m_ModelRunner;
/// <summary>

8
com.unity.ml-agents/Runtime/Policy/BehaviorParameters.cs


namespace MLAgents
{
[AddComponentMenu("ML Agents/Behavior Parameters", (int) MenuGroup.Default)]
[AddComponentMenu("ML Agents/Behavior Parameters", (int)MenuGroup.Default)]
[Serializable]
private enum BehaviorType
{

[HideInInspector]
[SerializeField]
string m_BehaviorName = "My Behavior";
[HideInInspector] [SerializeField]
[HideInInspector][SerializeField]
int m_TeamID = 0;
[HideInInspector]
[SerializeField]

public string behaviorName
{
}
public IPolicy GeneratePolicy(Func<float[]> heuristic)

2
com.unity.ml-agents/Runtime/Policy/HeuristicPolicy.cs


namespace MLAgents
{
/// <summary>
/// The Heuristic Policy uses a hards coded Heuristic method
/// to take decisions each time the RequestDecision method is

public void Dispose()
{
}
}
}

2
com.unity.ml-agents/Runtime/Policy/IPolicy.cs


/// <summary>
/// IPolicy is connected to a single Agent. Each time the agent needs
/// a decision, it will request a decision to the Policy. The decision
/// will not be taken immediately but will be taken before or when
/// will not be taken immediately but will be taken before or when
/// DecideAction is called.
/// </summary>
public interface IPolicy : IDisposable

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


SensorCompressionType m_CompressionType;
public CameraSensor(Camera camera, int width, int height, bool grayscale, string name,
SensorCompressionType compression)
SensorCompressionType compression)
{
m_Camera = camera;
m_Width = width;

}
}
public void Update() { }
public void Update() {}
public SensorCompressionType GetCompressionType()
{

2
com.unity.ml-agents/Runtime/Sensor/CameraSensorComponent.cs


namespace MLAgents.Sensor
{
[AddComponentMenu("ML Agents/Camera Sensor", (int) MenuGroup.Sensors)]
[AddComponentMenu("ML Agents/Camera Sensor", (int)MenuGroup.Sensors)]
public class CameraSensorComponent : SensorComponent
{
public new Camera camera;

3
com.unity.ml-agents/Runtime/Sensor/ISensor.cs


/// Sensor interface for generating observations.
/// For custom implementations, it is recommended to SensorBase instead.
/// </summary>
public interface ISensor {
public interface ISensor
{
/// <summary>
/// Returns the size of the observations that will be generated.
/// For example, a sensor that observes the velocity of a rigid body (in 3D) would return new {3}.

10
com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensor.cs


}
public RayPerceptionSensor(string name, float rayDistance, List<string> detectableObjects, float[] angles,
Transform transform, float startOffset, float endOffset, float castRadius, CastType castType,
int rayLayerMask)
Transform transform, float startOffset, float endOffset, float castRadius, CastType castType,
int rayLayerMask)
{
var numObservations = (detectableObjects.Count + 2) * angles.Length;
m_Shape = new[] { numObservations };

// For each ray sublist stores categorical information on detected object
// along with object distance.
int bufferOffset = 0;
for (var rayIndex = 0; rayIndex<rayAngles.Count; rayIndex++)
for (var rayIndex = 0; rayIndex < rayAngles.Count; rayIndex++)
{
var angle = rayAngles[rayIndex];
Vector3 startPositionLocal, endPositionLocal;

float hitFraction;
GameObject hitObject;
if(castType == CastType.Cast3D)
if (castType == CastType.Cast3D)
{
RaycastHit rayHit;
if (castRadius > 0f)

else if (Application.isEditor)
{
// Legacy drawing
Debug.DrawRay(startPositionWorld,rayDirection, Color.black, 0.01f, true);
Debug.DrawRay(startPositionWorld, rayDirection, Color.black, 0.01f, true);
}
if (castHit)

2
com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensorComponent2D.cs


namespace MLAgents.Sensor
{
[AddComponentMenu("ML Agents/Ray Perception Sensor 2D", (int) MenuGroup.Sensors)]
[AddComponentMenu("ML Agents/Ray Perception Sensor 2D", (int)MenuGroup.Sensors)]
public class RayPerceptionSensorComponent2D : RayPerceptionSensorComponentBase
{
public RayPerceptionSensorComponent2D()

2
com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensorComponent3D.cs


namespace MLAgents.Sensor
{
[AddComponentMenu("ML Agents/Ray Perception Sensor 3D", (int) MenuGroup.Sensors)]
[AddComponentMenu("ML Agents/Ray Perception Sensor 3D", (int)MenuGroup.Sensors)]
public class RayPerceptionSensorComponent3D : RayPerceptionSensorComponentBase
{
[Header("3D Properties", order = 100)]

7
com.unity.ml-agents/Runtime/Sensor/RayPerceptionSensorComponentBase.cs


anglesOut[0] = 90f;
for (var i = 0; i < raysPerDirection; i++)
{
anglesOut[2 * i + 1] = 90 - (i+1) * delta;
anglesOut[2 * i + 2] = 90 + (i+1) * delta;
anglesOut[2 * i + 1] = 90 - (i + 1) * delta;
anglesOut[2 * i + 2] = 90 + (i + 1) * delta;
}
return anglesOut;
}

var color = Color.Lerp(rayHitColor, rayMissColor, lerpT);
color.a = alpha;
Gizmos.color = color;
Gizmos.DrawRay(startPositionWorld,rayDirection);
Gizmos.DrawRay(startPositionWorld, rayDirection);
// Draw the hit point as a sphere. If using rays to cast (0 radius), use a small sphere.
if (rayInfo.castHit)

}
}
}
}
}

6
com.unity.ml-agents/Runtime/Sensor/RenderTextureSensor.cs


SensorCompressionType m_CompressionType;
public RenderTextureSensor(RenderTexture renderTexture, bool grayscale, string name,
SensorCompressionType compressionType)
SensorCompressionType compressionType)
{
m_RenderTexture = renderTexture;
var width = renderTexture != null ? renderTexture.width : 0;

public byte[] GetCompressedObservation()
{
using(TimerStack.Instance.Scoped("RenderTexSensor.GetCompressedObservation"))
using (TimerStack.Instance.Scoped("RenderTexSensor.GetCompressedObservation"))
{
var texture = ObservationToTexture(m_RenderTexture);
// TODO support more types here, e.g. JPG

}
}
public void Update() { }
public void Update() {}
public SensorCompressionType GetCompressionType()
{

2
com.unity.ml-agents/Runtime/Sensor/RenderTextureSensorComponent.cs


namespace MLAgents.Sensor
{
[AddComponentMenu("ML Agents/Render Texture Sensor", (int) MenuGroup.Sensors)]
[AddComponentMenu("ML Agents/Render Texture Sensor", (int)MenuGroup.Sensors)]
public class RenderTextureSensorComponent : SensorComponent
{
public RenderTexture renderTexture;

2
com.unity.ml-agents/Runtime/Sensor/SensorBase.cs


return numFloats;
}
public void Update() { }
public void Update() {}
public virtual byte[] GetCompressedObservation()
{

3
com.unity.ml-agents/Runtime/Sensor/SensorShapeValidator.cs


namespace MLAgents.Sensor
{
public class SensorShapeValidator
{
private List<int[]> m_SensorShapes;

}
}
}
}
}

1
com.unity.ml-agents/Runtime/Sensor/StackingSensor.cs


}
// TODO support stacked compressed observations (byte stream)
}
}

1
com.unity.ml-agents/Runtime/Sensor/VectorSensor.cs


AddFloatObs(observation ? 1f : 0f);
}
public void AddOneHotObservation(int observation, int range)
{
for (var i = 0; i < range; i++)

1
com.unity.ml-agents/Runtime/SideChannel/EngineConfigurationChannel.cs


{
public class EngineConfigurationChannel : SideChannel
{
public override int ChannelType()
{
return (int)SideChannelType.EngineSettings;

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


namespace MLAgents
{
public interface IFloatProperties
{
/// <summary>

public class FloatPropertiesChannel : SideChannel, IFloatProperties
{
private Dictionary<string, float> m_FloatProperties = new Dictionary<string, float>();
private Dictionary<string, Action<float>> m_RegisteredActions = new Dictionary<string, Action<float>>();

10
com.unity.ml-agents/Runtime/SideChannel/RawBytesChannel.cs


{
public class RawBytesChannel : SideChannel
{
private List<byte[]> m_MessagesReceived = new List<byte[]>();
private int m_ChannelId;

/// <param name="channelId"> The identifier for the RawBytesChannel. Must be
/// <param name="channelId"> The identifier for the RawBytesChannel. Must be
public override int ChannelType()
{
return (int)SideChannelType.RawBytesChannelStart + m_ChannelId;

}
/// <summary>
/// Sends the byte array message to the Python side channel. The message will be sent
/// Sends the byte array message to the Python side channel. The message will be sent
/// alongside the simulation step.
/// </summary>
/// <param name="data"> The byte array of data to send to Python.</param>

}
/// <summary>
/// Gets the messages that were sent by python since the last call to
/// Gets the messages that were sent by python since the last call to
/// GetAndClearReceivedMessages.
/// </summary>
/// <returns> a list of byte array messages that Python has sent.</returns>

}
/// <summary>
/// Gets the messages that were sent by python since the last call to
/// Gets the messages that were sent by python since the last call to
/// GetAndClearReceivedMessages. Note that the messages received will not
/// be cleared with a call to GetReceivedMessages.
/// </summary>

7
com.unity.ml-agents/Runtime/SideChannel/SideChannel.cs


{
// Invalid side channel
Invalid = 0,
// Reserved for the FloatPropertiesChannel.
// Reserved for the FloatPropertiesChannel.
FloatProperties = 1,
//Reserved for the EngineConfigurationChannel.
EngineSettings = 2,

public List<byte[]> MessageQueue = new List<byte[]>();
/// <summary>
/// An int identifier for the SideChannel. Ensures that there is only ever one side channel
/// An int identifier for the SideChannel. Ensures that there is only ever one side channel
/// of each type. Ensure the Unity side channels will be linked to their Python equivalent.
/// </summary>
/// <returns> The integer identifier of the SideChannel</returns>

public abstract void OnMessageReceived(byte[] data);
/// <summary>
/// Queues a message to be sent to Python during the next simulation step.
/// Queues a message to be sent to Python during the next simulation step.
/// </summary>
/// <param name="data"> The byte array of data to be sent to Python.</param>
protected void QueueMessageToSend(byte[] data)

}
}

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


{
[DataMember]
public float value;
[DataMember( Name = "min")]
[DataMember(Name = "min")]
[DataMember( Name = "max")]
[DataMember(Name = "max")]
public float maxValue;
[DataMember]
public uint count;

1
com.unity.ml-agents/Runtime/Utilities.cs


{
public static class Utilities
{
/// <summary>
/// Puts a Texture2D into a WriteAdapter.
/// </summary>

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


var agentSendInfo = typeof(Agent).GetMethod("SendInfo",
BindingFlags.Instance | BindingFlags.NonPublic);
agentEnableMethod?.Invoke(agent1, new object[] { });
agentEnableMethod?.Invoke(agent1, new object[] {});
agentSendInfo?.Invoke(agent1, new object[] { });
agentSendInfo?.Invoke(agent1, new object[] {});
demoRecorder.Close();

8
com.unity.ml-agents/Tests/Editor/EditModeTestInternalBrainTensorApplier.cs


var action1 = new AgentAction();
var callbacks = new List<AgentIdActionPair>()
{
new AgentIdActionPair{agentId = 0, action = (a) => action0 = a},
new AgentIdActionPair{agentId = 1, action = (a) => action1 = a}
new AgentIdActionPair {agentId = 0, action = (a) => action0 = a},
new AgentIdActionPair {agentId = 1, action = (a) => action1 = a}
};
applier.Apply(inputTensor, callbacks);

var action1 = new AgentAction();
var callbacks = new List<AgentIdActionPair>()
{
new AgentIdActionPair{agentId = 0, action = (a) => action0 = a},
new AgentIdActionPair{agentId = 1, action = (a) => action1 = a}
new AgentIdActionPair {agentId = 0, action = (a) => action0 = a},
new AgentIdActionPair {agentId = 1, action = (a) => action1 = a}
};
applier.Apply(inputTensor, callbacks);

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


{
var agentEnableMethod = typeof(Agent).GetMethod("OnEnableHelper",
BindingFlags.Instance | BindingFlags.NonPublic);
agentEnableMethod?.Invoke(agent, new object[] { });
agentEnableMethod?.Invoke(agent, new object[] {});
}
agentA.collectObservationsSensor.AddObservation(new Vector3(1, 2, 3));
agentB.collectObservationsSensor.AddObservation(new Vector3(4, 5, 6));

var agent1 = agentInfos[1];
var inputs = new List<AgentInfoSensorsPair>
{
new AgentInfoSensorsPair{agentInfo = agent0._Info, sensors = agent0.sensors},
new AgentInfoSensorsPair{agentInfo = agent1._Info, sensors = agent1.sensors},
new AgentInfoSensorsPair {agentInfo = agent0._Info, sensors = agent0.sensors},
new AgentInfoSensorsPair {agentInfo = agent1._Info, sensors = agent1.sensors},
};
generator.Generate(inputTensor, batchSize, inputs);
Assert.IsNotNull(inputTensor.data);

var agent1 = agentInfos[1];
var inputs = new List<AgentInfoSensorsPair>
{
new AgentInfoSensorsPair{agentInfo = agent0._Info, sensors = agent0.sensors},
new AgentInfoSensorsPair{agentInfo = agent1._Info, sensors = agent1.sensors},
new AgentInfoSensorsPair {agentInfo = agent0._Info, sensors = agent0.sensors},
new AgentInfoSensorsPair {agentInfo = agent1._Info, sensors = agent1.sensors},
};
generator.Generate(inputTensor, batchSize, inputs);
Assert.IsNotNull(inputTensor.data);

var agent1 = agentInfos[1];
var inputs = new List<AgentInfoSensorsPair>
{
new AgentInfoSensorsPair{agentInfo = agent0._Info, sensors = agent0.sensors},
new AgentInfoSensorsPair{agentInfo = agent1._Info, sensors = agent1.sensors},
new AgentInfoSensorsPair {agentInfo = agent0._Info, sensors = agent0.sensors},
new AgentInfoSensorsPair {agentInfo = agent1._Info, sensors = agent1.sensors},
};
generator.Generate(inputTensor, batchSize, inputs);

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


{
public class TestAgent : Agent
{
public AgentInfo _Info
{
get

{
return new float[0];
}
}
public class TestSensor : ISensor

return sensorName;
}
public void Update() { }
public void Update() {}
}
[TestFixture]

var agentEnableMethod = typeof(Agent).GetMethod("OnEnableHelper",
BindingFlags.Instance | BindingFlags.NonPublic);
agentEnableMethod?.Invoke(agent2, new object[] { });
agentEnableMethod?.Invoke(agent1, new object[] { });
agentEnableMethod?.Invoke(agent2, new object[] {});
agentEnableMethod?.Invoke(agent1, new object[] {});
// agent1 was not enabled when the academy started
// The agents have been initialized

// agent1 will take an action at every step and request a decision every 2 steps
// agent2 will request decisions only when RequestDecision is called
agentEnableMethod?.Invoke(agent1, new object[] { });
agentEnableMethod?.Invoke(agent1, new object[] {});
var numberAgent1Reset = 0;
var numberAgent2Initialization = 0;

//Agent 2 is only initialized at step 2
if (i == 2)
{
agentEnableMethod?.Invoke(agent2, new object[] { });
agentEnableMethod?.Invoke(agent2, new object[] {});
numberAgent2Initialization += 1;
}

var decisionRequester = agent1.gameObject.AddComponent<DecisionRequester>();
decisionRequester.DecisionPeriod = 2;
agentEnableMethod?.Invoke(agent2, new object[] { });
agentEnableMethod?.Invoke(agent2, new object[] {});
var numberAgent1Reset = 0;
var numberAgent2Reset = 0;

//Agent 1 is only initialized at step 2
if (i == 2)
{
agentEnableMethod?.Invoke(agent1, new object[] { });
agentEnableMethod?.Invoke(agent1, new object[] {});
}
// Set agent 1 to done every 11 steps to test behavior
if (i % 11 == 5)

[TestFixture]
public class EditModeTestMiscellaneous
{
[SetUp]
public void SetUp()
{

agent1.maxStep = 20;
agentEnableMethod?.Invoke(agent2, new object[] { });
agentEnableMethod?.Invoke(agent1, new object[] { });
agentEnableMethod?.Invoke(agent2, new object[] {});
agentEnableMethod?.Invoke(agent1, new object[] {});
var j = 0;

agent1.AddReward(10f);
aca.EnvironmentStep();
}
}
}

2
com.unity.ml-agents/Tests/Editor/Sensor/FloatVisualSensorTests.cs


}
}
public void Update() { }
public void Update() {}
public SensorCompressionType GetCompressionType()
{

4
com.unity.ml-agents/Tests/Editor/Sensor/RayPerceptionSensorTests.cs


public void TestGetRayAngles()
{
var angles = RayPerceptionSensorComponentBase.GetRayAngles(3, 90f);
var expectedAngles = new [] { 90f, 60f, 120f, 30f, 150f, 0f, 180f };
var expectedAngles = new[] { 90f, 60f, 120f, 30f, 150f, 0f, 180f };
Assert.AreEqual(expectedAngles.Length, angles.Length);
for (var i = 0; i < angles.Length; i++)
{

perception.detectableTags.Add(k_CubeTag);
perception.detectableTags.Add(k_SphereTag);
var radii = new [] { 0f, .5f };
var radii = new[] { 0f, .5f };
foreach (var castRadius in radii)
{
perception.sphereCastRadius = castRadius;

26
com.unity.ml-agents/Tests/Editor/Sensor/StackingSensorTests.cs


ISensor wrapped = new VectorSensor(4);
ISensor sensor = new StackingSensor(wrapped, 4);
Assert.AreEqual("StackingSensor_size4_VectorSensor_size4", sensor.GetName());
Assert.AreEqual(sensor.GetObservationShape(), new [] {16});
Assert.AreEqual(sensor.GetObservationShape(), new[] {16});
}
[Test]

ISensor sensor = new StackingSensor(wrapped, 3);
wrapped.AddObservation(new [] {1f, 2f});
SensorTestHelper.CompareObservation(sensor, new [] {0f, 0f, 0f, 0f, 1f, 2f});
wrapped.AddObservation(new[] {1f, 2f});
SensorTestHelper.CompareObservation(sensor, new[] {0f, 0f, 0f, 0f, 1f, 2f});
wrapped.AddObservation(new [] {3f, 4f});
SensorTestHelper.CompareObservation(sensor, new [] {0f, 0f, 1f, 2f, 3f, 4f});
wrapped.AddObservation(new[] {3f, 4f});
SensorTestHelper.CompareObservation(sensor, new[] {0f, 0f, 1f, 2f, 3f, 4f});
wrapped.AddObservation(new [] {5f, 6f});
SensorTestHelper.CompareObservation(sensor, new [] {1f, 2f, 3f, 4f, 5f, 6f});
wrapped.AddObservation(new[] {5f, 6f});
SensorTestHelper.CompareObservation(sensor, new[] {1f, 2f, 3f, 4f, 5f, 6f});
wrapped.AddObservation(new [] {7f, 8f});
SensorTestHelper.CompareObservation(sensor, new [] {3f, 4f, 5f, 6f, 7f, 8f});
wrapped.AddObservation(new[] {7f, 8f});
SensorTestHelper.CompareObservation(sensor, new[] {3f, 4f, 5f, 6f, 7f, 8f});
wrapped.AddObservation(new [] {9f, 10f});
SensorTestHelper.CompareObservation(sensor, new [] {5f, 6f, 7f, 8f, 9f, 10f});
wrapped.AddObservation(new[] {9f, 10f});
SensorTestHelper.CompareObservation(sensor, new[] {5f, 6f, 7f, 8f, 9f, 10f});
SensorTestHelper.CompareObservation(sensor, new [] {5f, 6f, 7f, 8f, 9f, 10f});
SensorTestHelper.CompareObservation(sensor, new[] {5f, 6f, 7f, 8f, 9f, 10f});
}
}

23
com.unity.ml-agents/Tests/Editor/Sensor/VectorSensorTests.cs


// Check that Update() clears the data
sensor.Update();
SensorTestHelper.CompareObservation(sensor, new[] { 0f, 0f, 0f, 0f });
}
[Test]

sensor.AddObservation(1.2f);
SensorTestHelper.CompareObservation(sensor, new []{1.2f});
SensorTestHelper.CompareObservation(sensor, new[] {1.2f});
}
[Test]

sensor.AddObservation(42);
SensorTestHelper.CompareObservation(sensor, new []{42f});
SensorTestHelper.CompareObservation(sensor, new[] {42f});
}
[Test]

sensor.AddObservation(new Vector3(1,2,3));
SensorTestHelper.CompareObservation(sensor, new []{1f, 2f, 3f});
sensor.AddObservation(new Vector3(1, 2, 3));
SensorTestHelper.CompareObservation(sensor, new[] {1f, 2f, 3f});
sensor.AddObservation(new Vector2(4,5));
sensor.AddObservation(new Vector2(4, 5));
SensorTestHelper.CompareObservation(sensor, new[] { 4f, 5f });
}

var sensor = new VectorSensor(4);
sensor.AddObservation(Quaternion.identity);
SensorTestHelper.CompareObservation(sensor, new []{0f, 0f, 0f, 1f});
SensorTestHelper.CompareObservation(sensor, new[] {0f, 0f, 0f, 1f});
}
[Test]

sensor.AddObservation(new [] {1f, 2f, 3f, 4f});
sensor.AddObservation(new[] {1f, 2f, 3f, 4f});
SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f, 3f, 4f });
}

{
var sensor = new VectorSensor(1);
sensor.AddObservation(true);
SensorTestHelper.CompareObservation(sensor, new []{1f});
SensorTestHelper.CompareObservation(sensor, new[] {1f});
}
[Test]

sensor.AddOneHotObservation(2, 4);
SensorTestHelper.CompareObservation(sensor, new []{0f, 0f, 1f, 0f});
SensorTestHelper.CompareObservation(sensor, new[] {0f, 0f, 1f, 0f});
}
[Test]

sensor.AddObservation(new [] {1f, 2f, 3f, 4f});
sensor.AddObservation(new[] {1f, 2f, 3f, 4f});
SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f});
}

{
var sensor = new VectorSensor(4);
sensor.AddObservation(new [] {1f, 2f});
sensor.AddObservation(new[] {1f, 2f});
// Make sure extra zeros are added
SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f, 0f, 0f});

6
com.unity.ml-agents/Tests/Editor/Sensor/WriterAdapterTests.cs


// AddRange
writer.SetTarget(buffer, shape, 0);
writer.AddRange(new [] {4f, 5f});
writer.AddRange(new[] {4f, 5f});
writer.AddRange(new [] {6f, 7f});
writer.AddRange(new[] {6f, 7f});
Assert.AreEqual(new[] { 4f, 6f, 7f }, buffer);
}

};
writer.SetTarget(t, 1, 1);
writer.AddRange(new [] {-1f, -2f});
writer.AddRange(new[] {-1f, -2f});
Assert.AreEqual(0f, t.data[0, 0]);
Assert.AreEqual(0f, t.data[0, 1]);
Assert.AreEqual(0f, t.data[0, 2]);

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


{
public class SideChannelTests
{
public List<int> m_MessagesReceived = new List<int>();
public override int ChannelType() { return -1; }

74
com.unity.ml-agents/.editorconfig


; see http://editorconfig.org/ for docs on this file
root = true
[*]
ignore_if_in_header = This code was generated by a tool|<auto-generated>
indent_style = space
indent_size = 4
; uncomment to help with sharing files across os's (i.e. network share or through local vm)
#end_of_line = lf
; avoid a bom, which causes endless problems with naive text tooling
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
; keeping auto-format enabled helps avoid merge hell for projects without CI-based format validation
#disable_auto_format = true
[*.cs]
; uncomment to enable full formatting of c# files
formatters = generic, uncrustify
[*.asmdef]
scrape_api = true
[**/Tests/**.asmdef]
scrape_api = false
[*.Tests.asmdef]
scrape_api = false
[*.md]
indent_size = 2
; trailing whitespace is unfortunately significant in markdown
trim_trailing_whitespace = false
; uncomment to enable basic formatting of markdown files
#formatters = generic
[{Makefile,makefile}]
; tab characters are part of the Makefile format
indent_style = tab
[*.asmdef]
indent_size = 4
[*.json]
indent_size = 2
[*.{vcproj,bat,cmd,xaml,tt,t4,ttinclude}]
end_of_line = crlf
; this VS-specific stuff is based on experiments to see how VS will modify a file after it has been manually edited.
; the settings are meant to closely match what VS does to minimize unnecessary diffs.
[*.{vcxproj,vcxproj.filters}]
indent_style = space
indent_size = 2
end_of_line = crlf
charset = utf-8-bom
trim_trailing_whitespace = true
insert_final_newline = false
; must be broken out because of 51-char bug (https://github.com/editorconfig/editorconfig-visualstudio/issues/21)
[*.{csproj,pyproj,props,targets}]
indent_style = space
indent_size = 2
end_of_line = crlf
charset = utf-8-bom
trim_trailing_whitespace = true
insert_final_newline = false
[*.{sln,sln.template}]
indent_style = tab
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = false
正在加载...
取消
保存