1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
|
%global _empty_manifest_terminate_build 0
Name: python-pyDMNrules
Version: 1.4.4
Release: 1
Summary: An implementation of DMN in Python. DMN rules are read from an Excel workbook
License: GNU General Public License v3 (GPLv3)
URL: https://github.com/russellmcdonell/pyDMNrules
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/ce/7c/0b7a1f7c768fc47efab752df5ea1f2c571a1f6721c4b22d075af8b5ed9d5/pyDMNrules-1.4.4.tar.gz
BuildArch: noarch
Requires: python3-datetime
Requires: python3-pySFeel
Requires: python3-openpyxl
Requires: python3-pandas
%description
# pyDMNrules
An implementation of DMN (Decision Model Notation) in Python, using the [pySFeel](https://pypi.org/project/pySFeel/), [openpyxl](https://pypi.org/project/openpyxl/) and [pandas](httpsL//pypi.org/project/pandas) modules.
DMN rules are read from an Excel workbook.
Then data, matching the input variables in the DMN rules is passed to the decide() function.
The returned data contains the decision.
The passed Excel workbook must contain a 'Decision' tab and may contain a 'Glossary' tab.
Other tabs contain as many DMN rules tables as necessary.
## Glossary - optional
The 'Glossary' tab, if it exists, must contain a table headed 'Glossary'.
A 'Glossary' table lets the user add additional documentation/clarification to the input and output data.
Data items can be grouped in to Business Concepts to better document where inputs come from and where outputs will be going to.
The 'Glossary' table must have exactly three columns with the headings 'Variable', 'Business Concept' and 'Attribute'.
The data in these three columns describe the inputs and outputs associated with the 'Decision'.
'Variable' can be any text and is used to pass data to and from pyDMNrules.
NOTE: the name 'Execute' is a reserved name and cannot be used as a Variable name. The name 'Execute' is reserved as a heading for output columns, output rows or the output variable of a Cross Tabs decision table. The output value(s) in an 'Execute' output column, 'Execute' output row or 'Execute' Cross Tabs decision table must be the name of a Decision Table which will be invoked when the matching rule is triggered. If the output value in an 'Execute' output column, an 'Execute' output or an output cell in an 'Execute' Cross Tabs decision table is missing (and empty cell), then no Decision Table will be invoked whe the matching rule is triggered.
'Business Concept' and 'Attribute' must be valid FEEL names as the 'Variable' will be mapped to a Glossary item created by joining these two FEEL names
with a period character, as in 'Order.orderSize'.
Vertically merged cells in the 'Business Concept' column are used to group multiple 'Variable'/'Attribute' pairs together into a single 'Businss Concept'.
The 'Glossary' can have multiple columns of Annotations to describe things like data types, valid values etc.
Items in the Glossary can be outputs of one decision table and inputs in the next decision table, which makes it easy to support complex business models.
Input decision cells and Output cells can refer to input and output values either by their 'Variable' name, or by their Glossary item (FEEL) name, of 'BusinessConcept.Attribute'
| Glossary | | |
|--------------|----------------------|---------------|
| **Variable** | **Business Concept** | **Attribute** |
| Customer | Customer | sector |
| OrderSize | Order | orderSize |
| Delivery | | delivery |
| Discount | Discount | discount |
If a 'Glossary' tab is not present - if no Glossary is supplied, then pyDMNrules will construct one using the input and output headings.
There will be a single 'Business Concept' called 'Data'.
Attributes will be created by replacing any space characters (' ') with an underscore character ('_') and then removing all **invalid** FEEL name characters.
This can cause conflicts. For instance ':' is a valid character in a Variable, but not in a FEEL name.
If there are two Varibles, being 'C' and 'C:' then both will be transformed to an Attribute of 'C' and a Glossary item of 'Data.C', which will be ambiguous.
This ambiguity can be avoided by supplying a 'Glossary' and explicitely mapping 'C:' to a valid FEEL name, such as 'Ccolon'.
The function getGlossary() will return the Glossary (either supplied or constructed).
## Decision - optional
In order to make a decision, pyDMNrules needs to know where to start, what to do, when and why.
The 'Decision' tab, if it exists, will contain a table headed 'Decision' which will provide the required details.
The heading for the 'Desion' table will be none or more Variable names,
a heading of 'Decisions', a heading of 'Execute Decision Table' and none or more headings for annotations.
The 'Decisions' column is documentation and contain a brief description of the DMN rules table which is named in 'Execute Decision Table' column
which is in effect just a list of DMN rules tables to be run in the specified order.
If there are any 'Variable' columns then these columns must contain valid DMN test as if they were DMN rules tables input columns.
pyDMNrules now knows where to start (with the first DMN rules table), what to do (each DMN rules table in turn), when (when all the 'Variable' tests are 'true')
and why (because all the 'Variable' tests are 'true')
| Decision | | | |
|-------------|--------------------|----------------------------|------------------|
| Variable(s) | **Decisions** | **Execute Decision Table** | Annotation(s) |
| input test | Determine Discount | Discount | Compute discount |
The 'Variable' cells are evaluated on the fly, which means that a preceeding DMN rules table can set or clear
a 'Variable' which can effect which DMN rules tables are included, and which DMN rules tables are excluded,
in the final decision.
The Decision tab, and associated 'Decision' table are optional because in many instances, what to do is obvious.
If the workbook does not contain a 'Decision' tab, then pyDMNrules will construct a 'Decision' table.
If there is only one DMN rules table pyDMNrules will create a 'Decision' table with just one row.
There can be several DMN rules tables that are independant and hence the order doesn't matter.
If there's more than one DMN rules table, pyDMNrules looks for dependancies and works out an acceptable order.
To do this, pyDMNrules looks at the inputs of each DMN rules table and check to see if that input is also an outputs from another DMN rules table.
If DMN rules table 'A' has an input 'X' and DMN rules table 'B' has an output of 'X', then pyDMNrules will ensure that DMN rules table 'B' is
is placed in the constructed 'Decision' table before DMN rules table 'A'.
The default order for the remaining table will be the order in which pyDMNrules found them in the workbook.
The function getDecision() will return the 'Decision' table (either supplied or constructed).
## Decision - recommended
A 'Decision' table tells pyDMNrules exacty what to do.
Only the DMN rules tables named in the 'Decision' table will be run (plus any DMN rules tables 'Execute'd
as a result of running the named DMN rules tables).
Without a 'Decision' table, pyDMNrules will run everything, even old, obsolete or test DMN rules tables
that you left in the workbook by mistake.
The exact DMN rules tables which were run, and the order in which they were run is returned be the 'decide()' and 'decidePandas()' functions.
It may not matter the order in which the DMN rules tables are run.
None the less, it may make you decision logic easier for others to understand if they can imagine them being executed in a specific order.
## Decision - required
In certain circumstances a 'Decision' table may be required, because pyDMNrules is unable to determine the correct decision order.
+ DMN rules table 'A' may have 'X' as an input and 'Y' as an output and DMN rules table 'B' may have 'Y' as an input and 'X' as an output.
This may be valid; you may calculate 'Y' from an 'X' approximation and then calculate an exact value of 'X' now that you have a valid value for 'Y'.
To pyDMNrules, this looks like a deadly embrace which it cannot resolve.
+ DMN rules table 'K' may 'Execute' DMN rules table 'L', which in turn will 'Excute' DMN rules table 'K' - an iterative process.
pyDMNrules cannot determine the correct starting point.
+ Input values can be used to programatically determine which DMN rules table to 'Execute'.
If 'PersonType' and 'AddressType' are inputs, then a rule in a DMN rules table could 'Execute' - (PersonType + AddressType).
There would need to be a set of DMN rules tables; for each valid combination of 'PersonType' and 'AddressType', each with the matching DMN rules table name.
pyDMNrules cannot determine runtime logic; it will create a 'Decision' table containing all the DMN rules tables and run them all.
+ The decision may require a DMN rules table to be run more than once.
A 'Decision' table created by pyDMNrules will have one row for each DMN rule table.
The decision logic can legitimately require a rule to be run more than one.
You cannot create iteration loops in pyDMNrules, but if you wanted to calculate the first five terms in a polynomial
then you would repeat the one DMN rules table five times in the 'Decision' table.
All of these examples **require** a user created 'Decision' table in order to ensure the desired decision logic.
There may be other scenario requiring a user created 'Decision' table.
Hence the recommendation to provide one for anything other than the most trivial decisions.
## DMN rules tables
The DMN rules table(s), listed under **Execute Decision Table**, in the 'Decision' table (either supplied or constructed) must exist
on other spreadsheets in the Excel workbook and can be 'Decisions as Rows', 'Decisions as Columns' or 'Decision as Crosstab' rules tables.
### Decision as Rows rules tables
Decisions as Rows DMN rules tables have columns of inputs and columns of outputs,
with a double line vertical border delineating where input columns stop and output columns begin.
- The headings for the input and output columns must be Variables from the Glossary or, for an output column, is can be the word 'Execute'.
- The input test cells under the input heading must contain expressions about the input Variable,
which will evaluate to True or False, depending upon the value of the input Variable.
- The values in the output results cells, under the output headings, are the values that will be assigned to the output Variables, if all the input cells evaluate to True on the same row. If the output heading is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked immediately. Which means any output values already assigned can be overwritten by the invoked Decision Table, and any outputs created by the invoked Decision Table can be overwritten by subsequent outputs in the current Decision Table.
[ExampleRows.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleRows.xlsx) is an example fo a Decision as Rows DMN table.
### Decision as Columns rules tables
Decisions as Columns DMN rules tables have rows of inputs and rows of outputs,
with a double line horizontal border delineating where input rows stop and output rows begin.
- The headings on the left hand side of the decision table, for the input and output rows, must be Variables from the Glossary.
- The input test cells across the row must contain expressions about the input Variable,
which will evalutate to True or False, depending upon the value of the input Variable.
- The values in the output cells, across the row, are the values that will be assigned to the output Variable, if all the input cells evaluate to True in the same column. If the output heading is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked immediately. Which means any output values already assigned can be overwritten by the invoked Decision Table, and any outputs created by the invoked Decision Table can be overwritten by subsequent outputs in the current Decision Table.
[ExampleColumns.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleColumns.xlsx) is an example fo a Decision as Columns DMN table.
### Decision as Crosstab rules tables
Decision as Crosstab DMN rules tables have one output heading at the top left of the table.
- The horizontal and vertical headings, which must be Variables from the Glossary, are the input headings.
- Under the horizontal headings and besides the vertical headings are the input test cells.
- The output results cells form the body of the table and are assigned to the output Variable when the input cells in the same row and same column, all evaluate to True. If the output Variable is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked as part of completing the decision.
[ExampleCrosstab.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleCrosstab.xlsx) is an example fo a Decision as Crosstab DMN table.
The function getSheets() returns all the DMN rules tables.
Each DMN rules table is returned as an XHTML rendering, with all Variables converted to their FEEL name equivalents (BusinessConcept.Attribute).
# Strings:
Decision Model Notation specifies that strings must be enclosed in double quotes ("), as in "this is a string", or be italicized.
pyDMNrules does not look for italicized text, but it does try to interpret unequivocal strings as string.
So, **HIGH,DECLINE** are both strings; they are not numbers, nor dates, nor time periods.
pyDMNrules also recognizes entries from the Glossary, so **Patient.age** is not a string if 'Patient' is a 'Business Concept' in the Glossary
and 'age' is an attribute associated with the 'Patient' Business Concept in the Glossary.
When any expression containing Patient.age is evaluated, Patient.age will be replaced with the current value associated with that Glossary entry.
However, strings that may be ambiguous, must be enclosed in double quotes (").
Any string that contains spaces or a comma is ambiguous and must enclosed in double quotes (").
All strings can be enclosed in double quotes, so HIGH,DECLINE and "HIGH","DECLINE" are equivalent.
# Ambigous strings:
If you don't enclose codes in double quotes the pyDMNrules will try and interpret them. So codes which are all digits will be interpreted as numbers.
Codes that start with a digit, such as 9A42, will cause FEEL errors and must be enclosed in double quotes. FEEL has a syntax for durations. Any code
that looks like a duration, such as P42D (42 days), will need to be enclosed in double quotes.
# USAGE:
import pyDMNrules
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('ExampleHPV.xlsx')
if 'errors' in status:
print('ExampleHPV.xlsx has errors', status['errors'])
sys.exit(0)
else:
print('ExampleHPV.xlsx loaded')
data = {}
data['Participant Age'] = 36
data['In Test of Cure'] = True
data['Hysterectomy Flag'] = False
data['Cancer Flag'] = False
data['HPV-V'] = 'V0'
data['Current Participant Risk Category'] = 'low'
print('Testing',repr(data))
(status, newData) = dmnRules.decide(data)
print('Decision',repr(newData))
if 'errors' in status:
print('With errors', status['errors'])
For a Single Hit Policy DMN rules table, newData will be a decision dictionary of the decision.
For a Multi Hit Policy DMN rules tables newData will be a list of decison dictionaries; one for each matched rule.
For a compound decision (a Decision table with multiple rows of DMN rules tables, where more than one Decision table is run) newData will be a list of decison dictionaries; one for each DMN rules table that is run. However, if only one of the DMN rules tables is run, and it is a Single Hit Policy DMN rules table, then newData will be a simple decision dictionary of the decision.
The keys to each decision dictionary are
- 'Result' - for a Single Hit Policy DMN rules table this will be a dictionary where all the keys will be 'Variables' from the Glossary and the matching the value will be the value of that 'Variable' after the decision was made. For a Multi Hit Policy DMN rules table this will be a list of decision dictionaries, one for each matched rule.
- 'Excuted Rule' - for a Single Hit Policy DMN rules table this will be a tuple of the Decision Table Description ('Decisions' from the 'Decision' table), the DMN rules table name ('Execute Decision Table' from the 'Decision' table) and the Rule number for the rule that matched in that DMN rules Table. For a Multi Hit Policy DMN rules table this will be the a list of tuples, being the Decision Table Description, DMN rules table name and matched Rule number for each matching rule.
- 'DecisionAnnotations'(optional) - list of tuples (heading, value) of the annotations from the 'Decision' table named in the 'Executed Rule' tuple.
- 'RuleAnnotations'(optional) - for a Single Hit Policy DMN rules table, this well be a list of tuples (heading, value) of the annotations for the matching rule, if there were any annotations for the matching rule. For a Multi Hit Policy DMN rules table this will be a list of the lists of any annotations for each matching rule, where an empty list means that the associated matching rule had no annotations.
If the Decision table contains multiple rows (multiple DMN rules tables run sequentially in order to make the decision) then the returned 'newData' will be a list of decision dictionaries, with each containing the keys 'Result', 'Excuted Rule', 'DecisionAnnotations'(optional) and 'RuleAnnotations'(optional), being one list entry for each DMN rules table used from the Decision table. The final enty in this list is the final decision. All other entries are the intermediate states involved in making the final decision.
$ python3 HPV.py
ExampleHPV.xlsx loaded
Testing {'Participant Age': 36, 'In Test of Cure': True, 'Hysterectomy Flag': False, 'Cancer Flag': False, 'HPV-V': 'V0', 'Current Participant Risk Category': 'low'}
Decision(newData) {'Result': {'Immune Deficient Flag': None, 'Hysterectomy Flag': False, 'Cancer Flag': False, 'In Test of Cure': True, 'Participant Age': 36.0, 'Current Participant Risk Category': 'low', 'HPV-V': 'V0', 'Cyto-S': None, 'Cyto-E': None, 'Cyto-O': None, 'Collection Method': None, 'Test Risk Code': 'L', 'New Participant Risk Category': 'low', 'Participant Care Pathway': 'toBeDetermined', 'Next Rule': 'CervicalRisk2'}, 'Executed Rule': ('Determine CervicalRisk', 'FirstTestOfCervicalRisk', '20'), 'DecisionAnnotations': [('Decides', 'Test risk')], 'RuleAnnotations': [('Test meaning', 'need more info')]}
# Pandas functionality
pyDMNrules can pass a Pandas DataFrame of value through the decide() function and return a Pandas DataFrame of decisions. The status of each decision is returned as a Pandas Series and a Pandas DataFrame of information about each decision is also returned.
(dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput)
dfInput is a Pandas DataFrame of rows of data about which decisions need to be made. Column names are mapped to decision Variables.
dfResults is a Pandas DataFrame with one row for each decision. Column names are mapped from all the Variables in the Glossary.
dfStatus is a Pandas Series of one value each decision. Values are the error message, or 'no errors' of there were no errors.
dfDecision is a Pandas DataFrame with columns of 'DecisionName', 'TableName', 'RuleId', 'DecisionAnnotation' and 'RuleAnnotation'
# USAGE:
import pyDMNrules
import pandas as pd
import sys
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('AN-SNAP rules (DMN).xlsx')
if 'errors' in status:
print('AN-SNAP rules (DMN).xlsx has errors', status['errors'])
sys.exit(0)
else:
print('AN-SNAP rules (DMN).xlsx loaded')
dataTypes = {'Patient_Age':int, 'Episode_Length_of_stay':int, 'Phase_Length_of_stay':int,
'Phase_FIM_Motor_Score':int, 'Phase_FIM_Cognition_Score':int, 'Phase_RUG_ADL_Score':int,
'Phase_w01':float, 'Phase_NWAU21':float,
'Indigenous_Status':str, 'Care_Type':str, 'Funding_Source':str, 'Phase_Impairment_Code':str,
'AROC_code':str, 'Phase_AN_SNAP_V4_0_code':str,
'Same_day_addmitted_care':bool, 'Delerium_or_Dimentia':bool, 'RadioTherapy_Flag':bool, 'Dialysis_Flag':bool}
dates = ['BirthDate', 'Admission_Date', 'Discharge_Date', 'Phase_Start_Date', 'Phase_End_Date']
dfInput = pd.read_csv('subAcuteExtract.csv', dtype=dataTypes, parse_dates=dates)
dfInput['Multidisciplinary'] = True
dfInput['Admitted_Flag'] = True
dfInput['Length_of_Stay'] = dfInput['Phase_Length_of_Stay']
dfInput['Long_term_care'] = False
dfInput.loc[dfInput['Length_of_Stay'] > 92, 'Long_term_care'] = True
dfInput['Same_day_admitted_care'] = False
dfInput['GEM_clinic'] = None
dfInput['Patient_Age_Type'] = None
dfInput['First_Phase'] = False
grouped = dfInput.groupby(['Patient_UR', 'Admission_Date'])
for index in grouped.head(1).index:
if dfInput.loc[index]['Phase_Type'] == 'Unstable':
dfInput.loc[index, 'First_Phase'] = True
columns = {'Admitted_Flag':'Admitted Flag', 'Care_Type':'Care Type', 'Length_of_Stay':'Length of Stay', 'Long_term_care':'Long term care',
'Same_day_admitted_care':'Same-day admitted care', 'GEM_clinic':'GEM clinic', 'Patient_Age':'Patient Age', 'Patient_Age_Type':'Patient Age Type',
'AROC_code':'AROC code', 'Delirium_of_Dimentia':'Delirium or Dimentia', 'Phase_Type':'Phase Type', 'First_Phase':'First Phase', 'Phase_FIM_Motor_Score':'FIM Motor score',
'Phase_FIM_Cognition_Score':'FIM Cognition score', 'Phase_RUG_ADL_Score':'RUG-ADL', 'Delirium_or_Dimentia':'Delirium or Dimentia',
'Problem_Severity_Scrore':'Problem Severity Score'}
(dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput, headings=columns)
if dfStatus.where(dfStatus != 'no errors').count() > 0:
print('has errors', dfStatus.loc['status' != 'no errors'])
sys.exit(0)
for index in dfResults.index:
print(index, dfResults.loc[index, 'AN_SNAP_V4_code'])
# Testing
pyDMNrules reserves the spreadsheet name 'Test' which can be used for storing test data.
The function test() reads the test data, passes it through the decide() function and assembles the results which are returned to the caller.
### Unit Test data table(s)
The 'Test' spreadsheet must contain Unit Test data tables.
- Each Unit Test data table must be named with a 'Business Concept'.
- The heading of the table must be Variables from the Glossary associated with the Business Concept.
- The data, in each column, must be valid input data for the associated Variable.
- Each row is considered a unit test data set.
- Unit Test data tables can have 'Annotations'
### DMNrulesTest - the test that will be run
pyDMNrules also searches the 'Test' worksheet for a special table named 'DMNrulesTests' which must exist.
- The 'DMNrulesTests' table has input columns followed by output columns with a double line vertical border delineating where input columns stop and output columns begin.
- The headings for the input columns must be Business Concepts from the Glossary.
- The data in input columns must be one based indexes into the matching unit test data table.
- The headings for the output columns must be Variables from the Glossary.
- The data in output columns will be valid data for the matching Variable and are the expected values returned by the decide() function.
- The 'DMNrulesTests' table can have 'Annotations'
The test() function will process each row in the 'DMNrulesTests' table, getting data from the Unit Test data tables and building a data{} dictionary. The test() function then passes this data{} dictionary to the decide() function. The returned newData{} is then compared to the output data for the matching test in the 'DMNrulesTests' table. The data{}, newData{} and a list of mismatches, if any, is then appended to the list of results, which is eventually passed back to the caller of the test() function.
The returned list is a list of dictionaries, one for each test in the 'DMNrulesTests' table. The keys to this dictionary are
- 'Test ID' - the one based index into the 'DMNrulesTests' table which identifies which test which was run
- 'TestAnnotations'(optional) - the list of annotation for this test - not present if no annotations were present in 'DMNrulesTests'
- 'data' - the dictionary of assembed data passed to the decide() function
- 'newData' - the decision dictionary returned by the decide() function [see above]
- 'DataAnnotations'(optional) - the list of annotations from the unit test data tables, for the unit test sets used in this test - not present if no annotations were persent in any of the unit test data tables for the selected unit test sets.
- 'Mismatches'(optional) - the list of mismatch reports, one for each 'DMNrulesTests' table output value that did not match the value returned from the decide() function - not present if all the data returned from the decide() function matched the values in the 'DMNrulesTest' table.
# Note
If an output value should be the value of an input, then you can use the 'Variable' from the Glossary. However, if the output is a manuipulation of an input, then you will need to use the internal name for that variable, being the 'Business Concept' and the 'Attibute' concateneted with the period character. That is, 'Patient Age' is valid, but 'Patient Age + 5' is not. Instead you will need to use the syntax 'Patient.age + 5'
# USAGE:
import pyDMNrules
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('Therapy.xlsx')
if 'errors' in status:
print('Therapy.xlsx has errors', status['errors'])
sys.exit(0)
else:
print('Therapy.xlsx loaded')
(testStatus, results) = dmnRules.test()
for test in range(len(results)):
if 'Mismatches' not in results[test]:
print('Test ID', results[test]['Test ID'], 'passed')
else:
print('Test ID', results[test]['Test ID'], 'failed')
$ python3 Therapy.py
Test ID 1 passed
Test ID 2 passed
Test ID 3 passed
Decisions(results) [{'Test ID': 1, 'data': {'Encounter Diagnosis': 'Acute Sinusitis', 'Patient Age': 58, 'Patient Allergies': ['Penicillin', 'Streptomycin'], 'Patient Creatinine Level': 2, 'Patient Creatinine Clearance': 44.42, 'Patient Weight': 78, 'Patient Active Medication': 'Coumadin'}, 'newData': {'Result': {'Encounter Diagnosis': 'Acute Sinusitis', 'Recommended Medication': 'Levofloxacin', 'Recommended Dose': '250mg every 24 hours for 14 days', 'Warning': 'Coumadin and Levofloxacin can result in reduced effectiveness of Coumadin.', 'Error Message': None, 'Patient Age': 58.0, 'Patient Weight': 78.0, 'Patient Allergies': ['Penicillin', 'Streptomycin'], 'Patient Creatinine Level': 2.0, 'Patient Creatinine Clearance': 44.416667, 'Patient Active Medication': 'Coumadin'}, 'Executed Rule': ('Check Drug Interaction', 'WarnAboutDrugInteraction', 'Interaction-1')}, 'status': {}}, {'Test ID': 2, 'data': {'Encounter Diagnosis': 'Acute Sinusitis', 'Patient Age': 65, 'Patient Creatinine Level': 1.8, 'Patient Creatinine Clearance': 48.03, 'Patient Weight': 83}, 'newData': {'Result': {'Encounter Diagnosis': 'Acute Sinusitis', 'Recommended Medication': 'Amoxicillin', 'Recommended Dose': '250mg every 24 hours for 14 days', 'Warning': None, 'Error Message': None, 'Patient Age': 65.0, 'Patient Weight': 83.0, 'Patient Allergies': None, 'Patient Creatinine Level': 1.8, 'Patient Creatinine Clearance': 48.032407, 'Patient Active Medication': None}, 'Executed Rule': ('Check Drug Interaction', 'WarnAboutDrugInteraction', 'Interaction-2')}, 'status': {}}, {'Test ID': 3, 'data': {'Encounter Diagnosis': 'Diabetes', 'Patient Age': 27, 'Patient Creatinine Level': 1.88, 'Patient Weight': 110}, 'newData': {'Result': {'Encounter Diagnosis': 'Diabetes', 'Recommended Medication': None, 'Recommended Dose': None, 'Warning': None, 'Error Message': 'Sorry, this decision service can handle only Acute Sinusitis', 'Patient Age': 27.0, 'Patient Weight': 110.0, 'Patient Allergies': None, 'Patient Creatinine Level': 1.88, 'Patient Creatinine Clearance': None, 'Patient Active Medication': None}, 'Executed Rule': ('Create Message', 'ErrorMessage', 'Error-1')}, 'status': {}}]
# NOTE
You can keep the Test worksheet in a separate workbook and load it after you have loaded the rules
status = dmnRules.loadTest('TherapyTests.xlsx')
Documentation:
More details can be found at [readthedocs](https://pyDMNrules.readthedocs.io/en/latest/)
%package -n python3-pyDMNrules
Summary: An implementation of DMN in Python. DMN rules are read from an Excel workbook
Provides: python-pyDMNrules
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-pyDMNrules
# pyDMNrules
An implementation of DMN (Decision Model Notation) in Python, using the [pySFeel](https://pypi.org/project/pySFeel/), [openpyxl](https://pypi.org/project/openpyxl/) and [pandas](httpsL//pypi.org/project/pandas) modules.
DMN rules are read from an Excel workbook.
Then data, matching the input variables in the DMN rules is passed to the decide() function.
The returned data contains the decision.
The passed Excel workbook must contain a 'Decision' tab and may contain a 'Glossary' tab.
Other tabs contain as many DMN rules tables as necessary.
## Glossary - optional
The 'Glossary' tab, if it exists, must contain a table headed 'Glossary'.
A 'Glossary' table lets the user add additional documentation/clarification to the input and output data.
Data items can be grouped in to Business Concepts to better document where inputs come from and where outputs will be going to.
The 'Glossary' table must have exactly three columns with the headings 'Variable', 'Business Concept' and 'Attribute'.
The data in these three columns describe the inputs and outputs associated with the 'Decision'.
'Variable' can be any text and is used to pass data to and from pyDMNrules.
NOTE: the name 'Execute' is a reserved name and cannot be used as a Variable name. The name 'Execute' is reserved as a heading for output columns, output rows or the output variable of a Cross Tabs decision table. The output value(s) in an 'Execute' output column, 'Execute' output row or 'Execute' Cross Tabs decision table must be the name of a Decision Table which will be invoked when the matching rule is triggered. If the output value in an 'Execute' output column, an 'Execute' output or an output cell in an 'Execute' Cross Tabs decision table is missing (and empty cell), then no Decision Table will be invoked whe the matching rule is triggered.
'Business Concept' and 'Attribute' must be valid FEEL names as the 'Variable' will be mapped to a Glossary item created by joining these two FEEL names
with a period character, as in 'Order.orderSize'.
Vertically merged cells in the 'Business Concept' column are used to group multiple 'Variable'/'Attribute' pairs together into a single 'Businss Concept'.
The 'Glossary' can have multiple columns of Annotations to describe things like data types, valid values etc.
Items in the Glossary can be outputs of one decision table and inputs in the next decision table, which makes it easy to support complex business models.
Input decision cells and Output cells can refer to input and output values either by their 'Variable' name, or by their Glossary item (FEEL) name, of 'BusinessConcept.Attribute'
| Glossary | | |
|--------------|----------------------|---------------|
| **Variable** | **Business Concept** | **Attribute** |
| Customer | Customer | sector |
| OrderSize | Order | orderSize |
| Delivery | | delivery |
| Discount | Discount | discount |
If a 'Glossary' tab is not present - if no Glossary is supplied, then pyDMNrules will construct one using the input and output headings.
There will be a single 'Business Concept' called 'Data'.
Attributes will be created by replacing any space characters (' ') with an underscore character ('_') and then removing all **invalid** FEEL name characters.
This can cause conflicts. For instance ':' is a valid character in a Variable, but not in a FEEL name.
If there are two Varibles, being 'C' and 'C:' then both will be transformed to an Attribute of 'C' and a Glossary item of 'Data.C', which will be ambiguous.
This ambiguity can be avoided by supplying a 'Glossary' and explicitely mapping 'C:' to a valid FEEL name, such as 'Ccolon'.
The function getGlossary() will return the Glossary (either supplied or constructed).
## Decision - optional
In order to make a decision, pyDMNrules needs to know where to start, what to do, when and why.
The 'Decision' tab, if it exists, will contain a table headed 'Decision' which will provide the required details.
The heading for the 'Desion' table will be none or more Variable names,
a heading of 'Decisions', a heading of 'Execute Decision Table' and none or more headings for annotations.
The 'Decisions' column is documentation and contain a brief description of the DMN rules table which is named in 'Execute Decision Table' column
which is in effect just a list of DMN rules tables to be run in the specified order.
If there are any 'Variable' columns then these columns must contain valid DMN test as if they were DMN rules tables input columns.
pyDMNrules now knows where to start (with the first DMN rules table), what to do (each DMN rules table in turn), when (when all the 'Variable' tests are 'true')
and why (because all the 'Variable' tests are 'true')
| Decision | | | |
|-------------|--------------------|----------------------------|------------------|
| Variable(s) | **Decisions** | **Execute Decision Table** | Annotation(s) |
| input test | Determine Discount | Discount | Compute discount |
The 'Variable' cells are evaluated on the fly, which means that a preceeding DMN rules table can set or clear
a 'Variable' which can effect which DMN rules tables are included, and which DMN rules tables are excluded,
in the final decision.
The Decision tab, and associated 'Decision' table are optional because in many instances, what to do is obvious.
If the workbook does not contain a 'Decision' tab, then pyDMNrules will construct a 'Decision' table.
If there is only one DMN rules table pyDMNrules will create a 'Decision' table with just one row.
There can be several DMN rules tables that are independant and hence the order doesn't matter.
If there's more than one DMN rules table, pyDMNrules looks for dependancies and works out an acceptable order.
To do this, pyDMNrules looks at the inputs of each DMN rules table and check to see if that input is also an outputs from another DMN rules table.
If DMN rules table 'A' has an input 'X' and DMN rules table 'B' has an output of 'X', then pyDMNrules will ensure that DMN rules table 'B' is
is placed in the constructed 'Decision' table before DMN rules table 'A'.
The default order for the remaining table will be the order in which pyDMNrules found them in the workbook.
The function getDecision() will return the 'Decision' table (either supplied or constructed).
## Decision - recommended
A 'Decision' table tells pyDMNrules exacty what to do.
Only the DMN rules tables named in the 'Decision' table will be run (plus any DMN rules tables 'Execute'd
as a result of running the named DMN rules tables).
Without a 'Decision' table, pyDMNrules will run everything, even old, obsolete or test DMN rules tables
that you left in the workbook by mistake.
The exact DMN rules tables which were run, and the order in which they were run is returned be the 'decide()' and 'decidePandas()' functions.
It may not matter the order in which the DMN rules tables are run.
None the less, it may make you decision logic easier for others to understand if they can imagine them being executed in a specific order.
## Decision - required
In certain circumstances a 'Decision' table may be required, because pyDMNrules is unable to determine the correct decision order.
+ DMN rules table 'A' may have 'X' as an input and 'Y' as an output and DMN rules table 'B' may have 'Y' as an input and 'X' as an output.
This may be valid; you may calculate 'Y' from an 'X' approximation and then calculate an exact value of 'X' now that you have a valid value for 'Y'.
To pyDMNrules, this looks like a deadly embrace which it cannot resolve.
+ DMN rules table 'K' may 'Execute' DMN rules table 'L', which in turn will 'Excute' DMN rules table 'K' - an iterative process.
pyDMNrules cannot determine the correct starting point.
+ Input values can be used to programatically determine which DMN rules table to 'Execute'.
If 'PersonType' and 'AddressType' are inputs, then a rule in a DMN rules table could 'Execute' - (PersonType + AddressType).
There would need to be a set of DMN rules tables; for each valid combination of 'PersonType' and 'AddressType', each with the matching DMN rules table name.
pyDMNrules cannot determine runtime logic; it will create a 'Decision' table containing all the DMN rules tables and run them all.
+ The decision may require a DMN rules table to be run more than once.
A 'Decision' table created by pyDMNrules will have one row for each DMN rule table.
The decision logic can legitimately require a rule to be run more than one.
You cannot create iteration loops in pyDMNrules, but if you wanted to calculate the first five terms in a polynomial
then you would repeat the one DMN rules table five times in the 'Decision' table.
All of these examples **require** a user created 'Decision' table in order to ensure the desired decision logic.
There may be other scenario requiring a user created 'Decision' table.
Hence the recommendation to provide one for anything other than the most trivial decisions.
## DMN rules tables
The DMN rules table(s), listed under **Execute Decision Table**, in the 'Decision' table (either supplied or constructed) must exist
on other spreadsheets in the Excel workbook and can be 'Decisions as Rows', 'Decisions as Columns' or 'Decision as Crosstab' rules tables.
### Decision as Rows rules tables
Decisions as Rows DMN rules tables have columns of inputs and columns of outputs,
with a double line vertical border delineating where input columns stop and output columns begin.
- The headings for the input and output columns must be Variables from the Glossary or, for an output column, is can be the word 'Execute'.
- The input test cells under the input heading must contain expressions about the input Variable,
which will evaluate to True or False, depending upon the value of the input Variable.
- The values in the output results cells, under the output headings, are the values that will be assigned to the output Variables, if all the input cells evaluate to True on the same row. If the output heading is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked immediately. Which means any output values already assigned can be overwritten by the invoked Decision Table, and any outputs created by the invoked Decision Table can be overwritten by subsequent outputs in the current Decision Table.
[ExampleRows.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleRows.xlsx) is an example fo a Decision as Rows DMN table.
### Decision as Columns rules tables
Decisions as Columns DMN rules tables have rows of inputs and rows of outputs,
with a double line horizontal border delineating where input rows stop and output rows begin.
- The headings on the left hand side of the decision table, for the input and output rows, must be Variables from the Glossary.
- The input test cells across the row must contain expressions about the input Variable,
which will evalutate to True or False, depending upon the value of the input Variable.
- The values in the output cells, across the row, are the values that will be assigned to the output Variable, if all the input cells evaluate to True in the same column. If the output heading is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked immediately. Which means any output values already assigned can be overwritten by the invoked Decision Table, and any outputs created by the invoked Decision Table can be overwritten by subsequent outputs in the current Decision Table.
[ExampleColumns.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleColumns.xlsx) is an example fo a Decision as Columns DMN table.
### Decision as Crosstab rules tables
Decision as Crosstab DMN rules tables have one output heading at the top left of the table.
- The horizontal and vertical headings, which must be Variables from the Glossary, are the input headings.
- Under the horizontal headings and besides the vertical headings are the input test cells.
- The output results cells form the body of the table and are assigned to the output Variable when the input cells in the same row and same column, all evaluate to True. If the output Variable is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked as part of completing the decision.
[ExampleCrosstab.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleCrosstab.xlsx) is an example fo a Decision as Crosstab DMN table.
The function getSheets() returns all the DMN rules tables.
Each DMN rules table is returned as an XHTML rendering, with all Variables converted to their FEEL name equivalents (BusinessConcept.Attribute).
# Strings:
Decision Model Notation specifies that strings must be enclosed in double quotes ("), as in "this is a string", or be italicized.
pyDMNrules does not look for italicized text, but it does try to interpret unequivocal strings as string.
So, **HIGH,DECLINE** are both strings; they are not numbers, nor dates, nor time periods.
pyDMNrules also recognizes entries from the Glossary, so **Patient.age** is not a string if 'Patient' is a 'Business Concept' in the Glossary
and 'age' is an attribute associated with the 'Patient' Business Concept in the Glossary.
When any expression containing Patient.age is evaluated, Patient.age will be replaced with the current value associated with that Glossary entry.
However, strings that may be ambiguous, must be enclosed in double quotes (").
Any string that contains spaces or a comma is ambiguous and must enclosed in double quotes (").
All strings can be enclosed in double quotes, so HIGH,DECLINE and "HIGH","DECLINE" are equivalent.
# Ambigous strings:
If you don't enclose codes in double quotes the pyDMNrules will try and interpret them. So codes which are all digits will be interpreted as numbers.
Codes that start with a digit, such as 9A42, will cause FEEL errors and must be enclosed in double quotes. FEEL has a syntax for durations. Any code
that looks like a duration, such as P42D (42 days), will need to be enclosed in double quotes.
# USAGE:
import pyDMNrules
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('ExampleHPV.xlsx')
if 'errors' in status:
print('ExampleHPV.xlsx has errors', status['errors'])
sys.exit(0)
else:
print('ExampleHPV.xlsx loaded')
data = {}
data['Participant Age'] = 36
data['In Test of Cure'] = True
data['Hysterectomy Flag'] = False
data['Cancer Flag'] = False
data['HPV-V'] = 'V0'
data['Current Participant Risk Category'] = 'low'
print('Testing',repr(data))
(status, newData) = dmnRules.decide(data)
print('Decision',repr(newData))
if 'errors' in status:
print('With errors', status['errors'])
For a Single Hit Policy DMN rules table, newData will be a decision dictionary of the decision.
For a Multi Hit Policy DMN rules tables newData will be a list of decison dictionaries; one for each matched rule.
For a compound decision (a Decision table with multiple rows of DMN rules tables, where more than one Decision table is run) newData will be a list of decison dictionaries; one for each DMN rules table that is run. However, if only one of the DMN rules tables is run, and it is a Single Hit Policy DMN rules table, then newData will be a simple decision dictionary of the decision.
The keys to each decision dictionary are
- 'Result' - for a Single Hit Policy DMN rules table this will be a dictionary where all the keys will be 'Variables' from the Glossary and the matching the value will be the value of that 'Variable' after the decision was made. For a Multi Hit Policy DMN rules table this will be a list of decision dictionaries, one for each matched rule.
- 'Excuted Rule' - for a Single Hit Policy DMN rules table this will be a tuple of the Decision Table Description ('Decisions' from the 'Decision' table), the DMN rules table name ('Execute Decision Table' from the 'Decision' table) and the Rule number for the rule that matched in that DMN rules Table. For a Multi Hit Policy DMN rules table this will be the a list of tuples, being the Decision Table Description, DMN rules table name and matched Rule number for each matching rule.
- 'DecisionAnnotations'(optional) - list of tuples (heading, value) of the annotations from the 'Decision' table named in the 'Executed Rule' tuple.
- 'RuleAnnotations'(optional) - for a Single Hit Policy DMN rules table, this well be a list of tuples (heading, value) of the annotations for the matching rule, if there were any annotations for the matching rule. For a Multi Hit Policy DMN rules table this will be a list of the lists of any annotations for each matching rule, where an empty list means that the associated matching rule had no annotations.
If the Decision table contains multiple rows (multiple DMN rules tables run sequentially in order to make the decision) then the returned 'newData' will be a list of decision dictionaries, with each containing the keys 'Result', 'Excuted Rule', 'DecisionAnnotations'(optional) and 'RuleAnnotations'(optional), being one list entry for each DMN rules table used from the Decision table. The final enty in this list is the final decision. All other entries are the intermediate states involved in making the final decision.
$ python3 HPV.py
ExampleHPV.xlsx loaded
Testing {'Participant Age': 36, 'In Test of Cure': True, 'Hysterectomy Flag': False, 'Cancer Flag': False, 'HPV-V': 'V0', 'Current Participant Risk Category': 'low'}
Decision(newData) {'Result': {'Immune Deficient Flag': None, 'Hysterectomy Flag': False, 'Cancer Flag': False, 'In Test of Cure': True, 'Participant Age': 36.0, 'Current Participant Risk Category': 'low', 'HPV-V': 'V0', 'Cyto-S': None, 'Cyto-E': None, 'Cyto-O': None, 'Collection Method': None, 'Test Risk Code': 'L', 'New Participant Risk Category': 'low', 'Participant Care Pathway': 'toBeDetermined', 'Next Rule': 'CervicalRisk2'}, 'Executed Rule': ('Determine CervicalRisk', 'FirstTestOfCervicalRisk', '20'), 'DecisionAnnotations': [('Decides', 'Test risk')], 'RuleAnnotations': [('Test meaning', 'need more info')]}
# Pandas functionality
pyDMNrules can pass a Pandas DataFrame of value through the decide() function and return a Pandas DataFrame of decisions. The status of each decision is returned as a Pandas Series and a Pandas DataFrame of information about each decision is also returned.
(dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput)
dfInput is a Pandas DataFrame of rows of data about which decisions need to be made. Column names are mapped to decision Variables.
dfResults is a Pandas DataFrame with one row for each decision. Column names are mapped from all the Variables in the Glossary.
dfStatus is a Pandas Series of one value each decision. Values are the error message, or 'no errors' of there were no errors.
dfDecision is a Pandas DataFrame with columns of 'DecisionName', 'TableName', 'RuleId', 'DecisionAnnotation' and 'RuleAnnotation'
# USAGE:
import pyDMNrules
import pandas as pd
import sys
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('AN-SNAP rules (DMN).xlsx')
if 'errors' in status:
print('AN-SNAP rules (DMN).xlsx has errors', status['errors'])
sys.exit(0)
else:
print('AN-SNAP rules (DMN).xlsx loaded')
dataTypes = {'Patient_Age':int, 'Episode_Length_of_stay':int, 'Phase_Length_of_stay':int,
'Phase_FIM_Motor_Score':int, 'Phase_FIM_Cognition_Score':int, 'Phase_RUG_ADL_Score':int,
'Phase_w01':float, 'Phase_NWAU21':float,
'Indigenous_Status':str, 'Care_Type':str, 'Funding_Source':str, 'Phase_Impairment_Code':str,
'AROC_code':str, 'Phase_AN_SNAP_V4_0_code':str,
'Same_day_addmitted_care':bool, 'Delerium_or_Dimentia':bool, 'RadioTherapy_Flag':bool, 'Dialysis_Flag':bool}
dates = ['BirthDate', 'Admission_Date', 'Discharge_Date', 'Phase_Start_Date', 'Phase_End_Date']
dfInput = pd.read_csv('subAcuteExtract.csv', dtype=dataTypes, parse_dates=dates)
dfInput['Multidisciplinary'] = True
dfInput['Admitted_Flag'] = True
dfInput['Length_of_Stay'] = dfInput['Phase_Length_of_Stay']
dfInput['Long_term_care'] = False
dfInput.loc[dfInput['Length_of_Stay'] > 92, 'Long_term_care'] = True
dfInput['Same_day_admitted_care'] = False
dfInput['GEM_clinic'] = None
dfInput['Patient_Age_Type'] = None
dfInput['First_Phase'] = False
grouped = dfInput.groupby(['Patient_UR', 'Admission_Date'])
for index in grouped.head(1).index:
if dfInput.loc[index]['Phase_Type'] == 'Unstable':
dfInput.loc[index, 'First_Phase'] = True
columns = {'Admitted_Flag':'Admitted Flag', 'Care_Type':'Care Type', 'Length_of_Stay':'Length of Stay', 'Long_term_care':'Long term care',
'Same_day_admitted_care':'Same-day admitted care', 'GEM_clinic':'GEM clinic', 'Patient_Age':'Patient Age', 'Patient_Age_Type':'Patient Age Type',
'AROC_code':'AROC code', 'Delirium_of_Dimentia':'Delirium or Dimentia', 'Phase_Type':'Phase Type', 'First_Phase':'First Phase', 'Phase_FIM_Motor_Score':'FIM Motor score',
'Phase_FIM_Cognition_Score':'FIM Cognition score', 'Phase_RUG_ADL_Score':'RUG-ADL', 'Delirium_or_Dimentia':'Delirium or Dimentia',
'Problem_Severity_Scrore':'Problem Severity Score'}
(dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput, headings=columns)
if dfStatus.where(dfStatus != 'no errors').count() > 0:
print('has errors', dfStatus.loc['status' != 'no errors'])
sys.exit(0)
for index in dfResults.index:
print(index, dfResults.loc[index, 'AN_SNAP_V4_code'])
# Testing
pyDMNrules reserves the spreadsheet name 'Test' which can be used for storing test data.
The function test() reads the test data, passes it through the decide() function and assembles the results which are returned to the caller.
### Unit Test data table(s)
The 'Test' spreadsheet must contain Unit Test data tables.
- Each Unit Test data table must be named with a 'Business Concept'.
- The heading of the table must be Variables from the Glossary associated with the Business Concept.
- The data, in each column, must be valid input data for the associated Variable.
- Each row is considered a unit test data set.
- Unit Test data tables can have 'Annotations'
### DMNrulesTest - the test that will be run
pyDMNrules also searches the 'Test' worksheet for a special table named 'DMNrulesTests' which must exist.
- The 'DMNrulesTests' table has input columns followed by output columns with a double line vertical border delineating where input columns stop and output columns begin.
- The headings for the input columns must be Business Concepts from the Glossary.
- The data in input columns must be one based indexes into the matching unit test data table.
- The headings for the output columns must be Variables from the Glossary.
- The data in output columns will be valid data for the matching Variable and are the expected values returned by the decide() function.
- The 'DMNrulesTests' table can have 'Annotations'
The test() function will process each row in the 'DMNrulesTests' table, getting data from the Unit Test data tables and building a data{} dictionary. The test() function then passes this data{} dictionary to the decide() function. The returned newData{} is then compared to the output data for the matching test in the 'DMNrulesTests' table. The data{}, newData{} and a list of mismatches, if any, is then appended to the list of results, which is eventually passed back to the caller of the test() function.
The returned list is a list of dictionaries, one for each test in the 'DMNrulesTests' table. The keys to this dictionary are
- 'Test ID' - the one based index into the 'DMNrulesTests' table which identifies which test which was run
- 'TestAnnotations'(optional) - the list of annotation for this test - not present if no annotations were present in 'DMNrulesTests'
- 'data' - the dictionary of assembed data passed to the decide() function
- 'newData' - the decision dictionary returned by the decide() function [see above]
- 'DataAnnotations'(optional) - the list of annotations from the unit test data tables, for the unit test sets used in this test - not present if no annotations were persent in any of the unit test data tables for the selected unit test sets.
- 'Mismatches'(optional) - the list of mismatch reports, one for each 'DMNrulesTests' table output value that did not match the value returned from the decide() function - not present if all the data returned from the decide() function matched the values in the 'DMNrulesTest' table.
# Note
If an output value should be the value of an input, then you can use the 'Variable' from the Glossary. However, if the output is a manuipulation of an input, then you will need to use the internal name for that variable, being the 'Business Concept' and the 'Attibute' concateneted with the period character. That is, 'Patient Age' is valid, but 'Patient Age + 5' is not. Instead you will need to use the syntax 'Patient.age + 5'
# USAGE:
import pyDMNrules
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('Therapy.xlsx')
if 'errors' in status:
print('Therapy.xlsx has errors', status['errors'])
sys.exit(0)
else:
print('Therapy.xlsx loaded')
(testStatus, results) = dmnRules.test()
for test in range(len(results)):
if 'Mismatches' not in results[test]:
print('Test ID', results[test]['Test ID'], 'passed')
else:
print('Test ID', results[test]['Test ID'], 'failed')
$ python3 Therapy.py
Test ID 1 passed
Test ID 2 passed
Test ID 3 passed
Decisions(results) [{'Test ID': 1, 'data': {'Encounter Diagnosis': 'Acute Sinusitis', 'Patient Age': 58, 'Patient Allergies': ['Penicillin', 'Streptomycin'], 'Patient Creatinine Level': 2, 'Patient Creatinine Clearance': 44.42, 'Patient Weight': 78, 'Patient Active Medication': 'Coumadin'}, 'newData': {'Result': {'Encounter Diagnosis': 'Acute Sinusitis', 'Recommended Medication': 'Levofloxacin', 'Recommended Dose': '250mg every 24 hours for 14 days', 'Warning': 'Coumadin and Levofloxacin can result in reduced effectiveness of Coumadin.', 'Error Message': None, 'Patient Age': 58.0, 'Patient Weight': 78.0, 'Patient Allergies': ['Penicillin', 'Streptomycin'], 'Patient Creatinine Level': 2.0, 'Patient Creatinine Clearance': 44.416667, 'Patient Active Medication': 'Coumadin'}, 'Executed Rule': ('Check Drug Interaction', 'WarnAboutDrugInteraction', 'Interaction-1')}, 'status': {}}, {'Test ID': 2, 'data': {'Encounter Diagnosis': 'Acute Sinusitis', 'Patient Age': 65, 'Patient Creatinine Level': 1.8, 'Patient Creatinine Clearance': 48.03, 'Patient Weight': 83}, 'newData': {'Result': {'Encounter Diagnosis': 'Acute Sinusitis', 'Recommended Medication': 'Amoxicillin', 'Recommended Dose': '250mg every 24 hours for 14 days', 'Warning': None, 'Error Message': None, 'Patient Age': 65.0, 'Patient Weight': 83.0, 'Patient Allergies': None, 'Patient Creatinine Level': 1.8, 'Patient Creatinine Clearance': 48.032407, 'Patient Active Medication': None}, 'Executed Rule': ('Check Drug Interaction', 'WarnAboutDrugInteraction', 'Interaction-2')}, 'status': {}}, {'Test ID': 3, 'data': {'Encounter Diagnosis': 'Diabetes', 'Patient Age': 27, 'Patient Creatinine Level': 1.88, 'Patient Weight': 110}, 'newData': {'Result': {'Encounter Diagnosis': 'Diabetes', 'Recommended Medication': None, 'Recommended Dose': None, 'Warning': None, 'Error Message': 'Sorry, this decision service can handle only Acute Sinusitis', 'Patient Age': 27.0, 'Patient Weight': 110.0, 'Patient Allergies': None, 'Patient Creatinine Level': 1.88, 'Patient Creatinine Clearance': None, 'Patient Active Medication': None}, 'Executed Rule': ('Create Message', 'ErrorMessage', 'Error-1')}, 'status': {}}]
# NOTE
You can keep the Test worksheet in a separate workbook and load it after you have loaded the rules
status = dmnRules.loadTest('TherapyTests.xlsx')
Documentation:
More details can be found at [readthedocs](https://pyDMNrules.readthedocs.io/en/latest/)
%package help
Summary: Development documents and examples for pyDMNrules
Provides: python3-pyDMNrules-doc
%description help
# pyDMNrules
An implementation of DMN (Decision Model Notation) in Python, using the [pySFeel](https://pypi.org/project/pySFeel/), [openpyxl](https://pypi.org/project/openpyxl/) and [pandas](httpsL//pypi.org/project/pandas) modules.
DMN rules are read from an Excel workbook.
Then data, matching the input variables in the DMN rules is passed to the decide() function.
The returned data contains the decision.
The passed Excel workbook must contain a 'Decision' tab and may contain a 'Glossary' tab.
Other tabs contain as many DMN rules tables as necessary.
## Glossary - optional
The 'Glossary' tab, if it exists, must contain a table headed 'Glossary'.
A 'Glossary' table lets the user add additional documentation/clarification to the input and output data.
Data items can be grouped in to Business Concepts to better document where inputs come from and where outputs will be going to.
The 'Glossary' table must have exactly three columns with the headings 'Variable', 'Business Concept' and 'Attribute'.
The data in these three columns describe the inputs and outputs associated with the 'Decision'.
'Variable' can be any text and is used to pass data to and from pyDMNrules.
NOTE: the name 'Execute' is a reserved name and cannot be used as a Variable name. The name 'Execute' is reserved as a heading for output columns, output rows or the output variable of a Cross Tabs decision table. The output value(s) in an 'Execute' output column, 'Execute' output row or 'Execute' Cross Tabs decision table must be the name of a Decision Table which will be invoked when the matching rule is triggered. If the output value in an 'Execute' output column, an 'Execute' output or an output cell in an 'Execute' Cross Tabs decision table is missing (and empty cell), then no Decision Table will be invoked whe the matching rule is triggered.
'Business Concept' and 'Attribute' must be valid FEEL names as the 'Variable' will be mapped to a Glossary item created by joining these two FEEL names
with a period character, as in 'Order.orderSize'.
Vertically merged cells in the 'Business Concept' column are used to group multiple 'Variable'/'Attribute' pairs together into a single 'Businss Concept'.
The 'Glossary' can have multiple columns of Annotations to describe things like data types, valid values etc.
Items in the Glossary can be outputs of one decision table and inputs in the next decision table, which makes it easy to support complex business models.
Input decision cells and Output cells can refer to input and output values either by their 'Variable' name, or by their Glossary item (FEEL) name, of 'BusinessConcept.Attribute'
| Glossary | | |
|--------------|----------------------|---------------|
| **Variable** | **Business Concept** | **Attribute** |
| Customer | Customer | sector |
| OrderSize | Order | orderSize |
| Delivery | | delivery |
| Discount | Discount | discount |
If a 'Glossary' tab is not present - if no Glossary is supplied, then pyDMNrules will construct one using the input and output headings.
There will be a single 'Business Concept' called 'Data'.
Attributes will be created by replacing any space characters (' ') with an underscore character ('_') and then removing all **invalid** FEEL name characters.
This can cause conflicts. For instance ':' is a valid character in a Variable, but not in a FEEL name.
If there are two Varibles, being 'C' and 'C:' then both will be transformed to an Attribute of 'C' and a Glossary item of 'Data.C', which will be ambiguous.
This ambiguity can be avoided by supplying a 'Glossary' and explicitely mapping 'C:' to a valid FEEL name, such as 'Ccolon'.
The function getGlossary() will return the Glossary (either supplied or constructed).
## Decision - optional
In order to make a decision, pyDMNrules needs to know where to start, what to do, when and why.
The 'Decision' tab, if it exists, will contain a table headed 'Decision' which will provide the required details.
The heading for the 'Desion' table will be none or more Variable names,
a heading of 'Decisions', a heading of 'Execute Decision Table' and none or more headings for annotations.
The 'Decisions' column is documentation and contain a brief description of the DMN rules table which is named in 'Execute Decision Table' column
which is in effect just a list of DMN rules tables to be run in the specified order.
If there are any 'Variable' columns then these columns must contain valid DMN test as if they were DMN rules tables input columns.
pyDMNrules now knows where to start (with the first DMN rules table), what to do (each DMN rules table in turn), when (when all the 'Variable' tests are 'true')
and why (because all the 'Variable' tests are 'true')
| Decision | | | |
|-------------|--------------------|----------------------------|------------------|
| Variable(s) | **Decisions** | **Execute Decision Table** | Annotation(s) |
| input test | Determine Discount | Discount | Compute discount |
The 'Variable' cells are evaluated on the fly, which means that a preceeding DMN rules table can set or clear
a 'Variable' which can effect which DMN rules tables are included, and which DMN rules tables are excluded,
in the final decision.
The Decision tab, and associated 'Decision' table are optional because in many instances, what to do is obvious.
If the workbook does not contain a 'Decision' tab, then pyDMNrules will construct a 'Decision' table.
If there is only one DMN rules table pyDMNrules will create a 'Decision' table with just one row.
There can be several DMN rules tables that are independant and hence the order doesn't matter.
If there's more than one DMN rules table, pyDMNrules looks for dependancies and works out an acceptable order.
To do this, pyDMNrules looks at the inputs of each DMN rules table and check to see if that input is also an outputs from another DMN rules table.
If DMN rules table 'A' has an input 'X' and DMN rules table 'B' has an output of 'X', then pyDMNrules will ensure that DMN rules table 'B' is
is placed in the constructed 'Decision' table before DMN rules table 'A'.
The default order for the remaining table will be the order in which pyDMNrules found them in the workbook.
The function getDecision() will return the 'Decision' table (either supplied or constructed).
## Decision - recommended
A 'Decision' table tells pyDMNrules exacty what to do.
Only the DMN rules tables named in the 'Decision' table will be run (plus any DMN rules tables 'Execute'd
as a result of running the named DMN rules tables).
Without a 'Decision' table, pyDMNrules will run everything, even old, obsolete or test DMN rules tables
that you left in the workbook by mistake.
The exact DMN rules tables which were run, and the order in which they were run is returned be the 'decide()' and 'decidePandas()' functions.
It may not matter the order in which the DMN rules tables are run.
None the less, it may make you decision logic easier for others to understand if they can imagine them being executed in a specific order.
## Decision - required
In certain circumstances a 'Decision' table may be required, because pyDMNrules is unable to determine the correct decision order.
+ DMN rules table 'A' may have 'X' as an input and 'Y' as an output and DMN rules table 'B' may have 'Y' as an input and 'X' as an output.
This may be valid; you may calculate 'Y' from an 'X' approximation and then calculate an exact value of 'X' now that you have a valid value for 'Y'.
To pyDMNrules, this looks like a deadly embrace which it cannot resolve.
+ DMN rules table 'K' may 'Execute' DMN rules table 'L', which in turn will 'Excute' DMN rules table 'K' - an iterative process.
pyDMNrules cannot determine the correct starting point.
+ Input values can be used to programatically determine which DMN rules table to 'Execute'.
If 'PersonType' and 'AddressType' are inputs, then a rule in a DMN rules table could 'Execute' - (PersonType + AddressType).
There would need to be a set of DMN rules tables; for each valid combination of 'PersonType' and 'AddressType', each with the matching DMN rules table name.
pyDMNrules cannot determine runtime logic; it will create a 'Decision' table containing all the DMN rules tables and run them all.
+ The decision may require a DMN rules table to be run more than once.
A 'Decision' table created by pyDMNrules will have one row for each DMN rule table.
The decision logic can legitimately require a rule to be run more than one.
You cannot create iteration loops in pyDMNrules, but if you wanted to calculate the first five terms in a polynomial
then you would repeat the one DMN rules table five times in the 'Decision' table.
All of these examples **require** a user created 'Decision' table in order to ensure the desired decision logic.
There may be other scenario requiring a user created 'Decision' table.
Hence the recommendation to provide one for anything other than the most trivial decisions.
## DMN rules tables
The DMN rules table(s), listed under **Execute Decision Table**, in the 'Decision' table (either supplied or constructed) must exist
on other spreadsheets in the Excel workbook and can be 'Decisions as Rows', 'Decisions as Columns' or 'Decision as Crosstab' rules tables.
### Decision as Rows rules tables
Decisions as Rows DMN rules tables have columns of inputs and columns of outputs,
with a double line vertical border delineating where input columns stop and output columns begin.
- The headings for the input and output columns must be Variables from the Glossary or, for an output column, is can be the word 'Execute'.
- The input test cells under the input heading must contain expressions about the input Variable,
which will evaluate to True or False, depending upon the value of the input Variable.
- The values in the output results cells, under the output headings, are the values that will be assigned to the output Variables, if all the input cells evaluate to True on the same row. If the output heading is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked immediately. Which means any output values already assigned can be overwritten by the invoked Decision Table, and any outputs created by the invoked Decision Table can be overwritten by subsequent outputs in the current Decision Table.
[ExampleRows.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleRows.xlsx) is an example fo a Decision as Rows DMN table.
### Decision as Columns rules tables
Decisions as Columns DMN rules tables have rows of inputs and rows of outputs,
with a double line horizontal border delineating where input rows stop and output rows begin.
- The headings on the left hand side of the decision table, for the input and output rows, must be Variables from the Glossary.
- The input test cells across the row must contain expressions about the input Variable,
which will evalutate to True or False, depending upon the value of the input Variable.
- The values in the output cells, across the row, are the values that will be assigned to the output Variable, if all the input cells evaluate to True in the same column. If the output heading is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked immediately. Which means any output values already assigned can be overwritten by the invoked Decision Table, and any outputs created by the invoked Decision Table can be overwritten by subsequent outputs in the current Decision Table.
[ExampleColumns.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleColumns.xlsx) is an example fo a Decision as Columns DMN table.
### Decision as Crosstab rules tables
Decision as Crosstab DMN rules tables have one output heading at the top left of the table.
- The horizontal and vertical headings, which must be Variables from the Glossary, are the input headings.
- Under the horizontal headings and besides the vertical headings are the input test cells.
- The output results cells form the body of the table and are assigned to the output Variable when the input cells in the same row and same column, all evaluate to True. If the output Variable is the word 'Execute', then the output value must be the name of a Decision Table, which will be invoked as part of completing the decision.
[ExampleCrosstab.xlsx](https://github.com/russellmcdonell/pyDMNrules/blob/master/ExampleCrosstab.xlsx) is an example fo a Decision as Crosstab DMN table.
The function getSheets() returns all the DMN rules tables.
Each DMN rules table is returned as an XHTML rendering, with all Variables converted to their FEEL name equivalents (BusinessConcept.Attribute).
# Strings:
Decision Model Notation specifies that strings must be enclosed in double quotes ("), as in "this is a string", or be italicized.
pyDMNrules does not look for italicized text, but it does try to interpret unequivocal strings as string.
So, **HIGH,DECLINE** are both strings; they are not numbers, nor dates, nor time periods.
pyDMNrules also recognizes entries from the Glossary, so **Patient.age** is not a string if 'Patient' is a 'Business Concept' in the Glossary
and 'age' is an attribute associated with the 'Patient' Business Concept in the Glossary.
When any expression containing Patient.age is evaluated, Patient.age will be replaced with the current value associated with that Glossary entry.
However, strings that may be ambiguous, must be enclosed in double quotes (").
Any string that contains spaces or a comma is ambiguous and must enclosed in double quotes (").
All strings can be enclosed in double quotes, so HIGH,DECLINE and "HIGH","DECLINE" are equivalent.
# Ambigous strings:
If you don't enclose codes in double quotes the pyDMNrules will try and interpret them. So codes which are all digits will be interpreted as numbers.
Codes that start with a digit, such as 9A42, will cause FEEL errors and must be enclosed in double quotes. FEEL has a syntax for durations. Any code
that looks like a duration, such as P42D (42 days), will need to be enclosed in double quotes.
# USAGE:
import pyDMNrules
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('ExampleHPV.xlsx')
if 'errors' in status:
print('ExampleHPV.xlsx has errors', status['errors'])
sys.exit(0)
else:
print('ExampleHPV.xlsx loaded')
data = {}
data['Participant Age'] = 36
data['In Test of Cure'] = True
data['Hysterectomy Flag'] = False
data['Cancer Flag'] = False
data['HPV-V'] = 'V0'
data['Current Participant Risk Category'] = 'low'
print('Testing',repr(data))
(status, newData) = dmnRules.decide(data)
print('Decision',repr(newData))
if 'errors' in status:
print('With errors', status['errors'])
For a Single Hit Policy DMN rules table, newData will be a decision dictionary of the decision.
For a Multi Hit Policy DMN rules tables newData will be a list of decison dictionaries; one for each matched rule.
For a compound decision (a Decision table with multiple rows of DMN rules tables, where more than one Decision table is run) newData will be a list of decison dictionaries; one for each DMN rules table that is run. However, if only one of the DMN rules tables is run, and it is a Single Hit Policy DMN rules table, then newData will be a simple decision dictionary of the decision.
The keys to each decision dictionary are
- 'Result' - for a Single Hit Policy DMN rules table this will be a dictionary where all the keys will be 'Variables' from the Glossary and the matching the value will be the value of that 'Variable' after the decision was made. For a Multi Hit Policy DMN rules table this will be a list of decision dictionaries, one for each matched rule.
- 'Excuted Rule' - for a Single Hit Policy DMN rules table this will be a tuple of the Decision Table Description ('Decisions' from the 'Decision' table), the DMN rules table name ('Execute Decision Table' from the 'Decision' table) and the Rule number for the rule that matched in that DMN rules Table. For a Multi Hit Policy DMN rules table this will be the a list of tuples, being the Decision Table Description, DMN rules table name and matched Rule number for each matching rule.
- 'DecisionAnnotations'(optional) - list of tuples (heading, value) of the annotations from the 'Decision' table named in the 'Executed Rule' tuple.
- 'RuleAnnotations'(optional) - for a Single Hit Policy DMN rules table, this well be a list of tuples (heading, value) of the annotations for the matching rule, if there were any annotations for the matching rule. For a Multi Hit Policy DMN rules table this will be a list of the lists of any annotations for each matching rule, where an empty list means that the associated matching rule had no annotations.
If the Decision table contains multiple rows (multiple DMN rules tables run sequentially in order to make the decision) then the returned 'newData' will be a list of decision dictionaries, with each containing the keys 'Result', 'Excuted Rule', 'DecisionAnnotations'(optional) and 'RuleAnnotations'(optional), being one list entry for each DMN rules table used from the Decision table. The final enty in this list is the final decision. All other entries are the intermediate states involved in making the final decision.
$ python3 HPV.py
ExampleHPV.xlsx loaded
Testing {'Participant Age': 36, 'In Test of Cure': True, 'Hysterectomy Flag': False, 'Cancer Flag': False, 'HPV-V': 'V0', 'Current Participant Risk Category': 'low'}
Decision(newData) {'Result': {'Immune Deficient Flag': None, 'Hysterectomy Flag': False, 'Cancer Flag': False, 'In Test of Cure': True, 'Participant Age': 36.0, 'Current Participant Risk Category': 'low', 'HPV-V': 'V0', 'Cyto-S': None, 'Cyto-E': None, 'Cyto-O': None, 'Collection Method': None, 'Test Risk Code': 'L', 'New Participant Risk Category': 'low', 'Participant Care Pathway': 'toBeDetermined', 'Next Rule': 'CervicalRisk2'}, 'Executed Rule': ('Determine CervicalRisk', 'FirstTestOfCervicalRisk', '20'), 'DecisionAnnotations': [('Decides', 'Test risk')], 'RuleAnnotations': [('Test meaning', 'need more info')]}
# Pandas functionality
pyDMNrules can pass a Pandas DataFrame of value through the decide() function and return a Pandas DataFrame of decisions. The status of each decision is returned as a Pandas Series and a Pandas DataFrame of information about each decision is also returned.
(dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput)
dfInput is a Pandas DataFrame of rows of data about which decisions need to be made. Column names are mapped to decision Variables.
dfResults is a Pandas DataFrame with one row for each decision. Column names are mapped from all the Variables in the Glossary.
dfStatus is a Pandas Series of one value each decision. Values are the error message, or 'no errors' of there were no errors.
dfDecision is a Pandas DataFrame with columns of 'DecisionName', 'TableName', 'RuleId', 'DecisionAnnotation' and 'RuleAnnotation'
# USAGE:
import pyDMNrules
import pandas as pd
import sys
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('AN-SNAP rules (DMN).xlsx')
if 'errors' in status:
print('AN-SNAP rules (DMN).xlsx has errors', status['errors'])
sys.exit(0)
else:
print('AN-SNAP rules (DMN).xlsx loaded')
dataTypes = {'Patient_Age':int, 'Episode_Length_of_stay':int, 'Phase_Length_of_stay':int,
'Phase_FIM_Motor_Score':int, 'Phase_FIM_Cognition_Score':int, 'Phase_RUG_ADL_Score':int,
'Phase_w01':float, 'Phase_NWAU21':float,
'Indigenous_Status':str, 'Care_Type':str, 'Funding_Source':str, 'Phase_Impairment_Code':str,
'AROC_code':str, 'Phase_AN_SNAP_V4_0_code':str,
'Same_day_addmitted_care':bool, 'Delerium_or_Dimentia':bool, 'RadioTherapy_Flag':bool, 'Dialysis_Flag':bool}
dates = ['BirthDate', 'Admission_Date', 'Discharge_Date', 'Phase_Start_Date', 'Phase_End_Date']
dfInput = pd.read_csv('subAcuteExtract.csv', dtype=dataTypes, parse_dates=dates)
dfInput['Multidisciplinary'] = True
dfInput['Admitted_Flag'] = True
dfInput['Length_of_Stay'] = dfInput['Phase_Length_of_Stay']
dfInput['Long_term_care'] = False
dfInput.loc[dfInput['Length_of_Stay'] > 92, 'Long_term_care'] = True
dfInput['Same_day_admitted_care'] = False
dfInput['GEM_clinic'] = None
dfInput['Patient_Age_Type'] = None
dfInput['First_Phase'] = False
grouped = dfInput.groupby(['Patient_UR', 'Admission_Date'])
for index in grouped.head(1).index:
if dfInput.loc[index]['Phase_Type'] == 'Unstable':
dfInput.loc[index, 'First_Phase'] = True
columns = {'Admitted_Flag':'Admitted Flag', 'Care_Type':'Care Type', 'Length_of_Stay':'Length of Stay', 'Long_term_care':'Long term care',
'Same_day_admitted_care':'Same-day admitted care', 'GEM_clinic':'GEM clinic', 'Patient_Age':'Patient Age', 'Patient_Age_Type':'Patient Age Type',
'AROC_code':'AROC code', 'Delirium_of_Dimentia':'Delirium or Dimentia', 'Phase_Type':'Phase Type', 'First_Phase':'First Phase', 'Phase_FIM_Motor_Score':'FIM Motor score',
'Phase_FIM_Cognition_Score':'FIM Cognition score', 'Phase_RUG_ADL_Score':'RUG-ADL', 'Delirium_or_Dimentia':'Delirium or Dimentia',
'Problem_Severity_Scrore':'Problem Severity Score'}
(dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput, headings=columns)
if dfStatus.where(dfStatus != 'no errors').count() > 0:
print('has errors', dfStatus.loc['status' != 'no errors'])
sys.exit(0)
for index in dfResults.index:
print(index, dfResults.loc[index, 'AN_SNAP_V4_code'])
# Testing
pyDMNrules reserves the spreadsheet name 'Test' which can be used for storing test data.
The function test() reads the test data, passes it through the decide() function and assembles the results which are returned to the caller.
### Unit Test data table(s)
The 'Test' spreadsheet must contain Unit Test data tables.
- Each Unit Test data table must be named with a 'Business Concept'.
- The heading of the table must be Variables from the Glossary associated with the Business Concept.
- The data, in each column, must be valid input data for the associated Variable.
- Each row is considered a unit test data set.
- Unit Test data tables can have 'Annotations'
### DMNrulesTest - the test that will be run
pyDMNrules also searches the 'Test' worksheet for a special table named 'DMNrulesTests' which must exist.
- The 'DMNrulesTests' table has input columns followed by output columns with a double line vertical border delineating where input columns stop and output columns begin.
- The headings for the input columns must be Business Concepts from the Glossary.
- The data in input columns must be one based indexes into the matching unit test data table.
- The headings for the output columns must be Variables from the Glossary.
- The data in output columns will be valid data for the matching Variable and are the expected values returned by the decide() function.
- The 'DMNrulesTests' table can have 'Annotations'
The test() function will process each row in the 'DMNrulesTests' table, getting data from the Unit Test data tables and building a data{} dictionary. The test() function then passes this data{} dictionary to the decide() function. The returned newData{} is then compared to the output data for the matching test in the 'DMNrulesTests' table. The data{}, newData{} and a list of mismatches, if any, is then appended to the list of results, which is eventually passed back to the caller of the test() function.
The returned list is a list of dictionaries, one for each test in the 'DMNrulesTests' table. The keys to this dictionary are
- 'Test ID' - the one based index into the 'DMNrulesTests' table which identifies which test which was run
- 'TestAnnotations'(optional) - the list of annotation for this test - not present if no annotations were present in 'DMNrulesTests'
- 'data' - the dictionary of assembed data passed to the decide() function
- 'newData' - the decision dictionary returned by the decide() function [see above]
- 'DataAnnotations'(optional) - the list of annotations from the unit test data tables, for the unit test sets used in this test - not present if no annotations were persent in any of the unit test data tables for the selected unit test sets.
- 'Mismatches'(optional) - the list of mismatch reports, one for each 'DMNrulesTests' table output value that did not match the value returned from the decide() function - not present if all the data returned from the decide() function matched the values in the 'DMNrulesTest' table.
# Note
If an output value should be the value of an input, then you can use the 'Variable' from the Glossary. However, if the output is a manuipulation of an input, then you will need to use the internal name for that variable, being the 'Business Concept' and the 'Attibute' concateneted with the period character. That is, 'Patient Age' is valid, but 'Patient Age + 5' is not. Instead you will need to use the syntax 'Patient.age + 5'
# USAGE:
import pyDMNrules
dmnRules = pyDMNrules.DMN()
status = dmnRules.load('Therapy.xlsx')
if 'errors' in status:
print('Therapy.xlsx has errors', status['errors'])
sys.exit(0)
else:
print('Therapy.xlsx loaded')
(testStatus, results) = dmnRules.test()
for test in range(len(results)):
if 'Mismatches' not in results[test]:
print('Test ID', results[test]['Test ID'], 'passed')
else:
print('Test ID', results[test]['Test ID'], 'failed')
$ python3 Therapy.py
Test ID 1 passed
Test ID 2 passed
Test ID 3 passed
Decisions(results) [{'Test ID': 1, 'data': {'Encounter Diagnosis': 'Acute Sinusitis', 'Patient Age': 58, 'Patient Allergies': ['Penicillin', 'Streptomycin'], 'Patient Creatinine Level': 2, 'Patient Creatinine Clearance': 44.42, 'Patient Weight': 78, 'Patient Active Medication': 'Coumadin'}, 'newData': {'Result': {'Encounter Diagnosis': 'Acute Sinusitis', 'Recommended Medication': 'Levofloxacin', 'Recommended Dose': '250mg every 24 hours for 14 days', 'Warning': 'Coumadin and Levofloxacin can result in reduced effectiveness of Coumadin.', 'Error Message': None, 'Patient Age': 58.0, 'Patient Weight': 78.0, 'Patient Allergies': ['Penicillin', 'Streptomycin'], 'Patient Creatinine Level': 2.0, 'Patient Creatinine Clearance': 44.416667, 'Patient Active Medication': 'Coumadin'}, 'Executed Rule': ('Check Drug Interaction', 'WarnAboutDrugInteraction', 'Interaction-1')}, 'status': {}}, {'Test ID': 2, 'data': {'Encounter Diagnosis': 'Acute Sinusitis', 'Patient Age': 65, 'Patient Creatinine Level': 1.8, 'Patient Creatinine Clearance': 48.03, 'Patient Weight': 83}, 'newData': {'Result': {'Encounter Diagnosis': 'Acute Sinusitis', 'Recommended Medication': 'Amoxicillin', 'Recommended Dose': '250mg every 24 hours for 14 days', 'Warning': None, 'Error Message': None, 'Patient Age': 65.0, 'Patient Weight': 83.0, 'Patient Allergies': None, 'Patient Creatinine Level': 1.8, 'Patient Creatinine Clearance': 48.032407, 'Patient Active Medication': None}, 'Executed Rule': ('Check Drug Interaction', 'WarnAboutDrugInteraction', 'Interaction-2')}, 'status': {}}, {'Test ID': 3, 'data': {'Encounter Diagnosis': 'Diabetes', 'Patient Age': 27, 'Patient Creatinine Level': 1.88, 'Patient Weight': 110}, 'newData': {'Result': {'Encounter Diagnosis': 'Diabetes', 'Recommended Medication': None, 'Recommended Dose': None, 'Warning': None, 'Error Message': 'Sorry, this decision service can handle only Acute Sinusitis', 'Patient Age': 27.0, 'Patient Weight': 110.0, 'Patient Allergies': None, 'Patient Creatinine Level': 1.88, 'Patient Creatinine Clearance': None, 'Patient Active Medication': None}, 'Executed Rule': ('Create Message', 'ErrorMessage', 'Error-1')}, 'status': {}}]
# NOTE
You can keep the Test worksheet in a separate workbook and load it after you have loaded the rules
status = dmnRules.loadTest('TherapyTests.xlsx')
Documentation:
More details can be found at [readthedocs](https://pyDMNrules.readthedocs.io/en/latest/)
%prep
%autosetup -n pyDMNrules-1.4.4
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-pyDMNrules -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Wed May 31 2023 Python_Bot <Python_Bot@openeuler.org> - 1.4.4-1
- Package Spec generated
|