import rdflib
import urllib2

uniprot_url = 'http://www.uniprot.org/uniprot/'

rdf_prefixes = """
    PREFIX up: <http://purl.uniprot.org/core/>
    PREFIX db: <http://purl.uniprot.org/database/>
    PREFIX faldo: <http://biohackathon.org/resource/faldo#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> """


def query_protein(protein_id):
    url = uniprot_url + protein_id + '.rdf'
    g = rdflib.Graph()
    try:
        g.parse(url)
    except urllib2.HTTPError:
        print 'Could not find protein with id %s' % protein_id
        return None
    return g


def get_hgnc_name(g):
    query = rdf_prefixes + """
        SELECT ?name
        WHERE {
            ?res a up:Resource .
            ?res up:database db:HGNC .
            ?res rdfs:comment ?name .
            }
        """
    res = g.query(query)
    try:
        hgnc_name = [r for r in res][0][0].toPython()
    except TypeError:
        return None
    return hgnc_name


def get_sequence(g):
    query = rdf_prefixes + """
        SELECT ?seq
        WHERE {
            ?simple_seq a up:Simple_Sequence .
            ?simple_seq rdf:value ?seq .
            }
        """
    res = g.query(query)
    seq = [r for r in res][0][0].toPython()
    return seq


def get_modifications(g):
    query = rdf_prefixes + """
        SELECT ?beg_pos ?comment
        WHERE {
            ?mod_res a up:Modified_Residue_Annotation .
            ?mod_res rdfs:comment ?comment .
            ?mod_res up:range ?range .
            ?range faldo:begin ?beg .
            ?range faldo:end ?end .
            ?beg a faldo:ExactPosition .
            ?beg faldo:position ?beg_pos .
            FILTER (?beg = ?end)
            }
        """
    res = g.query(query)
    mods = []
    for r in res:
        mods.append((r[0].value, r[1].value))

    return mods


if __name__ == '__main__':
    g = query_protein('Q02750')
    seq = get_sequence(g)
    mods = get_modifications(g)
    hgnc_name = get_hgnc_name(g)

@@ -881,27 +881,39 @@
 (query)%0A    
-try
+if len(res) %3E 0
 :%0A        hg
@@ -964,67 +964,564 @@
     
-except TypeError:%0A        return None%0A
+    return hgnc_name%0A    else:%0A        return None%0A%0A%0Adef get_gene_name(g):%0A    # This is an alternative to get_hgnc_name and is useful when%0A    # HGNC name is not availabe (for instance, when the organism %0A    # is not homo sapiens)%0A    query = rdf_prefixes + %22%22%22%0A        SELECT ?name%0A        WHERE %7B%0A            ?gene a up:Gene .%0A            ?gene skos:prefLabel ?name .%0A            %7D%0A        %22%22%22%0A    res = g.query(query)%0A    if len(res) %3E 0:%0A        gene_name = %5Br for r in res%5D%5B0%5D%5B0%5D.toPython()%0A 
     
+   
 return 
-hgnc
+gene
 _name%0A
+    else:%0A        return None%0A   
 %0A%0Ade
@@ -2372,17 +2372,16 @@
 value))%0A
-%0A
     retu
@@ -2536,12 +2536,45 @@
 gnc_name(g)%0A
+    gene_name = get_gene_name(g)%0A

Add get_gene_name