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


# # Modularisierung

# Module (modules) sind Python-Dateien mit der Endung .py, die Funktionen und Variablen (Datencontainer) für bestimmte Aufgaben bereitstellen. Mehrere Module werden zu Paketen (packages) zusammengefasst, um den Funktionsumfang von Python zu erweitern. Oft werde auch Pakete und Unterpakete einfach Modul genannt.

# Erstelle Datei compla2026.py im selben Ordner, in dem auch lektion4.ipynb liegt.

# ## Einbinden von Modulen und Paketen

# In[5]:


import compla2026


# In[2]:


PROJEKT_NAME


# In[4]:


compla2026.PROJEKT_NAME


# In[ ]:


compla2026.begruessung('Julia')


# In[ ]:


from compla2026 import begruessung


# In[ ]:


begruessung('Max')


# ## Aliase

# In[ ]:


import compla2026 as cla


# In[ ]:


cla.begruessung('Eve')


# In[ ]:


from compla2026 import begruessung as hello


# In[ ]:


hello('Tom')


# In[ ]:


hallo = begruessung # das geht nur, weil wir vorher "from compla26 import begruessung" ausgefuehrt haben.


# In[ ]:


hallo('Li')


# # Einführung in NumPy

# Listen sind als Vektoren nicht so gut zu gebrauchen.

# In[ ]:


[1, 1.] + [2, 3.]


# NumPy ist ein Paket das Vektoren, Matrizen, Tensoren, mathematische Funktionen, einen Zufallszahlengenerator, grundlegende Verfahren der linearen Algebra und vieles mehr zur Verfügung stellt.

# Hier ist ein winziger Ausschnitt aus der Ordnerstruktur von numpy
# ```text
# numpy/                      # Hauptordner = Paket
# │
# ├── __init__.py             # Sagt Python: "Ich bin ein Paket!"
# │
# ├── linalg/                 # Unterordner = Sub-Paket!
# │   ├── __init__.py         # Sagt Python: "Ich bin ein Sub-Paket!"
# │   └── _linalg.py          # Einzelne Datei = Das eigentliche Modul
# │
# └── random/                 # Unterordner = Sub-Paket!
#     ├── __init__.py         # Sagt Python: "Ich bin ein Sub-Paket!"
#     ├── generator.py        # Einzelne Datei = Modul
#     └── mtrand.pyx          # Einzelne Datei = Modul
# ```

# In[ ]:


import numpy as np


# In[ ]:


#dir(np)


# In[ ]:


v = np.array((1, 2))
v


# In[ ]:


np.pi


# In[ ]:


np.sin(np.pi)


# ## Vektoren und Matrizen in NumPy erzeugen (Teil 1)

# In[ ]:


u = np.array([1, 2, 3])      # 1D Array (Vektor)
u


# In[ ]:


v = np.array([4, 5])
v


# In[ ]:


A = np.array([[3, 2, 1], [3, 5, 4], [8, 6, 7]])  # 2D Array (Matrix)
A


# In[ ]:


type(u), type(v), type(A)


# In[ ]:


u


# In[ ]:


v


# In[ ]:


A


# In[ ]:


w = np.array(5)    # eine skalare Größe (0D array)


# In[ ]:


w


# In[ ]:


3*u  # jedes Element wird mit 3 multipliziert


# In[ ]:


e = np.array([1, 1, 1])
e


# In[ ]:


3*u - e # Skalarmultiplikation und Addidtion/Substraktion von Vektoren/Arrays


# ## Attribute (eines NumPy Arrays)
# 
# Mit 
# ```python
#    obj.name
# ```
# greift man auf das Attribut mit <code>name</code> des Objekts <code>obj</code> zu.
# 
# 

# In[ ]:


a = 1.23 - 98.7j


# In[ ]:


a.real


# In[ ]:


a.imag


# <code>ndim</code> Anzahl der Dimensionen eines NumPy arrays anzeigen: 

# In[ ]:


w.ndim


# In[ ]:


A.ndim


# Es gibt <code>ndim</code> auch als numpy Funktion:

# In[ ]:


np.ndim(u)


# In[ ]:


np.ndim(A)


# Die Elemente des <code>shape</code> Tupels geben die Größe der entsprechenden Array Dimensionen an.
# 
# Ebenso wie <code>ndim</code> gibt es auch <code>shape</code> sowohl als Attribut als auch als Funktion.
# 

# In[ ]:


A.shape


# In[ ]:


u.shape


# In[ ]:


w.shape


# In[ ]:


np.shape(A)


# In[ ]:


np.shape(u)


# In[ ]:


len(u)


# <code>size</code> gibt die Anzahl der Elemente des Arrays an:

