{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Let us first import all the necessary packages required for our analysis"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport os\nimport glob\nfrom tqdm.auto import tqdm\nimport pydicom\nfrom matplotlib import pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!conda install -c conda-forge gdcm -y","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### In the following analysis our aim would be just to gain insights about a patients' OSIC Pulmonary Fibrosis condition based on CT scan reports, FVC score and Percent. \n\n### Later on we would do the task of predictive modelling where we would use these data and insights to predict a patient's FVC score along with the confidence for a future date."},{"metadata":{},"cell_type":"markdown","source":"### Let us import the train data"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = pd.read_csv(\"/kaggle/input/osic-pulmonary-fibrosis-progression/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Getting a list of unique patients from the train data"},{"metadata":{"trusted":true},"cell_type":"code","source":"unique_patients = train_data[\"Patient\"].unique()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Let us iterate over every unique patient and get a detailed report in the form of an image"},{"metadata":{"trusted":true},"cell_type":"code","source":"for patient in tqdm(unique_patients,total=len(unique_patients)):\n    patient_ID = glob.glob(\"/kaggle/input/osic-pulmonary-fibrosis-progression/train/\"+str(patient)+\"/*.dcm\")\n    patient_subset = train_data[train_data[\"Patient\"]==patient]\n    patient_info = {\"ID\":patient_subset[\"Patient\"].unique()[0],\n                    \"Age\":patient_subset[\"Age\"].unique()[0],\n                    \"Sex\":patient_subset[\"Sex\"].unique()[0],\n                    \"Smoking Status\":patient_subset[\"SmokingStatus\"].unique()[0]}\n    f = plt.figure(figsize=(15,10))\n    #plt.tight_layout()\n    plt.suptitle(\"Patient ID : {}    Age : {}     Sex : {}    Smoking Status : {}\".format(patient_info[\"ID\"],patient_info[\"Age\"],patient_info[\"Sex\"],patient_info[\"Smoking Status\"]),fontsize=16)\n    for i,week in enumerate(patient_subset[\"Weeks\"]):\n        file_path = \"/kaggle/input/osic-pulmonary-fibrosis-progression/train/\"+str(patient)+\"/\"+str(week)+\".dcm\"\n        patient_fvc = patient_subset[patient_subset[\"Weeks\"]==week][\"FVC\"].values[0]\n        patient_percent = patient_subset[patient_subset[\"Weeks\"]==week][\"Percent\"].values[0]\n        \n        try:\n            file = pydicom.dcmread(file_path)\n            total_size = len(patient_subset[\"Weeks\"])\n            cols = 3\n            rows = np.ceil(total_size / 3)\n        \n            plt.subplot(rows,cols,i+1)\n            plt.figsize=(10,10)\n            #plt.subplots_adjust(top=0.85)\n            #plt.tight_layout(pad=2)\n            plt.imshow(file.pixel_array,cmap=plt.cm.bone)\n            plt.axis(\"off\")\n            plt.title(\"Week : {} , FVC : {} , Percent : {} %\".format(week,patient_fvc,np.round(patient_percent,2)))\n        except FileNotFoundError:\n            print(\"File not found in kaggle input data repository\")\n        except:\n            print(\"Error due to gdcm\")\n        \n    plt.savefig(\"report_\"+str(patient_info[\"ID\"])+\".jpg\")","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}