The SciPy Library

  1. Integration (scipy.integrate): Provides functions for numerical integration, including single and multiple integrals, as well as solving ordinary differential equations (ODEs).
  2. Optimization (scipy.optimize): Offers optimization algorithms for finding the minimum or maximum of a function, both constrained and unconstrained, and for curve fitting.
  3. Interpolation (scipy.interpolate): Contains functions for interpolating data, including linear, polynomial, and spline interpolation.
  4. Linear Algebra (scipy.linalg): Provides functions for performing linear algebra operations, such as solving linear systems, computing eigenvalues and eigenvectors, and singular value decomposition (SVD).
  5. Statistics (scipy.stats): Contains a wide range of probability distributions and statistical functions for calculating statistics, generating random numbers, and performing hypothesis testing.
  6. Signal Processing (scipy.signal): Offers functions for signal processing, including filtering, spectral analysis, and waveform generation.
  7. Fast Fourier Transform (scipy.fft): Provides functions for computing the discrete Fourier transform (DFT) and its inverse, as well as for working with Fourier transforms in general.
  8. Sparse matrices (scipy.sparse): Contains functions for working with sparse matrices, including creating sparse matrices, performing matrix-vector multiplication, and solving linear systems.
  9. Spatial algorithms (scipy.spatial): Provides functions for working with spatial data structures and algorithms, such as nearest-neighbor queries and Delaunay triangulations.
  10. Image Processing (scipy.ndimage): Offers functions for image processing tasks, such as filtering, morphological operations, and measurements on images.

Example: integration

\[ y = \int_{0}^{1}(x^2 + 2x) dx \]

import scipy.integrate as spi

# Define the function to be integrated
def f(x):
    return x**2 + 2*x

# Calculate the definite integral of f(x) from 0 to 1
result, error = spi.quad(f, 0, 1)

print("Result:", result)
print("Error:", error)
Result: 1.3333333333333333
Error: 1.4802973661668752e-14

Example: calculating the frequency spectrum of a signal

import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft, fftfreq

# Generate a sample signal
fs = 1000  # Sampling frequency
t = np.linspace(0, 1, fs, endpoint=False)  # Time vector from 0 to 1 second
f1, f2 = 10, 100  # Frequencies of the two components of the signal
signal = np.sin(2 * np.pi * f1 * t) + 0.5 * np.sin(2 * np.pi * f2 * t)  # Signal with two components

# Compute the FFT
fft_result = fft(signal)
magnitude = np.abs(fft_result)
frequencies = fftfreq(len(signal), 1/fs)

# Plot the signal
plt.figure(figsize=(12, 6))
plt.subplot(2, 1, 1)
plt.plot(t, signal)
plt.title('Input Signal')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')

# Plot the frequency spectrum
plt.subplot(2, 1, 2)
plt.plot(frequencies[:fs//2], magnitude[:fs//2])  # Plot only the positive frequencies
plt.title('Frequency Spectrum')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.tight_layout()
plt.show()

Exercise: plotting a Voronoi diagram from a random collection of points.

Check this page about Voronoi diagrams.

Suppose, now, we generate some random points in a 2D space:

import numpy as np

np.random.seed(0)
points = np.random.rand(10, 2)

The following code plots an image showing the Voronoi diagram.

voronoi_plot_2d(vor, show_vertices=False, line_colors='orange', line_width=2)
plt.plot(points[:, 0], points[:, 1], 'ko')  # Plot the points
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.gca().set_aspect('equal', adjustable='box')
plt.title('Voronoi Diagram')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

Notice that you still need the object vor that contains the Voronoi vertices.

  • How do you get it using SciPy? What is the function I should use?
  • What’s exactly the object that vor points to? Try to explore that.