BridgeDb workflow: Gene HGNC name to Ensembl identifier

public public 1yr ago Version: master @ 0f98fd8 0 bookmarks

This tutorial explains how to use the BridgeDb identifier mapping service to translate HGNC names to Ensembl identifiers. This step is part of the OpenRiskNet use case to link Adverse Outcome Pathways to WikiPathways .

Code Snippets

 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Here are the packages imported in to the program. (be sure that the are installed).
import requests
import pandas
import urllib

import seaborn as sns
import matplotlib.pyplot as plt

from IPython.display import display, HTML
from SPARQLWrapper import SPARQLWrapper, JSON
15
16
17
18
# Here are the three url's, of the web-page's that will be used, stored as variables.. 
chemidconvert = 'https://chemidconvert.cloud.douglasconnect.com/v1/'
tggatesconvert = 'http://open-tggates-api.cloud.douglasconnect.com/v2/'
bridgedb = "http://bridgedb.prod.openrisknet.org/Human/xrefs/X/"
22
23
24
25
"""This set, contains the chemical names of the compound that are used in this notebook.
To research different compounds, you need to change the names.
"""
compoundset = {'paracetamol', 'acetominophen', 'methapyrilene', 'phenylbutazone', 'simvastatin', 'valproic acid'}
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
pandas.set_option('display.max_colwidth', -1)  # Make the table.
compounds = pandas.DataFrame(columns=['Compound name', 'Smiles', 'Image'])

# Fill "compounds" with the "smiles" by the compound name.
for compound in compoundset:
    smiles = requests.get(chemidconvert + 'name/to/smiles', params={'name': compound}).json()['smiles']
    compounds = compounds.append({'Compound name': compound, 'Smiles': smiles, 'Image': smiles}, ignore_index=True)


def smiles_to_image_html(smiles):  # "smiles" shadows "smiles" from outer scope, use this function only in "to_html().
    """Gets for each smile the image, in HTML.
    :param smiles: Takes the “smiles” form “compounds”.
    :return: The HTML code for the image of the given smiles.
    """
    return '<img style="width:150px" src="' + chemidconvert+'asSvg?smiles='+urllib.parse.quote(smiles)+'"/>'


# Return a HTML table of "compounds", after "compounds" is fill by "smiles_to_image_html".
HTML(compounds.to_html(escape=False, formatters=dict(Image=smiles_to_image_html)))
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Get the names from "compoundset" and put a “|” between them for the "TGGATES".                                         
compounds_name = "|".join(compoundset)
compounds_name

#  Get more information from the "TGGATES" about the compounds by "compounds_name".                                      
r2 = requests.get(tggatesconvert + 'samples',
                  params={'limit': 10000, 'compoundNameFilter': compounds_name,
                          'organismFilter': 'Human', 'tissueFilter': 'Liver',
                          'cellTypeFilter': 'in vitro', 'repeatTypeFilter': 'Single',
                          'timepointHrFilter': '24.0', 'doseLevelFilter': 'High'
                          })

# The "TGGATES" status code is printed and, verified if it is 200; and thereafter transform to a jason. 
# The "TGGATES" status code is printed, to show the user that it is "200" (or not).
print("TGGATES Status code: " + str(r2.status_code))
samples = None
if r2.status_code == 200:  # It is checked whether the status code is "200".                                                                                              
    samples = r2.json()  # the received data from "TGGATES" is stored in the variable "samples" as json format.                                                                                             
    # Print the 'samples' information of the "samples" as a data frame.                                                      
    print(pandas.DataFrame(samples['samples']))
else:
    print("samples has not been created, because the TGGATES status code was not 200. The code will now exit.")
    exit(1)
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
# Again contact is maid with "TGGATES" to get more information from the samples.


#  The important variable "foldchanges" (which will be used till the last coding block) is made. 
foldchanges = pandas.DataFrame


for sample in samples["samples"]:
    sampleId = sample["sampleId"]
    sampleName = sample["compoundName"] + "\n" + sample["sampleId"]
    r3 = requests.get(tggatesconvert+'results',
                      params={'limit': 'none', 'sampleIdFilter': sampleId,
                              'valueTypeFilter': 'log2fold', 'pValueMax': '0.1'})  # The query is execute.

    """The  status code of the query is checked,
    and a temporarily data frame ("df") is created,
    to store the results of the query.
    """
    df = None
    if r3.status_code == 200:
        data = r3.json()
        df = pandas.DataFrame(data['results'])
        df = df.filter(items=['assayId', 'value'])
        df.columns = ['ProbeSet', sampleName]
    else:
        print("samples has not been created, because the TGGATES Status code was not 200. The code will now exit.")
        exit(1)

    # Every Temporarily data frame is added to  "foldchanges".
    if foldchanges.empty:
        foldchanges = df
    else:
        foldchanges = pandas.merge(foldchanges, df, how='outer', on=['ProbeSet'])
