Example #1
0
def old_boolean_func_from_coop_binding(world, channels, bindings):
    """Convert a coop binding into a boolean function"""
    # Can't assume all sites are unique, so we need to reconstruct a truth
    # table entries to pool together sites that are the same.
    unique = list(set(channels))
    indexes = {unique[i]: i for i in range(len(unique))}

    # Generate all possible states
    all_states = [_ for _ in itertools.product([0, 1], repeat=len(bindings))]

    # We'll put the truth table entries that are TRUE into this
    is_true = []
    for state in all_states:
        # We squash our entries down to the unique entries
        entry = [0] * len(unique)
        summed = 0
        for s, c, b in zip(state, channels, bindings):
            # If the current column entry is true...
            if s:
                # ... make sure the corresponding entry is true
                entry[indexes[c]] = 1
                # And add the binding strength in
                summed += b

        # This tracks what we do in the cpp class ...
        if summed >= len(bindings):
            is_true.append(entry)

    # This should be possible, but sympy barfs on 'E1' for some bizarre reason
    # names = [world.name_for_channel(u) for u in unique]
    # So, we use simple names and the replace at the end...
    names = list('abcdefghijklmnopqrstuvwxyz')[:len(unique)]
    sop = SOPform(names, is_true)

    # Now force the 0 and 1 (on and off channels) to be evaluated
    for i, u in enumerate(unique):
        # off channel
        if u == 0:
            # This is ALWAYS OFF
            sop = sop.subs(names[i], 0)
        # On channel
        if u == 1:
            # This is ALWAYS ON
            sop = sop.subs(names[i], 1)

    # Simplify the logic again
    sop = simplify_logic(sop)

    if sop == False:
        return "OFF"
    if sop == True:
        return "ON"

    text = detex(sop)

    # Necessary cos of the E1 problem
    for i, n in enumerate(names):
        text = text.replace(n, world.name_for_channel(unique[i]))

    return text
Example #2
0
File: tcc.py Project: fsMateus/fsm
def calcula_custo(bitin, bits, entradas, mintermos, individuo):

    n = bits + bitin
    dontcares = obter_dontcare(entradas, bits, individuo)

    var = list(string.ascii_lowercase[:n])

    test = symbols(var)
    #a, b, c, d, e = symbols('a b c d e')

    resultado = SOPform(test, mintermos, dontcares)

    expressao = str(resultado)
    #print(resultado)

    #custo = []
    termos = expressao.count('|') + 1
    cont = 0
    for i in expressao:
        if i in var:
            cont += 1

    cont += termos
    #print(cont)
    #custo.append(cont)

    # custo_total = 0
    # for j in custo:
    #     custo_total += j

    #custo_total += len(resultado)
    return cont, termos, expressao
Example #3
0
def exactly_one_permutation_of_actions(curr_teams, teams_actions):
    if len(teams_actions) == 1:
        return [teams_actions]

    if curr_teams >= len(teams_actions):
        return [[act] for act in teams_actions]

    symbols_string = (" ".join([str(act) for act in teams_actions]))
    symbols_sympy = symbols(symbols_string)
    all_and_combinations = [
        POSform(comb, minterms=[{symbol: 1
                                 for symbol in comb}])
        for comb in combinations(symbols_sympy,
                                 min(curr_teams, len(teams_actions)))
    ]

    sop = SOPform(all_and_combinations,
                  minterms=[{
                      comb: 1
                  } for comb in all_and_combinations])
    exactly_one_perm_clauses = True
    if len(
            teams_actions
    ) > curr_teams:  # more actions than teams, has to choose one exactly permutation
        for set1, set2 in combinations(sop.args, 2):
            exactly_one_perm_clauses = And(exactly_one_perm_clauses,
                                           Or(Not(set1), Not(set2)))
    final_cnf = to_cnf(And(exactly_one_perm_clauses, sop))
    return cnf_with_boolean_symbols_to_valid_clauses(final_cnf)
