Finished re-writing lab 1. Getting started guide introduces variables, functions, and logic

This commit is contained in:
Adog64 2025-01-19 03:01:16 -05:00
parent 6d2257bbf8
commit ee51f180d4
10 changed files with 159 additions and 54 deletions

View File

@ -1,18 +1,18 @@
# Getting Started with Python for DSP # Getting Started with Python for DSP
In this tutorial set, I will start with a fresh installation of Windows 10. The steps should be similar, if not identical, if you are using Windows 11. If you are running macOS, please follow along as best as possible. Finally, if you are running Linux, please let me know, and I will help you. The goal of this preliminary tutorial is to get you set up with a functional Python environment. I will be starting with a fresh installation of Windows 10, but the steps should be similar, if not identical, if you are using Windows 11. If you are running macOS, please follow along as best as possible. Finally, if you are running Linux, depending on your distribution, you may have Python installed by default.
If you run into any issues, please reach out to Aidan Sharpe via email: Regardless of your system, if you run into any issues at all during the setup process, please reach out to Aidan Sharpe via email:
[sharpe23@students.rowan.edu](mailto:sharpe23@students.rowan.edu?subject=DSP%20Help%20-%20FULL%20NAME) subject line: **DSP Help - FULL NAME**. [sharpe23@students.rowan.edu](mailto:sharpe23@students.rowan.edu?subject=DSP%20Help%20-%20FULL%20NAME) subject line: **DSP Help - FULL NAME**.
## The Python Language ## The Python Language
Recall your Computer Science & Programming and Introduction to Embedded Systems classes. You are familiar with C and C++, where by compiling `.c` or `.cpp` file, you generate an executable `.exe` file. Both C and C++ are considered *compiled languages* for this reason. You can email the `.exe` file to a friend, and without any code (or even a compiler) they can run your file on their machine. When this file is executed, it runs in its own *process* on the operating system, which you can see by opening your task manager while the program is still running. Recall your Computer Science & Programming and Introduction to Embedded Systems classes. You are familiar with C and C++, where by compiling a `.c` or `.cpp` file, you generate an executable `.exe` file. Both C and C++ are considered *compiled languages* for this reason. You can email the `.exe` file to a friend, and without any code (or even a compiler) they can run your file on their machine. When this file is executed, it runs in its own *process* on the operating system, which you can see by opening your task manager while the program is still running.
Python is *not* a compiled language. Instead, it is what we call an interpreted language. Rather than creating an executable file, the code is run line-by-line by a program called an interpreter. In the next section, we will install the Python Interpreter. Importantly, since no executable file is created, anyone who wants to run your code will have to run it with their own Python Interpreter. Additionally, unlike a compiled language, the program does not have its own OS process. In the case of Python 3, your program will run in the `python` process. Python is *not* a compiled language. Instead, it is what we call an interpreted language. Rather than creating an executable file, the code is run line-by-line by a program called an interpreter. In the next section, we will install the Python Interpreter. Importantly, since no executable file is created, anyone who wants to run your code will have to run it with their own Python Interpreter. Additionally, unlike a compiled language, the program does not have its own OS process. In the case of Python 3, your program will run in the `python` process.
## Installing Python ## Installing Python
Before we begin writing any code, we need to install the Python Interpreter. These installation instructions are, as noted prviously, targetted at Windows 10/11 users. If you happen to be running Linux, you probably already have a Python interpreter installed, especially if you are running a "just works" distribution such as Ubuntu or Fedora. If you happen to be running macOS, please follow the installation instructions on [python.org](https://www.python.org/downloads/macos/). Before we begin writing any code, we need to install the Python Interpreter. These installation instructions are, as noted prviously, targetted at Windows 10/11 users. If you happen to be running Linux, you probably already have a Python interpreter installed, especially if you are running a "just works" distribution such as Ubuntu or Fedora. If for whatever reason your Linux installation does not have Python, simply install it from your package manager. If you happen to be running macOS, please follow the installation instructions on [python.org](https://www.python.org/downloads/macos/).
\newpage \newpage
### 1. Open the Microsoft Store ### 1. Open the Microsoft Store
@ -41,3 +41,58 @@ Open your "Start" menu and see if Python 3.13 and IDLE are shown.
Start by opening "Python 3.13". This is the *Python Interpreter* we mentioned earlier. When run directly as an application, we are met with the *Python Shell*. Here, we can type Python code, and it will be executed as we go. For example, we can write a one-line "Hello, World" style program simply by typing `print("Hello, World!")` and hitting the enter key. The text "Hello, World!" will be printed, and we are prompted again on the following line. We can change the text inside the quotes to whatever we want, and that text will be printed out as well. Congratulations, you have run your first Python code! Start by opening "Python 3.13". This is the *Python Interpreter* we mentioned earlier. When run directly as an application, we are met with the *Python Shell*. Here, we can type Python code, and it will be executed as we go. For example, we can write a one-line "Hello, World" style program simply by typing `print("Hello, World!")` and hitting the enter key. The text "Hello, World!" will be printed, and we are prompted again on the following line. We can change the text inside the quotes to whatever we want, and that text will be printed out as well. Congratulations, you have run your first Python code!
![](hello-dsp.png) ![](hello-dsp.png)
\newpage
## Basic Concepts - Variables, Functions, and Logic
You are likely used to declaring a variable in the following manner:
```c
int x;
```
where you specify a data type and a variable name. In languages like C and C++, the variable $x$ will always be an integer within the scope that it was declared as one. This system of declaration is called *static typing*, which simply means that the data type of a variable---integer in this case---cannot change. Python is what is called a *dynamically typed* language, meaning that variables can change their data type at any time. For example, the following C code would generate an error
```c
int x = 5;
x = "hello";
```
but the following Python code would be valid:
```python
x = 5
x = "hello"
```
Two things should stand out when comparing the C and Python samples above. First, the Python code does not have semi-colons since statements in Python are terminated by a new line. Second, the Python code should stand out in that no type is explicitly stated. That is not to say that the variable does not have a type, but rather the type can change based on the value being stored. In the case of our example, $x$ is initially an integer, but then changed to a string.
Rarely, do we see Python code standing alone outside a function like this, however. This is because functions allow us to re-use complex code segments. We create a function by using the `def` keyword, followed by the function name, a parameter list in parenthesis, and the line ends with a colon (:). The following line starts the body of the function, and it *must* be tabbed in once more than the line with the definition.
**IMPORTANT:** In Python, changing the tabbing can change the behavior of the code, so be careful. Be patient, building the habit of paying attention to tabbing can take some time.
Below is a simple function that adds two variables ($a$ and $b$) and returns the result.
```python
def add(a, b):
return a+b
```
The final basic concept is control logic. This will allow our program to make decisions based on the current program state. The simplest example is the `if`-`elif`-`else` statement. For example, if we wanted to find the maximum value between two variables $a$ and $b$ we might write the following:
```python
def max(a,b):
if a > b:
return a
else:
return b
```
With this simple case, either $a$ is greater than $b$ and $a$ is the max, or $a$ is not greater than $b$ and $b$ is the max. It doesn't matter what we return if the two values are equal, because the result will be indistinguishable.
Say we want to calculate our letter grade based on our number grade. We may write a function:
```python
def letter_grade(number_grade):
if number_grade >= 90:
return 'A'
elif number_grade >= 80:
return 'B'
elif number_grade >= 70:
return 'C'
elif number_grade >= 60:
return 'D'
else:
return 'F'
```
Here, we exhibit two new Python concepts: the `elif` keyword and "snake case". The `elif` keyword is Python's version of the `else if` you may be familiar with in other programming languages. Snake case (often stylized as snake_case) simply means all lower case with underscores between words. It is recommended that for Python code all variable and function names be written using snake_case as opposed to something like camelCase or PascalCase. According to PEP 8 - the style guide for Python, snake case is correct Python style.

View File

@ -1,2 +1,2 @@
syms t syms t % Define t as a symbolic variable
a=simplify(fourier(sin(0.5*t)/(0.5*t))) a=simplify(fourier(sin(0.5*t)/(0.5*t))) % Print the simplified Fourier transform of sin(0.5t)/(0.5t) = sinc(0.5t)

View File

@ -3,45 +3,18 @@ ECE 09351 - Digital Signal Processing
Lab 1 Question 3 Lab 1 Question 3
Translated from MATLAB by Aidan Sharpe Translated from MATLAB by Aidan Sharpe
Last Modified: January 17, 2025 Last Modified: January 18, 2025
""" """
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from sympy import simplify, fourier_transform, sinc
def cft(g, f): from sympy.abc import t, f
result = np.zeros(len(f), dtype=complex)
for i, ff in enumerate(f):
result[i] = complex_quad(lambda t: g(t)*np.exp(-2j*np.pi*ff*t), -5, 5)
return result
def complex_quad(g, a, b):
t = np.linspace(a, b, 2501)
x = g(t)
return sp.integrate.simpson(y=x, x=t)
def main(): def main():
g = lambda t: np.sinc(0.5*t/np.pi) x = sinc(0.5*t) # Define x as sinc(0.5t) = sin(0.5t)/(0.5t)
X = simplify(fourier_transform(x, t, f)) # Evaluate the Fourier transform of x, converting from t domain to f domain
f_s = 1 print(X)
T_s = 1/f_s
t_0 = 1000
t = np.arange(-t_0, t_0, T_s)
f = np.linspace(-f_s/2, f_s/2, len(t), endpoint=False)
omega = 2*np.pi*f
G = np.fft.fftshift(np.fft.fft(g(t)) * np.exp(-2j*np.pi*f*t_0) /f_s)
G_analytic = 2*np.pi*(np.heaviside(omega+0.5, 1) - np.heaviside(omega-0.5, 1))
plt.plot(f, G_analytic, color="red")
plt.scatter(f, G)
plt.show()
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -1,12 +1,12 @@
% Lab 1 % Lab 1
% Question 4 % Question 4
fs=4; fs=4; % Sample frequency 4[Hz]
ts=1/fs; ts=1/fs; % Period is reciprocal of frequency
n=0:1:99; n=0:1:99; % Sample indicies (0 to 99)
x(n+1)=cos(2*pi*n*ts/5)+sin(4*pi*n*ts/7)+cos(16*pi*n*ts/9); x(n+1)=cos(2*pi*n*ts/5)+sin(4*pi*n*ts/7)+cos(16*pi*n*ts/9);
stem(n,x,'linewidth',2); stem(n,x,'linewidth',2); % Plot samples on stem plot
xlabel('n') xlabel('n')
ylabel('x(n)') ylabel('x(n)')

View File

@ -0,0 +1,30 @@
"""
ECE 09351 - Digital Signal Processing
Lab 1 Question 4
Translated from MATLAB by Aidan Sharpe
Last Modified: January 18, 2025
"""
import numpy as np
import matplotlib.pyplot as plt
def main():
f_s = 4 # Sample frequency 4[Hz]
T_s = 1/f_s # Period is reciprocal of frequency
n = np.arange(100) # Sample indicies (0 to 99)
t = n*T_s # Conversion between index and time
x = np.cos(2*np.pi*t/5) + np.sin(4*np.pi*t/7) + np.cos(16*np.pi*t/9)
plt.stem(n, x) # Plot samples against index on stem plot
plt.xlabel("n")
plt.ylabel("x(n)")
plt.show() # Show the plot
if __name__ == "__main__":
main()

View File

@ -1,3 +1,3 @@
syms t syms t % Define t as a symbolic variable
f=exp(-t*4)*heaviside(t); f=exp(-t*4)*heaviside(t); % Define f(t) = e^(-4t)*u(t)
ff=fourier(f); ff=fourier(f); % Take the Fourier transform of f(t)

View File

@ -0,0 +1,19 @@
"""
ECE 09351 - Digital Signal Processing
Lab 1 Question 5
Translated from MATLAB by Aidan Sharpe
Last Modified: January 18, 2025
"""
from sympy import fourier_transform, exp, Q
from sympy.abc import t, f
def main():
x = exp(-4*t)*Heaviside(t) # Define x(t) = e^(-4t)*u(t)
X = fourier_transform(x, t, f) # Take the Fourier transform of x(t)
print(x)
if __name__ == "__main__":
main()

View File

@ -1,9 +1,8 @@
syms a b t syms a b t % Define a, b, and t as symbolic variables
assume(a > 0) assume(a > 0) % Assume a is a positive real number
f = exp(-a*abs(t)); f = exp(-a*abs(t)); % Define f(t) = e^(-a|t|)
ff = fourier(f); ff = fourier(f) % Take the Fourier transform of f(t)
assume(b > 0)
g = f*cos(b*t);
gg = simplify(fourier(g));
assume(b > 0) % Assume b is a positive real number
g = f*cos(b*t); % Define g(t) = e^(-a|t|)*cos(bt)
gg = simplify(fourier(g)) % Take the Fourier transform of g(t)

View File

@ -0,0 +1,29 @@
"""
ECE 09351 - Digital Signal Processing
Lab 1 Question 6
Translated from MATLAB by Aidan Sharpe
Last Modified: January 18, 2025
"""
from sympy import *
from sympy.abc import a, b, t, w
# Please note that the answers are given as piecewise functions.
# The conditions are unnecessary, so take the first part of the piecewise result.
def main():
# Assume that a and b are positive real numbers
with assuming(Q.positive(a), Q.positive(b)):
x_1 = exp(-a*abs(t)) # x1(t) = e^(-a|t|)
X_1 = integrate(x_1*exp(-1j*w*t), (t, -oo, oo)) # Fourier transform of x1(t)
print(simplify(X_1))
x_2 = x_1*cos(b*t) # x2(t) = x1(t)*cos(bt)
X_2 = integrate(x_2*exp(-1j*w*t), (t, -oo, oo)) # Fourier transform of x2(t)
print(simplify(X_2))
if __name__ == "__main__":
main()