diff --git a/Python version/base/Callback.py b/Python version/base/callback.py similarity index 96% rename from Python version/base/Callback.py rename to Python version/base/callback.py index b7c0f6f..b95dd64 100644 --- a/Python version/base/Callback.py +++ b/Python version/base/callback.py @@ -1,10 +1,10 @@ -from abc import ABCMeta, abstractmethod - -class Callback(object): - """This interface is used to communicate results of solver invocation to the user""" - - __metaclass__ = ABCMeta - - @abstractmethod - def callback(self, o): +from abc import ABCMeta, abstractmethod + +class Callback(object): + """This interface is used to communicate results of solver invocation to the user""" + + __metaclass__ = ABCMeta + + @abstractmethod + def callback(self, o): pass \ No newline at end of file diff --git a/Python version/base/Handler.py b/Python version/base/handler.py similarity index 86% rename from Python version/base/Handler.py rename to Python version/base/handler.py index 22d4fd3..f2b9e57 100644 --- a/Python version/base/Handler.py +++ b/Python version/base/handler.py @@ -1,132 +1,132 @@ -from abc import ABCMeta - -class Handler(object): - """A collection of InputProgram and OptionDescriptor. - The subclasses have to implement startAsync(Callback, List, List) and startSync(List, List) methods. - Each instance inside _programs and _options are represented by an integer (id) , respectively. - """ - __metaclass__ = ABCMeta - - def __init__(self): - self._programs = dict() # Is where InputProgram elements are stored. - self._options = dict() # Is where OptionDescriptor elements are stored - - def addOption(self, o): - """Add a new element inside _options dict. - The o parameter is the new OptionDescriptor instance. - The method return the id associate to the new added OptionDescriptor instance. - """ - last_index = len(self._options) - current_value = last_index - self._options[last_index]=o - return current_value - - def addProgram(self, program): - """Add a new element inside _programs dict. - The program param is the InputProgram instance added to the collection. - The method return the id associate to the new added InputProgram instance. - """ - last_index = len(self._programs) - current_value = last_index - self._programs[last_index]=program - return current_value - - def _collect_options(self, option_index): - """Return a list of options in _options dict, according to set of indexes given. - If option_index is empty, the method return a list of all options. - """ - input_option = list() - if (not option_index): - for k in self._options.keys(): - input_option.append(self._options.get(k)) - else: - for index in option_index: - input_option.append(self._options.get(index)) - return input_option - - def _collect_programs(self, program_index): - """Return a list of programs in _programs dict, according to set of indexes given. - If program_index is empty, the method return a list of all program. - """ - input_programs = list() - if (not program_index): - for k in self._programs.keys(): - input_programs.append(self._programs.get(k)) - else: - for index in program_index: - input_programs.append(self._programs.get(index)) - return input_programs - - def getInputProgram(self, key): - """Returns the specified InputProgram element - The parameter key represents the id - The method return the InputProgram element associate with the given key - """ - return self._programs.get(key) - - def getOptionDescriptor(self, key): - """Returns the specified OptionDescriptor element - The parameter key represents the id - The method return the OptionDescriptor element associate with the given key - """ - return self._options.get(key) - - def removeAll(self): - """Removes all of the elements from _programs and _options. - Both of the collections will be empty after this method returns. - """ - self._options.clear() - self._programs.clear() - - def removeOptionFromId(self, option_id): - """Removes the element associate within the given id from _options dict. - option_id represents the id associate within an element. - """ - self._options.pop(option_id) - - def removeOptionFromValue(self, o): - """Removes every occurrence of a specified OptionDescriptor element from _options dict. - the parameter o represents the element to be removed - The method return true if one or more elements are removed, false otherwise - """ - result=False - for k in self._options: - if(self._options.get(k) == o): - self._options.pop(k) - result=True - return result - - def removeProgramFromValue(self, p): - """Removes every occurrence of a specified InputProgram element from _programs dict. - The parameter p represents the element to be removed - The method return true if one or more elements are removed, false otherwise - """ - result=False - for k in self._programs: - if(self._programs.get(k) == p): - self._programs.pop(k) - result=True - return result - - def removeProgramFromId(self, program_id): - """Removes the element associate within the given id from _programs} dict. - The parameter program_id represents the id associate within an element - """ - self._programs.pop(program_id) - - - def startAsync(self, c, program_index=None, option_index=None): - """This method have to be implemented by subclasses to execute solver in a asynchronous way, - if no parameters are given, the entire sets of programs and option are used - """ - pass - - def startSync(self, program_index=None, option_index=None): - """This method have to be implemented by subclasses to execute solver in a synchronous way, - if no parameters are given, the entire sets of programs and option are used - """ - return None - - - +from abc import ABCMeta + +class Handler(object): + """A collection of InputProgram and OptionDescriptor. + The subclasses have to implement start_async(Callback, List, List) and start_sync(List, List) methods. + Each instance inside _programs and _options are represented by an integer (id) , respectively. + """ + __metaclass__ = ABCMeta + + def __init__(self): + self._programs = dict() # Is where InputProgram elements are stored. + self._options = dict() # Is where OptionDescriptor elements are stored + + def add_option(self, o): + """Add a new element inside _options dict. + The o parameter is the new OptionDescriptor instance. + The method return the id associate to the new added OptionDescriptor instance. + """ + last_index = len(self._options) + current_value = last_index + self._options[last_index]=o + return current_value + + def add_program(self, program): + """Add a new element inside _programs dict. + The program param is the InputProgram instance added to the collection. + The method return the id associate to the new added InputProgram instance. + """ + last_index = len(self._programs) + current_value = last_index + self._programs[last_index]=program + return current_value + + def _collect_options(self, option_index): + """Return a list of options in _options dict, according to set of indexes given. + If option_index is empty, the method return a list of all options. + """ + input_option = list() + if (not option_index): + for k in self._options.keys(): + input_option.append(self._options.get(k)) + else: + for index in option_index: + input_option.append(self._options.get(index)) + return input_option + + def _collect_programs(self, program_index): + """Return a list of programs in _programs dict, according to set of indexes given. + If program_index is empty, the method return a list of all program. + """ + input_programs = list() + if (not program_index): + for k in self._programs.keys(): + input_programs.append(self._programs.get(k)) + else: + for index in program_index: + input_programs.append(self._programs.get(index)) + return input_programs + + def get_input_program(self, key): + """Returns the specified InputProgram element + The parameter key represents the id + The method return the InputProgram element associate with the given key + """ + return self._programs.get(key) + + def get_option_descriptor(self, key): + """Returns the specified OptionDescriptor element + The parameter key represents the id + The method return the OptionDescriptor element associate with the given key + """ + return self._options.get(key) + + def remove_all(self): + """Removes all of the elements from _programs and _options. + Both of the collections will be empty after this method returns. + """ + self._options.clear() + self._programs.clear() + + def remove_option_from_id(self, option_id): + """Removes the element associate within the given id from _options dict. + option_id represents the id associate within an element. + """ + self._options.pop(option_id) + + def remove_option_from_value(self, o): + """Removes every occurrence of a specified OptionDescriptor element from _options dict. + the parameter o represents the element to be removed + The method return true if one or more elements are removed, false otherwise + """ + result=False + for k in self._options: + if(self._options.get(k) == o): + self._options.pop(k) + result=True + return result + + def remove_program_from_value(self, p): + """Removes every occurrence of a specified InputProgram element from _programs dict. + The parameter p represents the element to be removed + The method return true if one or more elements are removed, false otherwise + """ + result=False + for k in self._programs: + if(self._programs.get(k) == p): + self._programs.pop(k) + result=True + return result + + def remove_program_from_id(self, program_id): + """Removes the element associate within the given id from _programs} dict. + The parameter program_id represents the id associate within an element + """ + self._programs.pop(program_id) + + + def start_async(self, c, program_index=None, option_index=None): + """This method have to be implemented by subclasses to execute solver in a asynchronous way, + if no parameters are given, the entire sets of programs and option are used + """ + pass + + def start_sync(self, program_index=None, option_index=None): + """This method have to be implemented by subclasses to execute solver in a synchronous way, + if no parameters are given, the entire sets of programs and option are used + """ + return None + + + \ No newline at end of file diff --git a/Python version/base/InputProgram.py b/Python version/base/input_program.py similarity index 75% rename from Python version/base/InputProgram.py rename to Python version/base/input_program.py index cc60c6e..1105753 100644 --- a/Python version/base/InputProgram.py +++ b/Python version/base/input_program.py @@ -1,79 +1,79 @@ -class InputProgram(object): - """Represents a generic option""" - - def __init__(self): - """Creates a new programs , setting space as default separator""" - self._programs = "" # Where programs data is stored - self.__files_paths = list() # Where associated files are stored - self._separator = " " # Used as separator for programs - - - def addObjectInput(self,inputObj): - raise "Functionality not implemented" - - def addObjectsInput(self, inputObjs): - for inputObj in inputObjs: - self.addObjectInput(inputObj) - - def addFilesPath(self, file_path): - """Add a new file path into __files_paths - The parameter file_path represents a new file path - """ - self.__files_paths.append(file_path) - - - def addProgram(self, new_instruction): - """Adds a new instruction directly into _programs - The parameter new_instruction rapresents a new programs instruction - """ - if(self._programs == None): - self._programs = new_instruction - else: - self._programs += self._separator + new_instruction - - def clearFilesPaths(self): - """After this method, __files_paths will be empty""" - del self.__files_paths[:] - - def clearPrograms(self): - """After this method, _programs will be empty""" - self._programs = None - - def clearAll(self): - """After this method, both __files_paths and _programs will be empty""" - self.clearFilesPaths() - self.clearPrograms() - - def getFilesPaths(self): - """Returns the __files_paths list""" - return self.__files_paths - - def getPrograms(self): - """Returns data stored in _programs""" - return self._programs - - def getSeparator(self): - """Separator the _separator character""" - return self._separator - - def getStringOfFilesPaths(self): - """Returns string concatenating files paths""" - to_return="" - for paths in self.__files_paths: - if(len(paths) != 0): - to_return += paths + " " - return to_return - - def setPrograms(self, programs): - """Sets _programs value to the new given one - The parameter programs, rapresents new value - """ - self._programs = programs - - def setSeparator(self, separator): - """Set programs separator to current value - The parameter separator is used as new separator - """ - self._separator = separator - - +class InputProgram(object): + """Represents a generic option""" + + def __init__(self): + """Creates a new programs , setting space as default separator""" + self._programs = "" # Where programs data is stored + self.__files_paths = list() # Where associated files are stored + self._separator = " " # Used as separator for programs + + + def add_object_input(self,inputObj): + raise "Functionality not implemented" + + def add_objects_input(self, inputObjs): + for inputObj in inputObjs: + self.add_object_input(inputObj) + + def add_files_path(self, file_path): + """Add a new file path into __files_paths + The parameter file_path represents a new file path + """ + self.__files_paths.append(file_path) + + + def add_program(self, new_instruction): + """Adds a new instruction directly into _programs + The parameter new_instruction rapresents a new programs instruction + """ + if(self._programs == None): + self._programs = new_instruction + else: + self._programs += self._separator + new_instruction + + def clear_files_paths(self): + """After this method, __files_paths will be empty""" + del self.__files_paths[:] + + def clear_programs(self): + """After this method, _programs will be empty""" + self._programs = None + + def clear_all(self): + """After this method, both __files_paths and _programs will be empty""" + self.clear_files_paths() + self.clear_programs() + + def get_files_paths(self): + """Returns the __files_paths list""" + return self.__files_paths + + def get_programs(self): + """Returns data stored in _programs""" + return self._programs + + def get_separator(self): + """Separator the _separator character""" + return self._separator + + def get_string_of_files_paths(self): + """Returns string concatenating files paths""" + to_return="" + for paths in self.__files_paths: + if(len(paths) != 0): + to_return += paths + " " + return to_return + + def set_programs(self, programs): + """Sets _programs value to the new given one + The parameter programs, rapresents new value + """ + self._programs = programs + + def set_separator(self, separator): + """Set programs separator to current value + The parameter separator is used as new separator + """ + self._separator = separator + + diff --git a/Python version/base/OptionDescriptor.py b/Python version/base/option_descriptor.py similarity index 81% rename from Python version/base/OptionDescriptor.py rename to Python version/base/option_descriptor.py index 1dbb7ec..414976d 100644 --- a/Python version/base/OptionDescriptor.py +++ b/Python version/base/option_descriptor.py @@ -1,36 +1,36 @@ -class OptionDescriptor(object): - """Represents options for a generic ASP programs""" - - def __init__(self, initial_option=None): - self._options = initial_option # Where options are stored - self._separator = "" # Used as option separator - - def addOption(self, option): - """Concatenate a new option in a string format to the current _options - The parameter option is the string to be concatenated - """ - if (self._options == None or self._options == ""): - self.setOptions(option) - else: - self._options += self._separator + option - - def clear(self): - """After using this method the _options variable will be empty""" - self._options = "" - - def getOptions(self): - """Returns values stored in _options, in a string format""" - return self._options - - def getSeparator(self): - """Get separator character""" - return self._separator - - def setOptions(self, option): - """Set _option string with new string""" - self._options = option - - def setSeparator(self, separator): - """Set _separator character with new separator""" - self._separator = separator +class OptionDescriptor(object): + """Represents options for a generic ASP programs""" + + def __init__(self, initial_option=None): + self._options = initial_option # Where options are stored + self._separator = "" # Used as option separator + + def add_option(self, option): + """Concatenate a new option in a string format to the current _options + The parameter option is the string to be concatenated + """ + if (self._options == None or self._options == ""): + self.set_options(option) + else: + self._options += self._separator + option + + def clear(self): + """After using this method the _options variable will be empty""" + self._options = "" + + def get_options(self): + """Returns values stored in _options, in a string format""" + return self._options + + def get_separator(self): + """Get separator character""" + return self._separator + + def set_options(self, option): + """Set _option string with new string""" + self._options = option + + def set_separator(self, separator): + """Set _separator character with new separator""" + self._separator = separator \ No newline at end of file diff --git a/Python version/base/Output.py b/Python version/base/output.py similarity index 82% rename from Python version/base/Output.py rename to Python version/base/output.py index f825662..11549ab 100644 --- a/Python version/base/Output.py +++ b/Python version/base/output.py @@ -1,26 +1,26 @@ -class Output(object): - """Represents a generic output for a solver""" - - def __init__(self, output=None, errors=None): - self._output = output # Variable in which results are stored - self._errors = errors # The errors thrown by the solver - - def getErrors(self): - """Get error string""" - return self._errors - - def getOutput(self): - """Get output string""" - return self._output - - def setErrors(self, errors): - """Set error string""" - self._errors=errors - - def setOutput(self, output): - """Set output string""" - self._output=output - - def _parse(self): - """This method have to be implemented by subclasses to parse a solver output""" +class Output(object): + """Represents a generic output for a solver""" + + def __init__(self, output=None, errors=None): + self._output = output # Variable in which results are stored + self._errors = errors # The errors thrown by the solver + + def get_errors(self): + """Get error string""" + return self._errors + + def get_output(self): + """Get output string""" + return self._output + + def set_errors(self, errors): + """Set error string""" + self._errors=errors + + def set_output(self, output): + """Set output string""" + self._output=output + + def _parse(self): + """This method have to be implemented by subclasses to parse a solver output""" pass \ No newline at end of file diff --git a/Python version/base/Service.py b/Python version/base/service.py similarity index 87% rename from Python version/base/Service.py rename to Python version/base/service.py index d9f55a5..63aec6e 100644 --- a/Python version/base/Service.py +++ b/Python version/base/service.py @@ -1,23 +1,23 @@ -from abc import ABCMeta, abstractmethod - -class Service(object): - """Contains generic methods for ASP Solver execution.""" - __metaclass__ = ABCMeta - - @abstractmethod - def startAsync(self, callback, programs, options): - """Starts ASP solving Asyncronously on a subset of data and options. - The parameter callback is an interface used to interact with user - The parameter programs rapresents a list of InputProgram used as data. - The parameter options is a list of OptionDescriptor used as options. - """ - pass - - @abstractmethod - def startSync(self, programs, options): - """Starts ASP solving Syncronously on a subset of data and options. - The parameter programs is a list of InputProgram used as data. - The parameter options is a list of OptionDescriptor used as options. - The method return an Output element filled with results - """ +from abc import ABCMeta, abstractmethod + +class Service(object): + """Contains generic methods for ASP Solver execution.""" + __metaclass__ = ABCMeta + + @abstractmethod + def start_async(self, callback, programs, options): + """Starts ASP solving Asyncronously on a subset of data and options. + The parameter callback is an interface used to interact with user + The parameter programs rapresents a list of InputProgram used as data. + The parameter options is a list of OptionDescriptor used as options. + """ + pass + + @abstractmethod + def start_sync(self, programs, options): + """Starts ASP solving Syncronously on a subset of data and options. + The parameter programs is a list of InputProgram used as data. + The parameter options is a list of OptionDescriptor used as options. + The method return an Output element filled with results + """ pass \ No newline at end of file diff --git a/Python version/languages/asp/AnswerSet.py b/Python version/languages/asp/answer_set.py similarity index 79% rename from Python version/languages/asp/AnswerSet.py rename to Python version/languages/asp/answer_set.py index 65ec076..36f0940 100644 --- a/Python version/languages/asp/AnswerSet.py +++ b/Python version/languages/asp/answer_set.py @@ -1,38 +1,38 @@ -from languages.asp.ASPMapper import ASPMapper - -class AnserSet(object): - """A collection of data representing a generic Answer Set""" - - def __init__(self, value, weightMap=dict()): - self.__value = value # Where data of answer set is stored - self.__weight_map = weightMap # Where weights of the answer set are stored - self.__atoms = set() # Where Answer set's atoms are stored - - def getAnswerSet(self): - """Return the current __value data - The method return a list of answer sets in a String format - """ - return self.__value - - def getAtoms(self): - """Return atoms stored in __atoms - The method return a set of Object filled with atoms data - """ - if not self.__atoms: - mapper = ASPMapper.getInstance() - for atom in self.__value: - obj = mapper.getObject(atom) - if (not obj == None): - self.__atoms.add(obj) - return self.__atoms - - def getWeights(self): - """Return the weight_map""" - return self.__weight_map - - def __str__(self): - """Overload string method""" - return str(self.__value) - - - +from languages.asp.asp_mapper import ASPMapper + +class AnserSet(object): + """A collection of data representing a generic Answer Set""" + + def __init__(self, value, weightMap=dict()): + self.__value = value # Where data of answer set is stored + self.__weight_map = weightMap # Where weights of the answer set are stored + self.__atoms = set() # Where Answer set's atoms are stored + + def get_answer_set(self): + """Return the current __value data + The method return a list of answer sets in a String format + """ + return self.__value + + def get_atoms(self): + """Return atoms stored in __atoms + The method return a set of Object filled with atoms data + """ + if not self.__atoms: + mapper = ASPMapper.get_instance() + for atom in self.__value: + obj = mapper.get_object(atom) + if (not obj == None): + self.__atoms.add(obj) + return self.__atoms + + def get_weights(self): + """Return the weight_map""" + return self.__weight_map + + def __str__(self): + """Overload string method""" + return str(self.__value) + + + diff --git a/Python version/languages/asp/AnswerSets.py b/Python version/languages/asp/answer_sets.py similarity index 53% rename from Python version/languages/asp/AnswerSets.py rename to Python version/languages/asp/answer_sets.py index 616e7de..92bfc5f 100644 --- a/Python version/languages/asp/AnswerSets.py +++ b/Python version/languages/asp/answer_sets.py @@ -1,20 +1,20 @@ -from base.Output import Output - -class AnswerSets(Output): - """A collection of AnswerSet""" - - def __init__(self, out, err=None): - super(AnswerSets, self).__init__(out, err) - self._answersets = None # Where Answer Sets are stored - - def getAnswerSets(self): - """Return a set of AnswerSet""" - if(self._answersets == None): - self._answersets = list() - self._parse() - return self._answersets - - def getAnswerSetsString(self): - """Return a string which contains all AnswerSet""" - return self._output - +from base.output import Output + +class AnswerSets(Output): + """A collection of AnswerSet""" + + def __init__(self, out, err=None): + super(AnswerSets, self).__init__(out, err) + self._answer_sets = None # Where Answer Sets are stored + + def get_answer_sets(self): + """Return a set of AnswerSet""" + if(self._answer_sets == None): + self._answer_sets = list() + self._parse() + return self._answer_sets + + def get_answer_sets_string(self): + """Return a string which contains all AnswerSet""" + return self._output + diff --git a/Python version/languages/asp/ASPFilterOption.py b/Python version/languages/asp/asp_filter_option.py similarity index 79% rename from Python version/languages/asp/ASPFilterOption.py rename to Python version/languages/asp/asp_filter_option.py index e052936..ea687b3 100644 --- a/Python version/languages/asp/ASPFilterOption.py +++ b/Python version/languages/asp/asp_filter_option.py @@ -1,10 +1,10 @@ -from abc import ABCMeta -from base.OptionDescriptor import OptionDescriptor - -class ASPFilterOption(OptionDescriptor): - """Generic filter option for ASP solver""" - - __metaclass__ = ABCMeta - - def __init__(self): +from abc import ABCMeta +from base.option_descriptor import OptionDescriptor + +class ASPFilterOption(OptionDescriptor): + """Generic filter option for ASP solver""" + + __metaclass__ = ABCMeta + + def __init__(self): super(ASPFilterOption, self).__init__("-filter=") \ No newline at end of file diff --git a/Python version/languages/asp/ASPInputProgram.py b/Python version/languages/asp/asp_input_program.py similarity index 60% rename from Python version/languages/asp/ASPInputProgram.py rename to Python version/languages/asp/asp_input_program.py index 7bf9c11..c97d495 100644 --- a/Python version/languages/asp/ASPInputProgram.py +++ b/Python version/languages/asp/asp_input_program.py @@ -1,21 +1,21 @@ -from base.InputProgram import InputProgram -from languages.asp.ASPMapper import ASPMapper - -class ASPInputProgram(InputProgram): - """A generic ASP program, with the capabilities of retrieve data by objects""" - - def __init__(self): - super(ASPInputProgram, self).__init__() - - - def addObjectInput(self, inputObj): - """Transforms a given Object class into a InputProgram and adds it to the current _programs - The parameter inputObj is an object to be transformed - """ - self.addProgram(ASPMapper.getInstance().getString(inputObj) + ".") - - - def addObjectsInput(self, inputObjs): - """Transforms a set of objects""" - for inputObj in inputObjs: - self.addObjectInput(inputObj) \ No newline at end of file +from base.input_program import InputProgram +from languages.asp.asp_mapper import ASPMapper + +class ASPInputProgram(InputProgram): + """A generic ASP program, with the capabilities of retrieve data by objects""" + + def __init__(self): + super(ASPInputProgram, self).__init__() + + + def add_object_input(self, inputObj): + """Transforms a given Object class into a InputProgram and adds it to the current _programs + The parameter inputObj is an object to be transformed + """ + self.add_program(ASPMapper.get_instance().get_string(inputObj) + ".") + + + def add_objects_input(self, inputObjs): + """Transforms a set of objects""" + for inputObj in inputObjs: + self.add_object_input(inputObj) \ No newline at end of file diff --git a/Python version/languages/asp/ASPMapper.py b/Python version/languages/asp/asp_mapper.py similarity index 75% rename from Python version/languages/asp/ASPMapper.py rename to Python version/languages/asp/asp_mapper.py index d1547bd..e5be670 100644 --- a/Python version/languages/asp/ASPMapper.py +++ b/Python version/languages/asp/asp_mapper.py @@ -1,49 +1,49 @@ -from languages.Mapper import Mapper -class ASPMapper(Mapper): - """Contains methods used to transform Objects into InputProgram""" - - __Instance = None - - def __init__(self): - if ASPMapper.__Instance: - raise("Instance already exists") - super(ASPMapper, self).__init__() - - @classmethod - def getInstance(cls): - """Return the instance of ASPMapper""" - if not cls.__Instance: - cls.__Instance = ASPMapper() - return cls.__Instance - - def _getActualString(self, predicate, parametersMap): - """Return a string representing atom, from given predicate string name, and set of parameters""" - atom = predicate + "(" - for i in range(0,len(parametersMap)): - if (i != 0): - atom += "," - objectTerm = parametersMap[i] - if (objectTerm == None): - raise("Wrong term number of predicate " + predicate) - if (isinstance(objectTerm, int)): - atom += str(objectTerm) - else: - atom += "\"" + str(objectTerm) + "\"" - atom += ")" - return atom - - def _getParameters(self, string): - """Return a set of parameter string name""" - return string[string.index("(")+1:string.index(")")].split(",") - - def _getPredicate(self, string): - """Return a string representing a predicate""" - if "(" not in string: - return string; - return string[:string.index("(")] - - - - - +from languages.mapper import Mapper +class ASPMapper(Mapper): + """Contains methods used to transform Objects into InputProgram""" + + __instance = None + + def __init__(self): + if ASPMapper.__instance: + raise("Instance already exists") + super(ASPMapper, self).__init__() + + @classmethod + def get_instance(cls): + """Return the instance of ASPMapper""" + if not cls.__instance: + cls.__instance = ASPMapper() + return cls.__instance + + def _get_actual_string(self, predicate, parametersMap): + """Return a string representing atom, from given predicate string name, and set of parameters""" + atom = predicate + "(" + for i in range(0,len(parametersMap)): + if (i != 0): + atom += "," + objectTerm = parametersMap[i] + if (objectTerm == None): + raise("Wrong term number of predicate " + predicate) + if (isinstance(objectTerm, int)): + atom += str(objectTerm) + else: + atom += "\"" + str(objectTerm) + "\"" + atom += ")" + return atom + + def _get_parameters(self, string): + """Return a set of parameter string name""" + return string[string.index("(")+1:string.index(")")].split(",") + + def _get_predicate(self, string): + """Return a string representing a predicate""" + if "(" not in string: + return string; + return string[:string.index("(")] + + + + + \ No newline at end of file diff --git a/Python version/languages/Mapper.py b/Python version/languages/mapper.py similarity index 53% rename from Python version/languages/Mapper.py rename to Python version/languages/mapper.py index 9242dbd..5b248da 100644 --- a/Python version/languages/Mapper.py +++ b/Python version/languages/mapper.py @@ -1,88 +1,88 @@ -from abc import ABCMeta, abstractmethod -from languages.Predicate import Predicate - -class Mapper(object): - """Base class, contains methods used to transform Objects into InputProgram""" - __metaclass__ = ABCMeta - - def __init__(self): - self._predicateClass = dict() # Represents a dict, where are stored a string name of a predicate as a key, and a corresponding Class element - - @abstractmethod - def _getActualString(self, predicate, parametersMap): - pass - @abstractmethod - def _getPredicate(self, string): - pass - @abstractmethod - def _getParameters(self, string): - pass - - def getClass(self, predicate): - """Returns a string for the given predicate name string""" - return self._predicateClass.get(predicate) - - def __populateObject(self, cl, parameters, obj): - """Sets a fields of object from set of parameters given, by invoking setters methods of object""" - for key, value in obj.getTermsType().items(): - if isinstance(value, tuple) and len(value) == 2: - nameMethod = "set" + value[0][:1].upper() + value[0][1:] - getattr(obj, nameMethod)(int(parameters[key])) - else: - nameMethod = "set" + value[:1].upper() + value[1:] - getattr(obj, nameMethod)(parameters[key]) - - - def getObject(self, string): - """Returns an Object for the given string - The parameter string is a string from witch data are extrapolated - The method return a Object for the given string data - """ - predicate = self._getPredicate(string) - if (predicate == None): - return None - cl = self.getClass(predicate) - if(cl == None): - return None - parameters = self._getParameters(string) - if(parameters == None): - return None - obj = cl() - self.__populateObject(cl, parameters, obj) - return obj - - def registerClass(self, cl): - """Insert an object into _predicateClass - The method return a string representing pairing key of _predicateClass - """ - if (not issubclass(cl,Predicate)): - raise("input class is not subclass of Predicate") - predicate = cl.getPredicateName() - if (" " in predicate): - raise("Value of the object is not valid") - self._predicateClass[predicate] = cl - return predicate - - def unregisterClass(self, cl): - """Remove an object from _predicateClass""" - if(not issubclass(cl, Predicate)): - raise("input class is not subclass of Predicate") - predicate = cl.getPredicateName() - del self._predicateClass[predicate] - - - def getString(self, obj): - """Returns data for the given Object - The parameter obj is the Object from witch data are extrapolated - The method return a string data for the given Object in a String format - """ - predicate = self.registerClass(obj.__class__) - parametersMap = dict() - for key, value in obj.getTermsType().items(): - if isinstance(value, tuple) and len(value) == 2: - val = getattr(obj, "get" + value[0][:1].upper() + value[0][1:])() - else: - val = getattr(obj, "get" + value[:1].upper() + value[1:])() - parametersMap[key] = val - return self._getActualString(predicate, parametersMap) +from abc import ABCMeta, abstractmethod +from languages.predicate import Predicate + +class Mapper(object): + """Base class, contains methods used to transform Objects into InputProgram""" + __metaclass__ = ABCMeta + + def __init__(self): + self._predicate_class = dict() # Represents a dict, where are stored a string name of a predicate as a key, and a corresponding Class element + + @abstractmethod + def _get_actual_string(self, predicate, parametersMap): + pass + @abstractmethod + def _get_predicate(self, string): + pass + @abstractmethod + def _get_parameters(self, string): + pass + + def get_class(self, predicate): + """Returns a string for the given predicate name string""" + return self._predicate_class.get(predicate) + + def __populate_object(self, cl, parameters, obj): + """Sets a fields of object from set of parameters given, by invoking setters methods of object""" + for key, value in obj.get_terms_type().items(): + if isinstance(value, tuple) and len(value) == 2: + nameMethod = "set_" + value[0] + getattr(obj, nameMethod)(int(parameters[key])) + else: + nameMethod = "set_" + value + getattr(obj, nameMethod)(parameters[key]) + + + def get_object(self, string): + """Returns an Object for the given string + The parameter string is a string from witch data are extrapolated + The method return a Object for the given string data + """ + predicate = self._get_predicate(string) + if (predicate == None): + return None + cl = self.get_class(predicate) + if(cl == None): + return None + parameters = self._get_parameters(string) + if(parameters == None): + return None + obj = cl() + self.__populate_object(cl, parameters, obj) + return obj + + def register_class(self, cl): + """Insert an object into _predicate_class + The method return a string representing pairing key of _predicate_class + """ + if (not issubclass(cl,Predicate)): + raise("input class is not subclass of Predicate") + predicate = cl.get_predicate_name() + if (" " in predicate): + raise("Value of the object is not valid") + self._predicate_class[predicate] = cl + return predicate + + def unregister_class(self, cl): + """Remove an object from _predicate_class""" + if(not issubclass(cl, Predicate)): + raise("input class is not subclass of Predicate") + predicate = cl.get_predicate_name() + del self._predicate_class[predicate] + + + def get_string(self, obj): + """Returns data for the given Object + The parameter obj is the Object from witch data are extrapolated + The method return a string data for the given Object in a String format + """ + predicate = self.register_class(obj.__class__) + parametersMap = dict() + for key, value in obj.get_terms_type().items(): + if isinstance(value, tuple) and len(value) == 2: + val = getattr(obj, "get_" + value[0])() + else: + val = getattr(obj, "get_" + value)() + parametersMap[key] = val + return self._get_actual_string(predicate, parametersMap) \ No newline at end of file diff --git a/Python version/languages/pddl/Plan.py b/Python version/languages/pddl/Plan.py deleted file mode 100644 index 011d5ab..0000000 --- a/Python version/languages/pddl/Plan.py +++ /dev/null @@ -1,31 +0,0 @@ -from base.Output import Output -from languages.pddl.PDDLMapper import PDDLMapper -from abc import ABCMeta - -class Plan(Output): - """A simplified solution to a PDDL problem""" - - __metaclass__ = ABCMeta - - def __init__(self, plan, error): - super(Plan, self).__init__(plan, error) - self._actionSequence = None - self.__actionsObjects = None - - def getActions(self): - """Return a set of Actions""" - if self._actionSequence == None: - self._actionSequence = list() - self._parse() - return self._actionSequence - - def getActionsObjects(self): - """Return a set of Objects represents Actions""" - if self.__actionsObjects == None: - self.__actionsObjects = list() - mapper = PDDLMapper.getInstance() - for a in self.getActions(): - obj = mapper.getObject(a.getName()) - if obj != None: - self.__actionsObjects.append(obj) - return self.__actionsObjects \ No newline at end of file diff --git a/Python version/languages/pddl/Action.py b/Python version/languages/pddl/action.py similarity index 80% rename from Python version/languages/pddl/Action.py rename to Python version/languages/pddl/action.py index 8633ea3..1cc856d 100644 --- a/Python version/languages/pddl/Action.py +++ b/Python version/languages/pddl/action.py @@ -1,12 +1,12 @@ -class Action(object): - """Represent a generic Action""" - def __init__(self, name): - self.__name = name - - def getName(self): - """Return the name of Action""" - return self.__name - - def setName(self, name): - """Sets the name of Action""" +class Action(object): + """Represent a generic Action""" + def __init__(self, name): + self.__name = name + + def get_name(self): + """Return the name of Action""" + return self.__name + + def set_name(self, name): + """Sets the name of Action""" self.name = name \ No newline at end of file diff --git a/Python version/languages/pddl/PDDLException.py b/Python version/languages/pddl/pddl_exception.py similarity index 97% rename from Python version/languages/pddl/PDDLException.py rename to Python version/languages/pddl/pddl_exception.py index c6ea8d2..6887049 100644 --- a/Python version/languages/pddl/PDDLException.py +++ b/Python version/languages/pddl/pddl_exception.py @@ -1,5 +1,5 @@ -class PDDLException(Exception): - """Represent a PDDL Exception""" - - def __init__(self, arg): +class PDDLException(Exception): + """Represent a PDDL Exception""" + + def __init__(self, arg): super(PDDLException, self).__init__(arg) \ No newline at end of file diff --git a/Python version/languages/pddl/PDDLInputProgram.py b/Python version/languages/pddl/pddl_input_program.py similarity index 51% rename from Python version/languages/pddl/PDDLInputProgram.py rename to Python version/languages/pddl/pddl_input_program.py index c523f14..02aa771 100644 --- a/Python version/languages/pddl/PDDLInputProgram.py +++ b/Python version/languages/pddl/pddl_input_program.py @@ -1,12 +1,12 @@ -from base.InputProgram import InputProgram - -class PDDLInputProgram(InputProgram): - """A generic PDDL program""" - - def __init__(self, progType): - super(PDDLInputProgram, self).__init__() - self.__programsType = progType # Where type of program are stored - - def getProgramsType(self): - """Return type of program""" - return self.__programsType \ No newline at end of file +from base.input_program import InputProgram + +class PDDLInputProgram(InputProgram): + """A generic PDDL program""" + + def __init__(self, progType): + super(PDDLInputProgram, self).__init__() + self.__programs_type = progType # Where type of program are stored + + def get_programs_type(self): + """Return type of program""" + return self.__programs_type \ No newline at end of file diff --git a/Python version/languages/pddl/PDDLMapper.py b/Python version/languages/pddl/pddl_mapper.py similarity index 62% rename from Python version/languages/pddl/PDDLMapper.py rename to Python version/languages/pddl/pddl_mapper.py index e7aec32..d012323 100644 --- a/Python version/languages/pddl/PDDLMapper.py +++ b/Python version/languages/pddl/pddl_mapper.py @@ -1,30 +1,30 @@ -from languages.Mapper import Mapper -class PDDLMapper(Mapper): - """Contains methods used to transform Objects into InputProgram""" - __Instance = None - - def __init__(self): - if PDDLMapper.__Instance: - raise("Instance already exists") - super(PDDLMapper, self).__init__() - - @classmethod - def getInstance(cls): - """Return the instance of PDDLMapper""" - if not cls.__Instance: - cls.__Instance = PDDLMapper() - return cls.__Instance - - def _getActualString(self, predicate, parametersMap): - return None - - def _getParameters(self, string): - """Return a set of parameter string name""" - return string[string.index(" ") + 1:string.rfind(")")].split(" ") - - def _getPredicate(self, string): - """Return a string representing a predicate""" - initialB = string.index("(") - if initialB != 0: - raise ("Wrong format") - return string[1:string.index(" ")] +from languages.mapper import Mapper +class PDDLMapper(Mapper): + """Contains methods used to transform Objects into InputProgram""" + __instance = None + + def __init__(self): + if PDDLMapper.__instance: + raise("Instance already exists") + super(PDDLMapper, self).__init__() + + @classmethod + def get_instance(cls): + """Return the instance of PDDLMapper""" + if not cls.__instance: + cls.__instance = PDDLMapper() + return cls.__instance + + def _get_actual_string(self, predicate, parametersMap): + return None + + def _get_parameters(self, string): + """Return a set of parameter string name""" + return string[string.index(" ") + 1:string.rfind(")")].split(" ") + + def _get_predicate(self, string): + """Return a string representing a predicate""" + initialB = string.index("(") + if initialB != 0: + raise ("Wrong format") + return string[1:string.index(" ")] diff --git a/Python version/languages/pddl/PDDLProgramType.py b/Python version/languages/pddl/pddl_program_type.py similarity index 97% rename from Python version/languages/pddl/PDDLProgramType.py rename to Python version/languages/pddl/pddl_program_type.py index fab717f..5643848 100644 --- a/Python version/languages/pddl/PDDLProgramType.py +++ b/Python version/languages/pddl/pddl_program_type.py @@ -1,4 +1,4 @@ -class PDDLProgramType(object): - """Represent an enumeration class that contains two constant, represents types of PDDL program""" - PROBLEM = 0 - DOMAIN = 1 +class PDDLProgramType(object): + """Represent an enumeration class that contains two constant, represents types of PDDL program""" + PROBLEM = 0 + DOMAIN = 1 diff --git a/Python version/languages/pddl/plan.py b/Python version/languages/pddl/plan.py new file mode 100644 index 0000000..7c71206 --- /dev/null +++ b/Python version/languages/pddl/plan.py @@ -0,0 +1,31 @@ +from base.output import Output +from languages.pddl.pddl_mapper import PDDLMapper +from abc import ABCMeta + +class Plan(Output): + """A simplified solution to a PDDL problem""" + + __metaclass__ = ABCMeta + + def __init__(self, plan, error): + super(Plan, self).__init__(plan, error) + self._action_sequence = None + self.__actions_objects = None + + def get_actions(self): + """Return a set of Actions""" + if self._action_sequence == None: + self._action_sequence = list() + self._parse() + return self._action_sequence + + def get_actions_objects(self): + """Return a set of Objects represents Actions""" + if self.__actions_objects == None: + self.__actions_objects = list() + mapper = PDDLMapper.get_instance() + for a in self.get_actions(): + obj = mapper.get_object(a.get_name()) + if obj != None: + self.__actions_objects.append(obj) + return self.__actions_objects \ No newline at end of file diff --git a/Python version/languages/Predicate.py b/Python version/languages/predicate.py similarity index 57% rename from Python version/languages/Predicate.py rename to Python version/languages/predicate.py index 4e3fafa..b17d5a8 100644 --- a/Python version/languages/Predicate.py +++ b/Python version/languages/predicate.py @@ -1,24 +1,24 @@ -from abc import ABCMeta - -class Predicate(object): - """This class have to be implemented by subclasses want it represent a predicate""" - __metaclass__ = ABCMeta - - def __init__(self, terms): - index = 0 - self.__mapTermsType = dict() # Dict where positional id and set of terms string name and optionally int type are stored - for val in terms: - if isinstance(val, tuple) and len(terms) > 1 and len(val) > 2: - raise Exception("Bad definition of term") - self.__mapTermsType[index] = val - index += 1 - - @classmethod - def getPredicateName(cls): - """Return a string representing the name of a predicate""" - return cls.predicateName - - def getTermsType(self): - """Return a __mapTermsType dict""" - return self.__mapTermsType +from abc import ABCMeta + +class Predicate(object): + """This class have to be implemented by subclasses want it represent a predicate""" + __metaclass__ = ABCMeta + + def __init__(self, terms): + index = 0 + self.__map_terms_type = dict() # Dict where positional id and set of terms string name and optionally int type are stored + for val in terms: + if isinstance(val, tuple) and len(terms) > 1 and len(val) > 2: + raise Exception("Bad definition of term") + self.__map_terms_type[index] = val + index += 1 + + @classmethod + def get_predicate_name(cls): + """Return a string representing the name of a predicate""" + return cls.predicate_name + + def get_terms_type(self): + """Return a __map_terms_type dict""" + return self.__map_terms_type \ No newline at end of file diff --git a/Python version/platforms/desktop/DesktopHandler.py b/Python version/platforms/desktop/desktop_handler.py similarity index 61% rename from Python version/platforms/desktop/DesktopHandler.py rename to Python version/platforms/desktop/desktop_handler.py index b0e91f7..28b5f21 100644 --- a/Python version/platforms/desktop/DesktopHandler.py +++ b/Python version/platforms/desktop/desktop_handler.py @@ -1,26 +1,26 @@ -from base.Handler import Handler - -class DesktopHandler(Handler): - """Is a Handler specialization for a Desktop platform""" - - def __init__(self, service): - super(DesktopHandler, self).__init__() - self.__service = service - - def startAsync(self, c, program_index=None, option_index=None): - """Specialization of superclass startAsync method - Starts ASP solving Asyncronously on a subset of data and options for a Desktop platform - """ - input_programs = self._collect_programs(program_index) - input_options = self._collect_options(option_index) - self.__service.startAsync(c, input_programs, input_options) - - def startSync(self, program_index=None, option_index=None): - """Specialization of superclass startSync method - Starts ASP solving Asyncronously on a subset of data and options for a Desktop platform - """ - input_programs = self._collect_programs(program_index) - input_options = self._collect_options(option_index) - return self.__service.startSync(input_programs, input_options) - +from base.handler import Handler + +class DesktopHandler(Handler): + """Is a Handler specialization for a Desktop platform""" + + def __init__(self, service): + super(DesktopHandler, self).__init__() + self.__service = service + + def start_async(self, c, program_index=None, option_index=None): + """Specialization of superclass start_async method + Starts ASP solving Asyncronously on a subset of data and options for a Desktop platform + """ + input_programs = self._collect_programs(program_index) + input_options = self._collect_options(option_index) + self.__service.start_async(c, input_programs, input_options) + + def start_sync(self, program_index=None, option_index=None): + """Specialization of superclass start_sync method + Starts ASP solving Asyncronously on a subset of data and options for a Desktop platform + """ + input_programs = self._collect_programs(program_index) + input_options = self._collect_options(option_index) + return self.__service.start_sync(input_programs, input_options) + \ No newline at end of file diff --git a/Python version/platforms/desktop/DesktopService.py b/Python version/platforms/desktop/desktop_service.py similarity index 71% rename from Python version/platforms/desktop/DesktopService.py rename to Python version/platforms/desktop/desktop_service.py index 0af23d2..48ba3df 100644 --- a/Python version/platforms/desktop/DesktopService.py +++ b/Python version/platforms/desktop/desktop_service.py @@ -1,92 +1,92 @@ -from base.Service import Service -from abc import abstractmethod -from base.OptionDescriptor import OptionDescriptor -from base.InputProgram import InputProgram -from base.Output import Output -import subprocess -import time -from threading import Thread - -class DesktopService(Service): - """Is a specialization for a Desktop platform""" - - def __init__(self, exe_path): - self._exe_path = exe_path # Stores solver's executable path - _load_from_STDIN_option = None # Stores option string for enable solver to read from standard input - - def getExePath(self): - """Return a execution path of DesktopService""" - return self._exe_path - - @abstractmethod - def _getOutput(self, output, error): - pass - - def setExePath(self, exe_path): - """Set _exe_path to a new path - The parameter exe_path is a string representing the path for the new solver - """ - self._exe_path = exe_path - - def startAsync(self, callback, programs, options): - """Start a new process for the _exe_path and starts solving in Asyncronously way""" - class myThread(Thread): - def __init__(self, startSync): - Thread.__init__(self) - self.startSync = startSync - def run(self): - callback.callback(self.startSync(programs, options)) - - th = myThread(self.startSync) - th.start() - - def startSync(self, programs, options): - """Start a new process for the _exe_path and starts solving in Syncronously way""" - option = "" - for o in options: - if(o != None): - option += o.getOptions() - option += o.getSeparator() - else: - print("Warning : wrong " + str(OptionDescriptor().__class__.__name__)) - files_paths = "" - final_program = "" - for p in programs: - if (p != None): - final_program += p.getPrograms() - program_file = p.getStringOfFilesPaths() - if (program_file != None): - files_paths += program_file - else: - print("Warning : wrong " + str(InputProgram().__class__.__name__)) - - if (self._exe_path == None): - return Output("", "Error: executable not found"); - - exep = str(self._exe_path) - - opt = str(option) - - lis = list() - lis.append(exep) - if opt != "": - lis.append(opt) - lis.append(files_paths[:-1]) - if self._load_from_STDIN_option != "": - lis.append(self._load_from_STDIN_option) - - print(exep + " " + opt + " " + files_paths + self._load_from_STDIN_option) - - start = int(time.time()*1e+9) - - proc = subprocess.Popen(lis, universal_newlines=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, ) - - output, error = proc.communicate(final_program) - - end = int(time.time()*1e+9) - - print("Total time : " + str(end - start)) - print("") - - return self._getOutput(output, error) +from base.service import Service +from abc import abstractmethod +from base.option_descriptor import OptionDescriptor +from base.input_program import InputProgram +from base.output import Output +import subprocess +import time +from threading import Thread + +class DesktopService(Service): + """Is a specialization for a Desktop platform""" + + def __init__(self, exe_path): + self._exe_path = exe_path # Stores solver's executable path + _load_from_STDIN_option = None # Stores option string for enable solver to read from standard input + + def getExePath(self): + """Return a execution path of DesktopService""" + return self._exe_path + + @abstractmethod + def _get_output(self, output, error): + pass + + def setExePath(self, exe_path): + """Set _exe_path to a new path + The parameter exe_path is a string representing the path for the new solver + """ + self._exe_path = exe_path + + def start_async(self, callback, programs, options): + """Start a new process for the _exe_path and starts solving in Asyncronously way""" + class myThread(Thread): + def __init__(self, start_sync): + Thread.__init__(self) + self.start_sync = start_sync + def run(self): + callback.callback(self.start_sync(programs, options)) + + th = myThread(self.start_sync) + th.start() + + def start_sync(self, programs, options): + """Start a new process for the _exe_path and starts solving in Syncronously way""" + option = "" + for o in options: + if(o != None): + option += o.get_options() + option += o.get_separator() + else: + print("Warning : wrong " + str(OptionDescriptor().__class__.__name__)) + files_paths = "" + final_program = "" + for p in programs: + if (p != None): + final_program += p.get_programs() + program_file = p.get_string_of_files_paths() + if (program_file != None): + files_paths += program_file + else: + print("Warning : wrong " + str(InputProgram().__class__.__name__)) + + if (self._exe_path == None): + return Output("", "Error: executable not found"); + + exep = str(self._exe_path) + + opt = str(option) + + lis = list() + lis.append(exep) + if opt != "": + lis.append(opt) + lis.append(files_paths[:-1]) + if self._load_from_stdin_option != "": + lis.append(self._load_from_stdin_option) + + print(exep + " " + opt + " " + files_paths + self._load_from_stdin_option) + + start = int(time.time()*1e+9) + + proc = subprocess.Popen(lis, universal_newlines=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, ) + + output, error = proc.communicate(final_program) + + end = int(time.time()*1e+9) + + print("Total time : " + str(end - start)) + print("") + + return self._get_output(output, error) \ No newline at end of file diff --git a/Python version/specializations/clingo/ClingoAnswerSets.py b/Python version/specializations/clingo/clingo_answer_sets.py similarity index 81% rename from Python version/specializations/clingo/ClingoAnswerSets.py rename to Python version/specializations/clingo/clingo_answer_sets.py index 2798596..3be66f7 100644 --- a/Python version/specializations/clingo/ClingoAnswerSets.py +++ b/Python version/specializations/clingo/clingo_answer_sets.py @@ -1,52 +1,52 @@ -from languages.asp.AnswerSets import AnswerSets -import re -from languages.asp.AnswerSet import AnserSet -import traceback - -class ClingoAnswerSets(AnswerSets): - """Represents Clingo's answersets""" - - def __init__(self, out, err=None): - super(ClingoAnswerSets, self).__init__(out, err) - - def _parse(self): - """Create new AnswerSet object represents output come from solver execution and add this in _answersets field""" - optimum = "OPTIMUM" in self._output - - if not optimum: - match = tuple(re.finditer(r"Answer: (\d+)\r?\n(.*)", self._output)) - else: - match = tuple(re.finditer(r"Answer: (\d+)\r?\n(.*)(\r?\nOptimization: (.+))", self._output)) - - for m in match: - try: - if m.group(1) == None or int(m.group(1)) <= len(self._answersets): - continue - except Exception: - traceback.print_exc() - break - - matcherAnswerSet = tuple(re.finditer(r"-?[a-z][A-Za-z0-9_]*(\(.*?\))?", m.group(2))) - answerSetList = list() - - for ma in matcherAnswerSet: - answerSetList.append(ma.group()) - - - if optimum: - weightMap = dict() - try: - split = m.group(4).split(" ") - level = len(split) - for weight in split: - weightMap[level] = int(weight) - level-=1 - except Exception: - traceback.print_exc() - - self._answersets.append(AnserSet(answerSetList, weightMap)) - - else: - self._answersets.append(AnserSet(answerSetList)) - +from languages.asp.answer_sets import AnswerSets +import re +from languages.asp.answer_set import AnserSet +import traceback + +class ClingoAnswerSets(AnswerSets): + """Represents Clingo's answersets""" + + def __init__(self, out, err=None): + super(ClingoAnswerSets, self).__init__(out, err) + + def _parse(self): + """Create new AnswerSet object represents output come from solver execution and add this in _answer_sets field""" + optimum = "OPTIMUM" in self._output + + if not optimum: + match = tuple(re.finditer(r"Answer: (\d+)\r?\n(.*)", self._output)) + else: + match = tuple(re.finditer(r"Answer: (\d+)\r?\n(.*)(\r?\nOptimization: (.+))", self._output)) + + for m in match: + try: + if m.group(1) == None or int(m.group(1)) <= len(self._answer_sets): + continue + except Exception: + traceback.print_exc() + break + + matcherAnswerSet = tuple(re.finditer(r"-?[a-z][A-Za-z0-9_]*(\(.*?\))?", m.group(2))) + answerSetList = list() + + for ma in matcherAnswerSet: + answerSetList.append(ma.group()) + + + if optimum: + weightMap = dict() + try: + split = m.group(4).split(" ") + level = len(split) + for weight in split: + weightMap[level] = int(weight) + level-=1 + except Exception: + traceback.print_exc() + + self._answer_sets.append(AnserSet(answerSetList, weightMap)) + + else: + self._answer_sets.append(AnserSet(answerSetList)) + \ No newline at end of file diff --git a/Python version/specializations/clingo/desktop/ClingoDesktopService.py b/Python version/specializations/clingo/desktop/ClingoDesktopService.py deleted file mode 100644 index 1993b6f..0000000 --- a/Python version/specializations/clingo/desktop/ClingoDesktopService.py +++ /dev/null @@ -1,21 +0,0 @@ -from platforms.desktop.DesktopService import DesktopService -from specializations.clingo.ClingoAnswerSets import ClingoAnswerSets - -class ClingoDesktopService(DesktopService): - """Is an extention of DesktopService for Clingo's solver""" - - def __init__(self, exe_path): - super(ClingoDesktopService, self).__init__(exe_path) - self._load_from_STDIN_option = "-" - - def _getOutput(self, output, error): - """Return a new ClingoAnwerSets from output and error given""" - return ClingoAnswerSets(output, error) - - def startSync(self, programs, options): - """Call startSync method of a superclass, and return her output object""" - return super(ClingoDesktopService, self).startSync(programs, options) - - def startAsync(self, callback, programs, options): - """Call startAsync method of a superclass""" - super(ClingoDesktopService, self).startAsync(callback, programs, options) \ No newline at end of file diff --git a/Python version/specializations/clingo/desktop/clingo_desktop_service.py b/Python version/specializations/clingo/desktop/clingo_desktop_service.py new file mode 100644 index 0000000..15b747f --- /dev/null +++ b/Python version/specializations/clingo/desktop/clingo_desktop_service.py @@ -0,0 +1,21 @@ +from platforms.desktop.desktop_service import DesktopService +from specializations.clingo.clingo_answer_sets import ClingoAnswerSets + +class ClingoDesktopService(DesktopService): + """Is an extention of DesktopService for Clingo's solver""" + + def __init__(self, exe_path): + super(ClingoDesktopService, self).__init__(exe_path) + self._load_from_stdin_option = "-" + + def _get_output(self, output, error): + """Return a new ClingoAnwerSets from output and error given""" + return ClingoAnswerSets(output, error) + + def start_sync(self, programs, options): + """Call start_sync method of a superclass, and return her output object""" + return super(ClingoDesktopService, self).start_sync(programs, options) + + def start_async(self, callback, programs, options): + """Call start_async method of a superclass""" + super(ClingoDesktopService, self).start_async(callback, programs, options) \ No newline at end of file diff --git a/Python version/specializations/dlv/desktop/DLVDesktopService.py b/Python version/specializations/dlv/desktop/dlv_desktop_service.py similarity index 59% rename from Python version/specializations/dlv/desktop/DLVDesktopService.py rename to Python version/specializations/dlv/desktop/dlv_desktop_service.py index b35e3f1..1175faa 100644 --- a/Python version/specializations/dlv/desktop/DLVDesktopService.py +++ b/Python version/specializations/dlv/desktop/dlv_desktop_service.py @@ -1,13 +1,13 @@ -from platforms.desktop.DesktopService import DesktopService -from specializations.dlv.DLVAnswerSets import DLVAnswerSets - -class DLVDesktopService(DesktopService): - """Is an extention of DesktopService for DLV's solver""" - - def __init__(self, exe_path): - super(DLVDesktopService, self).__init__(exe_path) - self._load_from_STDIN_option = "--" - - def _getOutput(self, output, error): - """Return a new DLVAnwerSets from output and error given""" +from platforms.desktop.desktop_service import DesktopService +from specializations.dlv.dlv_answer_sets import DLVAnswerSets + +class DLVDesktopService(DesktopService): + """Is an extention of DesktopService for DLV's solver""" + + def __init__(self, exe_path): + super(DLVDesktopService, self).__init__(exe_path) + self._load_from_stdin_option = "--" + + def _get_output(self, output, error): + """Return a new DLVAnwerSets from output and error given""" return DLVAnswerSets(output, error) \ No newline at end of file diff --git a/Python version/specializations/dlv/DLVAnswerSets.py b/Python version/specializations/dlv/dlv_answer_sets.py similarity index 73% rename from Python version/specializations/dlv/DLVAnswerSets.py rename to Python version/specializations/dlv/dlv_answer_sets.py index 4ad67ea..e8adef8 100644 --- a/Python version/specializations/dlv/DLVAnswerSets.py +++ b/Python version/specializations/dlv/dlv_answer_sets.py @@ -1,20 +1,20 @@ -from languages.asp.AnswerSets import AnswerSets -from languages.asp.AnswerSet import AnserSet -import re - -class DLVAnswerSets(AnswerSets): - """Represent an AnswerSet specific for DLV""" - - def __init__(self, out, err=None): - super(DLVAnswerSets, self).__init__(out, err) - - def _parse(self): - """Create new AnswerSet object represents output come from solver execution and add this in _answersets field""" - match = tuple(re.finditer(r"\{(.*)\}", self._output)) - for m in match: - answerSet = m.group() - answerSetList = set() - matcherAnswerSet = tuple(re.finditer(r"(-?[a-z][A-Za-z0-9_]*(\(.+?\))?)(, |\})", answerSet)) - for ma in matcherAnswerSet: - answerSetList.add(ma.group(1)) - self._answersets.append(AnserSet(answerSetList)) +from languages.asp.answer_sets import AnswerSets +from languages.asp.answer_set import AnserSet +import re + +class DLVAnswerSets(AnswerSets): + """Represent an AnswerSet specific for DLV""" + + def __init__(self, out, err=None): + super(DLVAnswerSets, self).__init__(out, err) + + def _parse(self): + """Create new AnswerSet object represents output come from solver execution and add this in _answer_sets field""" + match = tuple(re.finditer(r"\{(.*)\}", self._output)) + for m in match: + answerSet = m.group() + answerSetList = set() + matcherAnswerSet = tuple(re.finditer(r"(-?[a-z][A-Za-z0-9_]*(\(.+?\))?)(, |\})", answerSet)) + for ma in matcherAnswerSet: + answerSetList.add(ma.group(1)) + self._answer_sets.append(AnserSet(answerSetList)) diff --git a/Python version/specializations/dlv/DLVFilterOption.py b/Python version/specializations/dlv/dlv_filter_option.py similarity index 80% rename from Python version/specializations/dlv/DLVFilterOption.py rename to Python version/specializations/dlv/dlv_filter_option.py index ecb141a..0b00411 100644 --- a/Python version/specializations/dlv/DLVFilterOption.py +++ b/Python version/specializations/dlv/dlv_filter_option.py @@ -1,6 +1,6 @@ -from languages.asp.ASPFilterOption import ASPFilterOption - -class DLVFilterOption(ASPFilterOption): - """Represent a filter option that's possible to add on a call of DLV execution, for filtering output generated by the solver""" - def __init__(self, initial_option): +from languages.asp.asp_filter_option import ASPFilterOption + +class DLVFilterOption(ASPFilterOption): + """Represent a filter option that's possible to add on a call of DLV execution, for filtering output generated by the solver""" + def __init__(self, initial_option): self._options += initial_option \ No newline at end of file diff --git a/Python version/specializations/dlv2/desktop/DLV2DesktopService.py b/Python version/specializations/dlv2/desktop/DLV2DesktopService.py deleted file mode 100644 index a50d33c..0000000 --- a/Python version/specializations/dlv2/desktop/DLV2DesktopService.py +++ /dev/null @@ -1,24 +0,0 @@ -from platforms.desktop.DesktopService import DesktopService -from base.OptionDescriptor import OptionDescriptor -from specializations.dlv2.DLV2AnswerSets import DLV2AnswerSets - -class DLV2DesktopService(DesktopService): - """Is an extention of DesktopService for DLV2's solver""" - - def __init__(self, exe_path): - super(DLV2DesktopService, self).__init__(exe_path) - self._load_from_STDIN_option = "--" - self.competitionOutputOption = OptionDescriptor("--competition-output") - - def _getOutput(self, output, error): - """Return a new DLV2AnwerSets from output and error given""" - return DLV2AnswerSets(output, error) - - def startAsync(self, callback, programs, options): - """Call startAsync method of a superclass""" - super(DLV2DesktopService, self).startAsync(callback, programs, options) - - def startSync(self, programs, options): - """Call startSync method of a superclass, and return her output object""" - options.append(self.competitionOutputOption) - return super(DLV2DesktopService, self).startSync(programs, options) \ No newline at end of file diff --git a/Python version/specializations/dlv2/desktop/dlv2_desktop_service.py b/Python version/specializations/dlv2/desktop/dlv2_desktop_service.py new file mode 100644 index 0000000..6c82b5d --- /dev/null +++ b/Python version/specializations/dlv2/desktop/dlv2_desktop_service.py @@ -0,0 +1,24 @@ +from platforms.desktop.desktop_service import DesktopService +from base.option_descriptor import OptionDescriptor +from specializations.dlv2.dlv2_answer_sets import DLV2AnswerSets + +class DLV2DesktopService(DesktopService): + """Is an extention of DesktopService for DLV2's solver""" + + def __init__(self, exe_path): + super(DLV2DesktopService, self).__init__(exe_path) + self._load_from_stdin_option = "--" + self.competition_output_option = OptionDescriptor("--competition-output") + + def _get_output(self, output, error): + """Return a new DLV2AnwerSets from output and error given""" + return DLV2AnswerSets(output, error) + + def start_async(self, callback, programs, options): + """Call start_async method of a superclass""" + super(DLV2DesktopService, self).start_async(callback, programs, options) + + def start_sync(self, programs, options): + """Call start_sync method of a superclass, and return her output object""" + options.append(self.competition_output_option) + return super(DLV2DesktopService, self).start_sync(programs, options) \ No newline at end of file diff --git a/Python version/specializations/dlv2/DLV2AnswerSets.py b/Python version/specializations/dlv2/dlv2_answer_sets.py similarity index 79% rename from Python version/specializations/dlv2/DLV2AnswerSets.py rename to Python version/specializations/dlv2/dlv2_answer_sets.py index 668cb2a..ebe10b7 100644 --- a/Python version/specializations/dlv2/DLV2AnswerSets.py +++ b/Python version/specializations/dlv2/dlv2_answer_sets.py @@ -1,43 +1,43 @@ -from languages.asp.AnswerSets import AnswerSets -import re -from languages.asp.AnswerSet import AnserSet -import traceback - -class DLV2AnswerSets(AnswerSets): - """Represents Dlv2's answersets""" - - def __init__(self, out, err=None): - super(DLV2AnswerSets, self).__init__(out, err) - - def _parse(self): - """Create new AnswerSet object represents output come from solver execution and add this in _answersets field""" - optimum = "OPTIMUM" in self._output - - if not optimum: - match = tuple(re.finditer(r"ANSWER\r?\n(.*)", self._output)) - else: - match = tuple(re.finditer(r"ANSWER\r?\n(.*)(\r?\nCOST (.+)\r?\nOPTIMUM)", self._output)) - - for m in match: - matcherAnswerSet = tuple(re.finditer(r"-?[a-z][A-Za-z0-9_]*(\(.*?\))?", m.group(1))) - answerSetList = list() - - for ma in matcherAnswerSet: - answerSetList.append(ma.group()) - - if optimum: - weightMap = dict() - try: - split = m.group(3).split(" ") - for weightLevel in split: - weightLevelArray = weightLevel.split("@") - weightMap[weightLevelArray[1]] = weightLevelArray[0] - except Exception: - traceback.print_exc() - - self._answersets.append(AnserSet(answerSetList, weightMap)) - - else: - self._answersets.append(AnserSet(answerSetList)) - +from languages.asp.answer_sets import AnswerSets +import re +from languages.asp.answer_set import AnserSet +import traceback + +class DLV2AnswerSets(AnswerSets): + """Represents Dlv2's answersets""" + + def __init__(self, out, err=None): + super(DLV2AnswerSets, self).__init__(out, err) + + def _parse(self): + """Create new AnswerSet object represents output come from solver execution and add this in _answer_sets field""" + optimum = "OPTIMUM" in self._output + + if not optimum: + match = tuple(re.finditer(r"ANSWER\r?\n(.*)", self._output)) + else: + match = tuple(re.finditer(r"ANSWER\r?\n(.*)(\r?\nCOST (.+)\r?\nOPTIMUM)", self._output)) + + for m in match: + matcherAnswerSet = tuple(re.finditer(r"-?[a-z][A-Za-z0-9_]*(\(.*?\))?", m.group(1))) + answerSetList = list() + + for ma in matcherAnswerSet: + answerSetList.append(ma.group()) + + if optimum: + weightMap = dict() + try: + split = m.group(3).split(" ") + for weightLevel in split: + weightLevelArray = weightLevel.split("@") + weightMap[weightLevelArray[1]] = weightLevelArray[0] + except Exception: + traceback.print_exc() + + self._answer_sets.append(AnserSet(answerSetList, weightMap)) + + else: + self._answer_sets.append(AnserSet(answerSetList)) + \ No newline at end of file diff --git a/Python version/specializations/solver_planning_domains/desktop/SPDDesktopService.py b/Python version/specializations/solver_planning_domains/desktop/spd_desktop_service.py similarity index 63% rename from Python version/specializations/solver_planning_domains/desktop/SPDDesktopService.py rename to Python version/specializations/solver_planning_domains/desktop/spd_desktop_service.py index 1601ad0..57d6d2c 100644 --- a/Python version/specializations/solver_planning_domains/desktop/SPDDesktopService.py +++ b/Python version/specializations/solver_planning_domains/desktop/spd_desktop_service.py @@ -1,115 +1,115 @@ -from platforms.desktop.DesktopService import DesktopService -from languages.pddl.PDDLInputProgram import PDDLInputProgram -import json -import traceback -import sys -from languages.pddl.PDDLProgramType import PDDLProgramType -from specializations.solver_planning_domains.SPDPlan import SPDPlan -from languages.pddl.PDDLException import PDDLException - -class SPDDesktopService(DesktopService): - """Is an extention of DesktopService for SPDD's solver""" - - def __init__(self): - super(SPDDesktopService, self).__init__("") - self.__solverUrlResourceName = "solver.planning.domains" - self.__solverUrlPath = "/solve" - - def __createJson(self, pddlInputProgram): - """Return a json object represents InputProgram""" - problem = "" - domain = "" - - for ip in pddlInputProgram: - if not isinstance(ip, PDDLInputProgram): - continue - pip = ip - pType = pip.getProgramsType() - - if pType is PDDLProgramType.DOMAIN: - domain += str(pip.getPrograms()) + str(pip.getSeparator()) - domain += self.__getFromFile(pip.getFilesPaths(), pip.getSeparator()) - elif pType is PDDLProgramType.PROBLEM: - problem += str(pip.getPrograms()) + str(pip.getSeparator()) - problem += self.__getFromFile(pip.getFilesPaths(), pip.getSeparator()) - else: - raise ("Program type : " + pip.getProgramsType() + " not valid.") - - if problem == "": - raise ("Problem file not specified") - if domain == "": - raise("Domain file not specified") - - data = {} - data["problem"] = problem - data["domain"] = domain - - json_data = json.dumps(data) - - return json_data - - - def __getFromFile(self, filesPaths, separator): - """Read file from list of path given and return their content, separate by separator string given""" - toReturn = "" - for s in filesPaths: - try: - toReturn += self.__readFile(s) - toReturn += separator - except IOError: - traceback.print_exc() - return toReturn - - - def __postJsonToURL(self, js): - """Post a json string given to SPD solver server and return result""" - result = "" - try: - if sys.version_info < (3,0): - import httplib - connection = httplib.HTTPConnection(self.__solverUrlResourceName) - else: - import http.client - connection = http.client.HTTPConnection(self.__solverUrlResourceName) - - headers = {'Content-type': 'application/json'} - - connection.request('POST', self.__solverUrlPath, js, headers) - - response = connection.getresponse() - - if response.status == 200: - result = response.read().decode() - else: - raise PDDLException("HTTP connection error, response code : " + str(response.status) + " response message : " + str(response.reason)) - except: - raise PDDLException("Impossible to perform HTTP connection") - finally: - connection.close() - return result - - def __readFile(self, s): - """Reand file from path given and return her content""" - everything = "" - with open(s, 'r') as f: - try: - everything = f.read() - finally: - f.close() - return everything - - def _getOutput(self, output, error): - """Return SPDPlan object from output and error strings given""" - return SPDPlan(output, error) - - def startSync(self, programs, options): - """Return SPDPlan object represent output generated from SPD solver server""" - if not programs: - return self._getOutput("", "PDDLInputProgram not defined") - try: - return self._getOutput(self.__postJsonToURL(str(self.__createJson(programs))), "") - except Exception as e: - return self._getOutput("", "Error: " + str(e)) - - - +from platforms.desktop.desktop_service import DesktopService +from languages.pddl.pddl_input_program import PDDLInputProgram +import json +import traceback +import sys +from languages.pddl.pddl_program_type import PDDLProgramType +from specializations.solver_planning_domains.spd_plan import SPDPlan +from languages.pddl.pddl_exception import PDDLException + +class SPDDesktopService(DesktopService): + """Is an extention of DesktopService for SPDD's solver""" + + def __init__(self): + super(SPDDesktopService, self).__init__("") + self.__solver_url_resource_name = "solver.planning.domains" + self.__solver_url_path = "/solve" + + def __create_json(self, pddlInputProgram): + """Return a json object represents InputProgram""" + problem = "" + domain = "" + + for ip in pddlInputProgram: + if not isinstance(ip, PDDLInputProgram): + continue + pip = ip + pType = pip.get_programs_type() + + if pType is PDDLProgramType.DOMAIN: + domain += str(pip.get_programs()) + str(pip.get_separator()) + domain += self.__get_from_file(pip.get_files_paths(), pip.get_separator()) + elif pType is PDDLProgramType.PROBLEM: + problem += str(pip.get_programs()) + str(pip.get_separator()) + problem += self.__get_from_file(pip.get_files_paths(), pip.get_separator()) + else: + raise ("Program type : " + pip.get_programs_type() + " not valid.") + + if problem == "": + raise ("Problem file not specified") + if domain == "": + raise("Domain file not specified") + + data = {} + data["problem"] = problem + data["domain"] = domain + + json_data = json.dumps(data) + + return json_data + + + def __get_from_file(self, filesPaths, separator): + """Read file from list of path given and return their content, separate by separator string given""" + toReturn = "" + for s in filesPaths: + try: + toReturn += self.__read_file(s) + toReturn += separator + except IOError: + traceback.print_exc() + return toReturn + + + def __post_json_to_url(self, js): + """Post a json string given to SPD solver server and return result""" + result = "" + try: + if sys.version_info < (3,0): + import httplib + connection = httplib.HTTPConnection(self.__solver_url_resource_name) + else: + import http.client + connection = http.client.HTTPConnection(self.__solver_url_resource_name) + + headers = {'Content-type': 'application/json'} + + connection.request('POST', self.__solver_url_path, js, headers) + + response = connection.getresponse() + + if response.status == 200: + result = response.read().decode() + else: + raise PDDLException("HTTP connection error, response code : " + str(response.status) + " response message : " + str(response.reason)) + except: + raise PDDLException("Impossible to perform HTTP connection") + finally: + connection.close() + return result + + def __read_file(self, s): + """Reand file from path given and return her content""" + everything = "" + with open(s, 'r') as f: + try: + everything = f.read() + finally: + f.close() + return everything + + def _get_output(self, output, error): + """Return SPDPlan object from output and error strings given""" + return SPDPlan(output, error) + + def start_sync(self, programs, options): + """Return SPDPlan object represent output generated from SPD solver server""" + if not programs: + return self._get_output("", "PDDLInputProgram not defined") + try: + return self._get_output(self.__post_json_to_url(str(self.__create_json(programs))), "") + except Exception as e: + return self._get_output("", "Error: " + str(e)) + + + diff --git a/Python version/specializations/solver_planning_domains/SPDPlan.py b/Python version/specializations/solver_planning_domains/spd_plan.py similarity index 77% rename from Python version/specializations/solver_planning_domains/SPDPlan.py rename to Python version/specializations/solver_planning_domains/spd_plan.py index dc2471f..5ad0b14 100644 --- a/Python version/specializations/solver_planning_domains/SPDPlan.py +++ b/Python version/specializations/solver_planning_domains/spd_plan.py @@ -1,27 +1,27 @@ -from languages.pddl.Plan import Plan -import json -from languages.pddl.Action import Action - -class SPDPlan(Plan): - """Represent a solution to a SPD problem""" - - def __init__(self, plan, error): - super(SPDPlan, self).__init__(plan, error) - - def _parse(self): - """Create new Action objects represents output given in a json forms and add this in _actionSequence field""" - if self._errors != "" or self._output=="": - return - try: - parsed_json = json.loads(self._output) - status = parsed_json["status"] - if "ok" in status: - arrayPlan = parsed_json["result"]["plan"] - for x in arrayPlan: - self._actionSequence.append(Action(x["name"])) - else: - self._errors += " " + str(parsed_json["result"]) - - except ValueError as e: - self._errors += "ParseException: " + e - +from languages.pddl.plan import Plan +import json +from languages.pddl.action import Action + +class SPDPlan(Plan): + """Represent a solution to a SPD problem""" + + def __init__(self, plan, error): + super(SPDPlan, self).__init__(plan, error) + + def _parse(self): + """Create new Action objects represents output given in a json forms and add this in _action_sequence field""" + if self._errors != "" or self._output=="": + return + try: + parsed_json = json.loads(self._output) + status = parsed_json["status"] + if "ok" in status: + arrayPlan = parsed_json["result"]["plan"] + for x in arrayPlan: + self._action_sequence.append(Action(x["name"])) + else: + self._errors += " " + str(parsed_json["result"]) + + except ValueError as e: + self._errors += "ParseException: " + e + diff --git a/Python version/test/language/asp/ASPMapperTest.py b/Python version/test/language/asp/ASPMapperTest.py deleted file mode 100644 index e878c8b..0000000 --- a/Python version/test/language/asp/ASPMapperTest.py +++ /dev/null @@ -1,39 +0,0 @@ -import unittest -from languages.asp.ASPMapper import ASPMapper -from test.specialization.dlv.Cell import Cell - - - -class ASPMapperTest(unittest.TestCase): - - def test(self): - - instance = ASPMapper.getInstance() - - try: - instance.registerClass(Cell) - - obj = instance.getObject("cell(1,2,5)") - - self.assertTrue(isinstance(obj, Cell)) - - self.assertEqual(1, obj.getRow()) - - self.assertEqual(2, obj.getColumn()) - - self.assertEqual(5, obj.getValue()) - - self.assertEqual("cell(1,2,5)", instance.getString(obj)) - - instance.unregisterClass(Cell) - - noneObject = instance.getObject("cell(1,2,5)") - - self.assertIsNone(noneObject) - - except Exception as e: - self.fail(str(e)) - - -if __name__ == '__main__': - unittest.main() \ No newline at end of file diff --git a/Python version/test/language/asp/asp_mapper_test.py b/Python version/test/language/asp/asp_mapper_test.py new file mode 100644 index 0000000..31d0387 --- /dev/null +++ b/Python version/test/language/asp/asp_mapper_test.py @@ -0,0 +1,39 @@ +import unittest +from languages.asp.asp_mapper import ASPMapper +from cell import Cell + + + +class ASPMapperTest(unittest.TestCase): + + def test(self): + + instance = ASPMapper.get_instance() + + try: + instance.register_class(Cell) + + obj = instance.get_object("cell(1,2,5)") + + self.assertTrue(isinstance(obj, Cell)) + + self.assertEqual(1, obj.get_row()) + + self.assertEqual(2, obj.get_column()) + + self.assertEqual(5, obj.get_value()) + + self.assertEqual("cell(1,2,5)", instance.get_string(obj)) + + instance.unregister_class(Cell) + + noneObject = instance.get_object("cell(1,2,5)") + + self.assertIsNone(noneObject) + + except Exception as e: + self.fail(str(e)) + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/Python version/test/specialization/dlv/Cell.py b/Python version/test/language/asp/cell.py similarity index 62% rename from Python version/test/specialization/dlv/Cell.py rename to Python version/test/language/asp/cell.py index f05d29a..16aeebd 100644 --- a/Python version/test/specialization/dlv/Cell.py +++ b/Python version/test/language/asp/cell.py @@ -1,24 +1,24 @@ -from languages.Predicate import Predicate - -class Cell(Predicate): - - predicateName="cell" - - def __init__(self, row=None, column=None, value=None): - super(Cell, self).__init__([("row", int), ("column", int), ("value", int)]) - self.row = row - self.value = value - self.column = column - - def getRow(self): - return self.row - def getColumn(self): - return self.column - def getValue(self): - return self.value - def setRow(self, row): - self.row = row - def setColumn(self, column): - self.column = column - def setValue(self, value): +from languages.predicate import Predicate + +class Cell(Predicate): + + predicate_name="cell" + + def __init__(self, row=None, column=None, value=None): + super(Cell, self).__init__([("row", int), ("column", int), ("value", int)]) + self.row = row + self.value = value + self.column = column + + def get_row(self): + return self.row + def get_column(self): + return self.column + def get_value(self): + return self.value + def set_row(self, row): + self.row = row + def set_column(self, column): + self.column = column + def set_value(self, value): self.value = value \ No newline at end of file diff --git a/Python version/test/language/pddl/PDDLMapperTest.py b/Python version/test/language/pddl/PDDLMapperTest.py deleted file mode 100644 index b542764..0000000 --- a/Python version/test/language/pddl/PDDLMapperTest.py +++ /dev/null @@ -1,26 +0,0 @@ -import unittest -from languages.pddl.PDDLMapper import PDDLMapper -from test.specialization.solver_planning_domains.PickUp import PickUp - - -class PDDLMapperTest(unittest.TestCase): - - def test(self): - - instance = PDDLMapper.getInstance() - - try: - instance.registerClass(PickUp) - - obj = instance.getObject("(pick-up b)") - - self.assertTrue(isinstance(obj, PickUp)) - - self.assertEqual("b", obj.getBlock()) - - except Exception as e: - self.fail(str(e)) - - -if __name__ == '__main__': - unittest.main() \ No newline at end of file diff --git a/Python version/test/language/pddl/pddl_mapper_test.py b/Python version/test/language/pddl/pddl_mapper_test.py new file mode 100644 index 0000000..c4aa78d --- /dev/null +++ b/Python version/test/language/pddl/pddl_mapper_test.py @@ -0,0 +1,26 @@ +import unittest +from languages.pddl.pddl_mapper import PDDLMapper +from pick_up import PickUp + + +class PDDLMapperTest(unittest.TestCase): + + def test(self): + + instance = PDDLMapper.get_instance() + + try: + instance.register_class(PickUp) + + obj = instance.get_object("(pick-up b)") + + self.assertTrue(isinstance(obj, PickUp)) + + self.assertEqual("b", obj.get_block()) + + except Exception as e: + self.fail(str(e)) + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/Python version/test/specialization/solver_planning_domains/PickUp.py b/Python version/test/language/pddl/pick_up.py similarity index 61% rename from Python version/test/specialization/solver_planning_domains/PickUp.py rename to Python version/test/language/pddl/pick_up.py index 119daa6..f3cde1f 100644 --- a/Python version/test/specialization/solver_planning_domains/PickUp.py +++ b/Python version/test/language/pddl/pick_up.py @@ -1,15 +1,15 @@ -from languages.Predicate import Predicate - -class PickUp(Predicate): - - predicateName="pick-up" - - def __init__(self, block=None): - super(PickUp, self).__init__([("block")]) - self.block = block - - def getBlock(self): - return self.block - - def setBlock(self, block): +from languages.predicate import Predicate + +class PickUp(Predicate): + + predicate_name="pick-up" + + def __init__(self, block=None): + super(PickUp, self).__init__([("block")]) + self.block = block + + def get_block(self): + return self.block + + def set_block(self, block): self.block = block \ No newline at end of file diff --git a/Python version/test/specialization/clingo/Cell.py b/Python version/test/specialization/clingo/cell.py similarity index 62% rename from Python version/test/specialization/clingo/Cell.py rename to Python version/test/specialization/clingo/cell.py index f05d29a..16aeebd 100644 --- a/Python version/test/specialization/clingo/Cell.py +++ b/Python version/test/specialization/clingo/cell.py @@ -1,24 +1,24 @@ -from languages.Predicate import Predicate - -class Cell(Predicate): - - predicateName="cell" - - def __init__(self, row=None, column=None, value=None): - super(Cell, self).__init__([("row", int), ("column", int), ("value", int)]) - self.row = row - self.value = value - self.column = column - - def getRow(self): - return self.row - def getColumn(self): - return self.column - def getValue(self): - return self.value - def setRow(self, row): - self.row = row - def setColumn(self, column): - self.column = column - def setValue(self, value): +from languages.predicate import Predicate + +class Cell(Predicate): + + predicate_name="cell" + + def __init__(self, row=None, column=None, value=None): + super(Cell, self).__init__([("row", int), ("column", int), ("value", int)]) + self.row = row + self.value = value + self.column = column + + def get_row(self): + return self.row + def get_column(self): + return self.column + def get_value(self): + return self.value + def set_row(self, row): + self.row = row + def set_column(self, column): + self.column = column + def set_value(self, value): self.value = value \ No newline at end of file diff --git a/Python version/test/specialization/clingo/ClingoDesktopServiceTest.py b/Python version/test/specialization/clingo/clingo_desktop_service_test.py similarity index 68% rename from Python version/test/specialization/clingo/ClingoDesktopServiceTest.py rename to Python version/test/specialization/clingo/clingo_desktop_service_test.py index 5e71dd0..7a30f1d 100644 --- a/Python version/test/specialization/clingo/ClingoDesktopServiceTest.py +++ b/Python version/test/specialization/clingo/clingo_desktop_service_test.py @@ -1,96 +1,96 @@ -import unittest -from languages.asp.ASPInputProgram import ASPInputProgram -from platforms.desktop.DesktopHandler import DesktopHandler -from base.Output import Output -from test.specialization.clingo.Cell import Cell -from test.specialization.clingo.MyCallback import MyCallback -import sys -import os -from specializations.clingo.desktop.ClingoDesktopService import ClingoDesktopService - - -class ClingoDesktopServiceTest(unittest.TestCase): - - n = 9 - inputMatrix = [ [ 1, 0, 0, 0, 0, 7, 0, 9, 0 ], - [ 0, 3, 0, 0, 2, 0, 0, 0, 8 ], - [ 0, 0, 9, 6, 0, 0, 5, 0, 0 ], - [ 0, 0, 5, 3, 0, 0, 9, 0, 0 ], - [ 0, 1, 0, 0, 8, 0, 0, 0, 2 ], - [ 6, 0, 0, 0, 0, 4, 0, 0, 0 ], - [ 3, 0, 0, 0, 0, 0, 0, 1, 0 ], - [ 0, 4, 1, 0, 0, 0, 0, 0, 7 ], - [ 0, 0, 7, 0, 0, 0, 3, 0, 0 ] ] - - - def getPath(self): - OS = sys.platform - path = os.path.join("..", "..", "..", "..", "test-resources", "asp", "executables", "clingo") - if OS.startswith("win32"): - if sys.maxsize > 2**32: - path = os.path.join(path, "clingo64.exe") - else: - path = os.path.join(path, "clingo32.exe") - else: - if OS.startswith("darwin"): - path = os.path.join(path, "clingo_macos") - else: - if OS.startswith("linux"): - path = os.path.join(path, "clingo_linux") - - return path - - def test_sudoku(self): - try: - handler = DesktopHandler(ClingoDesktopService(self.getPath())) - - inp = ASPInputProgram() - - for i in range(9): - for j in range(9): - if (self.inputMatrix[i][j] != 0): - inp.addObjectInput(Cell(i,j,self.inputMatrix[i][j])) - - inp.addFilesPath(os.path.join("..", "..", "..", "..", "test-resources", "asp", "sudoku")) - - handler.addProgram(inp) - - - mc = MyCallback() - - handler.startAsync(mc) - - mc.await() - - out = mc.getOutput() - - # out = handler.startSync() - - - self.assertIsNotNone(out) - - self.assertTrue(isinstance(out, Output), "Error, result object is not Output") - - self.assertIsNone(out.getErrors(), "Found error in the Plan\n" + str(out.getErrors())) - - - if (len(out.getAnswerSets()) == 0): - return - - ans = out.getAnswerSets()[0] - - for obj in ans.getAtoms(): - self.inputMatrix[obj.getRow()][obj.getColumn()] = obj.getValue() - - tmp="" - for i in range(9): - for j in range(9): - tmp += str(self.inputMatrix[i][j]) + " " - print(tmp) - tmp="" - - except Exception as e: - self.fail("Exception " + str(e)) - -if __name__ == '__main__': - unittest.main() \ No newline at end of file +import unittest +from languages.asp.asp_input_program import ASPInputProgram +from platforms.desktop.desktop_handler import DesktopHandler +from base.output import Output +from cell import Cell +from my_callback import MyCallback +import sys +import os +from specializations.clingo.desktop.clingo_desktop_service import ClingoDesktopService + + +class ClingoDesktopServiceTest(unittest.TestCase): + + n = 9 + inputMatrix = [ [ 1, 0, 0, 0, 0, 7, 0, 9, 0 ], + [ 0, 3, 0, 0, 2, 0, 0, 0, 8 ], + [ 0, 0, 9, 6, 0, 0, 5, 0, 0 ], + [ 0, 0, 5, 3, 0, 0, 9, 0, 0 ], + [ 0, 1, 0, 0, 8, 0, 0, 0, 2 ], + [ 6, 0, 0, 0, 0, 4, 0, 0, 0 ], + [ 3, 0, 0, 0, 0, 0, 0, 1, 0 ], + [ 0, 4, 1, 0, 0, 0, 0, 0, 7 ], + [ 0, 0, 7, 0, 0, 0, 3, 0, 0 ] ] + + + def getPath(self): + OS = sys.platform + path = os.path.join("..", "..", "..", "..", "test-resources", "asp", "executables", "clingo") + if OS.startswith("win32"): + if sys.maxsize > 2**32: + path = os.path.join(path, "clingo64.exe") + else: + path = os.path.join(path, "clingo32.exe") + else: + if OS.startswith("darwin"): + path = os.path.join(path, "clingo_macos") + else: + if OS.startswith("linux"): + path = os.path.join(path, "clingo_linux") + + return path + + def test_sudoku(self): + try: + handler = DesktopHandler(ClingoDesktopService(self.getPath())) + + inp = ASPInputProgram() + + for i in range(9): + for j in range(9): + if (self.inputMatrix[i][j] != 0): + inp.add_object_input(Cell(i,j,self.inputMatrix[i][j])) + + inp.add_files_path(os.path.join("..", "..", "..", "..", "test-resources", "asp", "sudoku")) + + handler.add_program(inp) + + + mc = MyCallback() + + handler.start_async(mc) + + mc.await() + + out = mc.get_output() + + # out = handler.startSync() + + + self.assertIsNotNone(out) + + self.assertTrue(isinstance(out, Output), "Error, result object is not Output") + + self.assertIsNone(out.get_errors(), "Found error in the Plan\n" + str(out.get_errors())) + + + if (len(out.get_answer_sets()) == 0): + return + + ans = out.get_answer_sets()[0] + + for obj in ans.get_atoms(): + self.inputMatrix[obj.get_row()][obj.get_column()] = obj.get_value() + + tmp="" + for i in range(9): + for j in range(9): + tmp += str(self.inputMatrix[i][j]) + " " + print(tmp) + tmp="" + + except Exception as e: + self.fail("Exception " + str(e)) + +if __name__ == '__main__': + unittest.main() diff --git a/Python version/test/specialization/dlv/MyCallback.py b/Python version/test/specialization/clingo/my_callback.py similarity index 82% rename from Python version/test/specialization/dlv/MyCallback.py rename to Python version/test/specialization/clingo/my_callback.py index f50f7c3..9ad16b4 100644 --- a/Python version/test/specialization/dlv/MyCallback.py +++ b/Python version/test/specialization/clingo/my_callback.py @@ -1,32 +1,32 @@ -import threading -from base.Callback import Callback -from languages.asp.AnswerSets import AnswerSets - -class MyCallback(Callback): - - def __init__(self, count=1): - self.count = count - self.lock = threading.Condition() - self.ans=None - - def __count_down(self): - self.lock.acquire() - self.count -= 1 - if self.count <= 0: - self.lock.notifyAll() - self.lock.release() - - def await(self): - self.lock.acquire() - while self.count > 0: - self.lock.wait() - self.lock.release() - - def callback(self, o): - if (not isinstance(o, AnswerSets)): - return - self.ans = o - self.__count_down() - - def getOutput(self): +import threading +from base.callback import Callback +from languages.asp.answer_sets import AnswerSets + +class MyCallback(Callback): + + def __init__(self, count=1): + self.count = count + self.lock = threading.Condition() + self.ans=None + + def __count_down(self): + self.lock.acquire() + self.count -= 1 + if self.count <= 0: + self.lock.notifyAll() + self.lock.release() + + def await(self): + self.lock.acquire() + while self.count > 0: + self.lock.wait() + self.lock.release() + + def callback(self, o): + if (not isinstance(o, AnswerSets)): + return + self.ans = o + self.__count_down() + + def get_output(self): return self.ans \ No newline at end of file diff --git a/Python version/test/specialization/dlv/cell.py b/Python version/test/specialization/dlv/cell.py new file mode 100644 index 0000000..16aeebd --- /dev/null +++ b/Python version/test/specialization/dlv/cell.py @@ -0,0 +1,24 @@ +from languages.predicate import Predicate + +class Cell(Predicate): + + predicate_name="cell" + + def __init__(self, row=None, column=None, value=None): + super(Cell, self).__init__([("row", int), ("column", int), ("value", int)]) + self.row = row + self.value = value + self.column = column + + def get_row(self): + return self.row + def get_column(self): + return self.column + def get_value(self): + return self.value + def set_row(self, row): + self.row = row + def set_column(self, column): + self.column = column + def set_value(self, value): + self.value = value \ No newline at end of file diff --git a/Python version/test/specialization/dlv/DLVDesktopServiceTest.py b/Python version/test/specialization/dlv/dlv_desktop_service_test.py similarity index 69% rename from Python version/test/specialization/dlv/DLVDesktopServiceTest.py rename to Python version/test/specialization/dlv/dlv_desktop_service_test.py index d58399a..d619616 100644 --- a/Python version/test/specialization/dlv/DLVDesktopServiceTest.py +++ b/Python version/test/specialization/dlv/dlv_desktop_service_test.py @@ -1,95 +1,95 @@ -import unittest -from languages.asp.ASPInputProgram import ASPInputProgram -from platforms.desktop.DesktopHandler import DesktopHandler -from specializations.dlv.desktop.DLVDesktopService import DLVDesktopService -from base.Output import Output -from test.specialization.dlv.Cell import Cell -from test.specialization.dlv.MyCallback import MyCallback -import sys -import os - - -class DLVDesktopServiceTest(unittest.TestCase): - - n = 9 - inputMatrix = [ [ 1, 0, 0, 0, 0, 7, 0, 9, 0 ], - [ 0, 3, 0, 0, 2, 0, 0, 0, 8 ], - [ 0, 0, 9, 6, 0, 0, 5, 0, 0 ], - [ 0, 0, 5, 3, 0, 0, 9, 0, 0 ], - [ 0, 1, 0, 0, 8, 0, 0, 0, 2 ], - [ 6, 0, 0, 0, 0, 4, 0, 0, 0 ], - [ 3, 0, 0, 0, 0, 0, 0, 1, 0 ], - [ 0, 4, 1, 0, 0, 0, 0, 0, 7 ], - [ 0, 0, 7, 0, 0, 0, 3, 0, 0 ] ] - - - def getPath(self): - OS = sys.platform - path = os.path.join("..", "..", "..", "..", "test-resources", "asp", "executables", "dlv") - if OS.startswith("win32"): - path = os.path.join(path, "dlv.mingw.exe") - else: - if OS.startswith("darwin"): - path = os.path.join(path, "dlv.i386-apple-darwin.bin") - else: - if OS.startswith("linux"): - if sys.maxsize > 2**32: - path = os.path.join(path, "dlv.x86-64-linux-elf-static.bin") - else: - path = os.path.join(path, "dlv.i386-linux-elf-static.bin") - return path - - def test_sudoku(self): - try: - handler = DesktopHandler(DLVDesktopService(self.getPath())) - - inp = ASPInputProgram() - - for i in range(9): - for j in range(9): - if (self.inputMatrix[i][j] != 0): - inp.addObjectInput(Cell(i,j,self.inputMatrix[i][j])) - - inp.addFilesPath(os.path.join("..", "..", "..", "..", "test-resources", "asp", "sudoku")) - - handler.addProgram(inp) - - - mc = MyCallback() - - handler.startAsync(mc) - - mc.await() - - out = mc.getOutput() - - # out = handler.startSync() - - - self.assertIsNotNone(out) - - self.assertTrue(isinstance(out, Output), "Error, result object is not Output") - - self.assertIsNone(out.getErrors(), "Found error in the Plan\n" + str(out.getErrors())) - - - if (len(out.getAnswerSets()) == 0): - return - - ans = out.getAnswerSets()[0] - - for obj in ans.getAtoms(): - self.inputMatrix[obj.getRow()][obj.getColumn()] = obj.getValue() - - tmp="" - for i in range(9): - for j in range(9): - tmp += str(self.inputMatrix[i][j]) + " " - print(tmp) - tmp="" - - except Exception as e: - self.fail("Exception " + str(e)) - -if __name__ == '__main__': +import unittest +from languages.asp.asp_input_program import ASPInputProgram +from platforms.desktop.desktop_handler import DesktopHandler +from specializations.dlv.desktop.dlv_desktop_service import DLVDesktopService +from base.output import Output +from cell import Cell +from my_callback import MyCallback +import sys +import os + + +class DLVDesktopServiceTest(unittest.TestCase): + + n = 9 + inputMatrix = [ [ 1, 0, 0, 0, 0, 7, 0, 9, 0 ], + [ 0, 3, 0, 0, 2, 0, 0, 0, 8 ], + [ 0, 0, 9, 6, 0, 0, 5, 0, 0 ], + [ 0, 0, 5, 3, 0, 0, 9, 0, 0 ], + [ 0, 1, 0, 0, 8, 0, 0, 0, 2 ], + [ 6, 0, 0, 0, 0, 4, 0, 0, 0 ], + [ 3, 0, 0, 0, 0, 0, 0, 1, 0 ], + [ 0, 4, 1, 0, 0, 0, 0, 0, 7 ], + [ 0, 0, 7, 0, 0, 0, 3, 0, 0 ] ] + + + def getPath(self): + OS = sys.platform + path = os.path.join("..", "..", "..", "..", "test-resources", "asp", "executables", "dlv") + if OS.startswith("win32"): + path = os.path.join(path, "dlv.mingw.exe") + else: + if OS.startswith("darwin"): + path = os.path.join(path, "dlv.i386-apple-darwin.bin") + else: + if OS.startswith("linux"): + if sys.maxsize > 2**32: + path = os.path.join(path, "dlv.x86-64-linux-elf-static.bin") + else: + path = os.path.join(path, "dlv.i386-linux-elf-static.bin") + return path + + def test_sudoku(self): + try: + handler = DesktopHandler(DLVDesktopService(self.getPath())) + + inp = ASPInputProgram() + + for i in range(9): + for j in range(9): + if (self.inputMatrix[i][j] != 0): + inp.add_object_input(Cell(i,j,self.inputMatrix[i][j])) + + inp.add_files_path(os.path.join("..", "..", "..", "..", "test-resources", "asp", "sudoku")) + + handler.add_program(inp) + + + mc = MyCallback() + + handler.start_async(mc) + + mc.await() + + out = mc.get_output() + + # out = handler.startSync() + + + self.assertIsNotNone(out) + + self.assertTrue(isinstance(out, Output), "Error, result object is not Output") + + self.assertIsNone(out.get_errors(), "Found error in the Plan\n" + str(out.get_errors())) + + + if (len(out.get_answer_sets()) == 0): + return + + ans = out.get_answer_sets()[0] + + for obj in ans.get_atoms(): + self.inputMatrix[obj.get_row()][obj.get_column()] = obj.get_value() + + tmp="" + for i in range(9): + for j in range(9): + tmp += str(self.inputMatrix[i][j]) + " " + print(tmp) + tmp="" + + except Exception as e: + self.fail("Exception " + str(e)) + +if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Python version/test/specialization/clingo/MyCallback.py b/Python version/test/specialization/dlv/my_callback.py similarity index 82% rename from Python version/test/specialization/clingo/MyCallback.py rename to Python version/test/specialization/dlv/my_callback.py index f50f7c3..9ad16b4 100644 --- a/Python version/test/specialization/clingo/MyCallback.py +++ b/Python version/test/specialization/dlv/my_callback.py @@ -1,32 +1,32 @@ -import threading -from base.Callback import Callback -from languages.asp.AnswerSets import AnswerSets - -class MyCallback(Callback): - - def __init__(self, count=1): - self.count = count - self.lock = threading.Condition() - self.ans=None - - def __count_down(self): - self.lock.acquire() - self.count -= 1 - if self.count <= 0: - self.lock.notifyAll() - self.lock.release() - - def await(self): - self.lock.acquire() - while self.count > 0: - self.lock.wait() - self.lock.release() - - def callback(self, o): - if (not isinstance(o, AnswerSets)): - return - self.ans = o - self.__count_down() - - def getOutput(self): +import threading +from base.callback import Callback +from languages.asp.answer_sets import AnswerSets + +class MyCallback(Callback): + + def __init__(self, count=1): + self.count = count + self.lock = threading.Condition() + self.ans=None + + def __count_down(self): + self.lock.acquire() + self.count -= 1 + if self.count <= 0: + self.lock.notifyAll() + self.lock.release() + + def await(self): + self.lock.acquire() + while self.count > 0: + self.lock.wait() + self.lock.release() + + def callback(self, o): + if (not isinstance(o, AnswerSets)): + return + self.ans = o + self.__count_down() + + def get_output(self): return self.ans \ No newline at end of file diff --git a/Python version/test/specialization/solver_planning_domains/MyCallback.py b/Python version/test/specialization/solver_planning_domains/my_callback.py similarity index 83% rename from Python version/test/specialization/solver_planning_domains/MyCallback.py rename to Python version/test/specialization/solver_planning_domains/my_callback.py index fa15467..786696a 100644 --- a/Python version/test/specialization/solver_planning_domains/MyCallback.py +++ b/Python version/test/specialization/solver_planning_domains/my_callback.py @@ -1,32 +1,32 @@ -import threading -from base.Callback import Callback -from languages.pddl.Plan import Plan - -class MyCallback(Callback): - - def __init__(self, count=1): - self.count = count - self.lock = threading.Condition() - self.ans=None - - def __count_down(self): - self.lock.acquire() - self.count -= 1 - if self.count <= 0: - self.lock.notifyAll() - self.lock.release() - - def await(self): - self.lock.acquire() - while self.count > 0: - self.lock.wait() - self.lock.release() - - def callback(self, o): - if (not isinstance(o, Plan)): - return - self.ans = o - self.__count_down() - - def getOutput(self): +import threading +from base.callback import Callback +from languages.pddl.plan import Plan + +class MyCallback(Callback): + + def __init__(self, count=1): + self.count = count + self.lock = threading.Condition() + self.ans=None + + def __count_down(self): + self.lock.acquire() + self.count -= 1 + if self.count <= 0: + self.lock.notifyAll() + self.lock.release() + + def await(self): + self.lock.acquire() + while self.count > 0: + self.lock.wait() + self.lock.release() + + def callback(self, o): + if (not isinstance(o, Plan)): + return + self.ans = o + self.__count_down() + + def get_output(self): return self.ans \ No newline at end of file diff --git a/Python version/test/specialization/solver_planning_domains/pick_up.py b/Python version/test/specialization/solver_planning_domains/pick_up.py new file mode 100644 index 0000000..f3cde1f --- /dev/null +++ b/Python version/test/specialization/solver_planning_domains/pick_up.py @@ -0,0 +1,15 @@ +from languages.predicate import Predicate + +class PickUp(Predicate): + + predicate_name="pick-up" + + def __init__(self, block=None): + super(PickUp, self).__init__([("block")]) + self.block = block + + def get_block(self): + return self.block + + def set_block(self, block): + self.block = block \ No newline at end of file diff --git a/Python version/test/specialization/solver_planning_domains/SPDDesktopServiceTest.py b/Python version/test/specialization/solver_planning_domains/spd_desktop_service_test.py similarity index 69% rename from Python version/test/specialization/solver_planning_domains/SPDDesktopServiceTest.py rename to Python version/test/specialization/solver_planning_domains/spd_desktop_service_test.py index 7a250ad..bcb9f61 100644 --- a/Python version/test/specialization/solver_planning_domains/SPDDesktopServiceTest.py +++ b/Python version/test/specialization/solver_planning_domains/spd_desktop_service_test.py @@ -1,100 +1,100 @@ -import unittest -import os -from platforms.desktop.DesktopHandler import DesktopHandler -from specializations.solver_planning_domains.desktop.SPDDesktopService import SPDDesktopService -from languages.pddl.PDDLInputProgram import PDDLInputProgram -from languages.pddl.PDDLProgramType import PDDLProgramType -from languages.pddl.PDDLMapper import PDDLMapper -from test.specialization.solver_planning_domains.MyCallback import MyCallback -import time -from test.specialization.solver_planning_domains.PickUp import PickUp - - - -class SPDDesktopServiceTest(unittest.TestCase): - - - def core(self, results_sizes, base_path): - - print("Testing " + str(len(results_sizes)) + " files for " + base_path) - - for i in range(1, len(results_sizes) + 1): - try: - plan = None - - handler = DesktopHandler(SPDDesktopService()) - - inputProgramDomain = PDDLInputProgram(PDDLProgramType.DOMAIN) - - inputProgramDomain.addFilesPath(base_path + "domain.pddl") - - inputProgramProblem = PDDLInputProgram(PDDLProgramType.PROBLEM) - - if i < 10: - problem = base_path + "p" + "0" + str(i) + ".pddl" - else: - problem = base_path + "p" + str(i) + ".pddl" - - self.assertTrue(os.path.isfile(problem) , "File not found: " + problem) - - inputProgramProblem.addFilesPath(problem) - - handler.addProgram(inputProgramDomain) - - handler.addProgram(inputProgramProblem) - - PDDLMapper.getInstance().registerClass(PickUp) - - self.assertIsNone(plan) - - mc = MyCallback() - - handler.startAsync(mc) - - mc.await() - - plan = mc.getOutput() - - self.assertIsNotNone(plan) - - tmp="" - for action in plan.getActions(): - tmp = tmp + action.getName() + "," - print(tmp) - - if results_sizes[i - 1] != 0: - self.assertTrue(not plan.getErrors(), "Found error in the Plan " + problem + "\n" + plan.getErrors()) - - self.assertEqual(results_sizes[i - 1], len(plan.getActions())) - - for obj in plan.getActionsObjects(): - if isinstance(obj, PickUp): - print(obj.getBlock()) - - time.sleep(0.5) - - except Exception as e: - self.fail("Exception " + str(e)) - - def test_blocksworld(self): - results_sizes = (6, 10, 6, 12, 10, 16, 12, 10, 20, 20, 24, 22, 18, 24, 16, 34, 28, 26, 42, 36, 36, 32, 46, 34, 40, 34, 58, 50, 44, 38, 46, 58, 66, 56, 56) - base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "blocksworld", "") - self.core(results_sizes, base_path) - - def test_depots(self): - results_sizes = (11, 16, 44, 36, 122, 64, 33, 56, 83, 25, 74, 133, 30, 0, 0, 36, 54, 103, 56, 146, 55, 0) - base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "depots", "") - self.core(results_sizes, base_path) - - def test_logistics(self): - results_sizes = (24, 27, 15, 34, 19, 10, 30, 14, 33, 34, 58, 58, 48, 68, 46, 49, 74, 55, 0, 84, 69, 117, 134, 102, 109, 127, 141, 128) - base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "logistics", "") - self.core(results_sizes, base_path) - - def test_gripper(self): - results_sizes = (15, 23, 31, 39, 47, 55, 63, 71, 79, 87, 95, 103, 111, 119, 127, 135, 143, 151, 159, 167) - base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "gripper", "") - self.core(results_sizes, base_path) - -if __name__ == '__main__': +import unittest +import os +from platforms.desktop.desktop_handler import DesktopHandler +from specializations.solver_planning_domains.desktop.spd_desktop_service import SPDDesktopService +from languages.pddl.pddl_input_program import PDDLInputProgram +from languages.pddl.pddl_program_type import PDDLProgramType +from languages.pddl.pddl_mapper import PDDLMapper +from my_callback import MyCallback +import time +from pick_up import PickUp + + + +class SPDDesktopServiceTest(unittest.TestCase): + + + def core(self, results_sizes, base_path): + + print("Testing " + str(len(results_sizes)) + " files for " + base_path) + + for i in range(1, len(results_sizes) + 1): + try: + plan = None + + handler = DesktopHandler(SPDDesktopService()) + + inputProgramDomain = PDDLInputProgram(PDDLProgramType.DOMAIN) + + inputProgramDomain.add_files_path(base_path + "domain.pddl") + + inputProgramProblem = PDDLInputProgram(PDDLProgramType.PROBLEM) + + if i < 10: + problem = base_path + "p" + "0" + str(i) + ".pddl" + else: + problem = base_path + "p" + str(i) + ".pddl" + + self.assertTrue(os.path.isfile(problem) , "File not found: " + problem) + + inputProgramProblem.add_files_path(problem) + + handler.add_program(inputProgramDomain) + + handler.add_program(inputProgramProblem) + + PDDLMapper.get_instance().register_class(PickUp) + + self.assertIsNone(plan) + + mc = MyCallback() + + handler.start_async(mc) + + mc.await() + + plan = mc.get_output() + + self.assertIsNotNone(plan) + + tmp="" + for action in plan.get_actions(): + tmp = tmp + action.get_name() + "," + print(tmp) + + if results_sizes[i - 1] != 0: + self.assertTrue(not plan.get_errors(), "Found error in the Plan " + problem + "\n" + plan.get_errors()) + + self.assertEqual(results_sizes[i - 1], len(plan.get_actions())) + + for obj in plan.get_actions_objects(): + if isinstance(obj, PickUp): + print(obj.get_block()) + + time.sleep(0.5) + + except Exception as e: + self.fail("Exception " + str(e)) + + def test_blocksworld(self): + results_sizes = (6, 10, 6, 12, 10, 16, 12, 10, 20, 20, 24, 22, 18, 24, 16, 34, 28, 26, 42, 36, 36, 32, 46, 34, 40, 34, 58, 50, 44, 38, 46, 58, 66, 56, 56) + base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "blocksworld", "") + self.core(results_sizes, base_path) + + def test_depots(self): + results_sizes = (11, 16, 44, 36, 122, 64, 33, 56, 83, 25, 74, 133, 30, 0, 0, 36, 54, 103, 56, 146, 55, 0) + base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "depots", "") + self.core(results_sizes, base_path) + + def test_logistics(self): + results_sizes = (24, 27, 15, 34, 19, 10, 30, 14, 33, 34, 58, 58, 48, 68, 46, 49, 74, 55, 0, 84, 69, 117, 134, 102, 109, 127, 141, 128) + base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "logistics", "") + self.core(results_sizes, base_path) + + def test_gripper(self): + results_sizes = (15, 23, 31, 39, 47, 55, 63, 71, 79, 87, 95, 103, 111, 119, 127, 135, 143, 151, 159, 167) + base_path = os.path.join("..", "..", "..", "..", "test-resources", "pddl", "gripper", "") + self.core(results_sizes, base_path) + +if __name__ == '__main__': unittest.main() \ No newline at end of file