Commit 7b15af6c authored by Michele's avatar Michele

working on integrating learning with tictactoe

parent b4a67f2a
# Copyright (c) 2015 Michele Volpato
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import random
random.seed(100)
import os, inspect, sys
# Include project dir in path
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.append(currentdir)
import socket
import logging
from tictacteacher import TicTacToeTeacher
from tictacoracle import TicTacToeOracle
from systems.iopurpose import InputPurpose, OutputPurpose
from learning.learning import LearningAlgorithm
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
HOST = 'localhost'
PORT = 29001 # Arbitrary non-privileged port
inputs = set(['0','1','2','3','4','5','6','7','8'])
outputs = set(['x','y'])
quiescence = 'delta'
outputExpert = OutputPurpose(set(['x','y', quiescence]))
inputExpert = InputPurpose(set(['0','1','2','3','4','5','6','7','8']))
T1 = TicTacToeTeacher(HOST, PORT, quiescence)
O1 = TicTacToeOracle()
tester = None
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
path = os.path.join(currentdir, "dotFiles")
print("Starting learning...")
L = LearningAlgorithm(T1, O1, printPath=path, maxLoops=4,
tablePreciseness=10000, logger=logger, tester=tester, outputPurpose=outputExpert,
inputPurpose=inputExpert)
minus, plus = L.run()
print("Models learned.")
# while True:
#
# data = s.recv(1024)
#
# if not data or data == "EXIT":
# break
#
# msg = data.decode("utf-8")
# print(msg)
# move1 = str(input("\nNext move? "))
#
# s.sendall(bytes(move1, 'UTF-8'))
# Copyright (c) 2015 Michele Volpato
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import os, inspect, sys
# Include project dir in path
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
currentdir = os.path.dirname(currentdir)
currentdir = os.path.dirname(currentdir)
sys.path.append(currentdir)
from teachers.baseoracle import AbstractOracle
import random
# TODO for the moment we keep SUL deterministic, simple oracle.
class TicTacToeOracle(AbstractOracle):
def __init__(self):
pass
# Reply to an observation query
# trace is a list of inputs and or outputs
# outputs is the set of outputs observed so far (after trace)
def observation(self, trace, outputs):
return True
# Copyright (c) 2015 Michele Volpato
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import os, inspect, sys
# Include project dir in path
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
currentdir = os.path.dirname(currentdir)
currentdir = os.path.dirname(currentdir)
sys.path.append(currentdir)
import random
import socket
import logging
import sys
import select
from teachers.baseteacher import AbstractTeacher
# Teacher for Tic Tac Toe.
class TicTacToeTeacher(AbstractTeacher):
def __init__(self, host, port, quiescence):
self._quiescence = quiescence
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.connect((host, port))
#Receiving confirmation from game
data = self._socket.recv(1024)
if data.decode("utf-8") != "CONNECTED\n":
logger.error("Cannot connect.")
sys.exit()
self._socket.setblocking(0)
#self._socket.settimeout(1) # 1 second timeout, for quiescence
#logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Reply to a membership/output query
# trace is a list of inputs and or outputs
def process(self, trace):
# reset SUL
self._socket.sendall(bytes("9", 'UTF-8'))
output = None
if len(trace) == 0:
# Get output for the empty trace
ready = select.select([self._socket], [], [], 1) # 1 second timeout, for quiescence
output = self._quiescence
if ready[0]:
output = self._socket.recv(1024)
for action in trace:
# TODO finish here, maybe not needed
return None
return output
# TODO arrived here!
# Provide a sequence of inputs (possibly one or even zero) end get an output
def oneOutput(self, actions):
for i in range(len(actions)):
if self._lts.move(actions[i]) == None:
return None
return self.output()
# Provide output from current state
def output(self):
# Select a randomic output for current state
output = random.sample(self._lts.outputs(), 1)[0]
self._lts.move(output)
return output
# Reset the SUT
def reset(self):
self._lts.reset()
# Get the input alphabet
def getInputAlphabet(self):
return self._lts.getInputs()
# Get the output alphabet
def getOutputAlphabet(self):
return self._lts.getOutputs()
# Get quiescence
def getQuiescence(self):
return self._lts.getQuiescence()
......@@ -363,7 +363,7 @@ if __name__ == "__main__":
#nice_print()
# 0 to 8 for moves, 9 for reset
HOST = 'localhost' # Symbolic name, meaning all available interfaces
HOST = 'localhost'
PORT = 29001 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
......@@ -379,20 +379,20 @@ if __name__ == "__main__":
print('Socket bind complete')
#Start listening on socket
s.listen(10)
s.listen(1) # only 1 connection
print('Socket now listening')
#wait to accept a connection - blocking call
conn, addr = s.accept()
print("Connected with client")
conn.send(bytes('Welcome to the Tic Tac Toe. 0-8 valid inputs, 9 for reset.\n', 'UTF-8'))
conn.send(bytes('CONNECTED\n', 'UTF-8'))
while True:
#Receiving from client
data = conn.recv(1024)
if not data:
if not data or data.decode("utf-8") == "EXIT":
break
move1 = int(data.decode("utf-8"))
......@@ -420,6 +420,7 @@ if __name__ == "__main__":
conn.sendall(bytes(board, 'UTF-8'))
conn.sendall(bytes("EXIT", 'UTF-8'))
# out of loop
conn.close()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment