Setup Anaconda, Jupyter, and Rust

Software Setup

We are taking a practical approach in the following sections. As such, we need the right tools and environments available in order to keep up with the examples and exercises. We will be using Rust along with packages that will form our scientific stack, such as ndarray (for multi-dimensional containers) and plotly (for interactive graphing), etc. We will write all of our code within a Jupyter Notebook, but you are free to use other IDEs.

Jupyter Lab

Figure 1 - A Jupyter Notebook being edited within Jupyter Lab.
Theme from

Install Miniconda

There are many different ways to get up and running with an environment that will facilitate our work. One approach I can recommend is to install and use Miniconda.

Miniconda is a free minimal installer for conda. It is a small, bootstrap version of Anaconda that includes only conda, Python, the packages they depend on, and a small number of other useful packages, including pip, zlib and a few others.

You can skip Miniconda entirely if you prefer and install Jupyter Lab directly, however, I prefer using it to manage other environments too.

You can find installation instructions for Miniconda on their website, but if you're using Linux (e.g. Ubuntu) you can execute the following commands from in your terminal:

chmod +x

This will download the installation files and start the interactive installation process. Follow the process to the end, where you should see the following message:

Thank you for installing Miniconda3!

All that's left is to close and re-open the terminal window.

Create Your Environment

Once Miniconda is installed, we need to create and configure our environment. If you added Miniconda to your PATH environment during the installation process, then you can run these commands directly from Terminal, Powershell, or CMD.

Now we can create and configure our conda environment using the following commands.

conda create -n darn python=3

You can replace darn (Data Analytics with Rust Notebooks) with a name of your choosing.

This will create a conda environment named darn with the latest Python 3 package ready to go. You should be presented with a list of packages that will be installed and asked if you wish to proceed. To do so, just enter the character y. If this operation is successful, you should see the following output at the end:

Preparing transaction: done
Verifying transaction: done
Executing transaction: done
# To activate this environment, use
#     $ conda activate darn
# To deactivate an active environment, use
#     $ conda deactivate

As the message suggests, you will need to type the following command to activate and start entering commands within our environment named darn.

conda activate darn

Once you do that, you should see your terminal prompt now leads with the environment name within parentheses:

(darn) melica:~ shahin$


The example above shows the macOS machine name "melica" and the user "shahin". You will see something different on your machine, and it may appear in a different format on a different operating system such as Windows. As long as the prompt leads with "(darn)", you are on the right track.

This will allow you to identify which environment you are currently operating in. If you restart your machine, you should be able to use conda activate darn within your conda prompt to get back into the same environment.

Install Packages

If your environment was already configured and ready, you would be able to enter the command jupyter lab to launch an instance of the Jupyter Lab IDE in the current directory. However, if we try that in our newly created environment, we will receive an error:

(darn) melica:~ shahin$ jupyter lab
-bash: jupyter: command not found

So let's fix that. Let's install Jupyter Lab and use the -y option which automatically says "yes" to any questions asked during the installation process.

conda install -c conda-forge jupyterlab=2.2.9

We'll also need cmake later on.

conda install -c anaconda cmake -y

Finally, let's install nodejs. This is needed to run our Jupyter Lab extension in the next section.

conda install -c conda-forge nodejs=15 -y

Install Jupyer Lab Extensions

There's one last thing we need to do before we move on, and that's installing any Jupyter Lab extensions that we may need. One particular extension that we need is the plotly extension, which will allow our Jupyter Notebooks to render our Plotly visualisations. Within your conda environment, simply run the following command:

jupyter labextension install jupyterlab-plotly

This may take some time, especially when it builds your jupyterlab assets, so keep an eye on it until you're returned control over the conda prompt, i.e. when you see the following:

(darn) melica:~ shahin$

Optionally, you may wish to install the purple looking theme from Figure 1 above.

jupyter labextension install @shahinrostami/theme-purple-please

Now we're good to go!

Install Rust

Now we'll install Rust using rustup, but you can check out the other installation methods if you need them.

curl --proto '=https' --tlsv1.2 -sSf | sh

The code samples in this book will work in many versions of Rust, but I can confirm them to be working with version 1.42.0. You can get the same version with:

rustup default 1.42.0

You will be given instructions for adding Cargo's bin directory to your PATH environment variable.

source $HOME/.cargo/env

This will work until your close your terminal, so make sure to add it to your shell profile. I use Z shell (Zsh) so this meant adding the following to .zshrc:

export PATH="$HOME/.cargo/bin:$PATH"

