{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Perform data normalization" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Perform data normalization using data for named metabolites from the metabolomics workbench or uploaded data files." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
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.
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Import Python modules..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "from __future__ import print_function\n", "\n", "import os\n", "import sys\n", "import time\n", "import re\n", "\n", "import requests\n", "\n", "import pandas as pd\n", "import numpy as np\n", "\n", "import ipywidgets as widgets\n", "\n", "from IPython.display import display, HTML\n", "from IPython import __version__ as ipyVersion\n", "\n", "# Import MW modules from the current directory or default Python directory...\n", "import MWUtil\n", "\n", "%matplotlib inline\n", "\n", "print(\"Python: %s.%s.%s\" % sys.version_info[:3])\n", "print(\"IPython: %s\" % ipyVersion)\n", "\n", "print()\n", "print(time.asctime())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The URL PATH\n", "\n", "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/):\n", "\n", "https://www.metabolomicsworkbench.org/rest/context/input_specification/output_specification\n", "\n", "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:\n", "\n", "context = study | compound | refmet | gene | protein | moverz | exactmass\n", "\n", "Part 2: The input specification consists of two required parameters describing the REST request:\n", "\n", "input_specification = input_item/input_value\n", "\n", "Part 3: The output specification consists of two parameters describing the output generated by the REST request:\n", "\n", "output_specification = output_item/(output_format)\n", "\n", "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.\n", "\n", "Setup MW REST base URL..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "MWBaseURL = \"https://www.metabolomicsworkbench.org/rest\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Retrieve or upload data for named metabolites...**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Initialize data...\n", "StudiesResultsData = None\n", "RetrievedMWData = None" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Setup UIF info text...\n", "TopInfoTextHTML = widgets.HTML(value = \"Retrieve or upload data and process any missing values\", \n", " placeholder='', description='')\n", "\n", "# Setup UIF to process any missing values...\n", "MissingValuesMethods = [\"NoAction\", \"DeleteRows\", \"DeleteColumns\", \"ReplaceByColumnMean\", \"ReplaceColumnMedian\", \"ReplaceByZero\" , \"LinearInterpolation\"]\n", "MissingValuesMethodsDropdown = widgets.Dropdown(options = MissingValuesMethods,\n", " value = \"NoAction\",\n", " description = \" \")\n", "ProcessMissingValueTopTextHTML = widgets.HTML(value = \"Method for processing missing values:\", \n", " placeholder='', description='')\n", "\n", "# Setup UIF to retrieve...\n", "StudyIDText = widgets.Text(value = \"ST000001 ST000002\", description = \"Study ID (s)\",\n", " placeholder = \"Type study ID\", disabled = False,\n", " layout = widgets.Layout(margin='0 10px 0 0'))\n", "RetrieveDataBtn = widgets.Button(description = 'Retrieve Data', disabled = False, button_stype = '',\n", " tooltip = \"Retrieve data for study ID\")\n", "\n", "RetrieveDataOutput = widgets.Output()\n", "def RetrieveDataBtnEventHandler(Object):\n", " global StudiesResultsData, RetrievedMWData\n", " \n", " RetrievedMWData = True\n", " StudiesResultsData = None\n", " \n", " StudyIDs = StudyIDText.value\n", " MissingValuesMethod = MissingValuesMethodsDropdown.value\n", " \n", " RetrieveDataOutput.clear_output()\n", " UploadDataOutput.clear_output()\n", " with RetrieveDataOutput:\n", " if len(StudyIDs):\n", " print(\"\\nProcessing study ID(s): %s\" % StudyIDs)\n", " StudiesResultsData = MWUtil.RetrieveStudiesAnalysisAndResultsData(StudyIDs, MWBaseURL, MissingValuesMethod)\n", " DisplayData = False if len(StudiesResultsData.keys()) > 5 else True\n", " MWUtil.ListStudiesAnalysisAndResultsData(StudiesResultsData, DisplayDataFrame = DisplayData,\n", " IPythonDisplayFuncRef = display, IPythonHTMLFuncRef = HTML)\n", " else:\n", " print(\"\\nNo study ID(s) specified...\")\n", "\n", "RetrieveDataBtn.on_click(RetrieveDataBtnEventHandler)\n", "\n", "# Setup UIF to upload data file(s)...\n", "FileUploadBtn = widgets.FileUpload(description = 'Upload File(s)', accept='.csv,.txt,.tsv', multiple = True,\n", " disabled = False)\n", "FileUploadTextHTML = widgets.HTML(value = \"File format: Col 1: Sample names; \\\n", " Col 2: Class identifiers; Remaining cols: Named metabolites; \\\n", " Exts: .csv, .txt, or .tsv\", placeholder='', description='')\n", "\n", "UploadDataOutput = widgets.Output()\n", "def FileUploadBtnEventHandler(Change):\n", " global StudiesResultsData, RetrievedMWData\n", " \n", " RetrievedMWData = False\n", " StudiesResultsData = None\n", " \n", " MissingValuesMethod = MissingValuesMethodsDropdown.value\n", " UploadedDataInfo = FileUploadBtn.value\n", " \n", " RetrieveDataOutput.clear_output()\n", " UploadDataOutput.clear_output()\n", " with UploadDataOutput:\n", " StudiesResultsData = MWUtil.RetrieveUploadedData(UploadedDataInfo, MissingValuesMethod)\n", " DisplayData = False if len(StudiesResultsData.keys()) > 5 else True\n", " MWUtil.ListStudiesAnalysisAndResultsData(StudiesResultsData, DisplayDataFrame = DisplayData,\n", " IPythonDisplayFuncRef = display, IPythonHTMLFuncRef = HTML)\n", " \n", "FileUploadBtn.observe(FileUploadBtnEventHandler, names = 'value')\n", "\n", "# Setup UIF to retrieve or upload data file...\n", "\n", "DataWarningTextHTML = widgets.HTML(value = \"
Warning: 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.
\", placeholder='', description='')\n", "OrTextHTML = widgets.HTML(value = \"Or\", placeholder='', description='')\n", "\n", "UIFDataBoxes = []\n", "UIFDataBoxes.append(widgets.HBox([TopInfoTextHTML]))\n", "UIFDataBoxes.append(widgets.HBox([ProcessMissingValueTopTextHTML, MissingValuesMethodsDropdown]))\n", "UIFDataBoxes.append(widgets.HBox([StudyIDText, RetrieveDataBtn],\n", " layout = widgets.Layout(margin='10px 0 0 0')))\n", "UIFDataBoxes.append(widgets.HBox([OrTextHTML]))\n", "UIFDataBoxes.append(widgets.HBox([FileUploadBtn]))\n", "UIFDataBoxes.append(widgets.HBox([FileUploadTextHTML]))\n", "UIFDataBoxes.append(widgets.HBox([DataWarningTextHTML]))\n", "\n", "for UIFDataBox in UIFDataBoxes:\n", " display(UIFDataBox)\n", "\n", "display(RetrieveDataOutput)\n", "display(UploadDataOutput)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "MWUtil.CheckAndWarnEmptyStudiesData(StudiesResultsData, RetrievedMWData, StudyIDText.value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Setup UIF for selecting and plotting available data..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Setup UIF data...\n", "StudiesUIFData = MWUtil.SetupUIFDataForStudiesAnalysisAndResults(StudiesResultsData)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "MWUtil.CheckAndWarnEmptyStudiesUIFData(StudiesUIFData, RetrievedMWData, StudyIDText.value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "# Setup a function to normalize data...\n", "def NormalizeData(InputDataFrame, Method = \"Median\", ClassColID = \"Class\", ClassNumColID = \"ClassNum\"):\n", " \n", " # Track and drop columns before performing data normalization...\n", " DataFrame = InputDataFrame\n", " \n", " # Track and drop columns before performing data normalization...\n", " TrackColIDs = []\n", " if ClassColID is not None:\n", " DataFrame = DataFrame.drop(ClassColID, axis = 1)\n", " TrackColIDs.append(ClassColID)\n", " \n", " if ClassNumColID is not None:\n", " DataFrame = DataFrame.drop(ClassNumColID, axis = 1)\n", " TrackColIDs.append(ClassNumColID)\n", " \n", " # Center data by mean...\n", " DataFrame = DataFrame - DataFrame.mean()\n", " \n", " if re.match(\"^Median$\", Method, re.I):\n", " DataFrame = DataFrame / DataFrame.median()\n", " elif re.match(\"^auto$\", Method, re.I):\n", " DataFrame = DataFrame / DataFrame.std()\n", " elif re.match(\"^Pareto$\", Method, re.I):\n", " DataFrame = DataFrame / np.sqrt(DataFrame.std())\n", " elif re.match(\"^Range$\", Method, re.I):\n", " DataFrame = DataFrame / (DataFrame.max() - DataFrame.min())\n", " else:\n", " print(\"***Warning: Failed to normalize data: Unknown method %s...\" % Method)\n", " return InputDataFrame\n", " \n", " # Format normalized values...\n", " DataFrame = DataFrame.applymap(\"{0:.4f}\".format)\n", " \n", " # Add any tracked col IDs...\n", " if len(TrackColIDs):\n", " TrackedColsDataFrame = InputDataFrame[TrackColIDs]\n", " DataFrame = pd.concat([TrackedColsDataFrame, DataFrame], axis = 1)\n", " \n", " return DataFrame" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "# Setup UIF...\n", "FirstStudyID = StudiesUIFData[\"StudyIDs\"][0]\n", "StudiesDropdown = widgets.Dropdown(options = StudiesUIFData[\"StudyIDs\"], value = FirstStudyID, \n", " description=\"Study:\", disabled = False)\n", "\n", "FirstAnalysisID = StudiesUIFData[\"AnalysisIDs\"][FirstStudyID][0]\n", "AnalysisDropdown = widgets.Dropdown(options = StudiesUIFData[\"AnalysisIDs\"][FirstStudyID], value = FirstAnalysisID,\n", " description = \"Analysis:\", disabled = False)\n", "\n", "Methods = [\"Median\", \"Auto\", \"Pareto\", \"Range\"]\n", "MethodsDropdown = widgets.Dropdown(options = Methods, value = Methods[0], description = \"Methods:\")\n", "\n", "NormalizeDataBtn = widgets.Button(description = 'Normalize Data', disabled = False, button_stype = '',\n", " tooltip = \"Normaliza data for a study ID\")\n", "\n", "DataLayout = widgets.Layout(margin='0 0 4px 0')\n", "StudiesDataHBox = widgets.HBox([StudiesDropdown, AnalysisDropdown], layout = DataLayout)\n", "MethodsDataHBox = widgets.HBox([MethodsDropdown], layout = DataLayout)\n", "NormalizeDataHBox = widgets.HBox([NormalizeDataBtn], layout = DataLayout)\n", "\n", "Output = widgets.Output()\n", "\n", "def PerformDataNormalization(Object):\n", " \n", " Output.clear_output()\n", " \n", " StudyID = StudiesDropdown.value\n", " AnalysisID = AnalysisDropdown.value\n", " NormalizationMethod = MethodsDropdown.value\n", " \n", " ResultsDataFrame = StudiesResultsData[StudyID][AnalysisID][\"data_frame\"]\n", " \n", " with Output:\n", " NormalizedResultsDataFrame = NormalizeData(ResultsDataFrame, NormalizationMethod)\n", " \n", " MWUtil.ListClassInformation(StudiesResultsData, StudyID, AnalysisID, RetrievedMWData) \n", " \n", " # Setup links to download data as CSV files...\n", " if RetrievedMWData:\n", " FileName = \"%s_%s_Data.csv\" % (StudyID, AnalysisID)\n", " HTMLText = MWUtil.SetupCSVDownloadLink(ResultsDataFrame, Title = \"Download data\", CSVFilename = FileName)\n", " display(HTML(HTMLText))\n", " \n", " if RetrievedMWData:\n", " FileName = \"%s_%s_Normalized_Data_%s.csv\" % (StudyID, AnalysisID, NormalizationMethod)\n", " else:\n", " FileRoot, FileExt = os.path.splitext(StudyID)\n", " FileName = \"%s_Normalized_Data.csv\" % (FileRoot)\n", " \n", " HTMLText = MWUtil.SetupCSVDownloadLink(NormalizedResultsDataFrame, Title = \"Download normalized data\", CSVFilename = FileName)\n", " display(HTML(HTMLText))\n", " \n", " print(\"Normalized data:\\n\")\n", " display(HTML(NormalizedResultsDataFrame.to_html(max_rows = 10, max_cols = 10)))\n", " \n", "\n", "# Setup function to update dropdown options...\n", "def UpdateAnalysisDropdown(StudyID):\n", " AnalysisDropdown.options = StudiesUIFData[\"AnalysisIDs\"][StudyID]\n", " AnalysisDropdown.value = StudiesUIFData[\"AnalysisIDs\"][StudyID][0]\n", "\n", "# Setup dropdown event handlers...\n", "def StudiesDropdownEventHandler(Change):\n", " StudyID = Change[\"new\"]\n", " \n", " UpdateAnalysisDropdown(StudyID)\n", "\n", "# Bind required event handlers...\n", "StudiesDropdown.observe(StudiesDropdownEventHandler, names = 'value')\n", "\n", "NormalizeDataBtn.on_click(PerformDataNormalization)\n", "\n", "display(StudiesDataHBox)\n", "display(MethodsDataHBox)\n", "display(NormalizeDataHBox)\n", "\n", "display(Output)\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" } }, "nbformat": 4, "nbformat_minor": 2 }