#!/usr/bin/env python
# coding: utf-8

# <h1>Einführung in NumpPy Teil 2<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Broadcasting" data-toc-modified-id="Broadcasting-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Broadcasting</a></span></li><li><span><a href="#Beispiel-zur-Verwendung-von-Index-Arrays." data-toc-modified-id="Beispiel-zur-Verwendung-von-Index-Arrays.-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Beispiel zur Verwendung von Index-Arrays.</a></span></li><li><span><a href="#Verwende-boolsche-Ausdrücke-bei-der-Definition-von-Matrizen" data-toc-modified-id="Verwende-boolsche-Ausdrücke-bei-der-Definition-von-Matrizen-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Verwende boolsche Ausdrücke bei der Definition von Matrizen</a></span></li><li><span><a href="#Achtung" data-toc-modified-id="Achtung-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Achtung</a></span></li><li><span><a href="#Universal-functions-(ufunc)" data-toc-modified-id="Universal-functions-(ufunc)-5"><span class="toc-item-num">5&nbsp;&nbsp;</span>Universal functions (ufunc)</a></span></li></ul></div>

# # Einführung in NumPy
# ## Broadcasting
# +, -, * , %, / &ast;&ast; wirken eintragsweise, __wobei die _singleton_ Dimension expandiert wird__.
# 
# _singleton_: fehlende Dimenson oder Dimension der Länge 1.

# In[ ]:


import numpy as np


# In[ ]:


A = np.array([[1, 2], [3, 4]])
v = np.array([-5, 7])
display(A, v) # das etwas übersichtlicher


# In[ ]:





# In[ ]:


# Das erste Element von v wird zu jeder zu jedem Element der ersten Spalte addiert
A + v


# In[ ]:


#' Das erste Element von v wird ...
A * v


# In[ ]:


A**v


# In[ ]:





# In[ ]:


# zu jedem Eintrag wird 1 addiert
A + 1


# In[ ]:


# jeder Eintrag wird durch 3 dividiert
A / 3 


# numpy macht hier einen sogenannten 'upcast', versucht also ganze Zahlen in Gleitkommazahlen (float) umzuwandeln und gibt als Ergebnis ein Array mit floats zurück.

# In[ ]:


# 3 wird durch jeden Eintrag dividiert
3 / A


# __Broadcastingregel__
# (aus https://numpy.org/doc/stable/user/basics.broadcasting.html)
# 
# When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimensions and works its way left. Two dimensions are compatible when
# 
# 1. they are equal, or
# 
# 2. one of them is 1
# 
# If these conditions are not met, a ValueError: operands could not be broadcast together exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the size that is not 1 along each axis of the inputs.
# 
# Arrays do not need to have the same number of dimensions. 

# In[ ]:


DreiArray = np.array(np.arange(3 * 4 * 5)).reshape(3, 4, 5)
DreiArray.shape


# In[ ]:


ZweiArray = np.array(np.arange(3 * 4)).reshape(3, 4)


# In[ ]:


DreiArray + ZweiArray


# In[ ]:


DreiArray_neu = np.array(np.arange(3 * 4 * 5)).reshape(5, 3, 4)
DreiArray_neu.shape


# In[ ]:


EinsArray = np.array(np.arange(5)).reshape(5, 1, 1)


# In[ ]:


#DreiArray_neu + ZweiArray + EinsArray


# In[ ]:


EinsArray


# In[ ]:


np.squeeze(EinsArray)


# ## Beispiel zur Verwendung von Index-Arrays.
# Erzeuge einen Vektor, der die Gegendiagonale einer Matrix enthält

# In[ ]:


A = np.arange(16).reshape(4, 4)
A


# In[ ]:


i = np.arange(4)
j = i[::-1] # view von i in umgekehrter Reihenfolge
j, i


# In[ ]:


b = A[i, j]
b


# ## Verwende boolsche Ausdrücke bei der Definition von Matrizen

# In[ ]:


# Bsp: Setze alle negativen Matrixeinträge auf Null
A 
B = A - 2*A.T 
B


# In[ ]:


B[B < 0] = 0
B


#  elementweises logisches "oder" und "und"

# In[ ]:


B = A - A.T
B


# In[ ]:


# Welche Elemente von B sind kleiner als -5 ODER größer als 6?
index_array = np.logical_or(B < -5, B > 6)
index_array


# In[ ]:


# Welche Elemente von B sind kleiner als 4 UND größer als 0?
display(B, np.logical_and(B < 4, B > 0))


# In[ ]:


B[index_array] = 100 # index_array = np.logical_or(B < -5, B > 6)
B


# ## Achtung
# 
# NumPy macht kein Ducktyping.
# 
# ... duck typing is an application of the duck test—"If it walks like a duck and it quacks like a duck, then it must be a duck" https://en.wikipedia.org/wiki/Duck_typing

# In[ ]:


a = np.array([1, -2])


# In[ ]:


a.dtype


# In[ ]:


a[0] = 1. + 1j


# In[ ]:


ac = np.array([1, -2.25], dtype='complex')
ac


# In[ ]:


ac[0] = 10. + 10j


# In[ ]:


a + ac


# In[ ]:


np.sqrt(a)


# In[ ]:


np.sqrt(a.astype('complex'))


# Die NumPy-Funktionen in emath (power, exp, log, und inverse trigonometrische Funktionen) passen den Ausgabedatentyp an, wenn der Ausgabedatentyp vom Eingabedatentyp abweicht.

# In[ ]:


np.emath.sqrt(a)


# In[ ]:


get_ipython().run_line_magic('pinfo', 'np.emath')


# ## Universal functions (ufunc)
# 
# Die universellen Funktionen aus NumPy (sin, cos, tan, arcsin, arccos, sinh, cosh, arcsinh, ... exp, log, log2, log10, sqrt, ...) wirken elementweise, wenn sie auf NumPy Arrays angewandt werden. https://numpy.org/doc/stable/reference/ufuncs.html

# In[ ]:


x = np.linspace(0, 5 * np.pi, 10)  # 10 äquidistante Zahlen zwischen 0 und 5 pi
display(x, np.sin(x))


# In[ ]:


get_ipython().run_line_magic('pinfo', 'np.expm1')


# In[ ]:


x = np.linspace(0, 5* np.pi, 1000)


# In[ ]:


get_ipython().run_cell_magic('timeit', '', 'y = np.sin(x)\n')


# In[ ]:


get_ipython().run_cell_magic('timeit', '', 'y = np.empty_like(x)\nfor k, xx in enumerate(x):\n    y[k] = np.sin(xx)\n')

