test_max_len_seq.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import numpy as np
  2. from numpy.testing import assert_allclose, assert_array_equal
  3. from pytest import raises as assert_raises
  4. from numpy.fft import fft, ifft
  5. from scipy.signal import max_len_seq
  6. class TestMLS:
  7. def test_mls_inputs(self):
  8. # can't all be zero state
  9. assert_raises(ValueError, max_len_seq,
  10. 10, state=np.zeros(10))
  11. # wrong size state
  12. assert_raises(ValueError, max_len_seq, 10,
  13. state=np.ones(3))
  14. # wrong length
  15. assert_raises(ValueError, max_len_seq, 10, length=-1)
  16. assert_array_equal(max_len_seq(10, length=0)[0], [])
  17. # unknown taps
  18. assert_raises(ValueError, max_len_seq, 64)
  19. # bad taps
  20. assert_raises(ValueError, max_len_seq, 10, taps=[-1, 1])
  21. def test_mls_output(self):
  22. # define some alternate working taps
  23. alt_taps = {2: [1], 3: [2], 4: [3], 5: [4, 3, 2], 6: [5, 4, 1], 7: [4],
  24. 8: [7, 5, 3]}
  25. # assume the other bit levels work, too slow to test higher orders...
  26. for nbits in range(2, 8):
  27. for state in [None, np.round(np.random.rand(nbits))]:
  28. for taps in [None, alt_taps[nbits]]:
  29. if state is not None and np.all(state == 0):
  30. state[0] = 1 # they can't all be zero
  31. orig_m = max_len_seq(nbits, state=state,
  32. taps=taps)[0]
  33. m = 2. * orig_m - 1. # convert to +/- 1 representation
  34. # First, make sure we got all 1's or -1
  35. err_msg = "mls had non binary terms"
  36. assert_array_equal(np.abs(m), np.ones_like(m),
  37. err_msg=err_msg)
  38. # Test via circular cross-correlation, which is just mult.
  39. # in the frequency domain with one signal conjugated
  40. tester = np.real(ifft(fft(m) * np.conj(fft(m))))
  41. out_len = 2**nbits - 1
  42. # impulse amplitude == test_len
  43. err_msg = "mls impulse has incorrect value"
  44. assert_allclose(tester[0], out_len, err_msg=err_msg)
  45. # steady-state is -1
  46. err_msg = "mls steady-state has incorrect value"
  47. assert_allclose(tester[1:], np.full(out_len - 1, -1),
  48. err_msg=err_msg)
  49. # let's do the split thing using a couple options
  50. for n in (1, 2**(nbits - 1)):
  51. m1, s1 = max_len_seq(nbits, state=state, taps=taps,
  52. length=n)
  53. m2, s2 = max_len_seq(nbits, state=s1, taps=taps,
  54. length=1)
  55. m3, s3 = max_len_seq(nbits, state=s2, taps=taps,
  56. length=out_len - n - 1)
  57. new_m = np.concatenate((m1, m2, m3))
  58. assert_array_equal(orig_m, new_m)