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")
    def _define(self):

        q = QuantumRegister(self.num_qubits, "q")
        qc = QuantumCircuit(q, name=self.name)

        theta = compute_theta(self.alpha)  # type: sparse.dok_matrix

        gray_code_rank = self.num_qubits - 1
        if gray_code_rank == 0:
            qc.append(self.gate(theta[0, 0]), [q[0]], [])
        else:
            from sympy.combinatorics.graycode import GrayCode
            gc = GrayCode(gray_code_rank)  # type: GrayCode

            current_gray = gc.current
            for i in range(gc.selections):
                qc.append(self.gate(theta[i, 0]), [q[-1]], [])
                next_gray = gc.next(i + 1).current

                control_index = int(
                    np.log2(int(current_gray, 2) ^ int(next_gray, 2)))
                qc.append(CXGate(), [q[control_index], q[-1]], [])

                current_gray = next_gray

        self._definition = qc
Esempio n. 3
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
Esempio 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)
Esempio n. 5
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)
Esempio n. 6
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
Esempio n. 7
0
def de2gray(d,n):    
    
    gray_list_str = list(GrayCode(n).generate_gray())
    gray_list = list(map(lambda ind: np.array(list(gray_list_str[ind]), dtype=np.int), range(len(gray_list_str))))
    g = list(map(lambda ind: gray_list[int(d[ind])], range(0,len(d))))

    return np.array(g)
Esempio n. 8
0
def generateWorstRepresentation(nbits, name = 'w'):
    """
    returns an encoding on nbits that has the worst locality using Harpers algorithm.
    """
    b = nbits
    c = list(GrayCode(b).generate_gray())
    rep = {}
    startstr = random.choice(c)
    parity = startstr.count("1") % 2
    rep[startstr] = 0

    sameParity = list(filter(lambda x: x.count("1")%2 == parity, c))
    sameParity.remove(startstr)
    random.shuffle(sameParity)

    oppParity = list(filter(lambda x: x.count("1")%2 != parity, c))
    random.shuffle(oppParity)

    assert(len(sameParity) + 1 + len(oppParity) == len(c))

    for i in range(len(sameParity)):
        rep[sameParity[i]] = i + 1

    for i in range(len(oppParity)):
        rep[oppParity[i]] = i + 2**(b-1)

    rp = Representation(rep, name)

    return Representation(rep, name)
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
Esempio n. 10
0
def generateRandomRepresentation(interval, name = 'r'):
    """
    returns a random mapping between bitstrings to numbers in the interval
    """
    b = numBitsToEncodeInterval(interval)
    c = list(GrayCode(b).generate_gray())
    random.shuffle(c)
    randRep = initializeEncodings(c, interval)
    return Representation(randRep, name)
Esempio n. 11
0
def generateAllReps(numbits):
    """
    returns a list of all representations on numbits bits
    """
    c = list(GrayCode(numbits).generate_gray())
    reps = []
    for perm in list(itertools.permutations(c)):
        reps.append(Representation(initializeEncodings(perm, (0, (2**numbits)-1, 1)), 'name'))
    return reps
Esempio n. 12
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']]
Esempio n. 13
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
Esempio n. 14
0
def generateGrayRepresentation(interval, b = None):
    """
    returns gray code as an instance of the Representation class 
    for a given real interval to be used in optimization
    """
    if b is None:
        b = numBitsToEncodeInterval(interval)
    gc = list(GrayCode(b).generate_gray())
    grayRep = initializeEncodings(gc, interval)
    return Representation(grayRep, "binary reflected gray")
Esempio n. 15
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)
Esempio n. 16
0
    def __init__(self, constellation, reorder_as_gray=True):
        """ Creates a custom Modem object. """

        if reorder_as_gray:
            m = log2(len(constellation))
            gray_code_sequence = GrayCode(m).generate_gray()
            gray_code_sequence_array = fromiter(
                (int(g, 2) for g in gray_code_sequence), int,
                len(constellation))
            self.constellation = array(constellation)[
                gray_code_sequence_array.argsort()]
        else:
            self.constellation = constellation
Esempio n. 17
0
    def unrank_gray(self, rank, superset):
        """
        Gets the Gray code ordered subset of the specified rank.

        Examples:
        >>> from sympy.combinatorics.subsets import Subset
        >>> Subset.unrank_gray(4, ['a','b','c']).subset
        ['a', 'b']
        >>> Subset.unrank_gray(0, ['a','b','c']).subset
        []
        """
        graycode_bitlist = GrayCode.unrank(len(superset), rank)
        return Subset.subset_from_bitlist(superset, graycode_bitlist)
