Inset Plotting with Matplotlib

Here in this article, I am trying to explain the process of creating inset pictures within Python plots. In many cases of data visualization, we need to make the best use of available space for plots. In my experience, each plot is unique in its own way so that few improvements here and there makes it visually more pleasing and we will be able to convey more information using minimum space. Here I am plotting Energy Decay Curve of an audio signal(wav file) with its time domain view in inset.
The first step would be to import the necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
One of the important parts is to know the dimension(or at least the aspect ratio) of the image you want. I usually take the Golden ratio(1.61) as the aspect ratio. You need to decide the font size also according to the dimension so that labels wont look too big or too small.
width  = 3.5
height = width / 1.618
labelsize = 10
legendfont = 8
lwidth          =   0.8
plt.rc('pdf', fonttype = 42)
plt.rc('font', family='serif')
plt.rc('text', usetex=True)
plt.rc('xtick', labelsize=labelsize)
plt.rc('ytick', labelsize=labelsize)
plt.rc('axes', labelsize=labelsize)
The following code generates the data to be plotted.
inputfile    = 'IRTrimmed.wav'
Fs, x    =   wavfile.read(inputfile)
Fs = float(Fs)
rangetoplot     = 2000
Lp = len(x)
Tp = np.arange(0, Lp/Fs, (1/Fs)).T
Ppower = np.square(x)
PpowerRev = Ppower[::-1]
PEnergy = np.cumsum(PpowerRev)[::-1]
PEdB        = 10*np.log10(PEnergy)
Next, we create a figure object.
fig1, ax = plt.subplots()
fig1.subplots_adjust(left=.16, bottom=.2, right=.99, top=.97)
Now we can plot the main data and label the axes and legend.
plt.plot(Tp, PEdB, ls='solid', color = 'b', label = 'Energy decay curve', linewidth = lwidth)
plt.grid(True, which = 'both', linestyle=":", linewidth = 0.6)
plt.xlabel('Time(sec)')
plt.ylabel('Energy(dB)')
plt.legend(loc='upper right',fontsize = legendfont)
Then we can create an inset inside our main plot and add a graph there.
ax2 = fig1.add_axes( [0.25, 0.25, 0.4, 0.4])
ax2.plot(Tp[0:rangetoplot], x[0:rangetoplot], ls='solid', color = 'k', linewidth=0.5, label ='RIR Time Domain' )
ax2.set_xticks([])
ax2.set_yticks([])
Finally, we can save the plot to a dimension we want.
fig1.set_size_inches(width, height)
fig1.savefig('EnergyRIR.png', dpi = 600)
And the final figure will look like this.
The source code can be found here and the input signal can be found here

Understanding Spectrogram with DTMF Signals

This MATLAB tutorial explains the Spectrogram visualization using DTMF audio as input signal. The code reads, analyzes and plots the spectrogram of a DTMF signal. The time-frequency resolution problem is explained with different frame sizes.


Screen Display Specifications

%Measure screen size of the device
%Calculate position values of figure Windows

scrsz = get(0,'ScreenSize');
P1=[40 500 scrsz(3)/3 scrsz(4)/3];
P2=[40 80 scrsz(3)/3 scrsz(4)/3];
P3=[600 500 scrsz(3)/3 scrsz(4)/3];
P4=[600 80 scrsz(3)/3 scrsz(4)/3];
P5=[1000 500 scrsz(3)/3 scrsz(4)/3];
P6=[1000 80 scrsz(3)/3 scrsz(4)/3];

File Reading

[y, Fs] = audioread('C:\Users\SAJIL\Documents\MATLAB\DTMF1.wav');
L=length(y);
N = nextpow2(L);
T=1/Fs;

Signal Analysis Part

t=(0:T:(L-1)/Fs)';
NFFT = 2^nextpow2(L);
Y = fft(y,NFFT);%/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
Mag=2*abs(Y(1:NFFT/2+1));

Plot Signal

figure('position', P1);
figure(1);
plot(t,y,'k');
grid on
title('Time Domain');
xlabel('Time in Seconds');
ylabel('Amplitude');
legend('DTMF Tone');

Plot single-sided Amplitude Spectrum.

figure('position',P2);
figure(2);
plot(f,Mag);
grid on
title('Magnitude Spectrum');
xlabel('Frequency (Hz)');
ylabel('|X(f)|');
legend('Frequency Spectrum');

DTMF Signal Table

I = imread('DTMF.png');
figure('position',P3);
figure(3);
image(I)
f=text(0.4,0.4,'Original Input is 0696675356','FontSize',12);
axis off

Spectrogram Display Part

figure('position',P4);
figure(4);
%spectrogram(x,window,noverlap,f,fs)
spectrogram(y,32);
text(0.4,28,'Frame Size 32','FontSize',12);
%colormap bone

figure('position',P5);
figure(5);
%spectrogram(x,window,noverlap,f,fs)
spectrogram(y,256);
text(0.4,28,'Frame Size 256','FontSize',12);

figure('position',P6);
figure(6);
%spectrogram(x,window,noverlap,f,fs)
spectrogram(y,512);
text(0.4,28,'Frame Size 512','FontSize',12);
  

Play back block

soundsc(y,Fs);

End of Program

An Intuitive Look Into Auto-Correlation

In this tutorial, we will take a look at the mathematical function called auto-correlation for various  common signals. The basic signals are generated and their respective auto-correlation output is plotted.


Screen Display Settings

%Measure Screen Size of the device
%Calculate position values of figure windows
scrsz = get(0,'ScreenSize');
P1 = [50 500 scrsz(3)/3 scrsz(4)/3];
P2 = [50 80 scrsz(3)/3 scrsz(4)/3];
P3 = [500 500 scrsz(3)/1.5 scrsz(4)/3];
P4 = [500 80 scrsz(3)/1.5 scrsz(4)/1.5];

Generate Basic Signals

figure('position', P4);
figure(1);

Sine Wave

t = 0:(1/1000):1;
x1 = sin(2*pi*1*t) ;
subplot(4,2,1);
plot(x1);
grid on
title('Sine Wave');
xlabel('Samples');
ylabel('Amplitude');

y1 = xcorr(x1,x1);
subplot(4,2,2);
plot(y1);
grid on
title('Sine Wave Autocorr');
xlabel('Samples');
ylabel('Amplitude');

Ramp

x2 = t;
subplot(4,2,3);
plot(t);
grid on
title('Ramp');
xlabel('Samples');
ylabel('Amplitude');

y2 = xcorr(x2,x2);
subplot(4,2,4);
plot(y2);
grid on
title('Ramp Autocorr');
xlabel('Samples');
ylabel('Amplitude');

Rectangular

x3 = ones(1,1500);
subplot(4,2,5);
plot(x3);
grid on
title('Rectangular');
xlabel('Samples');
ylabel('Amplitude');

y3 = xcorr(x3,x3);
subplot(4,2,6);
plot(y3);
grid on
title('Rect Autocorr');
xlabel('Samples');
ylabel('Amplitude');

1 minus x^2

x4 = 1- t.*t;
subplot(4,2,7);
plot(x4);
grid on
title('XSquare');
xlabel('Samples');
ylabel('Amplitude');

y4 = xcorr(x4,x4);
subplot(4,2,8);
plot(y4);
grid on
title('XSquare Autocorr');
xlabel('Samples');
ylabel('Amplitude');

End of Program

Sea Channel Simulation with MATLAB

The following MATLAB code simulates the effects happening to a signal transmitted over sea channel underwater cable. The changes happening to the signal is plotted at their respective stages.


19/05/2015 6:00 PM 'C:\Users\SAJIL\Documents\MATLAB\Seachannel.m'

%Version 1.0
%Sajil C. K., DCB, Uok.
%sajildcb@gmail.com
%This program Reads a speech wav file from Hard disk, then its applied
%though transformations in whcin it is attenuated and is affected by
%Gaussian noise. We can hear to the effects of these after each steps

Screen Display Specifications

%Measure screen size of PC
%Calculate position values of figure Windows

scrsz = get(0,'ScreenSize');
P1=[40 500 scrsz(3)/3 scrsz(4)/3];
P2=[40 80 scrsz(3)/3 scrsz(4)/3];
P3=[600 500 scrsz(3)/3 scrsz(4)/3];
P4=[600 80 scrsz(3)/3 scrsz(4)/3];
P5=[1000 500 scrsz(3)/3 scrsz(4)/3];
P6=[1000 80 scrsz(3)/3 scrsz(4)/3];
P =[P1;P2;P3;P4;P5;P6];
c=['m' 'c' 'r' 'g' 'b' 'k'];

File Reading

[x, Fs] = audioread('I Love You Daddy.wav');
x=x(:,1); % Discard one channel
N=length(x);
t=(0:(N-1))'/Fs;

Parameter specifications

A = 0.5; %Channel attenuation value
G = 6; %Specify Number of Gate Breaks here
i = 1;

Channel Model

while i<=G

Plot Signal

    figure('position', P(i,:));
    figure(i);
    plot(t,x,c(i));
    grid on
    title(strcat('Transmitted Signal at Gate ', num2str(i)));
    xlabel('Time in Seconds');
    ylabel('Amplitude');
    legend(strcat('Speech @ Gate ',num2str(i)));
     

Play back of Original

    p= audioplayer(x,Fs);
    play(p);
    pause(max(size(x))/Fs);

Generate Guassian Noise Model

    n= 0.5*rand(N,1)-0.5;

Signal Attenuation and Noise

    x=x*A;
    x=x+n;
    i=i+1;
end

End of Program

Echo Generation using Room Impulse Response Using MATLAB

The following code produces auralization effects to audio sounds saved in hard disk to add echo effect. The input will be a dry sound with no echo/reverberation but the output will sound like in a tunnel or Cathedral.


Screen Display Specifications

%Measure screen size of the device
%Calculate position values of figure Windows

scrsz = get(0,'ScreenSize');
P1=[40 500 scrsz(3)/3 scrsz(4)/3];
P2=[40 80 scrsz(3)/3 scrsz(4)/3];

Read Room Impulse Response File

[x1,Fs1]=audioread('tunnel_balloon_441k.wav');
[x2,Fs1]=audioread('carpark_balloon _441k.wav');

% Discard one channel
x1=x1(:,1);
x2=x2(:,1);

Plot Impulse Response of Tunnel

figure('position', P1);
figure(1);
plot(x1,'k');
grid on
title('IR of tunnel balloon 441k.wav');
xlabel('Samples');
ylabel('Amplitude');
legend('tunnel IR');

Plot Impulse Response of Underground Carpark

figure('position', P2);
figure(2);
plot(x2,'r');
grid on
title('carpark balloon 441k.wav');
xlabel('Samples');
ylabel('Amplitude');
legend('Carpark IR');

Read Input Signal

[y,Fs2]=audioread('Asianet.wav');
y=y(:,1);

Perform Convolution

o1 = conv(x1,y);
o2 = conv(x2,y);

Playback the Output Signal

%soundsc(o1,Fs1);
%soundsc(o2,Fs1);

End of Program

Matrix Multiplication in Real Life

Matrix Multiplication in Real Life


Hello World,
Let me start this discussion with a basic question. What does simple multiplication means?
To me, it feel like this. Say your IQ is 120. You have a magic wand, you wave it and say “Let my IQ go twice”. With multiplication you can grow or shrink some quantity as you wish.
Suppose I am having a Rs. 1000/- note in my purse and if  I wish that “Let my amount in purse  go 1.5 x” will turn the Rs. 1000/- to Rs. 1500/-   :-)))
We can’t multiply things that don’t exist. I don’t have a private Jet Air plane so does I can’t multiply it.
This concept can be thought of shrinking or expanding values.
Let’s take a simple case of 1\times N and N\times 1 element matrix multiplication.
Analogy 1
list
 \begin{pmatrix}Lemon & Sugar & Salt &Water\end{pmatrix}\times</p> <p>\begin{pmatrix}<br /> 2\quad Spoons\\<br /> 2\quad Spoons\\<br /> 0.5\quad Spoon\\<br /> 1\quad Glass  \end{pmatrix} = \begin{pmatrix}Lemonade\quad with\quad particular\quad taste\end{pmatrix}
In this analogy, ingredients  are kept on a table as a row and recipe as column
[Ingredients][quantity] = [final product]
The output number can be thought of as the taste or quality of the final product. Although it is not a perfect analogy (eg. negative spoons are not possible in real life, – 2 spoons of sugar means nothing), the point here is we made a connection between abstract matrix multiplication and a real life event and chances are rare that we forget both together.
Analogy 2
\begin{pmatrix}quizzes&Assignments&Midterm&Final \end{pmatrix}\times<br /> \begin{pmatrix}<br /> 10\%\\<br /> 20\%\\<br /> 20\%\\<br /> 50\%\\<br /> \end{pmatrix} = \begin{pmatrix}Final Mark\end{pmatrix}
The instructor can adjust the weights as you want is an additional insight here!. Isn’t this process looks like the features in machine learning or weights of a neural network ?
Creative unanswered questions on this topic
  1. What is the need for such a row column rule ? Easy readability..?
  2. Why don’t A*B != B*A..?
Conclusion
Let me wind up from the simple matrix multiplication concept! All those who are interested in this topic , please share your valuable suggestions and of course that  will add lot of values to the topic.
Matrix multiplication is related to Dot  Product, so let’s explore more about it next!