def isConectorComponent(components): index = None i = 0 for component in components: if tokenizador(component) == 'conector': index = i break i += 1 return index
def modus_tollens(x, y): result = None if '~' in " ".join(x): component = x[1] if tokenizador(component) == 'atomo': if '->' in ' '.join(y): # array = prop2.remove('->') if component == y[2]: result = '~ '+y[0] return result
def modus_tollens(x, y): result = None if '~' in " ".join(x): component = x[1] if tokenizador(component) == 'atomo': if '->' in ' '.join(y): # array = prop2.remove('->') if component == y[2]: result = '~ ' + y[0] return result
def rules_negative(components, op): old_token = '' possible = False queue = Queue.LifoQueue() partial = [] formule = [] #Varrendo componentes for component in components: #TOKEN token = tokenizador(component) #Caso encontrado if possible: #Encontrando formula interna. if token == 'close_parentheses': queue.get(')') #Fim de formula interna if queue.empty(): #Verificar se em parcial tem op if op in " ".join(partial): result = elimination_negative_parentheses(partial, op) formule = formule + result else: formule.append('~') formule.append('(') formule = formule + partial formule.append(')') partial = [] possible = False else: partial.append(component) elif token == 'open_parentheses' and old_token == 'negative': possible = True queue.put(')') else: if token != 'negative' and not possible: if old_token == 'negative': formule.append('~') formule.append(component) old_token = token return formule
def rules_negative_double(components): older_token = '' count = 1 for component in components: token = tokenizador(component) if token == 'negative': if older_token == 'negative': components[count - 1] = '' components[count - 2] = '' older_token = token count += 1 return filter(None, components)
def calculate(formules): #Encontrar verdades new_formule = [] resp = [] dict = {} oposto = {} count = 0 size = len(formules) - 1 tic = 0 while count < size: for formule in formules: ispredicate, value = isPredicate(formule) if ispredicate: x = dict.get(formule) if x is None: if value: count += 1 dict[formule] = value dict['~' + formule] = not value else: res = formule.replace('~ ', '~') dict[res] = not value dict[res.replace('~', '').strip()] = value for formule in formules: aux = [] strformule = formule.replace('~ ', '~') for component in strformule.split(' '): token = tokenizador(component) if token == 'atomo': value = dict.get(component) if value is not None: aux.append(str(value)) else: aux.append(str(component)) else: aux.append(component) array = " ".join(aux).split(' v ') if len(array) > 1: if array[0] == 'True' or array[1] == 'True': count += 1 aux = ['True'] elif array[0] == 'False': aux = [array[1]] elif array[1] == 'False': aux = [array[0]] new_formule.append(" ".join(aux)) formules = new_formule resp = new_formule new_formule = [] result = '' for r in resp: if not result: result = r else: if r == 'False': result = 'False' elif r != 'True': result = r return result, dict
def run_inference_rules(propositions, conclusion): temp_num = 1 premissas = [] prop_to_temp = {} temp_to_prop = {} temps = [] for proposition in propositions: isFormuleInternal = False state_parentheses = False queue = Queue.LifoQueue() internal = [] partial = [] final = [] print proposition for component in proposition: state_parentheses = False print 'INCIANDO' print component token = tokenizador(component) #Verificando o componente é uma abertura if token == 'open_parentheses': print 'Iniciando formula interna' #Estado de abertura state_parentheses = True #Verifica se é uma formula interna interna if isFormuleInternal: print '+Interna' for p in partial: internal.append(p) partial = [] #Já é uma formula interna isFormuleInternal = True #Adicionando pendencia na pilha queue.put(")") elif token == 'close_parentheses': print 'Fim de formula interna - Criar Temporario' #Estado de Fechamento state_parentheses = True #Removendo pendencia na pilha queue.get(")") if queue.empty() and len(internal) > 0: partial = internal internal = [] formule = " ".join(partial) print 'String formule: '+formule #Verificando se já existe temporia com essa formula temp = prop_to_temp.get(formule) print 'TEMPORARIO' print temp #Se não existe temporario, vamos criar um novo if not temp: print 'Novo Temporario' temp = 'temp'+str(temp_num) temp_num += 1 prop_to_temp[formule] = temp temp_to_prop[temp] = formule temps.append(temp) print prop_to_temp size = len(internal) if size > 0: print 'Adicionando na formula interna' internal.append(temp) else: print 'Lista interna vazia. Adicionar na lista Final' final.append(temp) #verificando se a pilha ta vazia if queue.empty(): print 'Pilha vazia. Fim de formula interna' partial = [] isFormuleInternal = False if not isFormuleInternal and not state_parentheses: print 'Adicionar na final' final.append(component) else: if not state_parentheses: print "Adicionar na parcial" partial.append(component) print 'FIM DE PROPOSIçÂO' print final premissas.append(final) print premissas print prop_to_temp print temps i = 0 j = 0 stop = premissas print 'STOP' print stop #Aplicando regras de inferencias size = len(premissas) while len(stop) > 0 : print 'PREMISSAS: '+str(len(stop)) print premissas # if i == size: # break if j != i: print j print i result, rule = inference_machine(premissas[i], premissas[j], temps) if result: p1 = premissas[i] p2 = premissas[j] #Tenho resultado print 'CASO 1 :'+rule print 'Propositions: '+" ".join(p1)+' ---- '+" ".join(p2) print 'Resultado: '+result if result in temps: result = temp_to_prop.get(result) stop.remove(p1) stop.remove(p2) premissas.append(result.split(' ')) size = len(premissas) print 'PREMISSAS' print premissas i = 0 j = 0 else: if j >= size - 1: i += 1 j = 0 else: j +=1 else: if j < size -1: j +=1 else: break text ='' for premissa in premissas: text += " ".join(premissa) print text print ' '.join(conclusion) if " ".join(conclusion) == text: print "VERDADE" else: print "FALSO"
def broke_formule(promise, possibility, components): values = {} count = 0 result = None for component in components: values[str(component)] = possibility[count] count += 1 need_queue = Queue.LifoQueue() #Formule Final final_formule = [] internal_formule = [] partial_formule = [] state_parantheses = False new_list = False end_formule = False list_conectors = [] list_components = [] isFormuleInternal = False for p in promise: token = tokenizador(p) state_parentheses = False if token == 'open_parentheses': state_parantheses = True #Verifica se é uma formula interna interna if isFormuleInternal: for p in partial_formule: internal_formule.append(p) # internal_formule.append(partial_formule) partial_formule = [] #Salvar a lista parcial #Gerar nova lista #Já é uma formula interna isFormuleInternal = True #Adicionando pendencia na pilha need_queue.put(")") elif token == 'close_parentheses': state_parantheses = True need_queue.get(")") if need_queue.empty() and len(internal_formule) > 0: partial_formule = internal_formule internal_formule = [] count = len(internal_formule) result = resolverFormule(partial_formule, values, list_components, list_conectors) if count == 0: final_formule.append(result) else: internal_formule.append(result) if need_queue.empty(): partial_formule = [] isFormuleInternal = False if token == 'conector' and p not in list_conectors: list_conectors.append(p) if token == "atomo" and p not in list_components: list_components.append(p) #Condições de leituras: if not isFormuleInternal and not state_parantheses: #Adicionar na Final final_formule.append(p) else: if not state_parantheses: #Adicionar na Parcial partial_formule.append(p) if final_formule[0] == 'True' or final_formule[0] == 'False' and len( final_formule) == 1: return final_formule[0] result = resolverFormule(final_formule, values, list_components, list_conectors) return result
def rules_or(components): older_token = '' possible = False formule = [] partial = [] queue = Queue.LifoQueue() resolved = False internal = False point = False count = 0 update = False last_token = '' for component in components: token = tokenizador(component) if possible: if token == 'close_parentheses': queue.get(')') if queue.empty(): formule.append(partial) partial = [] internal = False update = True resolved = True formule = elimination_or(formule, last_p) aux = components[:point] formule = aux + formule possible = False if token == 'open_parentheses': queue.put(')') internal = True if token == 'conector': if component != '^' and not internal: possible = False if component == '^' and not internal: formule.append(partial) partial = [] if not resolved: if component == '^' and not internal: print 'ok' else: partial.append(component) else: if token == 'open_parentheses': if older_token == 'v': if last_token != '^': queue.put(')') possible = True formule = [] point = count - 2 if token == 'conector': last_token = older_token older_token = component if token == 'atomo': last_p = component count += 1 if update: return formule else: return components
def broke_formule(promise, possibility, components): values = {} count = 0 result = None for component in components: values[str(component)] = possibility[count] count += 1 need_queue = Queue.LifoQueue() #Formule Final final_formule = [] internal_formule = [] partial_formule= [] state_parantheses = False new_list = False end_formule = False list_conectors = [] list_components = [] isFormuleInternal = False for p in promise: token = tokenizador(p) state_parentheses = False if token == 'open_parentheses': state_parantheses = True #Verifica se é uma formula interna interna if isFormuleInternal: for p in partial_formule: internal_formule.append(p) # internal_formule.append(partial_formule) partial_formule = [] #Salvar a lista parcial #Gerar nova lista #Já é uma formula interna isFormuleInternal = True #Adicionando pendencia na pilha need_queue.put(")") elif token == 'close_parentheses': state_parantheses = True need_queue.get(")") if need_queue.empty() and len(internal_formule) > 0: partial_formule = internal_formule internal_formule = [] count = len(internal_formule) result = resolverFormule(partial_formule, values,list_components, list_conectors) if count == 0: final_formule.append(result) else: internal_formule.append(result) if need_queue.empty(): partial_formule = [] isFormuleInternal = False if token == 'conector' and p not in list_conectors : list_conectors.append(p) if token =="atomo" and p not in list_components: list_components.append(p) #Condições de leituras: if not isFormuleInternal and not state_parantheses: #Adicionar na Final final_formule.append(p) else: if not state_parantheses: #Adicionar na Parcial partial_formule.append(p) if final_formule[0] == 'True' or final_formule[0] == 'False' and len(final_formule) == 1: return final_formule[0] result = resolverFormule(final_formule, values,list_components, list_conectors) return result
def run(cls, propositions, conclusion): temp_num = 1 premissas = [] prop_to_temp = {} temp_to_prop = {} temps = [] for proposition in propositions: isFormuleInternal = False queue = Queue.LifoQueue() internal = [] partial = [] final = [] for component in proposition: state_parentheses = False token = tokenizador(component) #Verificando o componente é uma abertura if token == 'open_parentheses': #Estado de abertura state_parentheses = True #Verifica se é uma formula interna interna if isFormuleInternal: for p in partial: internal.append(p) partial = [] #Já é uma formula interna isFormuleInternal = True #Adicionando pendencia na pilha queue.put(")") elif token == 'close_parentheses': #Estado de Fechamento state_parentheses = True #Removendo pendencia na pilha queue.get(")") if queue.empty() and len(internal) > 0: partial = internal internal = [] formule = " ".join(partial) #Verificando se já existe temporia com essa formula temp = prop_to_temp.get(formule) #Se não existe temporario, vamos criar um novo if not temp: temp = 'temp'+str(temp_num) temp_num += 1 prop_to_temp[formule] = temp temp_to_prop[temp] = formule temps.append(temp) size = len(internal) if size > 0: internal.append(temp) else: final.append(temp) #verificando se a pilha ta vazia if queue.empty(): partial = [] isFormuleInternal = False if not isFormuleInternal and not state_parentheses: final.append(component) else: if not state_parentheses: partial.append(component) premissas.append(final) i = 0 j = 0 stop = premissas #Aplicando regras de inferencias size = len(premissas) case = 1 while len(stop) > 0 : if j != i: result, rule = inference_machine(premissas[i], premissas[j], temps) if result: p1 = premissas[i] p2 = premissas[j] #Tenho resultado print '*******************************************************' print 'CASO '+str(case)+' :'+rule print 'Propositions: '+" ".join(p1)+' ---- '+" ".join(p2) print 'Resultado: '+result print '*******************************************************' case += 1 if result in temps: result = temp_to_prop.get(result) stop.remove(p1) stop.remove(p2) premissas.append(result.split(' ')) size = len(premissas) print premissas print ' ' i = 0 j = 0 else: if j >= size - 1: i += 1 j = 0 else: j +=1 else: if j < size -1: j +=1 else: break text ='' for premissa in premissas: text += " ".join(premissa) if " ".join(conclusion[0]) == text: print "Verdade" else: print "Falsa"
def run_inference_rules(propositions, conclusion): temp_num = 1 premissas = [] prop_to_temp = {} temp_to_prop = {} temps = [] for proposition in propositions: isFormuleInternal = False state_parentheses = False queue = Queue.LifoQueue() internal = [] partial = [] final = [] print proposition for component in proposition: state_parentheses = False print 'INCIANDO' print component token = tokenizador(component) #Verificando o componente é uma abertura if token == 'open_parentheses': print 'Iniciando formula interna' #Estado de abertura state_parentheses = True #Verifica se é uma formula interna interna if isFormuleInternal: print '+Interna' for p in partial: internal.append(p) partial = [] #Já é uma formula interna isFormuleInternal = True #Adicionando pendencia na pilha queue.put(")") elif token == 'close_parentheses': print 'Fim de formula interna - Criar Temporario' #Estado de Fechamento state_parentheses = True #Removendo pendencia na pilha queue.get(")") if queue.empty() and len(internal) > 0: partial = internal internal = [] formule = " ".join(partial) print 'String formule: ' + formule #Verificando se já existe temporia com essa formula temp = prop_to_temp.get(formule) print 'TEMPORARIO' print temp #Se não existe temporario, vamos criar um novo if not temp: print 'Novo Temporario' temp = 'temp' + str(temp_num) temp_num += 1 prop_to_temp[formule] = temp temp_to_prop[temp] = formule temps.append(temp) print prop_to_temp size = len(internal) if size > 0: print 'Adicionando na formula interna' internal.append(temp) else: print 'Lista interna vazia. Adicionar na lista Final' final.append(temp) #verificando se a pilha ta vazia if queue.empty(): print 'Pilha vazia. Fim de formula interna' partial = [] isFormuleInternal = False if not isFormuleInternal and not state_parentheses: print 'Adicionar na final' final.append(component) else: if not state_parentheses: print "Adicionar na parcial" partial.append(component) print 'FIM DE PROPOSIçÂO' print final premissas.append(final) print premissas print prop_to_temp print temps i = 0 j = 0 stop = premissas print 'STOP' print stop #Aplicando regras de inferencias size = len(premissas) while len(stop) > 0: print 'PREMISSAS: ' + str(len(stop)) print premissas # if i == size: # break if j != i: print j print i result, rule = inference_machine(premissas[i], premissas[j], temps) if result: p1 = premissas[i] p2 = premissas[j] #Tenho resultado print 'CASO 1 :' + rule print 'Propositions: ' + " ".join(p1) + ' ---- ' + " ".join(p2) print 'Resultado: ' + result if result in temps: result = temp_to_prop.get(result) stop.remove(p1) stop.remove(p2) premissas.append(result.split(' ')) size = len(premissas) print 'PREMISSAS' print premissas i = 0 j = 0 else: if j >= size - 1: i += 1 j = 0 else: j += 1 else: if j < size - 1: j += 1 else: break text = '' for premissa in premissas: text += " ".join(premissa) print text print ' '.join(conclusion) if " ".join(conclusion) == text: print "VERDADE" else: print "FALSO"
def run(cls, propositions, conclusion): temp_num = 1 premissas = [] prop_to_temp = {} temp_to_prop = {} temps = [] for proposition in propositions: isFormuleInternal = False queue = Queue.LifoQueue() internal = [] partial = [] final = [] for component in proposition: state_parentheses = False token = tokenizador(component) #Verificando o componente é uma abertura if token == 'open_parentheses': #Estado de abertura state_parentheses = True #Verifica se é uma formula interna interna if isFormuleInternal: for p in partial: internal.append(p) partial = [] #Já é uma formula interna isFormuleInternal = True #Adicionando pendencia na pilha queue.put(")") elif token == 'close_parentheses': #Estado de Fechamento state_parentheses = True #Removendo pendencia na pilha queue.get(")") if queue.empty() and len(internal) > 0: partial = internal internal = [] formule = " ".join(partial) #Verificando se já existe temporia com essa formula temp = prop_to_temp.get(formule) #Se não existe temporario, vamos criar um novo if not temp: temp = 'temp' + str(temp_num) temp_num += 1 prop_to_temp[formule] = temp temp_to_prop[temp] = formule temps.append(temp) size = len(internal) if size > 0: internal.append(temp) else: final.append(temp) #verificando se a pilha ta vazia if queue.empty(): partial = [] isFormuleInternal = False if not isFormuleInternal and not state_parentheses: final.append(component) else: if not state_parentheses: partial.append(component) premissas.append(final) i = 0 j = 0 stop = premissas #Aplicando regras de inferencias size = len(premissas) case = 1 while len(stop) > 0: if j != i: result, rule = inference_machine(premissas[i], premissas[j], temps) if result: p1 = premissas[i] p2 = premissas[j] #Tenho resultado print '*******************************************************' print 'CASO ' + str(case) + ' :' + rule print 'Propositions: ' + " ".join( p1) + ' ---- ' + " ".join(p2) print 'Resultado: ' + result print '*******************************************************' case += 1 if result in temps: result = temp_to_prop.get(result) stop.remove(p1) stop.remove(p2) premissas.append(result.split(' ')) size = len(premissas) print premissas print ' ' i = 0 j = 0 else: if j >= size - 1: i += 1 j = 0 else: j += 1 else: if j < size - 1: j += 1 else: break text = '' for premissa in premissas: text += " ".join(premissa) if " ".join(conclusion[0]) == text: print "Verdade" else: print "Falsa"
def rules_negative_parentheses(components, op): older_token = '' possible = False formule = [] partial = [] queue = Queue.LifoQueue() resolved = False internal = False point = False count = 0 update = False for component in components: token = tokenizador(component) if possible: if token == 'close_parentheses': queue.get(')') if queue.empty(): formule.append(partial) partial = [] internal = False update = True resolved = True # if op in partial: formule = elimination_negative_parentheses(formule, op) aux = components[:point] formule = aux + formule possible = False if token == 'open_parentheses': queue.put(')') internal = True if token == 'conector': if component != op and not internal: possible = False if component == op and not internal: formule.append(partial) partial = [] if not resolved: if component == op and not internal: print 'ok' else: partial.append(component) else: if token == 'open_parentheses': if older_token == 'negative': queue.put(')') possible = True formule = [] point = count - 1 older_token = token count += 1 if update: return formule else: return components
def calculate(formules): #Encontrar verdades new_formule = [] resp = [] dict = {} oposto = {} count = 0 size = len(formules) - 1 tic = 0 while count < size : for formule in formules: ispredicate, value = isPredicate(formule) if ispredicate: x = dict.get(formule) if x is None: if value: count +=1 dict[formule] = value dict['~'+formule] = not value else: res = formule.replace('~ ', '~') dict[res] = not value dict[res.replace('~', '').strip()] = value for formule in formules: aux = [] strformule = formule.replace('~ ', '~') for component in strformule.split(' '): token = tokenizador(component) if token == 'atomo': value = dict.get(component) if value is not None: aux.append(str(value)) else: aux.append(str(component)) else: aux.append(component) array = " ".join(aux).split(' v ') if len(array) > 1: if array[0] == 'True' or array[1] == 'True': count +=1 aux = ['True'] elif array[0] == 'False': aux = [array[1]] elif array[1] == 'False': aux = [array[0]] new_formule.append(" ".join(aux)) formules = new_formule resp = new_formule new_formule = [] result = '' for r in resp: if not result: result = r else: if r == 'False': result = 'False' elif r != 'True': result = r return result, dict