{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "RegulomeExplorer Draft Gexpr-CNV", "version": "0.3.2", "provenance": [], "collapsed_sections": [ "v-3gnS2hsQau", "dOiLP6godt9-" ] }, "kernelspec": { "name": "python3", "display_name": "Python 3" } }, "cells": [ { "metadata": { "id": "7U3xdSiq1N4f", "colab_type": "text" }, "cell_type": "markdown", "source": [ "# Regulome Explorer Notebook 1\n", "\n", "Gene-gene correlations using PanCancer expression and copy number data.\n" ] }, { "metadata": { "id": "eTxa1hqJiDDy", "colab_type": "text" }, "cell_type": "markdown", "source": [ "## Authentication and Setup" ] }, { "metadata": { "colab_type": "text", "id": "Q9W2cFJqiGL3" }, "cell_type": "markdown", "source": [ "### Authenticate with Google (IMPORTANT)\n", "Our first step is to authenticate with Google -- you will need to be a member of a Google Cloud Platform (GCP) project, with authorization to run BigQuery jobs in order to run this notebook. If you don't have access to a GCP project, please contact the ISB-CGC team for help (www.isb-cgc.org)" ] }, { "metadata": { "colab_type": "code", "id": "JR6NGONAiGL5", "outputId": "52affb77-9d0d-4049-ab14-3b6a79cf67ea", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "from google.colab import auth\n", "try:\n", " auth.authenticate_user()\n", " print('You have been successfully authenticated!')\n", "except:\n", " print('You have not been authenticated.')" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "You have been successfully authenticated!\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "fWCknLBUiGMA" }, "cell_type": "markdown", "source": [ "### Initialize connection to BigQuery (IMPORTANT)\n", "Once you're authenticated, we'll begin getting set up to pull data out of BigQuery. \n", "\n", "The first step is to initialize the BigQuery client. This requires specifying a Google Cloud Platform (GCP) **project id** in which you have the necessary privileges (also referred to as \"roles\") to execute queries and access the data used by this notebook.\n", "\n", "Below, we use a GCP project called ``isb-cgc-bq``. If you have your own GCP project that you would like to use instead, please **edit** the line below that sets the ``project_id`` variable *before* running the next cell." ] }, { "metadata": { "colab_type": "code", "outputId": "1409751c-b783-4b21-c7b6-af3ea5e48b87", "id": "fvLoeBq7iGMB", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "from google.cloud import bigquery\n", "try:\n", " project_id = 'isb-cgc-02-0001'\n", " bqclient = bigquery.Client(project=project_id)\n", " print('BigQuery client successfully initialized')\n", "except:\n", " print('Failure to initialize BigQuery client')" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "BigQuery client successfully initialized\n" ], "name": "stdout" } ] }, { "metadata": { "id": "v-3gnS2hsQau", "colab_type": "text" }, "cell_type": "markdown", "source": [ "### Software Configuration\n", "\n", "Unless any part of this section fails to run, you only need to look at this in detail if you are interested in understanding how this notebook works or in modifying it for your own purposes. \n", "\n", "Note that running this section alone will take about **5 minutes** due to the sizes of some of the libraries being imported, as well as the number of dependent libraries. \n", "\n", "Of course, once this section has been run, you will be able to run, modify, and re-run any of the later sections of this notebook without having to come back and rerun this section (as long as you have not lost your connection to the Jupyter server)." ] }, { "metadata": { "id": "i-g6ePPSZ7eT", "colab_type": "text" }, "cell_type": "markdown", "source": [ "#### Import Python libraries\n", "\n", "Import NumPy, Pandas, and seaborn" ] }, { "metadata": { "id": "GV1ir0jGZzch", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "import numpy as np\n", "import pandas as pd\n", "import seaborn as sns" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "ig6oNOMoWHRc", "colab_type": "text" }, "cell_type": "markdown", "source": [ "#### Python convenience functions\n", "\n", "We define two convenience functions here:\n", "\n", "- **`runQuery`**: a relatively generic BigQuery query-execution wrapper function which can be used to run a query in \"dry-run\" mode or not: the call to the `query()` function itself is inside a `try/except` block and if it fails we return `None`; otherwise a \"dry\" will return an empty dataframe, and a \"live\" run will return the query results as a dataframe\n", "\n", "- **`checkQueryResults`**: a generic function that makes sure that what was returned is a dataframe, and checks how many rows are in the returned dataframe" ] }, { "metadata": { "id": "rbY7BD2xWGET", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def runQuery ( client, qString, dryRun=False ):\n", " \n", " print ( \"\\n in runQuery ... \" )\n", " if ( dryRun ):\n", " print ( \" dry-run only \" )\n", " \n", " ## set up QueryJobConfig object\n", " job_config = bigquery.QueryJobConfig()\n", " job_config.dry_run = dryRun\n", " job_config.use_query_cache = True\n", " job_config.use_legacy_sql = False\n", " \n", " ## run the query\n", " try:\n", " query_job = client.query ( qString, job_config=job_config )\n", " ## print ( \" query job state: \", query_job.state )\n", " except:\n", " print ( \" FATAL ERROR: query execution failed \" )\n", " return ( None )\n", " \n", " ## return results as a dataframe (or an empty dataframe for a dry-run) \n", " if ( not dryRun ):\n", " try:\n", " df = query_job.to_dataframe()\n", " if ( query_job.total_bytes_processed==0 ):\n", " print ( \" the results for this query were previously cached \" )\n", " else:\n", " print ( \" this query processed {} bytes \".format(query_job.total_bytes_processed) )\n", " if ( len(df) < 1 ):\n", " print ( \" WARNING: this query returned NO results \")\n", " return ( df )\n", " except:\n", " print ( \" FATAL ERROR: query execution failed \" )\n", " return ( None )\n", " \n", " else:\n", " print ( \" if not cached, this query will process {} bytes \".format(query_job.total_bytes_processed) )\n", " ## return an empty dataframe\n", " return ( pd.DataFrame() )\n", " \n", "\n", "\n", "def checkQueryResults ( qr ):\n", " print ( \"\\n in checkQueryResults ... \" )\n", " if ( not isinstance(qr, pd.DataFrame) ):\n", " print ( \" query execution failed! \" )\n", " return ( False )\n", " else:\n", " if ( len(qr) > 0 ): \n", " print ( \" # of rows in query results: {} \".format(len(qr)) )\n", " print ( \"\\n\", qr.head() )\n", " else:\n", " print ( \" query returned NO results ?!? \" ) \n", " return ( True )" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "dOiLP6godt9-", "colab_type": "text" }, "cell_type": "markdown", "source": [ "### SQL Building Functions\n" ] }, { "metadata": { "id": "flysN5k4duVC", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def build_cohort ( study ):\n", " qString = \"\"\"\n", " WITH\n", " --\n", " -- we start with the clinical table\n", " --\n", " cohort AS (\n", " SELECT\n", " acronym as Study,\n", " bcr_patient_barcode as ParticipantBarcode\n", " FROM\n", " `isb-cgc-01-0008.Filtered.clinical_PANCAN_patient_with_followup_filtered` \n", " WHERE\n", " acronym = '__study__'\n", " )\n", " \"\"\".replace('__study__',study)\n", " return(qString)\n", " " ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "L2qVcsmyd6NA", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def select_genes ( dtype, n ):\n", " if dtype == 'expr':\n", " qString = \"\"\"\n", " selected_genes AS (\n", " SELECT\n", " Symbol,\n", " STDDEV(normalized_count) AS sigmaExp\n", " FROM\n", " `isb-cgc-01-0008.Filtered.EBpp_AdjustPANCAN_RNASeqV2_filtered`\n", " WHERE\n", " Symbol IS NOT NULL\n", " AND ParticipantBarcode IN (\n", " SELECT\n", " ParticipantBarcode\n", " FROM\n", " cohort)\n", " GROUP BY\n", " 1\n", " ORDER BY\n", " sigmaExp DESC\n", " LIMIT\n", " __n__ )\n", " \"\"\".replace('__n__', str(n))\n", " \n", " elif dtype == 'cnv':\n", " qString = \"\"\"\n", " selected_genes AS (\n", " SELECT\n", " Gene_Symbols as Symbol,\n", " STDDEV(GISTIC_Calls) AS sigmaExp\n", " FROM\n", " `isb-cgc-01-0008.Filtered.all_CNVR_data_by_gene_filtered`\n", " WHERE\n", " Symbol IS NOT NULL\n", " AND ParticipantBarcode IN (\n", " SELECT\n", " ParticipantBarcode\n", " FROM\n", " cohort)\n", " GROUP BY\n", " 1\n", " ORDER BY\n", " sigmaExp DESC\n", " LIMIT\n", " __n__ )\n", " \"\"\".replace('__n__', str(n))\n", " else:\n", " # \n", " # Could be some other gene selection function here ##\n", " #\n", " qString = ''\n", " return(qString)" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "Kvc3PWFxliOH", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def get_expr_data():\n", " qString = \"\"\"\n", " expr_data AS (\n", " SELECT\n", " Symbol,\n", " ParticipantBarcode,\n", " SampleBarcode,\n", " normalized_count as expr,\n", " DENSE_RANK() OVER (PARTITION BY SampleBarcode ORDER BY normalized_count ASC) AS rankExpr\n", " FROM\n", " `isb-cgc-01-0008.Filtered.EBpp_AdjustPANCAN_RNASeqV2_filtered`\n", " WHERE\n", " Symbol IS NOT NULL AND\n", " Symbol IN (\n", " SELECT\n", " Symbol\n", " FROM\n", " selected_genes)\n", " AND ParticipantBarcode IN (\n", " SELECT\n", " ParticipantBarcode\n", " FROM\n", " cohort) \n", " )\n", " \"\"\"\n", " return(qString)\n" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "2o33wpg9mVlG", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def get_cnv_data():\n", " qString = \"\"\"\n", " cnv_data AS (\n", " SELECT\n", " Gene_Symbol as Symbol,\n", " ParticipantBarcode,\n", " SampleBarcode,\n", " GISTIC_Calls as cnv,\n", " DENSE_RANK() OVER (PARTITION BY SampleBarcode ORDER BY GISTIC_Calls ASC) AS rankCNV\n", " FROM\n", " `isb-cgc-01-0008.Filtered.all_CNVR_data_by_gene_filtered`\n", " WHERE\n", " \t Gene_Symbol IS NOT NULL AND\n", " Gene_Symbol IN (\n", " SELECT\n", " Symbol AS Gene_Symbol\n", " FROM\n", " selected_genes)\n", " AND ParticipantBarcode IN (\n", " SELECT\n", " ParticipantBarcode\n", " FROM\n", " cohort) \n", " )\n", " \"\"\"\n", " return(qString)\n", "\n" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "J_VxV7_sfmZI", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ " def join_data():\n", " qString = \"\"\"\n", " j_data AS (\n", " SELECT\n", " expr_data.Symbol as Symbol,\n", " expr_data.SampleBarcode as SampleBarcode,\n", " expr,\n", " rankExpr,\n", " cnv,\n", " rankCNV\n", " FROM\n", " expr_data JOIN cnv_data\n", " ON\n", " expr_data.SampleBarcode = cnv_data.SampleBarcode\n", " AND expr_data.Symbol = cnv_data.Symbol \n", " )\n", " \"\"\"\n", " return(qString)" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "fXQlABc1u-EU", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def comp_corr():\n", " qString = \"\"\"\n", " corr_table AS (\n", " SELECT\n", " Symbol,\n", " CORR(rankExpr,rankCNV) AS corr\n", " FROM\n", " j_data\n", " GROUP BY\n", " 1\n", " ORDER BY\n", " corr DESC\n", " )\n", " \"\"\"\n", " return(qString)\n" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "uwBhaorUy0zO", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def final( last_table ):\n", " qString = \"\"\"\n", " SELECT * FROM __last_table__\n", " \"\"\".replace('__last_table__', last_table)\n", " return(qString)\n" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "c13LfwSbzx_I", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "def build_query( study, dtype, size ):\n", " sql = (\n", " build_cohort( study ) + ',\\n' +\n", " select_genes ( dtype, size ) + ',' +\n", " get_expr_data() + ',\\n' +\n", " get_cnv_data() + ',\\n' +\n", " join_data() + ',\\n' +\n", " comp_corr() + '\\n' +\n", " final( 'corr_table' )\n", " )\n", " return(sql)" ], "execution_count": 0, "outputs": [] }, { "metadata": { "colab_type": "text", "id": "ZWIIjxKuiGMG" }, "cell_type": "markdown", "source": [ "" ] }, { "metadata": { "id": "By0ap5rf1NKq", "colab_type": "text" }, "cell_type": "markdown", "source": [ "## Select variables to analyze\n", "\n" ] }, { "metadata": { "id": "g_d7LV6jivX5", "colab_type": "text" }, "cell_type": "markdown", "source": [ "Choose a TCGA study, number of genes, and the data source to use in ranking genes." ] }, { "metadata": { "id": "vLYGUSVRjYP4", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "# select a tumor type\n", "\n", "studyList = [ 'ACC', 'BLCA', 'BRCA', 'CESC', 'CHOL', 'COAD', 'DLBC', 'ESCA', \n", " 'GBM', 'HNSC', 'KICH', 'KIRC', 'KIRP', 'LAML', 'LGG', 'LIHC', \n", " 'LUAD', 'LUSC', 'MESO', 'OV', 'PAAD', 'PCPG', 'PRAD', 'READ', \n", " 'SARC', 'SKCM', 'STAD', 'TGCT', 'THCA', 'THYM', 'UCEC', 'UCS', 'UVM' ]\n", "\n", "study = studyList[1]\n", "\n", "# choosing which genes to look at\n", "vartype = 'expr' # 'expr' or 'cnv'; to use for ranking genes\n", "n = 100 # the n most variable genes\n", "\n", "# building the query string\n", "sql = build_query (study, vartype, size)\n", "\n", "# print(sql)" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "E7jT5HX9jHOq", "colab_type": "code", "outputId": "a121ab60-9a88-49d5-f0b0-598e82d766cd", "colab": { "base_uri": "https://localhost:8080/", "height": 68 } }, "cell_type": "code", "source": [ "# calling Google! #\n", "\n", "res0 = runQuery ( bqclient, sql, dryRun=False )\n" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "\n", " in runQuery ... \n", " this query processed 23098505631 bytes \n" ], "name": "stdout" } ] }, { "metadata": { "id": "FyTzLgdN2CaT", "colab_type": "text" }, "cell_type": "markdown", "source": [ "## Results\n" ] }, { "metadata": { "id": "nWM3AVOhGEN-", "colab_type": "code", "outputId": "6331c5b6-165a-40ba-a66e-49a78c9cd38d", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "res0.shape" ], "execution_count": 0, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "(95, 2)" ] }, "metadata": { "tags": [] }, "execution_count": 122 } ] }, { "metadata": { "id": "qW85FrbELL0V", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "res0['index'] = range(0,95)" ], "execution_count": 0, "outputs": [] }, { "metadata": { "id": "NPYOVJEpMe4E", "colab_type": "code", "outputId": "dd8cd6a3-4cd4-42d3-8ca1-d5fa59f01113", "colab": { "base_uri": "https://localhost:8080/", "height": 173 } }, "cell_type": "code", "source": [ "res0[1:5]" ], "execution_count": 0, "outputs": [ { "output_type": "execute_result", "data": { "text/html": [ "
\n", " | Symbol | \n", "corr | \n", "index | \n", "
---|---|---|---|
1 | \n", "TAGLN2 | \n", "0.579321 | \n", "1 | \n", "
2 | \n", "RPL32 | \n", "0.524293 | \n", "2 | \n", "
3 | \n", "PABPC1 | \n", "0.519061 | \n", "3 | \n", "
4 | \n", "ERBB2 | \n", "0.482017 | \n", "4 | \n", "