113
114
115
116
117
118
119
120
121
122
"""The variable "high" is set to be "true",
so that the "Bitwise Operator" "&" is true, as long as the foldchanges are not higher then 1
"""
high = True 

# Compare the fold change of the "samples", and chose the highest.
for sample in samples["samples"]:
    high = high & (foldchanges[sample["compoundName"] + "\n" + sample["sampleId"]] >= 1)

foldchanges = foldchanges[high]
131
% matplotlib inline
135
136
137
138
139
140
# Makes the heat map.
for_vis = foldchanges.set_index('ProbeSet')
plt.figure(figsize=(4, 4))
sns.set(font="Dejavu sans")
sns_plot = sns.heatmap(for_vis)  # type: object
sns_plot
144
145
146
147
#  Get the "Ensembl" and the "HGNC" in "foldchanges" as columns.
da = "?dataSource="  # The final part part to finis the url.
foldchanges['Ensembl'] = foldchanges.ProbeSet.apply(lambda url: requests.get(bridgedb+url+da+"En").text.split("\t")[0])
foldchanges['HGNC'] = foldchanges.ProbeSet.apply(lambda url: requests.get(bridgedb+url+da+"H").text.split("\t")[0])
155
156
# SPARQLWrapper makes it possible to use sparql queries on the web-page.
sparql = SPARQLWrapper("http://sparql.wikipathways.org")
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# This is the creation of a data frame to store and represent data created in this coding block.
pathways = pandas.DataFrame(columns=['Gene', 'Ensembl', 'Pathway', 'Pathway Res', 'Pathway Title'])

genes = foldchanges['Ensembl']  # Here we continue with the "foldchanges".
results = None
for gene in genes:
    # Here the queries are made en the results are stored in "results".
    pathwayQuery = '''
      SELECT DISTINCT ?ensembl ?pathwayRes (str(?wpid) as ?pathway) (str(?title) as ?pathwayTitle)
      WHERE {{
        ?gene a wp:GeneProduct ;
          dcterms:identifier ?id ;
          dcterms:isPartOf ?pathwayRes ;
          wp:bdbEnsembl <http://identifiers.org/ensembl/{0}> .
        ?pathwayRes a wp:Pathway ;
          dcterms:identifier ?wpid ;
          dc:title ?title .
        BIND ( "{0}" AS ?ensembl )
      }}
    '''.format(gene)
    sparql.setQuery(pathwayQuery)
    sparql.setReturnFormat(JSON)  # Here the queries are made en the results are stored in "results".
    results = sparql.query().convert()

    for result in results["results"]["bindings"]:
        pathways = pathways.append({
            'Gene': foldchanges.loc[foldchanges['Ensembl'] == gene].iloc[0]["HGNC"],
            'Ensembl': result["ensembl"]["value"],
            'Pathway': result["pathway"]["value"],
            'Pathway Res': result["pathwayRes"]["value"],
            'Pathway Title': result["pathwayTitle"]["value"],
        }, ignore_index=True)
6
callUrl = 'https://webservice.bridgedb.org/Human/xrefs/H/MECP2'
15
16
17
18
19
20
21
22
23
24
25
lines = response.text.split("\n")
mappings = {}
for line in lines:
    if ('\t' in line):
        tuple = line.split('\t')
        identifier = tuple[0]
        database = tuple[1]
        if (database == "Ensembl"):
            mappings[identifier] = database

print(mappings)
29
30
31
callUrl = 'https://webservice.bridgedb.org/Human/xrefs/H/MECP2?dataSource=En'
response = requests.get(callUrl)
response.text
ShowHide 13 more snippets with no or duplicated tags.

Login to post a comment if you would like to share your experience with this workflow.

Do you know this workflow well? If so, you can request seller status , and start supporting this workflow.

Free

Created: 1yr ago
Updated: 1yr ago
Maitainers: public
URL: https://github.com/OpenRiskNet/notebooks.git
Name: bridgedb-tutorial-gene-hgnc-name-to-ensembl-identi
Version: master @ 0f98fd8
Badge:
workflow icon

Insert copied code into your website to add a link to this workflow.

Downloaded: 0
Copyright: Public Domain
License: None
  • Future updates

Related Workflows

cellranger-snakemake-gke
snakemake workflow to run cellranger on a given bucket using gke.
A Snakemake workflow for running cellranger on a given bucket using Google Kubernetes Engine. The usage of this workflow ...