Exemplo n.º 1
0
def MapToKarnaughMap(_map):
    # Turn map to MapToKarnaugh Maps
    # Generate ReverseBinCode
    index = ReverseBinCode(len(_map[0]))
    #index = np.array([[int(char) for char in strcode] for strcode in index])

    dim1 = (int(len(_map[0]) / 2))
    dim2 = (len(_map[0]) - int(len(_map[0]) / 2))
    #print('dim =', dim1, 'x', dim2)

    gc1 = GrayCode(dim1)
    gc2 = GrayCode(dim2)
    gd1 = dict(zip(list(gc1.generate_gray()), range(2**dim1)))
    gd2 = dict(zip(list(gc2.generate_gray()), range(2**dim2)))
    #print(gd1)
    #print(gd2)

    _map = np.array(_map).T
    KarnaughMaps = []
    for targetStates in _map:
        #print('-------')
        Karnaugh = np.array(([[0] * (2**dim1)]) * (2**dim2)).T
        #print(Karnaugh)
        for state, mcode in zip(index, targetStates):
            #print(state, '->', mcode)
            #print('c1=',state[0:dim1])
            #print('c2=',state[dim1:])
            Karnaugh[gd1[state[0:dim1]], gd2[state[dim1:]]] = mcode
        KarnaughMaps += [Karnaugh]
        #print(Karnaugh)

    return np.array(KarnaughMaps)
Exemplo n.º 2
0
def test_graycode():
    g = GrayCode(2)
    got = []
    for i in g.generate_gray():
        if i.startswith('0'):
            g.skip()
        got.append(i)
    assert got == '00 11 10'.split()
    a = GrayCode(6)
    assert a.current == '0'*6
    assert a.rank == 0
    assert len(list(a.generate_gray())) == 64
    codes = ['011001', '011011', '011010',
    '011110', '011111', '011101', '011100', '010100', '010101', '010111',
    '010110', '010010', '010011', '010001', '010000', '110000', '110001',
    '110011', '110010', '110110', '110111', '110101', '110100', '111100',
    '111101', '111111', '111110', '111010', '111011', '111001', '111000',
    '101000', '101001', '101011', '101010', '101110', '101111', '101101',
    '101100', '100100', '100101', '100111', '100110', '100010', '100011',
    '100001', '100000']
    assert list(a.generate_gray(start='011001')) == codes
    assert list(
        a.generate_gray(rank=GrayCode(6, start='011001').rank)) == codes
    assert a.next().current == '000001'
    assert a.next(2).current == '000011'
    assert a.next(-1).current == '100000'

    a = GrayCode(5, start='10010')
    assert a.rank == 28
    a = GrayCode(6, start='101000')
    assert a.rank == 48

    assert GrayCode(6, rank=4).current == '000110'
    assert GrayCode(6, rank=4).rank == 4
    assert [GrayCode(4, start=s).rank for s in
            GrayCode(4).generate_gray()] == [0, 1, 2, 3, 4, 5, 6, 7, 8,
                                             9, 10, 11, 12, 13, 14, 15]
    a = GrayCode(15, rank=15)
    assert a.current == '000000000001000'

    assert bin_to_gray('111') == '100'

    a = random_bitstring(5)
    assert type(a) is str
    assert len(a) == 5
    assert all(i in ['0', '1'] for i in a)

    assert get_subset_from_bitstring(
        ['a', 'b', 'c', 'd'], '0011') == ['c', 'd']
    assert get_subset_from_bitstring('abcd', '1001') == ['a', 'd']
    assert list(graycode_subsets(['a', 'b', 'c'])) == \
        [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'],
         ['a', 'c'], ['a']]

    raises(ValueError, lambda: GrayCode(0))
    raises(ValueError, lambda: GrayCode(2.2))
    raises(ValueError, lambda: GrayCode(2, start=[1, 1, 0]))
    raises(ValueError, lambda: GrayCode(2, rank=2.5))
    raises(ValueError, lambda: get_subset_from_bitstring(['c', 'a', 'c'], '1100'))
    raises(ValueError, lambda: list(GrayCode(3).generate_gray(start="1111")))
