Example #1
0
	def loop(self):	

		node1 = BayesianNode()

		self.running = True

		inputThread = threading.Thread(target = self.inputManager)
		inputThread.start()

		# Set backgroundinitial color to white
		self.screen.fill(Color(255,255,255,255))
		try:
			while(self.running):

				# Event-handling
				for event in pygame.event.get():
					if event.type == QUIT:
						running = False
						return
				# Redraw
				self.screen.blit(BayesianNode.image, BayesianNode.imageRect)
				pygame.display.flip()
		except:
			er("Something went wrong...")
		finally:
			# Clean-up
			self.running = False

			pygame.quit()
			inputThread.join()
Example #2
0
    def getProbabilityOfValue(self, value):
        if not value in self.values:
            er("[Node]: Value is not in self.values")

        # Find row
        row = self.values.index(value)

        # Set start, we assume a start prob of 0
        probability = 0

        # If this is observable we can really just check if the value passed in
        # is the same as the currently set value
        if (self.observable):
            if (value == self.currentValue):
                return 1
            else:
                return 0
        else:
            for valueTuple in self.CPT[row]:
                nodeProb = valueTuple[1]

                for parent, value in valueTuple[0]:
                    if not parent == None:
                        nodeProb *= parent.getProbabilityOfValue(value)

                probability += nodeProb
        return probability
Example #3
0
 def addParents(self, parents):
     if (self.finalized):
         er("[Node]: Node is already finalized. Can not perform addParents."
            )
         return
     for parent in self.parents:
         self.addParent(parent)
Example #4
0
    def loop(self):

        node1 = BayesianNode()

        self.running = True

        inputThread = threading.Thread(target=self.inputManager)
        inputThread.start()

        # Set backgroundinitial color to white
        self.screen.fill(Color(255, 255, 255, 255))
        try:
            while (self.running):

                # Event-handling
                for event in pygame.event.get():
                    if event.type == QUIT:
                        running = False
                        return
                # Redraw
                self.screen.blit(BayesianNode.image, BayesianNode.imageRect)
                pygame.display.flip()
        except:
            er("Something went wrong...")
        finally:
            # Clean-up
            self.running = False

            pygame.quit()
            inputThread.join()
Example #5
0
	def getProbabilityOfValue(self, value):
		if not value in self.values:
			er("[Node]: Value is not in self.values")
		
		# Find row
		row = self.values.index(value)

		# Set start, we assume a start prob of 0
		probability = 0
		
		# If this is observable we can really just check if the value passed in
		# is the same as the currently set value
		if(self.observable):
			if(value == self.currentValue):
				return 1
			else:
				return 0
		else:
			for valueTuple in self.CPT[row]:
				nodeProb = valueTuple[1]

				for parent, value in valueTuple[0]:
					if not parent == None:
						nodeProb *= parent.getProbabilityOfValue(value)	

				probability += nodeProb
		return probability
Example #6
0
    def createSave(self, name, network=None):
        if (not cnf.useSaveFile):
            er("You are trying to create a save while saves are disabled, enable saving by running 'NetworkLoader.enableSaves()'"
               )
            return

        # Check if directory exists, and make one if not
        if (not os.path.isdir("saves")):
            os.makedirs("saves/")
            specificSaveFile = open("saves/" + name, 'ab+')

        saveFile = open('saveFile', 'ab+')

        while (saveFile.read().find("save:" + name) != -1):
            er("Save already exists.")
            newName = raw_input("Please input a new name: ")
            name = str(newName)

        specificSaveFile = open('saves/' + name, 'ab+')

        saveFile.write("\nsave:" + name + " = " + "\"saves/" + name + "\"")
        saveFile.close()

        # We have a network we need to save
        if (network != None):
            lol = False
Example #7
0
	def createSave(self, name, network = None):
		if(not cnf.useSaveFile):
			er("You are trying to create a save while saves are disabled, enable saving by running 'NetworkLoader.enableSaves()'")
			return

		# Check if directory exists, and make one if not
		if(not os.path.isdir("saves")):
			os.makedirs("saves/")
			specificSaveFile = open("saves/"+name, 'ab+')
		
		saveFile = open('saveFile', 'ab+')

		while(saveFile.read().find("save:"+name) != -1):
			er("Save already exists.")
			newName = raw_input("Please input a new name: ")
			name = str(newName)

		specificSaveFile = open('saves/'+name, 'ab+')

		saveFile.write("\nsave:"+name +" = " + "\"saves/"+name+"\"")
		saveFile.close()

		# We have a network we need to save
		if(network != None):
			lol = False