You can make sure everything works by closing and re-opening your terminal and typing cargo. If this returns the usage documentation then you're all set.


Don't forget to activate your environment when opening the terminal.

Install the EvCxR Jupyter Kernel

Now we'll install the EvCxR Jupyter Kernel. If you're wondering how it's pronounced, it's been mentioned to be "Evic-ser". This is what will allow us to execute Rust code in a Jupyter Notebook.

You can get other installation methods methods for EvCxR if you need then, but we will be using:

cargo install evcxr_jupyter --version 0.5.3
evcxr_jupyter --install

A Quick Test

Let's test if everything is working as it should be. In your conda prompt, within your conda environment, run the following command

jupyter lab

This should start the Jupyter Lab server and launch a browser window with the IDE ready to use.

Figure 2 - A fresh installation of Jupyter Lab.

Let's create a new notebook. In the Launcher tab which has opened by default, click "Rust" under the Notebook heading. This will create a new and empty notebook named Untitled.ipynb in the current directory.

If everything is configured as it should be, you should see no errors. Type the following into the first cell and click the "play" button to execute it and create a new cell.

In [2]:
println!("Hello World!");
Hello World!

If we followed all the instructions and didn't encounter any errors, everything should be working. We should see "Hello World!" in the output cell.


In this section, we've downloaded, installed, configured, and tested our environment such that we're ready to run the following examples and experiments. If you ever find that you're missing Jupyter Lab packages, you can install them in the same way as we installed Jupyter Lab and the others in this section.



The Rust programming language has become a popular choice amongst software engineers since its release in 2010. Besides being something new and interesting, Rust promised to offer exceptional performance and reliability. In particular, Rust achieves memory-safety and thread-safety through its ownership model. Instead of runtime checks, this safety is assured at compile time by Rust's borrow checker. This prevents undefined behaviour such as dangling pointers!

In [5]:
println!("Hello World!");
Hello World!

