Beispiel #1
0
 def update_convert_field(self, field_id, value):
     # print('updating convert field', field_id, value)
     return Sai(
         selection=field_id,
         # action='UpdateTextField',
         action='UpdateTextArea',
         inputs={'value': value})
Beispiel #2
0
 def update_answer_field(self, field_id, value):
     print('updating answer field', field_id, value)
     return Sai(
         selection=field_id,
         # action='UpdateTextField',
         action='UpdateTextArea',
         inputs={'value': value})
def old_test_compile_addition():
    engine = AdditionEngine()

    engine.reset()

    f1 = Fact(id='JCommTable.R0C0', value='1', contentEditable=False)
    f2 = Fact(id='JCommTable.R1C0', value='2', contentEditable=False)
    f3 = Fact(id='JCommTable.R1C1', contentEditable=True, value='')

    engine.declare(f1)
    engine.declare(f2)
    engine.declare(f3)
    engine.run(10)

    ex = Explanation(engine.sais[0])
    nr = ex.new_rule

    new_wm = ExpertaWorkingMemory(EmptyAdditionEngine())
    new_wm.add_rule(nr)

    f1b = Fact(id='JCommTable.R0C0', value='1', contentEditable=False)
    f2b = Fact(id='JCommTable.R1C0', value='2', contentEditable=False)
    f3b = Fact(id='JCommTable.R1C1', contentEditable=True, value='')

    new_wm.ke.declare(f1b)
    new_wm.ke.declare(f2b)
    new_wm.ke.declare(f3b)
    # test that the new rule fires correctly
    new_wm.ke.run(10)
    s = new_wm.ke.sais[0]
    assert s == Sai(selection='JCommTable.R1C1',
                    action='UpdateTextField',
                    inputs={'value': '3'})
Beispiel #4
0
 def click_done(self):
     print("FIRED CLICK DONE")
     x = Sai(selection='done',
             action='ButtonPressed',
             inputs={'value': '-1'})
     self.sais.append(x)
     return x
Beispiel #5
0
 def update_field(self, field_id, value):
     #print("FIRED UPDATE FIELD")
     s = Sai(
         selection=field_id,
         action='UpdateTextField',
         # action='UpdateTextArea',
         inputs={'value': value})
     if int(value) == 3:
         self.sais.append(s)
     return s
Beispiel #6
0
    def correct_add_convert_num(self, value1, value2):
        new_value = float(value1) + float(value2)
        if new_value.is_integer():
            new_value = int(new_value)
        new_value = str(new_value)

        return Sai(
            selection='JCommTable6.R0C0',
            # action='UpdateTextField',
            action='UpdateTextArea',
            inputs={'value': new_value})
Beispiel #7
0
    def correct_multiply_denom(self, value1, value2):
        new_value = float(value1) * float(value2)
        if new_value.is_integer():
            new_value = int(new_value)
        new_value = str(new_value)

        return Sai(
            selection='JCommTable6.R1C0',
            # action='UpdateTextField',
            action='UpdateTextArea',
            inputs={'value': new_value})
Beispiel #8
0
def check(http_request, agent_id):
    """
    Uses the knoweldge base to check the correctness of an SAI in provided
    state.
    """
    try:
        if http_request.method != "POST":
            return HttpResponseNotAllowed(["POST"])
        data = json.loads(http_request.body.decode("utf-8"))

        errs = []

        if "state" not in data:
            errs.append("request body missing 'state'")
        if "selection" not in data:
            errs.append("request body missing 'selection'")
        if "action" not in data:
            errs.append("request body missing 'action'")
        if "inputs" not in data:
            errs.append("request body missing 'inputs'")

        if len(errs) > 0:
            for err in errs:
                log.error(err)
            # print("errors: {}".format(",".join(errs)))
            return HttpResponseBadRequest("errors: {}".format(",".join(errs)))

        agent = Agent.objects.get(id=agent_id)
        agent.inc_check()
        agent.save()

        response = {}

        sai = Sai(
            selection=data["selection"],
            action=data["action"],
            inputs=data["inputs"],
        )

        data['sai'] = sai
        del data['selection']
        del data['action']
        del data['inputs']

        response["reward"] = agent.instance.check(**data)
        return HttpResponse(json.dumps(response))

    except Exception as exp:
        log.exception('ERROR IN TRAIN')
        log.error('POST data:')
        log.error(data)
        return HttpResponseServerError(str(exp))
