# Path: inmembrane/plugins/tmhmm.py
# def parse_tmhmm(text, proteins, id_mapping=[]):
#     seqid = None
#     for i_line, l in enumerate(text.split('\n')):
#         if i_line == 0:
#             continue
#         words = l.split()
#         if not words:
#             continue
# 
#         if l.startswith("#"):
#             seqid = parse_fasta_header(words[1])[0]
#         else:
#             seqid = parse_fasta_header(words[0])[0]
#         if seqid is None:
#             continue
# 
#         # re-map from a safe_seqid to the original seqid
#         if id_mapping:
#             seqid = id_mapping[seqid]
# 
#         # initialize fields in proteins[seqid]
#         if 'tmhmm_helices' not in proteins[seqid]:
#             proteins[seqid].update({
#                 'tmhmm_helices': [],
#                 'tmhmm_inner_loops': [],
#                 'tmhmm_outer_loops': []
#             })
# 
#         if 'inside' in l:
#             proteins[seqid]['tmhmm_inner_loops'].append(
#                 (int(words[-2]), int(words[-1])))
#         if 'outside' in l:
#             proteins[seqid]['tmhmm_outer_loops'].append(
#                 (int(words[-2]), int(words[-1])))
#         if 'TMhelix' in l:
#             proteins[seqid]['tmhmm_helices'].append(
#                 (int(words[-2]), int(words[-1])))
# 
#     return proteins
# 
# Path: inmembrane/helpers.py
# def log_stderr(s, width=76, comment=True):
#     """
#     Wrapper for all stderr out. Allows future customization.
#     """
#     if LOG_SILENT:
#         return
#     if s and s[-1] != "\n":
#         s += "\n"
#     if not s.startswith("#"):
#         s = "# " + s
#     sys.stderr.write(s)
# 
# Path: inmembrane/helpers.py
# def generate_safe_seqids(proteins):
#     """
#     Takes a 'proteins' dictionary, keyed by sequence id, and
#     adds a 'safe' sequence id ('safe_seqid') that is less likely
#     to be munged or break various external programs.
# 
#     Returns a tuple of the updated proteins dictionary and a dictionary
#     mapping the 'safe' sequence ids to the original ids.
#     """
#     id_mapping = {}
#     count = 0
#     for seqid in proteins:
#         safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count`
#         id_mapping[safe_id] = seqid
#         proteins[seqid]['safe_seqid'] = safe_id
#         count += 1
# 
#     return (proteins, id_mapping)
# 
# def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50):
#     """
#     Takes a proteins dictionary and returns a string containing
#     all the sequences in FASTA format. Option parameters are
#     a list of seqids to output (seqids) and the line width (width).
#     """
#     if seqids:
#         idlist = seqids
#     else:
#         idlist = proteins
# 
#     fasta_out = ""
#     for seqid in idlist:
#         seq_wrap = textwrap.fill(proteins[seqid]['seq'], width)
#         if use_safe_seqid:
#             header = proteins[seqid]['safe_seqid']
#         else:
#             header = proteins[seqid]['name']
#         fasta_out += ">%s\n%s\n" % (header, seq_wrap)
#     return fasta_out


import sys, os, time
import requests
import inmembrane
from StringIO import StringIO
from BeautifulSoup import BeautifulSoup
    from collections import OrderedDict
    from ordereddict import OrderedDict
from inmembrane.plugins.tmhmm import parse_tmhmm
from inmembrane.helpers import log_stderr
from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta

try:
except:



def annotate(params, proteins, \
             batchsize=500, \
             force=False):
    """
    This plugin interfaces with the TMHMM web interface (for humans) and
    scrapes the results. There once was a SOAP service but it was discontinued,
    so now we use this.
    """

    baseurl = "http://www.cbs.dtu.dk"
    url = baseurl + '/cgi-bin/webface2.fcgi'

    # grab the cached results if present
    outfile = "tmhmm_scrape_web.out"
    if not force and os.path.isfile(outfile):
        log_stderr("# -> skipped: %s already exists" % outfile)
        proteins, id_mapping = generate_safe_seqids(proteins)
        fh = open(outfile, 'r')
        resultpage = fh.read()
        fh.close()
        # soup = BeautifulSoup(resultpage)
        proteins = parse_tmhmm(resultpage, proteins, id_mapping=id_mapping)
        return proteins