# In[ ]:


A.size


# In[ ]:


np.size(A)


# In[ ]:


u.size


# In[ ]:


np.size(u)


# In[ ]:


len(A)


# ## Mathematische Operationen für NumPy Arrays
# ### Addition, Subtraktion, Multiplikation, Division, modulo, potenzieren
# 
# *, / , % und &ast;&ast; wirken eintragsweise, wie  + und - 

# In[ ]:


u


# In[ ]:


a = np.array(range(4,7))
a


# In[ ]:


u * a


# In[ ]:


u**u


# In[ ]:


A*A


# In[ ]:


A


# In[ ]:


A


# In[ ]:


A/A


# Transponierte Matrix

# In[ ]:


A.T 


# ### Der @ Operator 
# 
# <code> @ </code> definiert auf np.arrays eine allgemeine Matrixmultplikation.
#  
# Skalarprodukt von Vektoren

# In[ ]:


u @ u


# In[ ]:


np.dot(u, u)


# Matrix-Vektor Produkt

# In[ ]:


A @ u


# In[ ]:


u @ A


# Matrix-Matrix Produkt

# In[ ]:


A @ A


# In[ ]:


np.dot(A, A)


# ## Ändern der Form eines ndarrays <code>reshape()<code>
# 
# Objekte haben neben Attributen auch eigene Funktionen, sogenannte Methoden. Mit
# ```python
#         obj.name()
# ```
# wird die Methode <code>name</code> des Objekts <code>obj</code> aufgerufen. Wichtig sind hier die Klammern.
# 
# Mit <code>.reshape()</code> oder <code>np.newaxis</code> kann man aus einem _flachen_ Vektor einen Zeilen- oder Spaltenvektor machen.
# 

# In[ ]:


u_zeile = u.reshape((1, -1)) # Zeilenvektor
u_zeile


# In[ ]:


u_zeile = u.reshape(1,-1)
u_zeile


# In[ ]:


u_zeile.ndim


# In[ ]:


u.ndim


# In[ ]:


u_zeile.shape


# In[ ]:


u.shape


# In[ ]:


u_zeile_ = u[:, np.newaxis]
u_zeile


# ## Zusammensetzen mit <code>concatenate</code>, <code>vstack</code> und <code>hstack</code>
# 

# In[ ]:


# Arrays zusammenkleben A soll um eine Zeile mit e erweitert werden
np.concatenate((A, e), axis=0)


# In[ ]:


np.concatenate((A, e.reshape(1, -1)), axis=0)


# In[ ]:


np.vstack((A, e)) # Arrays vertikal zusammenkleben mit np.vstack


# In[ ]:


np.concatenate((A, e.reshape(-1, 1)), axis=1)


# In[ ]:


np.hstack((A, e.reshape(-1, 1))) # Arrays horizontal zusammenkleben mit np.hstack


# In[ ]:


np.hstack((A, A))


# In[ ]:


np.concatenate((A, A), axis=1)


# ## Auf Einträge zugreifen  und  Einträge ändern 

# In[ ]:


C = np.concatenate((A, 10*A), axis=0)
C


# In[ ]:


C[0, 0] #Element links oben in C


# In[ ]:


C[-1, -2]


# In[ ]:


C[-1, -1] = 101 # Element rechts unten
C


# In[ ]:


C[2, :]


# In[ ]:


C


# In[ ]:


C[1::2, [1]] # Spaltenvektor


# In[ ]:


C[1::2, 1]  # flacher Vektor


# In[ ]:


C[2:4, 1:3]  # 2d Array


# In[ ]:


C[2, :] = -1
C


# In[ ]:


u[0] = 100
u_zeile  # u_zeile ist nur eine Ansicht (view) von u und zeigt auf dieselben Einträge im Speicher


# In[ ]:


u_spalte = u[:, np.newaxis]
u_spalte


# In[ ]:


u_spalte @ u_zeile  # äußeres Produkt


# In[ ]:


u_zeile @ u_spalte  # Skalarprodukt (inneres Produkt) Achtung, das ist ein 1 x 1 array


# In[ ]:


u_zeile.flatten() @ u_spalte.flatten() # Skalarprodukt (inneres Produkt)


# In[ ]:


u_spalte @ A


# In[ ]:


u_zeile @ A


