Esempio n. 1
0
    def setParams(self, params):
        # Get initial model path
        try:
            self.initialModelPath = par = params["InitialModelPath"]
        except:
            traceback.print_exc()
            print "Error reading config params"
            sys.exit(-1)
        # Read initial model and set it as the last modification
        #try:
        self.currentModel = xmlModelParser.graphFromXML(self.initialModelPath)
        #except Exception, e:
        #print 'Can\'t open ' + self.initialModelPath + '.'
        #sys.exit(-1)
        self.initialModel = self.currentModel
        print 'INITIAL MODEL: ', self.initialModel
        self.lastModification = self.initialModel
        print self.lastModification.version

        self.worldModelICE = AGM2ModelConversion.fromInternalToIce(
            self.currentModel)

        self.timer.start(self.Period)
        self.timer.timeout.connect(self.compute)

        self.broadcastCurrentModel()

        return True
Esempio n. 2
0
	def __init__(self, fileList):
		QMainWindow.__init__(self)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		# Graph painters
		self.tool = 'Node - Move'
		self.connect(self.ui.actionChangeAppearance, SIGNAL("triggered(bool)"),  self.changeAppearance)
		self.connect(self.ui.actionQuit,             SIGNAL("triggered(bool)"),  self.appClose)
		self.connect(self.ui.actionAutomatic,        SIGNAL("triggered(bool)"),  self.setAutomaticLayout)
		self.connect(self.ui.actionManual,           SIGNAL("triggered(bool)"),  self.setManualLayout)
		self.drawers = []
		self.widgets = []
		self.automatic = False#True
		
		global vertexDiameter
		global fontName
		global fontSize
		vertexDiameter = 45
		fontName = 'Arial 14'

		# Node appearance
		self.appearance = Appearance()
		self.appearance.ui.radius.setValue(vertexDiameter)

		# Font
		font = QFont(fontName, fontSize)
		font.setItalic(False)
		font.setItalic(False)
		self.fontDialog = QFontDialog(font, self)
		self.fontDialog.setCurrentFont(font)
		self.font = self.fontDialog.currentFont()
		self.connect(self.ui.actionChangeFont,                 SIGNAL("triggered(bool)"),                                      self.changeFont)

		self.resize(1200,700)
		for fil in range(len(fileList)):
			self.widgets.append(QWidget())
			self.widgets[fil].resize(1200/len(fileList), 700)
			self.widgets[fil].show()
			self.ui.horizontalLayout.addWidget(self.widgets[fil])
		for fil in range(len(fileList)):
			self.drawers.append(GraphDraw(self.widgets[fil], self, "xxxx"))
			print 'xmlModelParser()', fileList[fil]
			self.drawers[fil].graph = xmlModelParser.graphFromXML(fileList[fil])
			
			print 'nodes',self.drawers[fil].graph.nodes
			for key in self.drawers[fil].graph.nodes.keys():
				v = self.drawers[fil].graph.nodes[key]
				print key,v, self.drawers[fil].graph.nodes[key].attributes
				
			print 'links',self.drawers[fil].graph.links
			L=self.drawers[fil].graph.links
			for index, item in enumerate(L):
					print index, item
					print item.attributes
			self.drawers[fil].show()

		self.timer = QTimer()
		self.connect(self.timer, SIGNAL('timeout()'), self.draw)
		self.timer.start(20)
