File size: 7,087 Bytes
05c9ac2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
using System;
using UnityEngine;
using System.Linq;
using Unity.MLAgents;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Actuators;
using UnityEngine.Rendering;
using UnityEngine.Serialization;
public class GridAgent : Agent
{
[FormerlySerializedAs("m_Area")]
[Header("Specific to GridWorld")]
public GridArea area;
public float timeBetweenDecisionsAtInference;
float m_TimeSinceDecision;
[Tooltip("Because we want an observation right before making a decision, we can force " +
"a camera to render before making a decision. Place the agentCam here if using " +
"RenderTexture as observations.")]
public Camera renderCamera;
VectorSensorComponent m_GoalSensor;
public enum GridGoal
{
GreenPlus,
RedEx,
}
// Visual representations of the agent. Both are blue on top, but different colors on the bottom - this
// allows the user to see which corresponds to the current goal, but it's not visible to the camera.
// Only one is active at a time.
public GameObject GreenBottom;
public GameObject RedBottom;
GridGoal m_CurrentGoal;
public GridGoal CurrentGoal
{
get { return m_CurrentGoal; }
set
{
switch (value)
{
case GridGoal.GreenPlus:
GreenBottom.SetActive(true);
RedBottom.SetActive(false);
break;
case GridGoal.RedEx:
GreenBottom.SetActive(false);
RedBottom.SetActive(true);
break;
}
m_CurrentGoal = value;
}
}
[Tooltip("Selecting will turn on action masking. Note that a model trained with action " +
"masking turned on may not behave optimally when action masking is turned off.")]
public bool maskActions = true;
const int k_NoAction = 0; // do nothing!
const int k_Up = 1;
const int k_Down = 2;
const int k_Left = 3;
const int k_Right = 4;
EnvironmentParameters m_ResetParams;
public override void Initialize()
{
m_GoalSensor = this.GetComponent<VectorSensorComponent>();
m_ResetParams = Academy.Instance.EnvironmentParameters;
}
public override void CollectObservations(VectorSensor sensor)
{
Array values = Enum.GetValues(typeof(GridGoal));
if (m_GoalSensor is object)
{
int goalNum = (int)CurrentGoal;
m_GoalSensor.GetSensor().AddOneHotObservation(goalNum, values.Length);
}
}
public override void WriteDiscreteActionMask(IDiscreteActionMask actionMask)
{
// Mask the necessary actions if selected by the user.
if (maskActions)
{
// Prevents the agent from picking an action that would make it collide with a wall
var positionX = (int)transform.localPosition.x;
var positionZ = (int)transform.localPosition.z;
var maxPosition = (int)m_ResetParams.GetWithDefault("gridSize", 5f) - 1;
if (positionX == 0)
{
actionMask.SetActionEnabled(0, k_Left, false);
}
if (positionX == maxPosition)
{
actionMask.SetActionEnabled(0, k_Right, false);
}
if (positionZ == 0)
{
actionMask.SetActionEnabled(0, k_Down, false);
}
if (positionZ == maxPosition)
{
actionMask.SetActionEnabled(0, k_Up, false);
}
}
}
// to be implemented by the developer
public override void OnActionReceived(ActionBuffers actionBuffers)
{
AddReward(-0.01f);
var action = actionBuffers.DiscreteActions[0];
var targetPos = transform.position;
switch (action)
{
case k_NoAction:
// do nothing
break;
case k_Right:
targetPos = transform.position + new Vector3(1f, 0, 0f);
break;
case k_Left:
targetPos = transform.position + new Vector3(-1f, 0, 0f);
break;
case k_Up:
targetPos = transform.position + new Vector3(0f, 0, 1f);
break;
case k_Down:
targetPos = transform.position + new Vector3(0f, 0, -1f);
break;
default:
throw new ArgumentException("Invalid action value");
}
var hit = Physics.OverlapBox(
targetPos, new Vector3(0.3f, 0.3f, 0.3f));
if (hit.Where(col => col.gameObject.CompareTag("wall")).ToArray().Length == 0)
{
transform.position = targetPos;
if (hit.Where(col => col.gameObject.CompareTag("plus")).ToArray().Length == 1)
{
ProvideReward(GridGoal.GreenPlus);
EndEpisode();
}
else if (hit.Where(col => col.gameObject.CompareTag("ex")).ToArray().Length == 1)
{
ProvideReward(GridGoal.RedEx);
EndEpisode();
}
}
}
private void ProvideReward(GridGoal hitObject)
{
if (CurrentGoal == hitObject)
{
SetReward(1f);
}
else
{
SetReward(-1f);
}
}
public override void Heuristic(in ActionBuffers actionsOut)
{
var discreteActionsOut = actionsOut.DiscreteActions;
discreteActionsOut[0] = k_NoAction;
if (Input.GetKey(KeyCode.D))
{
discreteActionsOut[0] = k_Right;
}
if (Input.GetKey(KeyCode.W))
{
discreteActionsOut[0] = k_Up;
}
if (Input.GetKey(KeyCode.A))
{
discreteActionsOut[0] = k_Left;
}
if (Input.GetKey(KeyCode.S))
{
discreteActionsOut[0] = k_Down;
}
}
// to be implemented by the developer
public override void OnEpisodeBegin()
{
area.AreaReset();
Array values = Enum.GetValues(typeof(GridGoal));
if (m_GoalSensor is object)
{
CurrentGoal = (GridGoal)values.GetValue(UnityEngine.Random.Range(0, values.Length));
}
else
{
CurrentGoal = GridGoal.GreenPlus;
}
}
public void FixedUpdate()
{
WaitTimeInference();
}
void WaitTimeInference()
{
if (renderCamera != null && SystemInfo.graphicsDeviceType != GraphicsDeviceType.Null)
{
renderCamera.Render();
}
if (Academy.Instance.IsCommunicatorOn)
{
RequestDecision();
}
else
{
if (m_TimeSinceDecision >= timeBetweenDecisionsAtInference)
{
m_TimeSinceDecision = 0f;
RequestDecision();
}
else
{
m_TimeSinceDecision += Time.fixedDeltaTime;
}
}
}
}
|