Exemple #1
0
def is_equal_to(a1, a2):
    # verificăm atomi cu același nume de predicat și același număr de argumente
    if not (is_atom(a1) and is_atom(a2) and get_head(a1) == get_head(a2)
            and len(get_args(a1)) == len(get_args(a2))):
        return False
    return all([
        equal_terms(get_args(a1)[i],
                    get_args(a2)[i]) for i in range(len(get_args(a1)))
    ])
Exemple #2
0
def equal_terms(t1, t2):
    if is_constant(t1) and is_constant(t2):
        return get_value(t1) == get_value(t2)
    if is_variable(t1) and is_variable(t2):
            return get_name(t1) == get_name(t2)
    if is_function_call(t1) and is_function(t2):
        if get_head(t1) != get_head(t2):
            return all([equal_terms(get_args(t1)[i], get_args(t2)[i]) for i in range(len(get_args(t1)))])
    return False
def findAllSubstitutions(action, atoms, subst):
    if not atoms:
        print(subst)
        applyLE(action, subst)
        applyLA(action, subst)
        return

    atom = atoms[0]
    name = get_head(atom)
    if name in env:
        facts = env[name]
    elif name in math_predicates:
        return findAllSubstitutions(action, atoms[1:], subst)
    else:
        facts = state

    for fact in facts:
        newSubst = unify(atom, fact)
        if newSubst != False and newSubst != None:
            copySubst = deepcopy(subst)
            copySubst.update(newSubst)

            remaining = deepcopy(atoms[1:])
            for i in range(len(remaining)):
                remaining[i] = substitute(remaining[i], newSubst)
            findAllSubstitutions(action, remaining, copySubst)
Exemple #4
0
def applyLA(action, substitution):
	global newState
	LA = deepcopy(action[4])
	subst = substitution[0]

	for i in range(len(LA)):
		LA[i] = substitute(LA[i], subst)
		name = get_head(LA[i])
		if not substitution[1] and name not in env and name not in math_predicates:
			if LA[i] not in newState:
				newState.append(LA[i])
	for subst in substitution[1]:
		for a in LA:
			a = substitute(a, subst)
			name = get_head(a)
			if name not in env and name not in math_predicates:
				if a not in newState:
					newState.append(a)
def applyLA(action, subst):
    global newState
    LA = action[3]
    for a in LA:
        a = substitute(a, subst)
        name = get_head(a)
        if name not in env and name not in math_predicates:
            if a not in newState:
                newState.append(a)
def applyLE(action, subst):
    global newState
    LE = action[4]
    for e in LE:
        e = substitute(e, subst)
        name = get_head(e)
        if e in newState:
            #print("found atom to remove " + str(e))
            newState.remove(e)
Exemple #7
0
def applyLE(action, substitution):
	global newState
	LE = deepcopy(action[5])
	subst = substitution[0]
	for i in range(len(LE)):
		LE[i] = substitute(LE[i], subst)
		name = get_head(LE[i])
		if name == 'isDirty':
			env['isDirty'].remove(LE[i])
		if LE[i] in newState:
			#print("found atom to remove " + str(e))
			newState.remove(LE[i])

	for subst in substitution[1]:
		for e in LE:
			e = substitute(e, subst)
			name = get_head(e)
			if e in newState:
				#print("found atom to remove " + str(e))
				newState.remove(e)
def preconditionsSatisfied(atoms):
    atom = atoms[0]
    #print("checking " + str(atom))
    name = get_head(atom)
    if name in env:
        #print("NAME IN ENV")
        facts = env[name]
    elif name in math_predicates:
        res = checkMathPredicates(name, atom)
        if res == True and len(atoms) == 1:
            return True
        elif res == True:
            return preconditionsSatisfied(atoms[1:])
        else:
            return False
    else:
        facts = state

    #print(facts)
    hasUnified = False

    for fact in facts:
        s = unify(atom, fact)
        #print("with " + str(fact) + " unify is " + str(s))
        if s != False and s != None:
            hasUnified = True
            #print("unify " + str(atom) + " with " + str(fact) + " under ")
            #print(s)
            if len(atoms) == 1:
                return True

            remaining = deepcopy(atoms[1:])
            for i in range(len(remaining)):
                remaining[i] = substitute(remaining[i], s)
            #print("remaining " + str(remaining))
            res = preconditionsSatisfied(remaining)
            if res == False:
                return False

    if hasUnified:
        return True
    return False
