**Exercise set 13**
==============


>In this exercise set, we use the discrete the Fourier transform
>for analyzing some simple signals. Our focus here is on the practical
>use of the fast Fourier transform.


**Exercise 13.1**

In this exercise, we will investigate how the time resolution and the
length of the measured signal (in time) will influence the discrete Fourier transform.
For performing the Fourier transform, we will make use of the
[`scipy.fft`](https://docs.scipy.org/doc/scipy/reference/fft.html) 
module which contains several methods for applying the fast Fourier transform (FFT).

Below, you will find some Python code for
calculating the FFT for a given signal.
```python
import numpy as np
from scipy.fft import fft, fftfreq
import matplotlib as mpl
from matplotlib import pyplot as plt
mpl.rcParams["savefig.format"] = 'pdf'
plt.style.use(['seaborn-talk', 'bmh'])


def run_fft(time, signal):
    """Do fft for the given signal.

    Parameters
    ----------
    time : numpy.array
        The times we have measured the signal at.
    signal : numpy.array
        The measured signal.

    Returns
    -------
    freq : numpy.array
        The positive frequencies.
    fourier : numpy.array
        The Fourier transform coefficients.
    amplitude : numpy.array
        The amplitude spectrum.
    power : numpy.array
        The power spectrum.

    """
    fourier = fft(signal)
    delta_t = time[1] - time[0]
    N = signal.size
    freq = fftfreq(N, delta_t)
    amplitude = np.abs(fourier / N)
    power = np.abs(fourier)**2
    # Normalize power:
    power = power / power.sum()
    return freq[:N//2], fourier, amplitude[:N//2], power[:N//2]


time = np.arange(0, 2, 0.01)
signal = np.sin(2.0 * 2.0 * np.pi * time)
freq, _, amplitude, _ = run_fft(time, signal)


fig, (ax1, ax2) = plt.subplots(constrained_layout=True, ncols=2)
ax1.plot(time, signal, lw=3)
ax2.plot(freq, amplitude, lw=3)
ax1.set(xlabel='Time (s)', ylabel='Signal amplitude')
ax2.set(xlabel='Frequency (Hz)', ylabel='Amplitude')
plt.show()
```

This method
returns several arrays of numbers:

*  The positive frequencies.

*  The Fourier transform coefficients (note that these are complex numbers).

*  The amplitude spectrum, obtained by taking the absolute value of the
complex numbers.

*  The power spectrum, obtained by taking the square of the amplitude spectrum.
When we analyze the Fourier transform, we are typically plotting the amplitude spectrum,
or the power spectrum, as a function of the frequencies.


**(a)** We will now consider the function,
\begin{equation}
y(t) = \sin (2 \times 2\pi t),
\label{eq:signal1}
\tag{1}\end{equation}

where $t$ is the time in seconds. This function has
a frequency of $2$ and a period of $\tfrac{1}{2}$.
Create three versions of this function by evaluating it for
different time ranges:

* (i)  from $0$ to $0.5$ (i.e. one period)
with a time step of $0.01$:
 `time = np.arange(0, 0.5, 0.01)`

* (ii) from $0$ to $1$ (i.e. two periods)
with a time step of $0.01$:
 `time = np.arange(0, 1, 0.01)`

* (iii) from $0$ to $5$ (i.e. $10$ periods)
with a time step of $0.01$:
 `time = np.arange(0, 5, 0.01)`


Create these three versions of the function in Eq. \eqref{eq:signal1},
calculate the FFT for each of them, and compare the amplitude spectra.
Based on your comparison, what is the effect of increasing the *length*
in time we sample the signal for?




```python
# Your code here
```

**Your answer to question 13.1(a):** *Double click here*

**(b)**  One "trick" we can do to increase the length of a signal is to
simply add zeros to the beginning and the end of the signal. This is
called "zero-padding", and we can do this with the method
[`pad`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html) 
from `numpy`:
`zero_pad = np.pad(signal, pad_width=250)`.  This will add $250$ zeros to
the beginning of the signal, and $250$ zeros to the end of the signal. Consider again
the signal you created in point (i) in part **13.1(a)** of this
exercise. Pad this signal by adding $250$ zeros to the beginning and $250$ zeros to
the end
of the signal, and calculate the FFT for the padded signal. Comparing this to
the non-padded version, what seems to
be the effect when you pad the signal?




```python
# Your code here
```

**Your answer to question 13.1(b):** *Double click here*

**(c)**  We will continue with the signal in Eq. 1, but this time we will
investigate the effect of changing the sampling frequency (i.e. the time step/how often
we measure the signal in time).
Create $4$ new versions of this signal:

* (i) from $0$ to $0.5$ (i.e. one period)
with a time step of $0.01$:

  `time = np.arange(0, 0.5, 0.01)`


* (ii) from $0$ to $0.5$ (i.e. one period)
with a time step of $0.005$:

  `time = np.arange(0, 0.5, 0.005)`


* (iii) from $0$ to $1$ (i.e. two periods)
with a time step of $0.125$:
  
  `time = np.arange(0, 1, 0.125)`


* (iv) from $0$ to $10$ (i.e. $20$ periods)
with a time step of $0.3$:
  
  `time = np.arange(0, 10, 0.3)`


Create these $4$ signals, calculate the FFT for each of
them, and compare the amplitude spectra. Based on your results, what seems
to be the effect of changing the sampling frequency? Can you explain the
results you obtain for the $4$th signal (point (iv) above)?




```python
# Your code here
```

**Your answer to question 13.1(c):** *Double click here*

**(d)**  We will now consider a new signal which contains two frequencies:
\begin{equation}
y(t) = \sin (2 \times 2\pi t)
+ \sin (2.1 \times 2\pi t),
\label{eq:signal2}
\tag{2}\end{equation}

If you were to separate these two frequencies ($2$ and $2.1$) with the FFT method,
how long would you have to sample the signal for? Test this by
calculating the FFT of this signal (Eq. \eqref{eq:signal2}) and
plotting the amplitude spectrum.



```python
# Your code here
```

**Your answer to question 13.1(d):** *Double click here*


**Exercise 13.2**

The file `Data/unknown_signal.txt` contains a measurement
of a signal with noise. The first column are the times for which the signal was
measured, and the signal itself can be found in the second column. You know that this
signal, $y$, should have the following form as a function of time, $t$,

\begin{equation}
y(t) = a \sin (f_1 \times 2\pi t) + b \sin(f_2 \times 2\pi t),
\label{eq:signal2}
\tag{3}\end{equation}

where $a$ and $b$ are coefficients, and $f_1$ and $f_2$ are two
frequencies. Determine the coefficients and the two frequencies by
calculating the FFT of the given signal. Note: Since the FFT method will find
both negative and positive frequencies, you should also include the
negative frequencies. We can show that, in this case, this is effectively
the same as only 
considering the positive frequencies, but doubling the 
amplitudes.(This statement should be justified. One simple argument
is as follows. For Eq. \ref{eq:signal2}, the Fourier coefficients will be
purely imaginary. Further, the coefficients for a pair of frequencies, $f$ and $-f$,
will be complex conjugates of each other. The sum of the contributions for these
two frequencies will be $c_{f} \text{e}^{2\pi f t} + c_{-f} \text{e}^{-2 \pi f t}$,
where $c_f$ and $c_{-f}$ are the two coefficients.
Performing this summation results in  $2 A_f \sin (2 \pi f t)$,
where $A_f = \sqrt{||c_f||^2} = \sqrt{||c_{-f}||^2}$ is
the amplitude. Try to show this yourself, by using
[Euler's formula](https://en.wikipedia.org/wiki/Euler\%27s\_formula),
and assuming that $c_f=c_{-f}^\ast$ is purely imaginary (here "$^\ast$" denotes
the complex conjugate).)




```python
# Your code here
```

**Your answer to question 13.2:** *Double click here*

**Exercise 13.3**

In the lectures, we have mentioned the song
[Scar tissue](https://open.spotify.com/track/1G391cbiT3v3Cywg8T7DM1?autoplay=true&v=T) 
by the Red Hot Chili Peppers (RHCP) and how one guitar string in the intro is apparently out of tune.
By nerdy inspection of RHCP music videos, we can see that the two first notes in the intro should be a
F note followed by a A note. However, the A note sounds slightly out of tune when comparing
a tuned guitar playing this note to the album version of the song. We
will here investigate if this is true and to what extent it is out of tune.


**(a)**  We will start by analyzing a known signal. The file `Data/440hz.txt.gz`
contains a sample of a A note at $440$ Hz. The first column of this file
is the time, and the second column is the sampled A note at the corresponding time.
Compute the FFT of this signal and verify that it contains the expected frequency.
Note: This file is compressed with
[gzip](https://en.wikipedia.org/wiki/Gzip) , but `numpy` can read this
file directly with the
[`loadtxt`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html)  
method: `np.loadtxt("Data/440hz.txt.gz")`




```python
# Your code here
```

**Your answer to question 13.3(a):** *Double click here*

**(b)** A recording of the first few seconds of
[Scar tissue](https://open.spotify.com/track/1G391cbiT3v3Cywg8T7DM1?autoplay=true&v=T) 
is shown in Fig 1. We will here focus on two parts of the signal, as
highlighted in the figure. In the first part of the signal, we expect to mainly
find the F note at $174.61$ Hz and harmonics which are multiples of this
frequency, for instance, $349.23\,\text{Hz} = 2 \times 174.61\,\text{Hz}$, and
$698.46\,\text{Hz} = 4 \times 174.61\,\text{Hz}$.(A table of notes and
frequencies can be found [here](https://pages.mtu.edu/suits/notefreqs.html))

In the second part of the signal, we expect to still find the F note, but also
the possible A note at $440$ Hz, as this is approximately when that note is
played. We will now try to identify the second note by comparing the
amplitude spectra obtained by taking the Fourier transform of the two parts separately.

* (i)  Calculate the FFT of the first part. The recording of this part
can be found in the file `Data/part1.txt.gz` where the first
column is the time and the second column is the amplitude. Can you find
the F note in this signal?

* (ii)  Calculate the FFT of the second part.
The recording of this part
can be found in the file `Data/part2.txt.gz` where the first
column is the time and the second column is the amplitude. Can you still find
the F note in this signal?

* (iii)  Compare the two amplitude spectra you have obtained. For your comparison,
it might be helpful to normalize the spectra so that the largest amplitude
is equal to $1$ in both spectra. When you compare the two spectra, can you
see a difference around $440$ Hz? Estimate the frequency
associated with the largest amplitude close to $440$ Hz in the amplitude
spectrum of part 2.



**Figure 1:** (Left) Amplitude in a recording of Scar Tissue as a function of time. (Right-top)
The first part (color red) of the signal we will analyze. (Right-bottom)
The second part (color red) of the signal we will analyze.



```python
# Your code here
```

**Your answer to question 13.3(b):** *Double click here*

**(c)**  Would you say that the frequency you identified above in part **13.3(b)**&ndash;(iii)
is out of tune with respect to the expected A note at $440$ Hz? Since we are, after all, at a
technical university, we can try to quantify this by calculating 
the number of cents measuring the interval between the two frequencies.
The number of cents, $n$, is a unit of measure for the ratio
between two frequencies, $f_1$ and $f_2$,
\begin{equation}
n = 1200 \times \log_2 \frac{f_1}{f_2},
\tag{4}\end{equation}

and
[Wikipedia](https://en.wikipedia.org/wiki/Cent\_(music)\#Human_perception)  states that
we can distinguish a difference in pitch of about $5$&ndash;$6$ cents. Calculate the number
of cents for the two frequencies $f_1 = 440\,\text{Hz}$ and $f_2$ equal to the
frequency you identified above, and use this to support your conclusion.
Further, Wikipedia gives a [Just-noticeable difference](https://en.wikipedia.org/wiki/Just-noticeable_difference) of 3 Hz for frequencies below 500 Hz for
simple tones, and you can also use this to support your conclusion.



```python
# Your code here
```

**Your answer to question 13.3(c):** *Double click here*





84843cabd298a5f4afadfaa4449c04c9ccf516b8
ipynb
Jupyter Notebook
exercises_2020/13_Exercise_Set_13.ipynb
sroet/chemometrics
c797505d07e366319ba1544e8a602be94b88fbb6
CC-BY-4.0
2020-02-04T12:09:19.000Z
2021-08-06T12:28:24.000Z
exercises_2020/13_Exercise_Set_13.ipynb
sroet/chemometrics
c797505d07e366319ba1544e8a602be94b88fbb6
CC-BY-4.0
2020-01-06T10:24:33.000Z
2022-01-21T10:37:46.000Z
exercises_2020/13_Exercise_Set_13.ipynb
sroet/chemometrics
c797505d07e366319ba1544e8a602be94b88fbb6
CC-BY-4.0
2020-01-09T12:04:26.000Z
2021-01-19T10:06:14.000Z
Qwen/Qwen-72B
1. YES
2. YES