Ejemplo n.º 1
0
 def __init__(self, identifier, text):
     self.identifier = identifier
     self.text = text
     self.parsed = AGMFileDataParsing.fromText(text)
     self.plannerCode = self.parsed.getAGGLPlannerCode(
         skipPassiveRules=True)
     self.module = self.getModuleFromText(self.plannerCode).RuleSet()
Ejemplo n.º 2
0
    def parse_domain(self, fileName):
        '''
		A parser function for files with .aggl extension
		'''
        agmData = AGMFileDataParsing.fromFile(fileName)
        for rule in agmData.agm.rules:
            self.action_list.append(rule.name)
Ejemplo n.º 3
0
    def parse_domain(self, fileName):
        '''
		A parser for Domain Files (.aggl extension)
		This reads domain file and gathers knowledge about action_list which contains all possible actions:
		'''
        agmData = AGMFileDataParsing.fromFile(fileName)
        for rule in agmData.agm.rules:
            self.action_list.append(rule.name)
Ejemplo n.º 4
0
		
		"""
		Sacamos el nombre de la regla jerarquica
		nombreRegla @  {   x:y x:y ...}      \n
		            n n+1  n+2        len-2  len-1
		"""
		f = open(ficheroPlan, "r")
		reglaJerarquica = f.readline()
		f.close()

		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: "
Ejemplo n.º 5
0
        ficheroPlan = sys.argv[
            3]  # Fichero P con el plan para alcanzar el mundo target.
        """
		Sacamos el nombre de la regla jerarquica
		nombreRegla @  {   x:y x:y ...}      \n
		            n n+1  n+2        len-2  len-1
		"""
        f = open(ficheroPlan, "r")
        reglaJerarquica = f.readline()
        f.close()

        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):
Ejemplo n.º 6
0
 def __init__(self, identifier, text):
     self.identifier = identifier
     self.text = text
     self.module = self.getModuleFromText(self.code).CheckTarget
     self.code = generateTarget_AGGT(
         self.module, AGMFileDataParsing.targetFromText(text))
