{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.tree import DecisionTreeClassifier, plot_tree\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np \n",
    "import pandas as pd \n",
    "from sklearn.metrics import confusion_matrix \n",
    "from sklearn.model_selection import train_test_split \n",
    "from sklearn.tree import DecisionTreeClassifier \n",
    "from sklearn.metrics import accuracy_score \n",
    "from sklearn.metrics import classification_report\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "import warnings\n",
    "from sklearn.metrics import mean_squared_error\n",
    "import numpy as np\n",
    "from sklearn.tree import _tree"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def tree_to_decision_table(tree_classifier, feature_names, class_names):\n",
    "   \n",
    "    def update_bounds(current_bounds, threshold, is_left):\n",
    "        \n",
    "        lower_bound, upper_bound = current_bounds\n",
    "        if is_left:\n",
    "            return (lower_bound, min(upper_bound, threshold))\n",
    "        else:\n",
    "            return (max(lower_bound, threshold), upper_bound)\n",
    "\n",
    "    \n",
    "    def format_rule(lower_bound, upper_bound):\n",
    "\n",
    "        if lower_bound == float('-inf') and upper_bound == float('inf'):\n",
    "            return \"-\"\n",
    "        elif lower_bound == float('-inf'):\n",
    "            return f\"<= {upper_bound:.2f}\"\n",
    "        elif upper_bound == float('inf'):\n",
    "            return f\"> {lower_bound:.2f}\"\n",
    "        else:\n",
    "            return f\"({lower_bound:.2f}; {upper_bound:.2f}]\"\n",
    "\n",
    "\n",
    "    tree_ = tree_classifier.tree_\n",
    "    feature = tree_.feature\n",
    "    threshold = tree_.threshold\n",
    "    children_left = tree_.children_left\n",
    "    children_right = tree_.children_right\n",
    "    value = tree_.value\n",
    "\n",
    "    decision_paths = []\n",
    "    bounds = {fn: (float('-inf'), float('inf')) for fn in feature_names}\n",
    "\n",
    "    def traverse(node, current_rule):\n",
    "        if feature[node] == -2:  # Leaf node\n",
    "            predictions = value[node][0]\n",
    "            predicted_class = class_names[np.argmax(predictions)]\n",
    "            formatted_rule = {k: format_rule(*v) for k, v in current_rule.items()}\n",
    "            decision_paths.append({**formatted_rule, 'Class': predicted_class})\n",
    "        else:\n",
    "            name = feature_names[feature[node]]\n",
    "            thres = threshold[node]\n",
    "            left_bounds = update_bounds(current_rule.get(name, (float('-inf'), float('inf'))), thres, True)\n",
    "            right_bounds = update_bounds(current_rule.get(name, (float('-inf'), float('inf'))), thres, False)\n",
    "\n",
    "            left_rule = current_rule.copy()\n",
    "            right_rule = current_rule.copy()\n",
    "            left_rule[name] = left_bounds\n",
    "            right_rule[name] = right_bounds\n",
    "\n",
    "            traverse(children_left[node], left_rule)\n",
    "            traverse(children_right[node], right_rule)\n",
    "\n",
    "    traverse(0, bounds)\n",
    "    decision_table = pd.DataFrame(decision_paths)\n",
    "    decision_table.fillna('-', inplace=True)\n",
    "    columns_sorted = [col for col in feature_names if col in decision_table] + ['Class']\n",
    "    decision_table = decision_table.reindex(columns=columns_sorted)\n",
    "\n",
    "    return decision_table.T\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
