Ejemplo n.º 1
0
Archivo: main.py Proyecto: dtbinh/stuff
def resolve(Ci, Cj):
	print "resolve",
	Ci.printClause()
	print " and",
	Cj.printClause()
	print " got:",

	#print""
	#print "Ci:",
	#Ci.printClause()
	#print""
	#Ci.vars = removeDuplicates(Ci.vars)
	#print "after remove dups:",
	#Ci.printClause()
	#print""

	#print "Cj:",
	#Cj.printClause()
	#print ""
	#print "after remove dups:",
	#Cj.printClause()
	#print""

	Cj.vars = removeDuplicates(Cj.vars)

	# eg. p and ~p are complimentary vars. The new resolved clause will not have p OR ~p.
	complimentaryVars = getComplimentaryVars(Ci, Cj)
	compVar = complimentaryVars[0]

	#make a new clause that is void of the complimentary variables and duplicates
	varsInCi = copy.deepcopy(Ci.vars)
	varsInCj = copy.deepcopy(Cj.vars)
	for var in varsInCi:
		if var.name == compVar:
			varsInCi.remove(var)
	for var in varsInCj:
		if var.name == compVar:
			varsInCj.remove(var)

	#new vars has the set of vars for the new clause.  All complimentary vars have been removed
	newVars = varsInCi + varsInCj
	newVars = removeDuplicates(newVars)

	parents = []
	parents.append(Ci.number)
	parents.append(Cj.number)
	#make a new clause from the two clauses that we have resolved together
	#note: clause number is set to 0, we assign real clause number when we add it to the KB
	resolvent = Clause(0, newVars, parents)

	resolvent.printClause()
	print ""

	return resolvent
Ejemplo n.º 2
0
def resolve(Ci, Cj):
    print "resolve",
    Ci.printClause()
    print " and",
    Cj.printClause()
    print " got:",

    #print""
    #print "Ci:",
    #Ci.printClause()
    #print""
    #Ci.vars = removeDuplicates(Ci.vars)
    #print "after remove dups:",
    #Ci.printClause()
    #print""

    #print "Cj:",
    #Cj.printClause()
    #print ""
    #print "after remove dups:",
    #Cj.printClause()
    #print""

    Cj.vars = removeDuplicates(Cj.vars)

    # eg. p and ~p are complimentary vars. The new resolved clause will not have p OR ~p.
    complimentaryVars = getComplimentaryVars(Ci, Cj)
    compVar = complimentaryVars[0]

    #make a new clause that is void of the complimentary variables and duplicates
    varsInCi = copy.deepcopy(Ci.vars)
    varsInCj = copy.deepcopy(Cj.vars)
    for var in varsInCi:
        if var.name == compVar:
            varsInCi.remove(var)
    for var in varsInCj:
        if var.name == compVar:
            varsInCj.remove(var)

    #new vars has the set of vars for the new clause.  All complimentary vars have been removed
    newVars = varsInCi + varsInCj
    newVars = removeDuplicates(newVars)

    parents = []
    parents.append(Ci.number)
    parents.append(Cj.number)
    #make a new clause from the two clauses that we have resolved together
    #note: clause number is set to 0, we assign real clause number when we add it to the KB
    resolvent = Clause(0, newVars, parents)

    resolvent.printClause()
    print ""

    return resolvent
Ejemplo n.º 3
0
    def resolve(self, c1, c2, literal):
        self.numResolve += 1
        ret = []
        ret.extend(c1.literals)
        ret.extend(c2.literals)
        ret.remove(literal)
        ret.remove(-literal)
        ret_clause = Clause()
        ret_clause.literals = list(set(ret))

        print(c1.to_string(), c2.to_string(), ret_clause.to_string(), literal)
        return ret_clause
Ejemplo n.º 4
0
 def build(self, premise):
     list1 = self._format(premise)
     for item in list1:  # 每个item 是一个字典,如 { "Term1":"3" , "judge(A,pay):"1" }
         cls = Clause()
         # print('item:', item) #DEBUG
         for key in item:  # item 的每个key 是 contractLiteralID
             conLitID, flag, num = key.partition('#')
             conLitID = conLitID.lstrip().rstrip()
             #print('conLitID:', conLitID) #DEBUG
             val = item[key]
             lit = self._newLiteral(conLitID, val)
             # print('literal:', lit.getID(), lit.getConLiteralID(), lit.getStatus()) #DEBUG
             cls.addLiteral(lit)
         self._clauseSet.append(cls)
     self._updateSATCore()
Ejemplo n.º 5
0
def read_knowledge_base(file_name, initial_clause_weight=0.5):
    """Initialize the knowledge base.

    :param file_name: the path of the knowledge base file. The file must contain:
        - a row with the list of predicates
        - a set of constraints. Each constraint is on the form:
        clause_weight:clause

        The clause_weight should be either a real number (in such a case this value is fixed) or an underscore
        (in this case the weight will be a tensorflow variable and learned during training).

        The clause must be represented as a list of literals separated by commas (that represent disjunctions).
        Negation must specified by adding the letter 'n' before the predicate name.

        An example:
           _:nDog,Animal

    :param initial_clause_weight: the initial value to the clause weights. Used for the clause precedeed by an
        underscore
    :return: the lists of clauses in the knowledge base
    """
    with open(file_name, 'r') as kb_file:
        unary_literals_string = kb_file.readline()
        kb_file.readline()
        rows = kb_file.readlines()

    u_groundings = unary_literals_string[:-1].split(',')

    unary_clauses = []

    for r in rows:
        unary_clauses.append(
            Clause(u_groundings, r[:-1], initial_clause_weight))

    return unary_clauses