Esempio n. 18
0
    def unrank_gray(self, rank, superset):
        """
        Gets the Gray code ordered subset of the specified rank.

        Examples
        ========
        >>> from sympy.combinatorics.subsets import Subset
        >>> Subset.unrank_gray(4, ['a','b','c']).subset
        ['a', 'b']
        >>> Subset.unrank_gray(0, ['a','b','c']).subset
        []
        """
        graycode_bitlist = GrayCode.unrank(len(superset), rank)
        return Subset.subset_from_bitlist(superset, graycode_bitlist)
Esempio n. 19
0
def _apply_mcu3_graycode(circuit, theta, phi, lam, ctls, tgt, use_basis_gates):
    """Apply multi-controlled u3 gate from ctls to tgt using graycode
    pattern with single-step angles theta, phi, lam."""

    n = len(ctls)

    from sympy.combinatorics.graycode import GrayCode
    gray_code = list(GrayCode(n).generate_gray())
    last_pattern = None

    for pattern in gray_code:
        if '1' not in pattern:
            continue
        if last_pattern is None:
            last_pattern = pattern
        # find left most set bit
        lm_pos = list(pattern).index('1')

        # find changed bit
        comp = [i != j for i, j in zip(pattern, last_pattern)]
        if True in comp:
            pos = comp.index(True)
        else:
            pos = None
        if pos is not None:
            if pos != lm_pos:
                circuit.cx(ctls[pos], ctls[lm_pos])
            else:
                indices = [i for i, x in enumerate(pattern) if x == '1']
                for idx in indices[1:]:
                    circuit.cx(ctls[idx], ctls[lm_pos])
        # check parity and undo rotation
        if pattern.count('1') % 2 == 0:
            # inverse CU3: u3(theta, phi, lamb)^dagger = u3(-theta, -lam, -phi)
            _apply_cu3(circuit,
                       -theta,
                       -lam,
                       -phi,
                       ctls[lm_pos],
                       tgt,
                       use_basis_gates=use_basis_gates)
        else:
            _apply_cu3(circuit,
                       theta,
                       phi,
                       lam,
                       ctls[lm_pos],
                       tgt,
                       use_basis_gates=use_basis_gates)
        last_pattern = pattern
Esempio n. 20
0
    def __init__(self, M, code_symbol, data_symbol, bit_rate, user, user_antenna, BS_antenna):
        """

        modulation class.

        Args:
            M : int = 4, 16, 64, 256
                  M-ary modulation number

            array_bit : 1D list [log2(M)]
                          Gray code list

                            ex) M = 4   : ['0', '1']
                                M = 16  : ['00', '01', '11', '10']
                                M = 64  : ['000', '001', '011', '010', '110', '111', '101', '100']
                                M = 256 : ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100',
                                           '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000']


            array_power : 1D ndarray [log2(M)]
                            the power list at placement point

                            ex) M = 4   : [-0.7071068  0.7071068]
                                M = 16  : [-0.9486833 -0.3162278  0.3162278  0.9486833]
                                M = 64  : [-1.0801234 -0.7715167 -0.46291   -0.1543033  0.1543033  0.46291    0.7715167  1.0801234]
                                M = 256 : [-1.1504475 -0.9970545 -0.8436615 -0.6902685 -0.5368755 -0.3834825 -0.2300895 -0.0766965
                                            0.0766965  0.2300895  0.3834825  0.5368755  0.6902685  0.8436615  0.9970545  1.1504475]


            threshould_power : 1D ndarray [log2(M) - 1 ]
                                 the power threshold for demodulation

                                 ex) M = 4   : [0.]
                                     M = 16  : [-0.6324555  0.         0.6324555]
                                     M = 64  : [-0.9258201 -0.6172134 -0.3086067  0.         0.3086067  0.6172134 0.9258201]
                                     M = 256 : [-1.073751  -0.920358  -0.766965  -0.613572  -0.460179  -0.306786  -0.153393  0.
                                                 0.153393   0.306786   0.460179   0.613572   0.766965   0.920358  1.073751]

        """

        self.M = M
        self.symbol = code_symbol
        self.data_symbol = data_symbol
        self.bit = bit_rate
        self.user = user
        self.user_antenna = user_antenna
        self.BS = BS_antenna
        self.array_bit = list((GrayCode(int(bit/2)).generate_gray()))
        self.array_power, self.threshould_power = self.calculate_power(M, bit)
Esempio n. 21
0
    def iterate_graycode(self, k):
        """
        Helper function used for prev_gray and next_gray.
        It performs k step overs to get the respective Gray codes.

        Examples:
        >>> from sympy.combinatorics.subsets import Subset
        >>> a = Subset([1,2,3], [1,2,3,4])
        >>> a.iterate_graycode(3).subset
        [1, 4]
        >>> a.iterate_graycode(-2).subset
        [1, 2, 4]
        """
        unranked_code = GrayCode.unrank(self.superset_size, (self.rank_gray + k) % self.cardinality)
        return Subset.subset_from_bitlist(self.superset, unranked_code)
