Ejemplo n.º 1
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))
Ejemplo n.º 2
0
    def inputManager(self):
        while (self.running):
            pr(cnf.mainMenu)
            ans = raw_input("What do you want to do? ")
            ans = convertInput(ans)

            # Decode input
            if (ans == 1):
                self.editNetwork()
            elif (ans == 2):
                self.saveNetwork()
            elif (ans == 3):
                self.loadNetwork()
            elif (ans == 4):
                self.running = False
Ejemplo n.º 3
0
	def inputManager(self):
		while(self.running):
			pr(cnf.mainMenu)
			ans = raw_input("What do you want to do? ")
			ans = convertInput(ans)
			
			# Decode input
			if(ans == 1):
				self.editNetwork()
			elif(ans == 2):
				self.saveNetwork()
			elif(ans == 3):
				self.loadNetwork()
			elif(ans == 4):
				self.running = False
Ejemplo n.º 4
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))
Ejemplo n.º 5
0
	def getListPossibleValues(self, cpt, i, j, rootTuple, currentSetValues, remainingList):
		# If we're at the bottom of the chain
		if len(remainingList) == 0:
			pr("[Node]: Please specify probability of " + str(rootTuple[0].getName()).upper() + " = " + str(rootTuple[1]).upper() + " given: ")
			for parent, value in currentSetValues:
				pr(str(parent.getName()) + " = " + value)
			ans = parseInputToNumber(input("Answer: "))
			cpt[i][j] = (list(currentSetValues), ans)
			return

		# Else 
		valueTuple = remainingList.pop()
		parent = valueTuple[0]
		values = valueTuple[1]

		for value in values:
			currentSetValues.append([parent, value])
			self.getListPossibleValues(cpt, i, j, rootTuple, currentSetValues, list(remainingList))
			currentSetValues.remove([parent, value])
			j = j+1
Ejemplo n.º 6
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
Ejemplo n.º 7
0
    def run(self):
        if (testMode != None):
            pygame.init()
            self.screen = pygame.display.set_mode(
                (self.mapsize[0], self.mapsize[1]))
            pygame.display.set_caption('UtilitySolver')
            pygame.mouse.set_visible(1)

        ## Init pyGame
        pygame.init()
        self.screen = pygame.display.set_mode(
            (self.mapsize[0], self.mapsize[1]))
        pygame.display.set_caption('UtilitySolver')
        pygame.mouse.set_visible(1)

        # load images
        BayesianNode.loadImages(1.2)

        # Init network
        self.loader = NetworkLoader()

        self.save = self.loader.checkForPossibleSaves()

        if (self.save == None):
            pr("Okey, no saves to load, lets make a new network.")
            name = raw_input("What do you want to call your network? ")
            self.save = self.loader.createSave(name)
            pr("New network " + name + " created")

        pr("UtilitySolver " + cnf.versionName + "\n")

        # Goto mainloop
        self.loop()
Ejemplo n.º 8
0
	def run(self):
		if(testMode != None):
			pygame.init()
			self.screen = pygame.display.set_mode((self.mapsize[0], self.mapsize[1]))
			pygame.display.set_caption('UtilitySolver')
			pygame.mouse.set_visible(1)


		## Init pyGame
		pygame.init()
		self.screen = pygame.display.set_mode((self.mapsize[0], self.mapsize[1]))
		pygame.display.set_caption('UtilitySolver')
		pygame.mouse.set_visible(1)

		# load images
		BayesianNode.loadImages(1.2)

		# Init network
		self.loader = NetworkLoader()

		self.save = self.loader.checkForPossibleSaves()

		if(self.save == None):
			pr("Okey, no saves to load, lets make a new network.")
			name = raw_input("What do you want to call your network? ")
			self.save = self.loader.createSave(name)
			pr("New network " + name + " created")

		pr("UtilitySolver " + cnf.versionName+"\n")

		# Goto mainloop
		self.loop()
Ejemplo n.º 9
0
    def editNetwork(self):
        pr(cnf.networkMenu)
        ans = raw_input("What do you want to do? ")
        ans = convertInput(ans)

        # Decode input
        if (ans == 0):
            self.finalizeNetwork()
        elif (ans == 1):
            self.addNodeToNetwork()
        elif (ans == 2):
            self.editNodeInNetwork()
        elif (ans == 3):
            self.deleteNodeInNetwork()
        elif (ans == 4):
            self.addUtilityNodeToNetwork()
        elif (ans == 5):
            self.addDecisionNodeToNetwork()
        elif (ans == 6):
            self.doInferenceOnNetwork()
        elif (ans == 7):
            self.definalizeNetwork()
Ejemplo n.º 10
0
	def editNetwork(self):
		pr(cnf.networkMenu)
		ans = raw_input("What do you want to do? ")
		ans = convertInput(ans)

		# Decode input
		if(ans == 0):
			self.finalizeNetwork()
		elif(ans == 1):
			self.addNodeToNetwork()
		elif(ans == 2):
			self.editNodeInNetwork()
		elif(ans == 3):
			self.deleteNodeInNetwork()
		elif(ans == 4):
			self.addUtilityNodeToNetwork()
		elif(ans ==  5):
			self.addDecisionNodeToNetwork()
		elif(ans == 6):
			self.doInferenceOnNetwork()
		elif(ans == 7):
			self.definalizeNetwork()
Ejemplo n.º 11
0
    def getListPossibleValues(self, cpt, i, j, rootTuple, currentSetValues,
                              remainingList):
        # If we're at the bottom of the chain
        if len(remainingList) == 0:
            pr("[Node]: Please specify probability of " +
               str(rootTuple[0].getName()).upper() + " = " +
               str(rootTuple[1]).upper() + " given: ")
            for parent, value in currentSetValues:
                pr(str(parent.getName()) + " = " + value)
            ans = parseInputToNumber(input("Answer: "))
            cpt[i][j] = (list(currentSetValues), ans)
            return

        # Else
        valueTuple = remainingList.pop()
        parent = valueTuple[0]
        values = valueTuple[1]

        for value in values:
            currentSetValues.append([parent, value])
            self.getListPossibleValues(cpt, i, j, rootTuple, currentSetValues,
                                       list(remainingList))
            currentSetValues.remove([parent, value])
            j = j + 1
Ejemplo n.º 12
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
Ejemplo n.º 13
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
Ejemplo n.º 14
0
 def doInferenceOnNetwork(self):
     pr("Inference for network " + network.name)
     pr(cnf.inferenceMenu)
Ejemplo n.º 15
0
	def doInferenceOnNetwork(self):
		pr("Inference for network " + network.name)
		pr(cnf.inferenceMenu)
Ejemplo n.º 16
0
 def enableSaves(self):
     if (cnf.useSaveFile):
         pr("Saves are already enabled")
     else:
         cnf.useSaveFile = True
Ejemplo n.º 17
0
	def enableSaves(self):
		if(cnf.useSaveFile):
			pr("Saves are already enabled")
		else:
			cnf.useSaveFile = True
Ejemplo n.º 18
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