Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean implementation of "decision matrix"

Tags:

python

matrix

I am trying to find a clean solution to implement a basic decision matrix in python. I have 8 sensors that monitor an installation, and based on the state of these 8 sensors, I need to activate some relays.

My decision matrix looks like (S are sensors and R are R):

S1   S2   S3   S4   S5   S6   S7   S8   R1   R2   R3
0    1    0    0    1    1    0    1    0    0    1
1    0    1    0    0    1    1    0    1    1    1
0    1    1    1    0    0    0    1    0    1    0
...

Currently the only implementation that I see, is a suite a if/elif statements for each row of my descision matrix like:

if S1==0 and S2==1 and S3==0 and S4==0 and S5==1 and S6==1 and S7==0 and S8==1:
    relay_state('R1', 0)
    relay_state('R2', 0)
    relay_state('R3', 1)
elif ...

This will definitely work, but I wonder if there is a cleaner way to implement this?

like image 849
cgaspoz Avatar asked Aug 31 '25 01:08

cgaspoz


2 Answers

you can use a dictionary of tuple

matrix = {
   (0,1,0,0,1,1,0,1):(0,0,1),
   (1,0,1,0,0,1,1,0):(1,1,1),
   (0,1,1,1,0,0,0,1):(0,1,0),

}
S1,S2,S3,S4,S5,S6,S7,S8 = 0,1,0,0,1,1,0,1
R1,R2,R3=matrix[S1,S2,S3,S4,S5,S6,S7,S8]
print (R1,R2,R3)

$python test.py
(0, 0, 1)
like image 196
Xavier Combelle Avatar answered Sep 02 '25 15:09

Xavier Combelle


Use list and compare lists:

if sensors == [0,1,0,1, ....]:

Even more efficient notations - if your handlers are functions, you may use a dictionary

decision_matrix = { (0,1,1,... ): some_handler, ... }
...
decision_matrix[sensors]()
like image 44
volcano Avatar answered Sep 02 '25 14:09

volcano