Esempio n. 22
0
    def iterate_graycode(self, k):
        """
        Helper function used for prev_gray and next_gray.
        It performs k step overs to get the respective Gray codes.

        Examples
        ========
        >>> from sympy.combinatorics.subsets import Subset
        >>> a = Subset([1,2,3], [1,2,3,4])
        >>> a.iterate_graycode(3).subset
        [1, 4]
        >>> a.iterate_graycode(-2).subset
        [1, 2, 4]
        """
        unranked_code = GrayCode.unrank(
            self.superset_size, (self.rank_gray + k) % self.cardinality)
        return Subset.subset_from_bitlist(self.superset, unranked_code)
Esempio n. 23
0
    def rank_gray(self):
        """
        Computes the Gray code ranking of the subset.

        Examples
        ========
        >>> from sympy.combinatorics.subsets import Subset
        >>> a = Subset(['c','d'], ['a','b','c','d'])
        >>> a.rank_gray
        2
        >>> a = Subset([2,4,5], [1,2,3,4,5,6])
        >>> a.rank_gray
        27
        """
        if self._rank_graycode == None:
            bits = Subset.bitlist_from_subset(self.subset, self.superset)
            self._rank_graycode = GrayCode(len(bits), start=bits).rank
        return self._rank_graycode
def _apply_mcu3(circuit, theta, phi, lam, ctls, tgt):
    """Apply multi-controlled u3 gate from ctls to tgt with angles theta,
    phi, lam."""

    n = len(ctls)

    gray_code = list(GrayCode(n).generate_gray())
    last_pattern = None

    theta_angle = theta * (1 / (2**(n - 1)))
    phi_angle = phi * (1 / (2**(n - 1)))
    lam_angle = lam * (1 / (2**(n - 1)))

    for pattern in gray_code:
        if not '1' in pattern:
            continue
        if last_pattern is None:
            last_pattern = pattern
        #find left most set bit
        lm_pos = list(pattern).index('1')

        #find changed bit
        comp = [i != j for i, j in zip(pattern, last_pattern)]
        if True in comp:
            pos = comp.index(True)
        else:
            pos = None
        if pos is not None:
            if pos != lm_pos:
                circuit.cx(ctls[pos], ctls[lm_pos])
            else:
                indices = [i for i, x in enumerate(pattern) if x == '1']
                for idx in indices[1:]:
                    circuit.cx(ctls[idx], ctls[lm_pos])
        #check parity
        if pattern.count('1') % 2 == 0:
            #inverse
            apply_cu3(circuit, -theta_angle, phi_angle, lam_angle,
                      ctls[lm_pos], tgt)
        else:
            apply_cu3(circuit, theta_angle, phi_angle, lam_angle, ctls[lm_pos],
                      tgt)
        last_pattern = pattern
Esempio n. 25
0
def _apply_mcu1(circuit, lam, ctls, tgt, global_phase=0):
    """Apply multi-controlled u1 gate from ctls to tgt with angle theta."""

    n = len(ctls)

    gray_code = list(GrayCode(n).generate_gray())
    last_pattern = None

    lam_angle = lam * (1 / (2**(n - 1)))
    gp_angle = angle(global_phase) * (1 / (2**(n - 1)))

    for pattern in gray_code:
        if '1' not in pattern:
            continue
        if last_pattern is None:
            last_pattern = pattern
        # find left most set bit
        lm_pos = list(pattern).index('1')

        # find changed bit
        comp = [i != j for i, j in zip(pattern, last_pattern)]
        if True in comp:
            pos = comp.index(True)
        else:
            pos = None
        if pos is not None:
            if pos != lm_pos:
                circuit.cx(ctls[pos], ctls[lm_pos])
            else:
                indices = [i for i, x in enumerate(pattern) if x == '1']
                for idx in indices[1:]:
                    circuit.cx(ctls[idx], ctls[lm_pos])
        # check parity
        if pattern.count('1') % 2 == 0:
            # inverse
            _apply_cu1(circuit, -lam_angle, ctls[lm_pos], tgt)
            if global_phase:
                circuit.u1(-gp_angle, ctls[lm_pos])
        else:
            _apply_cu1(circuit, lam_angle, ctls[lm_pos], tgt)
            if global_phase:
                circuit.u1(gp_angle, ctls[lm_pos])
        last_pattern = pattern
