{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Pulmonary embolism\nPulmonary embolism is a blockage in one of the pulmonary arteries in your lungs. In most cases, pulmonary embolism is caused by blood clots that travel to the lungs from deep veins in the legs or, rarely, from veins in other parts of the body (deep vein thrombosis).\n\nBecause the clots block blood flow to the lungs, pulmonary embolism can be life-threatening. However, prompt treatment greatly reduces the risk of death. Taking measures to prevent blood clots in your legs will help protect you against pulmonary embolism.\n![img](https://www.mayoclinic.org/-/media/kcms/gbs/patient-consumer/images/2013/11/15/17/38/ds00223_-ds00429_-ds01005_im01276_mcdc7_pulmonaryembolismthu_jpg.jpg)\n# Symptoms\nPulmonary embolism symptoms can vary greatly, depending on how much of your lung is involved, the size of the clots, and whether you have underlying lung or heart disease.\n\nCommon signs and symptoms include:\n\n* Shortness of breath. This symptom typically appears suddenly and always gets worse with exertion.\n* Chest pain. You may feel like you're having a heart attack. The pain is often sharp and felt when you breathe in deeply, often stopping you from being able to take a deep breath. It can also be felt when you cough, bend or stoop.\n* Cough. The cough may produce bloody or blood-streaked sputum.\n\nOther signs and symptoms that can occur with pulmonary embolism include:\n\n* Rapid or irregular heartbeat\n* Lightheadedness or dizziness\n* Excessive sweating\n* Fever\n* Leg pain or swelling, or both, usually in the calf caused by a deep vein thrombosis\n* Clammy or discolored skin (cyanosis)"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"!conda install -c conda-forge gdcm -y\n!pip install pandas-profiling -y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Setup\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nfrom matplotlib import animation, rc\nimport seaborn as sns\n\nsns.set_style('darkgrid')\nimport pydicom as dcm\nimport scipy.ndimage\nimport gdcm\nimport glob\nimport imageio\nfrom IPython import display\n\nfrom skimage import measure \nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nfrom skimage.morphology import disk, opening, closing\nfrom tqdm import tqdm\n\nfrom IPython.display import HTML\nfrom PIL import Image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\nfrom os import listdir, mkdir\n\npath = \"../input/rsna-str-pulmonary-embolism-detection/\"\nfiles = glob.glob(path+'/train/*/*/*.dcm')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reading Data\ntrain = pd.read_csv(path + \"train.csv\")\ntest = pd.read_csv(path + \"test.csv\")\nprint(\"Train Data Shape:\",train.shape)\nprint(\"Test Data Shape:\",test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head(5).T\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Missing values in train data:',train.isnull().sum().sum())\nprint('Missing values in test data:',test.isnull().sum().sum())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from pandas_profiling import ProfileReport\nprofile = ProfileReport(train, title='Training Data Report')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# EDA"},{"metadata":{"trusted":true},"cell_type":"code","source":"profile.to_notebook_iframe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cols = train.copy()\ncols.drop(['StudyInstanceUID','SeriesInstanceUID','SOPInstanceUID'],axis=1,inplace=True)\ncolumns = cols.columns\n\ncorr = cols.corr()\nmask = np.zeros_like(corr)\nmask[np.triu_indices_from(mask)] = True\nwith sns.axes_style(\"white\"):\n    f, ax = plt.subplots(figsize=(12, 12))\n    ax = sns.heatmap(corr,mask=mask,square=True,linewidths=.8,cmap=\"gnuplot\",annot=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(7,2,figsize=(16,28))\nfor i,col in enumerate(columns): \n    plt.subplot(7,2,i+1)\n    sns.countplot(cols[col],palette=\"gnuplot\")   ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# what is dicom?\nigital Imaging and Communications in Medicine (DICOM) - an international standard related to the exchange, storage and communication of digital medical images. Prior to this format, there was no standardized way to transfer medical scans. So loading up a single patient's study outside the hospital, in older formats took about 10-30 minutes for a single scan!\n\nWhile DICOM 16-bit images (with values ranging from -32768..32767), other 8-bit greyscale images store values 0 - 255. These value ranges in DICOM are useful, as they correlate with the Hounsfield Scale. Each voxel can store a large amount of information.\n\nRead more about it here: https://www.dicomstandard.org/\n\n![img](https://media.giphy.com/media/2kWaWmhoFfFkI/giphy.gif)\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"from random import randint\n# This function reads dicom images from the given path\ndef load_dicom(path):\n    files = listdir(path)\n    f = [dcm.dcmread(path + \"/\" + str(file)) for file in files]\n    return f\n\nrandom_integer = randint(0,len(train))\nexample = path + \"train/\" + train.StudyInstanceUID.values[random_integer] +'/'+ train.SeriesInstanceUID.values[random_integer]\nscans = load_dicom(example)\nscans[randint(0,len(scans))]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, plots = plt.subplots(3, 3, sharex='col', sharey='row', figsize=(15, 15))\nfor i in range(9):\n    plots[i // 3, i % 3].axis('off')\n    plots[i // 3, i % 3].imshow(dcm.dcmread(np.random.choice(files[:3000])).pixel_array,cmap='gist_earth_r')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(10, 10))\nax.imshow(dcm.dcmread(np.random.choice(files[:3000])).pixel_array, cmap=\"gist_earth_r\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_slice(path):\n    slices = [dcm.read_file(path + '/' + s) for s in listdir(path)]\n    slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))\n    try:\n        slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])\n    except:\n        slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)\n        \n    for s in slices:\n        s.SliceThickness = slice_thickness\n        \n    return slices\n\ndef transform_to_hu(slices):\n    images = np.stack([file.pixel_array for file in slices])\n    images = images.astype(np.int16)\n\n    # convert ouside pixel-values to air:\n    # I'm using <= -1000 to be sure that other defaults are captured as well\n    images[images <= -1000] = 0\n    \n    # convert to HU\n    for n in range(len(slices)):\n        \n        intercept = slices[n].RescaleIntercept\n        slope = slices[n].RescaleSlope\n        \n        if slope != 1:\n            images[n] = slope * images[n].astype(np.float64)\n            images[n] = images[n].astype(np.int16)\n            \n        images[n] += np.int16(intercept)\n    \n    return np.array(images, dtype=np.int16)\nfirst_patient = load_slice(path+'/train/0003b3d648eb/d2b2960c2bbf')\nfirst_patient_pixels = transform_to_hu(first_patient)\n\nfig, plots = plt.subplots(8, 10, sharex='col', sharey='row', figsize=(20, 16))\nfor i in range(80):\n    plots[i // 10, i % 10].axis('off')\n    plots[i // 10, i % 10].imshow(first_patient_pixels[i], cmap=\"gray\") ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimageio.mimsave(\"/tmp/gif.gif\", first_patient_pixels, duration=0.08)\ndisplay.Image(filename=\"/tmp/gif.gif\", format='png')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prevention\nPreventing clots in the deep veins in your legs (deep vein thrombosis) will help prevent pulmonary embolism. For this reason, most hospitals are aggressive about taking measures to prevent blood clots, including:\n\n* Blood thinners (anticoagulants). These medications are often given to people at risk of clots before and after an operation — as well as to people admitted to the hospital with medical conditions, such as heart attack, stroke or complications of cancer.\n* Compression stockings. Compression stockings steadily squeeze your legs, helping your veins and leg muscles move blood more efficiently. They offer a safe, simple and inexpensive way to keep blood from stagnating during and after general surgery.\n\n* Leg elevation. Elevating your legs when possible and during the night also can be very effective. Raise the bottom of your bed 4 to 6 inches (10 to 15 cm) with blocks or books.\n\n* Physical activity. Moving as soon as possible after surgery can help prevent pulmonary embolism and hasten recovery overall. This is one of the main reasons your nurse may push you to get up, even on your day of surgery, and walk despite pain at the site of your surgical incision.\n\n* Pneumatic compression. This treatment uses thigh-high or calf-high cuffs that automatically inflate with air and deflate every few minutes to massage and squeeze the veins in your legs and improve blood flow."},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}