Example #4
0
def main():
    mod = 3
    operation = mod_mult
    #operation = mod_add

    num_bits = math.ceil(math.log(mod, 2))

    dontcares = generate_dontcares(num_bits, mod)

    for index in range(0, num_bits):
        print("Minimized Sum of Products (SOP) boolean expression for c" +
              str(index))

        # Create a list of inputs where the output is 1
        minterms = []
        for a in GrayCode(num_bits).generate_gray():
            for b in GrayCode(num_bits).generate_gray():
                if b + a in dontcares:
                    continue
                if operation(a, b, mod)[-(index + 1)] == '1':
                    minterms += [b + a]

        # Transform dontcares and minterms into format required by SOPform
        transformed_dontcares = [[int(c) for c in el] for el in dontcares]
        transformed_minterms = [[int(c) for c in el] for el in minterms]

        #Prepare a symbol string e.g. 'b2, b1, b0, a2, a1, a0'
        symbol_string = ', '.join(
            [c + str(i) for c in ['a', 'b'] for i in range(num_bits)][::-1])

        solution = SOPform(symbols(symbol_string), transformed_minterms,
                           transformed_dontcares)
        evaluate(solution)
Example #5
0
            def teams_clauses(curr_num_teams, team_locs):
                if len(team_locs) == 1:
                    return [team_locs]

                syms = ''
                for i in team_locs:
                    syms += str(i) + ' '

                symbs = symbols(syms)
                and_groups = [
                    POSform(group, minterms=[{symb: 1
                                              for symb in group}])
                    for group in combinations(
                        symbs, min(curr_num_teams, len(team_locs)))
                ]

                SOP = SOPform(and_groups,
                              minterms=[{
                                  group: 1
                              } for group in and_groups])

                Xor_group = True
                if len(team_locs) > curr_num_teams:
                    for clause1, clause2 in combinations(SOP.args, 2):
                        Xor_group = And(Xor_group,
                                        Or(Not(clause1), Not(clause2)))

                final_teams_cnf = to_cnf(And(Xor_group, SOP))
                return cnf_to_clauses(final_teams_cnf)
def build_sympy_expr(net, ip):
    ip_vars = ['ip_{}'.format(i) for i in range(ip)]
    ip_syms = symbols(" ".join(ip_vars))
    syms = {i: x for i, x in enumerate(ip_syms)}
    for i, layer in enumerate(net.layers):
        expr = dict()
        for j, neuron in enumerate(layer):
            if neuron is not None:
                reqd_syms = [syms[ip_num] for ip_num in neuron.inputs]
                expr[j] = SOPform(reqd_syms, neuron.minterms(),
                                  neuron.dont_cares())
        syms = expr
    return ip_vars, ip_syms, syms[0]
from sympy.logic import simplify_logic
from sympy.abc import x, y, z
from sympy import S

from sympy.logic import SOPform
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
            [1, 1, 1, 1]]
dontcares = [[1, 1, 0, 1], [0, 0, 0, 0], [0, 0, 1, 0]]
SOPform(['w', 'x', 'y', 'z'], minterms, dontcares)

from sympy.logic import POSform
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
            [1, 1, 1, 1]]
dontcares = [[1, 1, 0, 1], [0, 0, 0, 0], [0, 0, 1, 0]]
POSform(['w', 'x', 'y', 'z'], minterms, dontcares)

expr = '(~x & y & ~z) | ( ~x & ~y & ~z)'
simplify_logic(expr)
S(expr)
simplify_logic(_)
Example #8
0
    #    tt = np.random.randint(2, size=8, dtype=bool)
    tt = np.array([False, True, True, True, False, False, True, True])
    print(tt.tolist())
    print(tt.tolist(), file=logfile)
    g = GP(
        num_vars=int(np.log2(tt.shape[0])),
        unique_pop=opt.unique_pop,
        bin_ops=(sympy.And, sympy.Or),
        target_tt=tt,
        pop_size=opt.pop_size,
        size_next_gen=opt.size_next_gen,
        lucky_per=opt.lucky_per,
        weight_num_gates=opt.weight_num_gates,
        weight_num_agree=opt.weight_num_agree,
        add_naive=opt.add_naive,
    )
    fn = g.util.syms[0] | (g.util.syms[1] & (~g.util.syms[2] | g.util.syms[0]))
    srepr = sympy.srepr(fn)
    mt = tt_to_sympy_minterms(g.util.target_tt)
    sop_form = SOPform(g.util.syms, mt)

    try:
        g.run(num_generations=opt.num_generations,
              init_pop_size=opt.init_pop_size)
        # g.run()
    except KeyboardInterrupt:
        pass
    g.print_best(logfile)

    # g.util.pool.terminate()  # terminated on this process's death, or so it seems
    n1 = source_nodes[_i]
    for _j in range(_i + 1, len(source_nodes)):
        n2 = source_nodes[_j]
        if check_branch_equality(G, n1, n2):
            equality_graph.add_edge(n1, n2)