# ## Kronecker Produkt
# Ein Beispiel statt einer Definition
# $$\scriptsize \begin{pmatrix} 1 & 2 \\ 3 & 4 \\ 5 & 6 \end{pmatrix}\otimes \begin{pmatrix} 7 & 8 \\ 9 & 0 \end{pmatrix}
# =\begin{pmatrix} 
# 1 \cdot \begin{pmatrix} 7 & 8 \\ 9 & 0 \end{pmatrix} & 2 \cdot \begin{pmatrix} 7 & 8 \\ 9 & 0 \end{pmatrix} \\\\
# 3 \cdot \begin{pmatrix} 7 & 8 \\ 9 & 0 \end{pmatrix} & 4 \cdot \begin{pmatrix} 7 & 8 \\ 9 & 0 \end{pmatrix} \\\\
# 5 \cdot \begin{pmatrix} 7 & 8 \\ 9 & 0 \end{pmatrix} & 6 \cdot \begin{pmatrix} 7 & 8 \\ 9 & 0 \end{pmatrix}
# \end{pmatrix}
# =\begin{pmatrix} 7 & 8 & \!\!\! & 14 & 16 \\ 9 & 0 & \!\!\! & 18 & 0 \\[0.6em] 21 & 24 & \!\!\! & 28 & 32 \\ 27 & 0 & \!\!\! & 36 & 0 \\[0.6em] 35 & 40 & \!\!\! & 42 & 48 \\ 45 & 0 & \!\!\! & 54 & 0 \end{pmatrix} $$

# In[ ]:


np.kron([1, 10, 100], [5, 6, 7])


# In[ ]:


D2 = np.array([[1, 0], [0, 2]])
E2 = np.array([[1, 3], [5, 2]])
D2


# In[ ]:


E2


# In[ ]:


np.kron(D2, E2)


# In[ ]:


np.kron(E2, D2)


# ## Definition spezieller Matrizen <code>ones</code>, <code>zeros</code>, <code>eye</code>, <code>arange</code>

# In[ ]:


E = np.ones((3, 3))   # Matrix aus Einsen
Z = np.zeros((3, 3))  # Nullmatrix
I = np.eye(3)         # Identität
A = np.arange(1,17)   # flacher "Vektor" [1,..16]


# In[ ]:


E 


# In[ ]:


Z


# In[ ]:


I


# In[ ]:


A


# In[ ]:


np.eye(4, 6, k=1)  # erste obere Nebendiagonale


# In[ ]:


np.eye(4, 6, k=-1)  # erste untere Nebendiagonale


# In[ ]:


np.eye(4, 6)   # Default Wert ist k=0, Hauptdiagonale


# ## Diagional- und Dreiecksmatrizen

# In[ ]:


A = A.reshape(4, 4)
A


# In[ ]:


np.diagonal(A) # Hauptdiagonale von A


# In[ ]:


np.tril(A) # Untere Dreiecksmatrix (lower triangular)


# In[ ]:


np.triu(A) # Obere Dreiecksmatrix (upper triangular)


# In[ ]:


A


# In[ ]:


NU = np.diagonal(A, offset=1)  # erste obere Nebendiagonale
NU


# In[ ]:


NL = np.diagonal(A, offset=-1) # erste untere Nebendiagonale
NL


# In[ ]:


B = np.diagflat(v.flatten()) # np.diagflat erzeugt Diagonalmatrix aus flachen Vektor
B


# In[ ]:


# Benutze np.diag zur Definition von Matrizen
x = np.array([1, 2, 3])
C = np.diagflat(x, k=-1) + np.diagflat(2*x, k=1) #k=-1 erste untere Nebendiagonale, k=1 erste obere Nebendiagonle
C


# ##  <code>max</code> und <code>min</code> für Arrays
# 
# <code>np.max(A)</code> oder <code>A.max()</code> liefert das maximale Matrixelement:
# (<code>min</code> geht analog)

# In[ ]:


A


# In[ ]:


np.max(A), A.max()


# In[ ]:


A.max(1) # Man kann auch das Maximum entlang der ersten Achse nehmen (zeilenweises Maximum)


# In[ ]:


A.max(0) # Man kann auch das Maximum entlang der nullten Achse (spaltenweises Maximum)


# In[ ]:


np.max(A, axis=0)


# In[ ]:


np.max(A, axis=1)  


# <code>.flatten()</code> A in ein 1-dim. Array umwandeln

# In[ ]:


A.flatten()


# __np.argmin(A)__ bzw. __np.argmax(A)__ liefert den Index, bezüglich "flattened array", des kleinsten / größten Matrixelements.
# 
# Falls das kleinste bzw. größte Element mehrfach vorkommt, erhält man den Index des ersten Elements.

# In[ ]:


A.argmax(), A.flatten()[np.argmax(A)]


# In[ ]:


B = np.array([3*i-4 for i in range(16)]).reshape(4, 4)
B


# In[ ]:


np.maximum(A, B) # elementweises maximum

