Exemple #1
0
def randomution(sch, pop_len, gens):
    if type(sch) == str:
        c17 = sa.read_scheme(sch)
        print('string')
    elif type(sch) == sa.scheme_alt:
        c17 = sch
        print('scheme')
    else:
        print('undefined scheme type')
    population = em.initial_population_rnd(c17, pop_len, 1)  # generate random population
    max_arr = []
    avr_arr = []
    x_axis = []
    for gen in range(gens):
        fitness = em.fitness(c17, population)
        print("GENERATION # ", gen)
        print("AVERAGE = ", (sum(fitness)/len(fitness)))
        print("MAXIMUM = ", max(fitness+max_arr))
        print("=================")
        max_arr.append(max(fitness+max_arr))
        avr_arr.append(sum(fitness)/len(fitness))
        x_axis.append(gen)
        #if max(fitness) == 1:
        #    return population[fitness.index(max(fitness))]
        population = em.initial_population_rnd(c17, pop_len, 1)  # generate random population
    plt.plot(x_axis, avr_arr, 'b--', x_axis, max_arr, 'r')
    return population[fitness.index(max(fitness))]
def check_overall_TMR(in_circ_file):
    main_circuit_etalon = sa.read_scheme(in_circ_file)
    initial_area = get_area(main_circuit_etalon)
    initial_reliability = external_reliability(main_circuit_etalon, 100000)
    tmr_circ = createTMRCirc(main_circuit_etalon)
    new_area = get_area(tmr_circ)
    new_reliability = external_reliability(tmr_circ, 100000)
    print('Initial reliability: {}'.format(initial_reliability))
    print('TMR reliability: {}'.format(new_reliability))
    print('New area: {} Initial Area: {} Growth Percent: {}%'.format(
        new_area, initial_area, round((100.0 * new_area) / initial_area), 2))
Exemple #3
0
def print_real_circuits_info(path_csv_test, path_csv_test_real):
    test = pd.read_csv(path_csv_test)
    features = get_features(test)

    if 1:
        ckt_path = os.path.join(get_project_directory(), 'circuits',
                                'LGSynth89')
        ckt_list = [
            '5xp1.txt', 'alu2_synth.txt', 'alu4_synth.txt', 'cm138a_synth.txt',
            'cu_synth.txt', 'f51m_synth.txt', 'misex1.txt', 'misex3.txt',
            'misex3c.txt', 'x2_synth.txt'
        ]
    if 0:
        ckt_path = os.path.join(get_project_directory(), 'temp',
                                'machine_learning')
        ckt_list = [
            'ckt-19999.txt', 'ckt-19998.txt', 'ckt-19997.txt', 'ckt-19996.txt',
            'ckt-19995.txt', 'ckt-19994.txt', 'ckt-19993.txt', 'ckt-19992.txt',
            'ckt-19991.txt', 'ckt-19990.txt'
        ]
    ckt_list_path = []
    for ckt in ckt_list:
        ckt_list_path.append(os.path.join(ckt_path, ckt))

    total = 0
    spval = dict()
    rel = dict()
    params = dict()
    for cp in ckt_list_path:
        ckt_init = sa.read_scheme(cp)
        ckt = create_circuit_external_yosys(ckt_init)
        if ckt is not None:
            if check_for_bufs(ckt) == 1:
                print('Problem [BUFs]')
                exit()
            if check_ouputs_connected(ckt) == 0:
                print('Problem [Output connections]')
                exit()
            print('Success')

        (reliability,
         vulnerability_map) = external_vulnerability_map(ckt, 10000)
        rel[total] = reliability
        params[total] = get_ckt_parameters(ckt)
        spval[total] = nt.singlepass_method_lk(ckt)
        params[total]['single_pass_value'] = spval[total]
        for f in features:
            if f not in params[total].keys():
                params[total][f] = -1
        total += 1
    print_resulted_csv(params, rel, path_csv_test_real, 0, len(params))
Exemple #4
0
def evolution2(sch, pop_len, gens):
    if type(sch) == str:
        c17 = sa.read_scheme(sch)
        print('string')
    elif type(sch) == sa.scheme_alt:
        c17 = sch
        print('scheme')
    else:
        print('undefined scheme type')
    max_arr = []
    avr_arr = []
    x_axis = []
    inp = c17.inputs()
    out = c17.outputs()
    el = c17.elements()
    population = em.initial_population_rnd(c17, pop_len, 1)  # generate random population
    fitness = em.fitness(c17, population)

    for gen in range(gens):

        print("GENERATION # ", gen)
        print("AVERAGE = ", (sum(fitness)/len(fitness)))
        print("MAXIMUM = ", max(fitness))
        print("=================")
        max_arr.append(max(fitness))
        avr_arr.append(sum(fitness)/len(fitness))
        x_axis.append(gen)
        if max(fitness) == 1:
            plt.plot(x_axis, avr_arr, 'b--', x_axis, max_arr, 'r')
            return population[fitness.index(max(fitness))]


        parents = em.tournament_selection(population, fitness)

        offsprings = em.coupling_rnd(parents, 2, 0.5)

        mutants = em.mutation(offsprings, 8)

        fitness_mtn = em.fitness(c17, mutants)

        (fitness, population) = em.reduction_selective(population, mutants, fitness + fitness_mtn)




    plt.plot(x_axis, avr_arr, 'b--', x_axis, max_arr, 'r')
    return population[-1]
Exemple #5
0
def find_ckts_chromosomes(num):
    total = 0
    print('Calc CKT Chromosomes...')
    max_len = 0
    chromos = dict()
    path_json = os.path.join(get_project_directory(), 'temp',
                             'machine_learning', 'chromos.json')
    while total < num:
        path_opt = os.path.join(get_project_directory(), 'temp',
                                'machine_learning', 'ckt-{}.txt'.format(total))
        ckt = sa.read_scheme(path_opt)
        chromos[total] = sch2chromo(ckt)
        if len(chromos[total][1]) > max_len:
            max_len = len(chromos[total][1])
        total += 1
    save_json(path_json, chromos)
    return max_len, chromos
Exemple #6
0
def find_ckts_singlepass_values(params, num):
    total = 0
    print('Calc CKT Single Pass Values...')
    spval = dict()
    path_json = os.path.join(get_project_directory(), 'temp',
                             'machine_learning', 'sp_values.json')
    if (os.path.isfile(path_json)):
        spval = load_json(path_json)
    while total < num:
        path_opt = os.path.join(get_project_directory(), 'temp',
                                'machine_learning', 'ckt-{}.txt'.format(total))
        ckt = sa.read_scheme(path_opt)
        if total not in spval:
            spval[total] = nt.singlepass_method_lk(ckt)
        params[total]['single_pass_value'] = spval[total]
        total += 1

    save_json(path_json, spval)
    return spval
