kleine Mathe-Spielereien

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
OSWALD
User
Beiträge: 226
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: 12490
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.
“Weltsprache No. 1 dürfte weder amerikanisches noch britisches, sondern schlechtes Englisch sein.”
— Ralf Callenberg in de.etc.sprache.deutsch
OSWALD
User
Beiträge: 226
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: 226
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: 226
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: 226
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: 226
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: 226
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: 226
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: 226
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: 226
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: 226
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()


Antworten