veeresht / CommPy

Digital Communication with Python
http://veeresht.github.com/CommPy
BSD 3-Clause "New" or "Revised" License
538 stars 176 forks source link

fix: non_sys_stream_2 in turbo_encode is twice the expected size #122

Open abidart opened 1 year ago

abidart commented 1 year ago

When using the turbo_encode function from the channelcoding module, I noticed that the non_sys_stream_2 was twice the expected length. The extra bits were all 0s. Looking a little deeper in the code, I notice that this changed fixed my issue for 1/3 encoding.

The issue seems to be related to the part where the puncturing is applied. The puncturing is supposed to drop bits according to the puncture matrix, but it seems like the function is not correctly applying the puncturing.

Here is the related code block:

j = 0
for i in range(number_outbits):
    if puncture_matrix[0][i % np.size(puncture_matrix, 1)] == 1:
        p_outbits[j] = outbits[i]
        j = j + 1

This block is intended to iterate through the encoded bits in outbits, and copy each bit to p_outbits only if the corresponding bit in the puncture matrix is 1. The j variable keeps track of the current position in the p_outbits array.

However, the length of p_outbits is set earlier in the function to be equal to the length of outbits:

outbits = np.zeros(number_outbits, 'int')
if puncture_matrix is not None:
    p_outbits = np.zeros(number_outbits, 'int')

Since puncturing is supposed to reduce the length of the output, it seems incorrect to set the length of p_outbits to be the same as outbits. If the puncture matrix has a lot of zeros (indicating a lot of bits to drop), then p_outbits could end up being much larger than the actual number of bits that are copied from outbits. This could be why non_sys_stream_2 is longer than expected.

The length of p_outbits should be set to the number of 1s in the puncture matrix, multiplied by the number of blocks of bits that are being encoded. In the case when this function is called from the turbo.py file to calculate the non_sys_stream_2, the puncture matrix has size (1, 2), so you would expect to keep half of the bits from outbits. Therefore, we should initialize p_outbits to have half the length of outbits.

One possible fix could be to calculate the correct size for p_outbits before initializing it:

number_punctured_bits = int(number_outbits * puncture_matrix.sum() / puncture_matrix.size)
p_outbits = np.zeros(number_punctured_bits, 'int')

Then, you can apply the puncturing as before:

j = 0
for i in range(number_outbits):
    if puncture_matrix[0][i % np.size(puncture_matrix, 1)] == 1:
        p_outbits[j] = outbits[i]
        j = j + 1

With these changes, p_outbits should end up being the correct length, and non_sys_stream_2 should also end up being the correct length.