Exemple #7
0
def find_ckts_parameters(num):
    total = 0
    print('Calc CKT Parameters...')
    params = dict()
    path_json = os.path.join(get_project_directory(), 'temp',
                             'machine_learning', 'parameters.json')
    if (os.path.isfile(path_json)):
        params = load_json3(path_json)
    while total < num:
        path_opt = os.path.join(get_project_directory(), 'temp',
                                'machine_learning', 'ckt-{}.txt'.format(total))
        ckt = sa.read_scheme(path_opt)
        if total not in params:
            params[total] = get_ckt_parameters(ckt)
        total += 1

    if not os.path.isfile(path_json):
        save_json(path_json, params)
    return params
def create_circuit_external_yosys (circuit):
    dfile = get_project_directory()
    run_path = os.path.join(dfile, "utils", "bin", "win32", "yosys")
    yosys_exe = os.path.join(run_path, "yosys.exe")
    circuit_file = os.path.join(dfile, "temp", "tmp_sheme_yosys.v")
    run_file = os.path.join(dfile, "temp", "tmp_runfile_yosys.txt")
    synth_file = os.path.join(dfile, "temp", "tmp_synth.v")
    converted_circuit_file = os.path.join(dfile, "temp", "tmp_synth_conv.txt")
    graph_file = os.path.join(dfile, "temp", "synth.svg")
    debug_file = os.path.join(dfile, "temp", "yosys_fail.txt")

    if os.path.isfile(circuit_file):
        os.remove(circuit_file)
    if os.path.isfile(run_file):
        os.remove(run_file)
    if os.path.isfile(synth_file):
        os.remove(synth_file)
    if os.path.isfile(converted_circuit_file):
        os.remove(converted_circuit_file)

    print_circuit_in_verilog_file(circuit, "circ", circuit_file)
    print_run_file(run_file, circuit_file, synth_file, graph_file)
    #print_run_file_opt(run_file, circuit_file, synth_file, graph_file)
    exe = yosys_exe + " < " + run_file
    try:
        ret = subprocess.check_output(exe, shell=True, cwd=run_path).decode('UTF-8')
    except:
        ret = 'Error'

    if not os.path.isfile(synth_file):
        # Если была проблема с Yosys выводим схему для последующего дебага
        circuit.print_circuit_in_file(debug_file)
        print('Yosys error')
        return None

    convert_file_to_relic_format(circuit, synth_file, converted_circuit_file)
    if os.path.isfile(converted_circuit_file) == False:
        return None
    new_ckt = sa.read_scheme(converted_circuit_file)
    return new_ckt
Exemple #9
0
def find_reliability_values(num):
    total = 0
    rel = dict()
    path_json = os.path.join(get_project_directory(), 'temp',
                             'machine_learning', 'reliability.json')
    if (os.path.isfile(path_json)):
        rel = load_json(path_json)
    while total < num:
        if total in rel.keys():
            print(
                'Reliability for test {} already exists: {}. Skipping!'.format(
                    total, rel[total]))
            total += 1
            continue
        file_name = os.path.join(get_project_directory(), 'temp',
                                 'machine_learning',
                                 'ckt-{}.txt'.format(total))
        ckt = sa.read_scheme(file_name)
        (reliability,
         vulnerability_map) = external_vulnerability_map(ckt, 10000)
        rel[total] = reliability
        total += 1
    save_json(path_json, rel)
    return rel
Exemple #10
0
def evolution(sch, pop_len, gens):
    if type(sch) == str:
        c17 = sa.read_scheme(sch)
        print('string')
    elif type(sch) == sa.scheme_alt:
        c17 = sch
        print('scheme')
    else:
        print('undefined scheme type')
    max_arr = []
    avr_arr = []
    entr_arr = []
    x_axis = []
    inp = c17.inputs()
    out = c17.outputs()
    el = c17.elements()
    population = em.initial_population_entropy(c17, pop_len, 1)  # generate random population
    time_fitness = 0
    time_selection = 0
    time_coupling = 0
    time_mutation = 0
    time_reduction = 0
    total = time.time()
    for gen in range(gens):

        tmp = time.time()
        fitness = em.fitness(c17, population)
        time_fitness += tmp - time.time()
        entropy = em.population_entropy(population)


        print("GENERATION # ", gen)
        print("AVERAGE = ", (sum(fitness)/len(fitness)))
        print("MAXIMUM = ", max(fitness))
        print("ENTROPY = ", entropy)
        print("=================")
        max_arr.append(max(fitness))
        avr_arr.append(sum(fitness)/len(fitness))
        entr_arr.append(entropy/out)
        x_axis.append(gen)
        if max(fitness) == 1:
            plt.plot(x_axis, avr_arr, 'b--', x_axis, max_arr, 'r', x_axis, entr_arr, 'y-')
            return population[fitness.index(max(fitness))]


        tmp = time.time()
        parents = em.tournament_selection(population, fitness)
        time_selection += tmp - time.time()

        tmp = time.time()
        offsprings = em.coupling_rnd(parents, 1, 0.9)
        time_coupling += tmp - time.time()

        tmp = time.time()
        mutants = em.mutation(offsprings, 0.5) # среднее число ошибок на 1 хромосому
        time_mutation += tmp - time.time()

        tmp = time.time()
        population = em.reduction_elite(population, mutants, fitness)
        time_reduction += tmp - time.time()

    print("time_fitness = ", time_fitness)
    print("time_selection = ", time_selection)
    print("time_coupling = ", time_coupling)
    print("time_mutation = ", time_mutation)
    print("time_reduction = ", time_reduction)
    print("TOTAL = ", total - time.time())
    plt.plot(x_axis, avr_arr, 'b--', x_axis, max_arr, 'r', x_axis, entr_arr, 'y-')
    return population[-1]
