/utils/match_ends.py

https://gitlab.com/jostikas/Thesis_final
Python | 65 lines | 38 code | 11 blank | 16 comment | 6 complexity | 011394d3d10b011f24779df49fbf8d5c MD5 | raw file
  1. #!/usr/bin/python
  2. """
  3. Match the phase of two ends of a complex baseband recording from gnuradio.
  4. Finds the starting and ending phase of the streams, takes their complex
  5. conjugate, finds the phases, creates a linear interpolation between them
  6. and multiplies the stream by the normalized value of the corresponding complex
  7. numbers.
  8. """
  9. import scipy
  10. import numpy as np
  11. import argparse
  12. import logging
  13. logging.basicConfig()
  14. log = logging.getLogger(__name__)
  15. log.setLevel(logging.WARNING)
  16. def match_ends(stream):
  17. # Find the starting and ending complex values of the file.
  18. # Since we want the phases to be 0 in the end, take their conjugates
  19. beg = stream[:1].mean().conj()
  20. end = stream[-1:].mean().conj()
  21. # Find the phases
  22. beg_phi = np.angle(beg)
  23. end_phi = np.angle(end)
  24. # Create the multiplication vector
  25. mult_phase = np.linspace(beg_phi, end_phi, num=len(stream))
  26. mult = np.exp(1j * mult_phase)
  27. # Rotate the source stream accordingly, return it
  28. return (stream * mult).astype(np.complex64)
  29. if __name__ == '__main__':
  30. parser = argparse.ArgumentParser(description=
  31. """Match the phase of the start and end to zero phase for glitchless looping and
  32. instant lock with a PLL in gnuradio."""
  33. )
  34. parser.add_argument('files', type=str, nargs='+', help="Files to process.")
  35. parser.add_argument('-v', dest='verbose', action='count',
  36. help="Dump more info. Add 'v'-s for victory.")
  37. args = parser.parse_args()
  38. if args.verbose == 1:
  39. log.setLevel(logging.INFO)
  40. elif args.verbose == 2:
  41. log.setLevel(logging.DEBUG)
  42. log.info('Processing files:')
  43. for srcfile_name in args.files:
  44. log.info(srcfile_name)
  45. for srcfile_name in args.files:
  46. destname = srcfile_name.rsplit('.', 1) # split off the extension
  47. destname = '-matched.'.join(destname)
  48. with open(srcfile_name) as srcfile:
  49. stream = scipy.fromfile(srcfile, dtype=scipy.complex64)
  50. stream = match_ends(stream)
  51. stream.tofile(destfile)
  52. log.debug('Processed', srcfile_name)
  53. print 'Done.'