_max_len_seq.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # Author: Eric Larson
  2. # 2014
  3. """Tools for MLS generation"""
  4. import numpy as np
  5. from ._max_len_seq_inner import _max_len_seq_inner
  6. __all__ = ['max_len_seq']
  7. # These are definitions of linear shift register taps for use in max_len_seq()
  8. _mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1],
  9. 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8],
  10. 14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14],
  11. 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21],
  12. 23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20],
  13. 27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7],
  14. 31: [28], 32: [31, 30, 10]}
  15. def max_len_seq(nbits, state=None, length=None, taps=None):
  16. """
  17. Maximum length sequence (MLS) generator.
  18. Parameters
  19. ----------
  20. nbits : int
  21. Number of bits to use. Length of the resulting sequence will
  22. be ``(2**nbits) - 1``. Note that generating long sequences
  23. (e.g., greater than ``nbits == 16``) can take a long time.
  24. state : array_like, optional
  25. If array, must be of length ``nbits``, and will be cast to binary
  26. (bool) representation. If None, a seed of ones will be used,
  27. producing a repeatable representation. If ``state`` is all
  28. zeros, an error is raised as this is invalid. Default: None.
  29. length : int, optional
  30. Number of samples to compute. If None, the entire length
  31. ``(2**nbits) - 1`` is computed.
  32. taps : array_like, optional
  33. Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence).
  34. If None, taps will be automatically selected (for up to
  35. ``nbits == 32``).
  36. Returns
  37. -------
  38. seq : array
  39. Resulting MLS sequence of 0's and 1's.
  40. state : array
  41. The final state of the shift register.
  42. Notes
  43. -----
  44. The algorithm for MLS generation is generically described in:
  45. https://en.wikipedia.org/wiki/Maximum_length_sequence
  46. The default values for taps are specifically taken from the first
  47. option listed for each value of ``nbits`` in:
  48. https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm
  49. .. versionadded:: 0.15.0
  50. Examples
  51. --------
  52. MLS uses binary convention:
  53. >>> from scipy.signal import max_len_seq
  54. >>> max_len_seq(4)[0]
  55. array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8)
  56. MLS has a white spectrum (except for DC):
  57. >>> import numpy as np
  58. >>> import matplotlib.pyplot as plt
  59. >>> from numpy.fft import fft, ifft, fftshift, fftfreq
  60. >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1
  61. >>> spec = fft(seq)
  62. >>> N = len(seq)
  63. >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-')
  64. >>> plt.margins(0.1, 0.1)
  65. >>> plt.grid(True)
  66. >>> plt.show()
  67. Circular autocorrelation of MLS is an impulse:
  68. >>> acorrcirc = ifft(spec * np.conj(spec)).real
  69. >>> plt.figure()
  70. >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-')
  71. >>> plt.margins(0.1, 0.1)
  72. >>> plt.grid(True)
  73. >>> plt.show()
  74. Linear autocorrelation of MLS is approximately an impulse:
  75. >>> acorr = np.correlate(seq, seq, 'full')
  76. >>> plt.figure()
  77. >>> plt.plot(np.arange(-N+1, N), acorr, '.-')
  78. >>> plt.margins(0.1, 0.1)
  79. >>> plt.grid(True)
  80. >>> plt.show()
  81. """
  82. taps_dtype = np.int32 if np.intp().itemsize == 4 else np.int64
  83. if taps is None:
  84. if nbits not in _mls_taps:
  85. known_taps = np.array(list(_mls_taps.keys()))
  86. raise ValueError('nbits must be between %s and %s if taps is None'
  87. % (known_taps.min(), known_taps.max()))
  88. taps = np.array(_mls_taps[nbits], taps_dtype)
  89. else:
  90. taps = np.unique(np.array(taps, taps_dtype))[::-1]
  91. if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1:
  92. raise ValueError('taps must be non-empty with values between '
  93. 'zero and nbits (inclusive)')
  94. taps = np.array(taps) # needed for Cython and Pythran
  95. n_max = (2**nbits) - 1
  96. if length is None:
  97. length = n_max
  98. else:
  99. length = int(length)
  100. if length < 0:
  101. raise ValueError('length must be greater than or equal to 0')
  102. # We use int8 instead of bool here because NumPy arrays of bools
  103. # don't seem to work nicely with Cython
  104. if state is None:
  105. state = np.ones(nbits, dtype=np.int8, order='c')
  106. else:
  107. # makes a copy if need be, ensuring it's 0's and 1's
  108. state = np.array(state, dtype=bool, order='c').astype(np.int8)
  109. if state.ndim != 1 or state.size != nbits:
  110. raise ValueError('state must be a 1-D array of size nbits')
  111. if np.all(state == 0):
  112. raise ValueError('state must not be all zeros')
  113. seq = np.empty(length, dtype=np.int8, order='c')
  114. state = _max_len_seq_inner(taps, state, nbits, length, seq)
  115. return seq, state