aggregated_source_nodes = list(nx.connected_components(equality_graph))
asn_sop = []

for asn in aggregated_source_nodes:
    minterms = []
    for node in asn:
        asn_dict = label2dict(G.nodes[node]['label'])
        minterms.append(get_minterm(asn_dict))
    syms = sorted(list(asn_dict.keys()))
    asn_sop.append(SOPform(symbols(syms), minterms))
    print(asn_sop[-1])

# --------------------------------------------------------
# Some stable motifs may not depend on input nodes. These should
# have identical branches, regardless of which asn they stem
# from. In these cases, they can be removed and put as top-level
# stable motifs

# I will pick one asn, pick a random source node (they should all be identical within an asn). I will loop over all its child nodes. Then I will loop over each other asn, and pick a random source node (again, they should be identical).

found_matching_motifs = dict(
)  # Keep track of whether or not a matching asn has been found

asn_reference = list(aggregated_source_nodes[0])
for edge in G.edges(asn_reference[0]):  # Loop over 2nd level nodes
Example #10
0
       [0, 1, 0],
       [0, 1, 1],
       [1, 0, 0],
       [1, 0, 1],
       [1, 1, 0],
       [1, 1, 1]]
    
if __name__== "__main__":
    vec = np.array([int(vec) for vec in input("input vec").split()]) #ввод вектора исходной функции
    #vec = np.array([1, 1, 0, 1, 1, 0, 0, 1])
    if len(vec) == 8:    #если количество элементов исходного вектора не равно 8 то программа не будет выполняться
        for i in range(len(vec)):
            if vec[i]:
                minterms += [xyz[i]] #заполнеие списка значениемями таблицы истинности при которых значения вктора равно 1
            else:
                dontcares += [xyz[i]] #заполнеие списка значениемями таблицы истинности при которых значения вктора равно 0
        r = pd.DataFrame(minterms) # инициализация таблицы для вывода сднф
        for i in range(len(minterms)): #инверсия элементов таблицы
            for j in range(3):
                if r.iloc[i, j]:
                    r.iloc[i, j] = 0
                else:
                    r.iloc[i, j] = 1
        #выполнение сднф
        sdnf = (r.apply(lambda r: '({}&{}&{})'.format('~'*r[0] + 'x', '~'*r[1] + 'y', '~'*r[2] + 'z'), axis=1).str.cat(sep = ' | '))
        print("СДНФ:")
        print(sdnf) #вывод сднф пользователю
        print("Минимизированная ДНФ")
        print(SOPform([x, y, z], minterms)) #вывод минимизированной сднф
    
  
Example #11
0
from sympy import *
from sympy.logic import SOPform
from sympy import symbols
x, y = symbols('x,y')
print( y | (x & y))
print( x >> y)
print(x | y)
print( ~x)
print((y & x).subs({x: True, y: True}))
print((x | y).atoms())
w, x, y, z = symbols('w x y z')
minterms = [[0, 0, 0, 1], [0, 0, 1, 1],[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]]
dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
print(SOPform([w, x, y, z], minterms, dontcares))
# | 0   | 1     | 1   | 0   || 1    | 1    |
# | 0   | 1     | 1   | 1   || 1    | 1    |
# | 1   | 0     | 0   | 0   || 0    | 0    |
# | 1   | 0     | 0   | 1   || 1    | 0    |
# | 1   | 0     | 1   | 0   || 1    | 0    |
# | 1   | 0     | 1   | 1   || 0    | 0    |

