{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Working with the med3pa Subpackage\n",
    "-----------------------------------------\n",
    "\n",
    "This tutorial guides you through the process of setting up and running comprehensive experiments using the `med3pa` subpackage. It includes steps to execute MED3pa experiment with `Med3paExperiment` and the combination of MED3pa and Detectron using `Med3paDetectronExperiment`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running the MED3pa Experiment\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 1: Setting up the Datasets\n",
    "First, configure the `DatasetsManager`. In the case of MED3pa only experiment you only need to set the DatasetManager with either `testing` and `reference` dataset:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "\n",
    "sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), '..')))\n",
    "\n",
    "from MED3pa.datasets import DatasetsManager\n",
    "\n",
    "# Initialize the DatasetsManager\n",
    "datasets = DatasetsManager()\n",
    "\n",
    "# Load datasets for reference, and testing\n",
    "datasets.set_from_file(dataset_type=\"reference\", file='./data/test_data.csv', target_column_name='Outcome')\n",
    "datasets.set_from_file(dataset_type=\"testing\", file='./data/test_data_shifted_0.6.csv', target_column_name='Outcome')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Configuring the Model\n",
    "Next, utilize the `ModelFactory` to load a pre-trained model, and set it as the base model for the experiment. Alternatively, you can train your own model and use it:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from MED3pa.models import BaseModelManager, ModelFactory\n",
    "\n",
    "# Initialize the model factory and load the pre-trained model\n",
    "factory = ModelFactory()\n",
    "model = factory.create_model_from_pickled(\"./models/diabetes_xgb_model.pkl\")\n",
    "\n",
    "# Set the base model using BaseModelManager\n",
    "base_model_manager = BaseModelManager()\n",
    "base_model_manager.set_base_model(model=model)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Running the MED3pa Experiment\n",
    "Execute the MED3PA experiment with the specified datasets and base model. You can also specify other parameters as needed. See the documentation of the subpackage for more information about the parameters.\n",
    "\n",
    "The experiment outputs two structure one for the reference set and the other for the testing set, both containing files indicating the extracted profiles at different declaration rates, the performance of the model on these profiles..etc.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running MED3pa Experiment on the reference set:\n",
      "IPC Model training completed.\n",
      "APC Model training completed.\n",
      "Confidence scores calculated for minimum_samples_ratio =  0\n",
      "Results extracted for minimum_samples_ratio =  0\n",
      "Confidence scores calculated for minimum_samples_ratio =  5\n",
      "Results extracted for minimum_samples_ratio =  5\n",
      "Confidence scores calculated for minimum_samples_ratio =  10\n",
      "Results extracted for minimum_samples_ratio =  10\n",
      "Confidence scores calculated for minimum_samples_ratio =  15\n",
      "Results extracted for minimum_samples_ratio =  15\n",
      "Confidence scores calculated for minimum_samples_ratio =  20\n",
      "Results extracted for minimum_samples_ratio =  20\n",
      "Confidence scores calculated for minimum_samples_ratio =  25\n",
      "Results extracted for minimum_samples_ratio =  25\n",
      "Confidence scores calculated for minimum_samples_ratio =  30\n",
      "Results extracted for minimum_samples_ratio =  30\n",
      "Confidence scores calculated for minimum_samples_ratio =  35\n",
      "Results extracted for minimum_samples_ratio =  35\n",
      "Confidence scores calculated for minimum_samples_ratio =  40\n",
      "Results extracted for minimum_samples_ratio =  40\n",
      "Confidence scores calculated for minimum_samples_ratio =  45\n",
      "Results extracted for minimum_samples_ratio =  45\n",
      "Confidence scores calculated for minimum_samples_ratio =  50\n",
      "Results extracted for minimum_samples_ratio =  50\n",
      "Running MED3pa Experiment on the reference set:\n",
      "IPC Model training completed.\n",
      "APC Model training completed.\n",
      "Confidence scores calculated for minimum_samples_ratio =  0\n",
      "Results extracted for minimum_samples_ratio =  0\n",
      "Confidence scores calculated for minimum_samples_ratio =  5\n",
      "Results extracted for minimum_samples_ratio =  5\n",
      "Confidence scores calculated for minimum_samples_ratio =  10\n",
      "Results extracted for minimum_samples_ratio =  10\n",
      "Confidence scores calculated for minimum_samples_ratio =  15\n",
      "Results extracted for minimum_samples_ratio =  15\n",
      "Confidence scores calculated for minimum_samples_ratio =  20\n",
      "Results extracted for minimum_samples_ratio =  20\n",
      "Confidence scores calculated for minimum_samples_ratio =  25\n",
      "Results extracted for minimum_samples_ratio =  25\n",
      "Confidence scores calculated for minimum_samples_ratio =  30\n",
      "Results extracted for minimum_samples_ratio =  30\n",
      "Confidence scores calculated for minimum_samples_ratio =  35\n",
      "Results extracted for minimum_samples_ratio =  35\n",
      "Confidence scores calculated for minimum_samples_ratio =  40\n",
      "Results extracted for minimum_samples_ratio =  40\n",
      "Confidence scores calculated for minimum_samples_ratio =  45\n",
      "Results extracted for minimum_samples_ratio =  45\n",
      "Confidence scores calculated for minimum_samples_ratio =  50\n",
      "Results extracted for minimum_samples_ratio =  50\n"
     ]
    }
   ],
   "source": [
    "from MED3pa.med3pa import Med3paExperiment\n",
    "from MED3pa.med3pa.uncertainty import AbsoluteError\n",
    "\n",
    "# Define parameters for the experiment\n",
    "ipc_params = {'n_estimators': 100}\n",
    "apc_params = {'max_depth': 3}\n",
    "med3pa_metrics = ['Auc', 'Accuracy', 'BalancedAccuracy']\n",
    "\n",
    "# Execute the MED3PA experiment\n",
    "reference_results, test_results = Med3paExperiment.run(\n",
    "                                    datasets_manager=datasets,\n",
    "                                    base_model_manager=base_model_manager,\n",
    "                                    uncertainty_metric=\"absolute_error\",\n",
    "                                    ipc_type='RandomForestRegressor',\n",
    "                                    ipc_params=ipc_params,\n",
    "                                    apc_params=apc_params,\n",
    "                                    samples_ratio_min=0,\n",
    "                                    samples_ratio_max=50,\n",
    "                                    samples_ratio_step=5,\n",
    "                                    med3pa_metrics=med3pa_metrics,\n",
    "                                    evaluate_models=True,\n",
    "                                    models_metrics=['MSE', 'RMSE']\n",
    "                                )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Analyzing and Saving the Results\n",
    "After running the experiment, you can analyze and save the results using the returned `Med3paResults` instance:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save the results to a specified directory\n",
    "reference_results.save(file_path='./med3pa_experiment_results/reference')\n",
    "test_results.save(file_path='./med3pa_experiment_results/test')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running the MED3pa and Detectron Experiment\n",
    "You can also run an experiment that combines the forces of Detectron in covariate shift detection with MED3pa problematic profiles extraction using the `Med3paDetectronExperiment` class. To be able to run this experiment, all datasets of the `DatasetsManager` should be set, alongside the ``BaseModelManager``. This experiment will run MED3pa experiment on the `testing` and `reference` sets and then run the `detectron` experiment on the `testing` set as a whole, and then on the **extracted profiles** from MED3pa:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We will add the training and validation set to the datasets\n",
    "datasets.set_from_file(dataset_type=\"training\", file='./data/train_data.csv', target_column_name='Outcome')\n",
    "datasets.set_from_file(dataset_type=\"validation\", file='./data/val_data.csv', target_column_name='Outcome')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running MED3pa Experiment on the reference set:\n",
      "IPC Model training completed.\n",
      "APC Model training completed.\n",
      "Confidence scores calculated for minimum_samples_ratio =  0\n",
      "Results extracted for minimum_samples_ratio =  0\n",
      "Confidence scores calculated for minimum_samples_ratio =  5\n",
      "Results extracted for minimum_samples_ratio =  5\n",
      "Confidence scores calculated for minimum_samples_ratio =  10\n",
      "Results extracted for minimum_samples_ratio =  10\n",
      "Confidence scores calculated for minimum_samples_ratio =  15\n",
      "Results extracted for minimum_samples_ratio =  15\n",
      "Confidence scores calculated for minimum_samples_ratio =  20\n",
      "Results extracted for minimum_samples_ratio =  20\n",
      "Confidence scores calculated for minimum_samples_ratio =  25\n",
      "Results extracted for minimum_samples_ratio =  25\n",
      "Confidence scores calculated for minimum_samples_ratio =  30\n",
      "Results extracted for minimum_samples_ratio =  30\n",
      "Confidence scores calculated for minimum_samples_ratio =  35\n",
      "Results extracted for minimum_samples_ratio =  35\n",
      "Confidence scores calculated for minimum_samples_ratio =  40\n",
      "Results extracted for minimum_samples_ratio =  40\n",
      "Confidence scores calculated for minimum_samples_ratio =  45\n",
      "Results extracted for minimum_samples_ratio =  45\n",
      "Confidence scores calculated for minimum_samples_ratio =  50\n",
      "Results extracted for minimum_samples_ratio =  50\n",
      "Running MED3pa Experiment on the reference set:\n",
      "IPC Model training completed.\n",
      "APC Model training completed.\n",
      "Confidence scores calculated for minimum_samples_ratio =  0\n",
      "Results extracted for minimum_samples_ratio =  0\n",
      "Confidence scores calculated for minimum_samples_ratio =  5\n",
      "Results extracted for minimum_samples_ratio =  5\n",
      "Confidence scores calculated for minimum_samples_ratio =  10\n",
      "Results extracted for minimum_samples_ratio =  10\n",
      "Confidence scores calculated for minimum_samples_ratio =  15\n",
      "Results extracted for minimum_samples_ratio =  15\n",
      "Confidence scores calculated for minimum_samples_ratio =  20\n",
      "Results extracted for minimum_samples_ratio =  20\n",
      "Confidence scores calculated for minimum_samples_ratio =  25\n",
      "Results extracted for minimum_samples_ratio =  25\n",
      "Confidence scores calculated for minimum_samples_ratio =  30\n",
      "Results extracted for minimum_samples_ratio =  30\n",
      "Confidence scores calculated for minimum_samples_ratio =  35\n",
      "Results extracted for minimum_samples_ratio =  35\n",
      "Confidence scores calculated for minimum_samples_ratio =  40\n",
      "Results extracted for minimum_samples_ratio =  40\n",
      "Confidence scores calculated for minimum_samples_ratio =  45\n",
      "Results extracted for minimum_samples_ratio =  45\n",
      "Confidence scores calculated for minimum_samples_ratio =  50\n",
      "Results extracted for minimum_samples_ratio =  50\n",
      "Running Global Detectron Experiment:\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:12<00:00,  8.24it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on reference set completed.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:13<00:00,  7.19it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Profiled Detectron Experiment:\n",
      "Running Detectron on Profile: *, Age <= -0.8201243877410889 & BloodPressure <= 0.4599476158618927 & Glucose <= -0.06547205429524183\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:13<00:00,  7.30it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on reference set completed.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:07<00:00, 13.59it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Detectron on Profile: *, Age <= -0.8201243877410889 & BloodPressure <= 0.4599476158618927\n",
      "Calibration record on reference set provided, skipping Detectron execution on reference set.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:09<00:00, 10.90it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Detectron on Profile: *, Age <= -0.8201243877410889\n",
      "Calibration record on reference set provided, skipping Detectron execution on reference set.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:12<00:00,  7.87it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Detectron on Profile: *, Age > -0.8201243877410889 & BMI <= -0.550771951675415\n",
      "Calibration record on reference set provided, skipping Detectron execution on reference set.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:13<00:00,  7.23it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Detectron on Profile: *, Age > -0.8201243877410889 & BMI > -0.550771951675415 & Glucose > -1.1373384594917297\n",
      "Calibration record on reference set provided, skipping Detectron execution on reference set.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:17<00:00,  5.84it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Detectron on Profile: *, Age > -0.8201243877410889 & BMI > -0.550771951675415\n",
      "Calibration record on reference set provided, skipping Detectron execution on reference set.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:18<00:00,  5.52it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Detectron on Profile: *, Age > -0.8201243877410889\n",
      "Calibration record on reference set provided, skipping Detectron execution on reference set.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:16<00:00,  5.90it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n",
      "Running Detectron on Profile: *, \n",
      "Calibration record on reference set provided, skipping Detectron execution on reference set.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "running seeds: 100%|██████████| 100/100 [00:16<00:00,  6.10it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Detectron execution on testing set completed.\n"
     ]
    }
   ],
   "source": [
    "from MED3pa.med3pa import Med3paDetectronExperiment\n",
    "from MED3pa.detectron.strategies import EnhancedDisagreementStrategy\n",
    "\n",
    "# Execute the integrated MED3PA and Detectron experiment\n",
    "reference_det_results, test_det_results, detectron_results = Med3paDetectronExperiment.run(\n",
    "    datasets=datasets,\n",
    "    base_model_manager=base_model_manager,\n",
    "    uncertainty_metric=\"absolute_error\",\n",
    "    samples_size=20,\n",
    "    ensemble_size=10,\n",
    "    num_calibration_runs=100,\n",
    "    patience=3,\n",
    "    test_strategies=\"enhanced_disagreement_strategy\",\n",
    "    allow_margin=False,\n",
    "    margin=0.05,\n",
    "    ipc_params=ipc_params,\n",
    "    apc_params=apc_params,\n",
    "    samples_ratio_min=0,\n",
    "    samples_ratio_max=50,\n",
    "    samples_ratio_step=5,\n",
    "    med3pa_metrics=med3pa_metrics,\n",
    "    evaluate_models=True,\n",
    "    models_metrics=['MSE', 'RMSE']\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save the results to a specified directory\n",
    "reference_det_results.save(file_path='./med3pa_detectron_experiment_results/reference')\n",
    "test_det_results.save(file_path='./med3pa_detectron_experiment_results/test')\n",
    "detectron_results.save(file_path='./med3pa_detectron_experiment_results/detectron')\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "det3pa",
   "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
