Perform data normalization

Perform data normalization 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 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 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)



The MW REST URL consists of three main parts, separated by forward slashes, after the common prefix specifying the invariant base URL (

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 = ""

Retrieve or upload data for named metabolites...

In [ ]:
# Initialize data...
StudiesResultsData = None
RetrievedMWData = None
In [ ]:
# Setup 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
    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)
            print("\nNo study ID(s) specified...")


# 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
    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([ProcessMissingValueTopTextHTML, MissingValuesMethodsDropdown]))
UIFDataBoxes.append(widgets.HBox([StudyIDText, RetrieveDataBtn],
                                 layout = widgets.Layout(margin='10px 0 0 0')))

for UIFDataBox in UIFDataBoxes:

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

Setup UIF for selecting and plotting available data...

In [ ]:
# Setup UIF data...
StudiesUIFData = MWUtil.SetupUIFDataForStudiesAnalysisAndResults(StudiesResultsData)
In [ ]:
MWUtil.CheckAndWarnEmptyStudiesUIFData(StudiesUIFData, RetrievedMWData, StudyIDText.value)
In [ ]:
# Setup a function to normalize data...
def NormalizeData(InputDataFrame, Method = "Median", ClassColID = "Class", ClassNumColID = "ClassNum"):
    # Track and drop columns before performing data normalization...
    DataFrame = InputDataFrame
    # Track and drop columns before performing data normalization...
    TrackColIDs = []
    if ClassColID is not None:
        DataFrame = DataFrame.drop(ClassColID, axis = 1)
    if ClassNumColID is not None:
        DataFrame = DataFrame.drop(ClassNumColID, axis = 1)
    # Center data by mean...
    DataFrame = DataFrame - DataFrame.mean()
    if re.match("^Median$", Method, re.I):
        DataFrame = DataFrame / DataFrame.median()
    elif re.match("^auto$", Method, re.I):
        DataFrame = DataFrame / DataFrame.std()
    elif re.match("^Pareto$", Method, re.I):
        DataFrame = DataFrame / np.sqrt(DataFrame.std())
    elif re.match("^Range$", Method, re.I):
        DataFrame = DataFrame / (DataFrame.max() - DataFrame.min())
        print("***Warning: Failed to normalize data: Unknown method %s..." % Method)
        return InputDataFrame
    # Format normalized values...
    DataFrame = DataFrame.applymap("{0:.4f}".format)
    # Add any tracked col IDs...
    if len(TrackColIDs):
        TrackedColsDataFrame = InputDataFrame[TrackColIDs]
        DataFrame = pd.concat([TrackedColsDataFrame, DataFrame], axis = 1)
    return DataFrame
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)

Methods = ["Median", "Auto", "Pareto", "Range"]
MethodsDropdown = widgets.Dropdown(options = Methods, value = Methods[0], description = "Methods:")

NormalizeDataBtn = widgets.Button(description = 'Normalize Data', disabled = False, button_stype = '',
                                  tooltip = "Normaliza data for a study ID")

DataLayout = widgets.Layout(margin='0 0 4px 0')
StudiesDataHBox = widgets.HBox([StudiesDropdown, AnalysisDropdown], layout = DataLayout)
MethodsDataHBox = widgets.HBox([MethodsDropdown], layout = DataLayout)
NormalizeDataHBox = widgets.HBox([NormalizeDataBtn], layout = DataLayout)

Output = widgets.Output()

def PerformDataNormalization(Object):
    StudyID = StudiesDropdown.value
    AnalysisID = AnalysisDropdown.value
    NormalizationMethod = MethodsDropdown.value
    ResultsDataFrame = StudiesResultsData[StudyID][AnalysisID]["data_frame"]
    with Output:
        NormalizedResultsDataFrame = NormalizeData(ResultsDataFrame, NormalizationMethod)
        MWUtil.ListClassInformation(StudiesResultsData, StudyID, AnalysisID, RetrievedMWData)  
        # Setup links to download data as CSV files...
        if RetrievedMWData:
            FileName = "%s_%s_Data.csv" % (StudyID, AnalysisID)
            HTMLText = MWUtil.SetupCSVDownloadLink(ResultsDataFrame, Title = "Download data", CSVFilename = FileName)
        if RetrievedMWData:
            FileName = "%s_%s_Normalized_Data_%s.csv" % (StudyID, AnalysisID, NormalizationMethod)
            FileRoot, FileExt = os.path.splitext(StudyID)
            FileName = "%s_Normalized_Data.csv" % (FileRoot)
        HTMLText = MWUtil.SetupCSVDownloadLink(NormalizedResultsDataFrame, Title = "Download normalized data", CSVFilename = FileName)
        print("Normalized data:\n")
        display(HTML(NormalizedResultsDataFrame.to_html(max_rows = 10, max_cols = 10)))

# 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"]

# Bind required event handlers...
StudiesDropdown.observe(StudiesDropdownEventHandler, names = 'value')