Exemplo n.º 3
0
def test_graycode():
    g = GrayCode(2)
    got = []
    for i in g.generate_gray():
        if i.startswith('0'):
            g.skip()
        got.append(i)
    assert got == '00 11 10'.split()
    a = GrayCode(6)
    assert a.current == '0'*6
    assert a.rank == 0
    assert len(list(a.generate_gray())) == 64
    codes = ['011001', '011011', '011010',
    '011110', '011111', '011101', '011100', '010100', '010101', '010111',
    '010110', '010010', '010011', '010001', '010000', '110000', '110001',
    '110011', '110010', '110110', '110111', '110101', '110100', '111100',
    '111101', '111111', '111110', '111010', '111011', '111001', '111000',
    '101000', '101001', '101011', '101010', '101110', '101111', '101101',
    '101100', '100100', '100101', '100111', '100110', '100010', '100011',
    '100001', '100000']
    assert list(a.generate_gray(start='011001')) == codes
    assert list(
        a.generate_gray(rank=GrayCode(6, start='011001').rank)) == codes
    assert a.next().current == '000001'
    assert a.next(2).current == '000011'
    assert a.next(-1).current == '100000'

    a = GrayCode(5, start='10010')
    assert a.rank == 28
    a = GrayCode(6, start='101000')
    assert a.rank == 48

    assert GrayCode(6, rank=4).current == '000110'
    assert GrayCode(6, rank=4).rank == 4
    assert [GrayCode(4, start=s).rank for s in
            GrayCode(4).generate_gray()] == [0, 1, 2, 3, 4, 5, 6, 7, 8,
                                             9, 10, 11, 12, 13, 14, 15]
    a = GrayCode(15, rank=15)
    assert a.current == '000000000001000'

    assert bin_to_gray('111') == '100'

    a = random_bitstring(5)
    assert type(a) is str
    assert len(a) == 5
    assert all(i in ['0', '1'] for i in a)

    assert get_subset_from_bitstring(
        ['a', 'b', 'c', 'd'], '0011') == ['c', 'd']
    assert get_subset_from_bitstring('abcd', '1001') == ['a', 'd']
    assert list(graycode_subsets(['a', 'b', 'c'])) == \
        [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'],
    ['a', 'c'], ['a']]
Exemplo n.º 4
0
def evaluate_fitness(name, fitness, k_color=False):
    if not k_color:
        problem = mlrose.DiscreteOpt(length=ILL_PROB_LENGTH,
                                     fitness_fn=fitness,
                                     maximize=True,
                                     max_val=2)
    else:
        problem = mlrose.MaxKColorGenerator.generate(
            seed=42, number_of_nodes=ILL_PROB_LENGTH, max_colors=2)
    result = []
    gray_code = GrayCode(ILL_PROB_LENGTH)
    for rep in gray_code.generate_gray():
        #        rep = np.binary_repr(i, ILL_PROB_LENGTH)
        state = [int(c) for c in rep]
        if k_color:
            res = ILL_PROB_LENGTH - problem.eval_fitness(state) + 1
        else:
            res = problem.eval_fitness(state)
        result.append(res)
    result = np.asarray(result)
    result /= result.max()
    df = pd.DataFrame(result, columns=[f'{name}'])
    plt.clf()
    df.plot(xlabel='Gray code index', ylabel='Fitness')
    savefig(name)
def IsCubicHamilton(n):
    if n > 1:
        print('There is a Hamilton cycly for the cubic Q', n, "graph")
        a = GrayCode(n)
        print(list(a.generate_gray()))
    else:
        print("There isn't a Hamilton path")
