Think DSP: Digital Signal Processing in Python, by Allen B. Downey.

Overview

ThinkDSP

LaTeX source and Python code for Think DSP: Digital Signal Processing in Python, by Allen B. Downey.

The premise of this book (and the other books in the Think X series) is that if you know how to program, you can use that skill to learn other things. I am writing this book because I think the conventional approach to digital signal processing is backward: most books (and the classes that use them) present the material bottom-up, starting with mathematical abstractions like phasors.

With a programming-based approach, I can go top-down, which means I can present the most important ideas right away. By the end of the first chapter, you can break down a sound into its harmonics, modify the harmonics, and generate new sounds.

Here's a notebook that previews what you will see in Chapter 1:

And if you want to see where were headed, here's a preview of Chapter 10:

Running the code

Most of the code for this book is in Jupyter notebooks. If you are not familiar with Jupyter, you can run a tutorial by clicking here. Then select "Try Classic Notebook". It will open a notebook with instructions for getting started.

To run the ThinkDSP code, you have several options:

Option 1: Run the notebooks on Google Colab.

Option 2: Run the notebooks on Binder.

Option 3: Use Conda to install the libraries you need and run the notebooks on your computer.

Option 4: Use poetry to install the libraries you need and run the notebooks on your computer.

The following sections explain these options in detail.

Note: I have heard from a few people who tried to run the code in Spyder. Apparently there were problems, so I don't recommend it.

Option 1: Run on Colab

I have recently updated most of the notebooks in this repository so they run on Colab.

You can open any of them by clicking on the links below. If you want to modify and save any of them, you can use Colab to save a copy in a Google Drive or your own GitHub repo, or on your computer.

Option 2: Run on Binder

To run the code for this book on Binder, press this button:

Binder

It takes a minute or so to start up, but then you should see the Jupyter home page with a list of files. Click on code to open the folder with the notebooks, then click on one of the notebooks (with the .ipynb extension).

Option 3: Install Python+Jupyter

First, download the files from this repository. If you are a Git user, you can run

git clone --depth 1 https://github.com/AllenDowney/ThinkDSP.git

Otherwise you can download this Zip file and unzip it. Either way, you should end up with a directory called ThinkDSP.

Now, if you don't already have Jupyter, I highly recommend installing Anaconda, which is a Python distribution that contains everything you need to run the ThinkDSP code. It is easy to install on Windows, Mac, and Linux, and because it does a user-level install, it will not interfere with other Python installations.

Information about installing Anaconda is here.

If you have the choice of Python 2 or 3, choose Python 3.

There are two ways to get the packages you need for ThinkDSP. You can install them by hand or create a Conda environment.

To install them by hand run

conda install jupyter numpy scipy pandas matplotlib seaborn

Or, to create a conda environment, run

cd ThinkDSP
conda env create -f environment.yml
conda activate ThinkDSP

Option 4: Use poetry to manage the project on your computer or notebook locally.

First, download the files from this repository. If you are a Git user, you can run

git clone --depth 1 https://github.com/AllenDowney/ThinkDSP.git

Then, assuming you have poetry installed on your machine, run

cd ThinkDSP
poetry install

to install the libraries you need in a virtual environment. To activate the environment, run

poetry shell

Then you can run Jupyter.

Run Jupyter

To start Jupyter, run:

jupyter notebook

Jupyter should launch your default browser or open a tab in an existing browser window. If not, the Jupyter server should print a URL you can use. For example, when I launch Jupyter, I get

