diff --git a/src/notebooks/Python Examples/GSC23 MGnify Workshop.ipynb b/src/notebooks/Python Examples/GSC23 MGnify Workshop.ipynb new file mode 100644 index 0000000..1f0fed2 --- /dev/null +++ b/src/notebooks/Python Examples/GSC23 MGnify Workshop.ipynb @@ -0,0 +1,1531 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "6f011bcd-c994-4681-8863-65adc0430908", + "metadata": { + "tags": [] + }, + "source": [ + "---\n", + "title: \"GSC23 MGnify Workshop\"\n", + "authors: \"Tatiana Gurbich\", \"Sandy Rogers\", \"Virginie Grosboillot\"\n", + "categories: [Python]\n", + "execute: \n", + " enabled: true\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "ce2d1dc9-1a56-4103-8353-5a5b3fdb24bc", + "metadata": { + "tags": [] + }, + "source": [ + "
" + ] + }, + { + "cell_type": "markdown", + "id": "5e7134e1-079b-421a-b634-261ce028e631", + "metadata": {}, + "source": [ + "\n", + "\n", + "# GSC23 MGnify Workshop Advanced Session - Practical Exercise\n", + "\n", + "### Aims:\n", + "\n", + "* become familiar with the MGnify API and learn to access it programmatically\n", + "* explore the MGnify Genomes resource using Python\n", + "\n", + "### How this notebook works: \n", + "\n", + "This is an interactive code notebook (a Jupyter Notebook).\n", + "To run this code, click into each cell and press the ▶ button in the top toolbar, or press `shift+enter`.\n", + "\n", + "### This notebook is divided into 3 sections: \n", + "\n", + "- Section 1 focuses on MGnify Analyses (metagenomic datasets and assemblies analysed by MGnify)\n", + "- Section 2 focuses on the MGnify Genomes resource (the genome catalogues)\n", + "- Bonus section allows you to practice writing your own code to query the API\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "d35fcccb-bf90-4cdd-8c36-415e9b843469", + "metadata": {}, + "source": [ + "### Import packages\n", + "\n", + "Execute the code below to import the Python libraries required to run the examples presented in this notebook." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ba4e90f6-7778-4d03-ae4f-05711d5d5c63", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Connection to MGnify API\n", + "from jsonapi_client import Session as APISession\n", + "from jsonapi_client import Modifier # allows us to query specific values in given fields (e.g.: 'taxon-lineage').\n", + "import requests\n", + "from itertools import islice\n", + "\n", + "# Dataframes and display\n", + "import pandas as pd\n", + "\n", + "pd.set_option('display.max_columns', None)\n", + "pd.set_option('display.max_colwidth', None)\n", + "\n", + "# Plots\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import plotly.graph_objects as go\n", + "%matplotlib inline \n", + "\n", + "# Data download\n", + "from urllib.request import urlretrieve\n", + "\n", + "# Warning verbosity\n", + "import warnings \n", + "warnings.filterwarnings(action=\"ignore\")" + ] + }, + { + "cell_type": "markdown", + "id": "16229ed2-70b0-4e5a-a2ec-3f8d63a227e9", + "metadata": {}, + "source": [ + "---\n", + "\n", + "## Section 1: explore MGnify analysis results programmatically" + ] + }, + { + "cell_type": "markdown", + "id": "0310546e-6b7a-41c9-a42a-7a03f0a16ab0", + "metadata": {}, + "source": [ + "In the first portion of today's workhop you learned about MGnify's analysis of metagenomic data. In this exercise we will fetch and explore MGnify analysis results programmatically. These are just a few examples of the types of commands and operations that can be peformed." + ] + }, + { + "cell_type": "markdown", + "id": "ce46df50-8a47-40d0-a0aa-499fa333b4ac", + "metadata": {}, + "source": [ + "#### Task 1: Browse the recently analysed studies and save them to a file\n", + "\n", + "Let's start by loading the 50 most recently analysed studies and saving them to a file called ```studies.csv``` (it would take too long to load all studies for this example so we limit the number at 50):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "80005880-ec79-4991-96b0-b1d8848eac99", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "endpoint = 'studies'\n", + "\n", + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as mgnify:\n", + " resources = map(lambda r: r.json, islice(mgnify.iterate(endpoint), 50))\n", + " resources = pd.json_normalize(resources)\n", + " resources.to_csv(f\"{endpoint}.csv\")" + ] + }, + { + "cell_type": "markdown", + "id": "eadfa1bd-fc42-47a5-b760-7bc573d159da", + "metadata": {}, + "source": [ + "Click on the three dots below to open up a line by line explanation of this code block." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0941782b-69e3-4c48-b036-fca19d9dde40", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, + "outputs": [], + "source": [ + "endpoint = 'studies'\n", + "# An \"endpoint\" is the specific resource within the API which we want to get data from. \n", + "# It is the URL relative to the \"server base URL\" of the API, which for MGnify is \n", + "# https://www.ebi.ac.uk/metagenomics/api/v1.\n", + "# You can find the endpoints in the API Docs https://www.ebi.ac.uk/metagenomics/api/docs/ \n", + "\n", + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as mgnify:\n", + " # Calling \"APISession\" is enabling a connection to the MGnify API, that can be used multiple times. \n", + " # The `with...as mgnify` syntax is a Python \"context\". \n", + " # Everything inside the `with...` block (i.e. indented lines below it) can use the APISession \n", + " # which we've called mgnify here. \n", + " # When the `with` block closes (the indentation stops), the connection to the API is cleaned up.\n", + "\n", + " resources = map(lambda r: r.json, islice(mgnify.iterate(endpoint), 50))\n", + " # `map` applies a function to every element of an iterable - so do something to each thing in a list.\n", + " # The MGnify API is paginated, which means query results are broken up into pages for easier handling.\n", + " # `mgnify.iterate(endpoint)` is a very helpful function that loops over as many pages of results as \n", + " # there are.\n", + " # `lambda r: r.json` is grabbing the JSON attribute from each study returned from the API.\n", + " # The islice() function from the itertools module is used to limit the number of results to 50. \n", + " # It ensures that only the first 50 items will be processed. We added this to avoid loading all of \n", + " # the studies, which would take a long time.\n", + " # All together, this makes `resources` be 50 JSON representations we could loop through, each containing \n", + " # the data of a study.\n", + "\n", + " resources = pd.json_normalize(resources)\n", + " # pd is the shorthand for the pandas package - you'll see it anywhere people are using pandas.\n", + " # The json_normalize function takes \"nested\" data and turns it into a table.\n", + "\n", + " resources.to_csv(f\"{endpoint}.csv\")\n", + " # Pandas has a built-in way of writing CSV (or TSV, etc) files, which is helpful for getting data into \n", + " # other tools. This writes the table-ified study list to a file called studies.csv." + ] + }, + { + "cell_type": "markdown", + "id": "2279b659-f142-4000-99d3-510484465039", + "metadata": { + "tags": [] + }, + "source": [ + "Studies have been saved to file. Double-click on the file name ```studies.csv``` in the left-hand panel to open it. You can see the list of study accessions and information about each of them." + ] + }, + { + "cell_type": "markdown", + "id": "a6ce33e3-0176-469b-834d-1018ed3c291c", + "metadata": {}, + "source": [ + "#### Task 2: Explore a selected a study\n", + "\n", + "Pick a study to load and explore in more detail. In the code below we picked study MGYS00001935 as the default, however, you can choose a different study accession from [the MGnify website](https://www.ebi.ac.uk/metagenomics/browse/studies/) or from the ```studies.csv``` file you just generated. When you execute the code block below, a prompt window will appear. When that happens, paste the study accession you chose into the window and press 'Enter'. To use the default, press 'Enter' without pasting anything into the window. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d1661765-bdf8-44b5-9c10-db0ffe7fb4d5", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from lib.variable_utils import get_variable_from_link_or_input\n", + "\n", + "accession = get_variable_from_link_or_input('MGYS', 'Study Accession', 'MGYS00001935')\n", + "\n", + "# you could also assign the accession value directly:\n", + "# accession = 'MGYS00001935'" + ] + }, + { + "cell_type": "markdown", + "id": "cb54b909-6dc4-4982-bd11-f03ca830d982", + "metadata": {}, + "source": [ + "#### Fetch data for the selected study\n", + "\n", + "Load analyses from this study into a [Pandas dataframe](https://pandas.pydata.org/docs/user_guide/index.html). Pandas is a Python library that is widely used to work with and manipulate data. A dataframe is a table with rows and columns. Note that we will be using a different endpoint here because now we are fetching analyses rather than studies. You will also notice that endpoints can go several levels beyond the original URL. In this example it's original URL + `studies` + \"specific study accession\" + `analyses`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5173ced5-e607-49a2-88d1-88c57d68baaf", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "endpoint = f\"studies/{accession}/analyses\"\n", + "\n", + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as mgnify:\n", + " analyses = map(lambda r: r.json, mgnify.iterate(endpoint))\n", + " analyses = pd.json_normalize(analyses)" + ] + }, + { + "cell_type": "markdown", + "id": "8992df39-d616-464c-a2dd-bb7f5d0cb352", + "metadata": {}, + "source": [ + "#### Inspect the data\n", + "\n", + "Analyses from the study are now loaded into the dataframe ```analyses```. The ```.head()``` method prints the first few rows of the table:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1071967-42f7-4890-99dd-58d138ebffac", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "analyses.head()" + ] + }, + { + "cell_type": "markdown", + "id": "5fc2218f-0330-4e41-92f4-7c619fdcf8b2", + "metadata": {}, + "source": [ + "#### Exploring the data - Example 1: distribution of sequencing instruments used for the analysed samples" + ] + }, + { + "cell_type": "markdown", + "id": "c735f165-ae58-4e0c-a1fd-312f2701c6fd", + "metadata": {}, + "source": [ + "Let's make a plot showing what instrument type(s) were used to sequence the samples in the study we just loaded." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd8ef42e-ea80-4a55-863e-12342dddab5a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "analyses.groupby('attributes.instrument-model').size().plot(kind='pie', autopct='%1.1f%%')\n", + "plt.title('Percentages of analysed samples by instrument type');" + ] + }, + { + "cell_type": "markdown", + "id": "ce30b73c-90f6-4bfb-b0ef-5245f6f54d58", + "metadata": {}, + "source": [ + "Click on the three dots below to open up an explanation of how this code works." + ] + }, + { + "cell_type": "markdown", + "id": "5df38bd1-428e-47c9-adf2-8478ca15cf03", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, + "source": [ + "```analyses.groupby('attributes.instrument-model')```: the groupby operation here groups the data \n", + "in the dataframe ```analyses``` based on the values in the column ```attributes.instrument-model```. That means it groups the data according to the instrument models mentioned in that column.\n", + "\n", + "The ```.size()``` function is applied after grouping to count the number of occurrences (size) of each group. It counts how many samples were analyzed using each instrument model.\n", + "\n", + "```.plot(kind='pie', autopct='%1.1f%%')```: this line creates a pie chart from the grouped and counted data. The ```kind='pie'``` parameter specifies that a pie chart should be plotted. The ```autopct='%1.1f%%'``` parameter formats the percentage values in the pie chart to show one decimal place.\n", + "\n", + "```plt.title('Percentages of analysed samples by instrument type')```: this line sets the title of the pie chart to \"Percentages of analysed samples by instrument type.\"" + ] + }, + { + "cell_type": "markdown", + "id": "7ff11f02-b375-4d15-bcf0-96dcca43c99b", + "metadata": { + "tags": [] + }, + "source": [ + "#### Exploring the data - Example 2: filtering results\n", + "\n", + "You might have noticed while exploring the dataframe ```analyses``` above that the column ```attributes.analysis-summary``` contains JSONs as its values. Let's run a Python code to add the information from these JSONs as new columns to the dataframe:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cda3bcef-00fa-4473-a3c1-2751c47e160b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# First we define a function which we will call \"analysis_summary_to_df\" that will \n", + "# take the attributes.analysis-summary column, convert it into a dataframe and then \n", + "# return it as a Pandas pivot table, which is a table that summarises the dataframe\n", + "def analysis_summary_to_df(analysis):\n", + " summary_df = pd.json_normalize(analysis['attributes.analysis-summary'])\n", + " if summary_df.size:\n", + " return summary_df.pivot_table(index=None, columns=\"key\", values=\"value\", aggfunc=\"first\")\n", + " return summary_df\n", + "\n", + "\n", + "# Add a column \"summary_df\" to the dataframe \"analyses\". The column is generated using\n", + "# the function \"analysis_summary_to_df\" that we defined above and will hold the data\n", + "# from the JSONs that we are converting here.\n", + "analyses['summary_df'] = analyses.apply(analysis_summary_to_df, axis=1)\n", + "\n", + "# Now we will generate a new dataframe called analyses_summary_df\n", + "analyses_summary_df = None\n", + "\n", + "# Iterate through the rows of the analyses dataframe\n", + "for idx, row in analyses.iterrows():\n", + " # Set the index of the summary_df dataframe to the index of the line we are iterating through\n", + " row.summary_df.index = [idx]\n", + " # Add lines from summary_df to analyses_summary_df\n", + " if analyses_summary_df is None:\n", + " analyses_summary_df = row.summary_df\n", + " else:\n", + " analyses_summary_df = pd.concat([analyses_summary_df, row.summary_df])\n", + "\n", + "# Concatenate the new analyses_summary_df dataframe (which has the data from JSON in column form)\n", + "# and our original analyses dataframe and save them to a new dataframe called transformed_analyses\n", + "transformed_analyses = pd.concat([analyses, analyses_summary_df], axis=1)\n", + "\n", + "# Remove the attributes.analysis-summary and summary_df columns, we no longer need them\n", + "transformed_analyses.drop(['attributes.analysis-summary', 'summary_df'], axis=1, inplace=True)\n", + "\n", + "# View the first few lines of the updated dataframe\n", + "transformed_analyses.head()\n" + ] + }, + { + "cell_type": "markdown", + "id": "99450b02-263d-4ed0-bb1b-4987dde678b6", + "metadata": {}, + "source": [ + "Scroll to the right to see the newly added fields.\n", + "\n", + "Let's filter the results to only show analyses that have at least 1 predicted LSU (large ribosomal subunit) sequence:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e1a219d6-26e5-4e7e-8c6c-571cb32ea9d6", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Create a new dataframe called filtered_analyses which will include all lines from the\n", + "# transformed_analyses dataframe except for the ones where the value in the \"Predicted LSU sequences\"\n", + "# column is \"0\" or no value (NaN)\n", + "filtered_analyses = transformed_analyses[\n", + " ~(transformed_analyses['Predicted LSU sequences'].isin(['0']))\n", + "]\n", + "\n", + "filtered_analyses = filtered_analyses.dropna(subset=[\"Predicted LSU sequences\"])\n", + "\n", + "# print the filtered dataframe\n", + "filtered_analyses" + ] + }, + { + "cell_type": "markdown", + "id": "fefb31c2-0b37-4f26-b8e1-9a6649dbb96c", + "metadata": { + "tags": [] + }, + "source": [ + "##### Q: How many analyses have at least 1 predicted LSU? \n", + "\n", + "Hint: look at the dataframe dimensions that are printed below the dataframe. What is the number of rows? Note that some studies might not have any predicted LSU sequences and the dataframe above could be empty. \n", + "You could also find the number of rows in the dataframe by executing the code:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e0210f7-d788-48a7-b327-2763b8183bbb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "filtered_analyses.shape[0]" + ] + }, + { + "cell_type": "markdown", + "id": "c8dc54b1-7dfe-4b23-8b5e-872fd54d10f0", + "metadata": {}, + "source": [ + "You can similarly filter the results using any of the other columns depending on what you are interested in." + ] + }, + { + "cell_type": "markdown", + "id": "b38075b5-8348-4730-bdd6-2fbd4a8a8e10", + "metadata": {}, + "source": [ + "#### Exploring the data - Example 3: download the analysis results files" + ] + }, + { + "cell_type": "markdown", + "id": "814024f7-a5be-4974-b183-62ddd6360f00", + "metadata": { + "tags": [] + }, + "source": [ + "Now let's fetch the actual results files. To do that we will use the ```/analyses/{analysisId}/downloads``` endpoint. For the purposes of this exercise we will download the results for only the first 2 analyses from the unfiltered dataframe ```analyses``` but in your own work you could download them all or download only the ones that passed the filters that you applied. \n", + "\n", + "There are different result files available, let's first check which ones we could download:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "269794af-c4c8-49c3-a832-8c0ce8a5241b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as session:\n", + " for analysisId in analyses.head(2)['attributes.accession']:\n", + " print(f\"\\nFiles available for analysis {analysisId}:\")\n", + " for download in session.iterate(f\"analyses/{analysisId}/downloads\"):\n", + " print(f\"{download.alias}: {download.description.label}\")" + ] + }, + { + "cell_type": "markdown", + "id": "a697378b-a026-4748-8d0e-607835919b0a", + "metadata": {}, + "source": [ + "As an example, let's download only the tables containing the taxonomic assignments for SSU rRNA." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aef7bd3e-79d5-44cf-ba47-a8e6259c21d6", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as session: \n", + " for analysisId in analyses.head(2)['attributes.accession']:\n", + " print(f\"Processing: {analysisId}\")\n", + " for download in session.iterate(\n", + " f\"analyses/{analysisId}/downloads\"\n", + " ):\n", + " # Start another for loop to go over the files to download\n", + " OTUFiles = f\"{analysisId}_MERGED_FASTQ_SSU_OTU.tsv\"\n", + " if (\n", + " download.description.label =='OTUs, counts and taxonomic assignments for SSU rRNA'\n", + " and\n", + " download.file_format.name == 'TSV'\n", + " ):\n", + " print(f\"Downloading file for {analysisId}\")\n", + " urlretrieve(download.links.self.url, OTUFiles)\n", + " break\n", + " print(\"Finished for\", analysisId)" + ] + }, + { + "cell_type": "markdown", + "id": "b0bc7f21-ce82-4fcf-9778-f96e441c2b9e", + "metadata": {}, + "source": [ + "Click on the three dots below to see an explanation for how this code works." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8d40a77f-fd58-4d9b-a5f9-95edbc49dcbe", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, + "outputs": [], + "source": [ + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as session:\n", + " # Starting a connection to MGnify's API just like we did before\n", + " \n", + " for analysisId in analyses.head(2)['attributes.accession']:\n", + " # Here we are starting a for loop to iterate over values in the 'attributes.accession' column\n", + " # of the analyses dataframe (this column contains analysis accessions). However, we only want \n", + " # to iterate over the first two accessions which is why we use the .head(2) method to give us \n", + " # just the first 2 records.\n", + " \n", + " print(f\"Processing: {analysisId}\")\n", + " # Print the analysis accession we are currently processing\n", + " \n", + " for download in session.iterate(\n", + " f\"analyses/{analysisId}/downloads\"\n", + " ):\n", + " # Start another for loop and use the .iterate() method to retrieve information about downloads \n", + " # associated with the current analysis ID. The method call is formatted with the analysisId to \n", + " # form the specific API endpoint: analyses/{analysisId}/downloads where the value for analysisId\n", + " # will be plugged in for each iteration.\n", + " \n", + " OTUFiles = f\"{analysisId}_MERGED_FASTQ_SSU_OTU.tsv\"\n", + " # This line generates the file name of the OTU results file: analysis accession followed by the\n", + " # string \"_MERGED_FASTQ_SSU_OTU.tsv\"\n", + " \n", + " if (\n", + " download.description.label =='OTUs, counts and taxonomic assignments for SSU rRNA'\n", + " and\n", + " download.file_format.name == 'TSV'\n", + " ):\n", + " # We only want to download the OTU files in this case and not any other result files. \n", + " # This piece of code is looking for those files by checking the format and file description.\n", + " # Once the correct format and description are found, the next block of code is executed.\n", + " print(f\"Downloading file for {analysisId}\")\n", + " urlretrieve(download.links.self.url, OTUFiles)\n", + " # Fetch the file link to which is stored in download.links.self.url. When saving the file locally,\n", + " # give it the name stored in the variable OTUFiles (f\"{analysisId}_MERGED_FASTQ_SSU_OTU.tsv\")\n", + " break\n", + " # After downloading the file, the code breaks out of the inner for loop since only one matching \n", + " # file is needed for each analysis ID. We don't need to check any more records.\n", + " print(\"Finished for\", analysisId)\n" + ] + }, + { + "cell_type": "markdown", + "id": "2dd2a1af-9373-4582-81c1-b50d067ea488", + "metadata": {}, + "source": [ + "You can see the downloaded tables in the left-hand panel. Double-click the file names to open and browse them." + ] + }, + { + "cell_type": "markdown", + "id": "6d56034b-3394-4753-ac02-71913ab5a691", + "metadata": {}, + "source": [ + "---\n", + "\n", + "## Section 2: exploring the MGnify Genomes resource programmatically" + ] + }, + { + "cell_type": "markdown", + "id": "d2ff1389-1e5e-492c-a22d-cfc4838cdcab", + "metadata": {}, + "source": [ + "In this section of the practical exercise we will look at a few ways how Python can be used to explore the MGnify Genomes resource via the API. " + ] + }, + { + "cell_type": "markdown", + "id": "a0657dbc-7463-4c0c-81f3-2d770e281002", + "metadata": { + "tags": [] + }, + "source": [ + "#### Task 1: Query the ```genomes``` database from MGnify API" + ] + }, + { + "cell_type": "markdown", + "id": "57850ce0-c9b3-49e6-a66e-dc1c4fd7dffa", + "metadata": {}, + "source": [ + "We will be using the ```genomes``` endpoint to work with MGnify Genomes:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5277dccd-35b4-43b4-b53c-cd23ce655222", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "endpoint = 'genomes'" + ] + }, + { + "cell_type": "markdown", + "id": "6d4a3c41-97c7-4ff2-92d6-c3278844b409", + "metadata": {}, + "source": [ + "Let's fetch data from this endpoint and see what the first result looks like:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "967be7ab-ec02-4759-a09c-e383ab874769", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "r = requests.get(f\"https://www.ebi.ac.uk/metagenomics/api/v1/{endpoint}\")\n", + "r.json()['data'][0]" + ] + }, + { + "cell_type": "markdown", + "id": "29d32b22-ca8d-4a85-b44c-0c5a1a5e2fbd", + "metadata": {}, + "source": [ + "Here we are looking at one genome, the metadata for this genome, results summary and links. You can see what types of information we can get for each genome from this API endpoint. Take a moment to look over the output." + ] + }, + { + "cell_type": "markdown", + "id": "6b4a903a-beb9-4fe3-bde9-b280fe3472b1", + "metadata": {}, + "source": [ + "##### Q: can you spot what catalogue this genome is from?" + ] + }, + { + "cell_type": "markdown", + "id": "0202fa29-aca9-4d57-92b1-7148795443fc", + "metadata": {}, + "source": [ + "##### Q: what is the taxon lineage for this genome?" + ] + }, + { + "cell_type": "markdown", + "id": "119f301d-7b85-4744-9d38-d4908e706948", + "metadata": {}, + "source": [ + "#### Task 2: Search for a specific taxon" + ] + }, + { + "cell_type": "markdown", + "id": "17c03f3b-cba1-4f5e-ba2c-ff4041086f43", + "metadata": {}, + "source": [ + "If we are interested in a specific taxon, for example, a specific genus or species, we can find information about it from the API. \n", + "Let's use the genus Prevotella and the species Prevotella melaninogenica as our examples. \n", + "\n", + "The ```taxon-lineage``` field contains domain, phylum, class, order, family, genus, species in the following format: \n", + "```d__Bacteria;p__Bacteroidota;c__Bacteroidia;o__Bacteroidales;f__Bacteroidaceae;g__Prevotella;s__Prevotella melaninogenica```\n", + "\n", + "If we wanted to filter the database for the genus Prevotella we could use the full lineage: ```d__Bacteria;p__Bacteroidota;c__Bacteroidia;o__Bacteroidales;f__Bacteroidaceae;g__Prevotella``` \n", + "or only part of it: \n", + "```g__Prevotella``` or ```Prevotella```." + ] + }, + { + "cell_type": "markdown", + "id": "d3c8c76c-b89c-4a9e-a12f-af4b00193647", + "metadata": {}, + "source": [ + "##### Set the desired filters" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ae24320a-813b-4658-bb09-63313e8195bb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "genus_filter = 'Prevotella'\n", + "species_filter = 'Prevotella melaninogenica'" + ] + }, + { + "cell_type": "markdown", + "id": "af37a489-325f-4e9a-84a8-cfbf86839734", + "metadata": {}, + "source": [ + "##### Query the database with the species filter and save to a Pandas DataFrame" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ddb1d36f-a3a4-4d25-85a7-3b68281ccdf4", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as mgnify:\n", + " search_filter_sp = Modifier(f\"taxon_lineage={species_filter}\")\n", + " resources_sp = map(lambda r: r.json, mgnify.iterate(endpoint, filter=search_filter_sp))\n", + " resources_df_sp = pd.json_normalize(resources_sp)\n", + " \n", + "# Here we are using the Modifier function from the jsonapi_client module. It allows us \n", + "# to query for specific values in given fields (e.g.: 'taxon-lineage', 'geographic-origin').\n", + "# In this case we are adding a filter that would limit results to those that have the species\n", + "# name that we have saved in the species_filter variable (Prevotella melaninogenica) in the \n", + "# taxon_lineage field." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16da3b82-4bd3-4043-b854-6da4bf39c149", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Display the table containing the results of the query\n", + "resources_df_sp" + ] + }, + { + "cell_type": "markdown", + "id": "b8ba942c-2ca0-44e0-bab0-0e770d78db0f", + "metadata": {}, + "source": [ + "##### Q: how many times does the species occur in the catalogues? In which biomes?" + ] + }, + { + "cell_type": "markdown", + "id": "64b728c6-d3e5-4788-9d5b-72ee569d9f52", + "metadata": { + "tags": [] + }, + "source": [ + "##### Query the database with the genus filter and store the results in a Pandas DataFrame." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "491f9888-2bef-4823-8e02-4e74c4a908af", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as mgnify:\n", + " search_filter = Modifier(f\"taxon_lineage={genus_filter}\")\n", + " resources = map(lambda r: r.json, mgnify.iterate(endpoint, filter=search_filter))\n", + " resources_df = pd.json_normalize(resources)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "568c1673-91bb-4a7b-b302-308e774bc127", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Display the table containing the results of the query\n", + "resources_df" + ] + }, + { + "cell_type": "markdown", + "id": "35b45d07-292e-4ed1-860e-90c94ddfdb82", + "metadata": {}, + "source": [ + "##### Q: how many times does the genus occur in MGnify Genomes?" + ] + }, + { + "cell_type": "markdown", + "id": "e73d3b6c-5651-4db3-b877-d1eb4e9639fd", + "metadata": {}, + "source": [ + "Let's get more information on the occurrence of this genus in MGnify Genomes." + ] + }, + { + "cell_type": "markdown", + "id": "cd609c69-de91-455c-8029-ac95179be2fc", + "metadata": {}, + "source": [ + "##### Which catalogues does the genus occur in?\n", + "We can use the information from the ```relationships.catalogue.data.id``` column to generate a pie chart that shows the catalogues where the genus can be found:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "be264754-f3f9-4f34-bd53-7885c88a1d04", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "resources_df.groupby('relationships.catalogue.data.id').size().plot(kind='pie', autopct='%1.0f%%')\n", + "plt.title('Catalogues where the genus Prevotella is found');" + ] + }, + { + "cell_type": "markdown", + "id": "29a1fe11-6493-4869-95fb-95fcde52073b", + "metadata": {}, + "source": [ + "##### What are the most common species from the Prevotella genus across the catalogues?" + ] + }, + { + "cell_type": "markdown", + "id": "5f613569-d0cc-4fa6-8b42-d56f86980510", + "metadata": {}, + "source": [ + "First, let's see what the total number of distinct lineages are within the Prevotella genus across the catalogues:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "03fd27c3-c3bb-4d3a-aee1-6cd2d256bef0", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "resources_df['attributes.taxon-lineage'].nunique()" + ] + }, + { + "cell_type": "markdown", + "id": "d7542a48-d4a2-4e3b-a3d9-af610a9ec24a", + "metadata": {}, + "source": [ + "Now let's find 10 most common species:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fa81e906-e898-424d-ad8a-6a7b639c93b0", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "resources_df['attributes.taxon-lineage'].value_counts().head(10)" + ] + }, + { + "cell_type": "markdown", + "id": "7267bc06-5cb7-4e40-aa59-ca39d0b641e1", + "metadata": {}, + "source": [ + "The top record occurs in the catalogues 87 times but there is no species name (the name is ```s__``` indicating that it could not be assigned by GTDB-Tk, the tool that we use for taxonomic analysis). This indicates that the species is not yet known in GTDB. \n", + "\n", + "Note: the 87 records represent multiple unknown (novel) species. In other words, across the catalogues we have 87\n", + "species representative genomes that belong to the genus Prevotella but we don't know what species they are.\n", + "\n", + "The next most common species occurs in the catalogues 3 times and there are at least 9 species like that as we can see from the table (there are likely more but we only printed the first 10 lines). Since our catalogues are dereplicated at the species level, each species can only be found in a biome-specific catalogue once. In total we currently have 9 catalogues so we wouldn't expect the maximum number of occurences for any species to exceed 9." + ] + }, + { + "cell_type": "markdown", + "id": "1a4bf1bc-afb5-4c19-81a2-a3d51130edac", + "metadata": {}, + "source": [ + "##### Which catalogues contain the novel Prevotella species?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2664b705-3904-4c40-9ca0-701d12892398", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Save the rows containing novel Prevotella species into a new dataframe\n", + "novel_prevotella_df = resources_df[resources_df['attributes.taxon-lineage'] == 'd__Bacteria;p__Bacteroidota;c__Bacteroidia;o__Bacteroidales;f__Bacteroidaceae;g__Prevotella;s__']\n", + "# Plot the catalogues\n", + "novel_prevotella_df.groupby('relationships.catalogue.data.id').size().plot(kind='pie', autopct='%1.0f%%')\n", + "plt.title('Catalogues where the novel Prevotella species are found');\n" + ] + }, + { + "cell_type": "markdown", + "id": "93ad9b03-9cd6-411a-986a-625cb5f9afea", + "metadata": {}, + "source": [ + "##### Q: Which catalogue has a higher number of novel Prevotella species? \n", + "\n", + "##### Q: Which catalogue only contains known Prevotella species?\n", + "Hint: compare this pie chart to the previous one - which catalogue disappeared?" + ] + }, + { + "cell_type": "markdown", + "id": "eacde0da-c37f-4681-889d-f50b6b5112c1", + "metadata": {}, + "source": [ + "#### Task 3: Create a graph showing most common phyla in MGnify Genomes." + ] + }, + { + "cell_type": "markdown", + "id": "cbae69d4-594e-414d-be2a-8a5383d091a7", + "metadata": {}, + "source": [ + "For this exercise we will be working with pre-fetched data for all genomes. This is because fetching it takes a while given the number of genomes but if you were fetching it yourself, the code for that is below (expand by clicking on the three dots but please don't uncomment and execute the code)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d576840c-5535-4958-8031-5952c66532b8", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# endpoint = \"genomes\"\n", + "# with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as mgnify:\n", + "# resources_all = map(lambda r: r.json, mgnify.iterate(endpoint))\n", + "# resources_all_df = pd.json_normalize(resources_all)\n", + "# resources_all_df.to_parquet('all_genome_resources_Aug2023.parquet')" + ] + }, + { + "cell_type": "markdown", + "id": "75956486-d5a3-46dd-aaa0-0fa37fb9b94e", + "metadata": {}, + "source": [ + "The table with all genomes has been saved as a Parquet file. This file format allows for efficient data storage and retrieval.\n", + "The file is located in ../example-data/genomes/ directory and is called ```all_genome_resources_Aug2023.parquet```.\n", + "\n", + "Let's load it into a dataframe ```all_genomes_df```:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b3aa6767-a07a-4c61-88aa-011183b6fb68", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "all_genomes_df = pd.read_parquet('../example-data/genomes/all_genome_resources_Aug2023.parquet')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "96ecd56e-6208-4b2c-bba9-72ea839b12ce", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Let's check what this dataframe looks like\n", + "all_genomes_df.head()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e0baef0-f81e-44f3-bac4-69a11ca27c96", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Using Pandas we could also do some quick analysis, for example, what is the average GC content of the \n", + "# genomes in MGnify? We can use the .describe() method that calculates statistical information.\n", + "all_genomes_df['attributes.gc-content'].describe()\n" + ] + }, + { + "cell_type": "markdown", + "id": "b21346da-7af6-4c1c-86fc-20a62da31f7c", + "metadata": {}, + "source": [ + "This is telling us that in total there are 12,530 GC content records (matching the total number of species representative genomes) and the mean GC% is 47.65%.\n", + "\n", + "Now let's plot the phyla. We need to do some prep work first:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a5fc7b37-3f13-4303-866a-bd9b572edc2e", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Split taxon lineage into columns (separate column for each taxonomic level)\n", + "\n", + "# Write each possible taxonomic level into a list called \"features\"\n", + "features = ['domain', 'phylum', 'class', 'order', 'family', 'genus', 'species']\n", + "\n", + "\n", + "def get_lineage_column(lineage_str, i):\n", + " # This is a Python function that takes in a full taxonomic lineage, for example,\n", + " # d__Bacteria;p__Bacillota;c__Bacilli;o__Lactobacillales;f__Lactobacillaceae;g__Lactobacillus;s__Lactobacillus delbrueckii\n", + " # and returns the value in the requested position. In Python we count from 0 so \n", + " # if we requested the taxon name in position 1 (i = 1), the function would \n", + " # return \"p__Bacillota\"\n", + "\n", + " lineage_split = lineage_str.split(';')\n", + " return lineage_split[i] \n", + "\n", + "\n", + "# Apply the function to create the new columns in the pandas DataFrame by splitting column attributes.taxon-lineage\n", + "for i, feature in enumerate(features):\n", + " all_genomes_df[feature] = all_genomes_df['attributes.taxon-lineage'].apply(lambda x: get_lineage_column(x, i))\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "93a7404a-e8e2-4427-b1da-497b94839e5d", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Let's see what the new columns look like (scroll to the right)\n", + "all_genomes_df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1c689272-26b9-41b1-9995-67714f661456", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Use the value_counts() to get the count of each phylum in the corresponding column.\n", + "# Sort values from largest to smallest by using method .sort_values(ascending=False) and keep just the first 20\n", + "# records (20 most common phyla). Store them in the phylum_counts series (one-dimensional array).\n", + "\n", + "phylum_counts = all_genomes_df['phylum'].value_counts().sort_values(ascending=False).head(20)\n", + "phylum_counts" + ] + }, + { + "cell_type": "markdown", + "id": "22ce77b9-79a5-4e7c-8c47-682bcdcfe15d", + "metadata": {}, + "source": [ + "We can add up all counts from phylum_counts to see what proportion of all genomes are from the top 20 phyla:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ac21473-cef7-497b-b9e0-2f4872e517cb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "phylum_counts.sum()" + ] + }, + { + "cell_type": "markdown", + "id": "f1e26003-8f6c-44f1-8229-4b87c8b37c02", + "metadata": {}, + "source": [ + "This tells us that out of a total of 12,530 genomes, 12,215 are in the 20 most abundant phyla." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ada2aec3-a17f-455f-b9af-4abdc9052c33", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Create the bar plot\n", + "plt.figure(figsize=(10, 6)) # Optional: Set the figure size\n", + "phylum_counts.plot(kind='bar')\n", + "\n", + "# Optional: Customize the plot\n", + "plt.title('Occurrences of each Phylum')\n", + "plt.xlabel('Phylum')\n", + "plt.ylabel('Count')\n", + "\n", + "# Show the plot\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "43a08890-9ec5-4035-9f8a-98f1b64fddad", + "metadata": {}, + "source": [ + "#### Task 4: produce a quality control figure similar to Extended Data Fig. 4a of [Almeida et al 2020](https://www.nature.com/articles/s41587-020-0603-3/figures/10)" + ] + }, + { + "cell_type": "markdown", + "id": "90bf98a3-cd12-4e68-bf99-acb5ee45694e", + "metadata": {}, + "source": [ + "Use the ```.describe()``` method to get statistical information for the completeness and contamination columns in the ```all_genomes_df``` dataframe:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83bcf853-2032-4bf2-a9e2-a40b20c42be7", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "all_genomes_df[['attributes.completeness', 'attributes.contamination']].describe()\n" + ] + }, + { + "cell_type": "markdown", + "id": "011e2c7f-634b-4cb9-be7b-7f150936b84a", + "metadata": {}, + "source": [ + "and make a plot:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dc45345b-db52-4cf2-9e3b-6a920f9a6f26", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "fig = plt.figure(figsize=(5, 10), layout=\"constrained\") # set the size and layout\n", + "spec = fig.add_gridspec(1, 1) # set the grid\n", + "\n", + "ax00 = fig.add_subplot(spec[0, 0]) # create the placeholder for the boxplot\n", + "\n", + "# Create the boxplot using Seaborn's boxplot function. It visualizes the distribution \n", + "# of two columns from the DataFrame 'all_genomes_df': 'attributes.completeness' and 'attributes.contamination'. \n", + "# The boxplot shows the median, quartiles, and any outliers in the data for each column.\n", + "sns.boxplot(data=all_genomes_df[['attributes.completeness', 'attributes.contamination']])\n", + "\n", + "plt.ylabel(\"%\") # set the y-axis labes to show percentages\n", + "\n", + "\n", + "fig.suptitle('Quality of genomes in MGnify Genomes');" + ] + }, + { + "cell_type": "markdown", + "id": "c1cf839a-d222-4dfc-89ef-4b37a507640e", + "metadata": {}, + "source": [ + "---\n", + "## Bonus section: write your own code." + ] + }, + { + "cell_type": "markdown", + "id": "aa60ccc3-a856-4e33-9f4a-1db1ca496d7b", + "metadata": {}, + "source": [ + "The goal of this bonus section is to give you an opportunity to try and write code that access the MGnify API yourself. We will provide a template and there is a solution at the bottom if you need help." + ] + }, + { + "cell_type": "markdown", + "id": "74f885ae-b84b-4ca9-badb-2cc5ed53a089", + "metadata": {}, + "source": [ + "#### Task 1: query the API to find out how many genomes there are in catalogue." + ] + }, + { + "cell_type": "markdown", + "id": "d4a7f7c0-83a3-49b7-9ff7-497f7c652243", + "metadata": {}, + "source": [ + "First you need to find the API endpoint to use. Open [this link](https://www.ebi.ac.uk/metagenomics/api/v1/genome-catalogues) to look through the list of endpoints. You can click on them to see what information is inside. Once you have picked the endpoint, fill in the blank below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f587a45e-c800-4b5a-9580-5847632cb0c2", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "endpoint = \"_________\" # fill in the blank" + ] + }, + { + "cell_type": "markdown", + "id": "d349a613-40e7-4457-991b-ead28583df33", + "metadata": {}, + "source": [ + "Write a codeblock below that will start an API session, iterate over the pages using the chosen endpoint and get JSONs for all catalogues. Convert JSONs into a dataframe called `resources_df`. Then print just the columns that contain catalogue name and the number of species in each (the species counts are saved in a variable called `attributes.genome-count` and there are several columns that contain catalogue name, you can pick any one.\n", + "\n", + "Hint: the code for quering the API is the same we already used to fetch analyses for a selected study earlier in the practical (but the endpoint is different)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6cc2ebaa-d2a4-4a37-8e11-8708a28e1406", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "with ______(\"_____________________\") as mgnify:\n", + " resources = __________________\n", + " resources_df = __________________________\n", + "resources_df[['_____________', 'attributes.genome-count']]" + ] + }, + { + "cell_type": "markdown", + "id": "be6607da-a45e-49ab-9366-aa3cd5bcdd3f", + "metadata": {}, + "source": [ + "Click on the three dots below to open the solution" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8dcb20f4-061d-411e-8622-1ad725191621", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# Solution\n", + "endpoint = \"genome-catalogues\"\n", + "\n", + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as mgnify:\n", + " resources = map(lambda r: r.json, mgnify.iterate(endpoint))\n", + " resources_df = pd.json_normalize(resources)\n", + " \n", + "# print the columns that contain the catalogue name and the number of genomes in each catalogue\n", + "resources_df[['attributes.name', 'attributes.genome-count']]" + ] + }, + { + "cell_type": "markdown", + "id": "f68b7fc4-742f-414e-ade7-8a6f0fe5c93c", + "metadata": {}, + "source": [ + "#### Task 2: generate a pie chart that would show relative sizes of the catalogues. Add catalogue names as labels on the chart." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "983ca9d7-1c11-4054-a7f6-ce745763e053", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Fill in the blanks in this code to generate the pie chart\n", + "\n", + "# Extract the 'attributes.name' and 'attributes.genome-count' columns from the resources_df dataframe\n", + "catalogue_names = _________________________\n", + "genome_counts = __________________________\n", + "\n", + "# Create the pie chart\n", + "plt.figure(figsize=(8, 8)) # Set the figure size\n", + "plt.pie(___________, labels=__________, autopct='%1.1f%%', startangle=140)\n", + "\n", + "# Set the title\n", + "plt.title('Relative Sizes of Catalogues')\n", + "\n", + "# Show the pie chart\n", + "____________" + ] + }, + { + "cell_type": "markdown", + "id": "21290ac4-2764-44cc-85d8-be54104cfb8b", + "metadata": {}, + "source": [ + "Click on the three dots below to see the solution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f2593f45-a17b-4342-94ad-5b5b439ff016", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# Solution\n", + "# Extract the 'attributes.name' and 'attributes.genome-count' columns\n", + "catalogue_names = resources_df['attributes.name']\n", + "genome_counts = resources_df['attributes.genome-count']\n", + "\n", + "# Create the pie chart\n", + "plt.figure(figsize=(8, 8)) # Set the figure size\n", + "plt.pie(genome_counts, labels=catalogue_names, autopct='%1.1f%%', startangle=140)\n", + "\n", + "# Set the title\n", + "plt.title('Relative Sizes of Catalogues')\n", + "\n", + "# Show the pie chart\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "0b3adcca-9c2f-4a5b-91d7-10d34d294df7", + "metadata": {}, + "source": [ + "#### Task 3: download a genome from the API" + ] + }, + { + "cell_type": "markdown", + "id": "2f962ee7-2845-460c-a3f3-1e7372ed4ac5", + "metadata": {}, + "source": [ + "We have downloaded analysis results earlier in this practical (at the end of Section 1). You can download genomes and annotations in a similar way. \n", + "For this exercise, let's download all predicted CDS for genome `MGYG000321626`.\n", + "\n", + "Start by identifying the endpoint you would need for this [here](https://www.ebi.ac.uk/metagenomics/api/v1/). \n", + "\n", + "Hint: review what endpoints looked like when we downloaded analyses - they are not always just one level beyond the base URL." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f1f8111-4174-44c2-a795-ea9a7b1ab63f", + "metadata": {}, + "outputs": [], + "source": [ + "endpoint = \"______________\"" + ] + }, + { + "cell_type": "markdown", + "id": "1113c919-741c-4aad-a487-402b9d344bac", + "metadata": {}, + "source": [ + "Fill in the blanks in the code block below to download the file. To see the file format and description label that we are looking for, use the link to API, navigate to the appropriate endpoint and see what the results look like in the browser." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16381adf-54d1-4c6f-a11b-6cf6035a30c5", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "endpoint = \"___________________\" \n", + "\n", + "with APISession(\"__________________\") as session: \n", + " for download in session.iterate(endpoint):\n", + " # Go over the different files to download until we find the one with CDS results\n", + " cds_file = \"MGYG000321626.faa\"\n", + " if (\n", + " download.description.label =='_____________'\n", + " and\n", + " download.file_format.name == '_____________'\n", + " ):\n", + " print(f\"Downloading the file\")\n", + " urlretrieve(_____________________________)\n", + " break\n", + "print(\"Finished downloading\", cds_file)" + ] + }, + { + "cell_type": "markdown", + "id": "583aef6a-726a-4855-b14b-1d3b481bf920", + "metadata": {}, + "source": [ + "Click on the three dots below to see the solution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8f5821ed-268a-4030-a2a5-e5d709e28b56", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, + "outputs": [], + "source": [ + "endpoint = \"genomes/MGYG000321626/downloads\" # we are only interested in a specific genome\n", + "\n", + "with APISession(\"https://www.ebi.ac.uk/metagenomics/api/v1\") as session: \n", + " for download in session.iterate(endpoint):\n", + " # Go over the different files to download until we find the one with CDS results\n", + " cds_file = \"MGYG000321626.faa\"\n", + " if (\n", + " download.description.label =='Predicted CDS (aa)'\n", + " and\n", + " download.file_format.name == 'FASTA'\n", + " ):\n", + " print(f\"Downloading the file\")\n", + " urlretrieve(download.links.self.url, cds_file)\n", + " break\n", + "print(\"Finished downloading\", cds_file)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python (mgnify-py-env)", + "language": "python", + "name": "conda-env-mgnify-py-env-py" + }, + "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.11.0" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/src/notebooks/example-data/genomes/all_genome_resources_Aug2023.parquet b/src/notebooks/example-data/genomes/all_genome_resources_Aug2023.parquet new file mode 100644 index 0000000..b92df9a Binary files /dev/null and b/src/notebooks/example-data/genomes/all_genome_resources_Aug2023.parquet differ