Exemplo n.º 6
0
def get_binmap(discrete_dim, binmode):
    b = discrete_dim // 2 - 1
    all_bins = []
    for i in range(1 << b):
        bx = np.binary_repr(i, width=discrete_dim // 2 - 1)
        all_bins.append('0' + bx)
        all_bins.append('1' + bx)
    vals = all_bins[:]
    if binmode == 'rand':
        print('remapping binary repr with random permute')
        random.shuffle(vals)
    elif binmode == 'gray':
        print('remapping binary repr with gray code')
        a = GrayCode(b)
        vals = []
        for x in a.generate_gray():
            vals.append('0' + x)
            vals.append('1' + x)
    else:
        assert binmode == 'normal'
    bm = {}
    inv_bm = {}
    for i, key in enumerate(all_bins):
        bm[key] = vals[i]
        inv_bm[vals[i]] = key
    return bm, inv_bm
Exemplo n.º 7
0
def test_graycode():
    a = GrayCode(6)
    assert a.current == '0' * 6
    assert a.rank == 0
    assert len(list(a.generate_gray())) == 64
    codes = [
        '011001', '011011', '011010', '011110', '011111', '011101', '011100',
        '010100', '010101', '010111', '010110', '010010', '010011', '010001',
        '010000', '110000', '110001', '110011', '110010', '110110', '110111',
        '110101', '110100', '111100', '111101', '111111', '111110', '111010',
        '111011', '111001', '111000', '101000', '101001', '101011', '101010',
        '101110', '101111', '101101', '101100', '100100', '100101', '100111',
        '100110', '100010', '100011', '100001', '100000'
    ]
    assert list(a.generate_gray(start='011001')) == codes
    assert list(
        a.generate_gray(rank=GrayCode(6, start='011001').rank)) == codes
    assert a.next().current == '000001'
    assert a.next(2).current == '000011'
    assert a.next(-1).current == '100000'

    a = GrayCode(5, start='10010')
    assert a.rank == 28
    a = GrayCode(6, start='101000')
    assert a.rank == 48

    assert GrayCode(6, rank=4).current == '000110'
    assert GrayCode(6, rank=4).rank == 4
    assert [GrayCode(4, start=s).rank for s in \
            GrayCode(4).generate_gray()] == [0, 1, 2, 3, 4, 5, 6, 7, 8, \
                                             9, 10, 11, 12, 13, 14, 15]
    a = GrayCode(15, rank=15)
    assert a.current == '000000000001000'

    assert bin_to_gray('111') == '100'

    a = random_bitstring(5)
    assert type(a) is str
    assert len(a) == 5
    assert all(i in ['0', '1'] for i in a)

    assert get_subset_from_bitstring(['a', 'b', 'c', 'd'],
                                     '0011') == ['c', 'd']
    assert get_subset_from_bitstring('abcd', '1001') == ['a', 'd']
    assert list(graycode_subsets(['a','b','c'])) == \
    [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], \
    ['a', 'c'], ['a']]
Exemplo n.º 8
0
def gray_to_int(bits):
    a = GrayCode(bits)
    grayCodes = list(a.generate_gray())

    grayDict = {}
    for i, grayCode in enumerate(grayCodes):
        grayDict[grayCode] = i

    return (grayDict)
Exemplo n.º 9
0
def PSK(M,sequence,Tb,fc,phase=0):
    """M-Phase Shift Keying Modulation. Returns modulated signal"""
    k=[]
    n=[]
    gray_values=GrayCode(math.log(M,2))
    gray_values=list(gray_values.generate_gray())
    for j in range(len(sequence)):
        n1=np.arange(math.log(M,2)*Tb*j,math.log(M,2)*Tb*(j+1),1/1000)
        n=np.append(n,n1)
        k=np.append(k,AM*np.cos(2*math.pi*fc*n1+2*math.pi*gray_values.index(sequence[j])/M)+phase)
    return n,k