from sympy.logic import SOPform
from sympy import symbols
from sympy import printing

x3, x2, x1, x0 = symbols('2s 100s FF2 FF1')

FF1_minterms = [[0, 0, 0, 1],
                [0, 0, 1, 1],
                [0, 1, 0, 0],
                [0, 1, 0, 1],
                [0, 1, 1, 0],
                [0, 1, 1, 1],]
result = SOPform([x3, x2, x1, x0], FF1_minterms)
print "FF1 = " + (printing.ccode(result))

FF2_minterms = [[0, 0, 1, 0],
                [0, 0, 1, 1],
                [0, 1, 1, 0],
                [0, 1, 1, 1],
                [1, 0, 0, 1],
                [1, 0, 1, 0],]
result = SOPform([x3, x2, x1, x0], FF2_minterms)
print "FF2 = " + (printing.ccode(result))
Example #13
0
def retornaCusto(populacaoCortada, bitin, bits, entradas):
    for i in range(len(populacaoCortada)):
        mintermos = populacaoCortada[i][1]
        cromossomo = populacaoCortada[i][2]
        dontcares = populacaoCortada[i][3]
        mintermosOut = populacaoCortada[i][5]

        n = bits + bitin
        var = list(string.ascii_lowercase[:n])
        test = symbols(var)

        #CALCULA CUSTOS DOS MINTERMOS DE SAIDA--------------
        auxiliarCont = []
        auxiliarTermos = []
        auxiliarExpressao = []
        avaliacao = []

        for j in range(len(mintermos)):
            resultado = SOPform(test, mintermos['y' + str(j)], dontcares)
            expressao = str(resultado)
            termos = expressao.count('|') + 1
            cont = 0
            for l in expressao:
                if l in var:
                    cont += 1

            cont += termos

            auxiliarCont.append(cont)
            auxiliarTermos.append(termos)
            auxiliarExpressao.append(expressao)
        avaliacao.append(auxiliarCont)
        avaliacao.append(auxiliarTermos)
        avaliacao.append(auxiliarExpressao)

        populacaoCortada[i][4] = avaliacao

        #CALCULA CUSTO DAS SAIDAS DA FSM---------------------------
        auxiliar2Cont = []
        auxiliar2Termos = []
        auxiliar2Expressao = []
        avaliacaoOut = []
        for m in range(len(mintermosOut)):
            resultado = SOPform(test, mintermosOut['s' + str(m)], dontcares)
            expressao = str(resultado)
            termos = expressao.count('|') + 1
            cont = 0
            for n in expressao:
                if n in var:
                    cont += 1
            cont += termos

            auxiliar2Cont.append(cont)
            auxiliar2Termos.append(termos)
            auxiliar2Expressao.append(expressao)
        avaliacaoOut.append(auxiliar2Cont)
        avaliacaoOut.append(auxiliar2Termos)
        avaliacaoOut.append(auxiliar2Expressao)
        populacaoCortada[i][6] = avaliacaoOut

        custoTotal = 0
        tempCusto = populacaoCortada[i][4][0]  #pega o custo do individuo
        for x in range(
                len(populacaoCortada[i][6]
                    [0])):  #for com repetições do tamanho do custo de saida
            tempCusto.append(populacaoCortada[i][6][0][x])
        custoTotal = sum(tempCusto)

        termosTotal = 0
        tempTermos = populacaoCortada[i][4][1]  #pega os termos do individuo
        for y in range(len(populacaoCortada[i][6][1])):
            tempTermos.append(populacaoCortada[i][6][1][y])
        custoTermos = sum(tempTermos)

        aux = []
        aux.append(custoTotal)
        aux.append(custoTermos)
        populacaoCortada[i][7] = aux

        populacaoAvaliada.append(populacaoCortada[i])

    #Pelo método 1 de paralização, quando a Thread termina ela sai silenciosamente e retorna. Dessa forma conforme as Threads forem terminando
    #o Array controleThread é escrito com um valor qualquer, apenas para controle
    return controleThread.append("1")