Example #8
0
	def addValue(self, value):
		if(self.finalized):
			er("[Node]: Node is already finalized. Can not perform addValue.")
			return
		# Set first value added as default value
		if(self.currentValue == None):
			self.currentValue = value
		self.values.append(value)
Example #9
0
 def addValue(self, value):
     if (self.finalized):
         er("[Node]: Node is already finalized. Can not perform addValue.")
         return
     # Set first value added as default value
     if (self.currentValue == None):
         self.currentValue = value
     self.values.append(value)
Example #10
0
	def removeConnectionTo(self, parent):
		if(finalized):
			er("[Node]: Node is already finalized. Can not perform removeConnectionTo.")
			return
		self.connect
		for connection in self.connections:
			if parent == connection.getParent():
				self.connections.remove(connection)
			parent.removeConnection(connection)
Example #11
0
	def removeConnection(self, connection):
		if(self.finalized):
			er("[Node]: Node is already finalized. Can not perform removeConnection.")
			return
		self.connect
		if connection in self.connections:
			if(connection.getParent() != self):
				connection.getParent().removeConnection(connection)
			self.connections.remove(connection)
Example #12
0
	def setObservable(self, boolean):
		if(self.finalized):
			er("[Node]: Node is already finalized. Can not perform setObservable.")
			return
		for parent in self.parents:
			if not parent.observable:
				er("[Node]: Cannot make node observable if parent is unobservable "+
				   "(this does not make any logical sense)")
				return
		self.observable = boolean
Example #13
0
	def addParent(self, parent):
		if(self.finalized):
			er("[Node]: Node is already finalized. Can not perform addParent.")
			return

		self.parents.append(parent)

		connection = Connection(self, parent)
		self.addConnection(connection)
		parent.addConnection(connection)
Example #14
0
    def addParent(self, parent):
        if (self.finalized):
            er("[Node]: Node is already finalized. Can not perform addParent.")
            return

        self.parents.append(parent)

        connection = Connection(self, parent)
        self.addConnection(connection)
        parent.addConnection(connection)
Example #15
0
	def updateSave(self, network, save):
		foundSave = ["/saveName/", "/notFound/"] 
		
		for existingSave in self.saves:
			if(existingSave[0] == save):
				foundSave = existingSave
		
		# Check if we have found a new save (i.e. foundSave is updated)
		if(foundSave[0] == "/saveName/" and foundSave[1] == "/notFound/"):
			er("Save " + save + " not found, please check your if your save exists")
Example #16
0
 def removeConnectionTo(self, parent):
     if (finalized):
         er("[Node]: Node is already finalized. Can not perform removeConnectionTo."
            )
         return
     self.connect
     for connection in self.connections:
         if parent == connection.getParent():
             self.connections.remove(connection)
         parent.removeConnection(connection)
Example #17
0
 def removeConnection(self, connection):
     if (self.finalized):
         er("[Node]: Node is already finalized. Can not perform removeConnection."
            )
         return
     self.connect
     if connection in self.connections:
         if (connection.getParent() != self):
             connection.getParent().removeConnection(connection)
         self.connections.remove(connection)
Example #18
0
 def setObservable(self, boolean):
     if (self.finalized):
         er("[Node]: Node is already finalized. Can not perform setObservable."
            )
         return
     for parent in self.parents:
         if not parent.observable:
             er("[Node]: Cannot make node observable if parent is unobservable "
                + "(this does not make any logical sense)")
             return
     self.observable = boolean
Example #19
0
    def updateSave(self, network, save):
        foundSave = ["/saveName/", "/notFound/"]

        for existingSave in self.saves:
            if (existingSave[0] == save):
                foundSave = existingSave

        # Check if we have found a new save (i.e. foundSave is updated)
        if (foundSave[0] == "/saveName/" and foundSave[1] == "/notFound/"):
            er("Save " + save +
               " not found, please check your if your save exists")
