Scientific Computing with Python

Contents

Installation

Spyder

Scientific Python Development Environment

sudo apt install python3-spyder spyder

NumPy

Library for numerical linear algebra,
such as the inverse of a matrix, etc.

sudo apt install python3-numpy

SciPy

Library with fundamental scientific algorithms,
such as the fast Fourier transform (FFT), etc.

sudo apt install python3-scipy python-scipy-doc

Matplotlib

Library for data visualization

sudo apt install python3-matplotlib

Examples

Sine

plot_sine.py
#!/usr/bin/env python3

import numpy as np
import matplotlib.pyplot as plt


class Figure:

    def __init__(self):
        self.fig, self.ax = plt.subplots(1, 1)
        self.ax.grid(True)

    def plot_sine(self, start, stop):
        x = np.arange(start, stop, 0.02)
        y = np.sin(x)
        self.ax.plot(x, y)

    def save(self, filename):
        self.fig.savefig(filename)


if __name__ == '__main__':
    figure = Figure()
    figure.plot_sine(0.0, 2.0*np.pi)
    figure.save('sine.svg')
    plt.show()
sine.svg

Curve fitting

fit_curve.py
#!/usr/bin/env python3

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize


class Figure:

    def __init__(self):
        self.fig, self.ax = plt.subplots(1, 1)
        self.ax.grid(True)
        self.ax.set_xlabel('x')
        self.ax.set_ylabel('f(x)')

    def plot_data(self, data_x, data_y):
        self.ax.plot(data_x, data_y, 'bo', label='data')

    def plot_curve_fit(self, data_x, data_y, func, fmt='r'):
        popt, pcov = scipy.optimize.curve_fit(func.f, data_x, data_y)
        self.ax.plot(data_x, func.f(data_x, *popt), fmt, label=func.string(*popt))
        self.ax.legend()

    def save(self, filename):
        self.fig.savefig(filename)


class LinearFunction:

    def f(x, a, b):
        return a*x + b

    def string(a, b):
        return "f(x) = {:4.2f} x {:+4.2f}".format(a, b)


class QuadraticFunction:

    def f(x, a, b, c):
        return a*x**2 + b*x + c

    def string(a, b, c):
        return "f(x) = {:4.2f} x² {:+4.2f} x {:+4.2f}".format(a, b, c)


if __name__ == '__main__':
    data_x = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
    data_y = np.array([2.5, 6.5, 12.5, 20.5, 30.5, 42.5, 56.5, 72.5])
    figure = Figure()
    figure.plot_data(data_x, data_y)
    figure.plot_curve_fit(data_x, data_y, LinearFunction, 'g')
    figure.plot_curve_fit(data_x, data_y, QuadraticFunction, 'r')
    figure.save('curve_fit.svg')
    plt.show()
curve_fit.svg