Beispiel #9
0
def get_user_demo():
    print()
    print("Current Player: " + game.current_player)
    print(game)
    print("Don't know what to do.")
    print("Please provide example of correct behavior.")
    print()

    while True:
        try:
            loc = input("Enter move as row and column integers "
                        "(e.g., 1,2):")
            loc = loc.split(',')

            row = int(loc[0])
            col = int(loc[1])
            player = game.current_player
            break
        except Exception:
            print("error with input, try again.")

    return Sai(None, "move", {"row": row, "col": col, "player": player})
Beispiel #10
0
    def train(self,
              state: Dict,
              sai: Sai = None,
              reward: float = None,
              skill_label=None,
              foci_of_attention=None,
              rhs_id=None,
              mapping=None,
              ret_train_expl=False,
              add_skill_info=False,
              **kwargs):  # -> return None
        # pprint(state)

        if (type(self.planner).__name__ == "FoPlannerModule"):
            state = add_QMele_to_state(state)
            sai.selection = "?ele-" + sai.selection if sai.selection[
                0] != "?" else sai.selection
        state = StateMultiView("object", state)
        state.register_transform("*", "variablize", self.state_variablizer)
        state.set_view("flat_ungrounded", self.planner.apply_featureset(state))
        # state_featurized = state.get_view("flat_ungrounded")
        # state_featurized =

        # print(sai, foci_of_attention)
        ###########ONLY NECESSARY FOR IMPLICIT NEGATIVES#############
        _ = [x for x in self.applicable_explanations(state)]
        ############################################################

        #Either the explanation (i.e. prev application of skill) is provided
        #   or we must infer it from the skills that would have fired
        if (rhs_id is not None and mapping is not None):
            # print("Reward: ", reward)
            explanations = [Explanation(self.rhs_list[rhs_id], mapping)]
            # print("EX: ",str(explanations[0]))
        elif (sai is not None):
            # pprint(state.get_view("object"))
            # print("TO HOW")
            t_s = time.time_ns()
            explanations = self.explanations_from_skills(
                state, sai, self.rhs_list, foci_of_attention)
            explanations = list(explanations)
            performance_logger.info("explanations_from_skills {} ms".format(
                (time.time_ns() - t_s) / (1e6)))

            explanations, nonmatching_explanations = self.where_matches(
                explanations, state)
            if (len(explanations) == 0):

                if (len(nonmatching_explanations) > 0):
                    explanations = [choice(nonmatching_explanations)]

                else:
                    # print(state_featurized)
                    t_s = time.time_ns()
                    explanations = self.explanations_from_how_search(
                        state, sai, foci_of_attention)
                    performance_logger.info(
                        "explanations_from_how_search {} ms".format(
                            (time.time_ns() - t_s) / (1e6)))

                    explanations = self.which_learner.select_how(explanations)

                    rhs_by_how = self.rhs_by_how.get(skill_label, {})
                    for exp in explanations:
                        # print("FOUND EX:", str(exp))
                        if (exp.rhs.as_tuple in rhs_by_how):
                            exp.rhs = rhs_by_how[exp.rhs.as_tuple]
                        else:
                            rhs_by_how[exp.rhs.as_tuple] = exp.rhs
                            self.rhs_by_how[skill_label] = rhs_by_how
                            self.add_rhs(exp.rhs)
        else:
            raise ValueError(
                "Call to train missing SAI, or unique identifiers")

        explanations = list(explanations)
        # print("FIT_A")
        self.fit(explanations, state, reward)
        if (self.ret_train_expl):
            out = []
            for exp in explanations:
                resp = exp.to_response(state, self)
                if (add_skill_info): resp.update(exp.get_skill_info(self))
                out.append(resp)

            return out