Example #20
0
	def finalize(self):
		if(self.network == None):
			er("[UtilityNode]: Can't finalize (any) node which is not a part of a network")
			return

		for parent in self.parents:
			if not parent.finalized == True:
				er("[UtilityNode]: Parent is not finalized, what are you doing?! Exiting ...")
				return
			for value in parent.getValues():
				pr("[UtilityNode]: Please specify utility for " + str(parent.getName()) + " = " + str(value))
				ans = parseInputToNumber(input("Answer: "))
				self.utilityTable.append(([parent, value], ans))
Example #21
0
    def finalize(self):
        if (self.finalized == True):
            er("[Node]: Node is already finalized. Please call definalize if you want to refinalize."
               )

        if (self.network == None):
            er("[Node]: Can't finalize a node which is not a part of a network, please call \"setNetwork()\""
               )

        self.finalized = True

        if (len(self.parents) == 0):
            if not self.observable:
                self.CPT = [[0] for i in range(len(self.values))]
                for i in range(0, len(self.values)):
                    pr("[Node]: Please specify probability for " +
                       self.getName() + " = " + str(self.values[i]))
                    ans = parseInputToNumber(input("Answer: "))
                    self.CPT[i] = ([[None, None]], ans)
                    return
            else:
                self.CPT = [[0] for i in range(len(self.values))]
                for i in range(len(self.values)):
                    self.CPT[i] = ([[None, None]], 1 / len(self.values))
                    return

        # Create CPT's
        valueLists = [[parent, parent.getValues()] for parent in self.parents]

        totalLength = 1
        for parent, valueSet in valueLists:
            totalLength *= len(valueSet)

        pr("[Node]: Finalizing node with a CPT of total size " +
           str(totalLength * len(self.values)))

        self.CPT = [[0] * totalLength for i in range(len(self.values))]

        if (self.observable == True):
            pr("[Node]: This node is observable. You should therefore make sure only one variable per row/column is set.\n[Node]: The CPT will be normalized automatically."
               )
        else:
            pr("[Node]: This node is not observable. All column/row-combinations can contain information.\n[Node]: The CPT will be normalized automatically"
               )
        emptyArray = []

        i = 0
        for value in self.values:
            self.getListPossibleValues(self.CPT, i, 0, [self, value],
                                       emptyArray, list(valueLists))
            i = i + 1
Example #22
0
    def finalize(self):
        if (self.network == None):
            er("[UtilityNode]: Can't finalize (any) node which is not a part of a network"
               )
            return

        for parent in self.parents:
            if not parent.finalized == True:
                er("[UtilityNode]: Parent is not finalized, what are you doing?! Exiting ..."
                   )
                return
            for value in parent.getValues():
                pr("[UtilityNode]: Please specify utility for " +
                   str(parent.getName()) + " = " + str(value))
                ans = parseInputToNumber(input("Answer: "))
                self.utilityTable.append(([parent, value], ans))
Example #23
0
    def setCurrentValue(self, value):
        if not value in self.values:
            er("Value does not exist in node")
            return
        self.currentValue = value

        # Update CPT's, if finalized
        if self.finalized:
            relevantRow = self.values.index(value)

            for row in self.CPT:
                for valuePair in row:
                    valuePair[1] = 0

            for valuePair in self.CPT[relevantRow]:
                valuePair[1] = 1
Example #24
0
	def setCurrentValue(self, value):
		if not value in self.values:
			er("Value does not exist in node")
			return
		self.currentValue = value

		# Update CPT's, if finalized
		if self.finalized:
			relevantRow = self.values.index(value)

			for row in self.CPT:
				for valuePair in row:
					valuePair[1] = 0

			for valuePair in self.CPT[relevantRow]:
				valuePair[1] = 1
