kleine Mathe-Spielereien

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

Hier wäre der Code auf Spyder.
Der gleiche Fehler kommt auch bei allen anderen
analogen Codes. Ich habe keine Ahnung.
Gute Zeit OSWALD

Code: Alles auswählen


from time import monotonic

from textual.app import App, ComposeResult
from textual.containers import ScrollableContainer
from textual.reactive import reactive
from textual.widgets import Button, Footer, Header, Static


class TimeDisplay(Static):
    """A widget to display elapsed time."""

    start_time = reactive(monotonic)
    time = reactive(0.0)
    total = reactive(0.0)

    def on_mount(self) -> None:
        """Event handler called when widget is added to the app."""
        self.update_timer = self.set_interval(1 / 60, self.update_time, pause=True)

    def update_time(self) -> None:
        """Method to update time to current."""
        self.time = self.total + (monotonic() - self.start_time)

    def watch_time(self, time: float) -> None:
        """Called when the time attribute changes."""
        minutes, seconds = divmod(time, 60)
        hours, minutes = divmod(minutes, 60)
        self.update(f"{hours:02,.0f}:{minutes:02.0f}:{seconds:05.2f}")

    def start(self) -> None:
        """Method to start (or resume) time updating."""
        self.start_time = monotonic()
        self.update_timer.resume()

    def stop(self):
        """Method to stop the time display updating."""
        self.update_timer.pause()
        self.total += monotonic() - self.start_time
        self.time = self.total

    def reset(self):
        """Method to reset the time display to zero."""
        self.total = 0
        self.time = 0


