Search code examples
pythonstate-machine

Flowchart logic in python


I have a flowchart that has components like a state machine. I am not able to decode how to start writing this in python. The TMS is an input list as [1,1,1,1,1,0,1,1,0]

enter image description here

I started writing some code, but got stuck in developing this further.

TMS = [1,1,1,1,1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0]

next_step = False
def test_logic_reset():
  if tms == 1:
    print("reset")
  elif tms == 0:
    run_test_idle()

for i in TMS:
  tms = i
  print(tms)
  test_logic_reset()

Can anyone help in understanding the paradigm which I should use?


Solution

  • This seems conducive to a state machine implementation. You can implement this from scratch, or you can use a Python library like pytransitions. This library has many features, like calling a method before or after a transition, executing a transition only if a condition is met, handling errors for invalid states/transitions, etc. A basic solution would look something like this:

    from transitions import Machine
    
    class StateMachine:
    
        states = ['test_logic_reset', 'run_test_idle', 'another_state']
    
        def __init__(self):
            self.machine = Machine(model=self, states=StateMachine.states, initial='test_logic_reset')
    
            # you can also use named arguments: trigger, source, dest
            self.machine.add_transition('input_0', 'test_logic_reset', 'run_test_idle')
            self.machine.add_transition('input_1', 'test_logic_reset', '=')
            self.machine.add_transition('input_0', 'run_test_idle', '=')
            self.machine.add_transition('input_1', 'run_test_idle', 'another_state')
    
        def trigger(self, value):
            if value == 0:
                self.input_0()
            elif value == 1:
                self.input_1()
            else:
                raise NotImplementedError
    

    You can then call it like this:

    TMS = [1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0]
    sm = StateMachine()
    for i in TMS:
        start_state = sm.state
        sm.trigger(i)
        end_state = sm.state
        print(f'Input: {i}, Transition: {start_state} -> {end_state}')