Example #25
0
	def finalize(self):
		if(self.finalized == True):
			er("[Node]: Node is already finalized. Please call definalize if you want to refinalize.")

		if(self.network == None):
			er("[Node]: Can't finalize a node which is not a part of a network, please call \"setNetwork()\"")

		self.finalized = True

		if(len(self.parents) == 0):
			if not self.observable:
				self.CPT = [[0] for i in range(len(self.values))]
				for i in range(0,len(self.values)):
					pr("[Node]: Please specify probability for " + self.getName() + " = " + str(self.values[i]))
					ans = parseInputToNumber(input("Answer: "))
					self.CPT[i] = ([[None, None]], ans)
					return
			else:
				self.CPT = [[0] for i in range(len(self.values))]
				for i in range(len(self.values)):
					self.CPT[i] = ([[None, None]], 1/len(self.values))	
					return

		# Create CPT's
		valueLists = [[parent, parent.getValues()] for parent in self.parents]

		totalLength = 1
		for parent, valueSet in valueLists:
			totalLength *= len(valueSet)

		pr("[Node]: Finalizing node with a CPT of total size " + str(totalLength*len(self.values)))

		self.CPT = [[0]*totalLength for i in range(len(self.values))]

		if(self.observable == True):
			pr("[Node]: This node is observable. You should therefore make sure only one variable per row/column is set.\n[Node]: The CPT will be normalized automatically.")
		else:
			pr("[Node]: This node is not observable. All column/row-combinations can contain information.\n[Node]: The CPT will be normalized automatically")
		emptyArray = []

		i = 0
		for value in self.values:
			self.getListPossibleValues(self.CPT, i, 0, [self, value], emptyArray, list(valueLists))
			i = i+1
Example #26
0
	def inferUtility(self):
		if(self.network == None):
			er("[UtilityNode]: Can't give the utility of a node not part of a network")

		totalUtility = 0
		for parent in self.parents:

			if parent.observable == False:
				for utilityTuple in self.utilityTable:
					if(utilityTuple[0][0] == parent):
						probability = parent.getProbabilityOfValue(utilityTuple[0][1])
						totalUtility += utilityTuple[1]*probability

			else:
				curValueForParent = parent.getCurrentValue()
				for utilityTuple in self.utilityTable:
					if(utilityTuple[0][0] == parent and utilityTuple[0][1] == curValueForParent):
						totalUtility += utilityTuple[1]
						break
		
		return totalUtility
Example #27
0
    def inferUtility(self):
        if (self.network == None):
            er("[UtilityNode]: Can't give the utility of a node not part of a network"
               )

        totalUtility = 0
        for parent in self.parents:

            if parent.observable == False:
                for utilityTuple in self.utilityTable:
                    if (utilityTuple[0][0] == parent):
                        probability = parent.getProbabilityOfValue(
                            utilityTuple[0][1])
                        totalUtility += utilityTuple[1] * probability

            else:
                curValueForParent = parent.getCurrentValue()
                for utilityTuple in self.utilityTable:
                    if (utilityTuple[0][0] == parent
                            and utilityTuple[0][1] == curValueForParent):
                        totalUtility += utilityTuple[1]
                        break

        return totalUtility
Example #28
0
	def setNetwork(self, network):
		if(self.finalized):
			er("[Node]: Node is already finalized. Can not perform setNetwork.")
			return
		self.network = network
Example #29
0
 def addConnection(self, connection):
     if (self.finalized):
         er("[Node]: Node is already finalized. Can not perform addConnection."
            )
         return
     self.connections.append(connection)
