### Execute DMN Rules via Command Line Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md Example output of running the DMN decision script from the terminal. ```bash $ 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')]} ``` -------------------------------- ### Initialize DMN Engine Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Creates a new instance of the DMN rules engine. ```python import pyDMNrules # Create a new DMN rules engine dmnRules = pyDMNrules.DMN() ``` -------------------------------- ### Initialize and Test DMN Rules Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md Load a DMN rule set from an Excel file and execute the associated test suite. Check the status dictionary for errors before proceeding with testing. ```python 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') ``` -------------------------------- ### Initialize and Execute pyDMNrules Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md Load an Excel-based DMN rules file and perform a decision based on input data. Ensure the input dictionary keys match the glossary items defined in the Excel file. ```python import pyDMNrules dmnRules = pyDMNrules.DMN() status = dmnRules.load('Example1.xlsx') if 'errors' in status: print('Example1.xlsx has errors', status['errors']) sys.exit(0) else: print('Example1.xlsx loaded') data = {} data['Applicant Age'] = 63 data['Medical History'] = 'bad' (status, newData) = dmnRules.decide(data) if 'errors' in status: print('Failed') ``` -------------------------------- ### Load and Execute DMN Rules Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md Initializes the DMN engine, loads rules from an Excel file, and executes a decision based on a dictionary of input variables. ```python 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']) ``` -------------------------------- ### POST /useTest Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md Configures an already loaded openpyxl workbook object for use in testing. ```APIDOC ## POST /useTest ### Description Uses an already loaded openpyxl workbook object that contains a 'Test' worksheet. ### Method POST ### Endpoint /useTest ### Parameters #### Request Body - **workbook** (openpyxl.workbook) - Required - An openpyxl workbook instance. ### Response #### Success Response (200) - **status** (dict) - Dictionary containing status information, including an 'error' key if issues were encountered. ``` -------------------------------- ### DMN() - Initialize Decision Engine Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Creates a new DMN rules engine instance that can load and execute decision models from Excel workbooks or DMN XML files. ```APIDOC ## DMN() ### Description Creates a new DMN rules engine instance that can load and execute decision models from Excel workbooks or DMN XML files. ### Method Initialization ### Endpoint N/A ### Request Example ```python import pyDMNrules # Create a new DMN rules engine dmnRules = pyDMNrules.DMN() ``` ### Response N/A ``` -------------------------------- ### POST /loadTest Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md Loads an Excel workbook from a file path to be used for subsequent testing operations. ```APIDOC ## POST /loadTest ### Description Loads an Excel workbook that must contain a 'Test' worksheet defining unit tests. ### Method POST ### Endpoint /loadTest ### Parameters #### Request Body - **testBook** (str) - Required - The path to the Excel workbook file. ### Response #### Success Response (200) - **status** (dict) - Dictionary containing status information, including an 'error' key if issues were encountered. ``` -------------------------------- ### Execute Python Script Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md Command to run the Python script and the expected output format showing test results and decision data. ```bash $ 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': {}}] ``` -------------------------------- ### pyDMNrules.DMN Class Methods Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md This section details the methods available within the pyDMNrules.DMN class for loading and interacting with DMN rule sets. ```APIDOC ## DMN.load(rulesBook) ### Description Loads a rulesBook from an Excel workbook. The workbook can contain a 'Glossary' sheet, a 'Decision' sheet, and other sheets with DMN rules tables. ### Method `load` ### Parameters #### Path Parameters - **rulesBook** (str) - Required - The name of the Excel workbook, including the path if it's not in the current working directory. ### Returns - **status** (dict) - A dictionary containing status information. Currently, only `status['error']` is implemented, which lists any errors encountered during loading. ### Notes If no 'Glossary' sheet is provided, one will be created from the input and output headings in the DMN rules tables. Ensure all input 'Variables' are named in an input or output column; dummy columns may be needed for variables used only in calculations. ``` ```APIDOC ## DMN.use(workbook) ### Description Uses an already loaded Excel workbook to apply DMN rules. The workbook can contain a 'Glossary' sheet, a 'Decision' sheet, and other sheets with DMN rules tables. ### Method `use` ### Parameters #### Path Parameters - **workbook** (openpyxl.workbook) - Required - An openpyxl workbook object. ### Returns - **status** (dict) - A dictionary containing status information. Currently, only `status['error']` is implemented, which lists any errors encountered during usage. ### Notes If no 'Glossary' sheet is provided, one will be created from the input and output headings in the DMN rules tables. Ensure all input 'Variables' are named in an input or output column; dummy columns may be needed for variables used only in calculations. ``` ```APIDOC ## DMN.loadXML(DMNxmlFile) ### Description Loads a DMN compliant XML file and builds a rules engine. ### Method `loadXML` ### Parameters #### Path Parameters - **DMNxmlFile** (str) - Required - The name of the DMN compliant file (including path if it is not in the current working directory). ### Returns - **status** (dict) - A dictionary containing status information. Currently, only `status['error']` is implemented, which lists any errors encountered during loading. ``` ```APIDOC ## DMN.useXML(text) ### Description Uses a DMN XML compliant string to build a rules engine. ### Method `useXML` ### Parameters #### Path Parameters - **text** (str) - Required - A string containing a DMN compliant XML structure. ### Returns - **status** (dict) - A dictionary containing status information. Currently, only `status['error']` is implemented, which lists any errors encountered during usage. ``` ```APIDOC ## DMN.getGlossaryNames() ### Description Returns the Glossary Names, which include the name of the glossary and annotation headings. ### Method `getGlossaryNames` ### Parameters **None** ### Returns - **str** - The Glossary Names. ``` ```APIDOC ## DMN.getGlossary() ### Description Returns the Glossary, detailing each Variable within each Business Concept, including its FEEL name, current value, and annotations. ### Method `getGlossary` ### Parameters **None** ### Returns - **dict** - A dictionary where keys are Business Concept names and values are dictionaries. These inner dictionaries have Variable names as keys and tuples containing (FEELname, current value, [annotations]) as values. ``` ```APIDOC ## DMN.getDecisionName() ### Description Returns the Decision Name, which is the heading for the Decision table or the 'name' from the root element in the DMN.xml file. ### Method `getDecisionName` ### Parameters **None** ### Returns - **str** - The Decision Name. ``` -------------------------------- ### POST /test Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md Executes unit tests defined in the 'Test' worksheet of a loaded Excel workbook and returns a comparison of actual vs expected results. ```APIDOC ## POST /test ### Description Reads unit test data and DMNrulesTests from the 'Test' worksheet and runs them through the decide() function. Returns a list of mismatches between returned and expected data. ### Method POST ### Endpoint /test ### Response #### Success Response (200) - **testStatus** (list) - List of status dictionaries returned by decide() for each test. - **results** (list) - List of dictionaries containing Test ID, TestAnnotations, data, newData, DataAnnotations, and Mismatches. ``` -------------------------------- ### Load Separate Test Workbook Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md Load a test suite from a separate Excel workbook after the main rules have been initialized. ```python status = dmnRules.loadTest('TherapyTests.xlsx') ``` -------------------------------- ### test() - Run Unit Tests from Excel Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Executes unit tests defined in the 'Test' worksheet of a loaded workbook. Returns test status and detailed results including any mismatches. ```APIDOC ## test() ### Description Executes unit tests defined in the 'Test' worksheet of a loaded workbook. Returns test status and detailed results including any mismatches. ### Method `test()` ### Parameters None ### Request Example ```python import pyDMNrules import sys dmnRules = pyDMNrules.DMN() status = dmnRules.load('Therapy.xlsx') if 'errors' in status: print('Therapy.xlsx has errors', status['errors']) sys.exit(1) # Run all tests defined in the 'Test' worksheet (testStatus, results) = dmnRules.test() # Check results for each test for test in range(len(results)): test_id = results[test]['Test ID'] if 'Mismatches' not in results[test]: print(f'Test ID {test_id} passed') else: print(f'Test ID {test_id} failed') for mismatch in results[test]['Mismatches']: print(f' Mismatch: {mismatch}') # Access test details print(f" Input data: {results[test]['data']}") print(f" Output data: {results[test]['newData']}") if 'TestAnnotations' in results[test]: print(f" Annotations: {results[test]['TestAnnotations']}") # Check for processing errors if len(testStatus) > 0: print('Test execution errors:', testStatus) ``` ### Response #### Success Response - **testStatus** (list) - A list of errors encountered during test execution. - **results** (list of dict) - A list containing detailed results for each test case. - **Test ID** (string) - The identifier for the test case. - **Mismatches** (list, optional) - A list of mismatches found between expected and actual results. - **data** (dict) - The input data used for the test. - **newData** (dict) - The output data generated by the decision table. - **TestAnnotations** (list, optional) - Annotations associated with the test case. #### Response Example ```json { "testStatus": [], "results": [ { "Test ID": "1", "data": {"Input1": "Value1"}, "newData": {"Output1": "Result1"} }, { "Test ID": "2", "data": {"Input1": "Value2"}, "newData": {"Output1": "Result2"}, "Mismatches": ["Output1: Expected Result3, Got Result2"] } ] } ``` ``` -------------------------------- ### Load DMN Rules from Excel Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Loads an Excel workbook containing decision tables. Returns a status dictionary that should be checked for errors. ```python import pyDMNrules import sys dmnRules = pyDMNrules.DMN() status = dmnRules.load('Therapy.xlsx') if 'errors' in status: print('Failed to load rules:', status['errors']) sys.exit(1) else: print('Rules loaded successfully') # Expected output when successful: # Rules loaded successfully ``` -------------------------------- ### Run DMN Rule Tests Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md Loads an Excel file containing DMN rules and executes tests defined in the 'DMNrulesTests' worksheet. It prints the status of each test, indicating whether it passed or failed, and lists any mismatches found. ```python 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') (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') for failure in range(len(results[test]['Mismatches'])): print(results[test]['Mismatches'][failure]) if 'errors' in testStatus[test]: print('Failed') ``` -------------------------------- ### Retrieve Decision Execution Order Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Displays the sequence in which decision tables are executed. ```python import pyDMNrules dmnRules = pyDMNrules.DMN() status = dmnRules.load('ExampleHPV.xlsx') # Get the decision execution order decisions = dmnRules.getDecision() # First row is headings headings = decisions[0] print('Decision Table Structure:') print(f' Columns: {headings}') # Remaining rows are decision table entries for i, row in enumerate(decisions[1:], 1): print(f'\n Step {i}:') for j, val in enumerate(row): print(f' {headings[j]}: {val}') ``` -------------------------------- ### getGlossary() - Retrieve Variable Definitions Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Returns the Glossary structure showing all Variables organized by Business Concept, including current values and annotations. ```APIDOC ## getGlossary() ### Description Returns the Glossary structure showing all Variables organized by Business Concept, including current values and annotations. ### Method `getGlossary()` ### Parameters None ### Request Example ```python import pyDMNrules dmnRules = pyDMNrules.DMN() status = dmnRules.load('ExampleHPV.xlsx') # Get the glossary (organized by Business Concept) glossary = dmnRules.getGlossary() # Structure: {BusinessConcept: {Variable: (FEELname, currentValue, [annotations])}} for concept in glossary: print(f'\nBusiness Concept: {concept}') for variable in glossary[concept]: feel_name, value, annotations = glossary[concept][variable] print(f' Variable: {variable}') print(f' FEEL name: {feel_name}') print(f' Current value: {value}') if annotations: print(f' Annotations: {annotations}') ``` ### Response #### Success Response - **glossary** (dict) - A dictionary where keys are Business Concepts. Each value is another dictionary where keys are Variable names. The values for each variable are a tuple containing: - **FEELname** (string) - The FEEL name of the variable. - **currentValue** (any) - The current value of the variable (can be None). - **annotations** (list) - A list of annotations associated with the variable. #### Response Example ```json { "Patient": { "Participant Age": ["Patient.Participant_Age", null, ["Integer", "Age in years"]] } } ``` ``` -------------------------------- ### pyDMNrules Unit Testing Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md The 'Test' spreadsheet is reserved for unit test data. Each table within 'Test' must be named with a 'Business Concept' and its heading must match Glossary Variables. Each row represents a test case. ```python # 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' ``` -------------------------------- ### decide() - Execute Decision Logic Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Processes input data through loaded DMN rules and returns the decision result. Takes a dictionary of input variables and returns a tuple of (status, newData). ```APIDOC ## decide() ### Description Processes input data through loaded DMN rules and returns the decision result. Takes a dictionary of input variables and returns a tuple of (status, newData). ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input_data** (dict) - Required - A dictionary where keys are variable names (matching Glossary Variables) and values are the input data for the decision. ### Request Example ```python import pyDMNrules import sys dmnRules = pyDMNrules.DMN() status = dmnRules.load('Therapy.xlsx') if 'errors' in status: print('Therapy.xlsx has errors', status['errors']) sys.exit(1) # Prepare input data - keys must match Variables in the Glossary data = { 'Patient Age': 56, 'Patient Allergies': ['Penicillin', 'Streptomycin'], 'Patient Creatinine Level': 2.0, 'Patient Weight': 78, 'Patient Active Medication': 'Coumadin', 'Encounter Diagnosis': 'Acute Sinusitis' } # Execute the decision (status, newData) = dmnRules.decide(data) if 'errors' in status: print('Decision errors:', status['errors']) else: # For single decision table with Single Hit Policy, newData is a dict # For multiple tables or Multi Hit Policy, newData is a list of dicts if isinstance(newData, list): # Multiple decision tables executed final_result = newData[-1]['Result'] print('Recommended Medication:', final_result.get('Recommended Medication')) print('Recommended Dose:', final_result.get('Recommended Dose')) print('Warning:', final_result.get('Warning')) else: # Single decision table result = newData['Result'] print('Decision Result:', result) print('Executed Rule:', newData['Executed Rule']) ``` ### Response #### Success Response (200) - **status** (dict) - A dictionary indicating the status of the decision execution. May contain 'errors' if issues occurred. - **newData** (dict or list) - The decision results. If a single decision table with Single Hit Policy was executed, this is a dictionary. For multiple tables or Multi Hit Policy, this is a list of dictionaries. #### Response Example (Single Decision Table) ```json { "status": {}, "newData": { "Result": "Some Decision Output", "Executed Rule": "Rule 1" } } ``` #### Response Example (Multiple Decision Tables) ```json { "status": {}, "newData": [ { "Result": { "Intermediate Result": "Value 1" }, "Executed Rule": "Rule A" }, { "Result": { "Recommended Medication": "Levofloxacin", "Recommended Dose": "250mg every 24 hours for 14 days", "Warning": "Coumadin and Levofloxacin can result in reduced effectiveness of Coumadin." }, "Executed Rule": "Rule B" } ] } ``` #### Error Response (400) - **status** (dict) - Contains an 'errors' key with a list of error messages related to the decision execution. #### Error Response Example ```json { "errors": [ "Input variable 'Patient Age' not found in Glossary." ] } ``` ``` -------------------------------- ### load() - Load DMN Rules from Excel Workbook Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Loads an Excel workbook containing DMN decision tables. The workbook may include optional 'Glossary' and 'Decision' sheets, plus one or more sheets with DMN rules tables. ```APIDOC ## load() ### Description Loads an Excel workbook containing DMN decision tables. The workbook may include optional 'Glossary' and 'Decision' sheets, plus one or more sheets with DMN rules tables. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filePath** (string) - Required - The path to the Excel workbook. ### Request Example ```python import pyDMNrules import sys dmnRules = pyDMNrules.DMN() status = dmnRules.load('Therapy.xlsx') if 'errors' in status: print('Failed to load rules:', status['errors']) sys.exit(1) else: print('Rules loaded successfully') ``` ### Response #### Success Response (200) - **status** (dict) - A dictionary containing the status of the load operation. If successful, it may be empty or contain success messages. If errors occurred, it will contain an 'errors' key with a list of error messages. #### Response Example ```json { "status": "Rules loaded successfully" } ``` #### Error Response (400) - **status** (dict) - Contains an 'errors' key with a list of error messages. #### Error Response Example ```json { "errors": [ "Error loading sheet 'Rules': Missing required columns." ] } ``` ``` -------------------------------- ### Batch Process with Pandas Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Processes multiple rows of data using pandas DataFrames. Requires mapping CSV column names to glossary variables. ```python import pyDMNrules import pandas as pd import sys dmnRules = pyDMNrules.DMN() status = dmnRules.load('AN-SNAP rules (DMN).xlsx') if 'errors' in status: print('Failed to load rules:', status['errors']) sys.exit(1) # Define data types for CSV columns dataTypes = { 'Patient_Age': int, 'Episode_Length_of_stay': int, 'Phase_Length_of_stay': int, 'Phase_FIM_Motor_Score': int, 'Phase_FIM_Cognition_Score': int, 'Indigenous_Status': str, 'Care_Type': str, 'Phase_Impairment_Code': str } # Load input data dfInput = pd.read_csv('subAcuteExtract.csv', dtype=dataTypes) # Map CSV column names to Glossary Variable names headings = { 'Patient_Age': 'Patient Age', 'Care_Type': 'Care Type', 'Phase_FIM_Motor_Score': 'FIM Motor score', 'Phase_FIM_Cognition_Score': 'FIM Cognition score' } # Process all rows through decision tables (dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput, headings=headings) # Check for errors in any row errors = dfStatus.where(dfStatus != 'no errors').dropna() if len(errors) > 0: print('Errors found:') for idx, err in errors.items(): print(f' Row {idx}: {err}') else: # Access results for each row for index in dfResults.index: print(f"Row {index}: AN-SNAP Code = {dfResults.loc[index, 'AN_SNAP_V4_code']}") ``` -------------------------------- ### Export Decision Tables as XHTML Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Converts all decision tables into XHTML format for external display or documentation. ```python import pyDMNrules dmnRules = pyDMNrules.DMN() status = dmnRules.load('ExampleRows.xlsx') # Get all decision tables as XHTML sheets = dmnRules.getSheets() # Each key is a table name, value is XHTML representation for table_name, xhtml in sheets.items(): print(f'Table: {table_name}') print(f'XHTML length: {len(xhtml)} characters') # Save to file for viewing with open(f'{table_name}.html', 'w') as f: f.write(xhtml) print(f'Saved to {table_name}.html') ``` -------------------------------- ### Load DMN rules and process data with pyDMNrules Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md Loads DMN rules from an Excel file and processes a pandas DataFrame. Ensure the Excel file and CSV are in the correct path. Data types and date parsing are specified for accurate data handling. ```python 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']) ``` -------------------------------- ### loadTest() - Load Tests from Separate Workbook Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Loads unit test definitions from a separate Excel workbook, allowing test data to be maintained independently from rules. ```APIDOC ## loadTest() - Load Tests from Separate Workbook ### Description Loads unit test definitions from a separate Excel workbook, allowing test data to be maintained independently from rules. ### Method `loadTest(test_workbook_path)` ### Parameters #### Path Parameters - **test_workbook_path** (string) - Required - The file path to the Excel workbook containing the test definitions. ### Request Example ```python import pyDMNrules import sys dmnRules = pyDMNrules.DMN() # Load rules from one workbook status = dmnRules.load('Therapy.xlsx') if 'errors' in status: print('Failed to load rules:', status['errors']) sys.exit(1) # Load tests from a separate workbook status = dmnRules.loadTest('TherapyTests.xlsx') if 'errors' in status: print('Failed to load tests:', status['errors']) sys.exit(1) # Run the tests (testStatus, results) = dmnRules.test() passed = sum(1 for r in results if 'Mismatches' not in r) print(f'{passed}/{len(results)} tests passed') ``` ### Response #### Success Response - **status** (dict) - A dictionary indicating the success or failure of loading the test workbook. If errors occurred, it will contain an 'errors' key. #### Response Example ```json { "status": "success" } ``` #### Error Response Example ```json { "errors": [ "Error loading file: TherapyTests.xlsx - File not found." ] } ``` ``` -------------------------------- ### Execute DMN Rules with Pandas Source: https://github.com/russellmcdonell/pydmnrules/blob/master/README.md Processes a Pandas DataFrame of input data to return decisions as DataFrames and Series. ```python (dfStatus, dfResults, dfDecision) = dmnRules.decidePandas(dfInput) ``` -------------------------------- ### Load DMN rules and process pandas DataFrame Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md Loads DMN rules from an Excel file and applies them to a pandas DataFrame. Includes data type and date parsing configurations. Handles potential errors during loading and processing. ```python 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']) ``` -------------------------------- ### Execute Unit Tests Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Runs tests defined in the 'Test' worksheet of an Excel workbook and iterates through results to identify mismatches. ```python import pyDMNrules import sys dmnRules = pyDMNrules.DMN() status = dmnRules.load('Therapy.xlsx') if 'errors' in status: print('Therapy.xlsx has errors', status['errors']) sys.exit(1) # Run all tests defined in the 'Test' worksheet (testStatus, results) = dmnRules.test() # Check results for each test for test in range(len(results)): test_id = results[test]['Test ID'] if 'Mismatches' not in results[test]: print(f'Test ID {test_id} passed') else: print(f'Test ID {test_id} failed') for mismatch in results[test]['Mismatches']: print(f' Mismatch: {mismatch}') # Access test details print(f" Input data: {results[test]['data']}") print(f" Output data: {results[test]['newData']}") if 'TestAnnotations' in results[test]: print(f" Annotations: {results[test]['TestAnnotations']}") # Check for processing errors if len(testStatus) > 0: print('Test execution errors:', testStatus) ``` -------------------------------- ### Retrieve Variable Glossary Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Extracts variable definitions organized by business concept, including current values and annotations. ```python import pyDMNrules dmnRules = pyDMNrules.DMN() status = dmnRules.load('ExampleHPV.xlsx') # Get the glossary (organized by Business Concept) glossary = dmnRules.getGlossary() # Structure: {BusinessConcept: {Variable: (FEELname, currentValue, [annotations])}} for concept in glossary: print(f'\nBusiness Concept: {concept}') for variable in glossary[concept]: feel_name, value, annotations = glossary[concept][variable] print(f' Variable: {variable}') print(f' FEEL name: {feel_name}') print(f' Current value: {value}') if annotations: print(f' Annotations: {annotations}') ``` -------------------------------- ### getSheets() - Retrieve Decision Tables as XHTML Source: https://context7.com/russellmcdonell/pydmnrules/llms.txt Returns all decision tables formatted as XHTML for display or documentation purposes. ```APIDOC ## getSheets() ### Description Returns all decision tables formatted as XHTML for display or documentation purposes. ### Method `getSheets()` ### Parameters None ### Request Example ```python import pyDMNrules dmnRules = pyDMNrules.DMN() status = dmnRules.load('ExampleRows.xlsx') # Get all decision tables as XHTML sheets = dmnRules.getSheets() # Each key is a table name, value is XHTML representation for table_name, xhtml in sheets.items(): print(f'Table: {table_name}') print(f'XHTML length: {len(xhtml)} characters') # Save to file for viewing with open(f'{table_name}.html', 'w') as f: f.write(xhtml) print(f'Saved to {table_name}.html') ``` ### Response #### Success Response - **sheets** (dict) - A dictionary where keys are the decision table names (strings) and values are the XHTML representations (strings) of each decision table. #### Response Example ```json { "DecisionTable1": "...
", "DecisionTable2": "...
" } ``` ``` -------------------------------- ### decide(data) - Make a Decision Source: https://github.com/russellmcdonell/pydmnrules/blob/master/docs/index.md This function executes the loaded DMN rules with the provided data and returns the resulting decision. ```APIDOC ## decide(data) ### Description Runs the provided data through the loaded DMN rules to produce a decision. ### Method POST ### Endpoint /decide ### Parameters #### Request Body - **data** (dict) - Required - A dictionary containing data for decision making. Keys must match Glossary Variables or Business Concepts. If a key is a Business Concept, its value must be a dictionary where keys match Glossary Variables. ### Request Example ```json { "data": { "input_variable_1": "value1", "business_concept_1": { "nested_variable": "nested_value" } } } ``` ### Response #### Success Response (200) - **tuple** - A tuple containing (status, newData). - **status** (dict) - Contains status information, potentially including an 'error' key with a list of errors if encountered. - **newData** (dict or list) - The decision result. For Single Hit Policy, it's a decision dictionary. For Multi Hit Policy, it's a list of decision dictionaries. If multiple DMN tables are executed, it's a list of dictionaries representing intermediate and final states. - **Result** (dict or list) - Contains decision variables or a list of decision dictionaries for Multi Hit Policy. - **Executed Rule** (tuple or list) - Information about the executed rule(s), including Decision Table Description, DMN rules table name, and Rule number. - **DecisionAnnotations** (optional, list) - Tuples of (heading, value) for annotations from the Decision table. - **RuleAnnotations** (optional, list) - Tuples of (heading, value) for annotations of the matching rule. #### Response Example ```json { "status": {}, "newData": { "Result": { "output_variable": "final_value" }, "Executed Rule": ["Decision Table Description", "DMN Table Name", 1], "RuleAnnotations": [["AnnotationHeading", "AnnotationValue"]] } } ``` ```