Exemple #11
0
    def actStart(self):
        # ==============================================================================================================
        p1, p2, p3, p4, f4 = 0.2, 0.1, 0.02, 0.009, 0.2
        ced_hemming = None
        rel_hemming = None
        ced_spectral = None
        ced_spectral_2 = None
        ced_spectral_4 = None
        rel_spectral = None
        ced_ldpc = None
        ced_ldpc_2 = None
        ced_ldpc_4 = None
        rel_ldpc = None
        rel_result = None
        result = None
        error_1 = False
        coders = None
        decoders = None
        # correlation_matrix = None
        # ==============================================================================================================
        options = [False, False]
        if self.checkBox_5.checkState() == 2: options[0] = True     # Log file
        if self.checkBox_6.checkState() == 2: options[1] = True     # Verilog file
        # ==============================================================================================================
        mtd = [False, False, False, False]
        if self.checkBox.checkState() == 2:     mtd[0] = True       # Clusterization
        if self.checkBox_4.checkState() == 2:   mtd[1] = True       # 3bits Hemming space
        if self.checkBox_3.checkState() == 2:   mtd[2] = True       # Spectral R-code
        if self.checkBox_2.checkState() == 2:   mtd[3] = True       # LDPC code
        # ==============================================================================================================
        if not self.path:
            self.textEdit.setTextColor(QColor(255, 0, 0))
            self.textEdit.append('Combinational circuit is not received.')
            return
        # ==============================================================================================================
        if mtd[0] and not mtd[3] and not mtd[2]:
            self.textEdit.setTextColor(QColor(255, 0, 0))
            self.textEdit.append('To perform clusterization, select method based on spectral or LDPC codes.')
            return
        # ==============================================================================================================
        if not mtd[3] and not mtd[2] and not mtd[1]:
            self.textEdit.setTextColor(QColor(255, 0, 0))
            self.textEdit.append('To perform analysis, select synthesis methods of CED circuit.')
            return
        # ==============================================================================================================
        dt = datetime.now()
        start_time = 'Start time - {:02d}:{:02d}:{:02d}'.format(dt.hour, dt.minute, dt.second)
        # ==============================================================================================================
        self.textEdit.setTextColor(QColor(0, 0, 0))
        self.textEdit.append('\n' + start_time + '\n')
        self.textEdit.append('Combinational circuit is received:')
        self.circuit = sch.read_scheme(self.path)
        self.textEdit.append(self.path)
        # ==============================================================================================================
        if mtd[2] and self.circuit.outputs() < 2:
            self.textEdit.setTextColor(QColor(255, 0, 0))
            self.textEdit.append('For this combinational circuit, it is not possible to generate a CED circuit based on'
                                 ' Spectral R-code.')
            error_1 = True
        # ==============================================================================================================
        if mtd[3] and self.circuit.outputs() < 3:
            self.textEdit.setTextColor(QColor(255, 0, 0))
            self.textEdit.append('For this combinational circuit, it is not possible to generate a CED circuit based on'
                                 ' LDPC code.')
            error_1 = True
        # ==============================================================================================================
        if error_1: return
        # ==============================================================================================================
        if mtd[0] and self.circuit.outputs() < 10:
            self.textEdit.setTextColor(QColor(255, 0, 0))
            self.textEdit.append('For this combinational circuit, it is not possible to perform clustarization.')
            return
        # ==============================================================================================================
        self.constraint = self.spinBox.value()
        if self.constraint == 0:
            self.textEdit.setTextColor(QColor(255, 0, 0))
            self.textEdit.append('Constraint on the value of structural redundancy is not received.')
            return
        # ==============================================================================================================
        t1 = round(float(t()), 2)
        # ==============================================================================================================
        self.textEdit.setTextColor(QColor(0, 0, 0))
        self.textEdit.append('Constraint on the value of structural redundancy is received:')
        self.textEdit.append(str(self.constraint))
        # ==============================================================================================================
        self.textEdit.append('Determining main characteristics of combinational circuit:')
        # ==============================================================================================================
        inp = self.circuit.inputs()
        k = self.circuit.outputs()
        n = self.circuit.elements()
        self.textEdit.append('PO = {}'.format(str(k)))
        self.textEdit.append('PI = {}'.format(str(inp)))
        self.textEdit.append('Structure redundancy = {}'.format(str(n)))
        # ==============================================================================================================
        if mtd[1]:
            self.textEdit.append('CED circuit based on coding in 3bits Hemming space:')
            num = 0
            for element in self.circuit.__elements__:
                element_type = self.circuit.__elements__[element][0]
                if element_type == 'BUF' or element_type == 'INV':  num += 1
            ced_hemming = 27 * n - 15 * num + 4 * k
            self.textEdit.append('Structure redundancy =  {}'.format(str(ced_hemming)))
            rel_hemming = 2 * k / ced_hemming
            self.textEdit.append('Reliability characteristic =  {}%'.format(str(round(rel_hemming * 100, 2))))
        # ==============================================================================================================
        if mtd[3]:
            self.textEdit.append('CED circuit based on LDPC code:')
            ced_ldpc = 2 * n + 7 * k
            self.textEdit.append('Structure redundancy =  {}'.format(str(ced_ldpc)))
            beta_1 = n / ced_ldpc
            rel_ldpc = beta_1 * (p1 + p2 + p3 + p4) + 4 * k / ced_ldpc * 0.75
            self.textEdit.append('Reliability characteristic =  {}%'.format(str(round(rel_ldpc * 100, 2))))
        # ==============================================================================================================
        if mtd[2]:
            self.textEdit.append('CED circuit based on Spectral R-code:')
            m = int(np.ceil(np.log2(k))) + 1
            xor = 0
            gx = list(np.sum(spectral.matrix_gx(self.circuit.outputs(), m - 1), 1))
            for i in gx:
                if i >= 2:
                    xor += i - 1
            ced_spectral = 2 * n + 2 * xor + 3 * m + m * k + 2 * k + 2
            self.textEdit.append('Structure redundancy =  {}'.format(str(ced_spectral)))
            beta_2 = n / (ced_spectral - n - k + 1)
            rel_spectral = beta_2 * p3 + beta_2 * p4 * f4 + k / (ced_spectral - n - k + 1) + (
                    1 - (2 ** (2 * k + 1) - 1) / (2 ** (3 * k + 1) - 1)) * ((3 * k + 1) / (ced_spectral - n - k + 1))

            self.textEdit.append('Reliability characteristic =  {}%'.format(str(round(rel_spectral * 100, 2))))
        # ==============================================================================================================
        if mtd[0]:
            if mtd[3] or mtd[2]:
                self.textEdit.append('Compiling matrix of dependencies.')
                # correlation_matrix = cluster.gen_correlation_matrix(self.circuit)
                self.textEdit.append('Clusterization combinational circuit outputs into 2 groups.')
                clusters_2, groups_2 = cluster.clusterization(self.circuit, 1)
                # ======================================================================================================
                if mtd[3]:
                    self.textEdit.append('CED circuit based on LDPC code:')
                    ced_groups = 0
                    ldpc_elements, ldpc_outputs = [], []
                    for group in groups_2:
                        out_ldpc = [self.circuit.__outputs__[group[i] - 1] for i in range(len(group))]
                        if len(out_ldpc) >= 3:
                            sch_ldpc = self.circuit.subscheme_by_outputs(out_ldpc)
                            ced_groups += sch_ldpc.elements() + 7 * sch_ldpc.outputs()
                            ldpc_elements.append(sch_ldpc.elements())
                            ldpc_outputs.append(sch_ldpc.outputs())
                        else:
                            ldpc_elements.append(0)
                            ldpc_outputs.append(len(group))
                    ced_ldpc_2 = n + ced_groups
                    self.textEdit.append('Structure redundancy =  {}'.format(str(ced_ldpc_2)))
                # ======================================================================================================
                if mtd[2]:
                    self.textEdit.append('CED circuit based on Spectral R-code:')
                    spectral_groups = 0
                    xor = 0
                    m = 0
                    spectral_elements, spectral_outputs = [], []
                    for group in groups_2:
                        out_spectral = [self.circuit.__outputs__[group[i] - 1] for i in range(len(group))]
                        if len(out_spectral) >= 2:
                            sch_spectral = self.circuit.subscheme_by_outputs(out_spectral)
                            m = int(np.ceil(np.log2(sch_spectral.outputs()))) + 1
                            xor = 0
                            gx = list(np.sum(spectral.matrix_gx(sch_spectral.outputs(), m - 1), 1))
                            sp_elem = sch_spectral.elements()
                            sp_out = sch_spectral.outputs()
                            for i in gx:
                                if i >= 2:  xor += i - 1
                        else:
                            sp_elem = 0
                            sp_out = len(group)
                        spectral_elements.append(sp_elem)
                        spectral_outputs.append(sp_out)
                        spectral_groups += sp_elem + 2 * xor + 3 * m + m * sp_out + 2 * sp_out + 2
                    ced_spectral_2 = n + spectral_groups + 2
                    self.textEdit.append('Structure redundancy =  {}'.format(str(ced_spectral_2)))
                # ======================================================================================================
                self.textEdit.append('Clusterization combinational circuit outputs into 4 groups.')
                clusters_4, groups_4 = cluster.clusterization(self.circuit, 2)
                # ======================================================================================================
                if mtd[3]:
                    self.textEdit.append('CED circuit based on LDPC code:')
                    ced_groups = 0
                    ldpc_elements, ldpc_outputs = [], []
                    for group in groups_4:
                        out_ldpc = [self.circuit.__outputs__[group[i] - 1] for i in range(len(group))]
                        if len(out_ldpc) >= 3:
                            sch_ldpc = self.circuit.subscheme_by_outputs(out_ldpc)
                            ced_groups += sch_ldpc.elements() + 7 * sch_ldpc.outputs()
                            ldpc_elements.append(sch_ldpc.elements())
                            ldpc_outputs.append(sch_ldpc.outputs())
                        else:
                            ldpc_elements.append(0)
                            ldpc_outputs.append(len(group))
                    ced_ldpc_4 = n + ced_groups
                    self.textEdit.append('Structure redundancy =  {}'.format(str(ced_ldpc_4)))
                # ======================================================================================================
                if mtd[2]:
                    self.textEdit.append('CED circuit based on Spectral R-code:')
                    spectral_groups = 0
                    xor = 0
                    m = 0
                    spectral_elements, spectral_outputs = [], []
                    for group in groups_4:
                        out_spectral = [self.circuit.__outputs__[group[i] - 1] for i in range(len(group))]
                        if len(out_spectral) >= 2:
                            sch_spectral = self.circuit.subscheme_by_outputs(out_spectral)
                            m = int(np.ceil(np.log2(sch_spectral.outputs()))) + 1
                            xor = 0
                            gx = list(np.sum(spectral.matrix_gx(sch_spectral.outputs(), m - 1), 1))
                            sp_elem = sch_spectral.elements()
                            sp_out = sch_spectral.outputs()
                            for i in gx:
                                if i >= 2:  xor += i - 1
                        else:
                            sp_elem = 0
                            sp_out = len(group)
                        spectral_elements.append(sp_elem)
                        spectral_outputs.append(sp_out)
                        if sp_elem != 0:
                            spectral_groups += sp_elem + 2 * xor + 3 * m + m * sp_out + 2 * sp_out + 2
                        else:
                            spectral_groups += 0
                    ced_spectral_4 = n + spectral_groups + 6
                    self.textEdit.append('Structure redundancy =  {}'.format(str(ced_spectral_4)))
        # ==============================================================================================================
        if mtd[1] is True and ced_hemming <= self.constraint:
            self.textEdit.append('Selected method based on encoding in 3bits Hemming space.')
            result = hemming.create_hemming_circuit(self.circuit)
            sim = hemming.error_simulation(result, 1, 10000)
            rel_result = round(sim[0][1] / sim[1] * 100, 2)
            method = 'H'
            t2 = round(float(t()), 2)
        # ==============================================================================================================
        # Without clusterization
        # ==============================================================================================================
        elif mtd[0] is False and mtd[2] is True and mtd[3] is False:    # Spectral
            if self.constraint >= ced_spectral:
                self.textEdit.append('Selected method based on Spectral R-code.')
                result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 0)
                method = 'R'
                t2 = round(float(t()), 2)
                sim = spectral.error_simulation(result, cone, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            else:
                t2 = round(float(t()), 2)
                self.textEdit.append('It is not possible to generate CED circuit for selected structural constraint!')
                method = 'E'
        elif mtd[0] is False and mtd[2] is False and mtd[3] is True:    # LDPC
            if self.constraint > ced_ldpc:
                self.textEdit.append('Selected method based on LDPC code')
                result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 0)
                method = 'L'
                t2 = round(float(t()), 2)
                sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            else:
                t2 = round(float(t()), 2)
                self.textEdit.append('It is not possible to generate CED circuit for selected structural constraint!')
                method = 'E'
        elif mtd[0] is False and mtd[2] is True and mtd[3] is True:     # Spectral + LDPC
            if self.constraint >= ced_spectral and self.constraint >= ced_ldpc:
                if rel_spectral <= rel_ldpc:
                    self.textEdit.append('Selected method based on Spectral R-code.')
                    result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 0)
                    method = 'R'
                    t2 = round(float(t()), 2)
                    sim = spectral.error_simulation(result, cone, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
                else:
                    self.textEdit.append('Selected method based on LDPC code.')
                    result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 0)
                    method = 'L'
                    t2 = round(float(t()), 2)
                    sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
            elif ced_spectral <= self.constraint:
                self.textEdit.append('Selected method based on Spectral R-code.')
                result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 0)
                method = 'R'
                t2 = round(float(t()), 2)
                sim = spectral.error_simulation(result, cone, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            elif ced_ldpc <= self.constraint:
                self.textEdit.append('Selected method based on LDPC code.')
                result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 0)
                method = 'L'
                t2 = round(float(t()), 2)
                sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            else:
                t2 = round(float(t()), 2)
                self.textEdit.append('It is not possible to generate CED circuit for selected structural constraint!')
                method = 'E'
                self.label_8.setText("None")
                self.label_9.setText("0")
                self.label_10.setText("0")
                self.label_11.setText("0")
                self.label_12.setText("0.00 %")
                self.label_13.setText("None")
        # ==============================================================================================================
        # With clusterization
        # ==============================================================================================================
        elif mtd[0] is True and mtd[2] is True and mtd[3] is False:             # Spectral
            if ced_spectral_4 <= self.constraint and ced_spectral_4 != n:
                self.textEdit.append('Selected method based on Spectral R-code with clusterization on 4 groups.')
                result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 2)
                method = 'R4'
                t2 = round(float(t()), 2)
                sim = spectral.error_simulation(result, cone, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            elif ced_spectral_2 <= self.constraint and ced_spectral_2 != n:
                self.textEdit.append('Selected method based on Spectral R-code with clusterization on 2 groups.')
                result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 1)
                method = 'R2'
                t2 = round(float(t()), 2)
                sim = spectral.error_simulation(result, cone, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            elif ced_spectral <= self.constraint:
                self.textEdit.append('Selected method based on Spectral R-code without clusterization.')
                result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 0)
                method = 'R'
                t2 = round(float(t()), 2)
                sim = spectral.error_simulation(result, cone, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            else:
                t2 = round(float(t()), 2)
                self.textEdit.append('It is not possible to generate CED circuit for selected structural constraint!')
                method = 'E'
                self.label_8.setText("None")
                self.label_9.setText("0")
                self.label_10.setText("0")
                self.label_11.setText("0")
                self.label_12.setText("0.00 %")
                self.label_13.setText("None")
        elif mtd[0] is True and mtd[2] is False and mtd[3] is True:             # LDPC
            if ced_ldpc_4 <= self.constraint and ced_ldpc_4 != n:
                self.textEdit.append('Selected method based on LDPC code with clusterization on 4 groups.')
                result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 2)
                method = 'L4'
                t2 = round(float(t()), 2)
                sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            elif ced_ldpc_2 <= self.constraint and ced_ldpc_2 != n:
                self.textEdit.append('Selected method based on LDPC code with clusterization on 2 groups.')
                result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 1)
                method = 'L2'
                t2 = round(float(t()), 2)
                sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            elif ced_ldpc <= self.constraint:
                self.textEdit.append('Selected method based on LDPC code without clusterization.')
                result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 0)
                method = 'L'
                t2 = round(float(t()), 2)
                sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                rel_result = round(sim[0][2] / sim[1] * 100, 2)
            else:
                t2 = round(float(t()), 2)
                self.textEdit.append('It is not possible to generate CED circuit for selected structural constraint!')
                method = 'E'
                self.label_8.setText("None")
                self.label_9.setText("0")
                self.label_10.setText("0")
                self.label_11.setText("0")
                self.label_12.setText("0.00 %")
                self.label_13.setText("None")
        elif mtd[0] is True and mtd[2] is True and mtd[3] is True:      # Spectral + LDPC
            if self.constraint >= ced_spectral and self.constraint >= ced_ldpc:
                if rel_spectral <= rel_ldpc:
                    if ced_spectral_4 <= self.constraint and ced_spectral_4 != n:
                        self.textEdit.append('Selected method based on Spectral R-code with clusterization on '
                                             '4 groups.')
                        result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 2)
                        method = 'R4'
                        t2 = round(float(t()), 2)
                        sim = spectral.error_simulation(result, cone, 1, 10000)
                        rel_result = round(sim[0][2] / sim[1] * 100, 2)
                    elif ced_spectral_2 <= self.constraint and ced_spectral_2 != n:
                        self.textEdit.append('Selected method based on Spectral R-code with clusterization on '
                                             '2 groups.')
                        result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 1)
                        method = 'R2'
                        t2 = round(float(t()), 2)
                        sim = spectral.error_simulation(result, cone, 1, 10000)
                        rel_result = round(sim[0][2] / sim[1] * 100, 2)
                    elif ced_spectral <= self.constraint:
                        self.textEdit.append('Selected method based on Spectral R-code without clusterization.')
                        result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 0)
                        method = 'R'
                        t2 = round(float(t()), 2)
                        sim = spectral.error_simulation(result, cone, 1, 10000)
                        rel_result = round(sim[0][2] / sim[1] * 100, 2)
                    else:
                        t2 = round(float(t()), 2)
                        self.textEdit.append(
                            'It is not possible to generate CED circuit for selected structural constraint!')
                        method = 'E'
                        self.label_8.setText("None")
                        self.label_9.setText("0")
                        self.label_10.setText("0")
                        self.label_11.setText("0")
                        self.label_12.setText("0.00 %")
                        self.label_13.setText("None")
                else:
                    if ced_ldpc_4 <= self.constraint and ced_ldpc_4 != n:
                        self.textEdit.append('Selected method based on LDPC code with clusterization on 4 groups.')
                        result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 2)
                        method = 'L4'
                        t2 = round(float(t()), 2)
                        sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                        rel_result = round(sim[0][2] / sim[1] * 100, 2)
                    elif ced_ldpc_2 <= self.constraint and ced_ldpc_2 != n:
                        self.textEdit.append('Selected method based on LDPC code with clusterization on 2 groups.')
                        result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 1)
                        method = 'L2'
                        t2 = round(float(t()), 2)
                        sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                        rel_result = round(sim[0][2] / sim[1] * 100, 2)
                    elif ced_ldpc <= self.constraint:
                        self.textEdit.append('Selected method based on LDPC code without clusterization.')
                        result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 0)
                        method = 'L'
                        t2 = round(float(t()), 2)
                        sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                        rel_result = round(sim[0][2] / sim[1] * 100, 2)
                    else:
                        t2 = round(float(t()), 2)
                        self.textEdit.append(
                            'It is not possible to generate CED circuit for selected structural constraint!')
                        method = 'E'
                        self.label_8.setText("None")
                        self.label_9.setText("0")
                        self.label_10.setText("0")
                        self.label_11.setText("0")
                        self.label_12.setText("0.00 %")
                        self.label_13.setText("None")
            elif ced_spectral <= self.constraint:
                if ced_spectral_4 <= self.constraint and ced_spectral_4 != n:
                    self.textEdit.append('Selected method based on Spectral R-code with clusterization on 4 groups.')
                    result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 2)
                    method = 'R4'
                    t2 = round(float(t()), 2)
                    sim = spectral.error_simulation(result, cone, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
                elif ced_spectral_2 <= self.constraint and ced_spectral_2 != n:
                    self.textEdit.append('Selected method based on Spectral R-code with clusterization on 2 groups.')
                    result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 1)
                    method = 'R2'
                    t2 = round(float(t()), 2)
                    sim = spectral.error_simulation(result, cone, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
                elif ced_spectral <= self.constraint:
                    self.textEdit.append('Selected method based on Spectral R-code without clusterization.')
                    result, cone, coders, decoders = spectral.create_spec_circuit(self.circuit, 0)
                    method = 'R'
                    t2 = round(float(t()), 2)
                    sim = spectral.error_simulation(result, cone, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
                else:
                    t2 = round(float(t()), 2)
                    self.textEdit.append('It is not possible to generate CED circuit for selected structural '
                                         'constraint!')
                    method = 'E'
                    self.label_8.setText("None")
                    self.label_9.setText("0")
                    self.label_10.setText("0")
                    self.label_11.setText("0")
                    self.label_12.setText("0.00 %")
                    self.label_13.setText("None")
            elif ced_ldpc <= self.constraint:
                if ced_ldpc_4 <= self.constraint and ced_ldpc_4 != n:
                    self.textEdit.append('Selected method based on LDPC code with clusterization on 4 groups.')
                    result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 2)
                    method = 'L4'
                    t2 = round(float(t()), 2)
                    sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
                elif ced_ldpc_2 <= self.constraint and ced_ldpc_2 != n:
                    self.textEdit.append('Selected method based on LDPC code with clusterization on 2 groups.')
                    result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 1)
                    method = 'L2'
                    t2 = round(float(t()), 2)
                    sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
                elif ced_ldpc <= self.constraint:
                    self.textEdit.append('Selected method based on LDPC code without clusterization.')
                    result, coders, decoders = ldpc.create_ldpc_circuit(self.circuit, 0)
                    method = 'L'
                    t2 = round(float(t()), 2)
                    sim = ldpc.error_simulation(self.circuit, result, 1, 10000)
                    rel_result = round(sim[0][2] / sim[1] * 100, 2)
                else:
                    t2 = round(float(t()), 2)
                    self.textEdit.append('It is not possible to generate CED circuit for selected structural '
                                         'constraint!')
                    method = 'E'
                    self.label_8.setText("None")
                    self.label_9.setText("0")
                    self.label_10.setText("0")
                    self.label_11.setText("0")
                    self.label_12.setText("0.00 %")
                    self.label_13.setText("None")
            else:
                t2 = round(float(t()), 2)
                self.textEdit.append('It is not possible to generate CED circuit for selected structural constraint!')
                method = 'E'
                self.label_8.setText("None")
                self.label_9.setText("0")
                self.label_10.setText("0")
                self.label_11.setText("0")
                self.label_12.setText("0.00 %")
                self.label_13.setText("None")
        else:
            t2 = round(float(t()), 2)
            self.textEdit.append('It is not possible to generate CED circuit for selected structural constraint!')
            method = 'E'
            self.label_8.setText("None")
            self.label_9.setText("0")
            self.label_10.setText("0")
            self.label_11.setText("0")
            self.label_12.setText("0.00 %")
            self.label_13.setText("None")
        # ==============================================================================================================
        t3 = round(float(t()), 2)
        t4 = round(float(t2) - float(t1), 2)
        self.textEdit.append('Search time = {}s'.format(str(t4)))
        # ==============================================================================================================
        if options[1] is True:
            if method == 'E':
                self.textEdit.append('CED circuit was not generated. Unable to save file in Verilog format.')
            else:
                self.textEdit.append('CED subcircuits are saved in Verilog format.')
                if method != 'H':
                    for n_coder in range(0, len(coders)):
                        verilog_filename = pathname + '//result//{}_coder_{}.v'.format(self.filename, n_coder+1)
                        coders[n_coder].print_verilog_in_file(verilog_filename, 'coder_{}'.format(n_coder+1))
                    for n_decoder in range(0, len(decoders)):
                        verilog_filename = pathname + '//result//{}_decoder_{}.v'.format(self.filename, n_decoder+1)
                        decoders[n_decoder].print_verilog_in_file(verilog_filename, 'decoder_{}'.format(n_decoder+1))
                else:
                    verilog_filename = pathname + '//result//{}.v'.format(self.filename)
                    result.print_verilog_in_file(verilog_filename, 'CED_circuit')
                self.textEdit.append('Files saved.')
        # ==============================================================================================================
        if method != 'E':
            self.textEdit.append('Determining main characteristics of received CED circuit:')
            self.textEdit.append('PO = {}'.format(str(result.outputs())))
            self.textEdit.append('PI = {}'.format(str(result.inputs())))
            self.textEdit.append('Structure redundancy =  {}'.format(str(result.elements())))
            self.textEdit.append('Reliability characteristic =  {}%'.format(str(rel_result)))

            if method == 'H':       self.label_8.setText('Hemming')
            elif method == 'R':     self.label_8.setText('Spectral R-code')
            elif method == 'L':     self.label_8.setText('LDPC code')

            self.label_9.setText(str(result.elements()))
            self.label_10.setText(str(result.inputs()))
            self.label_11.setText(str(result.outputs()))
            self.label_12.setText(str(rel_result) + ' %')

            if method == 'R4' or method == 'L4':    self.label_13.setText('4 groups')
            elif method == 'R2' or method == 'L2':  self.label_13.setText('2 groups')
            else:                                   self.label_13.setText('Without clusterization')
        # ==============================================================================================================
        # LOG FILE - ON
        # ==============================================================================================================
        if options[0] is True:
            log_filename = pathname + '//result//{}.txt'.format(self.filename)
            f = open(log_filename, "a")
            f.write(start_time + '\n')
            f.write('Start program.\n')
            f.write('Input circuit is received.\n')
            f.write('Constraint to structure redundancy for CED circuit is received.\n')
            f.write('Constraint = {}\n'.format(self.constraint))
            f.write('Determining main characteristics of combinational circuit:\n')
            f.write('PI = {}\n'.format(inp))
            f.write('PO = {}\n'.format(k))
            f.write('Structure redundancy =  {}\n'.format(n))
            if mtd[1] is True:
                f.write('Calculation of estimated structure redundancy for CED circuit based on encoding in 3bits '
                        'Hemming space:\n')
                f.write('Structure redundancy =  {}\n'.format(ced_hemming))
            if mtd[3] is True:
                f.write('Calculation of estimated structure redundancy for CED circuit based on LDPC code:\n')
                f.write('Structure redundancy =  {}\n'.format(ced_ldpc))
                f.write('Calculation of estimated reliability characteristic for CED circuit based on LDPC code:\n')
                f.write('Reliability characteristic =  {}%\n'.format(round(rel_ldpc, 2)))
            if mtd[2] is True:
                f.write('Calculation of estimated structure redundancy for CED circuit based on Spectral R-code:\n')
                f.write('Structure redundancy =  {}\n'.format(ced_spectral))
                f.write('Calculation of estimated reliability characteristic for CED circuit based on Spectral '
                        'R-code:\n')
                f.write('Reliability characteristic =  {}%\n'.format(round(rel_spectral, 2)))
            if mtd[0] is True:
                if mtd[2] is True or mtd[3] is True:
                    f.write('Compiling matrix of dependencies.\n')
                    f.write('Clusterization circuit outputs into 2 groups.\n')
                    if mtd[3] is True:
                        f.write('Calculation of estimated structure redundancy for CED circuit based on LDPC code:\n')
                        f.write('Structure redundancy =  {}\n'.format(ced_ldpc_2))
                    if mtd[2] is True:
                        f.write('Calculation of estimated structure redundancy for CED circuit based on Spectral '
                                'R-code:\n')
                        f.write('Structure redundancy =  {}\n'.format(ced_spectral_2))
                    f.write('Clusterization circuit outputs into 4 groups.\n')
                    if mtd[3] is True:
                        f.write('Calculation of estimated structure redundancy for CED circuit based on LDPC code:\n')
                        f.write('Structure redundancy =  {}\n'.format(ced_ldpc_4))
                    if mtd[2] is True:
                        f.write('Calculation of estimated structure redundancy for CED circuit based on Spectral '
                                'R-code:\n')
                        f.write('Structure redundancy =  {}\n'.format(ced_spectral_4))
            if method == 'E':
                f.write('It is not possible to generate CED circuit for selected structural constraint!\n')
                f.write('Time  {}s\n'.format(round(float(t3) - float(t1), 2)))
                f.close()
            else:
                f.write('Selected method based on ')

                if method == 'H':       f.write('encoding in 3bits Hemming space.\n')
                elif method == 'R4':    f.write('Spectral R-code with clusterization on 4 groups.\n')
                elif method == 'R2':    f.write('Spectral R-code with clusterization on 2 groups.\n')
                elif method == 'R':     f.write('Spectral R-code without clusterization.\n')
                elif method == 'L4':    f.write('LDPC code with clusterization on 4 groups.\n')
                elif method == 'L2':    f.write('LDPC code with clusterization on 2 groups.\n')
                elif method == 'L':     f.write('LDPC code without clusterization.\n')

                f.write('Search time = {}s\n'.format(t4))
                f.write('Determining main characteristics of received CED circuit:\n')
                f.write('PO = {}\n'.format(result.outputs()))
                f.write('PI =  {}\n'.format(result.inputs()))
                f.write('Structure redundancy =  {}\n'.format(result.elements()))
                f.write('Reliability characteristic =  {}%\n'.format(rel_result))
                if options[0] is True:
                    f.write('Recording Verilog files.\n')
                    f.write('Files saved.\n')
                f.write('Time {}s\n'.format(round(float(t3) - float(t1), 2)))
                f.close()

        self.textEdit.append('Program execution time {}s\n'.format(str(round(float(t3) - float(t1), 2))))
