\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{moeregrind8645} \pdfinfo{ /Title (python-datenanalyse.pdf) /Creator (Cheatography) /Author (moeregrind8645) /Subject (Python Datenanalyse Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{0F0F0F} \definecolor{LightBackground}{HTML}{F7F7F7} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Python Datenanalyse Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{moeregrind8645} via \textcolor{DarkBackground}{\uline{cheatography.com/183657/cs/38236/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}moeregrind8645 \\ \uline{cheatography.com/moeregrind8645} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 10th August, 2023.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Python Basics}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{17.67cm}}{`\{\{lang-py\}\}import numpy as np`} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} `\%matplotlib notebook`, `\%matplotlib inline` & interaktive Plots \tn % Row Count 4 (+ 3) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{17.67cm}}{`\{\{lang-py\}\}a = np.array({[}0,1,2,3,4{]})`} \tn % Row Count 5 (+ 1) % Row 3 \SetRowColor{white} `data{[}a,b{]}` & zweidimensionales Array, gibt Werte mit Koordinaten (a,b) zurück \tn % Row Count 9 (+ 4) % Row 4 \SetRowColor{LightBackground} `\{\{lang-py\}\}print(a{[}1:3){]}` & `{[}start:ende{]}` \tn % Row Count 11 (+ 2) % Row 5 \SetRowColor{white} `\{\{lang-py\}\}b = a + 1'` & mult/add array \tn % Row Count 13 (+ 2) % Row 6 \SetRowColor{LightBackground} `\{\{lang-py\}\}a = np.zeros(5)` & 5 x 0.0 \tn % Row Count 15 (+ 2) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{17.67cm}}{`\{\{lang-py\}\}a = np.ones(5)`} \tn % Row Count 16 (+ 1) % Row 8 \SetRowColor{LightBackground} `\{\{lang-py\}\}a = np.linspace(a\_min, a\_max, n\_a)` & d\_a = 1/(n\_a -1) \tn % Row Count 19 (+ 3) % Row 9 \SetRowColor{white} `n\_points = np.logspace(1, np.log10(len(data)), 100 , dtype=int) ` & logarithmisches array \# wir wollen 100 zahlen \tn % Row Count 23 (+ 4) % Row 10 \SetRowColor{LightBackground} `\{\{lang-py\}\}a = np.arange(a\_min, a\_max, d\_a)` & n\_a = \seqsplit{(a\_max-a\_min)/d\_a} (aufgerundet, array ohne a\_max) \tn % Row Count 26 (+ 3) % Row 11 \SetRowColor{white} `\{\{lang-py\}\}a = {[}0, math.pi ,0{]} b = np.exp(a)` & Funktion auf Array anwenden \tn % Row Count 29 (+ 3) % Row 12 \SetRowColor{LightBackground} `\{\{lang-py\}\}np.loadtxt?` & Dokumentation einer Funktion \tn % Row Count 31 (+ 2) \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Python Basics (cont)}} \tn % Row 13 \SetRowColor{LightBackground} `\{\{lang-py\}\}print('Die Summe der Zahlen \{\} und \{\} ist gleich \{\}.'.format(3, 5, 8))` & \{:d\} : Integer \{:f\} : Fliesskomma \{:0.2f\}: Fliesskomma mit 2 Nachkommestellen \tn % Row Count 5 (+ 5) % Row 14 \SetRowColor{white} `\{\{lang-py\}\} np.array({[}np.fromstring(l, dtype=float, sep=','){]})` & String Daten in Array (l ist String) \tn % Row Count 9 (+ 4) % Row 15 \SetRowColor{LightBackground} `np.stack((a, b))` & Matrix mit Zeilen (a,b) \tn % Row Count 11 (+ 2) % Row 16 \SetRowColor{white} `a.to\_numpy()` & Array zu np-Array \tn % Row Count 12 (+ 1) % Row 17 \SetRowColor{LightBackground} `X = np.reshape(df{[}'x'{]}.values, newshape=(-1, 1)) \# (-1, 1) bedeutet: eine Spalte mit sovielen Zeilen wie n{\"o}tig` & reshape macht aus 1 dimensionalem array ein zweidimensionales (jeder wert wird zu einem Array mit einem Eintrag) \tn % Row Count 18 (+ 6) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Iteration und Enumerate}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}for c\_i in c: \newline print(c\_i) \newline for index, wert in enumerate(a): \newline b{[}index{]} = wert**2} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{0.0 0.25 0.5 0.75 1.0 \newline Wir m{\"o}chten jedem b{[}i{]} den Wert a{[}i{]}**2 zuweisen.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Plotten eines Datensatztes}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}import matplotlib.pyplot as plt \newline \newline \# Umrechnung von Zoll in cm (1 Zoll = 2.54 cm) \newline cm = 0.393701 \newline \newline \# Definition von globalen Parametern, hier die Schriftgr{\"o}sse \newline plt.rcParams.update(\{'font.size': 16\}) \newline plt.rcParams.update(\{'axes.labelsize': 16\}) \newline \newline \# Definition der Figur, mit Gr{\"o}ssenangabe \newline fig = plt.figure(figsize=(20{\emph{cm, 17}}cm)) \newline ax1 = fig.add\_subplot(1, 1, 1) (anzahl, (x,y)) \newline \# Definitiond er zu plottenden Daten mit Label \newline ax1.plot(x0, y0, 'bo', label='Data') \#b = blue, o = Punkte \newline ax1.plot(x0, y0, 'r-', label=r'\$y = x\textasciicircum{}2\$') \#Rote Striche \newline \# Achsenbeschriftung, die Angegebene Schriftgr{\"o}sse überschrebit die globale Schriftgr{\"o}sse \newline ax1.set\_xlabel('x (x unit)') \newline ax1.set\_ylabel('y (y unit)') \newline ax1.set\_title("Titel") \newline \# Definition des Bereichs der geplottet werden soll \newline ax1.set\_xlim(0, 2) \newline ax1.set\_ylim(0, 4) \newline \# Erzeugen einer Legende, hier werden die Label aus der Plotfunktion übernommen \newline ax1.legend(fontsize=20, frameon=False) \newline \newline \newline \# Abspeichern der Figur \newline fig.savefig(r'Figur.png', dpi=400, transparent=True)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.8077 cm} x{8.4623 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Plotbefehle}} \tn % Row 0 \SetRowColor{LightBackground} `ax3.bar(bins{[}:-1{]}, hist, width=0.8*binsize)` & Balkendiagramm \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} `ax.axvline(V\_mean, color='r')` & Linie einzeichnen \tn % Row Count 5 (+ 2) % Row 2 \SetRowColor{LightBackground} \seqsplit{`fig.tight\_layout()`} & sch{\"o}nes Layout \tn % Row Count 6 (+ 1) % Row 3 \SetRowColor{white} `ax.plot(time1, signal1, 'x-')` & gemessene Datenpunkte markieren \tn % Row Count 8 (+ 2) % Row 4 \SetRowColor{LightBackground} \seqsplit{`plt.scatter(t\_mess}, U\_mess, zorder=2, color = "red", marker='o')` & Punkte \tn % Row Count 12 (+ 4) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{17.67cm}}{\seqsplit{`plt.axes().set\_aspect('auto'}, 'datalim')`} \tn % Row Count 13 (+ 1) % Row 6 \SetRowColor{LightBackground} `ax.legend()` & Legende erstellen \tn % Row Count 14 (+ 1) % Row 7 \SetRowColor{white} \seqsplit{`ax.semilogx(n\_points}, mean\_n)` & logarithmische x-achse \tn % Row Count 16 (+ 2) % Row 8 \SetRowColor{LightBackground} ` \seqsplit{ax.set\_yscale("log")`} & \# Logarithmische Skalierung der y-Achse \tn % Row Count 19 (+ 3) % Row 9 \SetRowColor{white} `ax1.errorbar(x, y, x\_error, y\_error)` & Graph mit Fehler \tn % Row Count 21 (+ 2) % Row 10 \SetRowColor{LightBackground} `ax3.plot(t, z,'.')` & Punkte plotten \tn % Row Count 22 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Abspeichern und Laden von Daten}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{SPEICHERN \newline \{\{lang-py\}\}np.savetxt('DataOut.txt', (x0, y0), delimiter = ',') \#Speichert Daten als ASCI (txt) \newline np.savetxt('DataOut.txt', (x,y,z), delimiter=',', header='Beispieldatei Datenanalyse, 14.2.2023. Format: x, y, z') \#Für Metadaten \newline \newline \newline LADEN \newline (x2, y2) = np.loadtxt('DataOut.txt', delimiter = ',' , comments = '\#') \#l{\"a}dt Daten, blendet \# aus \newline data = np.loadtxt('DataOut.txt', delimiter = ',') \#Daten von allg. Datenarray \newline \newline print(data.shape) \# a=np.array({[}{[}{[}0{]},{[}0{]}{]}{]}) hat shape (1,2,1) (3-dimensional) \newline x3 = data{[}0, :{]} \newline y3= data{[}1, :{]} \newline plt.plot(x3, y3) \newline zeilen, spalten = a.shape} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Mit 'shape' erfahren wir die Form. Diese Funktion gibt ein Tupel zurück mit den L{\"a}ngen der einzelnen Dimensionen des Arrays} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{zeilenweise Lesen und Speichern}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}LADEN \newline with open(file, 'r') as f: \newline lines = f.readlines() \newline \#lines ist ein String Array mit allen Daten \newline \newline d = np.zeros((len(lines)-1, 2)) \newline i = 0 \newline for l in lines{[}1:{]}: \newline d{[}i,:{]} = np.array({[}np.fromstring(l, dtype=float, sep=','){]}) \newline i = i+1 \newline \newline SPEICHERN \newline with open('DataOut.txt', 'w') as f: \newline f.writelines('x, y, z\textbackslash{}n') \#schreibe header \newline for i in range(0, len(x)): \newline f.writelines('\{:0.5f\}, \{:0.5f\}, \{:0.5f\}\textbackslash{}n'.format(x{[}i{]}, y{[}i{]}, z{[}i{]}))} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Lineare und logistische Regression}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{IMPORTS \newline from sklearn.model\_selection import train\_test\_split \newline from sklearn.linear\_model import LinearRegression \newline from sklearn.metrics import r2\_score \newline \newline \# Daten in Trainingsset und Testset aufteilen \newline X\_train, X\_test, y\_train, y\_test = train\_test\_split(X, y, test\_size=0.3, random\_state=42) \newline \newline \# Regressionsmodell trainieren, d.h. Koeffizienten optimieren. \newline linreg = LinearRegression() \newline linreg.fit(X\_train, y\_train) \newline \#analog für logistische Regression \newline \# Logistische Regression \newline lr = LogisticRegression() \newline lr.fit(X\_train, y\_train) \newline \newline \newline \# Measure the quality of the regression in the test data. \newline y\_pred = linreg.predict(X\_test) \newline r2 = r2\_score(y\_test, y\_pred) \newline print("R2 on test data: \{:.3f\}".format(r2)) \newline \newline Auf neuen Datensatz anwenden \newline \newline X\_final = \seqsplit{pd.read\_csv("Daten\_Aufgabe2/X\_final.csv")} \newline y\_final = linreg.predict(X\_final) \newline print(y\_final) \newline \newline \newline from sklearn.neural\_network import MLPClassifier \newline \newline \# Neuronales Netzwerk \newline mlp = \seqsplit{MLPClassifier(hidden\_layer\_sizes=(100},), max\_iter=1000, random\_state=42) \newline mlp.fit(X\_train, y\_train) \newline \newline y\_pred\_mlp = mlp.predict(X\_test) \newline accuracy\_mlp = accuracy\_score(y\_test, y\_pred\_mlp)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Entscheidungsb{\"a}ume}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}IMPORTS \newline from sklearn.model\_selection import train\_test\_split \newline from sklearn.tree import DecisionTreeClassifier \newline from sklearn.metrics import accuracy\_score \newline from sklearn.tree import plot\_tree \newline \newline \# 1. Daten in Testdaten und Trainingsdaten aufteilen \newline X\_train, X\_test, y\_train, y\_test = train\_test\_split(X, y, test\_size=0.3, random\_state=42) \newline \newline \# 2. Entscheidungsbaum erstellen und trainieren \newline tree = \seqsplit{DecisionTreeClassifier(random\_state=42}, max\_depth=4) \newline tree.fit(X\_train, y\_train) \newline \newline \# 3. Vorhersagen des Baumes überprüfen \newline y\_pred\_tree = tree.predict(X\_test) \newline accuracy\_tree = accuracy\_score(y\_test, y\_pred\_tree) \newline print("Accuracy of classification tree on test data: \{:.3f\}".format(accuracy\_tree)) \newline \newline \# Entscheidungsbaum plotten \newline plot\_tree(tree, \seqsplit{feature\_names=X.columns)} \newline plt.savefig('decision\_tree.pdf')} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{pandas}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\} \newline IMPORTS \newline import numpy as np \newline import pandas as pd \newline import matplotlib.pyplot as plt \newline from evaluate import * \newline \newline \# Lade Daten in ein pandas Dataframe \newline df = \seqsplit{pd.read\_csv('periodic\_table.csv')} \newline \newline \# Zeige die ersten fünf Zeilen des Dataframes \newline df.head() \newline \newline \#Bereich von Spalten ausw{\"a}hlen und anzeigen \newline df{[}5:10{]} \newline \newline \#Spalte ausw{\"a}hlen (Namen eingeben) \newline df{[}'Atomic\_Weight'{]} \newline df{[}{[}'Symbol', 'Melting\_Point', 'Boiling\_Point'{]}{]} \newline \newline \# Spalten ausschliessen: \newline df.drop({[}'Name', 'Atomic\_Number', 'Atomic\_Radius'{]}, axis=1)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Mode und Median}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}def mode(data, resolution): \newline \# Berechnen der PMF \newline x, px = PMF(data, resolution) \newline \# Der Wahrscheinlichste Wert ist derjenige, bei dem die PMF ein Maximum hat. \newline return x{[}np.argmax(px){]} \newline \newline -{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}- \newline \newline def median(data): \newline \# Wir sortieren die Daten, der Median entspricht dem Datenpunkt in der Mitte. \newline data\_sorted = np.sort(data) \newline if len(data) \% 2 != 0: \newline median = data\_sorted{[}len(data)//2{]} \newline \# Bei ungerader Anzahl Datenpunkten mitteln wir über die beiden benachbarten Punkte. \newline else: \newline median = (data\_sorted{[}len(data)//2{]} + data\_sorted{[}len(data)//2 - 1{]}) / 2 \newline return median} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Probability Mass Function}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}def PMF(data, resolution): \newline \# Definieren der Bins und Berechnen des Histogramms \newline \# Wir addieren resolution / 1000 zur Obergrenze, um sicherzustellen, dass der letzte Wert auch im Array ist. \newline bin\_centers = np.arange(np.min(data), np.max(data) + resolution / 1000, resolution) \newline bin\_edges = np.linspace(bin\_centers{[}0{]} - resolution / 2, \newline bin\_centers{[}-1{]} + resolution / 2, \newline len(bin\_centers) + 1) \newline \newline hist, \_ = np.histogram(data, bin\_edges) \newline \newline \# Normieren \newline px = hist / np.sum(hist) \newline \newline return bin\_centers, px} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Bandpass Filter}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}def ffilter(t, A, fmin, fmax): \newline N = len(t) \newline dt = t{[}1{]} - t{[}0{]} \newline f = np.fft.fftfreq(N, dt) \newline \newline spectrum = np.fft.fft(A) \newline \newline for i,freq in enumerate(f): \newline if abs(freq) \textless{} fmin or abs(freq) \textgreater{} fmax: \newline spectrum{[}i{]} = 0 \newline \newline return np.fft.ifft(spectrum)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Binomialverteilung}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}def binomial(n, k, p): \newline return scipy.special.binom(n,k){\emph{p{\bf{k}}(1-p)}}(n-k)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Tiefpassfilter durch Mitteln}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}def LP\_filter(x\_sample, N\_num): \newline \# N\_num ist die Anzahl Werte vor und nach jedem originalen Wert, die gemittelt werden \newline N\_av = 2*N\_num+1 \# Filterl{\"a}nge \newline n\_x = len(x\_sample) \# Anzahl des Messwerte in x \newline x\_filtered = x\_sample.copy() \# wir erstellen eine Kopie von x, um die neuen Werte hineinzuschreiben \newline for n in range(N\_num,n\_x-N\_num): \# wir ignoriernen wir N\_num ersten und letzte Werte \newline x\_filtered{[}n{]} = sum(x\_sample{[}n-N\_num:n+N\_num+1{]})/N\_av \# Mittelwert \newline return x\_filtered} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Spektrale Leistungsdichtige}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}from scipy import signal \newline \newline \#f\_samling = 1/sampling time \newline \newline f,PSDx = \seqsplit{scipy.signal.periodogram(U\_mess},f\_sampling,return\_onesided=True,scaling='density') \newline \newline alternative Berechnung \newline \newline from numpy.fft import fftfreq, fft, ifft \newline \newline data = \seqsplit{np.loadtxt('autocorrelation\_laser.txt')} \newline t = data{[}:, 0{]} {\emph{ 1e-12 \# in ps abgespeichert. Wir konvertieren in s \newline signal = data{[}:, 1{]} \newline \newline \# Zeitaufl{\"o}sung und L{\"a}nge des Signals berechnen \newline dt = t{[}1{]} - t{[}0{]} \newline N = len(t) \newline \newline \# Fouriertransformation \newline frequency = fftfreq(N, d=dt) \newline spectrum = fft(signal) \newline \newline \# Spektrale Leistungsdichte \newline psd = dt / N }} np.abs(spectrum)**2 \newline \newline Fourier Rücktransformation: \newline singal = np.fft.ifft(spectrum). \newline np.real(signal)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Fourieranalyse}} \tn % Row 0 \SetRowColor{LightBackground} Sei t das Zeit Array und V das Signal Array & ` N = len(t)` \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{17.67cm}}{`dt = t{[}1{]} -t{[}0{]}`} \tn % Row Count 4 (+ 1) % Row 2 \SetRowColor{LightBackground} ` f\_ny = 1 / (2 * (t{[}1{]} - t{[}0{]}))` & Nyquist-Frequenz \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} `df = 1 / t{[}-1{]}` & Frequenzaufl{\"o}sung \tn % Row Count 7 (+ 1) % Row 4 \SetRowColor{LightBackground} `f = np.fft.fftfreq(N, dt)` & Berechnen der geordneten Frequenzachse: welche Frequenzen k{\"o}nnen vorkommen \tn % Row Count 11 (+ 4) % Row 5 \SetRowColor{white} `spectrum = np.fft.fft(V)` & \seqsplit{Fouriertansformation} (Amplituden der entsprechenden Frequenzen) \tn % Row Count 15 (+ 4) % Row 6 \SetRowColor{LightBackground} `psd = dt / N {\emph{ np.abs(spectrum)}}*2` & Spektrale Leisungsdichte \tn % Row Count 17 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Fouriertransformation}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{{\bf{Koeffizienten für eine Frequenz bestimmen}} \newline \newline \newline \{\{lang-py\}\}def CN(x,f): \newline Xn = 0 \newline for n in range(N): \newline Xn += x{[}n{]} {\emph{ cmath.exp(-1j}}2{\emph{np.pi}}f*n) \newline return Xn \newline \newline fc = 0.022 \#f\_sig1 \newline \newline print(CN(x,fc)) \newline \#print(CN(U,-fc))} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Kovarianz und Autokovarianz}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\} \newline C = np.stack((U1\_mess,U3\_mess), axis=0) \newline np.cov(C) \#Kovarianzmatirx \newline np.corrcoef(C) \#Koeffizienten \newline \newline AUTOKOVARIANZFUNKTION \newline def Rxx(x, delta): \newline xm = np.mean(x) \newline dev\_sum = 0 \newline for i in range(len(x) - delta): \newline dev\_sum += (x{[}i{]} - xm) * (x{[}i + delta{]} - xm) \newline return dev\_sum / (len(x) - delta)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{6.0445 cm} x{11.2255 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{numpy Befehle}} \tn % Row 0 \SetRowColor{LightBackground} \seqsplit{`np.min(array)`} & Minimum \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} `np.mean(x)` & Mittelwert von Array x \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} `np.std(x)` & Standartabweichung von Array x \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} `np.abs(x)` & Betrag \tn % Row Count 6 (+ 1) % Row 4 \SetRowColor{LightBackground} \seqsplit{`np.sort(array)`} & gibt sortiertes array zurück \tn % Row Count 8 (+ 2) % Row 5 \SetRowColor{white} \seqsplit{`np.diff(array)`} & gibt differenz-array zurück \tn % Row Count 10 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Histogramm}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\} \newline \newline V = {\emph{Spannungswerte}} \newline \newline \#W{\"a}hle Bingr{\"o}sse und erstelle einzelne bins \newline binsize = 0.01 \newline bins = np.arange(np.min(V), np.max(V)+1, binsize) \newline \newline hist, b = np.histogram(V, bins) \#hist: h{\"a}ufigkeiten, b: array mit bin\_edges \newline \newline \#plotte normal balken (breite kleiner als binsize) \newline fig = plt.figure(figsize=(30{\emph{cm, 25.5}}cm)) \newline ax1 = fig.add\_subplot(2,2,1) \newline ax1.bar(bins{[}:-1{]}, hist, width=0.8*binsize) \newline ax1.set\_title('Binsize: \{:.2f\}V'.format(binsize))} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Messe diskrete Werte für Spannung, Histogramm zeigt, wie oft welche Spannung gemessen wurde.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Aufl{\"o}sung}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\{\{lang-py\}\}def \seqsplit{extract\_resolution(measured\_values):} \newline '''Extract smallest difference between two unique values in an array. \newline Values are treated as unique if their absolute difference is greater than the tolerance.''' \newline \newline sorted\_values = \seqsplit{np.sort(measured\_values)} \newline differences = np.diff(sorted\_values) \newline sorted\_differences = \seqsplit{np.sort(np.abs(differences))} \newline resolution = -1 \newline \newline tolerance = \seqsplit{np.max(np.abs(measured\_values))} * 1e-10 \# Gleitkommavergleich \newline for diff in sorted\_differences: \newline if diff \textgreater{} tolerance: \newline resolution = diff \newline break \newline \newline return resolution} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \end{document}