# 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

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


#### 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.

• Write a function that generates a chirp pulse: pulse = genChirpPulse(Npulse, f0, f1, fs)

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


• To validate that the function works display the real-part of the pulse generated with Npulse = 200, f0=1000, f1 = 8000, fs = 44100
In []:
# your code here:


#### Generate Pulse Trains

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

• Write a new function ptrain = genPulseTrain(pulse, Nrep, Nseg) The function accepts pulse = a pulse generated by genChirpPulse, Nrep = number of pulse repetitions and Nseg = length of each pulse train segment (which is >= to the length of pulse).

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)



#### Define audio recording functions:

In []:
import numpy as np
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_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()

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


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.

• Generate a f0=f1=15KHz, 60 samples pulse with fs=44100. Window the pulse with a square-rooted hanning window. This will result in a pulse slightly longer than 1.5ms. You should be able to hear this tone, though most adults above 40 would not.
In []:
# your code here:


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

In []:
# your code here:

• Play and record the pulse train. Scale the amplitude of the pulses to 1/2. Make sure your volume is set to maximum of 70%
• Plot the input pulse train and the received pulse train on the same plot.
In []:
# your code here:

• Extract a single pulse from the received pulse train. Extrat at least 2 Npulse samples before the pulse and 20 Npulse samples after. Plot the received pulse. Can you see any echoes?
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.

• Compute the cross correlation (matched filter) of the received signal with the analytic function of the pulse. You can use signal.fftconvolve'
• Take the absolute value to recover its envelope
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.

• Write a function idx = findDelay(rcv, Nseg) that takes the result of the matched filtering and finds the index 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


• Find the position of the first pulse and Extract the portion of the entire pulse train
• Reshape the vector of pulses into a matrix in which each row is a time-segment.
• For the purpose of display we will normalize the feedthrough matched filter result to 1. For that, compute the average of the first column of the matrix and normalize the matrix by the result.
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.

• Create a vector corresponding echo-arrival time to distance of the target from the source. Don't forget that the arrival time include the time to the target and back and therefore the distance should be halved.
• Create a vector corresponding to the start time of each impulse in the impulse train.

• Display the result as image intensity. Use aspect='auto' and set vmax=0.2 so that you can see the echoes. Set the axis to show only distances between 0cm and 3m. Label the axis appropriately.

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.

• Run the sonar with different parameters. You can get interesting targets by moving your laptop, moving yourself next to the computer, using a book as a reflecting surface. It would be easier for you to distinguish the target if you move it back and forth. Play with the pulse lengths, the frequency sweeps, etc.
• Submit 4 interesting set of parameters. Explain why you chose them.
In []:
sonar(300,10000,19000,44100,4410,100,T=18.5,maxDist=300)
`