Lab 1: Time Domain

Part 2: Sonar

In this part of the lab we will write a simple application that implements a sonar using the laptop internal speaker and microphone.

The basic idea is very simple and is the basis of sonar and ultrasound imagers -- Objects reflect sound waves. If we send a pulse of sound, we will get reflection echoes of that pulse. Detecting the echos and their time-of-flight will reveal their distance from the source, based on the speed of sound in air.

The way we are going to implement the sonar is to generate a series of rapid pulses, and use matched filtering to detect the source and the returning echos. There are many parameters in this lab that can be tweaked to get different results. We encourage you to experiment. We enjoyed very much making the lab and played quite a bit! we hope you enjoy it too.

Unfortunately, the quallity of the sonar system is going to be highly dependent on your laptop quallity, and the position of the speakers and microphone. It is recommended that you adjust the sound settings on your system such that only the speaker that is closer to the microphone is active. For example, macBookAirs have the microphone on the side of the computer -- so you should set adjust the audio settings to left speaker only. Also, it is recommended that the speaker volume be set to half of its maximum to avoid non-linear distortions.

If you are getting poor results, please consult with us.

This lab was inspired from an iphone app called active-radar.

In []:
# Import functions and libraries
import numpy as np
from numpy import *
import matplotlib.pyplot as plt
import pyaudio
from numpy import pi
from numpy import sin
from numpy import cos
from numpy import sqrt
from numpy import zeros
from numpy import r_
from scipy import signal

# Task II
import threading,time

# Task IV
from rtlsdr import RtlSdr
from numpy import mean
from numpy import power
from numpy.fft import fft
from numpy.fft import fftshift
from numpy.fft import ifft
from numpy.fft import ifftshift
%matplotlib inline

Task I:

Generate Pulses

At first, we will look at short pulses with a pure frequency carrier. These are very common in radar and sonar systems. There are several considerations that we need to make. To be able to detect short distances, and also to be able to get good localization in time our pulses need to be very short. At the same time, shorter pulses carry less energy and have a wider bandwidth (why?). These reduce the signal to noise ratio and reduce our ability to detect targets. At the end, we will have to compromise in order to get satisfactory results in terms of detectibility and resolution.

Here we are going to design a pulsed sonar system in which we repeatedly send pulses and then listen to the returning echoes. The arrival time of the echos will correspond to double the distance from a target.

The function will accept: Npulse = number of samples, f0,f1 = starting and ending frequency and fs = sampling frequency. The function will return the analytic function of the chirp \(e^{j 2\pi \int_0^t f(t)dt}\) with amplitude 1.

In []:
def genChirpPulse(Npulse, f0, f1, fs):
    #     Function generates an analytic function of a chirp pulse
    #     Inputs:
    #             Npulse - pulse length in samples
    #             f0     - starting frequency of chirp
    #             f1     - end frequency of chirp
    #             fs     - sampling frequency
    
    # your code here:
In []:
# your code here:

Generate Pulse Trains

We will use the pulses generated by genChirpPulse in a pulse train.

The function returns ptrain which is a vector of length Nrep x Nseg

In []:
def genPulseTrain(pulse, Nrep, Nseg):
    # Funtion generates a pulse train from a pulse. 
    #Inputs:
    #    pulse = the pulse generated by genChirpPulse
    #    Nrep  =  number of pulse repetitions
    #    Nseg  =  Length of pulse segment >= length(pulse)
    
   # your code here:
    
    
    

Define audio recording functions:

In []:
import numpy as np
import threading,time
import pyaudio

## Define functions that play and record audio

def play_audio( data, p, fs):
    # play_audio plays audio with sampling rate = fs
    # data - audio data array
    # p    - pyAudio object
    # fs    - sampling rate
    # 
    # Example:
    # fs = 44100
    # p = pyaudio.PyAudio() #instantiate PyAudio
    # play_audio( data, p, fs ) # play audio
    # p.terminate() # terminate pyAudio
    
    # open output stream
    ostream = p.open(format=pyaudio.paFloat32, channels=1, rate=int(fs),output=True)
    # play audio
    ostream.write( data.astype(np.float32).tostring() )
    
    
def record_audio( odata, p, fs, record_seconds ):
    # record_audio records audio with sampling rate = fs
    # odata - output data
    # p     - pyAudio object
    # fs    - sampling rate
    # record_seconds - record seconds
    #
    # Example:
    # fs = 44100
    # record_seconds = 5
    # odata = zeros( fs * record_seconds ) # initialize odata
    # p = pyaudio.PyAudio() #instantiate PyAudio
    # record_audio( odata, p, fs, record_seconds ) # play audio
    # p.terminate() # terminate pyAudio
    
    # open input stream
    chunk = 1024
    istream = p.open(format=pyaudio.paFloat32, channels=1, rate=int(fs),input=True,frames_per_buffer=chunk)

    # record audio in chunks and append to frames
    frames = [];
    for i in range(0, int(fs / chunk * record_seconds)):
        data_str = istream.read(chunk) # read a chunk of data
        data_flt = np.fromstring( data_str, 'float32' ) # convert string to float
        frames.append( data_flt ) # append to list
        
    # flatten list to array
    data = np.concatenate( frames )
    # copy to output
    np.copyto(odata[0:len(data)], data)

