Merge branch 'master' of whale.am28.uni-tuebingen.de:scientificComputing

This commit is contained in:
Jan Benda 2018-03-16 22:35:17 +01:00
commit ad33012da7
16 changed files with 553 additions and 207 deletions

View File

@ -439,11 +439,11 @@ that help to solve the problem.
steps for correctness. steps for correctness.
\item Call for help and explain the program to someone else. When you \item Call for help and explain the program to someone else. When you
do this, start at the beginning and walk through the program line by do this, start at the beginning and walk through the program line by
line. Often it is not necessary that the other person is a line. Often, it is not necessary that the other person is a
programmer or exactly understands what is going on. Often, it is the programmer or exactly understands what is going on. Rather, it is the
own reflection on the problem and the chosen approach that helps own reflection on the problem and the chosen approach that helps
finding the bug. (This strategy is also known as \codeterm{Rubber finding the bug (This strategy is also known as \codeterm{Rubber
duck debugging}. duck debugging}).
\end{enumerate} \end{enumerate}
@ -492,15 +492,16 @@ The toolbar of the editor offers now a new set of tools for debugging:
\item \textbf{Step} --- Execute the next command and stop. \item \textbf{Step} --- Execute the next command and stop.
\item \textbf{Step in} --- If the next command is a \item \textbf{Step in} --- If the next command is a
function call, step into it and stop at the first command. function call, step into it and stop at the first command.
\item \textbf{Step out} --- If the next command is a function call, \item \textbf{Step out} --- Suppose you entered a function with
proceed until the called function returns, then stop. \emph{step in}. \emph{Step out} will continue with the execution and
stop once you are back in the calling function.
\item \textbf{Run to cursor} --- Execute all statements up to the \item \textbf{Run to cursor} --- Execute all statements up to the
current cursor position. current cursor position.
\item \textbf{Quit debugging} --- Immediately stop the debugging \item \textbf{Quit debugging} --- Immediately stop the debugging
session and stop the further code execution. session and stop further code execution.
\end{enumerate} \end{enumerate}
The debugger offers some more (advanced) features but the The debugger offers some more (advanced) features but the
functionality offered by the basic tools is often enough to debug a program. functionality offered by the basic tools is often enough to debug a
program.

View File

@ -1,11 +1,11 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Design patterns} \chapter{Design pattern}
Many code fragments are variations of some basic patterns. These Many code fragments are variations of some basic pattern. These
patterns are used in many different variations in many different pattern are used in many different variations in many different
contexts. In this chapter we summarize a few of these \enterm[design contexts. In this chapter we summarize a few of these \enterm[design
pattern]{design patterns}. pattern]{design pattern}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Looping over vector elements} \section{Looping over vector elements}

View File

@ -133,7 +133,7 @@ Log-Likelihood
\begin{eqnarray*} \begin{eqnarray*}
\log {\cal L}(\theta|(x_1,y_1,\sigma_1), \ldots, (x_n,y_n,\sigma_n)) \log {\cal L}(\theta|(x_1,y_1,\sigma_1), \ldots, (x_n,y_n,\sigma_n))
& = & \sum_{i=1}^n \log \frac{1}{\sqrt{2\pi \sigma_i^2}}e^{-\frac{(y_i-f(x_i;\theta))^2}{2\sigma_i^2}} \\ & = & \sum_{i=1}^n \log \frac{1}{\sqrt{2\pi \sigma_i^2}}e^{-\frac{(y_i-f(x_i;\theta))^2}{2\sigma_i^2}} \\
& = & \sum_{i=1}^n - \log \sqrt{2\pi \sigma_i^2} -\frac{(x_i-f(y_i;\theta))^2}{2\sigma_i^2} \\ & = & \sum_{i=1}^n - \log \sqrt{2\pi \sigma_i^2} -\frac{(y_i-f(x_i;\theta))^2}{2\sigma_i^2} \\
\end{eqnarray*} \end{eqnarray*}
Der einzige Unterschied zum vorherigen Beispiel ist, dass die Der einzige Unterschied zum vorherigen Beispiel ist, dass die
Mittelwerte der Normalverteilungen nun durch die Funktionswerte Mittelwerte der Normalverteilungen nun durch die Funktionswerte

View File

@ -0,0 +1,54 @@
clear all
close all
max_frames = 500;
f_x = 1;
f_y = 1.5;
dt = 2*pi/500;
f = figure();
set(f, 'visible', 'off');
set(f, 'PaperUnits', 'centimeter', 'PaperSize', [2.5, 2.5], ...
'PaperPosition', [0, 0, 2.5, 2.5], 'Color', 'white')
writer = VideoWriter('../lecture/images/lissajous.mp4', 'MPEG-4');
writer.FrameRate = 25;
writer.Quality = 50;
open(writer);
for i = 1:max_frames
x = sin(f_x * 2 * pi * dt * i);
y = sin(f_y * 2 * pi * dt * i);
scatter(x, y, 30, 'r', 'filled');
xlim([-1.05, 1.05])
xticks([-1., 0., 1.])
ylim([-1.05, 1.05])
yticks([-1., 0., 1.])
xlabel('x')
ylabel('y')
drawnow;
frame = getframe(f);
writeVideo(writer, frame);
end
close(writer)
x_positions = zeros(max_frames, 1);
y_positions = zeros(max_frames, 1);
for i = 1:max_frames
x_positions(i) = sin(f_x * 2 * pi * dt * i);
y_positions(i) = sin(f_y * 2 * pi * dt * i);
end
f = figure();
set(f, 'PaperUnits', 'centimeter', 'PaperSize', [5, 5], ...
'PaperPosition', [0, 0, 5, 5], 'Color', 'white')
scatter(x_positions, y_positions, 10, 'r', 'filled');
xlim([-1.05, 1.05])
xticks([-1., 0., 1.])
ylim([-1.05, 1.05])
yticks([-1., 0., 1.])
xlabel('x')
ylabel('y')
saveas(f, '../lecture/images/lissajous.png')

52
plotting/code/scaling.py Normal file
View File

@ -0,0 +1,52 @@
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as spst
y_data = np.arange(89., 99., 1.) + np.random.randn(10) * 3.;
x_labels = ['10.18', '11.18', '12.18', '01.19', '02.19',
'03.19', '04.19','05.19','06.19','07.19']
x_data = np.arange(len(x_labels))
slope, intercept, _, _, _ = spst.linregress(x_data, y_data)
fit = x_data * slope + intercept
fig = plt.figure()
fig.set_size_inches(7.5, 2.5)
ax1 = plt.subplot2grid((2, 5), (0, 0), rowspan=2)
ax2 = plt.subplot2grid((2, 5), (0, 1), rowspan=2)
ax3 = plt.subplot2grid((2, 5), (1, 2), rowspan=1)
ax4 = plt.subplot2grid((2, 5), (0, 3), rowspan=2, colspan=2)
ax1.grid(axis='y', zorder=0)
ax1.scatter(x_data, y_data, zorder=3)
ax1.plot(x_data, fit, zorder=4, color='r')
ax1.set_ylim([85, 101])
ax1.set_xticks(x_data[0::2])
ax1.set_xticklabels(x_labels[0::2], rotation=45, fontsize=9)
ax1.text(-0.3, 1.05, "A", transform=ax1.transAxes, size=12)
ax2.grid(axis='y', zorder=0)
ax2.scatter(x_data, y_data, zorder=3)
ax2.plot(x_data, fit, zorder=4, color='r')
ax2.set_ylim([0, 120])
ax2.set_xticks(x_data[0::2])
ax2.set_xticklabels(x_labels[0::2], rotation=45, fontsize=9)
ax2.text(-0.3, 1.05, "B", transform=ax2.transAxes, size=12)
ax3.grid(axis='y', zorder=0)
ax3.scatter(x_data, y_data, zorder=3)
ax3.plot(x_data, fit, zorder=4, color='r')
ax3.set_ylim([85, 101])
ax3.set_xticks(x_data[0::2])
ax3.set_xticklabels(x_labels[0::2], rotation=45, fontsize=9)
ax3.text(-0.3, 1.1, "C", transform=ax3.transAxes, size=12)
ax4.grid(axis='y', zorder=0)
ax4.scatter(x_data, y_data, zorder=3)
ax4.plot(x_data, fit, zorder=4, color='r')
ax4.set_ylim([85, 101])
ax4.set_xticks(x_data)
ax4.set_xticklabels(x_labels, rotation=45, fontsize=9)
ax4.text(-0.15, 1.05, "D", transform=ax4.transAxes, size=12)
fig.subplots_adjust(left=0.05, top=0.9, bottom=0.175, right=0.97, hspace=0.5, wspace=0.4)
plt.savefig('../lecture/images/plot_scaling.pdf')