Example #30
0
	def checkForPossibleSaves(self):
		# Open file
		db("Checking for saves")
		if(not os.path.isfile('saveFile')): 
			ans = raw_input("You dont have a saveFile, do you want to make one(y/n)? ")
			if(ans.lower() == "y"):
				f = open('saveFile', 'w+')
				f.write("# Declare version\nmeta:version = " + self.saveFileVersionName +"\n\n")
				f.write("# Save counter\nmeta:counter = " + str(0) +"\n\n")
				f.write("# Saves\n# Example:\n#save:savename = savedir/savefilename")
				f.close()
			else:
				cnf.useSaveFile = False
			return 

		saveFile = open('saveFile', 'r')

		saveFileContent = saveFile.read()
		commentLines = []

		# Remove comment-lines from saveFileContent
		index = saveFileContent.find("#")
		while(index != -1):
			newLineIndex = saveFileContent.find("\n", index)

			# End of file has been reached
			if(newLineIndex == -1):
				commentLines.append(saveFileContent[index:])
			else:
				commentLines.append(saveFileContent[index:newLineIndex])

			index = saveFileContent.find("#", newLineIndex)

		# Remove commentlines
		for line in commentLines:
			saveFileContent = saveFileContent.replace(line, "")

		# Find version
		version = extractValue(saveFileContent, "meta:version")

		if(version == cnf.notFoundHash):
			er("Could not find meta:version in the saveFile. Please manually add: " + self.saveFileVersionName)
		elif(version == cnf.errorHash):
			er("Something went wrong while looking for meta:version...")

		if(not version == self.saveFileVersionName):
			try:
				verId = int(version.replace(".", "").split("x")[1])
				if(verId > self.saveFileVersionCode):
					er("saveFile's version is ahead of yours, perhaps its time to udpate?")
				else:
					er("saveFile's version is outdated, do you want to update it?")
					answer = raw_input("(y/n): ")
					if(answer.lower() == "y"):
						db("Updating saveFile...")
						#TODO
					else:
						pr("Working with outdated saveFile, errors might occur.")
			except:
				er("Illformatted version? Version should be: " + str(self.saveFileVersionCode))

		# No more operations to do on file, we can close it
		saveFile.close()

		# Find count
		saveCount = extractValue(saveFileContent, "meta:count")

		if(saveCount == cnf.notFoundHash):
			er("Could not find meta:count in saveFile. Please add one reflecting the amount of saves in the saveFile")
		elif(saveCount == cnf.errorHash):
			er("Something went wrong while looking for meta:count...")

		try:
			saveCount = int(saveCount)
		except:
			er("Is meta:count not an integer?")

		db(str(saveCount))

		# Find saves
		nextIndex = 0
		while(saveFileContent.find("save:", nextIndex) != -1):
			index = saveFileContent.find("save:", nextIndex)
			saveName = saveFileContent[index+5 : saveFileContent.find(" ", index)]
			saveValue = extractValue(saveFileContent, "save:", index)
		
			db("Save found!")
			db(saveName)
			db(saveValue)
			
			self.saves.append([saveName, saveValue.replace("\"", "")])
			nextIndex = index + 1 

		# Check for default file
		default = extractValue(saveFileContent, "meta:defaultNetwork")

		if(default != cnf.notFoundHash):
			answer = raw_input("Default network is " + default + ". Do you want to load it(y/n)?")
			
			# Load default save
			if(answer.lower() == "y"):
				return [i[0] for i in self.saves].index("Tormod")


		# Ask if anything should be loaded
		if(len(self.saves) == 0):
			return None
		else:
			pr("Save content found:\n----------------")
			i = 1
			for tuple in self.saves:
				print '['+str(i)+'] {0}\t:\t{1}'.format(tuple[0], tuple[1])
				i = i+1
			ans = raw_input("Do you want to load anything right now (LoadNr / n)?")
			if(str(ans) == "n"):
				return -1

			# Check if number is outside the bounds, or is not an integer
			while(True):
				try:
					ans = int(ans)
				except:
					ans = raw_input("Invalid load-value, try again: ")
					continue

				if(ans >= i or ans < 1):
					ans = raw_input("Invalid load-value, try again: ")
					continue
				else:
					break
			return loadSave(ans-1)
		return None
Example #31
0
 def setNetwork(self, network):
     if (self.finalized):
         er("[Node]: Node is already finalized. Can not perform setNetwork."
            )
         return
     self.network = network
