You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CozmoAgent.cs 11KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. ///-----------------------------------------------------------------
  2. /// Namespace: <Cozmo>
  3. /// Class: <CozmoAgent>
  4. /// Description: <The actual agent in the scene. Collects observations and executes the actions.
  5. /// Also rewards the agent and sets an actionmask.>
  6. /// Author: <Tobias Hassel> Date: <29.07.2019>
  7. /// Notes: <>
  8. ///-----------------------------------------------------------------
  9. ///
  10. using MLAgents;
  11. using OpenCvSharp;
  12. using System;
  13. using System.Collections.Generic;
  14. using UnityEngine;
  15. namespace Cozmo
  16. {
  17. public class CozmoAgent : Agent
  18. {
  19. // Possible Actions
  20. private const int STOP = 0;
  21. private const int FORWARD = 1;
  22. private const int RIGHT = 2;
  23. private const int LEFT = 3;
  24. // Used to determine different areas in the image (near to the center, far away)
  25. private const float NEAR_AREA_PERCENTAGE_OFFSET = 0.3f;
  26. [Tooltip("The virtual Cozmo camera")]
  27. public Camera renderCamera;
  28. [Tooltip("Reference to the CozmoMovement script")]
  29. public CozmoMovementController movementController;
  30. [Tooltip("The time between decisions at inference")]
  31. public float timeBetweenDecisionsAtInference;
  32. [Tooltip("The amout of actions that should be remembered by the agent.")]
  33. public int maxStoredMovementStates = 1;
  34. [Tooltip("If activated the maxStoredMovementStates has no impact on the training.")]
  35. public bool useOriginalActionMasking = true;
  36. private Academy academy; // CozmoAcademy
  37. private float timeSinceDecision; // time since last decision
  38. private ImageProcessor imageProcessor; // reference to the ImageProcessor
  39. private int nearAreaLimit = 0; // X coordinate limit for the near to the imagecenter area
  40. private int centerOfImageX = 0; // Middle of the image in x direction
  41. private MovementState lastChosenMovement = MovementState.Stop; // The last action/movement that was executed
  42. private Queue<MovementState> lastActions = new Queue<MovementState>(); // Queue to store the last chosen Actions
  43. private double startTime = 0;
  44. private void Start()
  45. {
  46. startTime = Time.time;
  47. academy = FindObjectOfType(typeof(CozmoAcademy)) as CozmoAcademy;
  48. imageProcessor = renderCamera.GetComponent<ImageProcessor>();
  49. nearAreaLimit = (int)(renderCamera.targetTexture.width / 2 * NEAR_AREA_PERCENTAGE_OFFSET);
  50. centerOfImageX = renderCamera.targetTexture.width / 2;
  51. }
  52. public void FixedUpdate()
  53. {
  54. WaitTimeInference();
  55. }
  56. public override void CollectObservations()
  57. {
  58. SetMask();
  59. }
  60. // Set ActionMask for training
  61. // Needs to be called from CollectObservations()
  62. private void SetMask()
  63. {
  64. if (useOriginalActionMasking)
  65. {
  66. // Stop is never allowed
  67. switch (lastChosenMovement)
  68. {
  69. // Do not allow stop decision after a stop
  70. case (MovementState.Stop):
  71. SetActionMask(STOP);
  72. break;
  73. // Do not allow stop after forward
  74. case (MovementState.Forward):
  75. SetActionMask(STOP);
  76. break;
  77. // Do not allow stop & left after right
  78. case (MovementState.Right):
  79. SetActionMask(STOP);
  80. SetActionMask(LEFT);
  81. break;
  82. // Do not allow stop & right after left
  83. case (MovementState.Left):
  84. SetActionMask(STOP);
  85. SetActionMask(RIGHT);
  86. break;
  87. default:
  88. throw new ArgumentException("Invalid MovementState.");
  89. }
  90. }
  91. else
  92. {
  93. // Do not allow stop decision after a stop
  94. if (lastChosenMovement == MovementState.Stop)
  95. {
  96. SetActionMask(STOP);
  97. }
  98. // Do not allow left decision if right was in the last actions
  99. if (lastActions.Contains(MovementState.Right))
  100. {
  101. SetActionMask(LEFT);
  102. }
  103. // Do not allow right decision if left was in the last actions
  104. if (lastActions.Contains(MovementState.Left))
  105. {
  106. SetActionMask(RIGHT);
  107. }
  108. }
  109. }
  110. // to be implemented by the developer
  111. public override void AgentAction(float[] vectorAction, string textAction)
  112. {
  113. double elapsedTime = Time.time - startTime;
  114. //Debug.Log("Elapsed time: " + elapsedTime);
  115. startTime = Time.time;
  116. int action = Mathf.FloorToInt(vectorAction[0]);
  117. Point centerOfGravity = imageProcessor.CenterOfGravity;
  118. AddReward(-0.01f);
  119. switch (action)
  120. {
  121. case STOP:
  122. movementController.currentMovementState = MovementState.Stop;
  123. lastChosenMovement = MovementState.Stop;
  124. SetReward(-0.02f);
  125. break;
  126. case FORWARD:
  127. movementController.currentMovementState = MovementState.Forward;
  128. lastChosenMovement = MovementState.Forward;
  129. SetReward(0.02f);
  130. break;
  131. case RIGHT:
  132. movementController.currentMovementState = MovementState.Right;
  133. lastChosenMovement = MovementState.Right;
  134. SetReward(0.01f);
  135. break;
  136. case LEFT:
  137. movementController.currentMovementState = MovementState.Left;
  138. lastChosenMovement = MovementState.Left;
  139. SetReward(0.01f);
  140. break;
  141. default:
  142. //movement.Move(0);
  143. throw new ArgumentException("Invalid action value. Stop movement.");
  144. }
  145. if (!useOriginalActionMasking)
  146. CollectLastMovementStates(lastChosenMovement);
  147. // Render new image after movement in order to update the centerOfGravity
  148. if (renderCamera != null)
  149. {
  150. renderCamera.Render();
  151. }
  152. RewardAgent();
  153. }
  154. // Set the reward for the agent based on how far away the center of gravity is from the center of the image
  155. private void RewardAgent()
  156. {
  157. float centerOfGravityX = imageProcessor.CenterOfGravity.X;
  158. float reward = 0;
  159. // Center of gravity is far away from the center (left)
  160. if (centerOfGravityX <= centerOfImageX - nearAreaLimit && centerOfGravityX >= 0)
  161. {
  162. float range = centerOfImageX - nearAreaLimit;
  163. reward = -(1 - (centerOfGravityX / range));
  164. // Clamp the reward to max -1 and divide it by 2
  165. reward = Mathf.Clamp(reward, -1, 0) / 2;
  166. }
  167. // Center of gravity is near left of the center
  168. else if ((centerOfGravityX <= centerOfImageX) && (centerOfGravityX >= (centerOfImageX - nearAreaLimit)))
  169. {
  170. float range = centerOfImageX - (centerOfImageX - nearAreaLimit);
  171. float distanceToLeftFarBorder = centerOfGravityX - (centerOfImageX - nearAreaLimit);
  172. reward = (distanceToLeftFarBorder / range);
  173. }
  174. // Center of gravity is far away from the center (right)
  175. else if ((centerOfGravityX >= (centerOfImageX + nearAreaLimit)) && (centerOfGravityX <= renderCamera.targetTexture.width))
  176. {
  177. float range = renderCamera.targetTexture.width - (centerOfImageX + nearAreaLimit);
  178. reward = -(((centerOfGravityX - (centerOfImageX + nearAreaLimit)) / range));
  179. // Clamp the reward to max -1 in order to handle rewards if the center of gravity is outside of the image
  180. reward = Mathf.Clamp(reward, -1, 0) / 2;
  181. }
  182. // Center of gravity is near right of the center
  183. else if ((centerOfGravityX >= centerOfImageX) && (centerOfGravityX <= (centerOfImageX + nearAreaLimit)))
  184. {
  185. float range = (centerOfImageX + nearAreaLimit) - centerOfImageX;
  186. float distanceToCenterOfImage = centerOfGravityX - centerOfImageX;
  187. reward = (1 - distanceToCenterOfImage / range);
  188. }
  189. else
  190. {
  191. SetReward(-1);
  192. AgentReset();
  193. Debug.Log("Out of image range");
  194. }
  195. Debug.Log("Reward: " + reward);
  196. SetReward(reward);
  197. }
  198. // Store the last movementStates in a Queue
  199. private void CollectLastMovementStates(MovementState movementState)
  200. {
  201. // Check if Queue exists and values should be stored
  202. if ((lastActions != null) && (maxStoredMovementStates > 0))
  203. {
  204. // maxStoredMovementStates is reached
  205. if (lastActions.Count >= maxStoredMovementStates)
  206. {
  207. // deque first value(s) when maxStoredMovementStates is reached
  208. for (int i = 0; i <= (lastActions.Count - maxStoredMovementStates); i++)
  209. {
  210. lastActions.Dequeue();
  211. }
  212. }
  213. // add last action to queue
  214. lastActions.Enqueue(movementState);
  215. }
  216. }
  217. // to be implemented by the developer
  218. public override void AgentReset()
  219. {
  220. academy.AcademyReset();
  221. }
  222. private void OnTriggerEnter(Collider other)
  223. {
  224. if (other.transform.CompareTag("Goal"))
  225. {
  226. Done();
  227. }
  228. }
  229. private void WaitTimeInference()
  230. {
  231. if (renderCamera != null)
  232. {
  233. renderCamera.Render();
  234. }
  235. if (!academy.GetIsInference())
  236. {
  237. RequestDecision();
  238. }
  239. else
  240. {
  241. if (timeSinceDecision >= timeBetweenDecisionsAtInference)
  242. {
  243. timeSinceDecision = 0f;
  244. RequestDecision();
  245. }
  246. else
  247. {
  248. timeSinceDecision += Time.fixedDeltaTime;
  249. }
  250. }
  251. }
  252. }
  253. }