浏览代码

Merge pull request #132 from Unity-Technologies/dev-logfile

Dev logfile
/tag-0.2.0
GitHub 7 年前
当前提交
989dea4a
共有 5 个文件被更改,包括 87 次插入13 次删除
  1. 3
      .gitignore
  2. 42
      python/unityagents/environment.py
  3. 31
      python/unityagents/exception.py
  4. 4
      unity-environment/Assets/ML-Agents/Scripts/Communicator.cs
  5. 20
      unity-environment/Assets/ML-Agents/Scripts/ExternalCommunicator.cs

3
.gitignore


/python/models
/python/summaries
# Environemnt logfile
*unity-environment.log
# Visual Studio 2015 cache directory
/unity-environment/.vs/

42
python/unityagents/environment.py


import struct
from .brain import BrainInfo, BrainParameters
from .exception import UnityEnvironmentException, UnityActionException
from .exception import UnityEnvironmentException, UnityActionException, UnityTimeOutException
from .curriculum import Curriculum
from PIL import Image

logger = logging.getLogger(__name__)
logger = logging.getLogger("unityagents")
class UnityEnvironment(object):

try:
self._socket.listen(1)
self._conn, _ = self._socket.accept()
self._conn.setblocking(1)
self._conn.settimeout(10)
raise UnityEnvironmentException(
raise UnityTimeOutException(
"The Unity environment took too long to respond. Make sure {} does not need user interaction to "
"launch and that the Academy and the external Brain(s) are attached to objects in the Scene."
.format(str(file_name)))

self._data = {}
self._global_done = None
self._academy_name = p["AcademyName"]
self._log_path = p["logPath"]
self._brains = {}
self._brain_names = p["brainNames"]
self._external_brain_names = p["externalBrainNames"]

raise
@property
def logfile_path(self):
return self._log_path
@property
def brains(self):
return self._brains

for k in self._resetParameters])) + '\n' + \
'\n'.join([str(self._brains[b]) for b in self._brains])
s = self._conn.recv(self._buffer_size)
message_length = struct.unpack("I", bytearray(s[:4]))[0]
s = s[4:]
while len(s) != message_length:
s += self._conn.recv(self._buffer_size)
try:
s = self._conn.recv(self._buffer_size)
message_length = struct.unpack("I", bytearray(s[:4]))[0]
s = s[4:]
while len(s) != message_length:
s += self._conn.recv(self._buffer_size)
except socket.timeout as e:
raise UnityTimeOutException("The environment took too long to respond.", self._log_path)
return s
def _get_state_image(self, bw):

if self._loaded:
self._conn.send(b"RESET")
self._conn.recv(self._buffer_size)
try:
self._conn.recv(self._buffer_size)
except socket.timeout as e:
raise UnityTimeOutException("The environment took too long to respond.", self._log_path)
self._conn.send(json.dumps({"train_model": train_mode, "parameters": config}).encode('utf-8'))
return self._get_state()
else:

self._data[b] = BrainInfo(observations, states, memories, rewards, agents, dones, actions)
self._global_done = self._conn.recv(self._buffer_size).decode('utf-8') == 'True'
try:
self._global_done = self._conn.recv(self._buffer_size).decode('utf-8') == 'True'
except socket.timeout as e:
raise UnityTimeOutException("The environment took too long to respond.", self._log_path)
return self._data

:param memory: a dictionary of lists of of memories.
:param value: a dictionary of lists of of value estimates.
"""
self._conn.recv(self._buffer_size)
try:
self._conn.recv(self._buffer_size)
except socket.timeout as e:
raise UnityTimeOutException("The environment took too long to respond.", self._log_path)
action_message = {"action": action, "memory": memory, "value": value}
self._conn.send(json.dumps(action_message).encode('utf-8'))

31
python/unityagents/exception.py


import logging
logger = logging.getLogger("unityagents")
class UnityEnvironmentException(Exception):
"""
Related to errors starting and closing environment.

Related to errors with sending actions.
"""
pass
class UnityTimeOutException(Exception):
"""
Related to errors with communication timeouts.
"""
def __init__(self, message, log_file_path = None):
if log_file_path is not None:
try:
with open(log_file_path, "r") as f:
printing = False
unity_error = '\n'
for l in f:
l=l.strip()
if (l == 'Exception') or (l=='Error'):
printing = True
unity_error += '----------------------\n'
if (l == ''):
printing = False
if printing:
unity_error += l + '\n'
logger.info(unity_error)
logger.error("An error might have occured in the environment. "
"You can check the logfile for more information at {}".format(log_file_path))
except:
logger.error("An error might have occured in the environment. "
"No unity-environment.log file could be found.")
super(UnityTimeOutException, self).__init__(message)

4
unity-environment/Assets/ML-Agents/Scripts/Communicator.cs


* it will be the name of the Academy GameObject */
public string apiNumber;
/**< \brief The API number for the communicator. */
public Dictionary<string, float> resetParameters;
public string logPath;
/**< \brief The location of the logfile*/
public Dictionary<string, float> resetParameters;
/**< \brief The default reset parameters are sent via socket*/
public List<string> brainNames;
/**< \brief A list of the all the brains names sent via socket*/

20
unity-environment/Assets/ML-Agents/Scripts/ExternalCommunicator.cs


using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.IO;
/// Responsible for communication with Python API.

byte[] messageHolder;
const int messageLength = 12000;
StreamWriter logWriter;
string logPath;
const string api = "API-2";

/// Contains the logic for the initializtation of the socket.
public void InitializeCommunicator()
{
Application.logMessageReceived += HandleLog;
logPath = Path.GetFullPath(".") + "/unity-environment.log";
logWriter = new StreamWriter(logPath, false);
logWriter.WriteLine(System.DateTime.Now.ToString());
logWriter.WriteLine(" ");
logWriter.Close();
messageHolder = new byte[messageLength];
// Create a TCP/IP socket.

accParamerters.brainNames = new List<string>();
accParamerters.externalBrainNames = new List<string>();
accParamerters.apiNumber = api;
accParamerters.logPath = logPath;
foreach (Brain b in brains)
{
accParamerters.brainParameters.Add(b.brainParameters);

SendParameters(accParamerters);
}
void HandleLog(string logString, string stackTrace, LogType type)
{
logWriter = new StreamWriter(logPath, true);
logWriter.WriteLine(type.ToString());
logWriter.WriteLine(logString);
logWriter.WriteLine(stackTrace);
logWriter.Close();
}
/// Listens to the socket for a command and returns the corresponding
/// External Command.

正在加载...
取消
保存