Exemplo n.º 10
0
def test_graycode():
    a = GrayCode(6)
    assert a.current == '0'*6
    assert a.rank == 0
    assert len(list(a.generate_gray())) == 64
    codes = ['011001', '011011', '011010',
    '011110', '011111', '011101', '011100', '010100', '010101', '010111',
    '010110', '010010', '010011', '010001', '010000', '110000', '110001',
    '110011', '110010', '110110', '110111', '110101', '110100', '111100',
    '111101', '111111', '111110', '111010', '111011', '111001', '111000',
    '101000', '101001', '101011', '101010', '101110', '101111', '101101',
    '101100', '100100', '100101', '100111', '100110', '100010', '100011',
    '100001', '100000']
    assert list(a.generate_gray(start='011001')) == codes
    assert list(a.generate_gray(rank=GrayCode(6, start='011001').rank)) == codes
    assert a.next().current == '000001'
    assert a.next(2).current == '000011'
    assert a.next(-1).current == '100000'

    a = GrayCode(5, start='10010')
    assert a.rank == 28
    a = GrayCode(6, start='101000')
    assert a.rank == 48

    assert GrayCode(6, rank=4).current == '000110'
    assert GrayCode(6, rank=4).rank == 4
    assert [GrayCode(4, start=s).rank for s in \
            GrayCode(4).generate_gray()] == [0, 1, 2, 3, 4, 5, 6, 7, 8, \
                                             9, 10, 11, 12, 13, 14, 15]
    a = GrayCode(15, rank=15)
    assert a.current == '000000000001000'

    assert bin_to_gray('111') == '100'
    random.seed(0)
    assert [random_bitstring(5) for i in range(3)] == ['11001', '01001', '11011']
    assert get_subset_from_bitstring(['a','b','c','d'], '0011') == ['c', 'd']
    assert get_subset_from_bitstring('abcd','1001') == ['a', 'd']
    assert list(graycode_subsets(['a','b','c'])) == \
    [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], \
    ['a', 'c'], ['a']]
def quantized_sampled_signal(signal, t, title_of_graph):
    L = 2**5  #total number of levels in binary -> L=2**q for q=5 bits
    D = 8 / L  #step size=D=2*A/L for A=4 Volts
    quantized_signal = D * np.round(signal / D)
    g = GrayCode(5)  #the 5-dimensional cube is created
    code_gray = list(g.generate_gray())  #its values are put in an array
    plt.yticks(np.arange(-4, 4 + D, step=D), code_gray)  #from -A to A+D
    plt.step(t, quantized_signal, label='Quantized Sampled Signal')
    plt.legend(loc='upper right')
    plt.xlabel("Time (Sec)")
    plt.ylabel(str(5) + "Gray Code bits")
    plt.title("Output of the Quantizer")
    plt.grid()
    plt.savefig(title_of_graph + ".jpg")
    plt.show()
    return quantized_signal
Exemplo n.º 12
0
def merge_supremum2(starting_intervals: List[HyperRectangle], show_bar=True) -> List[HyperRectangle]:
    """merge all the intervals provided, assumes they all have the same action"""
    if len(starting_intervals) <= 1:
        return starting_intervals
    # intervals: List[HyperRectangle] = [x for x in starting_intervals if not is_negligible(x)]  # remove size 0 intervals
    intervals = starting_intervals
    if len(intervals) <= 1:
        return intervals
    state_size = len(intervals[0])
    merged_list = []

    with StandardProgressBar(prefix="Merging the intervals ", max_value=len(starting_intervals)) if show_bar else nullcontext()  as bar:
        i = 0
        while True:
            if show_bar:
                bar.update(max(len(starting_intervals) - len(intervals), 0))
            tree = utils.create_tree([(x, True) for x in intervals])
            # find leftmost interval
            boundaries = []
            for i in range(state_size):
                boundaries.append((float(tree.get_bounds()[i * 2]), float(tree.get_bounds()[i * 2 + 1])))
            boundaries = tuple(boundaries)
            a = GrayCode(state_size)
            codes = list(a.generate_gray())
            for c, code in enumerate(codes):
                new_boundaries = merge_iteration(boundaries, codes, c, tree, intervals)
                boundaries = new_boundaries
            if len(merged_list) != 0 and merged_list[len(merged_list) - 1] == boundaries:
                print("endless loop")
            # show_plot(intervals, [(boundaries, True)])
            # new_group_tree = utils.create_tree([(boundaries, True)])  # add dummy action
            # remainings, _ = compute_remaining_intervals4_multi(intervals, new_group_tree, debug=False)
            remainings = []
            for interval in intervals:
                remaining, _, _ = compute_remaining_intervals3(interval, [(boundaries, True)], debug=False)
                remainings.extend(remaining)

            merged_list.append(boundaries)
            if len(remainings) == 0:
                break
            intervals = remainings
            i += 1  # bar.update(i)
    return merged_list
