Peform relative log abundance analysis

Perform relative log abundance analysis using data for named metabolites from the metabolomics workbench or uploaded data files.

Note: This notebook contains IPython widgets. Consequently, you won't be able to use Kernal/Restart & Restart command to automatically execute all cells in the notebook. You must use Run command individually to execute each cell and advance to the next cell.

Import Python modules...

In [ ]:
from __future__ import print_function

import os
import sys
import time
import re

import requests

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

import ipywidgets as widgets

from IPython.display import display, HTML
from IPython import __version__ as ipyVersion

# Import MW modules from the current directory or default Python directory...
import MWUtil

%matplotlib inline

print("Python: %s.%s.%s" % sys.version_info[:3])
print("IPython: %s" % ipyVersion)

print()
print(time.asctime())

The URL PATH

The MW REST URL consists of three main parts, separated by forward slashes, after the common prefix specifying the invariant base URL (https://www.metabolomicsworkbench.org/rest/):

https://www.metabolomicsworkbench.org/rest/context/input_specification/output_specification

Part 1: The context determines the type of data to be accessed from the Metabolomics Workbench, such as metadata or results related to the submitted studies, data from metabolites, genes/proteins and analytical chemistry databases as well as other services related to mass spectrometry and metabolite identification:

context = study | compound | refmet | gene | protein | moverz | exactmass

Part 2: The input specification consists of two required parameters describing the REST request:

input_specification = input_item/input_value

Part 3: The output specification consists of two parameters describing the output generated by the REST request:

output_specification = output_item/(output_format)

The first parameter is required in most cases. The second parameter is optional. The input and output specifications are context sensitive. The context determines the values allowed for the remaining parameters in the input and output specifications as detailed in the sections below.

Setup MW REST base URL...

In [ ]:
MWBaseURL = "https://www.metabolomicsworkbench.org/rest"

Retrieve or upload data for named metabolites...

In [ ]:
# Initialize data...
StudiesResultsData = None
RetrievedMWData = None
In [ ]:
# Set up UIF info text...
TopInfoTextHTML = widgets.HTML(value = "<strong>Retrieve or upload data and process any missing values</strong>", 
                               placeholder='', description='')

# Setup UIF to process any missing values...
MissingValuesMethods = ["NoAction", "DeleteRows", "DeleteColumns", "ReplaceByColumnMean", "ReplaceColumnMedian", "ReplaceByZero" , "LinearInterpolation"]
MissingValuesMethodsDropdown = widgets.Dropdown(options = MissingValuesMethods,
                                                value = "NoAction",
                                                description = " ")
ProcessMissingValueTopTextHTML = widgets.HTML(value = "Method for processing missing values:", 
                                              placeholder='', description='')

# Setup UIF to retrieve...
StudyIDText = widgets.Text(value = "ST000001 ST000002", description = "Study ID (s)",
                           placeholder = "Type study ID", disabled = False,
                           layout = widgets.Layout(margin='0 10px 0 0'))
RetrieveDataBtn = widgets.Button(description = 'Retrieve Data', disabled = False, button_stype = '',
                                 tooltip = "Retrieve data for study ID")

RetrieveDataOutput = widgets.Output()
def RetrieveDataBtnEventHandler(Object):
    global StudiesResultsData, RetrievedMWData
    
    RetrievedMWData = True
    StudiesResultsData = None
    
    StudyIDs = StudyIDText.value
    MissingValuesMethod = MissingValuesMethodsDropdown.value
    
    RetrieveDataOutput.clear_output()
    UploadDataOutput.clear_output()
    with RetrieveDataOutput:
        if len(StudyIDs):
            print("\nProcessing study ID(s): %s" % StudyIDs)
            StudiesResultsData = MWUtil.RetrieveStudiesAnalysisAndResultsData(StudyIDs, MWBaseURL, MissingValuesMethod)
            DisplayData = False if len(StudiesResultsData.keys()) > 5 else True
            MWUtil.ListStudiesAnalysisAndResultsData(StudiesResultsData, DisplayDataFrame = DisplayData,
                                              IPythonDisplayFuncRef = display, IPythonHTMLFuncRef = HTML)
        else:
            print("\nNo study ID(s) specified...")

RetrieveDataBtn.on_click(RetrieveDataBtnEventHandler)

# Setup UIF to upload data file(s)...
FileUploadBtn = widgets.FileUpload(description = 'Upload File(s)', accept='.csv,.txt,.tsv', multiple = True,
                                  disabled = False)
FileUploadTextHTML = widgets.HTML(value = "<strong>File format:</strong> Col 1: Sample names; \
                                Col 2: Class identifiers; Remaining cols: Named metabolites; \
                                <strong>Exts: </strong>.csv, .txt, or .tsv", placeholder='', description='')

UploadDataOutput = widgets.Output()
def FileUploadBtnEventHandler(Change):
    global StudiesResultsData, RetrievedMWData
    
    RetrievedMWData = False
    StudiesResultsData = None
    
    MissingValuesMethod = MissingValuesMethodsDropdown.value
    UploadedDataInfo = FileUploadBtn.value
    
    RetrieveDataOutput.clear_output()
    UploadDataOutput.clear_output()
    with UploadDataOutput:
        StudiesResultsData = MWUtil.RetrieveUploadedData(UploadedDataInfo, MissingValuesMethod)
        DisplayData = False if len(StudiesResultsData.keys()) > 5 else True
        MWUtil.ListStudiesAnalysisAndResultsData(StudiesResultsData, DisplayDataFrame = DisplayData,
                                                IPythonDisplayFuncRef = display, IPythonHTMLFuncRef = HTML)
        
FileUploadBtn.observe(FileUploadBtnEventHandler, names = 'value')

# Setup UIF to retrieve or upload data file...

DataWarningTextHTML = widgets.HTML(value = "<div class='alert alert-warning'><strong>Warning:</strong> Don't re-run the current cell after specifying study ID(s) or selecting file(s) and retrieving the data. Click on the next cell to advance.</div>", placeholder='', description='')
OrTextHTML = widgets.HTML(value = "<strong>Or</strong>", placeholder='', description='')

UIFDataBoxes = []
UIFDataBoxes.append(widgets.HBox([TopInfoTextHTML]))
UIFDataBoxes.append(widgets.HBox([ProcessMissingValueTopTextHTML, MissingValuesMethodsDropdown]))
UIFDataBoxes.append(widgets.HBox([StudyIDText, RetrieveDataBtn],
                                 layout = widgets.Layout(margin='10px 0 0 0')))
UIFDataBoxes.append(widgets.HBox([OrTextHTML]))
UIFDataBoxes.append(widgets.HBox([FileUploadBtn]))
UIFDataBoxes.append(widgets.HBox([FileUploadTextHTML]))
UIFDataBoxes.append(widgets.HBox([DataWarningTextHTML]))

for UIFDataBox in UIFDataBoxes:
    display(UIFDataBox)

display(RetrieveDataOutput)
display(UploadDataOutput)
In [ ]:
MWUtil.CheckAndWarnEmptyStudiesData(StudiesResultsData, RetrievedMWData, StudyIDText.value)

Setup UIF for selecting and plotting available data...

In [ ]:
# Setup UIF data...
StudiesUIFData = MWUtil.SetupUIFDataForStudiesAnalysisAndResults(StudiesResultsData, MinClassCount = None)
In [ ]:
MWUtil.CheckAndWarnEmptyStudiesUIFData(StudiesUIFData, RetrievedMWData, StudyIDText.value)
In [ ]:
# Setup a function to calculate relative log abundance and generate dataframe for the plot...
def GenerateRLAData(InputDataFrame, Mode = "AcrossClasses", ClassColID = "Class", ClassNumColID = "ClassNum"):
    """Calculate RLA and generate data frames. """
    
    DataFrame = InputDataFrame.copy()
    
    # Drop Class column...
    TrackColIDs = []
    if ClassColID is not None:
        DataFrame = DataFrame.drop(ClassColID, axis = 1)
        TrackColIDs.append(ClassColID)
    
    if ClassNumColID is not None:
        TrackColIDs.append(ClassNumColID)
    
    if re.match("^WithinClasses$", Mode, re.I):
        UniqueClassNums = DataFrame[ClassNumColID].unique()
        
        ClassDataFrames = []
        for ClassNum in UniqueClassNums:
            ClassDataFrame = DataFrame[DataFrame[ClassNumColID] == ClassNum]
            ClassDataFrame = ClassDataFrame.drop(ClassNumColID, axis = 1)
            
            ClassDataFrame = np.log(ClassDataFrame)
            ClassDataFrame = ClassDataFrame - ClassDataFrame.median()
            
            ClassDataFrames.append(ClassDataFrame)
            
        PlotDataFrame = pd.concat(ClassDataFrames)
    else:
        # Across classes...
        if ClassNumColID is not None:
            DataFrame = DataFrame.drop(ClassNumColID, axis = 1)
    
        PlotDataFrame = np.log(DataFrame)
        PlotDataFrame = PlotDataFrame - PlotDataFrame.median()
    
    # Setup RLA data frame containing class information...
    RLADataFrame = PlotDataFrame.copy()
    RLADataFrame = RLADataFrame.applymap("{0:.4f}".format)
    if len(TrackColIDs):
        TrackedColsDataFrame = InputDataFrame[TrackColIDs]
        RLADataFrame = pd.concat([TrackedColsDataFrame, RLADataFrame], axis = 1)
    
    # Transpose data for plotting columns corresponding to sample IDs...
    PlotDataFrame = PlotDataFrame.transpose()
    
    return (PlotDataFrame, RLADataFrame)
    
In [ ]:
# Setup UIF...
FirstStudyID = StudiesUIFData["StudyIDs"][0]
StudiesDropdown = widgets.Dropdown(options = StudiesUIFData["StudyIDs"], value = FirstStudyID, 
                                   description="Study:", disabled = False)

FirstAnalysisID = StudiesUIFData["AnalysisIDs"][FirstStudyID][0]
AnalysisDropdown = widgets.Dropdown(options = StudiesUIFData["AnalysisIDs"][FirstStudyID], value = FirstAnalysisID,
                                    description = "Analysis:", disabled = False)

RLAModes = ["WithinClasses", "AcrossClasess"]
RLAModesDropdown = widgets.Dropdown(options = RLAModes, value = RLAModes[0], description = "Mode:")

PlotTypes = ["Bar plot", "Box plot", "Violin plot", "Beesworm plot"]
PlotTypesDropdown = widgets.Dropdown(options = PlotTypes, value = PlotTypes[1], description = "Plot type:")

PlotStyles = ["Darkgrid", "Whitegrid", "Dark", "White", "Ticks"]
PlotStylesDropdown = widgets.Dropdown(options = PlotStyles, value = "Darkgrid", description = "Plot style:")

PlotColorPalettes = ["Deep", "Muted", "Pastel", "Bright", "Dark", "Colorblind"]
PlotColorPalettesDropdown = widgets.Dropdown(options = PlotColorPalettes, value = "Bright", description = "Color palette:")

DefaultPlotWidth = 10
DefaultPlotHeight = 8

PlotSizeText = widgets.Text(value = "10x8", description = "Plot size:", placeholder = "Type WxH; Hit enter",
                            disabled = False, continuous_update=False)

DataLayout = widgets.Layout(margin='0 0 4px 0')
StudiesDataHBox = widgets.HBox([StudiesDropdown, AnalysisDropdown, RLAModesDropdown], layout = DataLayout)
PlotsDataHBox1 = widgets.HBox([PlotTypesDropdown, PlotStylesDropdown, PlotColorPalettesDropdown], layout = DataLayout)
PlotsDataHBox2 = widgets.HBox([PlotSizeText], layout = DataLayout)

UIFDataHBox1 = widgets.HBox([StudiesDropdown, AnalysisDropdown], layout = DataLayout)
UIFDataHBox2 = widgets.HBox([RLAModesDropdown, PlotTypesDropdown], layout = DataLayout)
UIFDataHBox3 = widgets.HBox([PlotStylesDropdown, PlotColorPalettesDropdown], layout = DataLayout)
UIFDataHBox4 = widgets.HBox([PlotSizeText], layout = DataLayout)

Output = widgets.Output()
OutputPlot = widgets.Output()

UpdatePlot = True

def DisablePlotUpdate():
    global UpdatePlot
    UpdatePlot = False

def EnablePlotUpdate():
    global UpdatePlot
    UpdatePlot = True

def GetUpdatePlotStatus():
    global UpdatePlot
    return True if UpdatePlot else False

# Setup function to update dropdown options...
def UpdateAnalysisDropdown(StudyID):
    AnalysisDropdown.options = StudiesUIFData["AnalysisIDs"][StudyID]
    AnalysisDropdown.value = StudiesUIFData["AnalysisIDs"][StudyID][0]
    
# Setup dropdown event handlers...
def StudiesDropdownEventHandler(Change):
    StudyID = Change["new"]
    
    DisablePlotUpdate()
    UpdateAnalysisDropdown(StudyID)
    EnablePlotUpdate()
    
    PlotData()

def AnalysisDropdownEventHandler(Change):
    PlotData()

def RLAModesDropdownEventHandler(Change):
    PlotData()
    
def PlotTypesDropdownEventHandler(Change):
    PlotData()

def PlotStylesDropdownEventHandler(Change):
    PlotData()
    
def PlotColorPalettesDropdownEventHandler(Change):
    PlotData()

def PlotSizeTextEventHandler(Change):
    PlotData()
    
# Bind required event handlers...
StudiesDropdown.observe(StudiesDropdownEventHandler, names = 'value')
AnalysisDropdown.observe(AnalysisDropdownEventHandler, names = 'value')

RLAModesDropdown.observe(RLAModesDropdownEventHandler, names = 'value')

PlotTypesDropdown.observe(PlotTypesDropdownEventHandler, names = 'value')
PlotStylesDropdown.observe(PlotStylesDropdownEventHandler, names = 'value')
PlotColorPalettesDropdown.observe(PlotColorPalettesDropdownEventHandler, names = 'value')

PlotSizeText.observe(PlotSizeTextEventHandler, names = 'value')

# Set up function to plot RLA data...
def PlotData():
    if not UpdatePlot:
        return
    
    Output.clear_output()
    OutputPlot.clear_output()
    
    StudyID = StudiesDropdown.value
    AnalysisID = AnalysisDropdown.value
    DataFrame = StudiesResultsData[StudyID][AnalysisID]["data_frame"]
    
    RLAMode = RLAModesDropdown.value
    
    PlotType = PlotTypesDropdown.value
    PlotStyle = PlotStylesDropdown.value
    PlotStyle = PlotStyle.lower()
    
    ColorPalette = PlotColorPalettesDropdown.value
    ColorPalette = ColorPalette.lower()
    
    FontScale = 1.2
    TitleFontWeight = "bold"
    LabelsFontWeight = "bold"
    
    PlotSize = PlotSizeText.value.lower()
    PlotSize = re.sub(" ", "", PlotSize)
    PlotSizeWords = PlotSize.split("x")
    
    if len(PlotSizeWords) == 2 and len(PlotSizeWords[0]) > 0 and len(PlotSizeWords[1]) > 0:
        PlotWidth = float(PlotSizeWords[0])
        PlotHeight = float(PlotSizeWords[1])
    else:
        PlotWidth = DefaultPlotWidth
        PlotHeight = DefaultPlotHeight
        with Output:
            print("Invalid plot size; Using default plot size: %sx%s\n" % (PlotWidth, PlotHeight))
    
    with OutputPlot:
        YLabel = None
        
        # Setup RLA plot data
        RLAPlotDataFrame, RLADataFrame = GenerateRLAData(DataFrame, Mode = RLAMode)
        
        # Set plot size and style...
        sns.set(rc = {'figure.figsize':(PlotWidth, PlotHeight)})
        sns.set(style = PlotStyle, font_scale = FontScale)
        
        if re.match("^Box plot$", PlotType, re.I):
            g = sns.boxplot(data = RLAPlotDataFrame, palette = ColorPalette)
        elif re.match("^Violin plot$", PlotType, re.I):
            g = sns.violinplot(data = RLAPlotDataFrame, palette = ColorPalette)
        elif re.match("^Beesworm plot$", PlotType, re.I):
            g = sns.swarmplot(data = RLAPlotDataFrame, s = 5, palette = ColorPalette)
            
            # Draw lines at the median...
            # Ref: https://stackoverflow.com/questions/37619952/drawing-points-with-with-median-lines-in-seaborn-using-stripplot
            MedianWidth = 0.4
            for Tick, Text in zip(g.get_xticks(), g.get_xticklabels()):
                SampleName = Text.get_text()  # "X" or "Y"
                Results = RLAPlotDataFrame[SampleName].tolist()
                
                MedianVal = np.median(Results)
                
                # Plot horizontal lines across the column, centered on the tick...
                g.plot([Tick - MedianWidth/2, Tick + MedianWidth/2], [MedianVal, MedianVal], lw = 4, color = 'k')
        else:
            # Use barplot as default plot...
            g = sns.barplot(data = RLAPlotDataFrame, palette = ColorPalette)
        
        # Set title and labels...
        g.set_title("Relative Log Abundance", fontweight = TitleFontWeight)
        
        g.set_xlabel("SampleID", fontweight = LabelsFontWeight)
        if YLabel is not None:
            g.set_ylabel(YLabel, fontweight = LabelsFontWeight)
        
        # Orient X labels...
        g.set_xticklabels(g.get_xticklabels(), rotation=90)
        
        plt.show()
    
    with Output:
        MWUtil.ListClassInformation(StudiesResultsData, StudyID, AnalysisID, RetrievedMWData)
        
        print("")
        if RetrievedMWData:
            FileName = "%s_%s_Data.csv" % (StudyID, AnalysisID)
            HTMLText = MWUtil.SetupCSVDownloadLink(DataFrame, Title = "Download data", CSVFilename = FileName)
            display(HTML(HTMLText))
        
        if RetrievedMWData:
            FileName = "%s_%s_RLA_%s_Data.csv" % (StudyID, AnalysisID, RLAMode)
        else:
            FileRoot, FileExt = os.path.splitext(StudyID)
            FileName = "%s_RLA_%s_Data.csv" % (FileRoot, RLAMode)
        
        HTMLText = MWUtil.SetupCSVDownloadLink(RLADataFrame, Title = "Download RLA data", CSVFilename = FileName)
        display(HTML(HTMLText))


display(UIFDataHBox1)
display(UIFDataHBox2)
display(UIFDataHBox3)
display(UIFDataHBox4)

display(OutputPlot)
display(Output)

PlotData()