def findSubstitutions(action, atoms, subst, allSubst, state):
    if not atoms:
        #print("found subst " + str(subst))
        if len(subst) != 0:
            allSubst.append(subst)
        return True

    atom = atoms[0]
    name = get_head(atom)
    if name in env:
        facts = env[name]
    elif name in math_predicates:
        newSubst = {}
        res = checkMathPredicates(name, atom, newSubst)
        if res == False:
            return False
        else:
            if newSubst != {}:
                #TODO update the remaining with the newSubst?
                subst.update(newSubst)
            return findSubstitutions(action, atoms[1:], subst, allSubst, state)
    else:
        facts = state

    hasUnifiedWithAll = True

    for fact in facts:
        #TODO pot sa aplic newSubst in unify si sa nu mai fac remaining?
        newSubst = unify(atom, fact)
        if newSubst != False and newSubst != None:
            copySubst = deepcopy(subst)
            copySubst.update(newSubst)

            remaining = deepcopy(atoms[1:])
            for i in range(len(remaining)):
                remaining[i] = substitute(remaining[i], newSubst)
            res = findSubstitutions(action, remaining, copySubst, allSubst,
                                    state)
            if not res:
                hasUnifiedWithAll = False

    return hasUnifiedWithAll
Exemple #10
0
def apply_rule(rule, facts):
    # TODO
    subst = {}
    prem = {}
    ans = []
    values = {}
    fact_values = {}
    
    for fact in facts:
        vals = []
        for arg in get_args(fact):
            vals.append(get_value(arg))
        if get_head(fact) not in values:
            values[get_head(fact)] = [tuple(vals)]
        else:
            values[get_head(fact)].append(tuple(vals))
            
        if get_head(fact) not in fact_values:
            fact_values[get_head(fact)] = [fact]
        else:
            fact_values[get_head(fact)].append(fact)
    
    for r in get_premises(rule):
        if isinstance(r, Sentence):
            var = get_name(get_args(get_args(r)[0])[0])
            prm = get_head(get_args(r)[0])
            prem[(prm, var)] = get_args(r)[0]
            continue
        var = get_name(get_args(r)[0])
        prem[(get_head(r), var)] = [r]

    index_h = {}
    max_index_h = {}
    for (pred, var) in prem:
        index_h[(pred, var)] = 0
        max_index_h[(pred, var)] = 0
        if pred in values:
            max_index_h[(pred, var)] = len(values[pred])
    
    
    pred = []
    for x in prem:
        pred.append(x)
    current_p = 0
    subst = {}
    while 1:
        p = pred[current_p]
        prd = p[0]
        val = p[1]
        p_index = index_h[p]
            
        if p_index == max_index_h[p]:
            index_h[p] = 0
            
            if current_p == 0:
                break
                
            current_p = current_p - 1
            p = pred[current_p]
            
            for x in get_args(prem[p]):
                name = get_name(x)
                if name in subst:
                    del subst[name]
            index_h[p] = index_h[p] + 1
            continue
        
        b_subst = deepcopy(subst)
        
        aux_subst = unify(prem[p], fact_values[prd][p_index], subst)
        if aux_subst!=False:
            subst = aux_subst
            if current_p == len(pred) - 1:
                ans.append(substitute(get_conclusion(rule),subst))
                subst = {}
                current_p = 0
                
                next_index = index_h[p] + 1
                    
                index_h[p] = next_index
                p = pred[current_p]

                continue
        else:
            subst = b_subst
            index_h[p] = index_h[p] + 1
            if index_h[p] == max_index_h[p]:
                index_h[p] = 0
                current_p = current_p - 1
                index_h[pred[current_p]] = index_h[pred[current_p]] + 1
                p = pred[current_p]
                for x in get_args(prem[p]):
                    name = get_name(x)
                    if name in subst:
                        del subst[name]
            continue
            
        
        if current_p < len(pred) - 1:
            current_p = current_p + 1
            continue
        index_h[p] = index_h[p] + 1

    return ans
