Ejemplo n.º 1
0
class instql_querier(object):
	def __init__(self):
		json_out = None

	def instql_show(self,dict_predicates, instql_asp):
	    self.ctl = Control()
	    self.ctl.load(temporary_text_file(instql_asp))
	    fact_asp = dict_funs_to_asp(dict_predicates)
	    self.ctl.load(temporary_text_file(fact_asp))
	    parts = []


	    self.ctl.ground(parts+[("base", [])])

	    self.ctl.solve(on_model=self.on_model)

	    out = state_dict_from_lists(self.observed,self.occurred,self.holdsat)
	    return out

	def on_model(self,model):
		last_solution = model.atoms()
		self.observed, self.occurred, self.holdsat = model_atoms_to_lists(model.atoms(Model.SHOWN),from_json=True)
Ejemplo n.º 2
0
class Sensor(object):

    def __init__(self, callback, initially, model_files, domain_facts, args):
        self.holdsat = initially
        self.occurred = []
        self.callback = callback
        self.last_solution = None
        self.cycle = 0
        self.horizon = 1
        self.args = args
        self.observation = None
	self.observed = []
        self.undo_external = []
        self.ctl = Control(['-c', 'horizon={0}'.format(self.horizon)])
        for x in model_files:
            if args.verbose>2: print("loading: ",x)
            self.ctl.load(x)
	parts = []
        for typename,literals in domain_facts.iteritems():
            for l in literals:
                parts += [(typename, [parse_term(l)])]
        if args.verbose>2: print("grounding: ", parts+[("base",[])])
        self.ctl.ground(parts+[("base", [])])
        if args.verbose>2: print("grounded")
	signature_types = [s[0] for s in self.ctl.domains.signatures()]
	from_domain_types = [d for d in domain_facts]
	#Testing for type names in domain file not in grounded file
	for d in from_domain_types:
            if d not in signature_types:
                print("WARNING: Type {} in domain file is not in grounded model.".format(d),file=sys.stderr)
        if args.verbose>2: print("initialized")

    def print_universe(self):
        print("universe:", len(self.ctl.domains))
        for x in self.ctl.domains:
            print(x.atom, x.is_fact, x.is_external)

    def check_events(self,event,present,absent):
        return self.check_sensor_data(event,self.occurred,present,absent)

    def check_facts(self,event,present,absent):
        return self.check_sensor_data(event,self.holdsat,present,absent)

    def check_sensor_data(self,event,data,present,absent):
        satisfied = True
        for f in present:
            # print("checking",f,present_state,sensor.holdsat)
            if not(parse_term(f) in data):
                print("Not satisfied({n})\n{event} |="
                      .format(event=event,n=self.cycle),f)
                satisfied = False
        for f in absent:
            # print("checking",f,present_state,sensor.holdsat)
            if (parse_term(f) in data):
                print("Not satisfied({n})\n{event} !|="
                      .format(event=event,n=self.cycle),f)
                satisfied = False
        # print("check_final",satisfied)
        return satisfied

    def solve(self, event):
        if self.args.verbose>1:
            print(self.cycle,"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
        self.observation = parse_term(event)
        for x in self.undo_external:
            if self.args.verbose>1:
                print("unassign",x)
            self.ctl.assign_external(x, False)
        self.undo_external = []
        if self.args.verbose>1:
            print(self.cycle,"----------------------------------------")
        for x in self.holdsat + [self.observation]:
            if self.args.verbose>1:
                print("assign",x)
            self.ctl.assign_external(x, True)
            self.undo_external.append(x)
        self.last_solution = None
        if self.args.verbose>1:
            print(self.cycle,"----------------------------------------")
        self.ctl.solve(on_model=self.on_model)
        # self.print_universe()
        if self.args.verbose>1:
            print(self.cycle,">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        if self.args.verbose>0: print("")
        self.cycle += 1
        return self.last_solution

    def on_model(self, model):
        self.last_solution = model.atoms()
        self.holdsat = []
        self.occurred = []
        self.observed, self.occurred, self.holdsat = model_atoms_to_lists(model.atoms(Model.ATOMS),verbose=self.args.verbose)
        if self.args.verbose>0:
            print(state_to_string(self.observed,self.occurred,self.holdsat))
			

    def get_state_json(self):
	return state_dict_from_lists(self.observed,self.occurred,self.holdsat)
Ejemplo n.º 3
0
class Oracle(object):

    def __init__(self, initially, model_files, domain_facts, args):
        self.answersets = {}
        self.cycle = 0
        self.args = args
        self.observations = None
        self.ctl = Control(['-n', str(args.number), '-c', 'horizon={0}'.format(args.length)])
        for x in model_files:
            if args.verbose>2: print("loading: ",x)
            self.ctl.load(x)
	parts = []
        for typename,literals in domain_facts.iteritems():
            for l in literals:
                parts += [(typename, [parse_term(l)])]
        if args.verbose>2: print("grounding: ", parts+[("base",[])])
        self.ctl.ground(parts+[("base", [])])
        if args.verbose>2: print("grounded")
	signature_types = [s[0] for s in self.ctl.domains.signatures()]
	from_domain_types = [d for d in domain_facts]
	#Testing for type names in domain file not in grounded file
	for d in from_domain_types:
            if d not in signature_types:
                print("WARNING: Type {} in domain file is not in grounded model.".format(d),file=sys.stderr)
        if args.verbose>2: print("initialization complete")

    def solve_iter(self,events):
        self.observations = events
        for x in self.observations:
            if self.args.verbose>1:
                print("assign",x)
            self.ctl.assign_external(x, True)
        self.cycle = self.args.length # len(self.observations)
        print(self.observations,self.cycle)
        answers = 0
        with self.ctl.solve_iter() as it:
            for m in it:
                # if self.args.verbose>0: print("Answer set {}".format(answers))
                if self.args.answer_set>0 and self.args.answer_set!=answers+1:
                    self.answersets[answers] = [] # may be make this [[],[],[]]??
                else:
                    self.answersets[answers] = self.process_answer_set(m,answers)
                # if self.args.verbose>0:
                #    print(state_to_string(self.answersets[answers][0], self.answersets[answers][1], self.answersets[answers][2]))
                # print(m.optimization())
                answers+=1
        # print(self.ctl.stats)
        if answers==1:
            print("There is 1 answer set")
        else:
            print("There are {} answer sets".format(answers))
        return

    def process_answer_set(self, model, answer):
        occurred = defaultdict(list)
        holdsat = defaultdict(list)
        observed = defaultdict(list)
        rejected = None
        if self.args.verbose > 2: print("FULL ATOM PRINTING\n---------------")
        for atom in model.atoms(Model.ATOMS):
	    if self.args.verbose > 2: print(atom)
            if atom.name() in ["observed","occurred","holdsat"]:
                what = Fun(atom.name(), atom.args()[:-1])
                when = atom.args()[-1]
                # print(what,when)
            if (atom.name()=="observed"):
                observed[when].append(what)
            if (atom.name()=="occurred"):
                occurred[when].append(what)
            if (atom.name()=="holdsat"):
                holdsat[when].append(what)
        # print(observed,occurred,holdsat)
        return [observed,occurred,holdsat]