Esempio n. 3
0
class Executive(object):
    def __init__(self, agglPath, initialModelPath, initialMissionPath,
                 doNotPlan, executiveTopic, executiveVisualizationTopic,
                 speech):
        self.doNotPlan = doNotPlan
        self.executiveActive = True
        self.mutex = threading.RLock()
        self.agents = dict()
        self.plan = None
        self.modifications = 0
        self.plannerCaller = PlannerCaller(self, agglPath)
        self.plannerCaller.start()

        # Set proxies
        self.executiveTopic = executiveTopic
        self.executiveVisualizationTopic = executiveVisualizationTopic
        self.speech = speech

        self.agglPath = agglPath
        self.initialModelPath = initialModelPath
        try:
            self.initialModel = xmlModelParser.graphFromXML(initialModelPath)
        except Exception, e:
            print 'Can\'t open ' + initialModelPath + '.'
            sys.exit(-1)

        print 'INITIAL MODEL: ', self.initialModel
        self.lastModification = self.initialModel
        print self.lastModification.version
        print self.lastModification.version
        print self.lastModification.version
        print self.lastModification.version
        print self.lastModification.version
        print self.lastModification.version
        self.backModelICE = None
        self.setAndBroadcastModel(
            xmlModelParser.graphFromXML(initialModelPath))
        self.worldModelICE = AGMModelConversion.fromInternalToIce(
            self.currentModel)
        self.setMission(initialMissionPath, avoidUpdate=True)
Esempio n. 4
0
	def __init__(self, agglPath, initialModelPath, initialMissionPath, doNotPlan, executiveTopic, executiveVisualizationTopic, speech):
		self.doNotPlan = doNotPlan
		self.executiveActive = True
		self.mutex = threading.RLock()
		self.agents = dict()
		self.plan = None
		self.modifications = 0
		self.plannerCaller = PlannerCaller(self, agglPath)
		self.plannerCaller.start()

		# Set proxies
		self.executiveTopic = executiveTopic
		self.executiveVisualizationTopic = executiveVisualizationTopic
		self.speech = speech

		self.agglPath = agglPath
		self.initialModelPath = initialModelPath
		try:
			self.initialModel = xmlModelParser.graphFromXML(initialModelPath)
		except Exception, e:
			print 'Can\'t open ' + initialModelPath + '.'
			sys.exit(-1)
Esempio n. 5
0
    def __init__(self, agglPath, initialModelPath, initialMissionPath,
                 doNotPlan, executiveTopic, executiveVisualizationTopic,
                 speech):
        self.doNotPlan = doNotPlan
        self.executiveActive = True
        self.mutex = threading.RLock()
        self.agents = dict()
        self.plan = None
        self.modifications = 0
        self.plannerCaller = PlannerCaller(self, agglPath)
        self.plannerCaller.start()

        # Set proxies
        self.executiveTopic = executiveTopic
        self.executiveVisualizationTopic = executiveVisualizationTopic
        self.speech = speech

        self.agglPath = agglPath
        self.initialModelPath = initialModelPath
        try:
            self.initialModel = xmlModelParser.graphFromXML(initialModelPath)
        except Exception, e:
            print 'Can\'t open ' + initialModelPath + '.'
            sys.exit(-1)
Esempio n. 6
0
		finNombre = reglaJerarquica.find("@")
		nombreRegla = reglaJerarquica[:finNombre]
		
		""" Aplicamos la regla sobre el mundo de origen y guardamos el resultado en un fichero temporal. Para ello, debemos... """
		"1) pasar el dominio de AGGL a PY" 
		agmData = AGMFileDataParsing.fromFile(ficheroDominio)
		agmData.generateAGGLPlannerCode("/tmp/domain.py", skipPassiveRules=True)
		dominioPython = "/tmp/domain.py"
		
		"2) Sacamos del dominio el conjunto de reglas"
		dominioFinal = imp.load_source('domain', dominioPython).RuleSet() 
		mapaReglas = copy.deepcopy(dominioFinal.getRules())
		
		"3) Preparamos el grafo de inicio"
		mundoInicio = WorldStateHistory(xmlModelParser.graphFromXML(ficheroMundo))
		mundoInicio.nodeId = 0 
		
		"4) Del mapa de reglas buscamos nuestra regla jerarquica y la aplicamos. Guardamos el resultado en un XML"
		for resultado in mapaReglas[nombreRegla](mundoInicio): print ' '
		resultado.graph.toXML("/tmp/resultado.xml")
		"5) Del fichero resultado tenemos que poner los nuevos nodos creados como variables no como constantes, para que el programa funcione: "
		quitar_Constantes_Creadas(ficheroMundo)
		
		"AHORA, una vez que tenemos el resultado de aplicar esa regla, la quitamos del dominio de reglas"	
		eliminar_Regla(ficheroDominio, nombreRegla)
		"Guardamos la ruta del fichero de dominio modificado sin la regla"
		ficheroDominioSinRegla = "/tmp/copiaDominio.aggl"
		
		"Llamamos al plan para que mire si el target guardado en result.xml es alcanzable sin la regla jerarquica"
		import subprocess