~/ThinkComplexity2$ jupyter notebook
[I 10:03:20.115 NotebookApp] Serving notebooks from local directory: /home/downey/ThinkDSP
[I 10:03:20.115 NotebookApp] 0 active kernels
[I 10:03:20.115 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/
[I 10:03:20.115 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

In this case, the URL is http://localhost:8888. When you start your server, you might get a different URL. Whatever it is, if you paste it into a browser, you should see a home page with a list of directories.

Click on code to open the folder with the notebooks, then click on one of the notebooks (with the .ipynb extension).

Select the cell with the import statements and press "Shift-Enter" to run the code in the cell. If it works and you get no error messages, you are all set.

If you get error messages about missing packages, you can install the packages you need using your package manager, or install Anaconda.

If you run into problems with these instructions, let me know and I will make corrections. Good luck!

Freesound

Special thanks to Freesound (http://freesound.org), which is the source of many of the sound samples I use in this book, and to the Freesound users who uploaded those sounds. I include some of their wave files in the GitHub repository for this book, using the original file names, so it should be easy to find their sources.

Unfortunately, most Freesound users don't make their real names available, so I can only thank them using their user names. Samples used in this book were contributed by Freesound users: iluppai, wcfl10, thirsk, docquesting, kleeb, landup, zippi1, themusicalnomad, bcjordan, rockwehrmann, marchascon7, jcveliz. Thank you all!

Here are links to the sources:

http://www.freesound.org/people/iluppai/sounds/100475/

http://www.freesound.org/people/wcfl10/sounds/105977/

http://www.freesound.org/people/Thirsk/sounds/120994/

http://www.freesound.org/people/ciccarelli/sounds/132736/

http://www.freesound.org/people/Kleeb/sounds/180960/

http://www.freesound.org/people/zippi1/sounds/18871/

http://www.freesound.org/people/themusicalnomad/sounds/253887/

http://www.freesound.org/people/bcjordan/sounds/28042/

http://www.freesound.org/people/rockwehrmann/sounds/72475/

http://www.freesound.org/people/marcgascon7/sounds/87778/

http://www.freesound.org/people/jcveliz/sounds/92002/

Comments
  • Can't run `make hevea`

    Can't run `make hevea`

    I wanted to build the HTML version of the book, to try and convert it into an EPUB version, but that failed with the following error (when running make hevea):

    sed 's/\(figs\/[^.]*\).\(pdf\|png\)/\1.eps/' book.tex > thinkdsp.tex
    rm -rf html
    mkdir html
    hevea -O -e latexonly htmlonly thinkdsp
    Exclude comment 'comment'
    /usr/lib/hevea/hyperref.hva:65: Warning: Ignoring option: 'bookmarks'
    ./thinkdsp.tex:68: Warning: Command not found: \topsep
    ./thinkdsp.tex:69: Warning: Command not found: \topsep
    ./thinkdsp.tex:5203: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5223: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5250: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5374: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5420: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5479: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5523: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5555: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:5578: Warning: '_' occurring outside math mode
    ./thinkdsp.tex:6830: Warning: Command not found: \backmatter
    HeVeA Warning: images may have changed, run 'imagen  thinkdsp'
    thinkdsp.html:488:143: Warning, block level element: div nested inside text-level element
    thinkdsp.html:488:142: This opening tag is pending
    thinkdsp.html:748:143: Warning, block level element: div nested inside text-level element
    thinkdsp.html:748:142: This opening tag is pending
    thinkdsp.html:1093:143: Warning, block level element: div nested inside text-level element
    thinkdsp.html:1093:142: This opening tag is pending
    thinkdsp.html:2999:126: Parser error: Unexpected </span>
    thinkdsp.html:3854:369: Lexer error: extract_tag
    thinkdsp.html:3854:369: Lexer error: abstract_tag
    grep -v latexonly thinkdsp.image.tex > a; mv a thinkdsp.image.tex
    grep -v fancyhdr thinkdsp.image.tex > a; mv a thinkdsp.image.tex
    imagen -png thinkdsp
    RESOLUTION: 100
    This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Arch Linux) (preloaded format=latex)
     restricted \write18 enabled.
    entering extended mode
    (./thinkdsp.image.tex
    LaTeX2e <2017-04-15>
    Babel <3.15> and hyphenation patterns for 84 language(s) loaded.
    (/usr/share/texmf-dist/tex/latex/base/book.cls
    Document Class: book 2014/09/29 v1.4h Standard LaTeX document class
    (/usr/share/texmf-dist/tex/latex/base/bk12.clo))
    Runaway argument?
    width=5.5in,height=8.5in, \newcommand {\theversion }{1.0.4} 
    ! Paragraph ended before \@fileswith@ptions was complete.
    <to be read again> 
                       \par 
    l.5 
        
    ? 
    ! Emergency stop.
    <to be read again> 
                       \par 
    l.5 
        
    No pages of output.
    Transcript written on thinkdsp.image.log.
    This is dvips(k) 5.997 Copyright 2017 Radical Eye Software (www.radicaleye.com)
    dvips: DVI file can't be opened: thinkdsp.image.dvi: No such file or directory
    hacha thinkdsp.html
    cp up.png next.png back.png html
    mv index.html thinkdsp.css thinkdsp*.html  html
    mv thinkdsp*.png *motif.gif html
    mv: cannot stat 'thinkdsp*.png': No such file or directory
    make: *** [Makefile:36: hevea] Error 1
    

    As far as I can see, some command generates the thinkdsp.image.tex file, which starts as follows:

    \newif\ifimagen\imagentrue
    \documentclass[12pt]{book}
    \usepackage[width=5.5in,height=8.5in,
    \newcommand{\theversion}{1.0.4}
    
    \pagestyle{empty}
    \thispagestyle{empty}
    \begin{document}
    \newtheorem{exercise}{Exercise}[chapter]
    \setcounter{chapter}{-1}
    

    The \usepackage[width=5.5in,height=8.5in, command (line 3) looks wrong to me.

    opened by heyLu 11
  • "No handles with labels found to put in legend" issue

    Hi all i just read the chapter 1 and ready to code a little bit. after cloned the repo, i run a few codes and python give me this words:No handles with labels found to put in legend. i googled something, but no results. here is my codes, my running env is anaconda 3.5.2 issue :

    from __future__ import print_function, division
    
    # %matplotlib inline
    import thinkdsp
    import thinkplot
    
    import numpy as np
    
    cos_sig = thinkdsp.CosSignal(freq=440, amp=10, offset=0)
    sin_sig = thinkdsp.SinSignal(freq=880, amp=0.5, offset=0)
    
    cos_sig.plot()
    thinkplot.config(xlabel='Time (s)', ylabel='amp(p)')
    
    
    opened by esunlon 8
  • Update chap02

    Update chap02

    The first line edited is self explanatory, that is a typo. If we create a sawtooth signal, we should say "sawtooth" instead of "triangle"

    The second edit is needed, since the spectrum that we are modifying is from line 440, which is before creating the new sawtooth signal. I discovered it by making changes to duration and framerate of the sawtooth signal, and when playing the two comparative audios (with just different phases) the lenghts of the audios were completely different.

    opened by struck89 5
  • getattr in thinkplot.py Config

    getattr in thinkplot.py Config

    I am using your notebooks with Jupyter 4.2.1 and Python 3.5.2 under Ubuntu Desktop 16.10

    The code snippet

    def Config(**options):
        for name in names:
            if name in options:
                getattr(pyplot, name)(options[name])
    

    generates TypeError: 'tuple' object is not callable

    The following seems to fix it for me

    def Config(**options):
        for name in names:
            if name in options:
                try:
                    getattr(pyplot, name)(options[name])
                except TypeError:
                    setattr(pyplot, name, options[name])
    
    opened by grfiv 5
  • missing latex files

    missing latex files

    A number of supporting latex files are not found in the repo making the make command not usable (outside your personal machine at least). Would you mind committing them (e.g. latexonly.tex) to this repo?

    opened by bmabey 5
  • 2 small issues I noticed (inverted lines of code in book + pcolor graph doesn't show)

    2 small issues I noticed (inverted lines of code in book + pcolor graph doesn't show)

    On page 42, the following 2 lines of code should be inverted (i.e. config before plot): spectrum.plot_power(linewidth=1, alpha=0.5) thinkplot.config(xscale='log', yscale='log')

    In thinkplot.py, I had to add the following 2 lines at the end of def Pcolor(...: if pcolor: plt.pcolormesh(X, Y, Z, **options) plt.show() #ADDED THIS OTHERWISE NOTHING SHOWS UP if contour: cs = plt.contour(X, Y, Z, **options) plt.clabel(cs, inline=1, fontsize=10) plt.show() # DITTO

    Excellent book though, I'm learning a lot!

    opened by nickk 4
  • Replace hevea with pandoc

    Replace hevea with pandoc

    This pull request replaces the hevea Makefile target with a simple pandoc target that generates an HTML5 version of the book. In order to have scalable graphics in the HTML version the PDF figures were converted to SVG files. Also, the latexonly file was inlined and htmlonly which is now redundant was removed. I was not sure if the EPS files are still required, if not I could remove them in the PR as well.

    opened by klingtnet 4
  • Production issues

    Production issues

    phi gets rendered differently in different contexts.

    For example, on page 31, phi looks different in an exponent or inline.

    One option is to use exp() as a function everywhere, rather than e^{exponent}

    opened by AllenDowney 4
  • Add 'hevea.sty'

    Add 'hevea.sty'

    Without it, compilation of source fails with the following output:

    ./book.tex:26: LaTeX Error: File 'hevea.sty' not found. [\usepackage]

    The same error has been reported here too.

    opened by usmanayubsh 4
  • Add Korean Version of book, OmegaT project, and translate Preface(Ch.0)

    Add Korean Version of book, OmegaT project, and translate Preface(Ch.0)

    Hello, I translated the Preface of the book into Korean, and added project file for OmegaT, which is Open-Source CAT(Computer Assisted Translation) tool for convenient future contributions(e.g. correcting translation errors).

    opened by mcpcseal 3
  • TypeError at use of make_spectrogram

    TypeError at use of make_spectrogram

    As the title reads, I have hit a bit of a snub trying the code out.

    Trying to run the code: import thinkdsp

    wave = thinkdsp.read_wave('100475__iluppai__saxophone-weep.wav') spectrogram = wave.make_spectrogram(seg_length=512) spectrogram.plot(high=700)

    on Python 3.6, resulting in: Traceback (most recent call last): ... File "/Users/filipthor/PycharmProjects/music/main.py", line 9, in spectrogram = wave.make_spectrogram(seg_length=512) File "/Users/filipthor/anaconda/lib/python3.6/site-packages/thinkdsp.py", line 943, in make_spectrogram segment = self.slice(i, j) File "/Users/filipthor/anaconda/lib/python3.6/site-packages/thinkdsp.py", line 897, in slice ys = self.ys[i:j].copy() TypeError: slice indices must be integers or None or have an index method

    Any ideas?

    opened by filipthor 3
  • Installation of thinkdsp

    Installation of thinkdsp

    I am writing to express my disappointment and frustration with trying to install thinkdsp on my system. I have followed the instructions on the GitHub page, but I am still unable to get thinkdsp working. I have tried troubleshooting the issue on my own, but I am unable to resolve it.

    I am very disappointed in the difficulty I have had trying to install thinkdsp, and I am asking for your help in resolving this issue. I would appreciate if someone from your team could provide assistance or offer guidance on how to successfully install thinkdsp.

    Thank you for your attention to this matter. I look forward to hearing from you and receiving help with this issue.

    opened by WuodOdhis 6
  • How to apply SNR to Guassian White Noise?

    How to apply SNR to Guassian White Noise?

    I have an exercise that requires applying a guassian white noise with signal to noise ratio of 10 dB on a sine signal with amp=1, sampling rate=1 Hz, duration=1 and freq=3 Hz. The question then requests application of some filtering with cut-off and moving average.

    The guassian noise implementation in thinkdsp does not take a SNR parameter. I didn't find anything signal to noise ratio in the book. Is it possible to solve this problem using thinkdsp and Python?

    noise = thinkdsp.UncorrelatedGaussianNoise()

    opened by djnotes 3
  • Added sig5 to the final signal summation

    Added sig5 to the final signal summation

    Created 5 cosine signals with varying frequencies however signal with freq 987 was not included in the final signal. Added sig5 to the final signal summation

    opened by Ragyi 0
  • if read_wave() then write(), the new audio is different in amp.

    if read_wave() then write(), the new audio is different in amp.

    https://github.com/AllenDowney/ThinkDSP/blob/eeef574b4b94c95d57c70c96d9083cd7cd33f346/code/thinkdsp.py#L124

    In read_wave(), the call to normalize() makes issue: if read_wave() then write(), the new audio is different in amp. Suggest don't call normalize(), but convert data to [-1.0, 1.0] using: ys = ys * 1.0 / ( 2 ** (sampwidth * 8 - 1));

    122,123d121 < ys = ys * 1.0 / ( 2 ** (sampwidth * 8 - 1)); < 126,127c124 < < # wave.normalize()

    wave.normalize()
    
    opened by fangpo 1
Owner
Allen Downey
Professor at Olin College, author of Think Python, Think Bayes, Think Stats, and other books. Blog author of Probably Overthinking It.
Allen Downey
A fast Python in-process signal/event dispatching system.

Blinker Blinker provides a fast dispatching system that allows any number of interested parties to subscribe to events, or "signals". Signal receivers

jason kirtland 1.4k Dec 31, 2022
Reproduce digital electronics in Python

Pylectronics Reproduce digital electronics in Python Report Bug · Request Feature Table of Contents About The Project Getting Started Prerequisites In

Filipe Garcia 45 Dec 20, 2021
Mnemosyne: efficient learning with powerful digital flash-cards.

Mnemosyne: Optimized Flashcards and Research Project Mnemosyne is: a free, open-source, spaced-repetition flashcard program that helps you learn as ef

null 359 Dec 24, 2022
Purge your likes and wall comments from VKontakte. Set yourself free from your digital footprint.

vk_liberator Regain liberty in the cruel social media world. This program assists you with purging your metadata from Russian social network VKontakte

null 20 Jun 11, 2021
Various hdas (Houdini Digital Assets)

aaTools My various assets for Houdini "ms_asset_loader" - Custom importer assets from Quixel Bridge "asset_placer" - Tool for placment sop geometry on

null 9 Dec 19, 2022
DSG - Source code for Digital Scholarship Grant project.

DSG Source code for Dr. Stephanie Tsang's Digital Scholarship Grant project. Work performed by Mr. Wang Minghao while as her Research Assistant. The s

null 1 Jan 4, 2022
The RAP community of practice includes all analysts and data scientists who are interested in adopting the working practices included in reproducible analytical pipelines (RAP) at NHS Digital.

The RAP community of practice includes all analysts and data scientists who are interested in adopting the working practices included in reproducible analytical pipelines (RAP) at NHS Digital.

NHS Digital 50 Dec 22, 2022
Audio2Face - a project that transforms audio to blendshape weights,and drives the digital human,xiaomei,in UE project

Audio2Face - a project that transforms audio to blendshape weights,and drives the digital human,xiaomei,in UE project

FACEGOOD 732 Jan 8, 2023
A Python Based Utility for Processing GST-Return JSON Files to Multiple Formats

GSTR 1/2A Utility by Shan.tk Open Source GSTR 1/GSTR 2A JSON to Excel utility based on Python. Useful for Auditors in Verifying GSTR 1 Return Invoices

Sudharshan TK 1 Oct 8, 2022
Framework for creating efficient data processing pipelines

Aqueduct Framework for creating efficient data processing pipelines. Contact Feel free to ask questions in telegram t.me/avito-ml Key Features Increas

avito.tech 137 Dec 29, 2022
Tools for downloading and processing numerical weather predictions

NWP Tools for downloading and processing numerical weather predictions At the moment, this code is focused on downloading historical UKV NWPs produced

Open Climate Fix 6 Nov 24, 2022
Project5 Data processing system

Project5-Data-processing-system User just needed to copy both these file to a folder and open Project5.py using cmd or using any python ide. It is to

null 1 Nov 23, 2021
Small Arrow Vortex clipboard processing library

Description Small Arrow Vortex clipboard processing library. Install You can install this library from PyPI with pip install av-clipboard-lib or compi

Delta Epsilon 1 Dec 18, 2021
A reference implementation for processing the content.log files found at opendata.dwd.de/weather

A reference implementation for processing the content.log files found at opendata.dwd.de/weather.

Deutscher Wetterdienst (DWD) 6 Nov 26, 2022
Todos os exercícios do Curso de Python, do canal Curso em Vídeo, resolvidos em Python, Javascript, Java, C++, C# e mais...

Exercícios - CeV Oferecido por Linguagens utilizadas atualmente O que vai encontrar aqui? ?? Esse repositório é dedicado a armazenar todos os enunciad

Coding in Community 43 Nov 10, 2022
PyDy, short for Python Dynamics, is a tool kit written in the Python

PyDy, short for Python Dynamics, is a tool kit written in the Python programming language that utilizes an array of scientific programs to enable the study of multibody dynamics. The goal is to have a modular framework and eventually a physics abstraction layer which utilizes a variety of backends that can provide the user with their desired workflow

PyDy 307 Jan 1, 2023
A Python script made for the Python Discord Pixels event.

Python Discord Pixels A Python script made for the Python Discord Pixels event. Usage Create an image.png RGBA image with your pattern. Transparent pi

Stanisław Jelnicki 4 Mar 23, 2022
this is a basic python project that I made using python

this is a basic python project that I made using python. This project is only for practice because my python skills are still newbie.

Elvira Firmansyah 2 Dec 14, 2022
Analisador de strings feito em Python // String parser made in Python

Este é um analisador feito em Python, neste programa, estou estudando funções e a sua junção com "if's" e dados colocados pelo usuário. Neste código,

Dev Nasser 1 Nov 3, 2021