Exemplo n.º 13
0
def gray(num):
    gg = GrayCode(num)
    result = list(gg.generate_gray())
    return result
Exemplo n.º 14
0
levels = 2**bits - 1
delta = 4.0 / levels  # απόσταση μεταξύ των levels

fs = fm * 45
time1 = sample_time(fm, fs, 4)
y = signal_sq_triangle(A, fm, time1)
y_quantized = np.zeros(len(y))
h = np.zeros(len(y))
for i in range(0, len(y)):
    h[i] = 2 * (y[i] // delta) + 1
    y_quantized[i] = (
        delta / 2) * h[i]  # mid riser, y_quantized = delta*([y/delta]+0.5)
y_axis = np.linspace(-4 + delta / 2, 4 - delta / 2, 16)
G_C = GrayCode(4)
grid(True)
plt.yticks(y_axis, G_C.generate_gray())

plt.stem(time1, y_quantized)
plt.xlabel("Time (sec)")
plt.ylabel("Quantizing Levels ( Natural Binary Coding 4bit )")
plt.title("Quantized Signal")
plt.show()


#b meros
def SNR(y, y_quantized, length):
    # η συνάρτηση υπολογίζει το Quantum error
    quantization_error = y_quantized - y
    average_error = 0
    for i in range(length):
        average_error += quantization_error[i] / length
Exemplo n.º 15
0
def gray_code_permutation(n):  # Generate the N grey code permutation matrix
    N = int(math.log(n, 2))
    graycode = GrayCode(N)
    graycode_list = list(graycode.generate_gray())
    return (Mat_of_ones_from_list_index(conv_list_b2_b10((graycode_list))))
Exemplo n.º 16
0
def test_graycode():
    g = GrayCode(2)
    got = []
    for i in g.generate_gray():
        if i.startswith("0"):
            g.skip()
        got.append(i)
    assert got == "00 11 10".split()
    a = GrayCode(6)
    assert a.current == "0" * 6
    assert a.rank == 0
    assert len(list(a.generate_gray())) == 64
    codes = [
        "011001",
        "011011",
        "011010",
        "011110",
        "011111",
        "011101",
        "011100",
        "010100",
        "010101",
        "010111",
        "010110",
        "010010",
        "010011",
        "010001",
        "010000",
        "110000",
        "110001",
        "110011",
        "110010",
        "110110",
        "110111",
        "110101",
        "110100",
        "111100",
        "111101",
        "111111",
        "111110",
        "111010",
        "111011",
        "111001",
        "111000",
        "101000",
        "101001",
        "101011",
        "101010",
        "101110",
        "101111",
        "101101",
        "101100",
        "100100",
        "100101",
        "100111",
        "100110",
        "100010",
        "100011",
        "100001",
        "100000",
    ]
    assert list(a.generate_gray(start="011001")) == codes
    assert list(
        a.generate_gray(rank=GrayCode(6, start="011001").rank)) == codes
    assert a.next().current == "000001"
    assert a.next(2).current == "000011"
    assert a.next(-1).current == "100000"

    a = GrayCode(5, start="10010")
    assert a.rank == 28
    a = GrayCode(6, start="101000")
    assert a.rank == 48

    assert GrayCode(6, rank=4).current == "000110"
    assert GrayCode(6, rank=4).rank == 4
    assert [GrayCode(4, start=s).rank
            for s in GrayCode(4).generate_gray()] == [
                0,
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10,
                11,
                12,
                13,
                14,
                15,
            ]
    a = GrayCode(15, rank=15)
    assert a.current == "000000000001000"

    assert bin_to_gray("111") == "100"

    a = random_bitstring(5)
    assert type(a) is str
    assert len(a) == 5
    assert all(i in ["0", "1"] for i in a)

    assert get_subset_from_bitstring(["a", "b", "c", "d"],
                                     "0011") == ["c", "d"]
    assert get_subset_from_bitstring("abcd", "1001") == ["a", "d"]
    assert list(graycode_subsets(["a", "b", "c"])) == [
        [],
        ["c"],
        ["b", "c"],
        ["b"],
        ["a", "b"],
        ["a", "b", "c"],
        ["a", "c"],
        ["a"],
    ]

    raises(ValueError, lambda: GrayCode(0))
    raises(ValueError, lambda: GrayCode(2.2))
    raises(ValueError, lambda: GrayCode(2, start=[1, 1, 0]))
    raises(ValueError, lambda: GrayCode(2, rank=2.5))
    raises(ValueError,
           lambda: get_subset_from_bitstring(["c", "a", "c"], "1100"))
    raises(ValueError, lambda: list(GrayCode(3).generate_gray(start="1111")))
Exemplo n.º 17
0
        
qlevels = np.linspace(min(values), max(values), 2**8)   # με 8 bits μπορούμε να απεικονίσουμε 2^8 = 256 επίπεδα

# η συνάρτηση μας βρίσκει το στοιχείο ενός πίνακα array που απέχει τη μικρότερη απόσταση από την τιμή του signal
def find_level(array, signal):
    level = (np.abs(array-signal)).argmin()
    return array[level]

quantized = []
for v in values:
    q = find_level(qlevels, v)
    quantized.append(q)
    
# Φτιάχνουμε τα επίπεδα κβάντισης με κωδικοποίηση Gray
a = GrayCode(8)
graylevels = list(a.generate_gray())

chars = np.arange(0,len(quantized),1)

fig = plt.figure(figsize=(170,150))
plt.yticks(qlevels, graylevels, fontsize = 55)
plt.step(chars, quantized, where = 'mid', color = 'blue')
plt.title('8-bit Quantized text signal', fontsize = 100)
plt.xlabel('Chars', fontsize = 80)
plt.ylabel('Quantized levels (Gray Code 8 bits)', fontsize = 80)
plt.show()


pulse = lambda b : 2*int(b) - 1

bitI = []
Exemplo n.º 18
0
def getGrayIndixes(bitWidth):
    gray = GrayCode(bitWidth)
    return [int(strb, 2) for strb in gray.generate_gray()]
Exemplo n.º 19
0
def main():
    count = 50
    xg = np.linspace(-5, 5, num=10000)
    yg = 0.4 * np.sin(0.8 * xg + 0.9) + 0.7 * np.cos(0.8 * xg - 1) * np.sin(7.3 * xg)
    population = []
    population1 = []
    population3 = []
    g = GrayCode(20)
    g = list(g.generate_gray())
    fig = plt.figure()
    ax_1 = fig.add_subplot(2, 1, 1)
    ax_2 = fig.add_subplot(2, 2, 3)
    ax_3 = fig.add_subplot(2, 2, 4)
    for i in range(count):
        r = random.randint(0, len(g) - 1)
        population.append(Population(g[r]))
    for i in range(50):  # чисто поколений
        tmp_pop = create_population(population)
        population = []
        population = tmp_pop
        tmp_pop = []
        tmp_pop = roll(population)
        population = []
        population = tmp_pop
        tmp_pop = []
        if i == 0:
            ax_1.plot(xg, yg)
            for el in population:
                population1.append(el)
            plot_some(population, ax_1)
        if i == 3:
            ax_2.plot(xg, yg)
            for el in population:
                population3.append(el)
            plot_some(population, ax_2)
    ax_3.plot(xg, yg)
    plot_some(population, ax_3)
    plt.show()
    sum1 = 0
    sum3 = 0
    sum50 = 0
    for i in range(len(population)):
        sum1 += population1[i].fp
        sum3 += population3[i].fp
        sum50 += population[i].fp
    print("Средние приспособленности 1, 3 и 50 поколений:")
    print(str(sum1 / 50))
    print(str(sum3 / 50))
    print(str(sum50 / 50))

    print("1 популяция:")
    print("{0:^2} | {1:^6} | {2:^20} | {3:^6} | {4:^6}".format("№", "X", "Хромосома", "Fc(x)", "Fp(x)"))
    for i in range(len(population1)):
        print("{0:2} | {1:=6} | {2} | {3:=6} | {4:^6}".format(i, round(population1[i].x, 3), population1[i].chromosome,
                                                              round(population1[i].fc, 3), round(population1[i].fp, 3)))
    print("")
    print("3 популяция:")
    print("{0:^2} | {1:^6} | {2:^20} | {3:^6} | {4:^6}".format("№", "X", "Хромосома", "Fc(x)", "Fp(x)"))
    for i in range(len(population3)):
        print("{0:2} | {1:=6} | {2} | {3:=6} | {4:^6}".format(i, round(population3[i].x, 3), population3[i].chromosome,
                                                              round(population3[i].fc, 3), round(population3[i].fp, 3)))
    print("")
    print("50 популяция:")
    print("{0:^2} | {1:^6} | {2:^20} | {3:^6} | {4:^6}".format("№", "X", "Хромосома", "Fc(x)", "Fp(x)"))
    for i in range(len(population)):
        print("{0:2} | {1:=6} | {2} | {3:=6} | {4:^6}".format(i, round(population[i].x, 3), population[i].chromosome,
                                                              round(population[i].fc, 3), round(population[i].fp, 3)))
Exemplo n.º 20
0
    """A function that takes the input x of a Mid Riser quantizer
    and returns the output of the quantizer"""
    return D*(math.floor(x/D)+1/2)

i=Mid_Riser(-2) 					 #lowest quantization level
quantize_levels=[]
for j in range(2**Q):                       #create the quantization levels
    quantize_levels.append(round(i,6))
    i+=D
fs=40*fm #sampling frequency
yd,n=sample_signal(trig,fs,0,4*T) #sampling of triagonal wave with fs=40fm sampling frequency
y_quantized=list(map(Mid_Riser,yd)) #quantization of sampled signal
for j in range(len(y_quantized)): #rounding the quantized values to match quantization levels
    y_quantized[j]=round(y_quantized[j],6)
gray_values=GrayCode(Q) #generate the Gray Code for quantization levels
gray_values=list(gray_values.generate_gray())

#plot the quantizer's output
plt.figure()
plt.xlabel("Time(seconds)")
plt.ylabel("Quantizer Output")
plt.title("6-bits Mid-Riser Quantization of triangle wave 2V,{}Hz(fm) ".format(fm))
plt.yticks(quantize_levels,gray_values, fontsize=5)
plt.step(n,y_quantized,"g",linewidth=0.5,where='post') #parameter where="post" in order to have the correct graph
plt.grid()

#part 2b
def calculate_SNRq(y,y_quantized,N):
    """This function calculates quantization error's variance
    and SNRq"""
    q=[]