Esempio n. 7
0
        finNombre = reglaJerarquica.find("@")
        nombreRegla = reglaJerarquica[:finNombre]
        """ Aplicamos la regla sobre el mundo de origen y guardamos el resultado en un fichero temporal. Para ello, debemos... """
        "1) pasar el dominio de AGGL a PY"
        agmData = AGMFileDataParsing.fromFile(ficheroDominio)
        agmData.generateAGGLPlannerCode("/tmp/domain.py",
                                        skipPassiveRules=True)
        dominioPython = "/tmp/domain.py"

        "2) Sacamos del dominio el conjunto de reglas"
        dominioFinal = imp.load_source('domain', dominioPython).RuleSet()
        mapaReglas = copy.deepcopy(dominioFinal.getRules())

        "3) Preparamos el grafo de inicio"
        mundoInicio = WorldStateHistory(
            xmlModelParser.graphFromXML(ficheroMundo))
        mundoInicio.nodeId = 0

        "4) Del mapa de reglas buscamos nuestra regla jerarquica y la aplicamos. Guardamos el resultado en un XML"
        for resultado in mapaReglas[nombreRegla](mundoInicio):
            print ' '
        resultado.graph.toXML("/tmp/resultado.xml")
        "5) Del fichero resultado tenemos que poner los nuevos nodos creados como variables no como constantes, para que el programa funcione: "
        quitar_Constantes_Creadas(ficheroMundo)

        "AHORA, una vez que tenemos el resultado de aplicar esa regla, la quitamos del dominio de reglas"
        eliminar_Regla(ficheroDominio, nombreRegla)
        "Guardamos la ruta del fichero de dominio modificado sin la regla"
        ficheroDominioSinRegla = "/tmp/copiaDominio.aggl"

        "Llamamos al plan para que mire si el target guardado en result.xml es alcanzable sin la regla jerarquica"
Esempio n. 8
0
import sys, traceback, Ice, subprocess, threading, time, Queue, os, time
import IceStorm

# AGM
sys.path.append('/usr/local/share/agm')

from parseAGGL import *
from generateAGGLPlannerCode import *
from agglplanner import *
from agglplanchecker import *

import xmlModelParser

import pickle

# Check that RoboComp has been correctly detected
ROBOCOMP = ''
try:
    ROBOCOMP = os.environ['ROBOCOMP']
except:
    pass
if len(ROBOCOMP) < 1:
    print 'ROBOCOMP environment variable not set! Exiting.'
    sys.exit()

