Skip to content

Instantly share code, notes, and snippets.

@salvatorecapolupo
Last active July 8, 2024 14:03
Show Gist options
  • Save salvatorecapolupo/3a845e7b5865f770107bfb356be652b2 to your computer and use it in GitHub Desktop.
Save salvatorecapolupo/3a845e7b5865f770107bfb356be652b2 to your computer and use it in GitHub Desktop.
Emulate a Markov process in Python 3, with a transition graph and an editable matrix. Source / Explanation: https://lipercubo.it/catene-di-markov.html
import random
import matplotlib.pyplot as plt
import networkx as nx
from matplotlib.animation import FuncAnimation
# Definizione degli stati e delle transizioni della catena di Markov
states = ["salve", "ciao", "buongiorno", "buonasera", "hey"]
transitions = {
"salve": {"ciao": 0.3, "buongiorno": 0.3, "buonasera": 0.2, "hey": 0.2},
"ciao": {"salve": 0.2, "buongiorno": 0.3, "buonasera": 0.2, "hey": 0.3},
"buongiorno": {"salve": 0.25, "ciao": 0.25, "buonasera": 0.25, "hey": 0.25},
"buonasera": {"salve": 0.3, "ciao": 0.3, "buongiorno": 0.2, "hey": 0.2},
"hey": {"salve": 0.25, "ciao": 0.25, "buongiorno": 0.25, "buonasera": 0.25}
}
# Funzione per scegliere il prossimo stato basato sulle probabilità di transizione
def next_state(current_state):
next_states = list(transitions[current_state].keys())
probabilities = list(transitions[current_state].values())
return random.choices(next_states, probabilities)[0]
# Generazione di una sequenza di saluti
def generate_greetings(start_state, n):
current_state = start_state
greetings = [current_state]
for _ in range(n - 1):
current_state = next_state(current_state)
greetings.append(current_state)
return greetings
# Generiamo una sequenza di 10 saluti partendo da "salve"
greetings_sequence = generate_greetings("salve", 10)
# Visualizzazione del processo con un grafo animato
G = nx.MultiDiGraph()
for state in states:
for next_state, prob in transitions[state].items():
G.add_edge(state, next_state, weight=prob)
pos = nx.spring_layout(G)
fig, ax = plt.subplots()
def update(num):
ax.clear()
current_state = greetings_sequence[num]
color_map = ['red' if node == current_state else 'skyblue' for node in G.nodes()]
nx.draw(G, pos, with_labels=True, node_color=color_map, node_size=3000, font_size=16, ax=ax)
labels = {e: f'{G.edges[e]["weight"]:.2f}' for e in G.edges}
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, ax=ax)
ax.set_title(f"Saluto attuale: {current_state}")
ani = FuncAnimation(fig, update, frames=len(greetings_sequence), interval=1000, repeat=True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment