Friday, July 07, 2023

Comparing the clusters with the different sampling rate following Shannon-Nyquist theorem

 


This Python programming tests how important to set the sampling rate denoted by M.

Shannon-Nyquist requirements claims that the sampling rate M has to be exact: either too small or too big. 

# importing necessary tools
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import pandas as pd
import random
import math
import cmath

# Defining the imaginary number
i=complex(0,1)

###### Drawing the full complex field circle with a different step size ######

# Definining the sampling rate
M=10

# Generating the list of the imaginary numbers
ImagList=[]
for j in range(1,M+1):
    ImagList.append((j/M)*i)

# Generating the exponentials of the imaginary numbers in ImagList
ExpList=[cmath.exp(2*math.pi*ImagList[j]) for j in range(len(ImagList))]

# Separating the exponentials into the real part and the imaginary part
ExpListR=[ExpList[j].real for j in range(len(ExpList))]
ExpListI=[ExpList[j].imag for j in range(len(ExpList))]

# # # Uncomment the following lines to show the circle graph
# # Plotting graph for a complex field circle
# plt.rcParams["figure.figsize"] = (9,9)
# plt.plot(ExpListR,ExpListI,'ro')
# plt.xlabel('Real field')
# plt.ylabel('Imaginary field')
# plt.show


###### ###### Comparison of the sampling rates ###### ######
###### ###### to test Shannon-Nyquist theorem  ###### ######

FreqSamples=[3*i,4*i,13*i]
SampleRateMs=[10,100,1000]
ColorList=['b','c','m']

Freq=[]
for k in range(len(SampleRateMs)):
    TempFreq=[FreqSamples[j]/SampleRateMs[k] for j in range(len(FreqSamples))]
    Freq.append(TempFreq)

ExpFreq=[]
for k in range(len(Freq)):
    TempExpFreq=[cmath.exp(2*math.pi*Freq[k][j]) for j in range(len(Freq[k]))]
    ExpFreq.append(TempExpFreq)

ExpFreqR=[]
ExpFreqI=[]
for k in range(len(ExpFreq)):
    BenchR=[1,0,-1,0]
    TempExpFreqR0=[ExpFreq[k][j].real for j in range(len(ExpFreq[k]))]
    TempExpFreqR1=BenchR+TempExpFreqR0
    ExpFreqR.append(TempExpFreqR1)
    BenchI=[0,1,0,-1]
    TempExpFreqI0=[ExpFreq[k][j].imag for j in range(len(ExpFreq[k]))]
    TempExpFreqI1=BenchI+TempExpFreqI0
    ExpFreqI.append(TempExpFreqI1)

panda_df = pd.DataFrame(data = ExpFreq)
display(panda_df)

# Compare plots with the different sampling rates
# Ref. https://stackoverflow.com/questions/37360568/python-organisation-of-3-subplots-with-matplotlib
plt.rcParams["figure.figsize"] = (20,20)
gs = gridspec.GridSpec(3, 3)
for k in range(len(ExpFreq)):
    ax = plt.subplot(gs[0, k]) # row 0, col 1
    plt.plot(ExpFreqR[k],ExpFreqI[k],'ro', color=ColorList[k])
    plt.title(f'Sampling Rate M= {SampleRateMs[k]}')
    plt.xlabel('Real field')
    plt.ylabel('Imaginary field')