Jupyter Notebook that evolved out of iPython and is aimed at providing a platform for easy sharing, interaction, and development of open-source software, standards and services. Althought primarily and originally used for phyton interactions, you can interact with multiple programming languages using Jupyter (although orignially expanded from iPython to includ Julia, Pythion, and R). Jupyter notebooks is a great way to create, test, and share live code, as well as equations and visualizations with markdown text.
To inlcude more languages, check out kernels that are supported and their installation instructions.
To get started, download and install Jupyter. Installation of Anaconda is reccomened by Jupyter becuase it will also cover your python and notebook installation at the same time. If you prefer, you can also install Jupyter with pip, but this is only suggested for advanced Python users. There is extensive documentation to help with installation and download availble on the Jupyter and Anaconda pages.
Once installed, launch the Anacdona Navigator and launch Jupter notebooks. Also open the Anaconda Prompt window. We will use this window to install extra widgets.
In your Anaconda Prompt window, type the statement below and press enter, continue by following the prompts.
conda install -c conda-forge ipyleaflet
In your Anaconda Prompt window, type the statement below and press enter, continue by following the prompts.
conda install -c conda-forge bqplot
In your Anaconda Prompt window, type the statement below and press enter, continue by following the prompts.
conda install -c conda-forge pythreejs
Check out this cheatsheet by DataCamp to help with the interface.
Spend some time going through these help features.
Markdown can be easily used in Jupyter. Simply change the dropdown for the cell to "Markdown". If you need a refresher, here is another good cheatsheet.
Special commands can change shell to run different commands, for example you can run bash commands and magic commands directly within a new cell.
In [44]:
!conda list
Magic commands- Single percent sign means the cells arguments come from the same line, 2 mean the entire cell is used for the entire argument. lsmagic command can be used to list all other commands.
In [43]:
%lsmagic
Out[43]:
In [27]:
%matplotlib inline
Matplotlib examples can be found here.
In [29]:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
matplotlib.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots()
ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
ax.set_title('Using hyphen instead of Unicode minus')
plt.show()
In [28]:
import matplotlib.pyplot as plt
from matplotlib import collections, colors, transforms
import numpy as np
nverts = 50
npts = 100
# Make some spirals
r = np.arange(nverts)
theta = np.linspace(0, 2*np.pi, nverts)
xx = r * np.sin(theta)
yy = r * np.cos(theta)
spiral = list(zip(xx, yy))
# Make some offsets
# Fixing random state for reproducibility
rs = np.random.RandomState(19680801)
xo = rs.randn(npts)
yo = rs.randn(npts)
xyo = list(zip(xo, yo))
# Make a list of colors cycling through the default series.
colors = [colors.to_rgba(c)
for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]
fig, axes = plt.subplots(2, 2)
fig.subplots_adjust(top=0.92, left=0.07, right=0.97,
hspace=0.3, wspace=0.3)
((ax1, ax2), (ax3, ax4)) = axes # unpack the axes
col = collections.LineCollection([spiral], offsets=xyo,
transOffset=ax1.transData)
trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0)
col.set_transform(trans) # the points to pixels transform
# Note: the first argument to the collection initializer
# must be a list of sequences of x,y tuples; we have only
# one sequence, but we still have to put it in a list.
ax1.add_collection(col, autolim=True)
# autolim=True enables autoscaling. For collections with
# offsets like this, it is neither efficient nor accurate,
# but it is good enough to generate a plot that you can use
# as a starting point. If you know beforehand the range of
# x and y that you want to show, it is better to set them
# explicitly, leave out the autolim kwarg (or set it to False),
# and omit the 'ax1.autoscale_view()' call below.
# Make a transform for the line segments such that their size is
# given in points:
col.set_color(colors)
ax1.autoscale_view() # See comment above, after ax1.add_collection.
ax1.set_title('LineCollection using offsets')
# The same data as above, but fill the curves.
col = collections.PolyCollection([spiral], offsets=xyo,
transOffset=ax2.transData)
trans = transforms.Affine2D().scale(fig.dpi/72.0)
col.set_transform(trans) # the points to pixels transform
ax2.add_collection(col, autolim=True)
col.set_color(colors)
ax2.autoscale_view()
ax2.set_title('PolyCollection using offsets')
# 7-sided regular polygons
col = collections.RegularPolyCollection(
7, sizes=np.abs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData)
trans = transforms.Affine2D().scale(fig.dpi / 72.0)
col.set_transform(trans) # the points to pixels transform
ax3.add_collection(col, autolim=True)
col.set_color(colors)
ax3.autoscale_view()
ax3.set_title('RegularPolyCollection using offsets')
# Simulate a series of ocean current profiles, successively
# offset by 0.1 m/s so that they form what is sometimes called
# a "waterfall" plot or a "stagger" plot.
nverts = 60
ncurves = 20
offs = (0.1, 0.0)
yy = np.linspace(0, 2*np.pi, nverts)
ym = np.max(yy)
xx = (0.2 + (ym - yy)/ym)**2 * np.cos(yy - 0.4)*0.5
segs = []
for i in range(ncurves):
xxx = xx + 0.02*rs.randn(nverts)
curve = list(zip(xxx, yy*100))
segs.append(curve)
col = collections.LineCollection(segs, offsets=offs)
ax4.add_collection(col, autolim=True)
col.set_color(colors)
ax4.autoscale_view()
ax4.set_title('Successive data offsets')
ax4.set_xlabel('Zonal velocity component (m/s)')
ax4.set_ylabel('Depth (m)')
# Reverse the y-axis so depth increases downward
ax4.set_ylim(ax4.get_ylim()[::-1])
plt.show()
In [34]:
%%HTML
<iframe src="https://giphy.com/embed/3o7qE32pRVNYJYKGBO" width="480" height="269" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/veep-3o7qE32pRVNYJYKGBO">via GIPHY</a></p>
To get started, let's practice some very basic python scripts. Start with trying to print "Hello World". Once you have entered your script hit Shift+Enter. This will execute your code and create or send you to the next cell. Once you have done that try checking out a Cheatsheet to help get you running with another basic code snippet.
Don't be afraid to try something new. You won't break the shell, it will simply return an error if something is wrong.
There are many cheatsheets out there if you are uncomfortable writing your own snippet. Just do a quick google search for a function and copy/paste/execute in a cell below.
In [4]:
print ('hello world');
print('this is neat')
In [8]:
print('This is cool!')
In [5]:
"abc"*52
Out[5]:
In [9]:
import pandas as pd
df = pd.DataFrame()
a=range(11)
b=range(10,21)
c=range(20,31)
df['a']=a
df['b']=b
df['c']=c
df
Out[9]:
In [8]:
import math
# Input list.
values = [0.9999999, 1, 2, 3]
# Sum values in list.
r = sum(values)
print(r)
# Sum values with fsum.
r = math.fsum(values)
print(r)
In [9]:
import math
value1 = 9
value2 = 16
value3 = 100
# Use sqrt method.
print(math.sqrt(value1))
print(math.sqrt(value2))
print(math.sqrt(value3))
In [7]:
import numpy as np
import bqplot.pyplot as plt
size = 100
plt.figure(title='Scatter plot with colors')
plt.scatter(np.random.randn(size), np.random.randn(size), color=np.random.randn(size))
plt.show()
In [6]:
from ipyleaflet import Map
Map(center=[36.146956, -86.779788], zoom=10)
In [22]:
from ipyleaflet import Map import json
Map(center=[36.146956, -86.779788], zoom=10)
In [12]:
from pythreejs import *
f = """
function f(origu,origv) {
// scale u and v to the ranges I want: [0, 2*pi]
var u = 2*Math.PI*origu;
var v = 2*Math.PI*origv;
var x = Math.sin(u);
var y = Math.cos(v);
var z = Math.cos(u+v);
return new THREE.Vector3(x,y,z)
}
"""
surf_g = ParametricGeometry(func=f);
surf = Mesh(geometry=surf_g, material=LambertMaterial(color='green', side='FrontSide'))
surf2 = Mesh(geometry=surf_g, material=LambertMaterial(color='yellow', side='BackSide'))
scene = Scene(children=[surf, surf2, AmbientLight(color='#777777')])
c = PerspectiveCamera(position=[2.5, 2.5, 2.5], up=[0, 0, 1],
children=[DirectionalLight(color='white',
position=[3, 5, 1],
intensity=0.6)])
Renderer(camera=c, scene=scene, controls=[OrbitControls(controlling=c)])
You can use LaTex within Jupyter. Check out the LaTex cheatsheet!
One alternative to LaTeX is prettyPy or sympy. These are all great ways to write out equations, although the pros and cons of each need to be weighed before using. For example prettyPy does not evaluate expressions but you also don't have to initialize variables.
In [5]:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
In [4]:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
Out[4]:
Check out these cool Jupyter notebooks.
Most resources used to build this tutorial were taken from sourced cheatsheets, documentation, and stack overflow.
In [ ]: