SciPy¶

SciPy

  • Baut auf NumPy auf
  • Kann numerisch integrieren, DGLs lösen, optimieren, minimieren, …
  • Enthält auch physikalische Konstanten und wichtige mathematische Funktionen

Überblick über (fast) alles weitere was SciPy kann gibt es hier:

In [1]:
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')

Inhalt¶

Abrufen von Naturkonstanten¶

Wenn solche Konstanten genutzt werden, muss das korrekt mitgeteilt, also zitiert werden. Darauf gehen wir nächste Woche im LaTeX-Workshop ein :-)

(Quelle hier: scipy + version)

In [2]:
import numpy as np

# physical constants
import scipy.constants as const

const.epsilon_0
Out[2]:
8.8541878128e-12
In [3]:
# a list of all included constants
# search the web for "scipy physical constants reference guide" to find the same list

# We don't print the full list in the html file, to keep the notebook more managable
# const.physical_constants
# Here are the keys for the availabel constants instead
const.physical_constants.keys()
Out[3]:
dict_keys(['Wien displacement law constant', 'atomic unit of 1st hyperpolarizablity', 'atomic unit of 2nd hyperpolarizablity', 'atomic unit of electric dipole moment', 'atomic unit of electric polarizablity', 'atomic unit of electric quadrupole moment', 'atomic unit of magn. dipole moment', 'atomic unit of magn. flux density', 'deuteron magn. moment', 'deuteron magn. moment to Bohr magneton ratio', 'deuteron magn. moment to nuclear magneton ratio', 'deuteron-electron magn. moment ratio', 'deuteron-proton magn. moment ratio', 'deuteron-neutron magn. moment ratio', 'electron gyromagn. ratio', 'electron gyromagn. ratio over 2 pi', 'electron magn. moment', 'electron magn. moment to Bohr magneton ratio', 'electron magn. moment to nuclear magneton ratio', 'electron magn. moment anomaly', 'electron to shielded proton magn. moment ratio', 'electron to shielded helion magn. moment ratio', 'electron-deuteron magn. moment ratio', 'electron-muon magn. moment ratio', 'electron-neutron magn. moment ratio', 'electron-proton magn. moment ratio', 'magn. constant', 'magn. flux quantum', 'muon magn. moment', 'muon magn. moment to Bohr magneton ratio', 'muon magn. moment to nuclear magneton ratio', 'muon-proton magn. moment ratio', 'neutron gyromagn. ratio', 'neutron gyromagn. ratio over 2 pi', 'neutron magn. moment', 'neutron magn. moment to Bohr magneton ratio', 'neutron magn. moment to nuclear magneton ratio', 'neutron to shielded proton magn. moment ratio', 'neutron-electron magn. moment ratio', 'neutron-proton magn. moment ratio', 'proton gyromagn. ratio', 'proton gyromagn. ratio over 2 pi', 'proton magn. moment', 'proton magn. moment to Bohr magneton ratio', 'proton magn. moment to nuclear magneton ratio', 'proton magn. shielding correction', 'proton-neutron magn. moment ratio', 'shielded helion gyromagn. ratio', 'shielded helion gyromagn. ratio over 2 pi', 'shielded helion magn. moment', 'shielded helion magn. moment to Bohr magneton ratio', 'shielded helion magn. moment to nuclear magneton ratio', 'shielded helion to proton magn. moment ratio', 'shielded helion to shielded proton magn. moment ratio', 'shielded proton magn. moment', 'shielded proton magn. moment to Bohr magneton ratio', 'shielded proton magn. moment to nuclear magneton ratio', '{220} lattice spacing of silicon', 'lattice spacing of silicon', 'alpha particle-electron mass ratio', 'alpha particle mass', 'alpha particle mass energy equivalent', 'alpha particle mass energy equivalent in MeV', 'alpha particle mass in u', 'alpha particle molar mass', 'alpha particle-proton mass ratio', 'Angstrom star', 'atomic mass constant', 'atomic mass constant energy equivalent', 'atomic mass constant energy equivalent in MeV', 'atomic mass unit-electron volt relationship', 'atomic mass unit-hartree relationship', 'atomic mass unit-hertz relationship', 'atomic mass unit-inverse meter relationship', 'atomic mass unit-joule relationship', 'atomic mass unit-kelvin relationship', 'atomic mass unit-kilogram relationship', 'atomic unit of 1st hyperpolarizability', 'atomic unit of 2nd hyperpolarizability', 'atomic unit of action', 'atomic unit of charge', 'atomic unit of charge density', 'atomic unit of current', 'atomic unit of electric dipole mom.', 'atomic unit of electric field', 'atomic unit of electric field gradient', 'atomic unit of electric polarizability', 'atomic unit of electric potential', 'atomic unit of electric quadrupole mom.', 'atomic unit of energy', 'atomic unit of force', 'atomic unit of length', 'atomic unit of mag. dipole mom.', 'atomic unit of mag. flux density', 'atomic unit of magnetizability', 'atomic unit of mass', 'atomic unit of momentum', 'atomic unit of permittivity', 'atomic unit of time', 'atomic unit of velocity', 'Avogadro constant', 'Bohr magneton', 'Bohr magneton in eV/T', 'Bohr magneton in Hz/T', 'Bohr magneton in inverse meters per tesla', 'Bohr magneton in K/T', 'Bohr radius', 'Boltzmann constant', 'Boltzmann constant in eV/K', 'Boltzmann constant in Hz/K', 'Boltzmann constant in inverse meters per kelvin', 'characteristic impedance of vacuum', 'classical electron radius', 'Compton wavelength', 'Compton wavelength over 2 pi', 'conductance quantum', 'conventional value of Josephson constant', 'conventional value of von Klitzing constant', 'Cu x unit', 'deuteron-electron mag. mom. ratio', 'deuteron-electron mass ratio', 'deuteron g factor', 'deuteron mag. mom.', 'deuteron mag. mom. to Bohr magneton ratio', 'deuteron mag. mom. to nuclear magneton ratio', 'deuteron mass', 'deuteron mass energy equivalent', 'deuteron mass energy equivalent in MeV', 'deuteron mass in u', 'deuteron molar mass', 'deuteron-neutron mag. mom. ratio', 'deuteron-proton mag. mom. ratio', 'deuteron-proton mass ratio', 'deuteron rms charge radius', 'electric constant', 'electron charge to mass quotient', 'electron-deuteron mag. mom. ratio', 'electron-deuteron mass ratio', 'electron g factor', 'electron gyromag. ratio', 'electron gyromag. ratio over 2 pi', 'electron mag. mom.', 'electron mag. mom. anomaly', 'electron mag. mom. to Bohr magneton ratio', 'electron mag. mom. to nuclear magneton ratio', 'electron mass', 'electron mass energy equivalent', 'electron mass energy equivalent in MeV', 'electron mass in u', 'electron molar mass', 'electron-muon mag. mom. ratio', 'electron-muon mass ratio', 'electron-neutron mag. mom. ratio', 'electron-neutron mass ratio', 'electron-proton mag. mom. ratio', 'electron-proton mass ratio', 'electron-tau mass ratio', 'electron to alpha particle mass ratio', 'electron to shielded helion mag. mom. ratio', 'electron to shielded proton mag. mom. ratio', 'electron volt', 'electron volt-atomic mass unit relationship', 'electron volt-hartree relationship', 'electron volt-hertz relationship', 'electron volt-inverse meter relationship', 'electron volt-joule relationship', 'electron volt-kelvin relationship', 'electron volt-kilogram relationship', 'elementary charge', 'elementary charge over h', 'Faraday constant', 'Faraday constant for conventional electric current', 'Fermi coupling constant', 'fine-structure constant', 'first radiation constant', 'first radiation constant for spectral radiance', 'hartree-atomic mass unit relationship', 'hartree-electron volt relationship', 'Hartree energy', 'Hartree energy in eV', 'hartree-hertz relationship', 'hartree-inverse meter relationship', 'hartree-joule relationship', 'hartree-kelvin relationship', 'hartree-kilogram relationship', 'helion-electron mass ratio', 'helion mass', 'helion mass energy equivalent', 'helion mass energy equivalent in MeV', 'helion mass in u', 'helion molar mass', 'helion-proton mass ratio', 'hertz-atomic mass unit relationship', 'hertz-electron volt relationship', 'hertz-hartree relationship', 'hertz-inverse meter relationship', 'hertz-joule relationship', 'hertz-kelvin relationship', 'hertz-kilogram relationship', 'inverse fine-structure constant', 'inverse meter-atomic mass unit relationship', 'inverse meter-electron volt relationship', 'inverse meter-hartree relationship', 'inverse meter-hertz relationship', 'inverse meter-joule relationship', 'inverse meter-kelvin relationship', 'inverse meter-kilogram relationship', 'inverse of conductance quantum', 'Josephson constant', 'joule-atomic mass unit relationship', 'joule-electron volt relationship', 'joule-hartree relationship', 'joule-hertz relationship', 'joule-inverse meter relationship', 'joule-kelvin relationship', 'joule-kilogram relationship', 'kelvin-atomic mass unit relationship', 'kelvin-electron volt relationship', 'kelvin-hartree relationship', 'kelvin-hertz relationship', 'kelvin-inverse meter relationship', 'kelvin-joule relationship', 'kelvin-kilogram relationship', 'kilogram-atomic mass unit relationship', 'kilogram-electron volt relationship', 'kilogram-hartree relationship', 'kilogram-hertz relationship', 'kilogram-inverse meter relationship', 'kilogram-joule relationship', 'kilogram-kelvin relationship', 'lattice parameter of silicon', 'Loschmidt constant (273.15 K, 101.325 kPa)', 'mag. constant', 'mag. flux quantum', 'molar gas constant', 'molar mass constant', 'molar mass of carbon-12', 'molar Planck constant', 'molar Planck constant times c', 'molar volume of ideal gas (273.15 K, 100 kPa)', 'molar volume of ideal gas (273.15 K, 101.325 kPa)', 'molar volume of silicon', 'Mo x unit', 'muon Compton wavelength', 'muon Compton wavelength over 2 pi', 'muon-electron mass ratio', 'muon g factor', 'muon mag. mom.', 'muon mag. mom. anomaly', 'muon mag. mom. to Bohr magneton ratio', 'muon mag. mom. to nuclear magneton ratio', 'muon mass', 'muon mass energy equivalent', 'muon mass energy equivalent in MeV', 'muon mass in u', 'muon molar mass', 'muon-neutron mass ratio', 'muon-proton mag. mom. ratio', 'muon-proton mass ratio', 'muon-tau mass ratio', 'natural unit of action', 'natural unit of action in eV s', 'natural unit of energy', 'natural unit of energy in MeV', 'natural unit of length', 'natural unit of mass', 'natural unit of momentum', 'natural unit of momentum in MeV/c', 'natural unit of time', 'natural unit of velocity', 'neutron Compton wavelength', 'neutron Compton wavelength over 2 pi', 'neutron-electron mag. mom. ratio', 'neutron-electron mass ratio', 'neutron g factor', 'neutron gyromag. ratio', 'neutron gyromag. ratio over 2 pi', 'neutron mag. mom.', 'neutron mag. mom. to Bohr magneton ratio', 'neutron mag. mom. to nuclear magneton ratio', 'neutron mass', 'neutron mass energy equivalent', 'neutron mass energy equivalent in MeV', 'neutron mass in u', 'neutron molar mass', 'neutron-muon mass ratio', 'neutron-proton mag. mom. ratio', 'neutron-proton mass ratio', 'neutron-tau mass ratio', 'neutron to shielded proton mag. mom. ratio', 'Newtonian constant of gravitation', 'Newtonian constant of gravitation over h-bar c', 'nuclear magneton', 'nuclear magneton in eV/T', 'nuclear magneton in inverse meters per tesla', 'nuclear magneton in K/T', 'nuclear magneton in MHz/T', 'Planck constant', 'Planck constant in eV s', 'Planck constant over 2 pi', 'Planck constant over 2 pi in eV s', 'Planck constant over 2 pi times c in MeV fm', 'Planck length', 'Planck mass', 'Planck mass energy equivalent in GeV', 'Planck temperature', 'Planck time', 'proton charge to mass quotient', 'proton Compton wavelength', 'proton Compton wavelength over 2 pi', 'proton-electron mass ratio', 'proton g factor', 'proton gyromag. ratio', 'proton gyromag. ratio over 2 pi', 'proton mag. mom.', 'proton mag. mom. to Bohr magneton ratio', 'proton mag. mom. to nuclear magneton ratio', 'proton mag. shielding correction', 'proton mass', 'proton mass energy equivalent', 'proton mass energy equivalent in MeV', 'proton mass in u', 'proton molar mass', 'proton-muon mass ratio', 'proton-neutron mag. mom. ratio', 'proton-neutron mass ratio', 'proton rms charge radius', 'proton-tau mass ratio', 'quantum of circulation', 'quantum of circulation times 2', 'Rydberg constant', 'Rydberg constant times c in Hz', 'Rydberg constant times hc in eV', 'Rydberg constant times hc in J', 'Sackur-Tetrode constant (1 K, 100 kPa)', 'Sackur-Tetrode constant (1 K, 101.325 kPa)', 'second radiation constant', 'shielded helion gyromag. ratio', 'shielded helion gyromag. ratio over 2 pi', 'shielded helion mag. mom.', 'shielded helion mag. mom. to Bohr magneton ratio', 'shielded helion mag. mom. to nuclear magneton ratio', 'shielded helion to proton mag. mom. ratio', 'shielded helion to shielded proton mag. mom. ratio', 'shielded proton gyromag. ratio', 'shielded proton gyromag. ratio over 2 pi', 'shielded proton mag. mom.', 'shielded proton mag. mom. to Bohr magneton ratio', 'shielded proton mag. mom. to nuclear magneton ratio', 'speed of light in vacuum', 'standard acceleration of gravity', 'standard atmosphere', 'Stefan-Boltzmann constant', 'tau Compton wavelength', 'tau Compton wavelength over 2 pi', 'tau-electron mass ratio', 'tau mass', 'tau mass energy equivalent', 'tau mass energy equivalent in MeV', 'tau mass in u', 'tau molar mass', 'tau-muon mass ratio', 'tau-neutron mass ratio', 'tau-proton mass ratio', 'Thomson cross section', 'triton-electron mag. mom. ratio', 'triton-electron mass ratio', 'triton g factor', 'triton mag. mom.', 'triton mag. mom. to Bohr magneton ratio', 'triton mag. mom. to nuclear magneton ratio', 'triton mass', 'triton mass energy equivalent', 'triton mass energy equivalent in MeV', 'triton mass in u', 'triton molar mass', 'triton-neutron mag. mom. ratio', 'triton-proton mag. mom. ratio', 'triton-proton mass ratio', 'unified atomic mass unit', 'von Klitzing constant', 'weak mixing angle', 'Wien frequency displacement law constant', 'Wien wavelength displacement law constant', 'atomic unit of mom.um', 'electron-helion mass ratio', 'electron-triton mass ratio', 'helion g factor', 'helion mag. mom.', 'helion mag. mom. to Bohr magneton ratio', 'helion mag. mom. to nuclear magneton ratio', 'Loschmidt constant (273.15 K, 100 kPa)', 'natural unit of mom.um', 'natural unit of mom.um in MeV/c', 'neutron-proton mass difference', 'neutron-proton mass difference energy equivalent', 'neutron-proton mass difference energy equivalent in MeV', 'neutron-proton mass difference in u', 'standard-state pressure', 'alpha particle relative atomic mass', 'Bohr magneton in inverse meter per tesla', 'Boltzmann constant in inverse meter per kelvin', 'conventional value of ampere-90', 'conventional value of coulomb-90', 'conventional value of farad-90', 'conventional value of henry-90', 'conventional value of ohm-90', 'conventional value of volt-90', 'conventional value of watt-90', 'deuteron relative atomic mass', 'electron gyromag. ratio in MHz/T', 'electron relative atomic mass', 'elementary charge over h-bar', 'helion relative atomic mass', 'helion shielding shift', 'hyperfine transition frequency of Cs-133', 'lattice spacing of ideal Si (220)', 'luminous efficacy', 'neutron gyromag. ratio in MHz/T', 'neutron relative atomic mass', 'nuclear magneton in inverse meter per tesla', 'Planck constant in eV/Hz', 'proton gyromag. ratio in MHz/T', 'proton relative atomic mass', 'reduced Compton wavelength', 'reduced muon Compton wavelength', 'reduced neutron Compton wavelength', 'reduced Planck constant', 'reduced Planck constant in eV s', 'reduced Planck constant times c in MeV fm', 'reduced proton Compton wavelength', 'reduced tau Compton wavelength', 'shielded helion gyromag. ratio in MHz/T', 'shielded proton gyromag. ratio in MHz/T', 'shielding difference of d and p in HD', 'shielding difference of t and p in HT', 'tau energy equivalent', 'triton relative atomic mass', 'triton to proton mag. mom. ratio', 'vacuum electric permittivity', 'vacuum mag. permeability', 'W to Z mass ratio'])
In [4]:
# convert temperatures:
print(const.convert_temperature(100, "c", "K"))
print(const.convert_temperature(100, "kelvin", "Celsius"))
373.15
-173.14999999999998
In [5]:
# convert angles:
print(np.rad2deg(np.pi))
print(np.deg2rad(90))
180.0
1.5707963267948966
In [6]:
const.physical_constants["proton mass"]
# value, unit, error
Out[6]:
(1.67262192369e-27, 'kg', 5.1e-37)

Fitten¶

Oft möchte man eine Funktion mit freien Parametern, zum Beispiel eine Erwartung aus der Theorie, an die gemessenen Werte anpassen. Dies nennt man Fit.

Die Funktion scipy.optimize.curve_fit nutzt die numerische Methode der kleinsten Quadrate, die arbiträre Funktionen fitten kann. Für Funktionen, die eine Linearkombination von Einzelfunktionen sind, also

$$ f(x) = \sum_i^N a_i \cdot f_i(x) $$

existiert eine analytische Lösung. Deswegen sollten in solchen Fällen (z.B. alle Polynome) entsprechende Funktionen genutzt werden (z.B. np.polyfit).

Lineare Regression bzw. Regression von Polynomen¶

Im folgenden wird eine lineare Regression mit np.polyfit durchgeführt:

$$ f(x) = a + b \cdot x $$

In [7]:
# prepare plot
%matplotlib inline
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = (10, 8)
plt.rcParams["font.size"] = 16

# load data
x, y = np.genfromtxt("data/example_data_linear.txt", unpack=True)

fig, ax = plt.subplots(1, 1, layout="constrained")

ax.plot(x, y, "k.", label="example data");
No description has been provided for this image
In [8]:
# Fit a polynomial of degree 1, return covariance matrix
params, covariance_matrix = np.polyfit(x, y, deg=1, cov=True)

