Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GraphMachine: set proportional font or allow caller control #621

Closed
ulemanstreaming opened this issue Apr 21, 2023 · 3 comments · Fixed by #668
Closed

GraphMachine: set proportional font or allow caller control #621

ulemanstreaming opened this issue Apr 21, 2023 · 3 comments · Fixed by #668
Assignees

Comments

@ulemanstreaming
Copy link

You have an idea for a feature that would make transitions more helpful or easier to use? Great! We are looking forward to your suggestion.

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
The graphs drawn by GraphMachine are great, but the fixed-pitch font looks a bit clunky and takes more space than it needs to. I tried to pass a keyword argument to get_graph() (font= or fontname= or font_name=) but it's not set up to pass that on to dot and raises a TypeError.

In principle, the **kwargs parameter could allow for a passthrough argument that lets the caller set this kind of layout properties but a general solution might be tricky and a lot of work to implement. Simply picking a nicer font and sticking with it would be an improvement to me and, I hope, to many other users.

Additional context
I started playing with FSMs using statemachine but switched to transitions because it seems better engineered (and more convenient for my purposes). Both packages produce similar graphs, but I think statemachine's look better (it uses Arial). (statemachine also makes nice, capitalized node labels from state names, but the font choice is the main thing for me.)

image
From transitions
image
From statemachine
@aleneum
Copy link
Member

aleneum commented Apr 22, 2023

Hello @ulemanstreaming,

the diagrams module supports pygraphviz and graphviz backends and get_graph will return either pygraphviz or graphviz graph objects which you can edit to your liking. If you use pygraphviz (default) you could edit pygraphviz.AGraph attributes like this:

from transitions.extensions import GraphMachine

states = ["welcome", "industry", "usecase", "load_data"]
transitions = [
    ["next_step", "welcome", "industry"],
    ["next_step", "industry", "usecase"],
    ["next_step", "usecase", "load_data"],
    ["previous_step", "load_data", "usecase"],
    ["previous_step", "usecase", "industry"],
    ["previous_step", "industry", "welcome"],
]

m = GraphMachine(states=states, transitions=transitions, initial='welcome')
graph = m.get_combined_graph()
graph.graph_attr["fontname"] = "arial"
graph.edge_attr["fontname"] = "arial"
graph.node_attr["fontname"] = "arial"
graph.draw('graph_arial.png', prog='dot')

graph_arial

But there is also a mechanism for 'global' graph settings:
The dot/graphviz settings are defined as class members (Graphmachine.machine_attributes, Graphmachine.style_attributes). For global changes you can either 'monkey patch' those or use inheritance and create your own configuration. For a start, you can copy the above mentioned configurations.

GraphMachine uses MarkupMachine to get a dictionary representation of the current machine configuration (states, transitions, etc.). You could override get_markup_config to intercept this process and add a capitalised label.

from transitions.extensions import GraphMachine
from copy import deepcopy

states = ["welcome", "industry", "usecase", "load_data"]
transitions = [
    ["next_step", "welcome", "industry"],
    ["next_step", "industry", "usecase"],
    ["next_step", "usecase", "load_data"],
    ["previous_step", "load_data", "usecase"],
    ["previous_step", "usecase", "industry"],
    ["previous_step", "industry", "welcome"],
]

machine_attributes = deepcopy(GraphMachine.machine_attributes)
style_attributes = deepcopy(GraphMachine.style_attributes)

machine_attributes["fontname"] = "arial"
style_attributes["node"]["default"]["fontname"] = "arial"
style_attributes["edge"]["default"]["fontname"] = "arial"


class ArialGraph(GraphMachine):

    machine_attributes=machine_attributes
    style_attributes=style_attributes

    def get_markup_config(self):
        config = super(ArialGraph, self).get_markup_config()
        for state in config['states']:
            state['label'] = state['name'].capitalize()
        return config


ag = ArialGraph(states=states, transitions=transitions, initial='welcome')
ag.get_combined_graph().draw('graph_inherited.png', prog='dot')

graph_inherited

So this is how you could achieve what you are looking for as of now. However, if you have some ideas about how to streamline this process and make it more user friendly let me know. Adding more parameters to the constructor is something I'd like to avoid since there are already so many of them.

@aleneum
Copy link
Member

aleneum commented Apr 22, 2023

Instead of

graph.graph_attr["fontname"] = "arial"
graph.edge_attr["fontname"] = "arial"
graph.node_attr["fontname"] = "arial"

you could also pass them as arguments to dot:

graph.draw('graph_args.png', prog='dot', args="-Gfontname=Arial -Efontname=Arial -Nfontname=Arial")

@ulemanstreaming
Copy link
Author

ulemanstreaming commented Apr 24, 2023

Thank you @aleneum . These are very helpful suggestions, and sufficient for my current purposes.

  • Using command line arguments is effective, though it feels a bit hacky.
  • I already subclass GraphMachine (using your suggested Alternative initialization pattern), so there's no need for me to create a separate subclass. I work in a Jupyter notebook, which can readily display a PNG if it's returned by a method named _repr_png_. So I simply implement that, along with your suggestions for get_markup_config() and the *_attribute data members. I also use a smaller font inside the graph and replace underscore with space in the state labels. This leads to:
class Wizard(GraphMachine):
    machine_attributes = deepcopy(GraphMachine.machine_attributes)
    style_attributes   = deepcopy(GraphMachine.style_attributes)
    
    machine_attributes['fontname']                  = 'arial'
    style_attributes['node']['default']['fontname'] = 'arial'
    style_attributes['edge']['default']['fontname'] = 'arial'
    style_attributes['node']['default']['fontsize'] = 9
    style_attributes['edge']['default']['fontsize'] = 9

    def __init(...)
        ...

    def get_markup_config(self):
        config = super(Wizard, self).get_markup_config()
        
        for state in config['states']:
            state['label'] = state['name'].capitalize().replace('_', ' ')
        return config
    
    def _repr_png_(self, **kwargs):
        return self.get_graph(title=self._title, **kwargs).draw(None, prog='dot', format='png')

image

So, it works. I have no suggestions for making it easier beyond documenting these tricks, or maybe doing more with the kwargs parameter in get_graph(). I agree that loading up the constructor with more parameters is not great; if you really wanted to give callers more control, adding one or a few methods to set style attributes might be preferable.

This issue can be closed as far as I'm concerned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants