{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Perform linear discriminant analysis" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Perform linear discriminant analysis 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 cell 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", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "\n", "from sklearn.preprocessing import StandardScaler\n", "from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\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, MinClassCount = 3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "MWUtil.CheckAndWarnEmptyStudiesUIFData(StudiesUIFData, RetrievedMWData, StudyIDText.value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Setup a function to perform LDA and generate dataframe for LDA plot...\n", "def GenerateLDAPlotData(InputDataFrame, NumComponents = 2, ClassColID = \"Class\", ClassNumColID = \"ClassNum\"):\n", " \"\"\"Perform LDA and generate plot data frame. \"\"\"\n", " \n", " DataFrame = InputDataFrame.copy()\n", " \n", " # Drop Class column...\n", " if ClassColID is not None:\n", " DataFrame = DataFrame.drop(ClassColID, axis = 1)\n", " \n", " # Setup a class dataframe...\n", " ClassesDataFrame = DataFrame.loc[:,[ClassNumColID]]\n", " \n", " # Setup class values for LDA...\n", " ClassValues = ClassesDataFrame[ClassNumColID].tolist()\n", " \n", " # Setup a features dataframe for metaboloties...\n", " FeaturesDataFrame = DataFrame.drop(ClassNumColID, axis = 1)\n", " \n", " # Standardize the featues...\n", " FeaturesDataValues = FeaturesDataFrame.values\n", " FeaturesDataValues = StandardScaler().fit_transform(FeaturesDataValues)\n", " \n", " # Perform analysis...\n", " LDAModel = LinearDiscriminantAnalysis(n_components = NumComponents)\n", " LDComponents = LDAModel.fit_transform(FeaturesDataValues, ClassValues)\n", " LDComponents = LDComponents.tolist()\n", " \n", " LDAColumnNames = []\n", " for Index in range(len(LDComponents[0])):\n", " ColumnID = \"LD%s\" % (Index + 1)\n", " LDAColumnNames.append(ColumnID)\n", " \n", " IndexValues = ClassesDataFrame.index.values.tolist()\n", " LDADataFrame = pd.DataFrame(data = LDComponents, columns = LDAColumnNames, index = IndexValues)\n", " \n", " # Setup final LDA dataframe including class numbers...\n", " LDADataFrame = pd.concat([ClassesDataFrame, LDADataFrame], axis = 1)\n", " \n", " ExplainedVariance = LDAModel.explained_variance_ratio_\n", " ExplainedVariance = ExplainedVariance.tolist()\n", " \n", " return (LDADataFrame, ExplainedVariance)\n", "\n", "# Setup a function to draw LDA plot...\n", "def DrawLDAPlot(LDAPlotDataFrame, ClassNumColID =\"ClassNum\", LD1ColID = \"LD1\", LD2ColID = \"LD2\",\n", " ColorPaletteName = \"bright\", PlotStyle = \"darkgrid\", FontScale = 1.3,\n", " TitleFontWeight = \"bold\", LabelsFontWeight = \"bold\",\n", " PlotWidth = 9, PlotHeight = 6):\n", " \n", " sns.set(rc = {'figure.figsize':(PlotWidth, PlotHeight)})\n", " sns.set(style = PlotStyle, font_scale = FontScale)\n", " \n", " # Color palette names: deep, muted, pastel, bright, dark, and colorblind.\n", " NumOfClasses = len(LDAPlotDataFrame[ClassNumColID].unique().tolist())\n", " ColorsPalette = sns.color_palette(ColorPaletteName, NumOfClasses)\n", " \n", " StyleColID = ClassNumColID if NumOfClasses <= 5 else None\n", " if StyleColID is not None:\n", " Axis = sns.scatterplot(x = LD1ColID, y = LD2ColID, hue = ClassNumColID, style = StyleColID,\n", " data = LDAPlotDataFrame, palette = ColorsPalette, legend = \"brief\")\n", " else:\n", " Axis = sns.scatterplot(x = LD1ColID, y = LD2ColID, hue = ClassNumColID, data = LDAPlotDataFrame,\n", " palette = ColorsPalette, legend = \"brief\")\n", " \n", " # Set title and labels...\n", " Axis.set_title(\"LDA Scores Plot\", fontweight = TitleFontWeight)\n", " Axis.set_xlabel(LD1ColID, fontweight = LabelsFontWeight)\n", " Axis.set_ylabel(LD2ColID, fontweight = LabelsFontWeight)\n", " \n", " # Draw legend outside the plot...\n", " plt.legend(bbox_to_anchor = (1.05, 1), loc = 2, borderaxespad = 0.)\n", " \n", " plt.show()" ] }, { "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", "Components = [\"2\", \"3\", \"4\", \"5\"]\n", "ComponentsDropdown = widgets.Dropdown(options = Components, value = \"2\", description = \"Components:\")\n", "\n", "PlotStyles = [\"Darkgrid\", \"Whitegrid\", \"Dark\", \"White\", \"Ticks\"]\n", "PlotStylesDropdown = widgets.Dropdown(options = PlotStyles, value = \"Darkgrid\", description = \"Plot style:\")\n", "\n", "DefaultPlotWidth = 9\n", "DefaultPlotHeight = 6\n", "PlotSizeText = widgets.Text(value = \"9x6\", description = \"Plot size:\", placeholder = \"Type WxH; Hit enter\",\n", " disabled = False, continuous_update=False)\n", "\n", "PlotColorPalettes = [\"Deep\", \"Muted\", \"Pastel\", \"Bright\", \"Dark\", \"Colorblind\"]\n", "PlotColorPalettesDropdown = widgets.Dropdown(options = PlotColorPalettes, value = \"Bright\", description = \"Color palette:\")\n", "\n", "\n", "DataLayout = widgets.Layout(margin='0 0 4px 0')\n", "StudiesDataHBox = widgets.HBox([StudiesDropdown, AnalysisDropdown], layout = DataLayout)\n", "ComponentsDataHBox = widgets.HBox([ComponentsDropdown], layout = DataLayout)\n", "PlotsDataHBox = widgets.HBox([PlotStylesDropdown, PlotSizeText], layout = DataLayout)\n", "ColorPalattesDataHBox = widgets.HBox([PlotColorPalettesDropdown], 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", "# Setup dropdown event handlers...\n", "def StudiesDropdownEventHandler(Change):\n", " StudyID = Change[\"new\"]\n", " \n", " DisablePlotUpdate()\n", " UpdateAnalysisDropdown(StudyID)\n", " EnablePlotUpdate()\n", " \n", " PlotData()\n", "\n", "def AnalysisDropdownEventHandler(Change):\n", " PlotData()\n", "\n", "def ComponentsDropdownEventHandler(Change):\n", " PlotData()\n", "\n", "def PlotStylesDropdownEventHandler(Change):\n", " PlotData()\n", " \n", "def PlotSizeTextEventHandler(Change):\n", " PlotData()\n", " \n", "def PlotColorPalettesDropdownEventHandler(Change):\n", " PlotData()\n", " \n", "# Bind required event handlers...\n", "StudiesDropdown.observe(StudiesDropdownEventHandler, names = 'value')\n", "AnalysisDropdown.observe(AnalysisDropdownEventHandler, names = 'value')\n", "ComponentsDropdown.observe(ComponentsDropdownEventHandler, names = 'value')\n", "\n", "PlotStylesDropdown.observe(PlotStylesDropdownEventHandler, names = 'value')\n", "PlotSizeText.observe(PlotSizeTextEventHandler, names = 'value')\n", "PlotColorPalettesDropdown.observe(PlotColorPalettesDropdownEventHandler, names = 'value')\n", "\n", "# Set up function to generate PCA plot...\n", "def PlotData():\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", " DataFrame = StudiesResultsData[StudyID][AnalysisID][\"data_frame\"]\n", " \n", " NumOfComponents = int(ComponentsDropdown.value)\n", " \n", " Style = PlotStylesDropdown.value\n", " Style = Style.lower()\n", " \n", " Palette = PlotColorPalettesDropdown.value\n", " Palette = Palette.lower()\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", " Width = float(PlotSizeWords[0])\n", " Height = float(PlotSizeWords[1])\n", " else:\n", " Width = DefaultPlotWidth\n", " Height = DefaultHeight\n", " with Output:\n", " print(\"Invalid plot size; Using default plot size: %sx%s\\n\" % (Width, Height))\n", " \n", " # Retrieve data for a PCA plot...\n", " with OutputPlot:\n", " LDAPlotDataFrame, ExplainedVariance = GenerateLDAPlotData(DataFrame, NumComponents = NumOfComponents,\n", " ClassColID = \"Class\", ClassNumColID = \"ClassNum\")\n", " \n", " with OutputPlot:\n", " # Draw LDA plot...\n", " DrawLDAPlot(LDAPlotDataFrame, ClassNumColID =\"ClassNum\", LD1ColID = \"LD1\", LD2ColID = \"LD2\",\n", " ColorPaletteName = Palette, PlotStyle = Style,\n", " PlotWidth = Width, PlotHeight = Height)\n", " \n", " print(\"Explained variance:\")\n", " for Index in range(len(ExplainedVariance)):\n", " ID = \"LD%s\" % (Index + 1)\n", " print(\"%s: %.2f%s\" % (ID, (ExplainedVariance[Index] * 100), \"%\"))\n", " \n", " with Output:\n", " MWUtil.ListClassInformation(StudiesResultsData, StudyID, AnalysisID, RetrievedMWData)\n", " \n", " # Setup a link to download data...\n", " if RetrievedMWData:\n", " FileName = \"%s_%s_Data.csv\" % (StudyID, AnalysisID)\n", " HTMLText = MWUtil.SetupCSVDownloadLink(DataFrame, Title = \"Download data\", CSVFilename = FileName)\n", " display(HTML(HTMLText))\n", " \n", " # Setup a link to download LDA data...\n", " if RetrievedMWData:\n", " FileName = \"%s_%s_LDA_Data.csv\" % (StudyID, AnalysisID)\n", " else:\n", " FileRoot, FileExt = os.path.splitext(StudyID)\n", " FileName = \"%s_LDA_Data.csv\" % (FileRoot)\n", " \n", " HTMLText = MWUtil.SetupCSVDownloadLink(LDAPlotDataFrame, Title = \"Download LDA data\", CSVFilename = FileName)\n", " display(HTML(HTMLText))\n", " \n", " # List dataframe...\n", " display(HTML(LDAPlotDataFrame.to_html(max_rows = 10, max_cols = 10)))\n", "\n", "\n", "display(StudiesDataHBox)\n", "display(ComponentsDataHBox)\n", "display(PlotsDataHBox)\n", "display(ColorPalattesDataHBox)\n", "\n", "display(OutputPlot)\n", "display(Output)\n", "\n", "PlotData()\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 }