Ejemplo n.º 6
0
 def consult(self, dir):
     with open(dir, 'r') as f:
         lines = f.readlines()
         for line in lines:
             temp = Clause.generate_from_string(line)
             if temp.get_number_of_units() == 1:
                 self.facts.append(temp)
             else:
                 self.rules.append(temp)
Ejemplo n.º 7
0
    def query(self, inp, out):
        with open(inp, 'r') as f:
            lines = f.readlines()

        algodict = [forward_chain, backward_chain, resolution]
        with open(out, 'w') as f:
            for line in lines:
                algoid = int(line[0])
                query = Clause.generate_from_string(line[1:])
                print('Query: ', query)
                self.export(f, algodict[algoid], query)
                now = time.time()
                print('Querying takes {} (s)'.format(time.time() - now))
    def resolve(self, c1, c2):
        self.numResolve += 1
        set1 = set(c1.literals)
        ret = []
        n_pairs = 0
        for x in c2.literals:
            if -x in set1:
                set1.remove(-x)
                n_pairs += 1
            else:
                ret.append(x)
        for x in set1:
            ret.append(x)

        if n_pairs != 1:
            return c1

        ret_clause = Clause()
        ret = sorted(ret, key=abs)
        ret_clause.literals = ret

        #print(c1.to_string(), c2.to_string(), ret , ret_clause.to_string())
        return ret_clause
Ejemplo n.º 9
0
def CreateKB(contradiction):

    KB.append(Clause([contradiction]))

    KB.append(Clause([Litteral("a"), Litteral("b", False)]))

    KB.append(Clause([Litteral("a"), Litteral("c", False)]))

    KB.append(Clause([Litteral("b"), Litteral("b", False)]))

    KB.append(Clause([Litteral("b"), Litteral("c", False)]))

    KB.append(Clause([Litteral("b"), Litteral("c", False)]))

    KB.append(Clause([Litteral("c")]))

    KB.append(Clause([Litteral("d")]))
 def add_clause(self, clause, form=0):
     print(clause, form)
     c = Clause(clause, form)
     print("Clause ", c.to_string())
     if form == 1:
         c.negate()
         clauses = [Clause(c.int2literal(x)) for x in c.literals]
         print("Hello")
         for clause in clauses:
             self.clauses.append(clause)
             print(clause.to_string())
         print("End hello")
     else:
         self.clauses.append(c)
Ejemplo n.º 11
0
Archivo: init.py Proyecto: t409wu/stuff
def getClausesFromFile(KBFileName):

    # container for the clauses we are going to grab
    clauses = []

    #each clause will be given a number to help keep track of it
    clauseNumber = 0

    KBFile = open(KBFileName)
    lines = KBFile.readlines()

    #for every line in the file make a new clause
    for line in lines:

        clauseNumber += 1

        # tokenize the line
        tokens = line.split()

        # for every token in line make a new variable. A clause is made up of these variables.
        variables = []
        for token in tokens:

            #see if there is a ~ for this variable
            neg = False
            name = ""
            if token[0] == '~':
                neg = True
                name = token.replace("~", "")
            else:
                name = token

            newVar = Variable(name, neg)

            variables.append(copy.deepcopy(newVar))
            # end token loop

        # now take that list of variables and use it to make a clause.  Clauses are numbered sequentially in the
        # order they are made/listed in the knowledge base file
        newClause = Clause(clauseNumber, variables)

        clauses.append(copy.deepcopy(newClause))
        #end line loop

    return clauses
Ejemplo n.º 12
0
            for Cj in KB:
                if Ci != Cj:
                    if len(getComplimentaryVars(Ci, Cj)) != 0:
                        resolvent = resolve(Ci, Cj)

                        # check to sees if the resolvent is the empty clause
                        # if we have an empty clause, then alpha is valid var in alpha is accounted for
                        # not a single var in ~alpha is satisfiable because it has been cancelled out
                        if len(resolvent.vars) == 0:
                            print "alpha is valid\n"
                            falseVar = Variable("False", False)
                            falseVars = []
                            falseVars.append(falseVar)
                            emptyClause = Clause(
                                len(KB) + 1,
                                falseVars,
                                resolvent.parents,
                            )
                            KB.append(copy.deepcopy(emptyClause))
                            print "the knowledge base"
                            for clause in KB:
                                clause.printClause()
                                print ""
                            print ""
                            tree = getProofTree()
                            outputToFile(commandLineArgs.KBFileName, tree)
                            sys.exit(0)

                        #if this clause is not already defined in the list of new clauses, then
                        # we add it to the set
                        if isInNewClauses(resolvent) == False:
Ejemplo n.º 13
0
 def addClause(self, clause):
     self.ClauseArray.append(Clause(clause))