I first encountered Rust sometime around 2015 when I was updating my teaching materials on memory management in C. A year later in 2016, I implemented a simple multi-objective evolutionary algorithm in Rust as an academic exercise (available: I didn't have any formal training with Rust, nor did I complete any tutorial series, I just figured things out using the documentation as I progressed through my project.

Some example code from this project takes ZDT1 from its mathematical expression in Equation 1

$$ \begin{aligned} f_1(x_1) &= x_1 \tag{1} \\ f_2(x) &= g \cdot h \\ g(x_2,\ldots,x_{\mathrm{D}}) &= 1 + 9 \cdot \sum_{d=2}^{\mathrm{D}} \frac{x_d}{(D-1)}\\ h(f_1,g) &= 1 - \sqrt{f1/g} \end{aligned} $$

to the Rust implementation below.

In [3]:
pub fn zdt1(parameters: [f32; 30]) -> [f32; 2] {

    let f1 = parameters[0];
    let mut g = 1_f32;

    for i in 1..parameters.len() {
        g = g + ((9_f32 / (parameters.len() as f32 - 1_f32)) * parameters[i]);

    let h = 1_f32 - (f1 / g).sqrt();
    let f2 = g * h;

    return [f1, f2];

It was interesting to see that since writing this code in 2016, some of my dependencies have been deprecated and replaced.

My greatest challenge was breaking away from what I already knew. Until this point, I was familiar with languages such as C, C++, C#, Java, Python, MATLAB, etc., with the majority of my time spent working with memory managed languages. I found myself resisting Rust's intended usage, and it is still something I'm working on.

Now that I am about to commence my sabbatical from my University post, I've decided to try Rust again. This time, I'm going to write a book which focusses on using Rust and Jupyter Notebooks to implement algorithms and conduct experiments, most likely in the fields of search, optimisation, and machine learning. Can we write and execute all our code in a Jupyter Notebook? Yes! Should we? Probably not. However, I enjoy the workflow, and making this an enjoyable process is important to me.


I aim to generate everything in this book through code. This means you will see the code for all my figures and tables, including things like flowcharts.

This book is currently available in early access form. It is being actively worked on and updated.

Every section is intended to be independent, so you will find some repetition as you progress from one section to another.

YAML for Configuration Files


In [ ]:
# used to create block diagrams
%reload_ext xdiag_magic
%xdiag_output_format svg
import os


In this section, we're going to have a look at YAML, which is a recursive acronym for "YAML Ain't Markup Language". It is a data interchange file format that is often found with a .yaml or .yml file extension.

What this section is most interested in is using YAML for configuration files, enabling us to extract parameters that we use within our programs so that they can be separated. This means that configuration files can be shared between scripts/programs, and they can be modified without needing to modify source code.

In [2]:
    orientation = portrait
    "config.yaml" <-> "notebook.ipynb"
    "config.yaml" [color = '#ffffcc']
blockdiag { orientation = portrait "config.yaml" <-> "notebook.ipynb" "config.yaml" [color = '#ffffcc'] } config.yamlnotebook.ipynb

Of course, there are many alternatives such as JavaScript Object Notation (JSON) or Tom's Obvious, Minimal Language (TOML), and they all have their advantages and disadvantages. We won't do a full comparison of YAML vs. alternatives, but some advantages of YAML are:

  • It is human-readable, making it easy for someone to read or create them.
  • Many popular programming languages have support for managing YAML files.
  • YAML is a superset of JSON, meaning that JSON can be easily converted to YAML if needed.

We can see that we have some key-value mappings, where the key appears before the colon and the value appears after. The first key we have is learning_rate with a value of 0.1, the second is random_seed with a value of 789108, and the third is maintainer with a value of Shahin Rostami. Finally, I have included a key mapping to a sequence, where categories has the value of list which contains the items "hotdog" and "not a hotdog".

You can read more about YAML at the YAML Specification web page.

So that we can work with this file later on in this section, you can paste the above YAML into a file in the same directory as this notebook and name it config.yaml. Alternatively, you can just run the cell below which will do it for you.

In [3]:
config_string = '''learning_rate:  0.1
random_seed: 789108
maintainer: Shahin Rostami
- hotdog
- not a hotdog'''

with open('config.yaml', 'w') as f:

Getting Python Ready for YAML

Before we begin working with YAML files in Python, we need to make sure we have PyYAML installed. There are alternatives to PyYAML available, but they may not be compatible with the following instructions. However, you can use ruamel.yaml as a drop-in replacement if you wish.

Some options to install PyYAML are with:


conda install -c conda-forge pyyaml


pip install PyYAML

Once you have the package installed you should be ready to import the PyYAML package within Python.

In [4]:
import yaml

Loading YAML with Python

It is surprisingly easy to load a YAML file into a Python dictionary with PyYAML.

In [5]:
with open('config.yaml') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)

We can confirm that it worked by displaying the contents of the config variable.

In [6]:
{'learning_rate': 0.1,
 'random_seed': 789108,
 'maintainer': 'Shahin Rostami',
 'categories': ['hotdog', 'not a hotdog']}

It's as easy as that. We can now access the various elements of the data structure like a normal Python dictionary.

In [7]:
In [8]:
['hotdog', 'not a hotdog']
In [9]:

Updating YAML with Python

Let's say we want to update our learning_rate to 0.2 and add an extra category to our category list. We can do this using the normal Python dictionary manipulation.

In [10]:
config['learning_rate'] = 0.2
In [11]:
config['categories'].append('kind of hotdog')

We can then write this back to the config.yaml file to save our changes.

In [12]:
with open('config.yaml', 'w') as f:
    config = yaml.dump(config, stream=f,
                       default_flow_style=False, sort_keys=False)

All done! We can confirm this by loading our YAML File again and displaying the dictionary.

In [13]:
with open('config.yaml') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)
{'learning_rate': 0.2,
 'random_seed': 789108,
 'maintainer': 'Shahin Rostami',
 'categories': ['hotdog', 'not a hotdog', 'kind of hotdog']}


In this section, we briefly introduced YAML before using the PyYAML package to load, manipulate, and save a collection of configuration settings that we stored in a file named config.yaml. Keeping your configuration settings separate from your source code comes with multiple benefits, e.g. allowing modification of these configurations without modifying source code, automation and search throughout your project, and sharing configurations between multiple bits of work.

Using a Framework with a Custom Objective Function


In [1]:
# used to create block diagrams
%reload_ext xdiag_magic
%xdiag_output_format svg
import numpy as np                   # for multi-dimensional containers
import pandas as pd                  # for DataFrames
import plotly.graph_objects as go    # for data visualisation
import platypus as plat              # multi-objective optimisation framework

# Optional Customisations
import as pio              # to set shahin plot layout
pio.templates['shahin'] = pio.to_templated(go.Figure().update_layout(
    legend=dict(orientation="h",y=1.1, x=.5, xanchor='center'),
pio.templates.default = 'shahin'
pio.renderers.default = "notebook_connected" # remove when running locally 


When applying multi-objective optimisation algorithms to real-world problems, we will often need to implement the objective functions ourselves. This problem comes in two parts:

  1. We need to design an objective function that correctly represents our real-world problem, taking the problem variables and producing the correct objective values;
  2. We need to implement this objective function in a way that can work with our optimiser.

This comes down to passing the desired number of problem variables to a custom objective function and receiving the desired number of objective values.

In [2]:
    orientation = portrait
    "Problem Variables" -> "Objective Function" -> "Objective Values"
    "Objective Function" [color = '#ffffcc']
blockdiag { orientation = portrait "Problem Variables" -> "Objective Function" -> "Objective Values" "Objective Function" [color = '#ffffcc'] } Problem VariablesObjective FunctionObjective Values

When preparing to implement multi-objective optimisation experiments, it's often more convenient to use a ready-made framework/library instead of programming everything from scratch. Many libraries and frameworks have been implemented in many different programming languages. With our focus on multi-objective optimisation, our choice is an easy one. We will choose Platypus which has a focus on multi-objective problems and optimisation.

Platypus is a framework for evolutionary computing in Python with a focus on multiobjective evolutionary algorithms (MOEAs). It differs from existing optimization libraries, including PyGMO, Inspyred, DEAP, and Scipy, by providing optimization algorithms and analysis tools for multiobjective optimization.

In this section, we will use the Platypus framework to apply the Non-dominated Sorting Genetic Algorithm II (NSGA-II)1 to a custom objective function.

The Custom Objective Function

For our custom objective function we will look to implement F2 from Schaffer 19852, which is described as being a two-valued function of one variable. The function has been listed in Equation 1.

$$ \text{Minimize} = \begin{cases} f_{1}\left(x\right) = x^{2} \\ \tag{1} f_{2}\left(x\right) = \left(x-2\right)^{2} \\ \end{cases} $$

Let's implement this objective function using Python.

In [3]:
def schaffer_f1(x):
    f1 = x[0]**2
    f2 = (x[0]-2)**2
    return [f1, f2]

Now let's get this Python function into the Platypus Problem object which can be used during the evaluation stage of Platypus' optimisation process.

First, we will instantiate an instance of the Problem object, passing in the parameters $1$ and $2$, indicating that we want 1 problem variable and 2 objective values, respectively.

In [4]:
problem = plat.Problem(1, 2)

Next, we need to specify the type of the problem variables and their boundaries. In this case, we want real-valued problem variables between -10 and 10.

In [5]:
problem.types[:] = plat.Real(-10, 10)

Finally, we will assign our implementation of the Schaffer F1 function to our Problem object.

In [6]:
problem.function = schaffer_f1

Now we're ready to apply an optimisation algorithm to the problem. Let's create an instance of the NSGA-II optimiser, and pass in our problem object as a parameter for its configurations.

In [7]:
algorithm = plat.NSGAII(problem)

Now we can execute the optimisation process. Let's give the optimiser a budget of 10,000 function evaluations as a termination criterion. This may take some time to complete depending on your processor speed and the number of function evaluations.

In [8]:

Finally, we can display the results. In this case, we will be printing the objective values for each solution in the final population of the above execution.

In [9]:
for solution in algorithm.result:
[3.9996322358184786, 8.453544443958733e-09]
[1.127924708147307e-09, 3.9998656627665743]
[0.9798470709617833, 1.020358071685673]
[0.38454443571031444, 1.9040785578226482]
[1.4000522224087213, 0.6671001247703413]
[1.0396611912826064, 0.96111009309569]
[3.120557393450522, 0.05451760477056071]
[0.15507594797751703, 2.579888604313192]
[0.05586760781523832, 3.1104144228061585]
[3.795712518927766, 0.0026771473383199176]
[0.12995986105920465, 2.6879620188460915]
[0.442734545468221, 1.7812025190797471]
[0.043914191052792075, 3.2056856680087042]
[3.9594481993794433, 0.00010330233728202961]
[1.462877051366248, 0.6248988763576042]
[0.9137834265475023, 1.0901026311933664]
[2.137411567917473, 0.28945593481973475]
[2.6281127195597533, 0.14353073511726708]
[0.1028805437839336, 2.819880660485834]
[2.2400471434314926, 0.2533323268644064]
[3.4949642404701513, 0.017034858112865314]
[0.16933601693373196, 2.5233177087306577]
[2.316596485257274, 0.2284486746241924]
[0.3122278938999198, 2.077133644791235]
[0.11845798135379029, 2.7417489701024493]
[0.03361445590868618, 3.300244634782279]
[0.0013879830400626606, 3.8523654054184067]
[0.022446195795436358, 3.4231640145761197]
[3.6121173809489924, 0.009888885620541785]
[5.5417156423586535e-05, 3.970278336997728]
[0.7531515748749863, 1.2817793392886352]
[3.335016828058249, 0.030205451374249754]
[2.974568926306082, 0.07579346823402558]
[0.6227290456133345, 1.4662017243608552]
[3.2455494485962753, 0.03938603263488005]
[1.70759398929653, 0.48059639710802016]
[0.009755198821972788, 3.6146815586590724]
[0.46852012022794337, 1.730578936848159]
[1.3281261056874352, 0.7183519581831387]
[0.4939912910703839, 1.6826107303625057]
[2.6773901390817945, 0.13229715079593576]
[2.7385527095743996, 0.11912347789661137]
[2.092858211254413, 0.30617251216286745]
[2.480997613339696, 0.18052447131019167]
[1.1429696226288717, 0.86657932682308]
[0.06781547066310753, 3.026159322690217]
[0.34232161644788617, 2.0019913271155922]
[1.0911922688466036, 0.9127863166268271]
[2.53733751871492, 0.1657285932206128]
[1.9164303143764225, 0.37902252462292085]
[0.8708387093981126, 1.1380891396613748]
[0.5159551289638773, 1.6427544636044185]
[0.18887275289624061, 2.4504930342099436]
[1.7712990008141112, 0.44769270310334053]
[1.5092097159097293, 0.5952138414145473]
[2.009733593994548, 0.33913067156092297]
[0.2820492177046786, 2.157716973615996]
[0.22423802971923834, 2.330086907050349]
[0.5387984568342028, 1.602682772916547]
[1.857169082454968, 0.4060494434010344]
[0.19545949273320382, 2.4270274517061075]
[0.29733282327112676, 2.1162034891100303]
[0.012438897673796682, 3.5663196728238167]
[0.6634371702923297, 1.405371068342083]
[2.3972773833404246, 0.20401990980948848]
[0.09064792531822503, 2.886336169545825]
[1.1770953571782887, 0.8373343367011681]
[0.035626971593630895, 3.2806226368391247]
[2.3857770761352266, 0.20739272274933312]
[0.7857648657640396, 1.240029701905262]
[0.7093285874093915, 1.3404626953694212]
[0.835113707012082, 1.1797314681493236]
[3.060507547326951, 0.06278500658334013]
[0.6783991787108243, 1.3837995278620008]
[0.7218287854266984, 1.3234084808105706]
[2.908479834012355, 0.08677349731054121]
[2.2629525429238626, 0.24570726898149148]
[3.3772159881142443, 0.026334693342310037]
[3.0300527064539917, 0.06723407437230668]
[3.2462927428403665, 0.039304198000999005]
[1.1060600033932322, 0.8992845097054939]
[0.005923729525801859, 3.698060655395711]
[0.5928784144324736, 1.5129344813519414]
[0.015966538093391217, 3.51053146857975]
[1.2002788819194288, 0.8179892850635956]
[3.6381177868037446, 0.008577526155013114]
[1.5587974579738235, 0.564725038837195]
[0.3627011361291642, 1.9537141751709635]
[1.8397673605122788, 0.4142463930662528]
[0.5699165074201945, 1.5502039186589538]
[0.8939168750213298, 1.1120297798873044]
[2.7886571769423756, 0.10894798932963871]
[3.426846159564005, 0.02214909938496754]
[0.26078850951633015, 2.2180902566504592]
[1.6348737998360936, 0.5203864553041416]
[0.2413675085210735, 2.2762008142334933]
[0.5577668809982602, 1.5704151949773184]
[0.7990044851918896, 1.2235224529240398]
[0.213883802440122, 2.36398087551613]
[2.8132404469853185, 0.1041535380412187]

Visualising Solutions in Objective Space

In the last section, we concluded by printing the objective values for every solution. This information will be easier to digest using a plot, so let's quickly put the data into a Pandas DataFrame and then use Plotly to create a scatterplot. Let's start by moving our Platypus data structure to a DataFrame.

In [10]:
objective_values = np.empty((0, 2))

for solution in algorithm.result:
    y = solution.objectives
    objective_values = np.vstack([objective_values, y])
# convert to DataFrame
objective_values = pd.DataFrame(objective_values, columns=['f1','f2'])

With that complete, we can have a peek at our DataFrame to make sure we've not made any obvious mistakes.

In [11]:
f1 f2
0 3.999632e+00 8.453544e-09
1 1.127925e-09 3.999866e+00
2 9.798471e-01 1.020358e+00
3 3.845444e-01 1.904079e+00
4 1.400052e+00 6.671001e-01
... ... ...
95 2.413675e-01 2.276201e+00
96 5.577669e-01 1.570415e+00
97 7.990045e-01 1.223522e+00
98 2.138838e-01 2.363981e+00
99 2.813240e+00 1.041535e-01

100 rows × 2 columns

With no obvious issues, let's visualise the results using a scatterplot.

In [12]:
fig = go.Figure()
fig.add_scatter(x=objective_values.f1, y=objective_values.f2, mode='markers')

Great! If you search the literature for the true Pareto-optimal front for Schaffer F1, you can see that our approximation is looking as expected.


In this section, we have demonstrated how we can use a popular multi-objective optimisation algorithm, NSGA-II, to approximate multiple trade-off solutions to the Schaffer F1 test problem. We did this using the Platypus framework, and by implementing our custom objective function. You can use this approach to write your own objective functions that can be optimised by any algorithm in the Platypus framework.

  1. Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE transactions on evolutionary computation, 6(2), 182-197. 

  2. Schaffer, J.. (1985). Multiple Objective Optimization with Vector Evaluated Genetic Algorithms. Proceedings of the First Int. Conference on Genetic Algortihms, Ed. G.J.E Grefensette, J.J. Lawrence Erlbraum. 93-100. 

Fourier Transform Algorithm


In [55]:
# used to create block diagrams
%reload_ext xdiag_magic
%xdiag_output_format svg
import numpy as np                   # for multi-dimensional containers
import pandas as pd                  # for DataFrames
import plotly.graph_objects as go    # for data visualisation
import as pio              # to set shahin plot layout
from plotly.subplots import make_subplots
import scipy.fftpack                 # discrete Fourier transforms

pio.templates['shahin'] = pio.to_templated(go.Figure().update_layout(margin=dict(t=0,r=0,b=40,l=40))).layout.template
pio.templates.default = 'shahin'

Fast Fourier Transform


In [1]:
# used to create block diagrams
%reload_ext xdiag_magic
%xdiag_output_format svg
import numpy as np                   # for multi-dimensional containers
import pandas as pd                  # for DataFrames
import plotly.graph_objects as go    # for data visualisation
import as pio              # to set shahin plot layout
from plotly.subplots import make_subplots
import scipy.fftpack                 # discrete Fourier transforms

pio.templates['shahin'] = pio.to_templated(go.Figure().update_layout(margin=dict(t=0,r=0,b=40,l=40))).layout.template
pio.templates.default = 'shahin'
pio.renderers.default = "notebook_connected"

In a previous section we looked at how to create a single Sine Wave and visualise it in the time domain.

In [2]:
sample_rate = 1000
start_time = 0
end_time = 10

time = np.arange(start_time, end_time, 1/sample_rate)

frequency = 3
amplitude = 1
theta = 0

sinewave = amplitude * np.sin(2 * np.pi * frequency * time + theta)

fig = go.Figure(layout=dict(xaxis=dict(title='Time (sec)'),yaxis=dict(title='Amplitude')))
fig.add_scatter(x=time, y=sinewave)

Fourier Transform

In [3]:
freq = scipy.fftpack.fft(sinewave)/len(time)
In [4]:
hz = np.linspace(0, sample_rate/2, int(np.floor(len(time)/2)+1))

fig = go.Figure(
        xaxis=dict(title='Frequency (Hz)', range=[0, np.max(frequency) * 1.2]),

fig.add_scatter(x=hz, y=2 * np.abs(freq))
In [ ]:

Summing Sine Waves

In [5]:
sample_rate = 1000
start_time = 0
end_time = 10
theta = 0

time = np.arange(start_time, end_time, 1/sample_rate)

frequency = [3, 5, 2, 1, 10]
amplitude = [1, 2, 7, 3, 0.1]

fig = go.Figure(layout=dict(xaxis=dict(title='Time (sec)'),yaxis=dict(title='Amplitude')))
fig.add_scatter(x=time, y=sinewave)
In [6]:
fig = go.Figure(layout=dict(xaxis=dict(title='Time (sec)'),yaxis=dict(title='Amplitude')))
fig.add_scatter(x=time, y=sinewave)