Esempio n. 26
0
    def modulation(self, send_bit, num_stream, bit_rate, code_symbol):
        """

        M-QAM modulation function.

        Args:
            send_bit (np.array): send bit

        Returns:
            send_signal (np.array): send signal after M-QAM modulation of send bit

                                us1  [[symbol11, symbol12, symbol13]
                                us2   [symbol21, symbol22, symbol23]
                                us3   [symbol31, symbol32, symbol33]
                                      [  ...  ,    ...   ,   ...   ]]

        """
        self.num_stream = num_stream
        self.bit_rate = bit_rate
        self.code_symbol = code_symbol

        send_signal = np.zeros((self.num_stream, self.code_symbol), dtype=np.complex)
        for s in range(self.num_stream):
            bit = self.bit_rate[s]
            M = 2 ** bit
            array_bit = list((GrayCode(int(bit/2)).generate_gray()))
            array_power, threshould_power = self.calculate_power(M, bit)

            for i in range(self.code_symbol):
                bit_I = ''
                bit_Q = ''
                for j in range(int(bit/2)):
                    bit_I += str(send_bit[s][bit*i+j])
                    bit_Q += str(send_bit[s][bit*i+j + int(bit/2)])

                idx_I = array_bit.index(bit_I)
                idx_Q = array_bit.index(bit_Q)

                send_signal[s,i] = array_power[idx_I] + 1j*array_power[idx_Q]

        return np.round(send_signal, decimals=7)
Esempio n. 27
0
    def demodulation(self, receive_signal, demod_type, sigma):
        """

        M-QAM demodulation fuction.

        Args:
            receive_signal (np.array): receive signal

        Returns:
            receive_bit (np.array): receive bit after QPSK demodulation of receive signal

        """

        if demod_type == 'hard':
            receive_bit = [[] for _ in range(self.num_stream)]
            idx = 0
            for bit in self.bit_rate:
                M = 2 ** bit
                array_bit = list((GrayCode(int(bit/2)).generate_gray()))
                array_power, threshould_power = self.calculate_power(M, bit)

                for i in range(self.code_symbol):

                    tmp = receive_signal[idx][i]

                    tmp_I = np.real(tmp)
                    tmp_Q = np.imag(tmp)

                    idx_I = 0
                    idx_Q = 0
                    for j in range(len(threshould_power)):
                        if tmp_I >= threshould_power[j]:
                            idx_I = j+1

                        if tmp_Q >= threshould_power[j]:
                            idx_Q = j+1

                    for j in range(bit):
                        if j < int(bit/2):
                            receive_bit[idx].append(int(array_bit[idx_I][j]))

                        else:
                            receive_bit[idx].append(int(array_bit[idx_Q][j-int(bit/2)]))
                idx += 1


        if demod_type == 'soft':
            receive_bit = []
            for bit in self.bit_rate:
                receive_bit.append(np.zeros(self.code_symbol * bit, dtype=np.float64))

            for s in range(self.num_stream):
                bit = self.bit_rate[s]
                M = 2 ** bit
                array_bit = list((GrayCode(int(bit/2)).generate_gray()))
                array_power, threshould_power = self.calculate_power(M, bit)

                constellation = []
                for i in array_power:
                    for j in array_power:
                        constellation.append(i + 1j*j)

                array_pattern = []
                for i in array_bit:
                    for j in array_bit:
                        array_pattern.append(i + j)

                for i in range(self.code_symbol):
                    current_symbol = receive_signal[s, i]
                    for bit_index in range(bit):
                        llr_num = 0
                        llr_den = 0
                        for bit_value, symbol in zip(array_pattern, constellation):

                            if bit_value[bit_index*-1 - 1] == '1':
                                llr_num += np.exp((-abs(current_symbol - symbol) ** 2) / (sigma*sigma))
                            else:
                                llr_den += np.exp((-abs(current_symbol - symbol) ** 2) / (sigma*sigma))

                        receive_bit[s][i * bit + bit - 1 - bit_index] = np.log(llr_num / llr_den)

        return receive_bit
Esempio n. 28
0
def generate_gray_code(number_of_controls):
    return list(GrayCode(number_of_controls).generate_gray())
Esempio n. 29
0
def test_sympy__combinatorics__graycode__GrayCode():
    from sympy.combinatorics.graycode import GrayCode
    # an integer is given and returned from GrayCode as the arg
    assert _test_args(GrayCode(3, start='100'))
    assert _test_args(GrayCode(3, rank=1))
Esempio n. 30
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']]
Esempio n. 31
0
#a meros
bits = 4
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
Esempio n. 32
0
def graycode(k):
    return list(GrayCode(k).generate_gray())
Esempio n. 33
0
def Mid_Riser(x):
    """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"""