Draw fysom defined state machines

If you have a finite state machine defined using the Python fysom library it is often useful to see how it looks in graphical form.

Take the following machine (from the fysom readme).

from fysom import Fysom

fsm = Fysom({
    'initial': 'green',
    'events': [
        {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
        {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
        {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
        {'name': 'clear', 'src': 'yellow', 'dst': 'green'}

This can be displayed using networkx and nxpd

import networkx as nx
from nxpd import draw

G = nx.MultiDiGraph()

for event, transitions in fsm._map.items():
    for from_state, to_state in transitions.items():
        G.add_edges_from([(from_state, to_state)], label=event)


This will generate the image below:

This also works inside iPython/Jupyter notebooks – just call the draw function as

draw(G, show='ipynb')

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.