def __init__(self, database): self.database = DATABASE() self.activeUsers = {} self.timeOfLastUsersUpdate = time.time()
def __init__(self): self.db = DATABASE() self.robots = self.db.Get_Living_Robots() self.numColumns = len(self.robots) self.commands = self.db.Get_Unique_Commands() random.shuffle(self.commands) while len(self.commands) > 10: del self.commands[-1] self.numRows = len(self.commands) self.cellWidth = 10 self.matrix = MATRIX( numRows = self.numRows , numColumns = self.numColumns , cellWidth = self.cellWidth ) self.Set_Cell_Colors() self.Set_Cell_Contents()
def __init__(self, primaryRobotIndex): self.db = DATABASE() self.primaryRobotIndex = primaryRobotIndex self.leftEdge = 1000 self.rightEdge = -1000 self.topEdge = -1000 self.bottomEdge = +1000 self.farLeftMargin = 0.0 self.leftMargin = 0.49 self.centerMargin = 0.5 self.rightMargin = 0.51 self.topRow = 0.9 self.rowHeight = 0.095 self.Compute_B_Index()
def __init__(self): self.database = DATABASE() self.Open_Connection() self.timeOfLastConnectionReset = time.time()
def __init__(self, primaryRobotIndex): self.primaryRobotIndex = primaryRobotIndex self.db = DATABASE() self.highestBIndex = -1 self.experimentStartTime = self.Compute_Experiment_Start_Time()
def Send_Reinforcement(color, reinforcement): db = DATABASE() ID = db.Get_Most_Recent_Bot_With_Color(color) if (ID == -1): print('bot not found') return if (reinforcement == 'y'): print('bot ' + str(ID) + ' positively reinforced.') else: print('bot ' + str(ID) + ' negatively reinforced.') db.Add_Reinforcement(ID, reinforcement)
def __init__(self): self.database = DATABASE() self.passiveGame = PASSIVE_GAME(self.database) self.tickerTape = TICKER_TAPE(self.database, self.passiveGame.Get_Screen())
import sys sys.path.insert(0, '..') from database.database import DATABASE db = DATABASE() db.Set_PtsPerSec_For_User(0.5,0)
import sqlite3 as lite import sys sys.path.insert(0, "..") from database.database import DATABASE if __name__ == "__main__": db = DATABASE() strng = 'PRAGMA table_info(USERS)' db.Safe_Execute(strng) returnedInfo = db.cur.fetchall() try: gotData = returnedInfo[8] except IndexError: print("Adding StartInfoClaims column to USERS") strng = 'ALTER TABLE USERS ADD StartInfoClaims Int DEFAULT(0)' db.Safe_Execute(strng) try: gotData = returnedInfo[9] except IndexError: print("Adding EndInfoClaims column to USERS") strng = 'ALTER TABLE USERS ADD EndInfoClaims Int DEFAULT(0)' db.Safe_Execute(strng)
class PROGRESS: def __init__(self, primaryRobotIndex): self.primaryRobotIndex = primaryRobotIndex self.db = DATABASE() self.highestBIndex = -1 self.experimentStartTime = self.Compute_Experiment_Start_Time() def Draw(self): self.Prep_Drawing() self.robots = self.db.Get_Robots() for robot in self.robots: self.Handle_Robot(robot) self.Draw_Current_Robot() self.Annotate_Figure() def Save(self): plt.savefig('test.png', facecolor=self.fig.get_facecolor(), transparent=True) plt.close() # ------------- Private methods ---------------- def Add_Robot_Creation_Date(self, robot): robotCreationDateAsString = self.db.From_Robot_Record_Get_Creation_Date( robot) robotCreationDate = datetime.strptime(robotCreationDateAsString, '%Y-%m-%d %H:%M:%S') totalSecondsElapsed = int( (robotCreationDate - self.experimentStartTime).total_seconds()) self.xCoordinates.append(totalSecondsElapsed) self.yCoordinates.append(0 + 0.01 * self.robotColorIndex) def Annotate_Figure(self): handles, labels = self.ax.get_legend_handles_labels() xTicks = [0, self.Seconds_Elapsed_So_Far()] xTickLabels = ['Start', 'Now'] plt.xticks(xTicks, xTickLabels, fontsize=22, horizontalalignment='left') yint = range(0, math.ceil(self.highestBIndex) + 1) plt.yticks(yint) plt.ylabel('Scores.', fontsize=22) plt.tight_layout() def Compute_Experiment_Start_Time(self): firstRobot = self.db.Get_First_Robot() firstRobotCreationDateAsString = self.db.From_Robot_Record_Get_Creation_Date( firstRobot) return datetime.strptime(firstRobotCreationDateAsString, '%Y-%m-%d %H:%M:%S') def Draw_Current_Robot(self): currentRobot = self.db.Get_Living_Robot_At_Position( self.primaryRobotIndex) currentRobotID = self.db.From_Robot_Record_Get_ID(currentRobot) x = self.Seconds_Elapsed_So_Far() y = self.db.Get_B_Index_For_Robot( currentRobotID) + 0.01 * self.primaryRobotIndex dotColor = c.colorRGBs[self.primaryRobotIndex] plt.plot(x, y, 'ko', markeredgecolor='black', markerfacecolor=dotColor, markersize=24) def Draw_Horizontal_Line_To_Right_Of_Plot(self): x = self.Seconds_Elapsed_So_Far() y = self.yCoordinates[-1] self.xCoordinates.append(x) self.yCoordinates.append(y) def Draw_Robots_BIndices(self): if self.xCoordinates == []: return lineColor = c.colorRGBs[self.robotColorIndex] if lineColor == [1, 1, 1]: lineColor = [0, 0, 0] if self.db.Robot_Is_Alive(self.robotID): self.Draw_Horizontal_Line_To_Right_Of_Plot() plt.plot(self.xCoordinates, self.yCoordinates, color=lineColor, linewidth=2) def Handle_Reinforcement(self): signal = self.db.From_Reinforcement_Record_Get_Signal( self.reinforcement) if signal == 'n': return timeOfReinforcementAsAString = self.db.From_Reinforcement_Record_Get_Time( self.reinforcement) BIndex = self.db.Get_B_Index_For_Robot_At_Time( self.robotID, timeOfReinforcementAsAString) if (BIndex > self.highestBIndex): self.highestBIndex = BIndex timeOfReinforcement = datetime.strptime(timeOfReinforcementAsAString, '%Y-%m-%d %H:%M:%S') totalSecondsElapsedSinceReinforcement = int( (timeOfReinforcement - self.experimentStartTime).total_seconds()) self.xCoordinates.append(totalSecondsElapsedSinceReinforcement) self.yCoordinates.append(BIndex + 0.01 * self.robotColorIndex) def Handle_Robot(self, robot): self.xCoordinates = [] self.yCoordinates = [] self.robotID = self.db.From_Robot_Record_Get_ID(robot) self.robotColorIndex = self.db.From_Robot_Record_Get_Color_Index(robot) self.Add_Robot_Creation_Date(robot) reinforcements = self.db.Get_Reinforcements_For_Robot(self.robotID) for self.reinforcement in reinforcements: self.Handle_Reinforcement() self.Draw_Robots_BIndices() def Prep_Drawing(self): plt.rcParams.update({'font.size': 22}) self.fig, self.ax = plt.subplots(1) self.fig.patch.set_facecolor('green') self.fig.patch.set_alpha(0.0) def Seconds_Elapsed_So_Far(self): totalSecondsElapsed = int( (datetime.now() - self.experimentStartTime).total_seconds()) return totalSecondsElapsed
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() db.Delete_Bad_Commands()
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() db.Print()
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() db.Add_Column()
class ROBOT_INFO: def __init__(self, primaryRobotIndex): self.db = DATABASE() self.primaryRobotIndex = primaryRobotIndex self.leftEdge = 1000 self.rightEdge = -1000 self.topEdge = -1000 self.bottomEdge = +1000 self.farLeftMargin = 0.0 self.leftMargin = 0.49 self.centerMargin = 0.5 self.rightMargin = 0.51 self.topRow = 0.9 self.rowHeight = 0.095 self.Compute_B_Index() def Draw(self): plt.rcParams.update({'font.size': 22}) self.fig, self.ax = plt.subplots(1) self.Draw_Text() self.Clean_Up() def Draw_Empty(self): plt.rcParams.update({'font.size': 22}) self.fig, self.ax = plt.subplots(1) self.Clean_Up() def Save(self): plt.savefig('../visualizations/rI.png') os.system( 'mv ../visualizations/rI.png ../visualizations/robotInfo.png') self.fig.clf() del self.fig del self.ax plt.close() # -------------- Private methods ----------- def Clean_Up(self): self.ax.set_xticks([]) self.ax.set_yticks([]) robotColor = c.colorNames[self.primaryRobotIndex] rgb = c.colorRGBs[self.primaryRobotIndex] self.ax.set_title(robotColor) # ,color=rgb) def Compute_B_Index(self): robot = self.db.Get_Living_Robot_At_Position(self.primaryRobotIndex) robotID = self.db.From_Robot_Record_Get_ID(robot) self.BIndex = self.db.Get_B_Index_For_Robot(robotID) self.commands = self.db.Get_Commands_Robot_Is_Most_Obedient_To(robotID) self.BIndex = 0 for command in sorted(self.commands, key=self.commands.get, reverse=True): numYesVotes = self.commands[command] if (numYesVotes > self.BIndex): self.BIndex = self.BIndex + 1 def Draw_Age(self): robot = self.db.Get_Living_Robot_At_Position(self.primaryRobotIndex) robotCreationDate = self.db.From_Robot_Record_Get_Creation_Date(robot) robotCreationDateString = robotCreationDate.strftime( "%Y-%m-%d %H:%M:%S") robotDate, robotTime = str.split(robotCreationDateString) robotYear, robotMonth, robotDay = str.split(robotDate, '-') robotHour, robotMinute, robotSecond = str.split(robotTime, ':') timeOfBirth = datetime.datetime(year=int(robotYear), month=int(robotMonth), day=int(robotDay), hour=int(robotHour), minute=int(robotMinute), second=int(robotSecond)) robotAge = str(datetime.datetime.now() - timeOfBirth) robotAgeSplitAttempted = str.split(robotAge) if (len(robotAgeSplitAttempted) == 1): robotAgeHour, robotAgeMinute, robotAgeSecond = str.split( robotAge, ':') plt.text(x=self.leftMargin, y=self.topRow, s='Age:', horizontalalignment='right') if (int(robotAgeHour) > 0): robotAgeHour = str(int(robotAgeHour)) if int(robotAgeHour) == 1: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeHour + ' hour. ', horizontalalignment='left') else: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeHour + ' hours.', horizontalalignment='left') elif (int(robotAgeMinute) > 0): robotAgeMinute = str(int(robotAgeMinute)) if int(robotAgeMinute) == 1: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeMinute + ' minute. ', horizontalalignment='left') else: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeMinute + ' minutes.', horizontalalignment='left') else: robotAgeSecond = str(int(float(robotAgeSecond))) if int(robotAgeSecond) == 1: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeSecond + ' second. ', horizontalalignment='left') else: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeSecond + ' seconds.', horizontalalignment='left') else: robotAgeDays = robotAgeSplitAttempted[0] plt.text(x=self.leftMargin, y=self.topRow, s='Age:', horizontalalignment='right') if int(robotAgeDays) == 1: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeDays + ' day. ', horizontalalignment='left') else: plt.text(x=self.rightMargin, y=self.topRow, s=robotAgeDays + ' days.', horizontalalignment='left') def Draw_B_Index(self): plt.text(x=self.leftMargin, y=self.topRow - 2 * self.rowHeight, s='Score:', horizontalalignment='right') plt.text(x=self.rightMargin, y=self.topRow - 2 * self.rowHeight, s=str(self.BIndex), horizontalalignment='left', weight='bold') def Draw_Commands(self): commandRank = 0 for command in sorted(self.commands, key=self.commands.get, reverse=True): textHeight = self.topRow - (4 + commandRank) * self.rowHeight plt.text(x=self.leftMargin, y=textHeight, s='!' + command + ':', horizontalalignment='right') if (commandRank < self.BIndex): textWeight = 'bold' else: textWeight = 'normal' yesVotes = str(self.commands[command]) if (commandRank > 0): plt.text(x=self.rightMargin, y=textHeight, s=yesVotes + ' w ', horizontalalignment='left', weight=textWeight) elif (self.commands[command] == 1): plt.text(x=self.rightMargin, y=textHeight, s=yesVotes + ' win. ', horizontalalignment='left', weight=textWeight) else: plt.text(x=self.rightMargin, y=textHeight, s=yesVotes + ' wins.', horizontalalignment='left', weight=textWeight) commandRank = commandRank + 1 if self.Reached_Bottom_Of_Window(commandRank): break #if self.No_More_Yes_Votes(command): # break def Draw_Owner(self): robot = self.db.Get_Living_Robot_At_Position(self.primaryRobotIndex) ownerID = self.db.From_Robot_Record_Get_Owner_ID(robot) if ownerID == -1: ownerName = "none." else: owner = self.db.Get_User_By_ID(ownerID) ownerName = self.db.From_User_Record_Get_Name(owner) plt.text(x=self.leftMargin, y=self.topRow - 1 * self.rowHeight, s='Owner:', horizontalalignment='right') plt.text(x=self.rightMargin, y=self.topRow - 1 * self.rowHeight, s=ownerName, horizontalalignment='left') def Draw_Text(self): self.Draw_Age() self.Draw_Owner() self.Draw_B_Index() self.Draw_Commands() def No_More_Yes_Votes(self, command): return self.commands[command] == 0 def Reached_Bottom_Of_Window(self, commandRank): return commandRank == 6
class CHAT_BOT(): def __init__(self): self.database = DATABASE() self.Open_Connection() self.timeOfLastConnectionReset = time.time() def Close_Connection(self): self.connection.close_socket() def Create_User_If_Necessary(self): if not self.database.User_Exists(self.username): self.database.Add_User(self.username) self.Welcome_New_User() def Send_Chat(self): chatType = random.randint(0, 5) if chatType == 0: self.Send_Command() elif chatType == 1: self.Send_Speedup() else: self.Send_ReinforcementUnlock() def Send_Command(self): print('*jump') self.connection.send_message('*jump') def Send_ReinforcementUnlock(self): randomColor = random.choice(c.colors) randomPrefix = random.choice(['', 'u']) randomChat = randomPrefix + randomColor print(randomChat) self.connection.send_message(randomChat) def Send_Speedup(self): print('+') self.connection.send_message('+') def Log_Chat(self): self.chat_all.handle_chat_message(self.username, self.message) def Open_Connection(self): file = open("../credentials.credentials", "r") oauth = file.readline().rstrip() channel = file.readline().rstrip() host = "irc.twitch.tv" port = 6667 identity = "TPR_Chatbot" self.rate = 20. / 30. self.connection = CONNECTION(channel, host, port, identity) self.connection.connect(oauth) self.chat_help = HELP(self.database, self.connection) self.chat_command = COMMAND(self.database, self.connection) self.chat_reinforcement = REINFORCEMENT(self.database, self.connection) self.chat_speedChange = SPEED_CHANGE(self.database, self.connection) self.chat_unlock = UNLOCK(self.database, self.connection) self.chat_showAll = SHOW_ALL(self.database, self.connection) self.chat_buyBot = BUY_BOT(self.database, self.connection) self.chat_stealBot = STEAL_BOT(self.database, self.connection) self.chat_unlockEnv = UNLOCK_ENV(self.database, self.connection) self.chat_all = ALL_CHAT(self.database, self.connection) def Print_To_Screen(self): print(self.username, self.message) def Respond_If_Buy_Bot(self): if self.chat_buyBot.is_valid_message(self.message): self.chat_buyBot.handle_chat_message(self.username, self.message) #print('') def Respond_If_Command(self): if self.chat_command.is_valid_message(self.message): self.chat_command.handle_chat_message(self.username, self.message) #print('') def Respond_If_Help(self): if self.chat_help.is_valid_message(self.message): self.chat_help.handle_chat_message(self.username, self.message) #print('') def Respond_If_Reinforcement(self): if self.chat_reinforcement.is_valid_message(self.message): self.chat_reinforcement.handle_chat_message( self.username, self.message) #print('') def Respond_If_Show_All(self): if self.chat_showAll.is_valid_message(self.message): self.chat_showAll.handle_chat_message(self.username, self.message) #print('') def Respond_If_Speed_Change(self): if self.chat_speedChange.is_valid_message(self.message): self.chat_speedChange.handle_chat_message(self.username, self.message) #print('') def Respond_If_Steal_Bot(self): if self.chat_stealBot.is_valid_message(self.message): self.chat_stealBot.handle_chat_message(self.username, self.message) #print('') def Respond_If_Unlock(self): if self.chat_unlock.is_valid_message(self.message): self.chat_unlock.handle_chat_message(self.username, self.message) #print('') def Respond_If_Unlock_Env(self): if self.chat_unlockEnv.is_valid_message(self.message): self.chat_unlockEnv.handle_chat_message(self.username, self.message) #print('') def Reset_Connection(self): secondsSinceLastConnectionReset = time.time( ) - self.timeOfLastConnectionReset if secondsSinceLastConnectionReset > c.timeBetweenConnectionResets: self.Close_Connection() self.Open_Connection() self.timeOfLastConnectionReset = time.time() def Shorten_Message_If_Necessary(self): if len(self.message) > c.longestUserMessage: self.message = self.message[:c.longestUserMessage] def Welcome_New_User(self): msg = "Welcome %s! Typing options for you will appear in stream shortly." % ( self.username) self.connection.send_message(msg) def handle_chat(self): # self.Reset_Connection() self.Get_Message() if not self.message: return self.Create_User_If_Necessary() self.user_dat = self.database.Get_User_Stats(self.username) self.Respond_If_Unlock_Env() self.Respond_If_Steal_Bot() self.Respond_If_Buy_Bot() self.Respond_If_Show_All() self.Respond_If_Speed_Change() self.Respond_If_Command() self.Respond_If_Reinforcement() self.Respond_If_Unlock() self.Respond_If_Help() self.Log_Chat()
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() db.Print_Robots()
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() db.Print_Unique_Commands()
#!/usr/bin/python3 import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": d = DATABASE() d.Populate()
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() reinforcements = db.Get_Reinforcements() for reinforcement in reinforcements: print(reinforcement)
class ROBOT_SCORE_BOARD: def __init__(self): self.db = DATABASE() self.robots = self.db.Get_Living_Robots() self.numColumns = len(self.robots) self.commands = self.db.Get_Unique_Commands() random.shuffle(self.commands) while len(self.commands) > 10: del self.commands[-1] self.numRows = len(self.commands) self.cellWidth = 10 self.matrix = MATRIX( numRows = self.numRows , numColumns = self.numColumns , cellWidth = self.cellWidth ) self.Set_Cell_Colors() self.Set_Cell_Contents() def Draw(self,primaryBotIndex): plt.rcParams.update({'font.size': 14}) plt.rcParams.update({'font.family': 'monospace'}) self.fig, self.ax = plt.subplots(1) self.fig.patch.set_facecolor('green') self.fig.patch.set_alpha(0.0) self.matrix.Draw(self.ax,primaryBotIndex) self.Draw_Commands() self.Underline_Rows() self.Clean_Up(self.ax,primaryBotIndex) def Print(self): self.matrix.Print() def Save(self,primaryBotIndex): self.Draw(primaryBotIndex) plt.savefig('test.png', transparent=True) self.fig.clf() del self.fig del self.ax plt.close() def Sufficient_Conditions_For_Drawing(self): return True # -------------- Private methods ------------------------- def Clean_Up(self,ax,primaryBotIndex): plt.axis([ self.matrix.Left() , self.matrix.Right() , self.matrix.Bottom() , self.matrix.Top() ]) ax.set_xticks([]) ax.set_yticks([]) ax.set_title('Yes votes for the ' + c.colorNamesNoParens[primaryBotIndex] + ' robot.') def Draw_Commands(self): for i in range(0,self.numRows): command = self.commands[ i ] commandString = '!' + self.db.From_UniqueCommand_Record_Get_String(command) self.matrix.On_Row_Draw_Text(i , commandString ) def Set_Cell_Colors(self): for i in range(0,self.numRows): command = self.commands[ i ] for j in range(0,self.numColumns): robotColor = c.colorRGBs[ j ] self.matrix.Set_Cell_Color( i , j , robotColor ) def Set_Cell_Contents(self): for i in range(0,self.numRows): command = self.commands[ i ] commandString = self.db.From_UniqueCommand_Record_Get_String(command) for j in range(0,self.numColumns): robot = self.robots[ j ] robotID = self.db.From_Robot_Record_Get_ID(robot) numYesVotes = self.db.Get_Yes_Votes_For_Robot_Under_Command(robotID,commandString) self.matrix.Set_Cell_Contents( i , j , str(numYesVotes) ) def Underline_Rows(self): self.matrix.Underline_Rows()
class ACTIVE_USERS: def __init__(self, database): self.database = DATABASE() self.activeUsers = {} self.timeOfLastUsersUpdate = time.time() def Draw_To(self, screen): row = cpg.numRows - 1 # Sort users by the number of commands they have entered. for user in sorted(self.activeUsers.values(), key=operator.attrgetter('points')): if (row > 0): user.Draw_To(screen, row) row = row - 1 def Get_Highest_Score(self): if self.activeUsers == {}: return 0 return self.Get_Highest_Scoring_User().points def Get_Max_Pts_And_Pts_Per_Sec(self): maxPts = 0.0 ptsPerSec = 0.1 for user in self.activeUsers: if self.activeUsers[user].Get_Points() > maxPts: maxPts = self.activeUsers[user].Get_Points() ptsPerSec = self.activeUsers[user].Get_Pts_Per_Sec() return maxPts, ptsPerSec def Print(self): for user in self.activeUsers: self.activeUsers[user].Print() def Update(self): self.Update_Users() self.Update_Points() # -------------- Private methods --------------- def File_Exists(self, fileName): return os.path.isfile(fileName) def Find_Active_Users(self): self.activeUsers = {} userMustHaveChattedSinceThisTime = time.time( ) - cpg.inactivateUserAfter userMustHaveChattedSinceThisTime = datetime.datetime.fromtimestamp( userMustHaveChattedSinceThisTime) recentChat = self.database.Get_Chat_Entered_Since( userMustHaveChattedSinceThisTime) if not recentChat: return for chat in recentChat: userID = self.database.From_ChatEntries_Record_Get_UserID(chat) user = self.database.Get_User_By_ID(userID) username = self.database.From_User_Record_Get_Name(user) points = self.database.From_User_Record_Get_Points(user) pointsPerSec = self.database.From_User_Record_Get_PointsPerSec( user) if username not in self.activeUsers: self.activeUsers[username] = ACTIVE_USER( userID, username, points, pointsPerSec) datetimeOfRecentChat = self.database.From_ChatEntries_Record_Get_Date( chat) self.activeUsers[username].Update_Datetime_Of_Most_Recent_Chat( datetimeOfRecentChat) def Get_Highest_Scoring_User(self): rankedUsers = sorted(self.activeUsers.values(), key=operator.attrgetter('points'), reverse=True) return rankedUsers[0] def Update_Points(self): for user in self.activeUsers: self.activeUsers[user].Update_Points() def Update_Users(self): secondsSinceLastUsersUpdate = time.time() - self.timeOfLastUsersUpdate if secondsSinceLastUsersUpdate > cpg.timeBetweenUsersUpdates: self.Find_Active_Users() self.timeOfLastUsersUpdate = time.time()
class TestDatabase(TestCase): testDb = DATABASE(dbFile="testDatabase.db") def setUp(self): self.testDb.Populate() def tearDown(self): self.testDb.Reset() def test_Add_Command_New(self): testCommand = "test" self.testDb.Add_Command(testCommand) executionString = "SELECT * FROM Commands WHERE command = '{}'".format(testCommand) self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() cmdList = [cmd for (cmd, date) in testQuery] dateList = [date for (cmd, date) in testQuery] self.assertEqual(len(cmdList), 1) self.assertEqual(len(dateList), 1) def test_Add_Command_Existing(self): executionString = "SELECT command FROM Commands ORDER BY command DESC LIMIT 1" self.testDb.cur.execute(executionString) testCommand = self.testDb.cur.fetchone()[0] self.testDb.Add_Command(testCommand) executionString = "SELECT * FROM Commands WHERE command = '{}'".format(testCommand) self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() cmdList = [cmd for (cmd, date) in testQuery] dateList = [date for (cmd, date) in testQuery] self.assertEqual(len(cmdList), 2) self.assertEqual(len(dateList), 2) def test_Add_Evaluation(self): testEval = (0, 'r', 'test') self.testDb.Add_Evaluation(*testEval) executionString = "SELECT * FROM Evaluations ORDER BY Id DESC LIMIT 1" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchone() print(testQuery) robotId = testQuery[1] robotColor = testQuery[2] command = testQuery[3] self.assertEqual(robotId, 0) self.assertEqual(robotColor, 'r') self.assertEqual(command, 'test') # TODO make Id increment in reinforcements table to make this test work def test_Add_Reinforcement(self): testReinforce = (3, 2, 'n') self.testDb.Add_Reinforcement(*testReinforce) executionString = "SELECT * FROM Reinforcements ORDER BY Id DESC LIMIT 1" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchone() evalId = testQuery[1] robotId = testQuery[2] reinforcement = testQuery[3] self.assertEqual(evalId, 3) self.assertEqual(robotId, 2) self.assertEqual(reinforcement, 'n') # TODO configure test with actual robot def test_Add_Robot(self): pass # TODO check vector encoding def test_Add_Unique_Command_New(self): testCommand = "'test'" self.testDb.Add_Unique_Command(testCommand) executionString = "SELECT * FROM UniqueCommands WHERE command = {}".format(testCommand) self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchone() command = testQuery[0] self.assertEqual(command, 'test') # TODO increment user Id for this to work def test_Add_User(self): testUser = "******" self.testDb.Add_User(testUser) executionString = "SELECT * FROM Users ORDER BY Id DESC LIMIT 1" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchone() user = testQuery[1] self.assertEqual(user, testUser) def test_Aggressor_Can_Kill_Defender_True(self): testRobotIds = (0, 1) self.assertTrue(self.testDb.Aggressor_Can_Kill_Defender(*testRobotIds)) def test_Aggressor_Can_Kill_Defender_True(self): testRobotIds = (1, 2) self.assertFalse(self.testDb.Aggressor_Can_Kill_Defender(*testRobotIds)) def test_Bot_Is_Dead_False(self): testRobotId = 0 self.assertFalse(self.testDb.Bot_Is_Dead(testRobotId)) def test_Bot_Is_Dead_True(self): testRobotId = 2 self.assertTrue(self.testDb.Bot_Is_Dead(testRobotId)) # TODO implement Get_Robot_Color_Index method in database.py def test_Color_Of_Bot(self): testRobotId = 0 self.testDb.Color_Of_Bot(testRobotId) def test_Command_Avaliable_True(self): self.assertTrue(self.testDb.Command_Available()) def test_Command_Avaliable_False(self): self.testDb.Reset() self.assertFalse(self.testDb.Command_Available()) def test_Command_Is_New_True(self): self.assertTrue(self.testDb.Command_Is_New("test")) def test_Command_Is_New_False(self): self.assertFalse(self.testDb.Command_Is_New("run")) # TODO find a way to test this def test_Connect(self): pass @patch('database.database.DATABASE.Create_Tables') def test_Create(self, Mock_Create_Tables): self.testDb.Create() self.testDb.Create_Tables.assert_called_once_with() def test_Create_Tables(self): # Drop all tables executionString = "SELECT * FROM sqlite_master WHERE type = 'table'" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() oldTableNames = [name for (table, name, *rest) in testQuery] [self.testDb.cur.execute("Drop Table {}".format(tableName)) for tableName in oldTableNames] # Recreate tables self.testDb.Create_Tables() # Assert tables were created self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() newTableNames = [name for (table, name, *rest) in testQuery] self.assertListEqual(newTableNames, oldTableNames) def test_Delete_Command_From_Queue(self): # Get old list of commands in Commands table executionString = "SELECT command FROM Commands" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() oldCommands = [cmd for (cmd,) in testQuery] # Delete first command from Commands self.testDb.Delete_Command_From_Queue() # Get new list of commands in COmmands table self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() newCommands = [cmd for (cmd,) in testQuery] # Assert new list is one entry shorter self.assertEqual(len(oldCommands), len(newCommands)+1) # TODO def test_Delete_Data_Files(self): pass def test_Delete_Evaluation(self): # Get old list of evaluations in Evaluation table executionString = "SELECT Id FROM Evaluations" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() oldEvalIds = [evalId for (evalId,) in testQuery] # Delete last evaluation from Evaluations self.testDb.Delete_Evaluation(2) # Get new list of evaluation in Evaluations table self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() newEvalIds = [evalId for (evalId,) in testQuery] # Assert new list is one entry shorter self.assertEqual(len(oldEvalIds), len(newEvalIds) + 1) def test_Delete_Evaluation_If_Non_Reinforced(self): import datetime # Add non-reinforced evaluation to Evaluations table Id = self.testDb.Get_Next_Available_Evaluation_ID() strng = 'INSERT INTO Evaluations VALUES (?,?,?,?,?)' date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") nonReEval = (str(Id), str(3), 'p', 'test', date) params = (nonReEval[0], nonReEval[1], nonReEval[2], nonReEval[3], nonReEval[4]) self.testDb.cur.execute(strng, params) self.testDb.con.commit() # Get old list of evaluations executionString = "SELECT Id FROM Evaluations" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() oldEvalIds = [evalId for (evalId,) in testQuery] # Delete non-reinforced entry self.testDb.Delete_Evaluation_If_Non_Reinforced(nonReEval[0]) # Check if entry was deleted self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() newEvalIds = [evalId for (evalId,) in testQuery] self.assertEqual(len(oldEvalIds), len(newEvalIds) + 1) def test_Delete_Non_Reinforced_Evaluations(self): import datetime # Add non-reinforced evaluation to Evaluations table Id = self.testDb.Get_Next_Available_Evaluation_ID() strng = 'INSERT INTO Evaluations VALUES (?,?,?,?,?)' date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") nonReEval = (str(Id), str(3), 'p', 'test', date) params = (nonReEval[0], nonReEval[1], nonReEval[2], nonReEval[3], nonReEval[4]) self.testDb.cur.execute(strng, params) self.testDb.con.commit() # Get old list of evaluations executionString = "SELECT Id FROM Evaluations" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() oldEvalIds = [evalId for (evalId,) in testQuery] # Delete non-reinforced entry self.testDb.Delete_Non_Reinforced_Evaluations() # Check if entry was deleted self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() newEvalIds = [evalId for (evalId,) in testQuery] self.assertEqual(len(oldEvalIds), len(newEvalIds) + 1) def test_Delete_Old_And_Non_Reinforced_Evaluations(self): import datetime # Add old non-reinforced evaluation to Evaluations table Id = self.testDb.Get_Next_Available_Evaluation_ID() strng = 'INSERT INTO Evaluations VALUES (?,?,?,?,?)' date = (datetime.datetime.now()-datetime.timedelta(minutes=9)).strftime("%Y-%m-%d %H:%M:%S") nonReEval = (str(Id), str(3), 'p', 'test', date) params = (nonReEval[0], nonReEval[1], nonReEval[2], nonReEval[3], nonReEval[4]) self.testDb.cur.execute(strng, params) self.testDb.con.commit() # Get old list of evaluations executionString = "SELECT Id FROM Evaluations" self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() oldEvalIds = [evalId for (evalId,) in testQuery] # Delete non-reinforced entry self.testDb.Delete_Old_And_Non_Reinforced_Evaluations() # Check if entry was deleted self.testDb.cur.execute(executionString) testQuery = self.testDb.cur.fetchall() newEvalIds = [evalId for (evalId,) in testQuery] self.assertEqual(len(oldEvalIds), len(newEvalIds) + 1) # TODO implement mock or patch to test this def test_Destroy(self): pass # TODO implement mock or patch to test this def test_Drop_Table(self): pass # TODO implement mock or patch to test this def test_Drop_Tables(self): pass def test_From_Evaluation_Record_Get_Id(self): testEval = (0, 1, 'r', 'walk', '2018-07-20 13:07:02') testId = self.testDb.From_Evaluation_Record_Get_Id(testEval) self.assertEqual(testId, testEval[0]) def test_From_Evaluation_Record_Get_RobotId(self): testEval = (0, 1, 'r', 'walk', '2018-07-20 13:07:02') testRobotId = self.testDb.From_Evaluation_Record_Get_RobotId(testEval) self.assertEqual(testRobotId, testEval[1]) def test_From_Evaluation_Record_Get_RobotColor(self): testEval = (0, 1, 'r', 'walk', '2018-07-20 13:07:02') testRobotColor = self.testDb.From_Evaluation_Record_Get_RobotColor(testEval) self.assertEqual(testRobotColor, testEval[2]) def test_From_Evaluation_Record_Get_Command(self): testEval = (0, 1, 'r', 'walk', '2018-07-20 13:07:02') testId = self.testDb.From_Evaluation_Record_Get_Command(testEval) self.assertEqual(testId, testEval[3]) def test_From_Evaluation_Record_Get_Date(self): testEval = (0, 1, 'r', 'walk', '2018-07-20 13:07:02') testDate = self.testDb.From_Evaluation_Record_Get_Date(testEval) self.assertEqual(testDate, testEval[4]) def test_From_Reinforcement_Record_Get_Evaluation_Id(self): testReinforce = (0, 1, 2, 'n', '2018-7-20-13:11:49') testEvalId = self.testDb.From_Reinforcement_Record_Get_Evaluation_ID(testReinforce) self.assertEqual(testEvalId, testReinforce[1]) def test_From_Reinforcement_Record_Get_Signal(self): testReinforce = (0, 1, 2, 'n', '2018-7-20-13:11:49') testSignal = self.testDb.From_Reinforcement_Record_Get_Signal(testReinforce) self.assertEqual(testSignal, testReinforce[3]) def test_From_Reinforcement_Record_Get_Time(self): testReinforce = (0, 1, 2, 'n', '2018-7-20-13:11:49') testEvalTime = self.testDb.From_Reinforcement_Record_Get_Time(testReinforce) self.assertEqual(testEvalTime, testReinforce[4]) def test_From_Robot_Record_Get_Id(self): testRobot = (2, 3, 1, '2018-07-20 13:17:38', 0) testId = self.testDb.From_Robot_Record_Get_ID(testRobot) self.assertEqual(testId, testRobot[0]) def test_From_Robot_Record_Get_Color_Index(self): testRobot = (2, 3, 1, '2018-07-20 13:17:38', 0) testColorIndex = self.testDb.From_Robot_Record_Get_Color_Index(testRobot) self.assertEqual(testId, testRobot[1]) def test_From_Robot_Record_Get_Parent_Id(self): testRobot = (2, 3, 1, '2018-07-20 13:17:38', 0) testParentId = self.testDb.From_Robot_Record_Get_Color_Index(testRobot) self.assertEqual(testId, testRobot[2]) def test_From_Robot_Record_Get_Creation_Date(self): testRobot = (2, 3, 1, '2018-07-20 13:17:38', 0) testParentId = self.testDb.From_Robot_Record_Get_Creation_Date(testRobot) self.assertEqual(testId, testRobot[3]) def test_From_Robot_Record_Get_Alive_Status(self): testRobot = (2, 3, 1, '2018-07-20 13:17:38', 0) testParentId = self.testDb.From_Robot_Record_Get_Alive_Status(testRobot) self.assertEqual(testId, testRobot[3]) def test_From_UniqueCommand_Record_Get_String(self): testCommand = ('walk',) testCommandString = self.testDb.From_UniqueCommand_Record_Get_String(testCommand) self.assertEqual(testCommandString, testCommand[0]) # TODO def test_Get_B_Index_For_Robot(self): pass # TODO def test_Get_B_Index_For_Robot_At_Time(self): pass # TODO find a way to test this def test_Get_Command_Encoding(self): # print(self.testDb.Get_Command_Encoding('jump')) pass def test_Get_Command_From_Queue(self): # Get first command in queue executionString = "SELECT * FROM Commands ORDER BY ROWID ASC LIMIT 1" self.testDb.cur.execute(executionString) row = self.testDb.cur.fetchone() testCommand = row[0] # Check if method fetches right command self.assertEqual(self.testDb.Get_Command_From_Queue(), testCommand) # TODO find a way to test this def test_Get_Command_Vector_Encoding(self): pass def test_Get_Commands(self): executionString = "SELECT * FROM Commands" self.testDb.cur.execute(executionString) cmdList = self.testDb.cur.fetchall() self.assertEqual(self.testDb.Get_Commands(), cmdList) # TODO def test_Get_Commands_Robot_Is_Most_Obedient_To(self): print(self.testDb.Get_Commands_Robot_Is_Most_Obedient_To(0)) def test_Get_Commands_Robot_Is_Most_Obedient_To_At_Time(self): pass def test_Get_Evaluation_Id(self): pass def test_Get_Evaluation_Where_Id_Equals(self): pass def test_Get_Evaluations(self): pass def test_Get_Evaluations_Where_RobotId_Equals(self):
#!/usr/bin/python3 import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": d = DATABASE() d.Destroy()
import sys sys.path.insert(0, '..') from database.database import DATABASE db = DATABASE() db.Add_User('joshb')
NEW_DATABASE = False if (NEW_DATABASE): from TPR_3.robot import ROBOT else: sys.path.insert(0, '../TPR_3') from robot import ROBOT dirname = '../data' myfiles = os.listdir(dirname) # returns a list robots = len(myfiles) -1 #only using xyz of pos sensor (size 3) sensors = 3 timesteps = c.evaluationTime db = DATABASE() ''' pick whether you want a single unique command or all of the commands given (you may need to get rid of multiword/unwanted to commands) ''' unique_commands = ([c[0] for c in db.Get_Unique_Commands()]) print(unique_commands) #command = 'move' def create_reinforcement_array(robots,command): ''' find the number of yes and no reinforcements from a robot normalize the difference using a method on page 5 from Mahoor,Felag,Bongard '''
import sys sys.path.insert(0, '..') from database.database import DATABASE db = DATABASE() db.Add_Chat_Message('?', 'joshb') db.Add_User('joshb')
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() db.Delete_Non_Reinforced_Evaluations()
import random import sys sys.path.insert(0, "..") import constants as c from database.database import DATABASE database = DATABASE() def All_But_Two_Envs_Locked(): lockedEnvs = database.Get_Locked_Environments() return len(lockedEnvs) == c.NUM_ENVIRONMENTS_AVAILABLE - 2 def Lock_Envs(): for e in range(3, c.NUM_ENVIRONMENTS_AVAILABLE + 1): # Do not lock the first two environments... database.Lock_Environment(e) def Locking_Required():
def Reset_Database(): d = DATABASE(silent_mode=True) d.Reset() print('The database is reset.') return d
import sys import os sys.path.insert(0, '..') from database.database import DATABASE if __name__ == "__main__": db = DATABASE() db.Print_Evaluations()