View File

@ -0,0 +1,28 @@
x = 1:2:100;
y = (0.5 .* x - 0.56) + randn(size(x)) .* 5.;
f = figure();
set(f, 'paperunits', 'centimeter', 'papersize', [15, 5], ...
'paperposition', [0, 0, 15, 5], 'color', 'white');
subplot(1, 3, 1);
scatter(x, y, 15, 'r', 'filled');
xlabel('x');
ylabel('y');
text(-35, max(ylim) * 1.075,'A', 'FontSize', 12);
subplot(1, 3, 2)
scatter(x, y, 1:length(x), 'r');
xlabel('x');
ylabel('y');
text(-35, max(ylim) * 1.075,'B', 'FontSize', 12);
subplot(1, 3, 3)
colors = zeros(length(x),3);
colors(:,1) = round(1:255/length(x):255)/255';
scatter(x, y, 15, colors, 'filled')
xlabel('x');
ylabel('y');
text(-35, max(ylim) * 1.075,'C', 'FontSize', 12);
saveas(f, '../lecture/images/scatterplot.png')

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -16,22 +16,12 @@
\input{plotting} \input{plotting}
\subsection{Error bars and error areas}
\subsection{Scatter plot}
\subsection{Histograms}
\subsection{Heatmaps} \subsection{Heatmaps}
\subsection{3-D plot} \subsection{3-D plot}
\subsection{Polar plot} \subsection{Polar plot}
\subsection{print instead of saveas????}
\subsection{Movies and animations}
\section{TODO} \section{TODO}
\begin{itemize} \begin{itemize}
\item Beispiele schlechter plots sollten mehr Bezug zu den Typen von \item Beispiele schlechter plots sollten mehr Bezug zu den Typen von

View File

