{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Plot distributions of named metabolites" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot distributions of named metabolities using data 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 cell and advance to the next cell.
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Import Python modules..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "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 matplotlib.pyplot as plt\n", "import seaborn as sns\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": [ "# Set up 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, MinClassCount = None)" ] }, { "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 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", "FirstMetaboliteID = StudiesUIFData[\"MetaboliteIDs\"][FirstStudyID][FirstAnalysisID][0]\n", "MetabolitesDropdown = widgets.Dropdown(options = StudiesUIFData[\"MetaboliteIDs\"][FirstStudyID][FirstAnalysisID],\n", " value = FirstMetaboliteID, description = \"Metabolite:\", disabled = False)\n", "\n", "PlotTypes = [\"Bar plot\", \"Box plot\", \"Violin plot\", \"Beesworm plot\"]\n", "PlotTypesDropdown = widgets.Dropdown(options = PlotTypes, value = PlotTypes[1], description = \"Plot type:\")\n", "\n", "PlotStyles = [\"Darkgrid\", \"Whitegrid\", \"Dark\", \"White\", \"Ticks\"]\n", "PlotStylesDropdown = widgets.Dropdown(options = PlotStyles, value = \"Darkgrid\", description = \"Plot style:\")\n", "\n", "DefaultPlotWidth = 10\n", "DefaultPlotHeight = 8\n", "\n", "PlotSizeText = widgets.Text(value = \"10x8\", description = \"Plot size:\", placeholder = \"Type WxH; Hit enter\",\n", " disabled = False, continuous_update=False)\n", "\n", "DataLayout = widgets.Layout(margin='0 0 4px 0')\n", "StudiesDataHBox = widgets.HBox([StudiesDropdown, AnalysisDropdown, MetabolitesDropdown], layout = DataLayout)\n", "PlotsDataHBox = widgets.HBox([PlotTypesDropdown, PlotStylesDropdown, PlotSizeText], layout = DataLayout)\n", "\n", "Output = widgets.Output()\n", "OutputPlot = widgets.Output()\n", "\n", "UpdatePlot = True\n", "\n", "def DisablePlotUpdate():\n", " global UpdatePlot\n", " UpdatePlot = False\n", "\n", "def EnablePlotUpdate():\n", " global UpdatePlot\n", " UpdatePlot = True\n", "\n", "def GetUpdatePlotStatus():\n", " global UpdatePlot\n", " return True if UpdatePlot else False\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", "def UpdateMetabolitesDropdown(StudyID, AnalysisID):\n", " MetabolitesDropdown.options = StudiesUIFData[\"MetaboliteIDs\"][StudyID][AnalysisID]\n", " MetabolitesDropdown.value = StudiesUIFData[\"MetaboliteIDs\"][StudyID][AnalysisID][0]\n", "\n", "# Setup dropdown event handlers...\n", "def StudiesDropdownEventHandler(Change):\n", " StudyID = Change[\"new\"]\n", " \n", " DisablePlotUpdate()\n", " UpdateAnalysisDropdown(StudyID)\n", " UpdateMetabolitesDropdown(StudyID, StudiesUIFData[\"AnalysisIDs\"][StudyID][0])\n", " EnablePlotUpdate()\n", " \n", " PlotMetaboliteData()\n", "\n", "def AnalysisDropdownEventHandler(Change):\n", " UpdatePlotStatus = GetUpdatePlotStatus()\n", " if UpdatePlotStatus:\n", " DisablePlotUpdate()\n", " \n", " UpdateMetabolitesDropdown(StudiesDropdown.value, Change[\"new\"])\n", " \n", " if UpdatePlotStatus:\n", " EnablePlotUpdate()\n", " \n", " PlotMetaboliteData()\n", "\n", "def MetabolitesDropdownEventHandler(Change):\n", " PlotMetaboliteData()\n", "\n", "def PlotTypesDropdownEventHandler(Change):\n", " PlotMetaboliteData()\n", "\n", "def PlotStylesDropdownEventHandler(Change):\n", " PlotMetaboliteData()\n", "\n", "def PlotSizeTextEventHandler(Change):\n", " PlotMetaboliteData()\n", " \n", "# Bind required event handlers...\n", "StudiesDropdown.observe(StudiesDropdownEventHandler, names = 'value')\n", "AnalysisDropdown.observe(AnalysisDropdownEventHandler, names = 'value')\n", "MetabolitesDropdown.observe(MetabolitesDropdownEventHandler, names = 'value')\n", "\n", "PlotTypesDropdown.observe(PlotTypesDropdownEventHandler, names = 'value')\n", "PlotStylesDropdown.observe(PlotStylesDropdownEventHandler, names = 'value')\n", "\n", "PlotSizeText.observe(PlotSizeTextEventHandler, names = 'value')\n", "\n", "# Set up function to plot metabolite data...\n", "def PlotMetaboliteData():\n", " if not UpdatePlot:\n", " return\n", " \n", " Output.clear_output()\n", " OutputPlot.clear_output()\n", " \n", " StudyID = StudiesDropdown.value\n", " AnalysisID = AnalysisDropdown.value\n", " MetaboliteID = MetabolitesDropdown.value\n", " Dataframe = StudiesResultsData[StudyID][AnalysisID][\"data_frame\"]\n", " \n", " PlotType = PlotTypesDropdown.value\n", " PlotStyle = PlotStylesDropdown.value\n", " PlotStyle = PlotStyle.lower()\n", " \n", " FontScale = 1.3\n", " TitleFontWeight = \"bold\"\n", " LabelsFontWeight = \"bold\"\n", " \n", " PlotSize = PlotSizeText.value.lower()\n", " PlotSize = re.sub(\" \", \"\", PlotSize)\n", " PlotSizeWords = PlotSize.split(\"x\")\n", " \n", " if len(PlotSizeWords) == 2 and len(PlotSizeWords[0]) > 0 and len(PlotSizeWords[1]) > 0:\n", " PlotWidth = float(PlotSizeWords[0])\n", " PlotHeight = float(PlotSizeWords[1])\n", " else:\n", " PlotWidth = DefaultPlotWidth\n", " PlotHeight = DefaultPlotHeight\n", " with Output:\n", " print(\"Invalid plot size; Using default plot size: %sx%s\\n\" % (PlotWidth, PlotHeight))\n", " \n", " with OutputPlot:\n", " YLabel = \"Measurement\"\n", " \n", " # Set plot size and style...\n", " sns.set(rc = {'figure.figsize':(PlotWidth, PlotHeight)})\n", " sns.set(style = PlotStyle, font_scale = FontScale)\n", " \n", " if re.match(\"^Box plot$\", PlotType, re.I):\n", " g = sns.boxplot(x = \"ClassNum\", y = MetaboliteID, data = Dataframe)\n", " elif re.match(\"^Violin plot$\", PlotType, re.I):\n", " g = sns.violinplot(x = \"ClassNum\", y = MetaboliteID, data = Dataframe)\n", " elif re.match(\"^Beesworm plot$\", PlotType, re.I):\n", " g = sns.swarmplot(x = \"ClassNum\", y = MetaboliteID, data = Dataframe, s = 10)\n", " \n", " # Draw lines at the median...\n", " # Ref: https://stackoverflow.com/questions/37619952/drawing-points-with-with-median-lines-in-seaborn-using-stripplot\n", " MedianWidth = 0.4\n", " for Tick, Text in zip(g.get_xticks(), g.get_xticklabels()):\n", " SampleName = Text.get_text() # \"X\" or \"Y\"\n", " Results = Dataframe.query(f\"ClassNum == '{SampleName}'\")\n", " \n", " MedianVal = np.median(Results[MetaboliteID])\n", " \n", " # Plot horizontal lines across the column, centered on the tick...\n", " g.plot([Tick - MedianWidth/2, Tick + MedianWidth/2], [MedianVal, MedianVal], lw = 4, color = 'k')\n", " else:\n", " # Use barplot as default plot...\n", " g = sns.barplot(x = \"ClassNum\", y = MetaboliteID, data = Dataframe)\n", " \n", " # Set title and labels...\n", " g.set_title(MetaboliteID, fontweight = TitleFontWeight)\n", " g.set_xlabel(\"ClassNum\", fontweight = LabelsFontWeight)\n", " g.set_ylabel(YLabel, fontweight = LabelsFontWeight)\n", " plt.show()\n", " \n", " with Output:\n", " MWUtil.ListClassInformation(StudiesResultsData, StudyID, AnalysisID, RetrievedMWData)\n", " \n", " if RetrievedMWData:\n", " print(\"\")\n", " FileName = \"%s_%s_Data.csv\" % (StudyID, AnalysisID)\n", " HTMLText = MWUtil.SetupCSVDownloadLink(Dataframe, Title = \"Download data\", CSVFilename = FileName)\n", " display(HTML(HTMLText))\n", "\n", "\n", "display(StudiesDataHBox)\n", "display(PlotsDataHBox)\n", "\n", "display(OutputPlot)\n", "display(Output)\n", "\n", "PlotMetaboliteData()\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 }