def __handle_mln_query(self, request): try: rospy.loginfo("Processing request...") config = self.__get_config(request) if self.__config_changed(config): rospy.loginfo("Configuration changed") self.__mln = MLN(config.logic, config.grammar, config.mlnFiles) self.__mln_date = os.path.getmtime(config.mlnFiles) self.__config = config db = self.__get_db(request, config, self.__mln) materialized_mln = self.__mln.materialize(db) mrf = materialized_mln.ground(db) if not request.query: raise Exception("No query provided!") inference = InferenceMethods.clazz(config.method)( mrf, request.query.queries) result = inference.run() self.__save_results(config, result) tuple_list = [] for atom, probability in inference.results.items(): tuple_list.append(AtomProbPair(str(atom), float(probability))) tuple_list.sort(key=lambda item: item.prob, reverse=True) to_return = MLNInterfaceResponse(MLNDatabase(tuple_list)) rospy.loginfo("Done!") return to_return except Exception: rospy.logfatal(traceback.format_exc()) return MLNDatabase([])
def infer(self, savegeometry=True, options={}, *args): mln_content = self.mln_container.editor.get("1.0", END).strip() db_content = self.db_container.editor.get("1.0", END).strip() # create conf from current gui settings self.update_config() # write gui settings self.write_gconfig(savegeometry=savegeometry) # hide gui self.master.withdraw() try: print((headline('PRACMLN QUERY TOOL'))) print() if options.get('mlnarg') is not None: mlnobj = MLN(mlnfile=os.path.abspath(options.get('mlnarg')), logic=self.config.get('logic', 'FirstOrderLogic'), grammar=self.config.get('grammar', 'PRACGrammar')) else: mlnobj = parse_mln( mln_content, searchpaths=[self.dir], projectpath=os.path.join(self.dir, self.project.name), logic=self.config.get('logic', 'FirstOrderLogic'), grammar=self.config.get('grammar', 'PRACGrammar')) if options.get('emlnarg') is not None: emln_content = mlnpath(options.get('emlnarg')).content else: emln_content = self.emln_container.editor.get("1.0", END).strip() if options.get('dbarg') is not None: dbobj = Database.load(mlnobj, dbfiles=[options.get('dbarg')], ignore_unknown_preds=self.config.get( 'ignore_unknown_preds', True)) else: out(self.config.get('ignore_unknown_preds', True)) dbobj = parse_db(mlnobj, db_content, ignore_unknown_preds=self.config.get( 'ignore_unknown_preds', True)) if options.get('queryarg') is not None: self.config["queries"] = options.get('queryarg') infer = MLNQuery(config=self.config, mln=mlnobj, db=dbobj, emln=emln_content) result = infer.run() # write to file if run from commandline, otherwise save result to project results if options.get('outputfile') is not None: output = io.StringIO() result.write(output) with open(os.path.abspath(options.get('outputfile')), 'w') as f: f.write(output.getvalue()) logger.info('saved result to {}'.format( os.path.abspath(options.get('outputfile')))) elif self.save.get(): output = io.StringIO() result.write(output) fname = self.output_filename.get() self.project.add_result(fname, output.getvalue()) self.project.save(dirpath=self.dir) logger.info( 'saved result to file results/{} in project {}'.format( fname, self.project.name)) else: logger.debug( 'No output file given - results have not been saved.') except: traceback.print_exc() # restore main window sys.stdout.flush() self.master.deiconify()
self.literal = literal def isvar(self, identifier): """ Variables must start with a question mark (or the + operator, anything else is considered a constant. """ return identifier[0] == '?' or identifier[0] == "+" if __name__ == '__main__': # f = '(a(x) ^ b(u) v !(c(h) v (r =/= k) ^ !(d(i) ^ !e(x) ^ g(x)))) => EXIST ?a,?b (f(x) ^ b(c))' from pracmln.mln.base import MLN from pracmln.mln.database import Database mln = MLN(grammar='PRACGrammar') # mln << 'foo(x, y)' mln << 'bar(x)' # mln << 'numberEats(k,n)' # mln << 'eats(p,m)' # mln << 'rel(x,y)' mln << 'a(s)' mln << 'b(s)' mln << 'c(s)' # mln << 'd(s)' # mln << 'e(s)' # mln << 'g(s)' # mln << 'f(s)' f = 'a|b|c(s) => (bar(y) <=> bar(x))' # f = 'a|b|c(s)'
self.literal = literal def isvar(self, identifier): ''' Variables must start with a question mark (or the + operator, anything else is considered a constant. ''' return identifier[0] == '?' or identifier[0] == "+" if __name__ == '__main__': # f = '(a(x) ^ b(u) v !(c(h) v (r =/= k) ^ !(d(i) ^ !e(x) ^ g(x)))) => EXIST ?a,?b (f(x) ^ b(c))' from pracmln.mln.base import MLN from pracmln.mln.database import Database mln = MLN(grammar='PRACGrammar') # mln << 'foo(x, y)' mln << 'bar(x)' # mln << 'numberEats(k,n)' # mln << 'eats(p,m)' # mln << 'rel(x,y)' mln << 'a(s)' mln << 'b(s)' mln << 'c(s)' # mln << 'd(s)' # mln << 'e(s)' # mln << 'g(s)' # mln << 'f(s)' f = 'a|b|c(s) => (bar(y) <=> bar(x))'
from pracmln.mln.base import MLN from pracmln.mln.database import Database from pracmln.mln.learning.bpll import BPLL mln = MLN(logic='FirstOrderLogic', grammar='StandardGrammar', mlnfile='onenote.mln') # mln.fixweights = [True, False] db = Database(mln, dbfile='onenote-train.db') mrf = mln.ground(db) method = BPLL(mrf, prior_stdev=1, verbose=True) result = method.run() for w in result: print('{:.3f}'.format(w))
self.formula = formula + StringEnd() self.predDecl = predDecl self.literal = literal def isvar(self, identifier): ''' Variables must start with a question mark (or the + operator, anything else is considered a constant. ''' return identifier[0] == '?' or identifier[0] == "+" if __name__ == '__main__': f = '(a(x) ^ b(u) v !(c(h) v (r =/= k) ^ !(d(i) ^ !e(x) ^ g(x)))) => EXIST ?a,?b (f(x) ^ b(c))' from pracmln.mln.base import MLN mln = MLN(grammar='PRACGrammar') mln << 'foo(x, y)' mln << 'bar(x)' mln << 'numberEats(k,n)' mln << 'eats(p,m)' mln << 'rel(x,y)' mln << 'a(s)' mln << 'b(s)' mln << 'c(s)' mln << 'd(s)' mln << 'e(s)' mln << 'g(s)' mln << 'f(s)' f = 'foo(x,x) => (bar(y) <=> bar(x))' f = mln.logic.grammar.parse_formula(f)
def initialize(self): self.mln = MLN.load( os.path.join(self.module_path, 'mln', 'predicates.mln'))
class MLNInterfaceServer: def __init__(self): self.__config = None self.__mln = None self.__mln_date = None def run(self, node_name="rosmln", service_name="mln_interface"): rospy.init_node(node_name) rospy.Service(service_name, MLNInterface, self.__handle_mln_query) rospy.loginfo("MLN is ready to be queried!") rospy.spin() def __handle_mln_query(self, request): try: rospy.loginfo("Processing request...") config = self.__get_config(request) if self.__config_changed(config): rospy.loginfo("Configuration changed") self.__mln = MLN(config.logic, config.grammar, config.mlnFiles) self.__mln_date = os.path.getmtime(config.mlnFiles) self.__config = config db = self.__get_db(request, config, self.__mln) materialized_mln = self.__mln.materialize(db) mrf = materialized_mln.ground(db) if not request.query: raise Exception("No query provided!") inference = InferenceMethods.clazz(config.method)( mrf, request.query.queries) result = inference.run() self.__save_results(config, result) tuple_list = [] for atom, probability in inference.results.items(): tuple_list.append(AtomProbPair(str(atom), float(probability))) tuple_list.sort(key=lambda item: item.prob, reverse=True) to_return = MLNInterfaceResponse(MLNDatabase(tuple_list)) rospy.loginfo("Done!") return to_return except Exception: rospy.logfatal(traceback.format_exc()) return MLNDatabase([]) def __config_changed(self, config): if self.__config is None or config is None: return True return not (self.__config.db == config.db and \ self.__config.logic == config.logic and \ self.__config.mlnFiles == config.mlnFiles and \ self.__config.output_filename == config.output_filename and \ self.__config.saveResults == config.saveResults and \ self.__config.grammar == config.grammar and \ os.path.getmtime(config.mlnFiles) == self.__mln_date) def __get_config(self, request): if self.__config is None and request.config.mlnFiles == "": raise Exception("No configuration provided!") elif request.config.mlnFiles != "": return request.config elif self.__config is not None: return self.__config def __get_db(self, request, config, mln): if not request.query.evidence and config.db == "": raise Exception("No evidence provided!") if request.query.evidence and config.db != "": raise Exception( "Duplicate evidence; provide either a db in the config or an evidence db in the query" ) if request.query.evidence: to_return = parse_db( mln, reduce(lambda x, y: x + "\n" + y, request.query.evidence)) else: to_return = Database.load(mln, config.db) if len(to_return) != 1: raise Exception("Only one db is supported!") return to_return[0] def __save_results(self, config, resutls): if config.saveResults: with open(config.output_filename, "w") as output: resutls.write(output)