class Stopwatch(Static):
    """A stopwatch widget."""

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Event handler called when a button is pressed."""
        button_id = event.button.id
        time_display = self.query_one(TimeDisplay)
        if button_id == "start":
            time_display.start()
            self.add_class("started")
        elif button_id == "stop":
            time_display.stop()
            self.remove_class("started")
        elif button_id == "reset":
            time_display.reset()

    def compose(self) -> ComposeResult:
        """Create child widgets of a stopwatch."""
        yield Button("Start", id="start", variant="success")
        yield Button("Stop", id="stop", variant="error")
        yield Button("Reset", id="reset")
        yield TimeDisplay()


class StopwatchApp(App):
    """A Textual app to manage stopwatches."""

    CSS_PATH = "C:/python311/TEXTUALOrdner/stopwatch.css"

    BINDINGS = [
        ("d", "toggle_dark", "Toggle dark mode"),
        ("a", "add_stopwatch", "Add"),
        ("r", "remove_stopwatch", "Remove"),
    ]

    def compose(self) -> ComposeResult:
        """Called to add widgets to the app."""
        yield Header()
        yield Footer()
        yield ScrollableContainer(Stopwatch(), Stopwatch(), Stopwatch(), id="timers")

    def action_add_stopwatch(self) -> None:
        """An action to add a timer."""
        new_stopwatch = Stopwatch()
        self.query_one("#timers").mount(new_stopwatch)
        new_stopwatch.scroll_visible()

    def action_remove_stopwatch(self) -> None:
        """Called to remove a timer."""
        timers = self.query("Stopwatch")
        if timers:
            timers.last().remove()

    def action_toggle_dark(self) -> None:
        """An action to toggle dark mode."""
        self.dark = not self.dark


if __name__ == "__main__":
    app = StopwatchApp()
    app.run()


Benutzeravatar
__blackjack__
User
Beiträge: 13168
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Also in der Konsole läuft das bei mir. Zum Testen sollte man Programme sowieso in der Umgebung laufen lassen wo sie am Ende auch produktiv laufen. IDEs verändern die Laufzeitumgebung in der Regel mehr oder weniger subtil, was zu Problemen in die eine oder andere Richtung führen kann.
“There will always be things we wish to say in our programs that in all known languages can only be said poorly.” — Alan J. Perlis
OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

Großartig, was jüngst bei Python hinsichtlich
Textual , Konsole und mehr entwickelt wurde.
Das gibt 'Arbeit' für die nächsten Monate,
Hoffentlich begreife ich das all auch.

Jetzt verstehe ich auch die letzte Nachricht von _blackjack_
Dafür vielen Dank.
Gute Zeit OSWALD
OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

Auf Python selbst gibt es für mich immer noch
einen riesigen Bereich, den ich gerne erkunden möchte.
Bei matplotlib habe ich ein schönes Beispiel für
'Text" und noch mehr entdeckt . Auch das Thema 'Raster' interessiert mich.
Gute Zeit OSWALD

Code: Alles auswählen

[



import numpy as np

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot()
fig.subplots_adjust(top=0.85)
#                "s u p"-title  ungewöhnlich
# Set titles for the figure and the subplot respectively
fig.suptitle('Hier  "Text"   mit matplotlib  ', fontsize= 20, fontweight='normal')
ax.set_title('Ein  Beispiel aus der Matplotlib-Api')

ax.set_xlabel('X - Achse')
ax.set_ylabel('Y - Achse')

# Set both x- and y-axis limits to [0, 10] instead of default [0, 1]
ax.axis([0, 10, 0, 10])

ax.text(2, 8, 'blauer  Stern vor roter Box', style='italic',
        bbox={'facecolor': 'yellow', 'alpha': 0.5, 'pad': 10})

ax.text(2, 6, r'Gleichung von Einstein: $E=mc^2$', fontsize=15)

ax.text(1, 2, 'Original-Code verändert ' ) 
          

ax.text(0.8, 0.01, 'Text  in beliebigen Farben    ',
        verticalalignment='bottom', horizontalalignment='right',
        transform=ax.transAxes,
        color='green', fontsize=15)

ax.plot([1], [8.6], '*')
ax.annotate('Masse x Lichtgeschwindigkeit²', xy=(6,5.5), xytext=(1,3),
            arrowprops=dict(facecolor='black', shrink=0.05))

plt.show()




















/code]
OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

18.9.23
Matplotlib und Python haben inzwischen gewaltig
in Richtung KI aufgerüstet. Deshalb ist notwendig, dass ich
jetzt in intensiver in matplotlib eintauche.
Hier zwei Beispiele von unzähligen anderen Möglichkeiten aus der
Matplotlib-API
Gute Zeit OSWALD

Code: Alles auswählen


import matplotlib.pyplot as plt
import matplotlib.pyplot as plt

fig = plt.figure()
plt.axis((0, 10, 0, 10))
t = ("'Arm am Beutel, krank am Herzen"  
      " schleppt ich meine langen Tage."
       "Armut ist die größte Plage "
       "Reichtum ist das höchste Gut")
plt.text(4, 1, t, ha='left', rotation=15, wrap=True)
plt.text(6, 5, t, ha='left', rotation=15, wrap=True)
plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)
plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',
         va='top', wrap=True)
plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)
plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)

plt.show()

#############################

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.cbook import get_sample_data
from matplotlib.offsetbox import (AnnotationBbox, DrawingArea, OffsetImage,
                                  TextArea)
from matplotlib.patches import Circle

fig, ax = plt.subplots()

# Define a 1st position to annotate (display it with a marker)
xy = (0.5, 0.7)
ax.plot(xy[0], xy[1], ".r")

# Annotate the 1st position with a text box ('Test 1')
offsetbox = TextArea("Test 1")

ab = AnnotationBbox(offsetbox, xy,
                    xybox=(-20, 40),
                    xycoords='data',
                    boxcoords="offset points",
                    arrowprops=dict(arrowstyle="->"),
                    bboxprops=dict(boxstyle="sawtooth"))
ax.add_artist(ab)

# Annotate the 1st position with another text box ('Test')
offsetbox = TextArea("Test")

ab = AnnotationBbox(offsetbox, xy,
                    xybox=(1.02, xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
                    box_alignment=(0., 0.5),
                    arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)

# Define a 2nd position to annotate (don't display with a marker this time)
xy = [0.3, 0.55]

# Annotate the 2nd position with a circle patch
da = DrawingArea(20, 20, 0, 0)
p = Circle((10, 10), 10)
da.add_artist(p)

ab = AnnotationBbox(da, xy,
                    xybox=(1., xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
                    box_alignment=(0.2, 0.5),
                    arrowprops=dict(arrowstyle="->"),
                    bboxprops=dict(alpha=0.5))

ax.add_artist(ab)

# Annotate the 2nd position with an image (a generated array of pixels)
arr = np.arange(100).reshape((10, 10))
im = OffsetImage(arr, zoom=2)
im.image.axes = ax

ab = AnnotationBbox(im, xy,
                    xybox=(-50., 50.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.3,
                    arrowprops=dict(arrowstyle="->"))

ax.add_artist(ab)

# Annotate the 2nd position with another image (a Grace Hopper portrait)
with get_sample_data("grace_hopper.jpg") as file:
    arr_img = plt.imread(file)

imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, xy,
                    xybox=(120., -80.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.5,
                    arrowprops=dict(
                        arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=3")
                    )

ax.add_artist(ab)

# Fix the display limits to see everything
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

plt.show()


OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

22.9.23
Nach ausfühlicher Beschäftigung mit
dem neuen Matplotlib 3.8.5 gehe ich jetzt auf
'Raster' ein, die Grundlage für weitere Themen, z.B. Vektoren.
Anbei noch ein Ausflug in die Matptlib-Bibliothek.
Gute Zeit OSWALD

Code: Alles auswählen



import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot()
fig.subplots_adjust(top=0.85)

# Set titles for the figure and the subplot respectively
fig.suptitle('Matplotlib kann auch Text', fontsize=14, fontweight='bold')
ax.set_title('mit etwas Phnmtasievielleicht noch besser')

ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

# Set both x- and y-axis limits to [0, 10] instead of default [0, 1]
ax.axis([0, 30, 0, 30])

ax.text(1, 24, r'Arm am Beutel krank am Herzen,', fontsize=15, color = 'red')
ax.text(1, 21, r'schleppt ich meine langen Tage'',', fontsize=15,color = 'green' )
ax.text(1, 18, r'Armut ist die größte Plage', fontsize=15 , color = 'blue'  )
ax.text(1, 15, r'Reichtum ist das höchste Gut.', fontsize=15, color = 'black') 
ax.text(2, 12, r'aus der "Schatzgräber"' , fontsize=15, color = 'magenta') 
ax.text(2, 9,  r'von Johann W.v.Goethe', fontsize=15 , color = 'blue')
ax.text(2, 3, 'erstellt mit Matplotlib 3.8.5', fontsize=15, color = 'green')



OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

23.9.23
Der Raster, ist ein auf einer Fläche verteiltes regelmäßiges Muster
(zum Beispiel Punktraster oder Strichraster)
gekennzeichnet durch Grauwert und Punktdicke.
Ihre Vielzahl und Vielfalt ist nicht abzählbar.
Das weist auf seine große Bedeutung Wirtschaft
und Wissenschaft hin, ist aber auch eine
große Herausforderung für mich.
Hier ein erstes Beispiel, das bereits viele neue
Fragen und Begriffe enthält.

Weitere Beispiele folgen
Gute Zeit OSWALD

Code: Alles auswählen


import numpy as np
check = np.zeros((8, 8))
check[::2, 1::2] = 1
check[1::2, ::2] = 1
import matplotlib.pyplot as plt
plt.imshow(check, cmap='gray', interpolation='nearest') 
plt.show() 







OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

nächstes Beispiel zu Rastern

Code: Alles auswählen





from matplotlib import colors
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)
Nr = 3
Nc = 2

fig, axs = plt.subplots(Nr, Nc)
fig.suptitle('Multiple images')

images = []
for i in range(Nr):
    for j in range(Nc):
        # Generate data with a range that varies from one plot to the next.
        data = ((1 + i + j) / 10) * np.random.rand(10, 20)
        images.append(axs[i, j].imshow(data))
        axs[i, j].label_outer()

# Find the min and max of all colors for use in setting the color scale.
vmin = min(image.get_array().min() for image in images)
vmax = max(image.get_array().max() for image in images)
norm = colors.Normalize(vmin=vmin, vmax=vmax)
for im in images:
    im.set_norm(norm)

fig.colorbar(images[0], ax=axs, orientation='horizontal', fraction=.1)


# Make images respond to changes in the norm of other images (e.g. via the
# "edit axis, curves and images parameters" GUI on Qt), but be careful not to
# recurse infinitely!
def update(changed_image):
    for im in images:
        if (changed_image.get_cmap() != im.get_cmap()
                or changed_image.get_clim() != im.get_clim()):
            im.set_cmap(changed_image.get_cmap())
            im.set_clim(changed_image.get_clim())


for im in images:
    im.callbacks.connect('changed', update)

plt.show()


OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

dieses Beispiel zeigt u.a.
die großen Fortschritte von matplotlib 3.8
OSWALD

Code: Alles auswählen

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import patheffects

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 3))
ax1.imshow([[1, 2], [2, 3]])
txt = ax1.annotate("test", (1., 1.), (0., 0),
                   arrowprops=dict(arrowstyle="->",
                                   connectionstyle="angle3", lw=2),
                   size=20, ha="center",
                   path_effects=[patheffects.withStroke(linewidth=3,
                                                        foreground="w")])
txt.arrow_patch.set_path_effects([
    patheffects.Stroke(linewidth=5, foreground="w"),
    patheffects.Normal()])

pe = [patheffects.withStroke(linewidth=3,
                             foreground="w")]
ax1.grid(True, linestyle="-", path_effects=pe)

arr = np.arange(25).reshape((5, 5))
ax2.imshow(arr)
cntr = ax2.contour(arr, colors="k")

cntr.set(path_effects=[patheffects.withStroke(linewidth=3, foreground="w")])

clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls, path_effects=[
    patheffects.withStroke(linewidth=3, foreground="w")])

# shadow as a path effect
p1, = ax3.plot([0, 1], [0, 1])
leg = ax3.legend([p1], ["Line 1"], fancybox=True, loc='upper left')
leg.legendPatch.set_path_effects([patheffects.withSimplePatchShadow()])

plt.show()

OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

225.9.23
Bei der Durcharbeitung meines Themas
(Raster,Vektor ,Pixel) stellte ich fest , dass
ich mich im in einem Irrgarten verlaufen hatte.
Also schnell zurück zu -Python und Matplotlib -
Hier nun eine erste Vektorgrafik und dann
noch einen " Polygon-Grafik- Darsteller"
( ebenfalls auf Vektorbasis)

1 auf beliebigen punkt , ziehen
2 mit 'ESC' wird ein neues Polygon gestartet
3 mit 'shift' Änderung aller V-Werte
4 mit 'ctrl' Änderung einzelnen V-Weerte
#( bei Spyder funktioniern / gelten diese Hinweie nicht)

Code: Alles auswählen

[


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector
#Um das Polygon programmgesteuert zu erstellen

fig, ax = plt.subplots()
fig.show()

selector = PolygonSelector(ax, lambda *args: None)

 
selector.verts = [(0.4, 0.7) ,
                  (0.5, 0.9) ,
                  (0.0, 0.2),
                  (0.6,0.6),
                  (0.2,0.0 )]

 

fig2, ax2 = plt.subplots()
fig2.show()

selector2 = PolygonSelector(ax2, lambda *args: None)
selector2.verts =[(0.4, 0.7) ,
                 (0.5, 0.3) ,
                 (0.3, 0.2),
                 (0.6,0.4),
                 (0.2,0.8 )]

plt.show()

/code]
OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

25.9.23
weitere Beispiele für Vektorgraphiken
Gute Zeit OSWALD

Code: Alles auswählen



import numpy as np
import matplotlib.pyplot as plt
  
# Vector origin location
X = [0]
Y = [0]
  
# Directional vectors
U = [2]  
V = [1]  
  
# Creating plot
plt.quiver(X, Y, U, V, color='b', units='xy', scale=1)
plt.title('Single Vector')
  
# x-lim and y-lim
plt.xlim(-2, 5)
plt.ylim(-2, 2.5)
  
# Show plot with grid
plt.grid()
plt.show()
 



#Beispiel 2: Erzeugen mehrerer Vektoren mit der Methode quiver() .

 
import numpy as np
import matplotlib.pyplot as plt
  
# Meshgrid
x, y = np.meshgrid(np.linspace(-5, 5, 10), 
                   np.linspace(-5, 5, 10))
  
# Directional vectors
u = -y/np.sqrt(x**2 + y**2)
v = x/(x**2 + y**2)
  
# Plotting Vector Field with QUIVER
plt.quiver(x, y, u, v, color='g')
plt.title('Vector Field')
  
# Setting x, y boundary limits
plt.xlim(-7, 7)
plt.ylim(-7, 7)
  
# Show plot with grid
plt.grid()
plt.show()
 


#Beispiel 3: Zeichnen mehrerer Vektoren mit der Methode streamplot() im Modul matplotlib .

# Import required modules
import numpy as np
import matplotlib.pyplot as plt
  
# 1D arrays
x = np.arange(-5,5,0.1)
y = np.arange(-5,5,0.1)
  
# Meshgrid
X,Y = np.meshgrid(x,y)
  
# Assign vector directions
Ex = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)
Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2)
  
# Depict illustration
plt.figure(figsize=(10, 10))
plt.streamplot(X,Y,Ex,Ey, density=1.4, linewidth=None, color='#A23BEC')
plt.plot(-1,0,'-or')
plt.plot(1,0,'-og')
plt.title('Electromagnetic Field')
  
# Show plot with grid
plt.grid()
plt.show()


/code]
OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

25.9.23
und schließlich noch eine Pixelgrafik,
in die wir beliebige Zahlen
eingeben können.
Die Ergebnisse können sehr schön werden..
Leider kann ich dieses Thema nicht weiter verfolgen.
Gute Zeit OSWALD

Code: Alles auswählen




import numpy as np
import matplotlib.pyplot as plt

nrows, ncols = 1000, 1000
z = 500 * np.random.random(nrows * ncols).reshape((nrows, ncols))

plt.imshow(z, interpolation='nearest')
plt.colorbar()
plt.show()
 

import numpy as np 
import matplotlib.pyplot as plt

# blibige Daten eingeben   und Ergebnis prüfen
nrows, ncols = 200, 200
xmin, xmax = 20.4, 42.0
ymin, ymax = 17.9, 101.3

dx = (xmax - xmin) / (ncols - 1)
dy = (ymax - ymin) / (ncols - 1)

x = np.linspace(xmin, xmax, ncols)
y = np.linspace(ymin, ymax, nrows)
x, y = np.meshgrid(x, y)

z = np.hypot(x - x.mean(), y - y.mean())
x, y, z = [item.flatten() for item in (x,y,z)]

# Scramble the order of the points so that we can't just simply reshape z
indicies = np.arange(x.size)
np.random.shuffle(indicies)
x, y, z = [item[indicies] for item in (x, y, z)]

#  Jetzt haben wir Daten ,  die irgend etwas bringen werden ?
 

# We need to make a regular grid out of our shuffled x, y, z indicies.
# Zellgröße und gridT müssen übereinstimmen 
# Zahl der rows and columns im grid 

# Umwandlung  der x und y -Positionen  zu  indicies...
idx = np.round((x - x.min()) / dx).astype(int)
idy = np.round((y - y.min()) / dy).astype(int)

#  ein leerer 2D Grid
grid = np.zeros((nrows, ncols), dtype=np.int_)

# die Daten eingeben
grid[idy, idx] = z
 
# jetzt der Plot
plt.imshow(grid, interpolation='nearest', 
        extent=(x.min(), x.max(), y.max(), y.min()))
plt.colorbar()

plt.grid()
plt.show()


OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

30.9.23
"Lernen mit Spiel und Spaß belohnen"
Ich habe mir deshalb einige Animationen aus den
zahlreichen Bibliotheken herunter geladen. Sicher
werde ich diese meist wenig oder gar nicht verstehen.
Und ich musste eine Menge neuer Module oder Pakete
laden und implementieren. Heute weiß ich, wie das einfach
und elegant gemacht wird.
Wichtig ist, dass beim Herunterladen von Python auch
'pip' dabei ist. Bei der Eingabeaufforderung muss man
nur noch 'pip install .........' eingeben .
Bie PYPi findet man die neuesten Module.
Hier ein erstes 'Spielzeug'
Gute Zeit Oswald


Code: Alles auswählen


class LineBuilder:
    def __init__(self, line):
        self.line = line
        self.xs = list(line.get_xdata())
        self.ys = list(line.get_ydata())
        self.cid = line.figure.canvas.mpl_connect('button_press_event', self)

    def __call__(self, event):
        print('click', event)
        if event.inaxes!=self.line.axes: return
        self.xs.append(event.xdata)
        self.ys.append(event.ydata)
        self.line.set_data(self.xs, self.ys)
        self.line.figure.canvas.draw()

fig, ax = plt.subplots()
ax.set_title('click to build line segments')
line, = ax.plot([0], [0])  # empty line
linebuilder = LineBuilder(line)

plt.show()

def __init__(self, line):
        self.line = line
        self.xs = list(line.get_xdata())
        self.ys = list(line.get_ydata())
        self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
        print('click', event)
        if event.inaxes!=self.line.axes: return
        self.xs.append(event.xdata)
        self.ys.append(event.ydata)
        self.line.set_data(self.xs, self.ys)
        self.line.figure.canvas.draw()

fig, ax = plt.subplots()
ax.set_title('click to build line segments')
line, = ax.plot([0], [0])   # empty line
linebuilder = LineBuilder(line)

plt.show()

 












OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

nächstes Beispiel
kann man das Pendel verlängern ?
ich versuch es mal
OSWALD

Code: Alles auswählen



from collections import deque

import matplotlib.pyplot as plt
import numpy as np
from numpy import cos, sin

import matplotlib.animation as animation

G = 9.8  # acceleration due to gravity, in m/s^2
L1 = 1.0  # length of pendulum 1 in m
L2 = 1.0  # length of pendulum 2 in m
L = L1 + L2  # maximal length of the combined pendulum
M1 = 1.0  # mass of pendulum 1 in kg
M2 = 1.0  # mass of pendulum 2 in kg
t_stop = 2.5  # how many seconds to simulate
history_len = 500  # how many trajectory points to display


def derivs(t, state):
    dydx = np.zeros_like(state)

    dydx[0] = state[1]

    delta = state[2] - state[0]
    den1 = (M1+M2) * L1 - M2 * L1 * cos(delta) * cos(delta)
    dydx[1] = ((M2 * L1 * state[1] * state[1] * sin(delta) * cos(delta)
                + M2 * G * sin(state[2]) * cos(delta)
                + M2 * L2 * state[3] * state[3] * sin(delta)
                - (M1+M2) * G * sin(state[0]))
               / den1)

    dydx[2] = state[3]

    den2 = (L2/L1) * den1
    dydx[3] = ((- M2 * L2 * state[3] * state[3] * sin(delta) * cos(delta)
                + (M1+M2) * G * sin(state[0]) * cos(delta)
                - (M1+M2) * L1 * state[1] * state[1] * sin(delta)
                - (M1+M2) * G * sin(state[2]))
               / den2)

    return dydx

# create a time array from 0..t_stop sampled at 0.02 second steps
dt = 0.01
t = np.arange(0, t_stop, dt)

# th1 and th2 are the initial angles (degrees)
# w10 and w20 are the initial angular velocities (degrees per second)
th1 = 120.0
w1 = 0.0
th2 = -10.0
w2 = 0.0

# initial state
state = np.radians([th1, w1, th2, w2])

# integrate the ODE using Euler's method
y = np.empty((len(t), 4))
y[0] = state
for i in range(1, len(t)):
    y[i] = y[i - 1] + derivs(t[i - 1], y[i - 1]) * dt

# A more accurate estimate could be obtained e.g. using scipy:
#
#   y = scipy.integrate.solve_ivp(derivs, t[[0, -1]], state, t_eval=t).y.T

x1 = L1*sin(y[:, 0])
y1 = -L1*cos(y[:, 0])

x2 = L2*sin(y[:, 2]) + x1
y2 = -L2*cos(y[:, 2]) + y1

fig = plt.figure(figsize=(5, 4))
ax = fig.add_subplot(autoscale_on=False, xlim=(-L, L), ylim=(-L, 1.))
ax.set_aspect('equal')
ax.grid()

line, = ax.plot([], [], 'o-', lw=2)
trace, = ax.plot([], [], '.-', lw=1, ms=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
history_x, history_y = deque(maxlen=history_len), deque(maxlen=history_len)


def animate(i):
    thisx = [0, x1[i], x2[i]]
    thisy = [0, y1[i], y2[i]]

    if i == 0:
        history_x.clear()
        history_y.clear()

    history_x.appendleft(thisx[2])
    history_y.appendleft(thisy[2])

    line.set_data(thisx, thisy)
    trace.set_data(history_x, history_y)
    time_text.set_text(time_template % (i*dt))
    return line, trace, time_text


ani = animation.FuncAnimation(
    fig, animate, len(y), interval=dt*1000, blit=True)
plt.show()


OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

30.9.23
Ja, man kann das Pendel verlängern, auf die 'Lupe' drücken
und ziehen.
OSWALD
OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

1.10.23
Hier eine 'interaktive' Animation mi
Je länger ich mich in diesem 'Dschungel' bewege,
umso großartiger erscheint er.
Gute Zeit OSWALD

Code: Alles auswählen



# uDrch Veränderung  von Funktion, linspace, Schleife, Intevall,  delay oder   shape
# kann nIhalt  und Form    beliebig verändert werden.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation

fig, ax = plt.subplots()


#############################################
def f(x, y):
    return np.sin(x)**2  + y**( -2) + np.cos (4*y*x)
      # return  1/x +  np.cos(y**3)  
      #return  1/ np.exp(y+x) -  np. sin(2*y)
#############################################

x = np.linspace(0, 2 *  np.pi,4 )
y = np.linspace(0, 2 * np.pi, 4).reshape(-1,1)

# ims is a list of lists, each row is a list of artists to draw in the
# current frame; here we are just animating one artist, the image, in
# each frame
ims = []
for i in range(160):
    x+=  np.pi / 30
    y+= np.pi / 10
     


    im = ax.imshow(f(x, y), animated=True)
    if i == 0:
        ax.imshow(f(x, y))  # show an initial one first
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=40, blit=True,
                                repeat_delay=1000)



OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

2.10.23
In Ergänzung zum Thema ' Pixel und Vektor'
hier noch 'vom Numpy array zur Bitmap
OSWALD

Code: Alles auswählen


mport matplotlib.pyplot as plt
import numpy as np 
from bitmap import BitMap

#erstes Beispiel
myData = np.array(
   [[2.5, 2.5, 2.5, 2.5],
    [2.5, 3.5, 3.5 ,2.5],
    [2.5 ,3.5 ,3.5, 2.5 ],
    [2.5,2.5, 2.5 , 2.5]])
plt.imshow(myData)
plt.colorbar()
plt.show()
 

#zweites Beispiel
myData = np.array([
        [0, 255, 137, 255, 0, 255, 0, 255],
        [255, 0, 255, 0, 255, 0, 255, 0],
        [0, 255, 0, 255, 0, 255, 0, 255],
        [255, 0, 255, 333, 255, 0, 255, 0],
        [0, 255, 0, 255, 0, 255, 0, 255],
        [255, 0, 255, 0, 255, 238, 255, 0],
        [0, 255, 0, 255, 0, 255, 0, 255],
        [255, 0, 255, 0, 255, 0, 255, 0]])
plt.imshow(myData)
plt.colorbar()
plt.show()
 



myData= np.array([
    [0,128,128,128,128],
    [128, 0, 128, 128 ,128],
    [128, 128, 0, 128,128],
    [128, 128, 128 , 0, 128 ],
    [128,128,128, 128,  0 ]])

plt.imshow(myData)
plt.colorbar()
plt.show()
 
#Anzahl der Bits einsetzen 8,26,32 ,64,128  und   beide  Zahlen-Formate  anzeigen
  
bm = BitMap(16)
print( bm.tostring())
bm.set(0)
print( bm.tostring())

bm = BitMap.fromstring("00011101")
print( bm.tostring())
bm.flip(1)
print( bm.tostring())



OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

5.10.23
Viele Neuerungen in scipy und matplotlib.
Anbei eine schöne Animation (Kreis- und sinus-Funktionen
parallel)).Erwarte viel Neues.
Visualisierungen auf Python wurden auch optimiert.
Gute Zeit OSWALD

Code: Alles auswählen


mport matplotlib.pyplot as plt
import numpy as np

import matplotlib.animation as animation
from matplotlib.patches import ConnectionPatch

fig, (axl, axr) = plt.subplots(
    ncols=2,
    sharey=True,
    figsize=(6, 2),
    gridspec_kw=dict(width_ratios=[1, 3], wspace=0),
)
axl.set_aspect(1)
axr.set_box_aspect(1 / 3)
axr.yaxis.set_visible(False)
axr.xaxis.set_ticks([0, np.pi, 2 * np.pi], ["0", r"$\pi$", r"$2\pi$"])

# draw circle with initial point in left Axes
x = np.linspace(0, 2 * np.pi, 50)
axl.plot(np.cos(x), np.sin(x), "k", lw=0.3)
point, = axl.plot(0, 0, "o")

# draw full curve to set view limits in right Axes
sine, = axr.plot(x, np.sin(x))

# draw connecting line between both graphs
con = ConnectionPatch(
    (1, 0),
    (0, 0),
    "data",
    "data",
    axesA=axl,
    axesB=axr,
    color="C0",
    ls="dotted",
)
fig.add_artist(con)


def animate(i):
    x = np.linspace(0, i, int(i * 25 / np.pi))
    sine.set_data(x, np.sin(x))
    x, y = np.cos(i), np.sin(i)
    point.set_data([x], [y])
    con.xy1 = x, y
    con.xy2 = i, y
    return point, sine, con


ani = animation.FuncAnimation(
    fig,
    animate,
    interval=50,
    blit=False,  # blitting can't be used with Figure artists
    frames=x,
    repeat_delay=100,
)

plt.show()




OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

6.10.23
Kleine Veränderungen mit großen Wirkungen
verbessern das Verständnis des Inhalts,
am Beispiel der letzten Animation.
Gute Zeit OSWALD

Code: Alles auswählen

mport matplotlib.pyplot as plt
import numpy as np

import matplotlib.animation as animation
from matplotlib.patches import ConnectionPatch

fig, (axl, axr) = plt.subplots(
    ncols=2,
    sharey=True,
    figsize=(6, 2),
    gridspec_kw=dict(width_ratios=[1, 3], wspace=0),
)
axl.set_aspect(1)
axr.set_box_aspect(1 / 3)
axr.yaxis.set_visible(False)
axr.xaxis.set_ticks([0, np.pi, 50 * np.pi], ["0", r"$\pi$", r"$2\pi$"])

# draw circle with initial point in left Axes
x = np.linspace(0, 25 * np.pi, 25)
axl.plot(np.cos(x), np.sin(x), "k", lw=0.3)
point, = axl.plot(0, 0, "o")

# draw full curve to set view limits in right Axes
sine, = axr.plot(x, np.sin(x))

# draw connecting line between both graphs
con = ConnectionPatch(
    (1, 0),
    (0, 0),
    "data",
    "data",
    axesA=axl,
    axesB=axr,
    color="C0",
    ls="dotted",
)
fig.add_artist(con)


def animate(i):
    x = np.linspace(0, i, int(i *50 / np.pi))
    sine.set_data(x, np.sin(x))
    x, y = np.cos(i), np.sin(i)
    point.set_data([x], [y])
    con.xy1 = x, y
    con.xy2 = i, y
    return point, sine, con


ani = animation.FuncAnimation(
    fig,
    animate,
    interval=50,
    blit=False,  # blitting can't be used with Figure artists
    frames=x,
    repeat_delay=100,
)

plt.show()


OSWALD
User
Beiträge: 369
Registriert: Freitag 18. März 2022, 17:32

8.10.23
Ein Scatter-Feld wird in ein bitmap-Feld umgewandelt.
Nach eine ziemlichen Plackerei ist mir das gelungen.
Gelungen ist es aus der Verbindung zwei bestehenden ,
von einander unabhängigen Codes.
Ich habe verschiedene Codes kombiniert.


Farbe der bitmaps = weiß
Farbe des Feldes ist blau

Es gibt dabei eInen engen Zusammenhang zwischen
der Anzahl von Scatter-Punkten ( = Anzahl der Bitmaps )
der Anzahl von grid-Punkten ( = Anzahl u n d Größe möglichen bitmaps)
Einfach ausprobieren.
Aktuelle Einstellung 16/16
(grid_points z.B. 8,16,32,64 usw.





Code: Alles auswählen


mport matplotlib.pyplot as plt
import numpy as np
n_points =16             #Farbe der bitmaps 

#Zahl der Scatter-Punkte

# create random coordinates
x, y = np.random.rand(n_points,2).T
fig, ax = plt.subplots()
ax.scatter(x,y)
ax.set_xlim([0,1])
ax.set_ylim([0,1])
ncolors = len(plt.rcParams['axes.prop_cycle'])
 
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
 
plt.grid()
plt.show()


##############
grid_points =16     # Größe der Bitmaps. Je höher die Anzahl  grid_points,
                                 #  umso kleiner die bitmaps


grid_x = np.linspace(0,1,grid_points)
grid_y = grid_x.copy()

# initiate array of ones (white)
image = np.ones([grid_points, grid_points])
for xp, yp in zip(x,y):
    # selecing the closest point in grid
    index_x = np.argmin(np.abs(xp - grid_x))
    index_y = np.argmin(np.abs(yp - grid_y))
    # setting to black
    image[index_x,index_y] = 0
#ncolors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0,5 , ncolors, endpoint=False)
for s in shift:
    ax.plot(x, np.tan(x), '')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
 
# by the columns and y by the rows
fig, ax = plt.subplots()
ax.imshow(
    image. T,
    origin='lower',
    cmap=plt.get_cmap('Purples'))
plt.show()

Antworten