Beispiel #11
0
 def done(self):
     # print('clicking done')
     return Sai(selection='done',
                action='ButtonPressed',
                inputs={'value': '-1'})
Beispiel #12
0
 def correct_copy_convert_denom(self, value3):
     return Sai(
         selection='JCommTable6.R1C0',
         # action='UpdateTextField',
         action='UpdateTextArea',
         inputs={'value': value3})
Beispiel #13
0
 def check(self):
     print('checking box')
     return Sai(selection="JCommTable8.R0C0",
                action='UpdateTextArea',
                inputs={'value': "x"})
Beispiel #14
0
 def click_done(self):
     print('clicking done')
     return Sai(selection='done',
                action='ButtonPressed',
                inputs={'value': -1})
Beispiel #15
0
def train(http_request, agent_id):
    """
    Trains the Agent with an state annotated with the SAI used / with
    feedback.
    """
    global last_call_time
    performance_logger.info("Interface Feedback Time: {} ms".format((time.time_ns()-last_call_time)/1e6))
    # pr.enable()
    try:
        if http_request.method != "POST":
            return HttpResponseNotAllowed(["POST"])
        data = json.loads(http_request.body.decode("utf-8"))

        # print(data)

        errs = []

        if "state" not in data or data["state"] is None:
            errs.append("request body missing 'state'")
        if "skill_label" not in data or data["skill_label"] is None:
            data["skill_label"] = "NO_LABEL"
        if "foci_of_attention" not in data or data["foci_of_attention"] is None:
            data["foci_of_attention"] = None
        if "selection" not in data or data["selection"] is None:
            errs.append("request body missing 'selection'")
        if "action" not in data or data["action"] is None:
            errs.append("request body missing 'action'")
        if "inputs" not in data or data["inputs"] is None:
            errs.append("request body missing 'inputs'")
        if "reward" not in data or data["reward"] is None:
            if "correct" in data:
                data["reward"] = 2 * int(data["correct"] == True) - 1
            else:
                errs.append("request body missing 'reward'")

        # Linter was complaining about too many returns so I consolidated all
        # of the errors above
        if len(errs) > 0:
            for err in errs:
                log.error(err)
            # print("errors: {}".format(",".join(errs)))
            return HttpResponseBadRequest("errors: {}".format(",".join(errs)))

        agent = get_agent_by_id(agent_id)
        agent.inc_train()

        sai = Sai(
            selection=data["selection"],
            action=data["action"],
            inputs=data["inputs"],
        )

        data['sai'] = sai
        del data['selection']
        del data['action']
        del data['inputs']

        start_t = time.time_ns()
        response = agent.instance.train(**data)
        performance_logger.info("Train Elapse Time: {} ms".format((time.time_ns()-start_t)/(1e6)))

        global dont_save
        if not dont_save:
            log.warning('Agent is being saved! This is probably not working.')
            agent.save()

        # pr.disable()
        # pr.dump_stats("al.cprof")
        last_call_time =  time.time_ns()

        if(response is not None):
             return HttpResponse(json.dumps(response))
        else:
            return HttpResponse("OK")

    except Exception as exp:
        log.exception('ERROR IN TRAIN')
        log.error('POST data:')
        log.error(data)
        # log.error(data)
        # traceback.print_exc()

        # pr.disable()
        # pr.dump_stats("al.cprof")
        return HttpResponseServerError(str(exp))
Beispiel #16
0
 def check(self, field_id):
     print("FIRED CHECK")
     return Sai(selection=field_id,
                action='UpdateTextArea',
                inputs={'value': "x"})
Beispiel #17
0
 def correct_done(self):
     return Sai(selection='done',
                action='ButtonPressed',
                inputs={'value': -1})
Beispiel #18
0
 def input_random(self, id):
     return Sai(selection=id,
                action='UpdateTextArea',
                inputs={'value': str(randint(0, 100))})