Exemple #11
0
def is_rule(formula):
    return get_head(formula) == 'or' or get_head(formula) == 'and'
def findBestAction(availableActions, path):
    # TODO
    global state, time
    cost = 0
    if 'Clean' in availableActions.keys():
        cost = get_value(availableActions['Clean'][0][0]['dim'])
        return ['Clean', 0, cost, cost]
    if 'Refill' in availableActions.keys():
        return ['Refill', 0, 1, 0]
    if 'Move' in availableActions.keys():
        substIndex = 0
        maxReward = -1
        cost = -1
        for subst in availableActions['Move']:
            moveCost = get_value(subst[0]['cost'])
            print('move cost ' + str(moveCost) + " time " + str(time))
            if moveCost > time:
                continue
            index = availableActions['Move'].index(subst)
            if len(path) >= 1 and getActionName(path[len(path) - 1]) == 'Move':
                args = getActionArgs(path[-1])
                #print("ARGS "  + str(args))
                if int(args[0]) == get_value(
                        subst[0]['r2']) and len(availableActions['Move']) > 1:
                    continue
            #TODO apply action
            # nu merge applyaction pentru ca ar modifica si env; asa schimb manual doar locatia
            #newState = applyAction(actions[0], subst)
            newState = deepcopy(state)
            for atom in newState:
                if get_head(atom) == 'location':
                    newState.remove(atom)
                    break
            newState.append(
                make_atom('location', make_const(get_value(subst[0]['r2']))))
            #TODO see available actions for the new states
            newAvailableActions = findAvailableActions(newState)
            print(newAvailableActions.keys())
            #TODO pick the best move
            if 'Clean' in newAvailableActions:
                cleanCost = get_value(
                    newAvailableActions['Clean'][0][0]['dim'])
                print("Clean cost " + str(cleanCost) + " max reward so far " +
                      str(maxReward))
                if 1000 + cleanCost - moveCost > maxReward and moveCost + cleanCost <= time:
                    maxReward = 1000 + cleanCost - moveCost
                    substIndex = index
                    cost = moveCost
            if 'Refill' in newAvailableActions:
                print("Refill" + " max reward so far " + str(maxReward))
                if 50 - moveCost > maxReward:
                    maxReward = 50 - moveCost
                    substIndex = index
                    cost = moveCost
            # if 'Move' in newAvailableActions and len(newAvailableActions['Move']) > 1: # daca nu e dead end
            # 	if 0 > maxReward:
            # 		maxReward = 0
            # 		substIndex = index
            # 		cost = moveCost
        print("chosen cost " + str(cost))
        if cost != -1:
            return ['Move', substIndex, cost, 0]
        else:
            substIndex = 0
            minCost = 9999
            for subst in availableActions['Move']:
                moveCost = get_value(subst[0]['cost'])
                if moveCost > time:
                    continue
                index = availableActions['Move'].index(subst)
                if len(path) >= 1 and getActionName(
                        path[len(path) - 1]) == 'Move':
                    args = getActionArgs(path[-1])
                    #print("ARGS "  + str(args))
                    if int(args[0]) == get_value(subst[0]['r2']) and len(
                            availableActions['Move']) > 1:
                        continue
                if moveCost < minCost:
                    substIndex = index
                    minCost = moveCost
            print("new chosen cost " + str(minCost))
            return ['Move', substIndex, minCost, 0]

    return [None, None, 0, 0]