Programming for Data Science ยท Lecture 08

Modules
and NumPy

The slides, and three pictures that are nothing but arrays. Each one takes fewer than 25 lines of code.

Slides (PDF) follow shortly
QR code to https://prods-numpy.pages.devprods-numpy.pages.dev
Eight million points

Eight million points

Twenty thousand points jump 400 times by the same two formulas. Nobody drew these curves; we only count where the points land.

You see here: Arithmetic on whole arrays, np.sin, np.histogram2d

Show the code
import numpy as np
import matplotlib.pyplot as plt

# 20,000 points start at random places and all jump 400 times
a, b, c, d = -1.7, 1.8, -1.9, -0.4
rng = np.random.default_rng(1)
x, y = rng.uniform(-1, 1, (2, 20_000))
xs, ys = [], []
for step in range(400):
    x, y = (np.sin(a * y) + c * np.cos(a * x),
            np.sin(b * x) + d * np.cos(b * y))
    if step > 20:
        xs.append(x)
        ys.append(y)

# count how many points land in each pixel, then draw the counts
counts, _, _ = np.histogram2d(np.concatenate(xs), np.concatenate(ys), bins=1200)
plt.figure(figsize=(8, 8))
plt.imshow(np.log1p(counts.T), cmap='magma', origin='lower')
plt.axis('off')
plt.savefig('attractor.png', bbox_inches='tight', pad_inches=0, facecolor='black')
Download ex1_attractor.py
Two stones in the water

Two stones in the water

Every pixel computes its distance to two points. Where the waves meet, they add up or cancel out.

You see here: 2D arrays, point-wise operations, np.meshgrid

Show the code
import numpy as np
import matplotlib.pyplot as plt

# every pixel gets an x and a y value
x, y = np.meshgrid(np.linspace(-10, 10, 900), np.linspace(-6, 6, 540))

# two stones fall into the water: distance to each, one wave each
r1 = np.sqrt((x + 3)**2 + y**2)
r2 = np.sqrt((x - 3)**2 + y**2)
z = np.sin(5 * r1) / np.sqrt(r1 + 0.5) + np.sin(5 * r2) / np.sqrt(r2 + 0.5)

plt.figure(figsize=(10, 6))
plt.imshow(z, cmap='twilight_shifted', vmin=-1.3, vmax=1.3)
plt.axis('off')
plt.savefig('waves.png', bbox_inches='tight', pad_inches=0)
Download ex2_waves.py
A corner of the Mandelbrot set

A corner of the Mandelbrot set

The same small formula, repeated 400 times for 600,000 complex numbers at once.

You see here: Boolean arrays as a filter: z[inside]

Show the code
import numpy as np
import matplotlib.pyplot as plt

# a 2D array of complex numbers, one per pixel
x, y = np.meshgrid(np.linspace(-0.748, -0.742, 1000), np.linspace(0.097, 0.1006, 600))
c = x + 1j * y
z = np.zeros_like(c)
age = np.zeros(c.shape)

for step in range(400):
    inside = np.abs(z) < 2              # boolean array
    z[inside] = z[inside]**2 + c[inside]
    age[inside] += 1

plt.figure(figsize=(10, 6))
plt.imshow(np.log(age), cmap='inferno', origin='lower')
plt.axis('off')
plt.savefig('mandelbrot.png', bbox_inches='tight', pad_inches=0)
Download ex3_mandelbrot.py