pytransitions / transitions

A lightweight, object-oriented finite state machine implementation in Python with many extensions
MIT License
5.5k stars 525 forks source link

State translations #442

Closed dennylab closed 4 years ago

dennylab commented 4 years ago

I'm using HierarchicalGraphMachine to generate a graph based on my model.

Here is a stripped version of my Model:

#  Copyright (C) 2012 - 2020 by labsolution S.a.r.l & Co KG. all rights reserved

class States:
    STATE_NEW = 'new'
    STATE_CONVERT = 'convert_to_tree'

SATTE_TRANSLATION = {
    States.STATE_NEW: 'New',
    States.STATE_CONVERT: 'Convert structured data into tree format',
}

class SMBModelDefinition:
    states = [
        States.STATE_NEW,
        States.STATE_CONVERT,
    ]

    transitions = [
      ['go', f'{States.STATE_NEW}', f'{States.STATE_CONVERT}'],
    ]

What I'm missing is a feature to generate the graph, but to use my SATTE_TRANSLATION as state labels. So I would have human readable labels on my graph, but internally I can use technical keywords because of technical reasons (hooks and so on).

aleneum commented 4 years ago

You can retrieve the graph without generating the graphviz representation by calling your model's get_graph method. How labels can be replaced depends on whether you use the graphviz or pygraphviz engine. Using pygraphviz, you can retrieve all nodes and change the label:

from transitions.extensions.diagrams import GraphMachine

states = ['A', 'B', 'C', 'D']
state_translations = {
    'A': 'Start',
    'B': 'Error',
    'C': 'Pending',
    'D': 'Done'
}

transitions = [['go', 'A', 'B'], ['process', 'A', 'C'], ['go', 'C', 'D']]

m = GraphMachine(states=states, transitions=transitions, initial='A')
graph = m.get_graph()

for node in graph.iternodes():
    node.attr['label'] = state_translations[node.attr['label']]

graph.draw('translated.png', prog='dot')

translated.png

translated

dennylab commented 4 years ago

Wooow! Awesome! Thanks for your fast help!! You might consider adding that to the doc, so others can take advantage of it too! :)