---
title: Lab Assignment - Head-Related Transfer Function
---

(page:labhrtf)=
# Lab Assignment: Head-Related Transfer Function

## System Characterization of the Outer Ear

### Background

The head-related transfer function (HRTF) is a function in the frequency domain that describes how sound in three-dimensional space is filtered by the external ear, the head, and the torso. It is used to simulate acoustic space when the sounds are presented through headphones. The HRTF is a function of frequency, azimuth, and elevation. HRTFs differ substantially across individuals, which is why you need to learn your own HRTFs to able to localize sounds. 

### Scope of this assignment

You will participate in an experiment in which you will measure your own ear-print (the **Head-Related Transfer Function**). We will insert a small microphone in your ear (actually: a tube at the beginning of your ear canal; {numref}`fig_assignmenthrtf`). You will be asked to sit quietly in our lab, while we present a **sweep** over all speakers. The experiment will take several minutes. After the experiments, your data collected will be returned to you (after preprocessing), and you will write a brief report on this.
This assignment consists of two parts. In this first part you will focus on how to characterize the head and outer-ear system, with the input signal being a sound coming from an external source, and the output being the sound passed to the middle ear (ear canal, middle-ear bones). In the second part (after the module on the Auditory System), you will be able to interpret the use of this system for sound localization.

```{figure} images/hrtfrecording.jpg
:name: fig_assignmenthrtf
HRTF recording setup. A small microphone (black, from Etymotic) will be taped to your neck. A small tube running from the microphone, will be inserted in your ear, so that the tip lies at the beginning of the ear canal.
```

### Duration
The experiment will take 5-10 min, and will typically be combined with the sound localisation experiment (see {ref}`page:labsoundlocalisation`). Creating a report will take 2 to 4 hours, depending on your familiarity with Matlab.

### Learning goals

This assignment has been developed to support you to achieve the following learning outcomes:
- You record your own HRTF set (and know what components are essential)
- You analyze your own HRTF set and its directional components
- You write a brief report 

```{admonition} learning goals
:class: tip 
At the end of this section, you will be able to:
- Provide definitions of a **linear system**, the **impulse response** function and the **transfer characteristic**
- Determine the transfer characteristic (**amplitude** or **gain** and **phase** as a function of frequency) for a linear system, that responds to an **input** signal, $x(t)$, with an **output** signal, $y(t)$
- Derive the impulse response from the transfer characteristic. 
```

### Product
- You will have measured your HRTFs in the week/days before the assigned computer practical (deadline **a**). 
- You will produce a brief report before next week's practical (deadline **b**). 

### Instructions

Work on your brief report on the system characterization aspects of HRTFs.

- **HRTF measurement**
- Make an appointment with a student assistant. 
- Let the coordinator know once you have done this. 
- Familiarise yourself with the methods and tools.
- Visit the lab and measure your HRTFs.
- **Create a brief report on HRTF measurements.** The report should contain all code and all figures made during the practical, with brief written explanation. The questions in this assignment should all be answered. The report should be a coherent story.

## Guidelines and protocol

### Methods

#### Stimulus

The stimulus presented is a Schroeder sweep, which is basically a frequency sweep. This sweep is presented 20 times at each speaker location.

```{admonition} question - sweep
:class: exercise

Explain what a sweep is and explain why such a signal is used. 

To explain and to answer these questions: 
- Plot the time waveform of this sweep.
- Plot the spectrum of this sweep (both magnitude and phase).
```

To do so, you need to load the sweep into Matlab {download}`Click here to download the sweep <data/singlesweep.mat>`.

```{code-block} matlab
load('singlesweep.mat');
```
The variables `sweep1` and `fs` will be loaded in the workspace of Matlab. With these variables you can plot the waveform as a function of time. 

```{admonition} question - sampling rate
:class: exercise

What is the sampling frequency? Which frequencies in the signal can we measure at such a high sampling rate?
```

Using `fft` you can plot the spectrum (see {ref}`page:practical_fourier`). With `abs` and `angle` you can get the magnitude and phase of the signal’s spectrum. It would be wise to plot the waveform and spectrum in a single figure, in separate subplots, and plot the spectrum on a logarithmic scale, for example:

```{code-block} matlab
figure(1);
clf; % clean figure
subplot(3,1,1);
plot(t,sweep1); % waveform
subplot(3,1,2);
plot(f,M); % magnitude
subplot(3,1,3);
plot(f,unwrap(P)); % phase
```

Please provide correct labelling and legend/caption. 
```{admonition} question - unwrap
:class: exercise

What does unwrap do?
- plot this without unwrap. What are the minimum and maximum values now?
- Check out the help on unwrap: `help unwrap`
```


```{admonition} question - impule
:class: exercise

Why do we not use an Impulse? In what way is the sweep like an impulse? 

```

You can save the `figure` by using the `saveas` function:
```{code-block} matlab
saveas('figure1','svg'); % to save as a vector-format svg file
```

Or by using the `savegraph` function (on brightspace):
```{code-block} matlab
savegraph('figure1','png'); % to save as a bitmap-format png file
```

#### Subject

Provide a picture of your ear including the HRTF recording set-up (microphone and tube).

```{admonition} question - ear size
:class: exercise

What is the distance from your ear canal to the tip of your concha and to the tip of your pinna? 

```

### Results

#### Elevation

An example data set is stored in `HRTF.mat`. {download}`Click here to download this HRTF data set <data/HRTF.mat>`. These are only for speakers on the cardinal axes; more data is provided in HRTFs.mat for all speakers. {download}`Click here to download the full HRTF data set <data/HRTFs.mat>` if you are interested in this. Your own HRTF data set can be downloaded from Brightspace. 

```{code-block} matlab
load('HRTF.mat');
```

The variables `azSweep`, `elSweep`, `az`, `el` and `fs` will be loaded in the workspace of Matlab, which you can check with:

```{code-block} matlab
whos azSweep elSweep az el
```

which will provide you with the size of these matrices and vectors:
```{code-block} matlab
Name            Size             Bytes  Class     Attributes
Fs              1x1                 8  double              
az              1x24               192  double              
azSweep         1024x24         196608  double              
el              1x21                168  double              
elSweep   1024x21          172032  double
```    

The `elSweep` and `azSweep` matrices contain the sweeps (waveforms in time domain) recorded over the microphone inserted in your ear. The `elSweep` are the sweeps played from the vertical speakers in the midsaggital plane (elevation `el` in deg; 24 in total), while the `azSweeps` are played from the speakers in the horizontal plane (azimuth `az` in deg; 27 in total). `Fs` is the sampling frequency (48828.125 Hz). The original stimulus contains 20 sweeps, the variables `el`- and `azSweep`s are an average of those sweeps.

```{admonition} question - waveform
:class: exercise

- What is the duration (in s) of each sweep?
- Plot the waveform of the central speaker (azimuth = 0 deg, elevation = 0 deg; hint: use selection vectors: `sel = el==0;`. Is this waveform meaningful?

```

With these variables you will determine the transfer characteristic via `fft` ({ref}`sec:fft`) for each location. 

```{admonition} question - frequency domain
:class: exercise
- How do you obtain the transfer characteristic? 
- Plot the HRTF (amplitude/gain transfer characteristic in dB) for all elevations in one plot (`semilogx`).
- Create a matrix called HRTF that contains all HRTFs. You can do so in a for-loop. You do not need to use `abs` and you do not need to throw away half (this will be done in the next exercise).

```{code-block} matlab
[m,n] = size(elSweep);
HRTF = zeros(m,n);
for ii = 1:n
    x = elSweep(:,ii)
    ft = fft(x,1024)
    HRTF(:,ii)=ft;
end
```

Since the data is noisy and contains non-directional components, we usually plot the smoothed so-called Directional Transfer Function.

```{code-block} matlab
DTF = getdtf(HRTF,Fs);
```

```{admonition} question - directionality
:class: exercise

These filters are directional: different locations yield a different transfer function. You can see it as a dip in the curve that changes systematically with elevation.
- Plot the DTF lines with `semilogx`. Note that `getdtf` takes half of the HRTFs (so you will have 513 samples). Plot only for frequencies between 3000 and 12000 Hz (use `xlim`).

```

#### Azimuth

```{admonition} question - filter
:class: exercise

The head acts as a filter for sounds. 
- What kind of filter?
- Plot the gain characteristic for a location at 70 deg contralaterally from the recorded ear.
    
```


#### Run this code


You can download all MATLAB scripts here:
- {download}`Matlab scripts <matlab/matlab_scripts.zip>`


Please unzip, put all in the same folder as your data file.
Replace the filename in 'analyseHRTF.m' and run

```{code-block} matlab
analyseHRTF;
```
Change the folder when asked to do so.


## Follow-up

In the module {ref}`page:auditorysystem`, you will learn how the information in the transfer characteristics can be used to localize sounds. You will also learn how the complex pattern in the HRTFs arise from reflections of sound in the ear. You will extend your brief report from this week by including this information.