Exemple #12
0
def debug_ckt():
    file_name = os.path.join(get_project_directory(), 'temp',
                             'machine_learning', 'ckt-{}.txt'.format(2))
    ckt = sa.read_scheme(file_name)
    (reliability, vulnerability_map) = external_vulnerability_map(ckt, 10000)
    print(reliability)
def improve_circuit_by_resynthesis_ver6(in_circ_file, out_circ_file,
                                        needed_replacements,
                                        max_area_overhead):
    """
    :param in_circ_file: File with input circuit .
    :param out_circ_file: File to store resulted circuit
    :param needed_replacements: Number of successfull replacemnts
    :param max_area_overhead: koeff for defined maximum area of generated circuit related to initial circuit (from 1.0)
    :return: true or false
    """
    overall_start = timeit.default_timer()
    calc_type = 1
    print("Start processing circuit:")
    main_circuit_etalon = sa.read_scheme(in_circ_file)
    initial_area = get_area(main_circuit_etalon)
    initial_circ_delay = getMaxLevel(main_circuit_etalon)
    main_circuit = sa.read_scheme(in_circ_file)
    (initial_reliability,
     vulnerability_map) = external_vulnerability_map(main_circuit,
                                                     MONTE_CARLO_ITER)
    latest_reliability = initial_reliability
    success_replacements_part1 = 0
    success_replacements = 0
    between_replacements = 0
    iterations = 50000

    bestFunction = [0] * 6
    bestFunctionReplace = [0] * 6
    inputOutputTotal = dict()
    inputOutputReplacements = dict()
    replacementLevelIncrease = []

    for zzz in range(1, iterations):
        print("\n|||||||||||||| Iteration " + zzz.__str__() +
              " ||||||||||||||")
        # main_circuit = cleanCKTFromBUFs(main_circuit)
        if calc_type == 1:
            rnd1 = get_random_subcircuit_v2(main_circuit, vulnerability_map,
                                            random.randint(2, 6), 1)
        else:
            rnd1 = get_random_subcircuit(main_circuit, random.randint(2, 6), 1)

        if rnd1.inputs() < 2:
            print("Too small subckt")
            continue
        if rnd1.inputs() > 9:
            print("Too big subckt")
            continue
        if rnd1.outputs() > 11:
            print("Too many outputs subckt")
            continue

        if (rnd1.inputs(), rnd1.outputs()) in inputOutputTotal:
            inputOutputTotal[rnd1.inputs(), rnd1.outputs()] += 1
        else:
            inputOutputTotal[rnd1.inputs(), rnd1.outputs()] = 1

        between_replacements += 1
        print("OK subckt [Inputs: {} Outputs: {}]".format(
            rnd1.inputs(), rnd1.outputs()))
        trtable = create_truth_table(rnd1)
        data = goEspresso_external(trtable, rnd1)

        # Здесь добавляем произвольный набор схем претендентов на замену
        t1 = current_milli_time()
        subckt = []
        try:
            sckt1 = createSubckt_method1(data, rnd1)
            subckt.append(sckt1)
        except:
            print('Error in subckt generation 1')
        try:
            sckt1 = createSubckt_method2(data, rnd1)
            subckt.append(sckt1)
        except:
            print('Error in subckt generation 2')
        try:
            sckt1 = createSubckt_method3(data, rnd1)
            subckt.append(sckt1)
        except:
            print('Error in subckt generation 3')
        yosys_subckt = create_circuit_external_yosys(rnd1)
        if yosys_subckt != None:
            subckt.append(yosys_subckt)
        if 0:
            tmrSubCkt = createTMRCirc(rnd1)
            # Проверяем что троирование не приведет к увеличению схемы сверх указанного
            if (get_area(main_circuit) - get_area(rnd1) +
                    get_area(tmrSubCkt)) < initial_area * max_area_overhead:
                subckt.append(tmrSubCkt)
            else:
                print('TMR SUBCKT skipped due to large area growth')
        t2 = current_milli_time()
        # print('Gen {} subckt OK. Generation time: {}'.format(len(subckt), round((t2-t1)/1000, 3)))

        # Проверяем что все сгенерированные подсхемы работают одинаково
        # Это можно будет убрать после полноценного тестирования
        for s in subckt:
            try:
                cmp = scheme_cmp(rnd1, s)
                if cmp == False:
                    print('Subckt have less inputs. Skip for now')
                    continue
                elif cmp < 0.99999:
                    print('Error with subckt it works incorrect check it')
                    exit(0)
            except:
                print(rnd1)
                print(s)
                main_circuit.print_circuit_in_file(
                    os.path.join(get_project_directory(), 'temp',
                                 'main_circuit_io_problem.txt'))
                rnd1.print_circuit_in_file(
                    os.path.join(get_project_directory(), 'temp',
                                 'rnd1_io_problem.txt'))
                s.print_circuit_in_file(
                    os.path.join(get_project_directory(), 'temp',
                                 'subckt_io_problem.txt'))
                print('Error: Input/output problem')
                continue

        # Рассчитываем вероятности комбинаций на входах подсхемы
        iternum = pow(2, rnd1.inputs()) * 1000
        t1 = current_milli_time()
        distr = distribution_estim_external(main_circuit, rnd1.input_labels(),
                                            rnd1.output_labels(), iternum)
        t2 = current_milli_time()
        # print('Distribution Estim C: {} seconds'.format(round((t2-t1)/1000, 3)))
        t1 = current_milli_time()
        subckt_reliability = external_reliability_uneven(rnd1, distr)
        t2 = current_milli_time()
        # print('Reliability uneven: {} seconds'.format(round((t2-t1)/1000, 3)))
        bestval = subckt_reliability + 1000000

        # Из набора подсхем выбираем самую надежную
        t1 = current_milli_time()
        subCKTNum = 0
        bestCKTIndex = 0
        allVals = []
        for s in subckt:
            subCKTNum += 1
            if s.input_labels() != rnd1.input_labels():
                print('Invalid input order in subckt')
                print(s.input_labels())
                print(rnd1.input_labels())
                exit()

            val2 = external_reliability_uneven(s, distr)
            allVals.append(val2)
            if val2 < bestval:
                bestckt = copy.deepcopy(s)
                bestval = val2
                bestCKTIndex = subCKTNum

        bestFunction[bestCKTIndex] += 1
        t2 = current_milli_time()
        # print('Get best CKT {}: {} seconds'.format(bestCKTIndex, round((t2-t1)/1000, 3)))

        print('Array of reliability: {}'.format(allVals))
        if subckt_reliability > bestval + 0.05:
            print("Success (Stage 1) {} > {} (CKT Index {})! =)".format(
                subckt_reliability, bestval, bestCKTIndex))
            success_replacements_part1 += 1
            t1 = current_milli_time()
            main_circuit_new = replace_subckt_v2(main_circuit, rnd1, bestckt)
            t2 = current_milli_time()
            # print('Replace subckt: {} seconds'.format(round((t2-t1)/1000, 3)))
            t1 = current_milli_time()
            (val_main_circuit_new,
             vulnerability_new) = external_vulnerability_map(
                 main_circuit_new, MONTE_CARLO_ITER)
            compare_same_logic_for_circuit_monte_carlo(main_circuit,
                                                       main_circuit_new, 10)
            if latest_reliability > val_main_circuit_new:
                print("Success (Stage 2) {} > {} ! =)".format(
                    latest_reliability, val_main_circuit_new))
                # Заменяем карту уязвимостей
                vulnerability_map = copy.deepcopy(vulnerability_new)
                main_circuit = copy.deepcopy(main_circuit_new)
                latest_reliability = val_main_circuit_new
                cur_area = get_area(main_circuit_new)
                print(
                    'New area: {} Initial Area: {} Growth Percent: {}%'.format(
                        cur_area, initial_area,
                        round((100.0 * cur_area) / initial_area), 2))
                success_replacements += 1
                between_replacements = 0
                # Статистика по входам выходам замененной подсхемы
                if (rnd1.inputs(), rnd1.outputs()) in inputOutputReplacements:
                    inputOutputReplacements[rnd1.inputs(), rnd1.outputs()] += 1
                else:
                    inputOutputReplacements[rnd1.inputs(), rnd1.outputs()] = 1
                # Сохраняем значение увеличения уровней подсхемы
                levelRnd1 = getMaxLevel(rnd1)
                levelBestCkt = getMaxLevel(bestckt)
                replacementLevelIncrease.append(levelBestCkt / levelRnd1)
                bestFunctionReplace[bestCKTIndex] += 1
            else:
                print("Fail (Stage 2) {} < {} ! =(".format(
                    latest_reliability, val_main_circuit_new))
                # Для тестирования ошибок во внешней проге
                rnd1.print_circuit_in_file(
                    os.path.join(get_project_directory(), 'temp', 'rnd1.txt'))
                bestckt.print_circuit_in_file(
                    os.path.join(get_project_directory(), 'temp',
                                 'subckt.txt'))
                main_circuit.print_circuit_in_file(
                    os.path.join(get_project_directory(), 'temp',
                                 'main_circuit.txt'))
                main_circuit_new.print_circuit_in_file(
                    os.path.join(get_project_directory(), 'temp',
                                 'main_circuit_new.txt'))

            t2 = current_milli_time()
            print('External reliability: {} seconds'.format(
                round((t2 - t1) / 1000, 3)))
            if success_replacements >= needed_replacements:
                break
        else:
            print("Fail (Stage 1)! =( " + subckt_reliability.__str__() +
                  " <= " + bestval.__str__())

        # Если за тысячу итераций не было успешных замен выходим
        if between_replacements > 1000:
            break

    endpoint_reliability = external_reliability(main_circuit, MONTE_CARLO_ITER)
    print("Total Iterations : " + zzz.__str__())
    print("Success replacements (P1): " + success_replacements_part1.__str__())
    print("Success replacements (P2): " + success_replacements.__str__())
    if success_replacements_part1 == 0:
        percent = 100
    else:
        percent = round(
            (100 * success_replacements) / success_replacements_part1, 2)
    print("Success rate: ", percent.__str__())
    print("Initial  reliability: " + initial_reliability.__str__())
    print("Endpoint reliability: " + endpoint_reliability.__str__())
    print("Initial number of elements: {}".format(initial_area))
    print("Endpoint number of elements: {}".format(get_area(main_circuit)))
    print("Best subckt generators: {}".format(bestFunction))
    overall_end = timeit.default_timer()
    print("Total runtime: {} seconds".format((overall_end - overall_start)))
    main_circuit.print_circuit_in_file(out_circ_file)
    compare_same_logic_for_circuit_monte_carlo(main_circuit_etalon,
                                               main_circuit, 1000)
    printInputOutputNumbersInReplaceStats(inputOutputTotal,
                                          inputOutputReplacements)
    printLevelIncreaseStat(replacementLevelIncrease)
    print("Best CKT for replace")
    print(bestFunctionReplace)
    resynt_circ_delay = getMaxLevel(main_circuit)
    circ_delay_percent = round((100 * resynt_circ_delay) / initial_circ_delay,
                               2)
    print("Levels in circ. Initial: {}, Resyntesized: {}, Percent: {}".format(
        initial_circ_delay, resynt_circ_delay, circ_delay_percent))