@ -66,8 +66,8 @@ sketch and the exact position of the data points is of no importance.
The following figures show examples of misleading or suggestive The following figures show examples of misleading or suggestive
presentaions of data. Several of the effects have been axaggerated to presentations of data. Several of the effects have been exaggerated to
make the point. A little more subtlely these methods are employed to make the point. A little more subtlety these methods are employed to
nudge the viewers experience into the desired direction. You can find nudge the viewers experience into the desired direction. You can find
more examples on \url{https://en.wikipedia.org/wiki/Misleading_graph}. more examples on \url{https://en.wikipedia.org/wiki/Misleading_graph}.
@ -75,7 +75,7 @@ more examples on \url{https://en.wikipedia.org/wiki/Misleading_graph}.
\includegraphics[width=0.35\textwidth]{misleading_pie} \includegraphics[width=0.35\textwidth]{misleading_pie}
\hspace{0.05\textwidth} \hspace{0.05\textwidth}
\includegraphics[width=0.35\textwidth]{sample_pie} \includegraphics[width=0.35\textwidth]{sample_pie}
\titlecaption{Perspective distortion influendes the perceived \titlecaption{Perspective distortion influences the perceived
size.}{By changing the perspective of the 3-D illustration the size.}{By changing the perspective of the 3-D illustration the
highlighted segment \textbf{C} gains more weight than it should highlighted segment \textbf{C} gains more weight than it should
have. In the left graph segments \textbf{A} and \textbf{C} appear have. In the left graph segments \textbf{A} and \textbf{C} appear
@ -85,21 +85,13 @@ more examples on \url{https://en.wikipedia.org/wiki/Misleading_graph}.
\end{figure} \end{figure}
\begin{figure}[p] \begin{figure}[p]
\begin{minipage}[t]{0.3\textwidth} \includegraphics[width=0.9\textwidth]{plot_scaling.pdf}
\includegraphics[width=0.9\textwidth]{line_graph1} \titlecaption{Choosing the figure format and scaling of the axes
\end{minipage} influences the perceived strength of a correlation.}{All subplots
\begin{minipage}[t]{0.3\textwidth} show the same data. By choosing a certain figure size we can
\includegraphics[width=0.9\textwidth]{line_graph1_3} pronounce or reduce the perceived strength of the correlation
\end{minipage} in the data. Technically all three plots are correct.
\begin{minipage}[t]{0.3\textwidth} }\label{misleadingscalingfig}
\includegraphics[width=0.9\textwidth]{line_graph1_4}
\end{minipage}
\titlecaption{Chosing the figure format influences the erceived
strength of a correlation.}{All three subplots show the same data.
By choosing a certain figure size we can pronounce or to reduce
the perceived strength of the correlation in th data. Techincally
all three plots are correct.
\url{https://en.wikipedia.org/wiki/Misleading_graph}}\label{misleadingscalingfig}
\end{figure} \end{figure}
\begin{figure}[p] \begin{figure}[p]
@ -116,8 +108,8 @@ more examples on \url{https://en.wikipedia.org/wiki/Misleading_graph}.
symbols have been used to illustrate the measurements made in two symbols have been used to illustrate the measurements made in two
categories. The measured value for category \textbf{B} is actually categories. The measured value for category \textbf{B} is actually
three times the measured value for category \textbf{A}. In the three times the measured value for category \textbf{A}. In the
left graph the symbol for catergory \textbf{B} has been scaled to left graph the symbol for category \textbf{B} has been scaled to
triple heigth while maintaining the porpotions. This appears jusst triple height while maintaining the proportions. This appears just
fair and correct but leads to the effect that the covered surface fair and correct but leads to the effect that the covered surface
is not increased to the 3-fold but the 9-fold (center plot). The is not increased to the 3-fold but the 9-fold (center plot). The
plot on the right shows how it could have been done correctly. plot on the right shows how it could have been done correctly.
@ -217,15 +209,15 @@ number of datasets.
\subsection{Simple plotting} \subsection{Simple plotting}
Creating a simple line-plot is rather easy. Assuming there exists a Creating a simple line-plot is rather easy. Assuming there exists a
varaible \varcode{y} in the \codeterm{Workspace} that contains the variable \varcode{y} in the \codeterm{Workspace} that contains the
measurement data it is enough to call \code[plot()]{plot(y)}. At the measurement data it is enough to call \code[plot()]{plot(y)}. At the
first call of this function a new window will be opened and the data first call of this function a new window will be opened and the data
will be plotted with as a line plot. If you repeatedly call this will be plotted with as a line plot. If you repeatedly call this
function the current plot will be replaced unless the the function the current plot will be replaced unless the \code[hold]{hold
\code[hold]{hold on} command was issued before. If it was, the current on} command was issued before. If it was, the current plot is held
plot is held and a second line will be added to it. Calling and a second line will be added to it. Calling \code[hold]{hold off}
\code[hold]{hold off} will release the plot and any subsequent will release the plot and any subsequent plotting will replace the
plotting will replace the previous plot. previous plot.
In our previous call to \varcode{plot} we have provided just a single In our previous call to \varcode{plot} we have provided just a single
variable containing the y-values of the plot. The x-axis will be variable containing the y-values of the plot. The x-axis will be
@ -239,8 +231,8 @@ plotted as a line plot with a solid blue line of the with 1pt. A
second plot that is added to the figure will be plotted in red using second plot that is added to the figure will be plotted in red using
the same standard settings. The order of the used colors depends on the same standard settings. The order of the used colors depends on
the \enterm{colormap} settings which can be adjusted to personal taste the \enterm{colormap} settings which can be adjusted to personal taste
or need. Table\,\ref{plotlinestyles} shows some predefined values or need. Table\,\ref{plotlinestyles} shows some predefined values that
that can be chosen for the line style, the marker, or the color. For can be chosen for the line style, the marker, or the color. For
additional options consult the help. additional options consult the help.
\begin{table}[tp] \begin{table}[tp]
@ -269,12 +261,12 @@ additional options consult the help.
\subsection{Changing properties of a line plot} \subsection{Changing properties of a line plot}
Die properties of line plots can be changed by passing more arguments The properties of line plots can be changed by passing more arguments
to the \varcode{plot} function. The command show in to the \varcode{plot} function. The command shown in
listing\,\ref{settinglineprops} creates line plot using the dotted listing\,\ref{settinglineprops} creates a line plot using the dotted
line style, setting the line width to 1.5pt, a red line color is line style, sets the line width to 1.5pt, a red line color is
chosen, and star marker symbols will be used. Finally the name of the chosen, and star marker symbols is used. Finally, the name of the
curve is set to 'plot 1' which will be displayed in a legend, if curve is set to \emph{plot 1} which will be displayed in a legend, if
chosen. chosen.
\begin{lstlisting}[label=settinglineprops, caption={Setting line properties when calling \varcode{plot}.}] \begin{lstlisting}[label=settinglineprops, caption={Setting line properties when calling \varcode{plot}.}]
@ -285,7 +277,7 @@ chosen.
\begin{important}[Choosing the right color.] \begin{important}[Choosing the right color.]
Choosing the perfect color goes a little bit beyond personal Choosing the perfect color goes a little bit beyond personal
taste. When creating a colored plot you may want to consider the taste. When creating a colored plot you may want to consider the
following: following points:
\begin{itemize} \begin{itemize}
\item A substantial amount (about 9\%) of the male population can \item A substantial amount (about 9\%) of the male population can
not distinguish between red and green. not distinguish between red and green.
@ -301,13 +293,13 @@ The first thing a data plot needs are axis labels with a correct
unit. By calling the functions \code[xlabel]{xlabel('Time [ms]')} and unit. By calling the functions \code[xlabel]{xlabel('Time [ms]')} and
\code[ylabel]{ylabel{'Voltage [mV]'}} these can be set. By default the \code[ylabel]{ylabel{'Voltage [mV]'}} these can be set. By default the
axes will be scaled to show the whole data range. The extremes will be axes will be scaled to show the whole data range. The extremes will be
selected as the closest integer for small values of the next full selected as the closest integer for small values or the next full
multiple of tens, hundreds, thousands, etc. depending on the maximum multiple of tens, hundreds, thousands, etc.\ depending on the maximum
value. If these defaults do not match our needs the limits of the axes value. If these defaults do not match our needs, the limits of the
can be explicitly set with the functions \code[xlim()]{xlim()} and axes can be explicitly set with the functions \code[xlim()]{xlim()}
\code[ylim()]{ylim()} functions. To do this, the functions expect a and \code[ylim()]{ylim()}. To do this, the functions expect a single
single argument that is a vector containing the minimum and maximum argument, that is a vector containing the minimum and maximum
value. Table\,\ref{plotaxisprops} list some of the commonly adjusted value. Table\,\ref{plotaxisprops} lists some of the commonly adjusted
properties of an axis. These properties can be set using the properties of an axis. These properties can be set using the
\code[set()]{set()} function. The \code{set} function expects as a \code[set()]{set()} function. The \code{set} function expects as a
first argument a \enterm{handle} of the affected axis. An axis handle first argument a \enterm{handle} of the affected axis. An axis handle
@ -315,8 +307,9 @@ of the current plot is returned by the \code[gca]{gca} function (gca
stands for ``get current axis''). The following arguments passed to stands for ``get current axis''). The following arguments passed to
\code{set} are pairs of the property name and the desired value. It is \code{set} are pairs of the property name and the desired value. It is
possible to set any number of properties using a single call to possible to set any number of properties using a single call to
\code{set}. See listing\,\ref{niceplotlisting} (lines 20 and 21) for an \code{set}. See listing\,\ref{niceplotlisting} (lines 20 and 21) for
example. an example (these commands could be joined into a single call to
\code{set} but have been split for better readability).
\begin{table}[tp] \begin{table}[tp]
\titlecaption{Incomplete list of axis properties.}{For a complete \titlecaption{Incomplete list of axis properties.}{For a complete
@ -325,18 +318,18 @@ example.
value of a property it will be listed first.}\label{plotaxisprops} value of a property it will be listed first.}\label{plotaxisprops}
\begin{tabular*}{1\textwidth}{lp{5.8cm}p{5.5cm}} \hline \begin{tabular*}{1\textwidth}{lp{5.8cm}p{5.5cm}} \hline
\textbf{property} & \textbf{Description} & \textbf{options} \erh \textbf{property} & \textbf{Description} & \textbf{options} \erh
\\ \hline \code{Box} & Defines whether the axes are drawn an all \\ \hline \code{Box} & Defines whether the axes are drawn on all
sides. & $\{'on'|'off'\}$ \erb\\ sides. & $\{'on'|'off'\}$ \erb\\
\code{Color} & Background color of the drawing area, not the whole figure. & Any RGB or CMYK \code{Color} & Background color of the drawing area, not the whole figure. & Any RGB or CMYK
values. \\ values. \\
\code{FontName} & Name of the font used for labeling. & Installed fonts. \\ \code{FontName} & Name of the font used for labeling. & Installed fonts. \\
\code{FontSize} & Fontsize used for labels. & any scalar value.\\ \code{FontSize} & Size of the font used for labels. & Any scalar value.\\
\code{FontUnit} & Unit in which the font size is given. & $\{'points' | 'centimeters' | 'inches', \code{FontUnit} & Unit in which the font size is given. & $\{'points' | 'centimeters' | 'inches',
...\}$\\ \code{FontWeight} & Bold or normal font. & $\{'normal' | 'bold'\}$\\ ...\}$\\ \code{FontWeight} & Bold or normal font. & $\{'normal' | 'bold'\}$\\
\code{TickDir} & Direction of the axis ticks. & $\{'in' | 'out'\}$\\ \code{TickDir} & Direction of the axis ticks. & $\{'in' | 'out'\}$\\
\code{TickLength} & Length of the ticks. & scalar value\\ \code{TickLength} & Length of the ticks. & A scalar value\\
\code{X-, Y-, ZDir} & Direction of axis scaling. Zero bottom/left, or not? & $\{'normal' | 'reversed'\}$\\ \code{X-, Y-, ZDir} & Direction of axis scaling. Zero bottom/left, or not? & $\{'normal' | 'reversed'\}$\\
\code{X-, Y-, ZGrid} & Defines whether grid line for the respective axes should be plotted? & \code{X-, Y-, ZGrid} & Defines whether grid lines for the respective axes should be plotted? &
$\{'off'|'on'\}$ \\ $\{'off'|'on'\}$ \\
\code{X-, Y-, ZScale} & Linear of logarithmic scaling? & $\{'linear' | 'log'\}$\\ \code{X-, Y-, ZScale} & Linear of logarithmic scaling? & $\{'linear' | 'log'\}$\\
\code{X-, Y-, ZTick} & Position of the tick marks. & Vector of positions.\\ \code{X-, Y-, ZTick} & Position of the tick marks. & Vector of positions.\\
@ -345,32 +338,34 @@ example.
\end{table} \end{table}
\subsection{Changing the figure properties} \subsection{Changing figure properties}
\begin{table}[tp] \begin{table}[tp]
\titlecaption{Incomple list of available figure properties.}{For a complete reference consult the \matlab{} help or select the property editor while having the figuree background selected \titlecaption{Incomplete list of available figure properties.}{For a
complete reference consult the \matlab{} help or select the
property editor while having the figure background selected
(\figref{ploteditorfig}).}\label{plotfigureprops} (\figref{ploteditorfig}).}\label{plotfigureprops}
\begin{tabular*}{1\textwidth}{lp{6.6cm}p{5.7cm}} \hline \begin{tabular*}{1\textwidth}{lp{6.6cm}p{5.7cm}} \hline
\textbf{property} & \textbf{description} & \textbf{options} \textbf{property} & \textbf{description} & \textbf{options}
\erh \\ \erh \\
\hline \code{Color} & Background color of the figure, not the drawing area. & Any RGB, CMYK values. \erb \hline \code{Color} & Background color of the figure, not the drawing area. & Any RGB, CMYK values. \erb
\\ \code{PaperPosition} & Position of the axes on the paper. & 4-element vector containing the positions of the botom-left and top-right corners. \\ \\ \code{PaperPosition} & Position of the axes on the paper. & 4-element vector containing the positions of the bottom-left and top-right corners. \\
\code{PaperSize} & Size of the paper. & 2-element vector defining width and height.\\ \code{PaperSize} & Size of the paper. & 2-element vector defining width and height.\\
\code{PaperUnits} & Unit in which size and postition are given. & $\{'inches' | 'centimeters' | \code{PaperUnits} & Unit in which size and position are given. & $\{'inches' | 'centimeters' |
'normalized' | 'points'\}$\\ 'normalized' | 'points'\}$\\
\code{Visible} & Defines whether the plot should actually be drawn on screen. Useful when plots should not be displayed but directly saved to file. & $\{'on' | 'off'\}$\\ \hline \code{Visible} & Defines whether the plot should actually be drawn on screen. Useful when plots should not be displayed but directly saved to file. & $\{'on' | 'off'\}$\\ \hline
\end{tabular*} \end{tabular*}
\end{table} \end{table}
Like axes also the whole figure has several properties that can be Like axes, also figure has several properties that can be adjusted to
adjusted to the current needs. Most notably the paper (figure) size the current needs. Most notably the paper (figure) size and the
and the placement of the axes on the placement of the axes on the paper. Table\,\ref{plotfigureprops} lists
paper. Table\,\ref{plotfigureprops} lists commonly used ones. For a commonly used properties. For a complete reference check the help. To
complete reference check the help. To change the properties, we again change the properties, we again use the \code{set()} function. The
use the \code{set()} function. The first argument is now a handle to first argument is now a handle to the current figure, not the current
the current figure, not the current axis as before. Analogously to the axis as before. Analogously to the \code{gca} command there is a
\code{gca} command there is a \code{gcf} (``get current figure'') \code{gcf} (``get current figure'') command with which the handle can
command with which the handle can be retrieved. be retrieved.
The script shown in the listing\,\ref{niceplotlisting} exemplifies The script shown in the listing\,\ref{niceplotlisting} exemplifies
several features of the plotting system and automatically generates several features of the plotting system and automatically generates
@ -378,10 +373,11 @@ and saves figure\,\ref{spikedetectionfig}. With any execution of this
script exactly the same plot will be created. If we decided to plot a script exactly the same plot will be created. If we decided to plot a
different recording, the format will stay exactly the same, just the different recording, the format will stay exactly the same, just the
data changes. Of special interest are the lines 22 and 23 which set data changes. Of special interest are the lines 22 and 23 which set
the size of the figure and line 26 which saves the figure in the 'pdf' the size of the figure and positions the axes on the paper. Line 26
format to file. When calling the function \code{saveas()} the first finally saves the figure in the 'pdf' format to file. When calling the
argument is the current figure handle a, the second the file name, and function \code{saveas()} the first argument is the current figure
the last one defines the output format (box\,\ref{graphicsformatbox}). handle, the second the file name, and the last one defines the
output format (box\,\ref{graphicsformatbox}).
\begin{figure}[t] \begin{figure}[t]
\includegraphics{spike_detection} \titlecaption{Automatically \includegraphics{spike_detection} \titlecaption{Automatically
@ -395,11 +391,11 @@ the last one defines the output format (box\,\ref{graphicsformatbox}).
\item \enterm{Bitmaps} \item \enterm{Bitmaps}
\item \enterm{Vector graphics} \item \enterm{Vector graphics}
\end{enumerate} \end{enumerate}
When using bitmaps a color is given for each pixel of the stored When using bitmaps a color value is given for each pixel of the
figure. Bitmaps do have a fixed resolution (e.g.\,300\,dpi --- dots stored figure. Bitmaps do have a fixed resolution (e.g.\,300\,dpi
per inch), they are very useful for photographs. In the contrary --- dots per inch), they are very useful for photographs. In the
vector graphics store descriptions of the graphic in terms of so contrary, vector graphics store descriptions of the graphic in terms
called primitives (lines, circles, polygons, etc.). The main of so called primitives (lines, circles, polygons, etc.). The main
advantage of a vector graphic is that it can be scaled without a advantage of a vector graphic is that it can be scaled without a
loss of quality. loss of quality.
@ -448,12 +444,56 @@ various examples and the respective code on their website
For some types of plots we present examples in the following sections. For some types of plots we present examples in the following sections.
\subsection{Line plot, subplots} \subsection{Scatter}
For displaying events or pairs of x-y coordinates the standard line
plot is not optimal. Rather, we use \code[scatter()]{scatter} for this
purpose. For example, we have a number of measurements of a system's
response to a certain stimulus intensity. There is no dependency
between the data points, drawing them with a line-plot would be
nonsensical (figure\,\ref{scatterplotfig}\,A). In contrast to
\codeterm{}{plot} we need to provide x- and y-coordinates in order to
draw the data. In the example we also provide further arguments to set
the size, color of the dots and specify that they are filled
(listing\,\ref{scatterlisting1}).
\lstinputlisting[caption={Creating a scatter plot with red filled dots.},
label=scatterlisting1, firstline=9, lastline=9]{scatterplot.m}
We could have used plot for this purpose and set the marker to
something and the line-style to ``none'' to draw an equivalent
plot. Scatter, however offers some more advanced features that allows
to add two more dimensions to the plot
(figure\,\ref{scatterplotfig}\,B,\,C). For each dot one can define an
individual size and color. In this example the size argument is simply
a vector of the same size as the data that contains number from 1 to
the length of 'x' (line 1 in listing\,\ref{scatterlisting2}). To
manipulate the color we need to specify a length(x)-by-3 matrix. For
each dot we provide an individual color (i.e. the RGB triplet in each
row of the color matrix, lines 2-4 in listing\,\ref{scatterlisting2})
\lstinputlisting[caption={Creating a scatter plot with size and color
variations. The RGB triplets define the respective color intensity
in a range 0:1. Here, we modify only the red color channel.},
label=scatterlisting2, linerange={15-15, 21-23}]{scatterplot.m}
\begin{figure}[t]
\includegraphics{scatterplot}
\titlecaption{Scatterplots.}{Scatterplots are used to draw
datapoints where there is no direct dependency between the
individual measurements (like time). Scatter offers several
advantages over the standard plot command. One can vary the size
and/or the color of each dot.}\label{scatterplotfig}
\end{figure}
\subsection{Subplots}
A very common scenario is to combine several plots in the same A very common scenario is to combine several plots in the same
figure. To do this we create so-called subplots figure. To do this we create so-called subplots
figures\,\ref{regularsubplotsfig},\,\ref{irregularsubplotsfig}. The figures\,\ref{regularsubplotsfig},\,\ref{irregularsubplotsfig}. The
\code[subplot()]{subplot()} command allows to place multiple axes onto \code[subplot()]{subplot()} command allows to place multiple axes onto
a single paper. Generally, \varcode{subplot} expects three argument a single sheet of paper. Generally, \varcode{subplot} expects three argument
defining the number of rows, column, and the currently active defining the number of rows, column, and the currently active
plot. The currently active plot number starts with 1 and goes up to plot. The currently active plot number starts with 1 and goes up to
$rows \cdot columns$ (numbers in the subplots in $rows \cdot columns$ (numbers in the subplots in
@ -472,18 +512,18 @@ figures\,\ref{regularsubplotsfig}, \ref{irregularsubplotsfig}).
grid \figref{regularsubplotsfig}.}, label=regularsubplotlisting, grid \figref{regularsubplotsfig}.}, label=regularsubplotlisting,
basicstyle=\ttfamily\scriptsize]{regular_subplot.m} basicstyle=\ttfamily\scriptsize]{regular_subplot.m}
By default, all suplots have the same size, if something else is By default, all subplots have the same size, if something else is
desired, e.g., one suplot should span a whole row, while two others desired, e.g.\ one subplot should span a whole row, while two others
are smaller and placed side by side in the same row, the third are smaller and should be placed side by side in the same row, the
argument of \varcode{subplot} can be a vector or numbers that should third argument of \varcode{subplot} can be a vector or numbers that
be joined. These have, of course, be adjacent numbers should be joined. These have, of course, to be adjacent numbers
(\figref{irregularsubplotsfig}, (\figref{irregularsubplotsfig},
listing\,\ref{irregularsubplotslisting}). listing\,\ref{irregularsubplotslisting}).
\begin{figure}[ht] \begin{figure}[ht]
\includegraphics[width=0.5\linewidth]{irregular_subplot} \includegraphics[width=0.5\linewidth]{irregular_subplot}
\titlecaption{Subplots of different size.}{The third argument of \titlecaption{Subplots of different size.}{The third argument of
\varcode{subpot} may be a vector of cells that should be joined \varcode{subplot} may be a vector of cells that should be joined
into the same subplot. See into the same subplot. See
listing\,\ref{irregularsubplotslisting}}\label{irregularsubplotsfig} listing\,\ref{irregularsubplotslisting}}\label{irregularsubplotsfig}
\end{figure} \end{figure}
@ -500,6 +540,98 @@ used cells of the grid by passing a vector as the third argument to
label=irregularsubplotslisting, label=irregularsubplotslisting,
basicstyle=\ttfamily\scriptsize]{irregular_subplot.m} basicstyle=\ttfamily\scriptsize]{irregular_subplot.m}
\subsection{Show estimation errors}
The repeated measurements of a quantity almost always results in
varying results. Neuronal activity, for example is notoriously
noisy. The responses of a neuron to repeated stimulation with the same
stimulus may share common features but are different each time. This
is the reason we calculate measures that describe the variability of
such as the standard deviation and thus need a way to
illustrate it in plots of scientific data. Providing an estimate of
the error gives the reader the chance of assessing the reliability of
the data and get a feeling of possible significance of a
difference in the average values.
\matlab{} offers several ways to plot the average and the error. We
will introduce two possible ways.
\begin{itemize}
\item The \code[errorbar()]{errorbar} function (figure\,\ref{errorbarplot} A, B).
\item Using the \code[fill()]{fill} function to draw an area showing
the spread of the data (figure\,\ref{errorbarplot} C).
\end{itemize}
\subsubsection{Errorbar}
Using the \code[errorbar()]{errorbar} function is rather straight
forward. In its easiest form, it expects three arguments being the x-
and y-values plus the error (line 5 in listing \ref{errorbarlisting},
note that we provide additional optional arguments to set the
marker). This form is obviously only suited for symmetric
distributions. In case the values are symmetrically distributed, a
separate error for positive and negative deflections from the mean are
more apt. Accordingly, four arguments are needed (line 12 in listing
\ref{errorbarlisting}). The first two arguments are the same, the next
to represent the positive and negative deflections.
By default the \code{errorbar} function does not draw a marker. In the
examples shown here we provide extra arguments to define that a circle
is used for that purpose. The line connecting the average values can
be removed by passing additional arguments. The properties of the
errorbars themselves (linestyle, linewidth, capsize, etc.) can be
changed by taking the return argument of \code{errorbar} and changing
its properties. See the \matlab{} help for more information.
\begin{figure}[ht]
\includegraphics[width=0.9\linewidth]{errorbars}
\titlecaption{Adding error bars to a line plot}{\textbf{A}
symmetrical error around the mean (e.g.\ using the standard
deviation). \textbf{B} Errorbars of an asymmetrical distribution
of the data (note: the average value is now the median and the
errors are the lower and upper quartiles). \textbf{C} A shaded
area is used to illustrate the spread of the data. See
listing\,\ref{errorbarlisting}}\label{errorbarplot}
\end{figure}
\lstinputlisting[caption={Illustrating estimation errors. Script that
creates \figref{errorbarplot}.},
label=errorbarlisting, firstline=13, lastline=29,
basicstyle=\ttfamily\scriptsize]{errorbarplot.m}
\subsubsection{Fill}
For a few years now it has become fancy to illustrate the error not
using errorbars but by drawing a shaded area around the mean. Beside
their fancyness there is also a real argument in favor of using error
areas instead of errorbars: In case you have a lot of data points with
respective errorbars such that they would merge in the figure it is
cleaner and probably easier to read and handle if one uses an error
area instead. To achieve an illustration as shown in
figure\,\ref{errorbarplot} C, we use the \code{fill} command in
combination with a standard line plot. The original purpose of
\code{fill} is to draw a filled polygon. We hence have to provide it
with the vertex points of the polygon. For each x-value we now have
two y-values (average minus error and average plus error). Further, we
want the vertices to be connected in a defined order. One can achieve
this by going back and forth on the x-axis; we append a reversed
version of the x-values to the original x-values using the \code{cat}
and inversion is done using the \code{fliplr} command (line 3 in
listing \ref{errorbarlisting2}; Depending on the layout of your data
you may need concatenate along a different dimension of the data and
use \code{flipud} instead). The y-coordinates of the polygon vertices
are concatenated in a similar way (line 4). In the example shown here
we accept the polygon object that is returned by fill (variable p) and
use it to change a few properties of the polygon. The \emph{FaceAlpha}
property defines the transparency (or rather the opaqueness) of the
area. The provided alpha value is a number between 0 and 1 with zero
leading to invisibility and a value of one to complete
opaqueness. Finally, we use the normal plot command to draw a line
connecting the average values.
\lstinputlisting[caption={Illustrating estimation errors. Script that
creates \figref{errorbarplot}.}, label=errorbarlisting2,
firstline=30,
basicstyle=\ttfamily\scriptsize]{errorbarplot.m}
\subsection{Annotations, text} \subsection{Annotations, text}
Sometimes want to highlight certain parts of a plot or simply add an Sometimes want to highlight certain parts of a plot or simply add an
@ -510,7 +642,7 @@ the plot. While \varcode{text} simply prints out the given text string
at the defined position (for example line in at the defined position (for example line in
listing\,\ref{regularsubplotlisting}) the \varcode{annotation} listing\,\ref{regularsubplotlisting}) the \varcode{annotation}
function allows to add some more advanced highlights like arrows, function allows to add some more advanced highlights like arrows,
lines, elipses, or rectangles. Figure\,\ref{annotationsplot} shows lines, ellipses, or rectangles. Figure\,\ref{annotationsplot} shows
some examples, the respective code can be found in some examples, the respective code can be found in
listing\,\ref{annotationsplotlisting}. For more options consult the listing\,\ref{annotationsplotlisting}. For more options consult the
documentation. documentation.
@ -528,19 +660,63 @@ documentation.
\begin{important}[Positions in data or figure coordinates.] \begin{important}[Positions in data or figure coordinates.]
A very confusing pitfall are the different coordinate systems used A very confusing pitfall are the different coordinate systems used
by \varcode{text} and \varcode{annotation}. While text expects the by \varcode{text} and \varcode{annotation}. While \varcode{text}
positions to be in data coordinates, i.e.\,in the limits of the x- expects the positions to be in data coordinates, i.e.\,in the limits
and y-axis, \varcode{annotation} requires the positions to be given of the x- and y-axis, \varcode{annotation} requires the positions to
in normalized figure coordinates. Normalized means that the width be given in normalized figure coordinates. Normalized means that the
and height of the figure are expressed by numbers in the range 0 to width and height of the figure are expressed by numbers in the range
1. The bottom/left corner then has the coordinates $(0,0)$ and the 0 to 1. The bottom/left corner then has the coordinates $(0,0)$ and
top/right corner the $(1,1)$. the top/right corner the $(1,1)$.
Why different coordinate systems? Using data coordinates is Why different coordinate systems? Using data coordinates is
convenient for annotations within a plot, but what about an arrow convenient for annotations within a plot, but what about an arrow
that should be drawn between two subplots? that should be drawn between two subplots?
\end{important} \end{important}
\subsection{Animations and movies}
A picture is worth a thousand words and sometimes creating animations
or movies is worth many pictures. They can help understanding complex
or time-dependent developments and may add some variety to a
presentation. The following example shows how a movie can be created
and saved to file. A similar mechanism is available to produce
animations that are supposed to be shown within \matlab{} but for this
we point to the documentation of the \code[movie()]{movie()}
command. The underlying principle is the same, however. The code shown
in listing\,\ref{animationlisting} creates an animation of a
Lissajous figure. The basic steps are:
\begin{enumerate}
\item Create a figure and set some basic properties (lines 7 --- 10).
\item Create a \code[VideoWriter()]{VideoWriter} object that, in this
example, takes the filename and the profile, the mpg-4 compression
profile, as arguments (line 12). For more options see the
documentation.
\item We can set the desired framerate and the quality of the video
(lines 13, 14). Quality is a value between 0 and 100, where 100 is
the best quality but leads to the largest files. The framerate
defines how quickly the individual frames will switched. In our
example, we create 500 frames and the video framerate is
25\,Hz. That is, the movie will have a duration of
$500/25 = 20$\,seconds.
\item Open the destination file (line 16). Opening means that the file
is created and opened for writing. This also implies that is has to
be closed after the whole process (line 31).
\item For each frame of the video, we plot the appropriate data (we
use \code[scatter]{scatter} for this purpose, line 20) and ``grab''
the frame (line 28). Grabbing is similar to making a screenshot of
the figure. The \code{drawnow}{drawnow} command (line 27) is used to
stop the excution of the for loop until the drawing process is
finished.
\item Write the frame to file (line 29).
\item Finally, close the file (line 31).
\end{enumerate}
\lstinputlisting[caption={Making animations and saving them as a
movie.}, label=animationlisting, firstline=3, lastline=33,
basicstyle=\ttfamily\scriptsize]{movie_example.m}
\section{Summary} \section{Summary}
A good plot of scientific data displays the data completely and A good plot of scientific data displays the data completely and

View File

@ -1,14 +1,16 @@
\documentclass[12pt,a4paper]{article} \documentclass[12pt,a4paper,landscape]{article}
\usepackage[ngerman]{babel}
\usepackage{pslatex} \usepackage{pslatex}
\usepackage{graphics}
%%%%% page style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% page style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[left=10mm,right=10mm,top=10mm,bottom=10mm,headsep=0ex,headheight=0ex,footskip=0ex]{geometry} \usepackage[left=10mm,right=10mm,top=10mm,bottom=10mm,headsep=0ex,headheight=0ex,footskip=0ex]{geometry}
\pagestyle{empty} \pagestyle{empty}
\newcommand{\rot}[1]{\rotatebox{90}{#1}\,\,}
\newcounter{studentnum} \newcounter{studentnum}
\newcommand{\num}{\rule{0pt}{5.8ex}{\stepcounter{studentnum}\small \arabic{studentnum}}} \newcommand{\num}{\rule{0pt}{7.0ex}{\stepcounter{studentnum}\small \arabic{studentnum}}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -17,28 +19,37 @@
\sffamily \sffamily
\section*{Scientific computing WS17/18} \section*{Scientific computing WS17/18}
\begin{tabular}{|p{0.15\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|p{0.07\textwidth}|} \noindent
\begin{tabular}{|p{0.16\textwidth}|p{0.1\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|p{0.024\textwidth}|l|l|}
\hline
Name & Project & \multicolumn{5}{l|}{Project} & \multicolumn{3}{l|}{Figures} & \multicolumn{8}{l|}{Code} & Sum & Grade \rule{0.pt}{3ex} \\
& & \rot{Understanding} & \rot{Presentation}\rot{Structure, didactics} & \rot{Completed} & \rot{Bonus:}\rot{Context} & \rot{Bonus:}\rot{Own ideas} & \rot{Readability}\rot{font size, etc.} & \rot{Labels}\rot{and units} & \rot{Design} & \rot{Runs} & \rot{Names of}\rot{vars and funcs} & \rot{Style: white space}\rot{Spaghetti, structure} & \rot{Functions: used,}\rot{purpose, standalone} & \rot{Docu script} & \rot{Docu functions} & \rot{Figures saved} & \rot{Bonus:}\rot{Interesting code} & & \\
& & 0--3 & 0--2 & 0--2 & 0, 1 & 0--2 & 0--2 & 0--2 & 0--2 & 0--2 & 0--2 & 0--2 & 0--3 & 0--2 & 0--2 & 0, 2 & 0--2 & 28 & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & & & & & & & & & & & \\ \hline
\end{tabular}
\noindent
\begin{tabular}{|p{0.16\textwidth}|p{0.1\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|p{0.023\textwidth}|l|l|}
\hline \hline
Name & \multicolumn{5}{l|}{Code} & \multicolumn{3}{l|}{Functions} & Figures \\ Name & Project & \multicolumn{5}{l|}{Project} & \multicolumn{3}{l|}{Figures} & \multicolumn{8}{l|}{Code} & Sum & Grade \rule{0.pt}{3ex} \\
& runs & docu & variable function script names & style & extras & NOT \newline used as scripts & docu & sep. \newline algo./ plot & saved \\ \hline & & \rot{Understanding} & \rot{Presentation}\rot{Structure, didactics} & \rot{Completed} & \rot{Bonus:}\rot{Context} & \rot{Bonus:}\rot{Own ideas} & \rot{Readability}\rot{font size, etc.} & \rot{Labels}\rot{and units} & \rot{Design} & \rot{Runs} & \rot{Names of}\rot{vars and funcs} & \rot{Style: white space}\rot{Spaghetti, structure} & \rot{Functions: used,}\rot{purpose, standalone} & \rot{Docu script} & \rot{Docu functions} & \rot{Figures saved} & \rot{Bonus:}\rot{Interesting code} & & \\
\num & & & & & & & & & \\ \hline & & 0--3 & 0--2 & 0--2 & 0, 1 & 0--2 & 0--2 & 0--2 & 0--2 & 0--2 & 0--2 & 0--2 & 0--3 & 0--2 & 0--2 & 0, 2 & 0--2 & 28 & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline \num & & & & & & & & & & & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\num & & & & & & & & & \\ \hline
\end{tabular} \end{tabular}
\end{document} \end{document}

26
projects/gradetable.py Normal file
View File

@ -0,0 +1,26 @@
import os
import numpy as np
import matplotlib.pylab as plt
lecture = 'Models of Neural Systems, WS 16/17'
exam = 1
pmax = 33 # maximum available points
p100 = 28 # points for 100%
# grades:
gradestable = [ [ 0.9, 1.0 ], [ 0.84, 1.3 ], [ 0.80, 1.7 ], [ 0.76, 2.0 ], [ 0.72, 2.3 ],
[ 0.68, 2.7 ], [ 0.64, 3.0 ], [ 0.60, 3.3 ], [ 0.56, 3.7 ], [ 0.50, 4.0 ] ]
df = open('notentabelle.dat', 'w')
df.write('# Notentabelle\n')
print '# Notentabelle'
df.write('\n')
df.write('#Key\n')
s = '# Note\tProzent\tPunkte'
df.write(s+'\n')
print s
for f,g in gradestable :
s = ' \t%3.1f\t%5.0f\t%5.1f' % (g, 100.0*f, p100*f)
df.write(s+'\n')
print s
df.close()

View File

@ -44,8 +44,9 @@ def gradient(p, t, y, scale=None):
def gradient_descent(t, y): def gradient_descent(t, y):
count = 80 count = 80
b_0 = np.mean(y) b_0 = np.mean(y)
omega_0 = 650 omega_0 = 870
params = [b_0, omega_0, np.min(y) + np.max(y), np.pi/2, (np.min(y) + np.max(y))/2, np.pi/3, (np.min(y) + np.max(y))/4, np.pi/4, (np.min(y) + np.max(y))/5, np.pi] amplitude = np.max(y) - np.min(y)
params = [b_0, omega_0, amplitude, np.pi/2, amplitude/2, np.pi/3, amplitude/4, np.pi/4, amplitude/5, np.pi]
scale = np.ones(len(params)) scale = np.ones(len(params))
scale[1] = 1000 scale[1] = 1000
eps = 0.01 eps = 0.01

View File

@ -32,8 +32,7 @@ locking, respectively.
i.e. the fish's field The data is sampled with 20\,kHz and the spike i.e. the fish's field The data is sampled with 20\,kHz and the spike
times are given in seconds. times are given in seconds.
\begin{parts} \begin{parts}
\part Plot an average of the single EOD cylces of each fish \part Plot the average EOD waveform of each fish together with an respective PSTH.
together with an respective PSTH.
\part Implement a function that estimates the vector strength \part Implement a function that estimates the vector strength
between the \textit{eod} and the spikes. between the \textit{eod} and the spikes.
\part Create a polar plot that shows the timing of the spikes \part Create a polar plot that shows the timing of the spikes

View File

@ -13,8 +13,8 @@
%%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry} \usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry}
\pagestyle{headandfoot} \header{{\bfseries\large \"Ubung \pagestyle{headandfoot} \header{{\bfseries\large Exercise
}}{{\bfseries\large Zeitabh\"angige Feuerrate}}{{\bfseries\large 13. Dezember, 2016}} }}{{\bfseries\large Time-dependent firing rate}}{{\bfseries\large December, 12, 2017}}
\firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email: \firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email:
jan.grewe@uni-tuebingen.de} \runningfooter{}{\thepage}{} jan.grewe@uni-tuebingen.de} \runningfooter{}{\thepage}{}
@ -24,53 +24,54 @@
\renewcommand{\baselinestretch}{1.15} \renewcommand{\baselinestretch}{1.15}
\newcommand{\code}[1]{\texttt{#1}} \newcommand{\code}[1]{\texttt{#1}}
\renewcommand{\solutiontitle}{\noindent\textbf{L\"osung:}\par\noindent} \renewcommand{\solutiontitle}{\noindent\textbf{Solution}\par\noindent}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document} \begin{document}
\vspace*{-6.5ex} \vspace*{-6.5ex}
\begin{center} \begin{center}
\textbf{\Large Einf\"uhrung in die wissenschaftliche Datenverarbeitung}\\[1ex] \textbf{\Large Introduction to scientific computing.}\\[1ex]
{\large Jan Grewe, Jan Benda}\\[-3ex] {\large Jan Grewe, Jan Benda}\\[-3ex]
Abteilung Neuroethologie \hfill --- \hfill Institut f\"ur Neurobiologie \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\ Abteilung Neuroethologie \hfill --- \hfill Institut f\"ur Neurobiologie \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\
\end{center} \end{center}
\begin{questions} \begin{questions}
\question Stelle die zeitabh\"angige Feuerrate eines Neurons \question Plot the time-dependent firing rate of a neuron. Calculate
dar. Diese soll auf Basis der instantanen Feuerrate (des the firing rate from the instantaneous firing rate (based on the
Interspikeintervals) berechnet werden. Verwende dazu den Datensatz interspike interval). Use the \code{lifoustim.mat}. The dataset
\code{lifoustim.mat}. Dieser enth\"at drei Variablen: 1. die contains three variables. 1st the spike times in different trials,
Spikezeiten, 2. den Stimulus und 3. die zeitliche Aufl\"osung. Die 2nd the stimulus, and 3rd the temporal resolution. The total
Dauer eines Trials betr\"agt 30 Sekunden. duration of each trial amounts to 30 seconds.
\begin{parts} \begin{parts}
\part Schreibe eine Funktion, die einen Vektor mit Spikezeiten, \part{} Write a function that takes three arguments: the spike
die Dauer des Trials, und die zeitliche Aufl\"osung entgegennimmt times of a single trial, the trial duration and the temporal
und die Zeitachse sowie die Feuerrate zur\"uckgibt. resolution. The function should return the time values and the
\part Benutze diese Funktion in einem Skript und stellt die Feuerrate firing rate in $Hz$.
eines einzelnen Trials sowie den Mittelwert \"uber alle Trials \part{} Write a script that applies the above function to estimate
dar. the firing rate of each trial. Plot a single individual responses
\part Erweitere das Programm so, dass die Abbildung den Richtlinien and the average response as a function of time into the same plot.
des \textit{Journal of Neuroscience} entspricht \part{} Extend your program that it saves the figure in a format
(Schriftgr\"o{\ss}e, Abbildungsgr\"o{\ss}e). according to the rules given by the \textit{Journal of
\part Die Abbildung sollte als pdf gespeichert werden. Neuroscience}. This relates to the figure size and the
fontsizes.
\part{} Store the figure in pdf format.
\end{parts} \end{parts}
\question Wie zuvor nur unter Verwendung der Binning Methode. \question{} As before but use the binning method.
\question Entscheide dich f\"ur eine Varainte und erweitere das \question{} Extend your script that it also plots the interspike
entsprechende Skript, sodass auch die Interspikeintervallverteilung interval histogram and the distribution of spike counts into
und die Verteilung der Spikecounts graphisch dargestellt werden. Die separate figures. Save the figures to file using the pdf format.
entsprechenden Abbildungen sollten als pdf gespeichert werden.
\question Einige Trials sind anders als die \"Ubrigen. Benutze den \question{} Some trials are different from the others.
Rasterplot um sie zu finden. Speichere die generierten Abbildungen.
\begin{parts} \begin{parts}
\part Benutze den Rasterplot um sie zu finden. Worin unterscheiden sie sich von den anderen? \part{} Use the rasterplot to identify them. In which sense
\part Plotte die Verteilung der Spike counts. are they different from the others? Save the rasterplot in pdf
\part Filtere all die Trials heraus, deren Spikecount mehr als format.
$2\sigma$ vom Mittelwert abweicht. \part{} Identify those trial in which the total spike count
\part Plotte die Feuerrate vor und nach dem Filtern. deviates more than $2\sigma$ from the average.
\end{parts} \end{parts}
\end{questions} \end{questions}

View File

@ -13,8 +13,8 @@
%%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% text size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry} \usepackage[left=20mm,right=20mm,top=25mm,bottom=25mm]{geometry}
\pagestyle{headandfoot} \header{{\bfseries\large \"Ubung \pagestyle{headandfoot} \header{{\bfseries\large Exercise
}}{{\bfseries\large Korrelation Stimulus und Antwort}}{{\bfseries\large 20. Dezember, 2016}} }}{{\bfseries\large Correlation of stimulus and response}}{{\bfseries\large December 19, 2017}}
\firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email: \firstpagefooter{Dr. Jan Grewe}{Phone: 29 74588}{Email:
jan.grewe@uni-tuebingen.de} \runningfooter{}{\thepage}{} jan.grewe@uni-tuebingen.de} \runningfooter{}{\thepage}{}
@ -24,53 +24,60 @@
\renewcommand{\baselinestretch}{1.15} \renewcommand{\baselinestretch}{1.15}
\newcommand{\code}[1]{\texttt{#1}} \newcommand{\code}[1]{\texttt{#1}}
\renewcommand{\solutiontitle}{\noindent\textbf{L\"osung:}\par\noindent} \renewcommand{\solutiontitle}{\noindent\textbf{Solution:}\par\noindent}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document} \begin{document}
\vspace*{-6.5ex} \vspace*{-6.5ex}
\begin{center} \begin{center}
\textbf{\Large Einf\"uhrung in die wissenschaftliche Datenverarbeitung}\\[1ex] \textbf{\Large Introduction to scientific computing}\\[1ex]
{\large Jan Grewe, Jan Benda}\\[-3ex] {\large Jan Grewe, Jan Benda}\\[-3ex]
Abteilung Neuroethologie \hfill --- \hfill Institut f\"ur Neurobiologie \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\ Abteilung Neuroethologie \hfill --- \hfill Institut f\"ur Neurobiologie \hfill --- \hfill \includegraphics[width=0.28\textwidth]{UT_WBMW_Black_RGB} \\
\end{center} \end{center}
\begin{questions} \begin{questions}
\question Stellt die zeitabh\"angige Feuerrate eines Neurons \question Estimate the time-dependent firing rate of a neuron. Use
dar. Diese soll mit der Faltungsmethode bestimmt werden. Verwendet the ``convoluion'' method to do it. The dataset \code{lifoustim.mat}
den Datensatz \code{lifoustim.mat}. Dieser enth\"at drei Variablen: contains three variables. 1st the spike times in different trials,
1. die Spikezeiten, 2. den Stimulus und 3. die zeitliche 2nd the stimulus, and 3rd the temporal resolution. The total
Aufl\"osung. Die Dauer eines Trials betr\"agt 30 Sekunden. duration of each trial amounts to 30 seconds.
\begin{parts} \begin{parts}
\part Schreibt eine Funktion, die einen Vektor mit Spikezeiten, \part{} Write a function that estimates the firing rate with the
die Dauer des Trials, und die zeitliche Aufl\"osung entgegennimmt ``convolution'' method. This function should take four input
und die Zeitachse sowie die Feuerrate zur\"uckgibt. arguments: (i) a vector of spike times, (ii) the temporal
\part Benutzt diese Funktion in einem Skript und stellt die Feuerrate resolution of the recording, (iii) the duration of the
eines einzelnen Trials sowie den Mittelwert \"uber alle Trials trial, and (iv) the standard deviation of the applied Gaussian
dar. kernel. The function should return two variables: (i) the firing
\part Erweitert das Programm so, dass die Abbildung den Richtlinien rate, and (ii) a vector representing time.
des \textit{Journal of Neuroscience} entspricht \part{} Write a script that uses this function to estimate the
(Schriftgr\"o{\ss}e, Abbildungsgr\"o{\ss}e). firing rate of all trial. Plot the mean (across trials) firing
\part Die Abbildung sollte als pdf gespeichert werden. rate as a function of time. Use two different kernel standard
deviations (e.g. 20\,ms and 100\,ms).
\part{} Save the figure according the style defined by the
\emph{J. Neuroscience} (figure width 1, 1.5, or two columns, 8.5,
11.6, or 17.6\,cm, respectively; fontsize 10 pt). Save the figure
as pdf.
\end{parts} \end{parts}
\question In einer vorherigen \"Ubung wurde die Korrelation zwischen \question In a previous exercise you were asked to estimate the
einer Reihe von Messungen und einer entsprechenden Anzahl correlation between a set of independent variables and the
unabh\"angiger Variablen bestimmt (Kapitel 4.4 im Skript). Wir respective measurements (Chapter 6.4 in the script). We can use
k\"onnen diese Korrelation benutzen um den Zusammenhang zwischen this function to learn a few things about the relation between
Stimulus und Antwort zu bestimmen. stimulus and response.
\begin{parts} \begin{parts}
\part Ermittelt die zeitabh\"angige Feuerrate mit einer der drei \part{} Estimate the firing rate of the neuronal response using one
Methoden und korrelliert sie mit dem Stimulus. of the three methods. Use the same dataset as before.
\part Verschiebt nun den Stimulus relativ zur Antwort um $\pm$ \part{} Calculate the correlation of stimulus and response.
50\,ms in 1\,ms Schritten und berechnet f\"ur jede Verschiebung \part{} Calculate the correlation of stimulus and response
die Korrelation. while shifting the response relative to the stimulus in a range
\part Stellt die so berechnete Kreuzkorrelation graphisch dar $\pm$ 50\,ms (1\,ms steps).
(x-Achse die Verschiebung, y-Achse der Korrelationskoeffizient). \part{} Plot these correlations as a function of the temporal shift
\part Was ist die maximale Korrelation und bei welcher (often called lag).
Verschiebung kommt sie vor? \part{} What is the maximum correlation and at which lag does it occur?
\part Was k\"onnte uns die Breite des Korrelationspeaks sagen? \part{} What could this tell us about the neuronal response properties?
\end{parts} \end{parts}
\end{questions} \end{questions}