model = xmlModelParser.graphFromXML(sys.argv[1])
model.filterGeometricSymbols().toXML(sys.argv[2])
Esempio n. 9
0
	def __init__(self, agmData, domainPath, init, planPath, targetPath, symbolMapping=dict(), resultPath='', verbose=False):
		object.__init__(self)
		## We get the initial world model graph
		self.initWorld  = WorldStateHistory([xmlModelParser.graphFromXML(init), agmData.getInitiallyAwakeRules()])

		# Get graph rewriting rules
		if verbose: print 'domainPath:', domainPath
		domain = imp.load_source('domain', domainPath)
		## We save the grammar rules
		self.domain = domain.RuleSet()
		# Get goal-checking code

		if type(targetPath)== type(''):
			if verbose: print 'targetPath:', targetPath
			target = imp.load_source('target', targetPath)
			self.targetCode = target.CheckTarget
		else:
			self.targetCode = targetPath

		## We get the plan code
		self.plan = AGGLPlannerPlan(planPath)

		# Apply plan
		if verbose: print "PyPlanChecker applying plan"
		try:
			world = copy.deepcopy(self.initWorld) # we copy the initial world status.
			#if verbose: print world
			line = 0 # This is the actions lines counter. It saves the lines of actions contained in a plan
			if verbose: print '<<plan'
			if verbose: print self.plan
			if verbose: print 'plan>>'
			# We check all the actions in a plan.
			for action in self.plan:
				if verbose: print 'Executing action', line,' ',action
				line += 1
				# We check that the actions parameters are into the world.
				for p in action.parameters.keys():
					if not action.parameters[p] in world.graph.nodes.keys():
						for r in agmData.agm.rules:
							if r.name == action.name:
								rhs = r.rhs
						if not (p in rhs.nodes.keys()):
							# If the parameter doesnt exit in the world nor the RHS of the rule, we raise an exception.
							# Just to warn we're receiving useless parameters
							raise WrongRuleExecution("Parameter '"+action.parameters[p]+"' (variable '"+p+"') doesn't exist in the current world model.")
				world = self.domain.getTriggers()[action.name](world, action.parameters, checked=False)
				if verbose:
					print 'result:'
					print world
				world.graph.toXML('after_plan_step'+str(line)+".xml")

			if verbose: print 'Done executing actions. Let\'s see what we\'ve got (computing score and checking if the goal was achieved).'
			if verbose: print targetPath
			# Get result
			score, achieved = self.targetCode(world.graph) # , symbolMapping
			## We store the result to check the plan
			self.valid = achieved
			if achieved:               # On the one hand, if we achieve the target world status, we will print all the  correct actions of the plan.
				if verbose: print 'GOAL ACHIEVED'
				self.achieved = True
				if verbose:
					for action in self.plan:
						print action
			else:                      # Otherwise, if we dont achieve the goal, we will print an error message.
				self.achieved = False
				if verbose: print 'Not achieved (didn\'t get to the goal)'

		# If we have thrown an exception (because a parameter of an action does not exist),
		# we handle part of the exception in this code.
		except WrongRuleExecution, e:
			if verbose: print 'Invalid rule execution', action
			if verbose: print 'Rule: ', e
			if verbose: print 'Line: ', line
			if verbose: print 'Not achieved'
			self.valid = False
			self.achieved = False
			if verbose: traceback.print_exc()