Example #32
0
    def checkForPossibleSaves(self):
        # Open file
        db("Checking for saves")
        if (not os.path.isfile('saveFile')):
            ans = raw_input(
                "You dont have a saveFile, do you want to make one(y/n)? ")
            if (ans.lower() == "y"):
                f = open('saveFile', 'w+')
                f.write("# Declare version\nmeta:version = " +
                        self.saveFileVersionName + "\n\n")
                f.write("# Save counter\nmeta:counter = " + str(0) + "\n\n")
                f.write(
                    "# Saves\n# Example:\n#save:savename = savedir/savefilename"
                )
                f.close()
            else:
                cnf.useSaveFile = False
            return

        saveFile = open('saveFile', 'r')

        saveFileContent = saveFile.read()
        commentLines = []

        # Remove comment-lines from saveFileContent
        index = saveFileContent.find("#")
        while (index != -1):
            newLineIndex = saveFileContent.find("\n", index)

            # End of file has been reached
            if (newLineIndex == -1):
                commentLines.append(saveFileContent[index:])
            else:
                commentLines.append(saveFileContent[index:newLineIndex])

            index = saveFileContent.find("#", newLineIndex)

        # Remove commentlines
        for line in commentLines:
            saveFileContent = saveFileContent.replace(line, "")

        # Find version
        version = extractValue(saveFileContent, "meta:version")

        if (version == cnf.notFoundHash):
            er("Could not find meta:version in the saveFile. Please manually add: "
               + self.saveFileVersionName)
        elif (version == cnf.errorHash):
            er("Something went wrong while looking for meta:version...")

        if (not version == self.saveFileVersionName):
            try:
                verId = int(version.replace(".", "").split("x")[1])
                if (verId > self.saveFileVersionCode):
                    er("saveFile's version is ahead of yours, perhaps its time to udpate?"
                       )
                else:
                    er("saveFile's version is outdated, do you want to update it?"
                       )
                    answer = raw_input("(y/n): ")
                    if (answer.lower() == "y"):
                        db("Updating saveFile...")
                        #TODO
                    else:
                        pr("Working with outdated saveFile, errors might occur."
                           )
            except:
                er("Illformatted version? Version should be: " +
                   str(self.saveFileVersionCode))

        # No more operations to do on file, we can close it
        saveFile.close()

        # Find count
        saveCount = extractValue(saveFileContent, "meta:count")

        if (saveCount == cnf.notFoundHash):
            er("Could not find meta:count in saveFile. Please add one reflecting the amount of saves in the saveFile"
               )
        elif (saveCount == cnf.errorHash):
            er("Something went wrong while looking for meta:count...")

        try:
            saveCount = int(saveCount)
        except:
            er("Is meta:count not an integer?")

        db(str(saveCount))

        # Find saves
        nextIndex = 0
        while (saveFileContent.find("save:", nextIndex) != -1):
            index = saveFileContent.find("save:", nextIndex)
            saveName = saveFileContent[index +
                                       5:saveFileContent.find(" ", index)]
            saveValue = extractValue(saveFileContent, "save:", index)

            db("Save found!")
            db(saveName)
            db(saveValue)

            self.saves.append([saveName, saveValue.replace("\"", "")])
            nextIndex = index + 1

        # Check for default file
        default = extractValue(saveFileContent, "meta:defaultNetwork")

        if (default != cnf.notFoundHash):
            answer = raw_input("Default network is " + default +
                               ". Do you want to load it(y/n)?")

            # Load default save
            if (answer.lower() == "y"):
                return [i[0] for i in self.saves].index("Tormod")

        # Ask if anything should be loaded
        if (len(self.saves) == 0):
            return None
        else:
            pr("Save content found:\n----------------")
            i = 1
            for tuple in self.saves:
                print '[' + str(i) + '] {0}\t:\t{1}'.format(tuple[0], tuple[1])
                i = i + 1
            ans = raw_input(
                "Do you want to load anything right now (LoadNr / n)?")
            if (str(ans) == "n"):
                return -1

            # Check if number is outside the bounds, or is not an integer
            while (True):
                try:
                    ans = int(ans)
                except:
                    ans = raw_input("Invalid load-value, try again: ")
                    continue

                if (ans >= i or ans < 1):
                    ans = raw_input("Invalid load-value, try again: ")
                    continue
                else:
                    break
            return loadSave(ans - 1)
        return None
Example #33
0
	def addConnection(self, connection):
		if(self.finalized):
			er("[Node]: Node is already finalized. Can not perform addConnection.")
			return
		self.connections.append(connection)
Example #34
0
	def addParents(self, parents):
		if(self.finalized):
			er("[Node]: Node is already finalized. Can not perform addParents.")
			return
		for parent in self.parents:
			self.addParent(parent)