# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
# Dependencies and Setup
# %matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Hide warning messages in notebook
import warnings
warnings.filterwarnings('ignore')

# File to Load (Remember to Change These)
mouse_drug_data = "data/mouse_drug_data.csv"
clinical_trial_data = "data/clinicaltrial_data.csv"

# Read the Mouse and Drug Data and the Clinical Trial Data
mouse_drug = pd.read_csv(mouse_drug_data)
clinical_trial = pd.read_csv(clinical_trial_data)

# Combine the data into a single dataset
combined_data = pd.merge(clinical_trial, mouse_drug, on = "Mouse ID", how="left")

# Display the data table for preview
combined_data.head()

# -

# ## Tumor Response to Treatment

# Store the Mean Tumor Volume Data Grouped by Drug and Timepoint 
drug_timepoint_vol = combined_data.groupby(["Drug", "Timepoint"])["Tumor Volume (mm3)"]
mean_tumor_volume = drug_timepoint_vol.mean()
# Convert to DataFrame
mean_tumor_volume = mean_tumor_volume.reset_index()
# Preview DataFrame
mean_tumor_volume.head()

# Store the Standard Error of Tumor Volumes Grouped by Drug and Timepoint
drug_timepoint_vol = combined_data.groupby(["Drug", "Timepoint"])["Tumor Volume (mm3)"]
sem_tumor_volume = drug_timepoint_vol.sem()
# Convert to DataFrame
sem_tumor_volume = sem_tumor_volume.reset_index()
# Preview DataFrame
sem_tumor_volume.head()


# Minor Data Munging to Re-Format the Data Frames
mean_volume_drug = mean_tumor_volume.pivot(index="Timepoint", columns="Drug", values="Tumor Volume (mm3)")
# Preview that Reformatting worked
mean_volume_drug.head()

# +
# Generate the Plot (with Error Bars)
capomulin = plt.errorbar(mean_volume_drug.index, mean_volume_drug["Capomulin"],
                         fmt="o", color= "red", ls = "--", lw = 0.5)
infubinol = plt.errorbar(mean_volume_drug.index, mean_volume_drug["Infubinol"], 
                         fmt="^", color= "blue", ls = "--", lw = 0.5)
ketapril = plt.errorbar(mean_volume_drug.index, mean_volume_drug["Ketapril"], 
                        fmt="s", color= "green", ls = "--", lw = 0.5)
placebo = plt.errorbar(mean_volume_drug.index, mean_volume_drug["Placebo"], 
                       fmt="d", color= "black", ls = "--", lw = 0.5)

plt.title("Tumor Response to Treatment")
plt.xlabel("Time (Days)")
plt.ylabel("Tumor Volume (mm3)")
plt.legend(loc= "best")
plt.grid()

# Save the Figure
plt.savefig("images/treatment.png")
# -

# Show the Figure
plt.show()

# ## Metastatic Response to Treatment

# Store the Mean Met. Site Data Grouped by Drug and Timepoint 
drug_timepoint_met = combined_data.groupby(["Drug", "Timepoint"])["Metastatic Sites"]
mean_met = drug_timepoint_met.mean()
# Convert to DataFrame
mean_met = mean_met.reset_index()
# Preview DataFrame
mean_met.head()

# Store the Standard Error associated with Met. Sites Grouped by Drug and Timepoint 
drug_timepoint_met = combined_data.groupby(["Drug", "Timepoint"])["Metastatic Sites"]
standard_error_met = drug_timepoint_met.sem()
# Convert to DataFrame
standard_error_met = standard_error_met.reset_index()
# Preview DataFrame
standard_error_met.head()

# Minor Data Munging to Re-Format the Data Frames
mean_met_drug = mean_met.pivot(index = "Timepoint", columns = "Drug", values = "Metastatic Sites")
# Preview that Reformatting worked
mean_met_drug.head()

# +
# Generate the Plot (with Error Bars)
capomulin = plt.errorbar(mean_met_drug.index, mean_met_drug["Capomulin"],
                         fmt="o", color= "red", ls = "--", lw = 0.5)