# Path: inmembrane/plugins/tmhmm.py
# def parse_tmhmm(text, proteins, id_mapping=[]):
#     seqid = None
#     for i_line, l in enumerate(text.split('\n')):
#         if i_line == 0:
#             continue
#         words = l.split()
#         if not words:
#             continue
# 
#         if l.startswith("#"):
#             seqid = parse_fasta_header(words[1])[0]
#         else:
#             seqid = parse_fasta_header(words[0])[0]
#         if seqid is None:
#             continue
# 
#         # re-map from a safe_seqid to the original seqid
#         if id_mapping:
#             seqid = id_mapping[seqid]
# 
#         # initialize fields in proteins[seqid]
#         if 'tmhmm_helices' not in proteins[seqid]:
#             proteins[seqid].update({
#                 'tmhmm_helices': [],
#                 'tmhmm_inner_loops': [],
#                 'tmhmm_outer_loops': []
#             })
# 
#         if 'inside' in l:
#             proteins[seqid]['tmhmm_inner_loops'].append(
#                 (int(words[-2]), int(words[-1])))
#         if 'outside' in l:
#             proteins[seqid]['tmhmm_outer_loops'].append(
#                 (int(words[-2]), int(words[-1])))
#         if 'TMhelix' in l:
#             proteins[seqid]['tmhmm_helices'].append(
#                 (int(words[-2]), int(words[-1])))
# 
#     return proteins
# 
# Path: inmembrane/helpers.py
# def log_stderr(s, width=76, comment=True):
#     """
#     Wrapper for all stderr out. Allows future customization.
#     """
#     if LOG_SILENT:
#         return
#     if s and s[-1] != "\n":
#         s += "\n"
#     if not s.startswith("#"):
#         s = "# " + s
#     sys.stderr.write(s)
# 
# Path: inmembrane/helpers.py
# def generate_safe_seqids(proteins):
#     """
#     Takes a 'proteins' dictionary, keyed by sequence id, and
#     adds a 'safe' sequence id ('safe_seqid') that is less likely
#     to be munged or break various external programs.
# 
#     Returns a tuple of the updated proteins dictionary and a dictionary
#     mapping the 'safe' sequence ids to the original ids.
#     """
#     id_mapping = {}
#     count = 0
#     for seqid in proteins:
#         safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count`
#         id_mapping[safe_id] = seqid
#         proteins[seqid]['safe_seqid'] = safe_id
#         count += 1
# 
#     return (proteins, id_mapping)
# 
# def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50):
#     """
#     Takes a proteins dictionary and returns a string containing
#     all the sequences in FASTA format. Option parameters are
#     a list of seqids to output (seqids) and the line width (width).
#     """
#     if seqids:
#         idlist = seqids
#     else:
#         idlist = proteins
# 
#     fasta_out = ""
#     for seqid in idlist:
#         seq_wrap = textwrap.fill(proteins[seqid]['seq'], width)
#         if use_safe_seqid:
#             header = proteins[seqid]['safe_seqid']
#         else:
#             header = proteins[seqid]['name']
#         fasta_out += ">%s\n%s\n" % (header, seq_wrap)
#     return fasta_out


# Path: inmembrane/plugins/tmhmm_scrape_web.py
import sys, os, time
import requests
import inmembrane
from StringIO import StringIO
from BeautifulSoup import BeautifulSoup
    from collections import OrderedDict
    from ordereddict import OrderedDict
from inmembrane.plugins.tmhmm import parse_tmhmm
from inmembrane.helpers import log_stderr
from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta


try:
except:



def annotate(params, proteins, \
             batchsize=500, \
             force=False):
    """
    This plugin interfaces with the TMHMM web interface (for humans) and
    scrapes the results. There once was a SOAP service but it was discontinued,
    so now we use this.
    """

    baseurl = "http://www.cbs.dtu.dk"
    url = baseurl + '/cgi-bin/webface2.fcgi'

    # grab the cached results if present
    outfile = "tmhmm_scrape_web.out"
    if not force and os.path.isfile(outfile):
        log_stderr("# -> skipped: %s already exists" % outfile)
        proteins, id_mapping = generate_safe_seqids(proteins)
        fh = open(outfile, 'r')
        resultpage = fh.read()
        fh.close()
        # soup = BeautifulSoup(resultpage)
        proteins = parse_tmhmm(resultpage, proteins, id_mapping=id_mapping)
        return proteins


    proteins, id_mapping = generate_safe_seqids(proteins)