def clielement(): """ CLI for the truth_table_generator package. """ parser = argparse.ArgumentParser() parser.add_argument('variables', help="List of variables e. g. \"['p', 'q']\"") parser.add_argument( '-p', '--propositions', help="List of propositions e. g. \"['p or q', 'p and q']\"" ) # NOQA long line parser.add_argument('-i', '--ints', default='True', help='True for 0 and 1; False for words') parser.add_argument('-a', '--ascending', default='False', help='True for reverse output (False before True)') args = parser.parse_args() variables = ast.literal_eval(args.variables) ints = ast.literal_eval(args.ints) asc = ast.literal_eval(args.ascending) print() if args.propositions is None: propositions = [] print(ttg.Truths(variables, propositions, ints, asc)) else: propositions = ast.literal_eval(args.propositions) print(ttg.Truths(variables, propositions, ints, asc)) print()
def t_t(number): list1 = list() for i in range(number): list1.append(str(i)) table = ttg.Truths(list1) list2 = table.as_pandas().values.tolist() return list2
def truth_table(number): list_temp = list() for i in range(number): list_temp.append(str(i)) table = ttg.Truths(list_temp) list2 = table.as_pandas().values.tolist() return list2
def mostrar_resultado(self): try: aux = cadena.proposicion(self.entrada.get()) var = cadena.variables(self.entrada.get()) prep = cadena.preposicionesConjugadas(self.entrada.get()) list(aux) prep.append(aux) table = ttg.Truths(var, [aux]) table2 = ttg.Truths(var, prep) print(aux) print(table2) print(table.valuation()) except BaseException: print('Entrada invalida')
def exportCircuit(self): ''' Exports the drawn circuit to the main GeneTech window: This evaluates the output of the circuit and converts it into boolean form. ''' #Evaluate each part as each part has its own boolean expression [part.evaluate_output() for part in self.circuit_builder.scene.parts] #Evaluate the output of the output part output = self.circuit_builder.circuit_output.evaluate_output( ) if self.circuit_builder.circuit_output else '' if not output: #if no output part is selected QMessageBox.critical(self, "Error", "Please select an output node") #### This transforms the output into standard sum of product form output = output.replace("''", "") output = output[ 1:-1] if output[0] == "(" and output[-1] == ")" else output # This creates the truth table table_val = ttg.Truths(['IPTG', 'aTc', 'Arabinose'], [output]) table = table_val.as_pandas() #Only select those rows which amount to True only_ones = table.loc[table.iloc[:, 3] == 1] sop = [] #All the product terms for itr, row in only_ones.iterrows(): #formatting the product term string_ = "IPTG{0}.aTc{1}.Arabinose{2}".format( "'" * row[0], "'" * row[1], "'" * row[2]) sop.append(string_) #Sum of all the products sop = "+".join(sop) #Hide the current window and show the main window, also process the expression self.hide() self.main_window.show() self.main_window.processDrawEquation(sop)
def get_table_truth(self): lista_variaveis = [] for a in range(self.num_variaveis): lista_variaveis.append(str(a)) tabela_verdade = ttg.Truths(lista_variaveis) df_variaveis = pd.DataFrame(tabela_verdade.as_pandas()) df_modificado = df_variaveis.replace(0, -1) colunas = df_modificado.columns n = 2 while n <= num_variaveis: combinacoes = combinations(colunas, r=n) for combinacao in combinacoes: nome_multi = combinacao[0] multi = df_modificado[combinacao[0]].values for j in range(1, len(combinacao)): nome_multi += combinacao[j] multi *= df_modificado[combinacao[j]].values df_modificado[nome_multi] = multi n += 1 return df_modificado
def generateTruth(self): # print(ttg.Truths(['p','q','r'],['(p or (~q)) => r'],ints=False)) # print(ttg.Truths(self.propVar, self.proposition, ints=False)) truth = ttg.Truths(self.propVar, self.proposition, ints=False) ans = truth.as_tabulate(index=False, table_format='html') return ans
def getResults(self): NgC = ttg.Truths(self.propVar, self.proposition, ints=True) res = NgC.as_pandas()[self.proposition].values.tolist() res = [str(i[0]) for i in res] res2 = "".join(res) return res2
def tautology_evaluator(): tautology_table = ttg.Truths(bases[0], formula[0]) tautology_pandas = tautology_table.as_pandas() tautology_models = 0 tautology_interpretation = tautology_pandas.values.tolist() tautology_expression = ttg.Truths( bases[0], formula[0]).as_pandas()[formula[0][0]].array for value in tautology_pandas[tautology_pandas.columns[-1]]: if value == 1: tautology_models += 1 print("\n ------------ Tautology Prover ------------") print(tautology_table) print("Number of models: ", tautology_models) print("Number of interpretations: ", len(tautology_interpretation)) get_evaluation(tautology_expression) print("\n ------------------- End -------------------") print("\n \n")
def problem1_solution(): for i in range(4): truth_table = ttg.Truths(cnf_bases[i], cnf_formula[i]) pandas_table = truth_table.as_pandas() models = 0 for value in pandas_table[pandas_table.columns[-1]]: if value == 1: models += 1 interpretations = ttg.Truths( cnf_bases[i], cnf_formula[i]).as_pandas()[cnf_formula[i]].values.tolist() expression = ttg.Truths( cnf_bases[i], cnf_formula[i]).as_pandas()[cnf_formula[i][0]].array print("\n", text[i]) print(truth_table) print("Number of models: ", models) print("Number of interpretations: ", len(interpretations)) get_evaluation(expression)
def contradiction_evaluator(): contradiction_table = ttg.Truths(bases[2], formula[2]) contradiction_pandas = contradiction_table.as_pandas() contradiction_models = 0 contradiction_interpretation = contradiction_pandas.values.tolist() contradiction_expression = ttg.Truths( bases[2], formula[2]).as_pandas()[formula[2][0]].array for value in contradiction_pandas[contradiction_pandas.columns[-1]]: if value == 1: contradiction_models += 1 print( "\n --------------------- Contradiction Prover ----------------------") print(contradiction_table) print("Number of models: ", contradiction_models) print("Number of interpretations: ", len(contradiction_interpretation)) get_evaluation(contradiction_expression) print( "\n ------------------------------ End ------------------------------") print("\n \n")
def mostrar_resultado(self): try: aux = cadena.proposicion(self.entrada.get()) var = cadena.variables(self.entrada.get()) table = ttg.Truths(var, [aux]) print(aux) print(table) print(table.valuation()) except BaseException: print('Entrada invalida')
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) raw = ttg.Truths(['p', 'q', 'r'], ['p and q and r', 'p or q or r', '(p or (~q)) => r']) context['pira_table_truths'] = raw #print(raw) #print(type(raw)) raw_ = str(raw) raw_ = raw_.replace('+', '').replace('-', '').replace( '||', '').replace(' ', '').replace('and', ' & ').replace('or', ' ó ').replace('\n', '') print(raw_) raw_arr = raw_.split('|') raw_arr.remove('') #print(raw_arr) context['pira_array'] = raw_arr return context
import ttg print("*** Truth Or Not ***") print(ttg.Truths([chr(i) for i in range(97, 97 + int(input("Bases: ")))]))
import ttg prop = [p for p in input('[+]ENTER THE PROPOSITIONS SEPERATED WITH SPACE: \n |\n |\n |\n |------[+] ').strip().split()] con = [c for c in input('\n[+]ENTER THE CONDITION(s) SEPERATED WITH HYPHEN(-): \n |\n |\n |\n |------[+] ').strip().split('-')] try: print('\n'+'-'*21+'TRUTH TABLE'+'-'*21) print(ttg.Truths(prop , con)) except: print('\n'+'-'*17+'DEFAULT TRUTH TABLE'+'-'*17) print(ttg.Truths(['p', 'q'] , ['p or q', 'p and q', 'p = q', 'p=>q']))
import ttg import numpy as np #exp = '((-A) and (-D)) or (B and (-D)) or (E and B and C) or (E and C and (-D)) or ((-E) and (-B) and (-C) and D)' exp = '(B and C and E) or (C and (-D) and E) or ((-A) and (-B) and (-C) and (-E)) or ((-B) and (-C) and D and (-E)) or (B and (-C) and (-D) and (-E))' table = ttg.Truths(['A', 'B', 'C', 'D', 'E'], [exp]) print(table.as_prettytable()) print( np.array(table.as_pandas_minterms()[exp].tolist()) * list(range(len(table.as_pandas_minterms())))) #printTrue = lambda l: print([l.index(i) for i in l if i==1]) #printTrue(table.as_pandas()[exp].tolist())
#returns the names of the files in the directory data as a list ###### Подготовильтельный блок list_of_files = os.listdir("dsa_almaz_s2p_file"); # директория CellPath = os.listdir("dsa_almaz_s2p_file"); Num_Of_Bits=int(len(list_of_files)/2); # Определили число битов в комбинации; #Создаем таблицу истинности # Лист битов ['Bit0', 'Bit1', 'Bit2', 'Bit3', 'Bit4', 'Bit5'] BitList = []; for i in range(0,Num_Of_Bits,1): BitList.append(str('Bit'+str(i))); #Таблица истинности Bit = ttg.Truths(BitList, ascending=True) # развенутная , младший - бит последний ###### Таблица Истиности готова; print(Bit); number_of_states = 2**Num_Of_Bits; ## число состояний #Надо разобрать еще все файлы, Cell_Name_List = []; Cell_P1dB_List = []; Cell_Truth_List = []; ################################ PhaseStep = 360/(2**Num_Of_Bits); NormalPhaseList= []; for state in range(number_of_states): Phase = state*PhaseStep; NormalPhaseList.append(Phase); #####################################
# This code demostrates the use of the ttg package which is helpful in generating TT # In this code, I make use of the example in Pg 119 of Taub and Schilling to demontrate how redundant minterms can be avoided in a K-Map #%% import ttg print( ttg.Truths(['A', 'B', 'C', 'D'], [ 'A and (~C) and (~D)', '(~A) and (~B) and C', '(~B) and C and (~D)', 'A and (~B) and (~D)' ])) # The final expression can be written as in eqn 3.20-8 (making use of eqn 3.20-6) print( ttg.Truths(['A', 'B', 'C', 'D'], [ '(A and (~C) and (~D)) or ((~A) and (~B) and C) or ((~B) and C and (~D))' ])) # The final expression can also be written making use of eqn 3.20-7 print( ttg.Truths(['A', 'B', 'C', 'D'], [ '(A and (~C) and (~D)) or ((~A) and (~B) and C) or (A and (~B) and (~D))' ])) # The final expression can also be written making use of both eqn 3.30-6 and eqn 3.20-7 (sum) # This has more terms than neccessary and therefore uses more logic gates. print( ttg.Truths(['A', 'B', 'C', 'D'], [ '(A and (~C) and (~D)) or ((~A) and (~B) and C) or (A and (~B) and (~D)) or ((~B) and C and (~D))' ]))
# importing truth table generator module import ttg import pandas print(ttg.Truths(['p', 'q', 'r'])) exp1 = 'p and q and r' exp2 = 'p or q or r' exp3 = '(p or (~q)) => r' table1 = ttg.Truths(['p', 'q', 'r'], [exp1, exp2, exp3]) print(table1) print(table1.as_prettytable()) print(table1.as_tabulate(index=False, table_format='latex')) table1.as_pandas() table1.as_pandas().style.set_properties(**{ 'text-align': 'center' }).hide_index() print(table1.as_tabulate()) print(table1.as_tabulate(index=False)) print(table1.valuation()) print(table1.valuation(4)) table2 = ttg.Truths(['p', 'q', 'r'], [exp1, exp2, exp3], ints=False) print(table2)
import ttg exp = '(B AND C AND E) OR (C AND NOT D AND E) OR (NOT A AND NOT B AND NOT C AND NOT E) OR (NOT B AND NOT C AND D AND NOT E) OR (B AND NOT C AND NOT D AND NOT E)' toLowerExp = lambda s: s.lower() if s in ["AND", "OR", "NOT", "(NOT"] else s exp = " ".join([toLowerExp(i) for i in exp.split(" ")]) table = ttg.Truths(['A', 'B', 'C', 'D', 'E']) tableSOP = ttg.Truths(['A', 'B', 'C', 'D', 'E'], [table.SOP([0, 2, 5, 8, 13, 15, 18, 21, 24, 29, 31])]) print("SOP") print(tableSOP.as_prettytable()) tableMin = ttg.Truths(['A', 'B', 'C', 'D', 'E'], [exp]) print("MIN") print(tableMin.as_prettytable()) toUpperExp = lambda s: s.upper() if s in ["and", "or", "not", "(not"] else s outExp = table.SOP([0, 2, 5, 8, 13, 15, 18, 21, 24, 29, 31]) outExp = " ".join([toUpperExp(i) for i in outExp.split(" ")]) outExp = outExp.replace("~", "NOT ") print(outExp)
import ttg print(ttg.Truths(['p1', 'p2', 'p3'], ['(p1 and(not p2)) => p3']))
import ttg """ print(ttg.Truths(['p', 'q', 'r'], ['p and q and r', 'p or q or r', '(p or (~q)) => r'])) print(ttg.Truths(['p', 'q'], ['p and q', 'p or q', '(p or (~q)) => (~p)'], ints=False)) Operators and their representations: negation: 'not', '-', '~' logical disjunction: 'or' logical nor: 'nor' exclusive disjunction: 'xor', '!=' logical conjunction: 'and' logical NAND: 'nand' material implication: '=>', 'implies' logical biconditional: '=' Note: Use parentheses! Especially with the negation operator. (not(p and q))or r """ print(ttg.Truths(['p', 'q', 'r'],['(~(p and q))','(~(p and q))' ' or r'],ints=False)) print(ttg.Truths(['p', 'q', 'r'],['(~(p and q))''or r'],ints=False))
import ttg print( 'Conjuncao -> and\nDisjuncao -> or\nImplicacao -> =>\nBi-implicacao -> =\nNegacao -> -\nParenteses -> ( )' ) while True: numProp = int(input("\nNumero de proposicoes: ")) p = str(input("Digite o radical 1: ")) if numProp >= 2: q = str(input("Digite o radical 2: ")) if numProp >= 3: r = str(input("Digite o radical 3: ")) if numProp >= 4: s = str(input("Digite o radical 4: ")) if numProp == 1: table = (ttg.Truths([p], [input("\nDigite a sentenca: ")], ints=False)) elif numProp == 2: table = (ttg.Truths([p, q], [input("\nDigite a sentenca: ")], ints=False)) elif numProp == 3: table = (ttg.Truths([p, q, r], [input("\nDigite a sentenca: ")], ints=False)) elif numProp == 4: table = (ttg.Truths([p, q, r, s], [input("\nDigite a sentenca: ")], ints=False)) print(table) print("Esta expressao e uma " + table.valuation())