errors = np.sqrt(np.diag(covariance_matrix))

for name, value, error in zip("ab", params, errors):
    print(f"{name} = {value:.3f} ± {error:.3f}")
a = 4.977 ± 0.021
b = 0.070 ± 0.124
In [9]:
x_plot = np.linspace(0, 10)

fig, ax = plt.subplots(1, 1, layout="constrained")

ax.plot(x, y, ".", label="Messwerte")
ax.plot(
    x_plot,
    params[0] * x_plot + params[1],
    label="Lineare Regression",
    linewidth=3,
)
ax.legend();
No description has been provided for this image

Nichtlineare Funktionen der Parameter¶

Wenn eine Funktion nicht linear bezüglich der freien Parameter ist, muss die Lösung numerisch gefunden werden.

Hierbei kann es sein, dass der Minimierungsalgorithmus in lokale Maxima hineinläuft und unsinnige Ergebnisse liefert, dies kann mit guten Startwerten meistens vermieden werden.

Als Beispiel einer komplexeren Funktion wird im Folgenden die Sigmoidfunktion verwendet (Ähnlich zum tanh):

$$ f(x; a, b, c) = \frac{a}{1 + \exp(-(x-b))} + c$$

In [10]:
def sigmoid(x, a, b, c):
    return a / (1 + np.exp(-(x - b))) + c