Esempio n. 10
0
	def __init__(self, domainAGM, domainPath, init, targetPath, indent, symbol_mapping, excludeList, resultFile, descomponiendo=False, estadoIntermedio='', awakenRules=set()):
		object.__init__(self)
		# Get initial world mdoel
		initWorld = WorldStateHistory([xmlModelParser.graphFromXML(init), domainAGM.getInitiallyAwakeRules()|awakenRules])
		initWorld.nodeId = 0 

		self.symbol_mapping = copy.deepcopy(symbol_mapping) 
		self.excludeList = copy.deepcopy(excludeList)
		self.indent = copy.deepcopy(indent)

		# Get graph rewriting rules
		domain = imp.load_source('domain', domainPath).RuleSet() # activeRules.py
		ruleMap = copy.deepcopy(domain.getRules()) #get all the active rules of the grammar
		for e in excludeList: 
			del ruleMap[e]  # delete the rules in excludeList from ruleMap
		#for r in ruleMap:
			#print 'Using', r

		# Get goal-checking code
		if type(targetPath)== type(''):  # type str
			target = imp.load_source('target', targetPath)
			## This attribute stores the code of the goal status world.
			self.targetCode = target.CheckTarget
		else:
			self.targetCode = targetPath

		# Search initialization
		## This attribute indicates the maximum size that can reach the graph
		self.maxWorldSize = maxWorldIncrement+len(initWorld.graph.nodes.keys())
		## This attribute indicates the minimun cost of the open nodes of the graph
		self.minCostOnOpenNodes = LockableInteger(0)
		## This is the lockable list of all the open nodes.
		self.openNodes = LockableList()
		## This is the lockable list of all the know nodes of the graph.
		self.knownNodes = LockableList()
		## This is the lockable list of all the calculated results.
		self.results = LockableList()
		## This is the lockable integer of all the explored nodes
		self.explored = LockableInteger(0)
		## This is the LockableInteger that stores the better cost of the solution
		self.cheapestSolutionCost = LockableInteger(-1)
		## This is the condition to stop.
		self.end_condition = EndCondition()
		# We save in the list of the open nodes, the initial status of the world
		self.openNodes.heapqPush((0, copy.deepcopy(initWorld)))
		if verbose>1 and indent=='': print 'INIT'.ljust(20), initWorld

		# Create initial state
		if self.symbol_mapping:
			initWorld.score, achieved = self.targetCode(initWorld.graph, self.symbol_mapping)
		else:
			initWorld.score, achieved = self.targetCode(initWorld.graph)

		if achieved:
			# If the goal is achieved, we save the solution in the result list, the
			# solution cost in the cheapest solution cost and we put the end_condition
			# as goal achieved in order to stop the execution.
			self.results.append(initWorld)
			self.cheapestSolutionCost.set(self.results.getFirstElement().cost)
			if self.indent == '':
				self.end_condition.set("GoalAchieved")

		elif number_of_threads>0:
			# But, if the goal is not achieved and there are more than 0 thread running (1, 2...)
			# we creates a list where we will save the status of all the threads, take all
			# the threads (with their locks) and save it in the thread_locks list.
			# Run working threads
			## This attributes is a list where we save all the thread that are running.
			self.thread_locks = []
			threadStatus = LockableList()
			for i in xrange(number_of_threads):
				lock = thread.allocate_lock()
				lock.acquire()
				threadStatus.append(True)
				self.thread_locks.append(lock)
				thread.start_new_thread(self.startThreadedWork, (copy.deepcopy(ruleMap), lock, i, threadStatus))
			# Wait for the threads to stop
			for lock in self.thread_locks:
				lock.acquire()
		else:
			# If the solution is not achieved and there arent any thread to execute the programm
			# we stop it and show an error message.
			self.startThreadedWork(ruleMap)

		# We make others checks over the end_condition:
		#	-- If the end condition is wrong.
		#	-- or the end condition exceeded the maximum cost
		#	-- or we have found the best overcome.
		#	-- or we have achieved the goal
		#	-- or we have exceeded the maximum time limit
		#	-- or the end condition doesnt have any message
		# we print the correspond message
		if self.end_condition.get() == "IndexError":
			if verbose > 0: print 'End: state space exhausted'
		elif self.end_condition.get() == "MaxCostReached":
			if verbose > 0: print 'End: max cost reached'
		elif self.end_condition.get() == "BestSolutionFound":
			if verbose > 0: print 'End: best solution found'
		elif self.end_condition.get() == "GoalAchieved":
			if self.indent == '' and verbose > 0: print 'End: goal achieved'
		elif self.end_condition.get() == "TimeLimit":
			if verbose > 0: print 'End: TimeLimit'
		elif self.end_condition.get() == None:
			if verbose > 0: print 'NDD:DD:D:EWJRI'
		else:
			print 'UNKNOWN ERROR'
			print self.end_condition.get()

		if len(self.results)==0: # If the length of the list is zero, it means that we have not found a plan.
			if verbose > 0: print 'No plan found.'
		else: # But, if the length is greater than zero, it means that we have found a plan.
			min_idx = 0
			for i in range(len(self.results)): # We go over all the actions of the plan, and we look for the best solution (the minimun cost).
				if self.results[i].cost < self.results[min_idx].cost:
					min_idx = i
			i = min_idx
			
			if self.indent=='' and verbose > 0: print 'Got', len(self.results),' plans!'
				
		
			try:
				plann = AGGLPlannerPlan([xx.split('@') for xx in self.results[i].history])
				n = copy.deepcopy(plann)
				while len(self.results[i].history)>0:
					n = n.removeFirstAction(initWorld.graph)
					#n = n.removeFirstActionDirect()
					try:
						#print 'QUITADA REGLA: ', self.results[i].history[0], '\nRESTO DEL PLAN: ', n
						"""ANIADIDO DE MERCEDES, YEAH!
						Si estamos descomponiendo una regla jerarquica (estamos buscando un plan para
						llegar al estado que nos indica la regla jerarquica) debemos crear el estado intermedio
						generado por la regla jerarquica y llamar con el al PyPlanChecker"""
						if descomponiendo==True:
							#print 'Hay que crear estado intermedio'
							from agglplanchecker import PyPlanChecker
							check = PyPlanChecker(domainAGM, domainPath, init, n, estadoIntermedio,symbol_mapping, verbose=False)
							
						else:
							#print 'No hay que crear estado intermedio'
							from agglplanchecker import PyPlanChecker
							check = PyPlanChecker(domainAGM, domainPath, init, n, targetPath,symbol_mapping, verbose=False)
					except:
						print 'Excepction!!'
						traceback.print_exc()
						break
					if check.achieved:
						print  '  (removed)', self.results[i].history[0]
						self.results[i].history = self.results[i].history[1:]
						plann = copy.deepcopy(n)
					else:
						print  '  (not removed)', self.results[i].history[0]
						break
				if descomponiendo==False:
					print 'ORIGINAL PLAN: ', self.results[i].cost
					for action in self.results[i].history:
						print '    ', action
			except:
				traceback.print_exc()
				pass
			rList = []
			planConDescomposicion = False
			if len(self.results[i].history) > 0:
				action = self.results[i].history[0]
				ac = AGGLPlannerAction(action)
				if ac.hierarchical:
					self.excludeList.append(ac.name)
					paramsWithoutNew = copy.deepcopy(ac.parameters)
					for param in ac.parameters:
						found = False
						for arule in domainAGM.agm.rules:
							if arule.name == ac.name:
								if param in arule.lhs.nodes:
									found = True
									break
						if not found:
							#print 'removing fixed goal symbol', param
							del paramsWithoutNew[param]
							#paramsWithoutNew[param] = str('v')+str(paramsWithoutNew[param])
					#print paramsWithoutNew
					print '\nDecomposing hierarchical rule ', ac.name, paramsWithoutNew
					"""ANIADIDO DE MERCEDES:
					Creamos estado intermedio, primero lo creamos en fichero .xml para poder quitarle los nuevos nodos creados
					al aplicar la regla jerarquica"""
					for estadoIntermedio in ruleMap[ac.name](initWorld): print ''
					estadoIntermedio.graph.toXML("/tmp/estadoIntermedio.xml")
					"""Quitamos los nodos constantes creados por la regla jerarquica: los volvemos variables para evitar
					errores cuando se genere el codigo target en python."""
					quitar_Constantes_Creadas(init)
					"""Generamos el codigo en python para pasarselo directamente al PyPlan"""
					graph = graphFromXML("/tmp/estadoIntermedio.xml")
					outputText = generateTarget(graph)
					ofile = open("/tmp/estadoIntermedio.py", 'w')
					ofile.write(outputText)
					ofile.close()
					"""Ponemos una bandera para pintar despues el plan completa una vez descompuesta la primera regla jerarquica"""
					planConDescomposicion = True
					aaa = PyPlan(      domainAGM, domainPath, init, domain.getHierarchicalTargets()[ac.name], indent+'\t', paramsWithoutNew, self.excludeList, rList, True, "/tmp/estadoIntermedio.py", copy.deepcopy(self.results[i].awakenRules|awakenRules))
					#if type(resultFile) == type([]):
						#resultFile = rList + resultFile[1:]
					#print self.indent
					self.results[i].history = self.results[i].history[1:]
				else:
					planConDescomposicion = False
				
			#printResult(self.results[i]) #the best solution
			total = rList + self.results[i].history
			if resultFile != None:
				for action in total:
					if type(resultFile) == type([]):
						resultFile.append(action)
					else:
						resultFile.write(str(action)+'\n')			
			if descomponiendo == False and planConDescomposicion == True:
				print 'FINAL PLAN WITH: ',len(total),' ACTIONS:'
				for action in total:
					print '    ',action
			
			if self.indent=='' and verbose > 0: print "----------------\nExplored", self.explored.get(), "nodes"