infubinol = plt.errorbar(mean_met_drug.index, mean_met_drug["Infubinol"], 
                         fmt="^", color= "blue", ls = "--", lw = 0.5)
ketapril = plt.errorbar(mean_met_drug.index, mean_met_drug["Ketapril"], 
                        fmt="s", color= "green", ls = "--", lw = 0.5)
placebo = plt.errorbar(mean_met_drug.index, mean_met_drug["Placebo"], 
                       fmt="d", color= "black", ls = "--", lw = 0.5)

plt.title("Metastatic Spread During Treatment")
plt.xlabel("Time Duration(Days)")
plt.ylabel("Met. Sites")
plt.legend(loc= "best")
plt.grid()

# Save the Figure
plt.savefig("images/spread.png")
# Show the Figure
plt.show()
# -

# ## Survival Rates

# +
# Store the Count of Mice Grouped by Drug and Timepoint (W can pass any metric)
drug_timepoint_mice = combined_data.groupby(["Drug", "Timepoint"])["Mouse ID"]
mice_count = drug_timepoint_mice.nunique()

# Convert to DataFrame
mice_count = mice_count.reset_index()
mice_count = mice_count.rename(columns={"Mouse ID": "Mouse Count"})
# Preview DataFrame
mice_count.head()
# -

# Minor Data Munging to Re-Format the Data Frames
mice_count_drug = mice_count.pivot(index = "Timepoint", columns = "Drug", values = "Mouse Count")
# Preview the Data Frame
mice_count_drug.head()

# +
# Generate the Plot (Accounting for percentages)
capomulin = plt.errorbar(mice_count_drug.index, mice_count_drug["Capomulin"],
                         fmt="o", color= "red", ls = "--", lw = 0.5)
infubinol = plt.errorbar(mice_count_drug.index, mice_count_drug["Infubinol"], 
                         fmt="^", color= "blue", ls = "--", lw = 0.5)
ketapril = plt.errorbar(mice_count_drug.index, mice_count_drug["Ketapril"], 
                        fmt="s", color= "green", ls = "--", lw = 0.5)
placebo = plt.errorbar(mice_count_drug.index, mice_count_drug["Placebo"], 
                       fmt="d", color= "black", ls = "--", lw = 0.5)

plt.title("Survival During Treatment")
plt.xlabel("Time (Days)")
plt.ylabel("Survival Rate (%)")
plt.legend(loc= "best")
plt.grid()
# Save the Figure
plt.savefig("images/survival.png")
# Show the Figure
plt.show()
# -

# ## Summary Bar Graph

# Calculate the percent changes for each drug
percentage_change = ((mean_volume_drug.iloc[-1]-mean_volume_drug.iloc[0])/mean_volume_drug.iloc[0])*100
# Display the data to confirm
percentage_change

# +
# Store all Relevant Percent Changes into a Tuple
drug_list = ["Capomulin", "Infubinol", "Ketapril", "Placebo"]
change_list = [percentage_change["Capomulin"],percentage_change["Infubinol"], 
               percentage_change["Ketapril"],percentage_change["Placebo"]]
# Splice the data between passing and failing drugs
colors = []
for change in change_list:
    if change > 0:
        colors.append("r")
    else:
        colors.append("g")
# Orient widths. Add labels, tick marks, etc. 
drug_plot = plt.bar(drug_list, change_list, width = -1, align = "edge", color = colors)
plt.title("Tumor Change Over 45 Day Treatment")
plt.ylabel("% Tumor Volume Change")
plt.ylim(-30, 70)
plt.grid()
# Use functions to label the percentages of changes
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        if height > 0:
            location = 2
        else:
            location = -8
        plt.text(rect.get_x() + rect.get_width()/2, location,"%d" % int(height)+"%", 
                 ha="center", va="bottom", color="white")
        
# Call functions to implement the function calls
autolabel(drug_plot)

# Save the Figure
plt.savefig("images/change.png")

# Show the Figure
plt.show()
# -



StarcoderdataJupyterScriptsDedupFiltered