x_plot = np.linspace(-50, 50, 1000)

ax.cla()

ax.set_xlabel("x")
ax.set_ylabel("y")

ax.plot(x_plot, sigmoid(x_plot, 1, 0, 0), label="Sigmoid")
ax.plot(x_plot, np.tanh(x_plot), label="tanh")
ax.legend()
fig
Out[10]:
No description has been provided for this image

Die Messwerte aus einem Praktikumsversuch:

In [11]:
x, y = np.loadtxt("data/fit_data_with_init_values.txt", unpack=True)

ax.cla()
ax.plot(x, y, "o", label=r"Messwerte")

ax.set_xlabel("Temperatur / °C")
ax.set_ylabel("$GP$")
fig
Out[11]:
No description has been provided for this image

Ein einfacher Fit wie oben funktioniert hier nicht so gut:

In [12]:
from scipy.optimize import curve_fit

params, covariance_matrix = curve_fit(sigmoid, x, y)

uncertainties = np.sqrt(np.diag(covariance_matrix))

for name, value, uncertainty in zip("abc", params, uncertainties):
    print(f"{name} = {value:8.3f} ± {uncertainty:.3f}")
a = -307.056 ± inf
b =    1.000 ± inf
c =  307.769 ± inf
/home/christian/.local/mambaforge/envs/toolbox/lib/python3.11/site-packages/scipy/optimize/_minpack_py.py:1010: OptimizeWarning: Covariance of the parameters could not be estimated
  warnings.warn('Covariance of the parameters could not be estimated',

Schaut man sich die berechnete Ausgleichskurve an sieht man auch, dass das nicht stimmen kann:

In [13]:
ax.cla()
ax.set_xlabel("Temperatur / °C")
ax.set_ylabel("$GP$")


ax.plot(x, y, "o", label="Messdaten")
ax.plot(x_plot, sigmoid(x_plot, *params), "-", label=r"Sigmoid Fit")

ax.legend(loc="best")
fig
Out[13]:
No description has been provided for this image

Was macht man jetzt?
Bei solchen Fragen hilft die Dokumentation der Pythonmodule (hier: scipy) oder Stack Overflow weiter.
Folgendes Google-Muster ist ein guter Anfang (beachte englische Sprache):

python <module-name> <function-name> <What went wrong?>

Also in diesem Fall: python scipy curve_fit fails

Damit dieser Fit funktioniert müssen die Startwerte für den internen Minimierungsalgorithmus angepasst werden.
Aus der Dokumentation/Stack Overflow wissen wir jetzt, dass man mit dem keyword argument p0 (Standardwert is p0=(1,1,1)) die Startwerte einstellt:

In [14]:
params, covariance_matrix = curve_fit(sigmoid, x, y, p0=(-1, 40, 1))


uncertainties = np.sqrt(np.diag(covariance_matrix))

for name, value, uncertainty in zip("abc", params, uncertainties):
    print(f"{name} = {value:8.3f} ± {uncertainty:.3f}")
a =   -0.494 ± 0.014
b =   40.668 ± 0.137
c =    0.839 ± 0.006
In [15]:
ax.cla()
ax.set_xlabel("Temperatur / °C")
ax.set_ylabel("$GP$")
x_plot = np.linspace(0, 50, 1000)


ax.plot(x, y, "o", label="Messwerte")
ax.plot(x_plot, sigmoid(x_plot, *params), "-", label="Sigmoid Fit")

ax.legend(loc="best")
fig
Out[15]:
No description has been provided for this image

Zum Vergleich der beiden Anfangswerte (seeds) kann man sich die einmal ansehen und mit den angepassten Parametern vergleichen:

In [16]:
default_seed = (1, 1, 1)
good_seed = (-1, 40, 1)

parameter = [default_seed, good_seed, params]

x_plot = np.linspace(-80, 80, 1000)

ax.cla()
for a, b, c in parameter:
    ax.plot(x_plot, sigmoid(x_plot, a, b, c), label=f"f(x; {a:0.3f}, {b:0.3f}, {c:0.3f})")

ax.legend()
fig
Out[16]:
No description has been provided for this image

Die richtigen Startwerte findet man entweder durch

  1. trial and error => einfach ausprobieren bis es klappt

  2. nachdenken => siehe unten

Im obigen Beispiel musste nur der Parameter b angepasst werden, weil der für die Form der Kurve sehr wichtig ist.

$$ f(x; a, b, c) = \frac{a}{1 + \exp(-(x-b))} + c$$

In [17]:
bs = [0, 20, 40]

x_plot = np.linspace(-50, 50, 1000)

ax.cla()
ax.set_xlabel("x")
ax.set_ylabel("y")


for b in bs:
    (line,) = ax.plot(x_plot, sigmoid(x_plot, 1, b, 0), label=f"f(x; 1, {b}, 0)")

    ax.plot(
        b,
        sigmoid(b, 1, b, 0),
        "o",
        color=line.get_color(),
        ms=20,
        label=f"f(x={b}) = {sigmoid(b, 1, b, 0)}",
    )


ax.legend()
fig
Out[17]:
No description has been provided for this image

Der Parameter $b$ gibt den $x$-Wert an, bei dem die Funktion auf die Hälfte des Maximums abgefallen ist.
Bei den Messwerten oben ist die Stelle ungefähr bei $x=40$, also ist b = 40 ein guter Startwert.

Das lässt sich auch automatisieren:

In [18]:
ax.cla()
ax.plot(x, y, "o")

idx = np.argmin(np.abs(y - 0.5))

ax.plot(x[idx], y[idx], "o")

print(x[idx], y[idx])
fig
40.8 0.5586250642
Out[18]:
No description has been provided for this image

Weitere nützliche Funktionen für das Praktikum¶

Folgende Eigenschaften von Scipy sollen nur die Idee vermitteln, was noch alles möglich ist.

Statistische Verteilungen und Funktionen¶

Das scipy.stats Modul enthält viele Wahrscheinlichkeitsverteilungen und -funktionen. Als Beispiel wird hier jedoch nur die Standardabweichung des Mittelwertes berechnet.

In [19]:
import numpy as np

x = np.array([2, 5, 7])  # create test array

from scipy.stats import sem

print(sem(x))  # standard error of the mean
1.4529663145135578

Finden von Peaks¶

Das scipy.signal Modul enthält Funktionen zur Signalverarbeitung. Das kann interessant sein zum automatischen Finden von Peaks, oder Bestimmung der Periodizität.

In [20]:
# example data
from scipy.datasets import electrocardiogram

x = electrocardiogram()[2000:4000]

# find peaks
from scipy.signal import find_peaks

peaks, _ = find_peaks(x, distance=150)

fig, ax = plt.subplots(1, 1, layout="constrained")

ax.plot(x, label="EKG")
ax.plot(peaks, x[peaks], "x", ms=10, label="peaks")
ax.legend();
No description has been provided for this image