Ejemplo n.º 7
0
if __name__ == '__main__':  # program domain problem result
    #from pycallgraph import *
    #from pycallgraph.output import GraphvizOutput
    #graphviz = GraphvizOutput()
    #graphviz.output_file = 'basic.png'
    if True:
        #with PyCallGraph(output=graphviz):
        from parseAGGL import AGMFileDataParsing  #AGMFileDataParsing en fichero parseAGGL.py
        t0 = time.time()

        if len(sys.argv) < 6:
            print 'Usage\n\t', sys.argv[
                0], ' domainFile.aggl activeRules.py init.xml target.xml.py trainFile [result.plan] [input_hierarchical.plan]'

        else:
            domainAGM = AGMFileDataParsing.fromFile(
                sys.argv[1])  #From domain.aggl
            domainPath = sys.argv[2]  # ActiveRules.py path
            initPath = sys.argv[3]  # Inital model or world.
            targetPath = sys.argv[4]  # Target model or world.
            trainFile = sys.argv[5]  # Sorting actions by relevance
            resultFile = None
            if len(sys.argv) >= 7: resultFile = open(sys.argv[6], 'w')
            hierarchicalInputPlan = None
            if len(sys.argv) >= 8:
                hierarchicalInputPlan = open(sys.argv[7], 'r')

            domainRuleSet = imp.load_source('module__na_me',
                                            domainPath).RuleSet()
            targetCode = imp.load_source('modeeeule__na_me',
                                         targetPath).CheckTarget
            targetVariablesCode = imp.load_source(
Ejemplo n.º 8
0
#!/usr/bin/env pypy

import sys, traceback
sys.path.append('/usr/local/share/agm/')

import xmlModelParser
from AGGL import *

from parseAGGL import AGMFileDataParsing
from agglplanner import *

if __name__ == '__main__': # program domain problem result
	if len(sys.argv)<4:
		print 'Usage\n\t', sys.argv[0], ' domain.aggl init.xml rulename [param1:value1 [param2:value2 [...]]]'
	else:
		agmData = AGMFileDataParsing.fromFile(sys.argv[1])

		params = dict()
		for i in xrange(4, len(sys.argv)):
			param = sys.argv[i].split(':')
			params[param[0]] = param[1]
		#params = eval(sys.argv[4])


		domainPath = "/tmp/domain.py"
		domain = imp.load_source('domain', domainPath).RuleSet()
		#             aggl   py-domain         init                                        target  indent  params             exclude  write-plan
		p = PyPlan(agmData, domainPath, sys.argv[2], domain.getHierarchicalTargets()[sys.argv[3]],     '', params,      [sys.argv[3]],       None)

Ejemplo n.º 9
0
    def parse_target(self, fileName):

        agmData = AGMFileDataParsing.targetFromFile(fileName)
        print(agmData['graph'].nodes)
        print(agmData['graph'].links)
        '''
		Parse files with .aggt extension, target files (with respect to planner not classifier)
		'''
        self.attr_node = []
        self.attr_link = []
        # Keep tracks of keys used to represent some object type
        var_map = {}
        f = open(fileName)
        flag = False
        for line in f:
            if "{" in line:
                flag = True
            elif "}" in line:
                # Preconditions are not considered while learning.
                break
            if flag:
                if ":" in line:
                    line = line.split(":")
                    final_type = line[1].split("(")[0].strip()
                    line[0] = line[0].strip()
                    # If id is given, initial type is matched to type of id
                    if line[0].isdigit():
                        init_type = self.typeMap[int(line[0])]
                    else:
                        ''' If id is not given, initial type is assumed to be same as final type
						and the mapping is recorded.
						'''
                        init_type = final_type
                        var_map[line[0]] = final_type
                    self.attr_node.append((init_type, final_type))

                elif "->" in line:
                    line = line.split("->")
                    temp = line[1].split("(")
                    # line[0] basically represents src id
                    line[0] = line[0].strip()
                    # temp[0] basically represents dst id.
                    temp[0] = temp[0].strip()
                    # rel stores relations between two id's.
                    rel = temp[1].split(")")[0].strip()

                    # There can be four cases, src id is int/symbol or dst id is int/symbol
                    if line[0].isdigit() and temp[0].isdigit():
                        id1 = int(line[0])
                        id2 = int(temp[0])
                        id_pair = (id1, id2)
                        type1 = self.typeMap[id1]
                        type2 = self.typeMap[id2]

                        self.attr_link.append((type1, rel, type2))
                        if id_pair in self.relMap:
                            for relation in self.relMap[id_pair]:
                                self.attr_link.append((type1, relation, type2))
                                self.attr_link.append(
                                    (type1, relation, rel, type2))

                    else:
                        if not line[0].isdigit():
                            if not temp[0].isdigit():
                                type1 = var_map[line[0]]
                                type2 = var_map[temp[0]]

                                self.attr_link.append((type1, rel, type2))
                                for id_pair in self.relMap:
                                    if type1 == self.typeMap[id_pair[
                                            0]] and type2 == self.typeMap[
                                                id_pair[1]]:
                                        for relation in self.relMap[id_pair]:
                                            self.attr_link.append(
                                                (type1, relation, type2))
                                            self.attr_link.append(
                                                (type1, relation, rel, type2))

                            else:
                                id2 = int(temp[0])
                                type1 = var_map[line[0]]
                                type2 = self.typeMap[id2]

                                self.attr_link.append((type1, rel, type2))
                                for id_pair in self.relMap:
                                    if self.typeMap[id_pair[
                                            0]] == type1 and id_pair[1] == id2:
                                        for relation in self.relMap[id_pair]:
                                            self.attr_link.append(
                                                (type1, relation, type2))
                                            self.attr_link.append(
                                                (type1, relation, rel, type2))

                        else:
                            id1 = int(line[0])
                            type1 = self.typeMap[id1]
                            type2 = var_map[temp[0]]

                            self.attr_link.append((type1, rel, type2))
                            for id_pair in self.relMap:
                                if id_pair[0] == id1 and self.typeMap[
                                        id_pair[1]] == type2:
                                    for relation in self.relMap[id_pair]:
                                        self.attr_link.append(
                                            (type1, relation, type2))
                                        self.attr_link.append(
                                            (type1, relation, rel, type2))
        print(self.attr_node)
        print(self.attr_link)

        f.close()
Ejemplo n.º 10
0
#!/usr/bin/env pypy

import sys, traceback
sys.path.append('/usr/local/share/agm/')

import xmlModelParser
from AGGL import *

from parseAGGL import AGMFileDataParsing
from agglplanner import *

if __name__ == '__main__':  # program domain problem result
    if len(sys.argv) < 4:
        print 'Usage\n\t', sys.argv[
            0], ' domain.aggl init.xml rulename [param1:value1 [param2:value2 [...]]]'
    else:
        agmData = AGMFileDataParsing.fromFile(sys.argv[1])

        params = dict()
        for i in xrange(4, len(sys.argv)):
            param = sys.argv[i].split(':')
            params[param[0]] = param[1]
        #params = eval(sys.argv[4])

        domainPath = "/tmp/domain.py"
        domain = imp.load_source('domain', domainPath).RuleSet()
        #             aggl   py-domain         init                                        target  indent  params             exclude  write-plan
        p = PyPlan(agmData, domainPath, sys.argv[2],
                   domain.getHierarchicalTargets()[sys.argv[3]], '', params,
                   [sys.argv[3]], None)
Ejemplo n.º 11
0
		for other in self.knownNodes:
			if deriv == other:
				if other.cost <= deriv.cost:
					return True
		return False

if __name__ == '__main__': # program domain problem result
	#from pycallgraph import *
	#from pycallgraph.output import GraphvizOutput
	#graphviz = GraphvizOutput()
	#graphviz.output_file = 'basic.png'
	if True:
	#with PyCallGraph(output=graphviz):
		from parseAGGL import AGMFileDataParsing   #AGMFileDataParsing en fichero parseAGGL.py
		t0 = time.time()

		if len(sys.argv)<5:
			print 'Usage\n\t', sys.argv[0], ' domain.aggl activeRules.py init.xml target.xml.py [result.plan]'

		else:
			domainAGM = AGMFileDataParsing.fromFile(sys.argv[1]) #From domain.aggl
			domainPath = sys.argv[2] # Get the activeRules.py path
			init = sys.argv[3]       # Get the inital model or world.
			targetPath = sys.argv[4] # Get the target model or world.
			resultFile = None        
			if len(sys.argv)>=6: resultFile = open(sys.argv[5], 'w')

			p = PyPlan(domainAGM, domainPath, init, targetPath, '', dict(), [], resultFile)
		print 'Tiempo Total: ', (time.time()-t0).__str__()