Now, we will create a function called xciever that will serve as a tranciever to transmit and receive pulses.

In []:
def xciever(ptrain, fs):
    # function takes a pulse train and a sampling frequency
    # it then plays and records at the same time. The function returns
    # the recorded sound. 
    
    
    RECORD_SECS = float32(len(ptrain))/fs + 1.0
    # allocate receive signal for signal  + 1 second
    rcv_sig = zeros( len(ptrain) + fs );

    # instantiate PyAudio
    p = pyaudio.PyAudio()
    
    # initialize threads
    t_play = threading.Thread(   target = play_audio,   args = (ptrain,   p, fs,  ))
    t_record = threading.Thread( target = record_audio, args = (rcv_sig, p, fs, RECORD_SECS , ))

    # start recording and playing threads
    
    t_record.start()
    t_play.start()
    

    # pause for Tplay+1 seconds
    time.sleep( RECORD_SECS+1)

    # terminate pyAudio
    p.terminate()
    return rcv_sig

Task II:

We now have components to generate pulses, generate a pulse train, play and record it. Lets see what we get! We will start with very short pulses with a single carrier frequency. Rectangular pulses are difficult for the speaker to produce as they exhibit discontinuities in the beginning and the end of the pulse. Therefore we will multiply the pulses with a smooth window. Here, we will use a square-rooted hanning window. Since we will be detecting with a matched filter, the result of the cross correlation will be the effect of a full hanning window on the spectrum of the cross correlation.

In []:
# your code here:

Use the pulse to generate a pulse train of Nrep=15 pulses, Nseg=4096 samples

In []:
# your code here:
In []:
# your code here:
In []:
# your code here:

Matched Filtering

The strong pulses we see are a result of direct feed-through from the transmitter to the receiver that does not scatter off targets. The echoes we see are a result of echoes from reflecting surfaces. The problem in our setup is that we don't know the exact delay between the transmitter and the receive hardware (in PyAudio). Instead, we will assume that the travel time for sound between the speaker and the microphone is negligible and much smaller than scatering targets. We can then detect when the pulses start based on the direct feedthrough signal.

We will detect both the feedthrough and echoes using matched filtering.

In []:
# your code here:

Again, extract a single pulse from the received pulse train. Extract at least 2 Npulse samples before the pulse and 20 Npulse samples after. Plot the received pulse. Can you see any echoes?

In []:
i# your code here:

Sonar System

In order to automate the the system and visualize the results we need a few more components. To extract the pulses we need to know the position of the first feedthrough pulse.

In []:
def findDelay(Xrcv, Nseg):
    # finds the first pulse
    # Inputs:  
    #         Xrcv - the received matched filtered signal
    #         Nseg - length of a segment
    
    # your code here:
    
    
    
In []:
# your code here:

We now have a matrix in which the rows represent distance of targets and column which represent time.

The speed of sound in air is given by the following equation: \[ v_s = 331.5\sqrt{1+T/273.15}~\mathrm{m/s}~,\] where T is the temperature in degree celcius.

In []:
# your code here:

You now have a working sonar! It would be much easier though to play with different parameters if we automate things. Therefore, write a function sonar(Npulse, f0, f1, fs, Nseg, Nrep, temperature=20,maxDist=400,vmax=0.2) The function will play sound, capture it and display the resulting scattering map.

In []:
def sonar(Npulse, f0, f1, fs, Nseg, Nrep, T=20,maxDist=400,vmax=0.2):
    # S sonar function
    # Inputs: 
    #      Npulse - number of samples in a pulse
    #      f0  - starting frequency for chirp
    #      f1 - ending chirp frequency
    #      fs - sampling rate
    #      Nseg - number of samples in a segment
    #      Nrep - number of pulse repetitions
    #      T = Temperature
    #      maxDist = maximum distance to display in plot
    #      vmax - windowing levvel of the image so echoes can be seen. 
    #
    #
   

Task III: Play with different parameters.

The detection resolution and sensitivity will depend on the parameters you will choose for the sonar. The longer the pulse is, the worse time resolution you will get, but much stronger matched filtering amplitude. You can buy the time resolution by using pulse compression with chirp pulses at the expense of increasing the bandwidth.

In []:
sonar(300,10000,19000,44100,4410,100,T=18.5,maxDist=300)

I hope you enjoyed the lab

Task IV (Optional Bonus only!): A real-time sonar application in python.

I challenge those who are interested to write a real-time application in which the computer continiously playes pulses and the processing is done and displayed in real-time. Please contact me if you have any questions. I can also give you some suggestions on how to go about it. This will count as an additional lab with full score.