Exemple #14
0
        os.remove(os.path.join(run_path, s1_path))
    if os.path.isfile(os.path.join(run_path, s2_path)):
        os.remove(os.path.join(run_path, s2_path))
    return result


def eq_check(sch1, sch2):
    '''
     Проводим проверку на эквивалентность двух схем в
     SchemeAlt() формате - sch1 и sch2
     :return: возвращаем 1 - в случае эквивалентности
                         0 - в обратном случае
                         сообщение об ошибке - при ошибке
     '''

    dfile = os.path.dirname(get_project_directory())
    run_path = os.path.join(dfile, "utils", "bin", "win32", "abc")
    s1_path = 'sch1.v'
    s2_path = 'sch2.v'
    sch1.print_verilog_in_file(os.path.join(run_path, s1_path), "top")
    sch2.print_verilog_in_file(os.path.join(run_path, s2_path), "top")
    ret = equivalence_check_abc()
    return ret


if __name__ == '__main__':
    c17 = sc.read_scheme("..\\circuits\\ISCAS\\c17.txt")
    c18 = sc.read_scheme("..\\circuits\\ISCAS\\c17.txt")
    print(eq_check(c17, c18))
    c18.__elements__['G10gat'] = ('AND', ['G1gat', 'G3gat'])
    print(eq_check(c17, c18))
    for i in range(n_outputs):
        result[i] = list(bin(result[i])[2:].zfill(capacity))
        for j in range(capacity):
            result[i][j] = int(result[i][j])

    for i in range(n_outputs):
        check[i] = list(bin(check[i])[2:].zfill(capacity))
        for j in range(capacity):
            check[i][j] = int(check[i][j])

    result = np.transpose(result)
    check = np.transpose(check)

    for i in range(capacity):
        outputs_ced_check.append(np.array_equal(result[i], check[i]))

    # Подсчет колличества ошибок каждого типа
    for i in range(capacity):
        if outputs_ced_check[i]: t_errors[0] += 1  # Маскирование ошибки
        elif not outputs_ced_check[i]: t_errors[1] += 1  # Пропуск ошибки

    return t_errors


shem = sch.read_scheme(
    'C://Users//Polinka//PycharmProjects//for_resume//LGSynth89//vg2.txt')
swc = create_ced(shem, 0)
t_errors, num = error_simulations(swc, 10000)
print('El', swc.elements())
print('SWC_err', t_errors, num)
#shem.display_truth_table()