def sequence(request):

    if 'sequence_id' in request.GET:

        uniprot, phogs, best_phogs, orthologs, phog_of_ortholog, error = \
            getOrthologQuerySet(
                request.GET['sequence_id'],
                request.GET.get('ortholog_type', OrthologTypes.PHOG_T_Medium),
                request.GET.get('threshold', 0.296874),
            )

        return render_to_response('hpy/sequence.html', {
            'phog_rows': [PHOGRow(phog) for phog in best_phogs],
        })

    return render_to_response('hpy/sequence.html', {})
def orthologs_as_csv(request, sequence_id):
  ortholog_type = OrthologTypes.SuperOrtholog
  threshold = 0.0
  if 'ortholog_type' in request.GET:
    ortholog_type_str = request.GET['ortholog_type']
    m = gi_re.match(ortholog_type_str)
    if m and len(m.group()) == len(ortholog_type_str):
      try:
        ortholog_type = int(ortholog_type_str)
        if ortholog_type < OrthologTypes.SuperOrtholog \
            or ortholog_type > OrthologTypes.PHOG_T_Custom:
          ortholog_type = OrthologTypes.SuperOrtholog
      except ValueError:
        ortholog_type = OrthologTypes.SuperOrtholog
    if ortholog_type == OrthologTypes.PHOG_T_Custom and \
        'threshold' in request.GET:
      threshold_str = request.GET['threshold']
      m = float_re.search(threshold_str)
      if m and len(m.group()) == len(threshold_str):
        try:
          threshold = float(threshold_str)
          if threshold < 0.0:
            threshold = 0.0
        except ValueError:
          threshold = 0.0
  (ownUniProt, phogs, best_phogs, 
   ortholog_set, phog_of_ortholog, error) \
    = getOrthologQuerySet(sequence_id, ortholog_type = ortholog_type,
                          threshold = threshold)
  if ortholog_type == OrthologTypes.SuperOrtholog:
    suffix = ''
  elif ortholog_type == OrthologTypes.PHOG_T_Tight:
    suffix = 'TC'
  elif ortholog_type == OrthologTypes.PHOG_T_Medium:
    suffix = 'TM'
  elif ortholog_type == OrthologTypes.PHOG_T_Loose:
    suffix = 'TD'
  elif ortholog_type == OrthologTypes.PHOG_T_Custom:
    suffix = 'T%g' % threshold
  filename = "%s-orthologs_%g.csv" % (sequence_id, threshold)
  return csv_ortholog_table_response(ortholog_set, error, filename, 
                                      includePHOG = True, 
                                      ortholog_type = ortholog_type,
                                      threshold = threshold,
                                      phog_of_ortholog = phog_of_ortholog)
def main():
    threshold = preset_thresholds[OrthologTypes.PHOG_T_Tight]
    ortholog_type = OrthologTypes.PHOG_T_Tight
    (ownUniProt, phogs, best_phogs,
      orthologs, phog_of_ortholog, error) \
        = getOrthologQuerySet('OXYR_HUMAN', ortholog_type, threshold)
    print "Got %d tight orthologs" % len(orthologs)
    num_queries_for_tight_orthologs = len(connection.queries)
    cum_queries_for_tight_orthologs = len(connection.queries)
    print "%d queries were made to get tight orthologs" \
            % num_queries_for_tight_orthologs
    tight_orthologs_time = 0.0
    for query in connection.queries:
        tight_orthologs_time += float(query['time'])
    print "Total time for tight orthologs: %0.3f" % tight_orthologs_time
    phog_rows = [
        PHOGRow(phog, ortholog_type, threshold) for phog in best_phogs
    ]
    print "Got %d tight PHOGRows" % len(phog_rows)
    num_queries_for_tight_phogrows \
      = len(connection.queries) - cum_queries_for_tight_orthologs
    cum_queries_for_tight_phogrows = len(connection.queries)
    print "%d queries were made to get tight PHOGRows" \
            % num_queries_for_tight_phogrows
    tight_phogrows_time = 0.0
    for query in connection.queries[cum_queries_for_tight_orthologs:]:
        tight_phogrows_time += float(query['time'])
    print "Total time for tight PHOGRows: %0.3f" % tight_phogrows_time
    for phog_row in phog_rows:
        print phog_row.accession, "%d sequences" \
          % phog_row.num_nonredundant_sequences
    threshold = 0.1
    ortholog_type = OrthologTypes.PHOG_T_Custom
    (ownUniProt, phogs, best_phogs,
      orthologs, phog_of_ortholog, error) \
        = getOrthologQuerySet('OXYR_HUMAN', ortholog_type, threshold)
    print "Got %d custom orthologs at threshold 0.1" % len(orthologs)
    num_queries_for_custom_orthologs \
      = len(connection.queries) - cum_queries_for_tight_phogrows
    cum_queries_for_custom_orthologs = len(connection.queries)
    print "%d queries were made to get custom orthologs" \
            % num_queries_for_custom_orthologs
    custom_orthologs_time = 0.0
    for query in connection.queries[cum_queries_for_tight_phogrows:]:
        custom_orthologs_time += float(query['time'])
    print "Total time for custom orthologs: %0.3f" % custom_orthologs_time
    phog_rows = [
        PHOGRow(phog, ortholog_type, threshold) for phog in best_phogs
    ]
    print "Got %d custom PHOGRows" % len(phog_rows)
    num_queries_for_custom_phogrows \
      = len(connection.queries) - cum_queries_for_custom_orthologs
    cum_queries_for_custom_phogrows = len(connection.queries)
    print "%d queries were made to get custom PHOGRows" \
            % num_queries_for_custom_phogrows
    custom_phogrows_time = 0.0
    for query in connection.queries[cum_queries_for_custom_orthologs:]:
        custom_phogrows_time += float(query['time'])
    print "Total time for custom PHOGRows: %0.3f" % custom_phogrows_time
    for phog_row in phog_rows:
        print phog_row.accession, "%d sequences" \
          % phog_row.num_nonredundant_sequences
    threshold = preset_thresholds[OrthologTypes.PHOG_T_Loose]
    ortholog_type = OrthologTypes.PHOG_T_Loose
    (ownUniProt, phogs, best_phogs,
      orthologs, phog_of_ortholog, error) \
        = getOrthologQuerySet('OXYR_HUMAN', ortholog_type, threshold)
    print "Got %d loose orthologs" % len(orthologs)
    num_queries_for_loose_orthologs = \
        len(connection.queries) - cum_queries_for_custom_phogrows
    cum_queries_for_loose_orthologs = len(connection.queries)
    print "%d queries were made to get loose orthologs" \
            % num_queries_for_loose_orthologs
    loose_orthologs_time = 0.0
    for query in connection.queries[cum_queries_for_custom_phogrows:]:
        loose_orthologs_time += float(query['time'])
    print "Total time for loose orthologs: %0.3f" % loose_orthologs_time
    phog_rows = [
        PHOGRow(phog, ortholog_type, threshold) for phog in best_phogs
    ]
    print "Got %d loose PHOGRows" % len(phog_rows)
    num_queries_for_loose_phogrows \
      = len(connection.queries) - cum_queries_for_loose_orthologs
    cum_queries_for_loose_phogrows = len(connection.queries)
    print "%d queries were made to get loose PHOGRows" \
            % num_queries_for_loose_phogrows
    loose_phogrows_time = 0.0
    for query in connection.queries[cum_queries_for_loose_orthologs:]:
        loose_phogrows_time += float(query['time'])
    print "Total time for loose PHOGRows: %0.3f" % loose_phogrows_time
    for phog_row in phog_rows:
        print phog_row.accession, "%d sequences" \
          % phog_row.num_nonredundant_sequences
    print "Tight ortholog queries: "
    print_query_range(0, cum_queries_for_tight_orthologs)
    print "Tight PHOGRow queries: "
    print_query_range(cum_queries_for_tight_orthologs,
                      cum_queries_for_tight_phogrows)
    print "Custom ortholog queries: "
    print_query_range(cum_queries_for_tight_phogrows,
                      cum_queries_for_custom_orthologs)
    print "Custom PHOGRow queries: "
    print_query_range(cum_queries_for_custom_orthologs,
                      cum_queries_for_custom_phogrows)
    print "Loose ortholog queries: "
    print_query_range(cum_queries_for_custom_phogrows,
                      cum_queries_for_loose_orthologs)
    print "Loose PHOGRow queries: "
    print_query_range(cum_queries_for_loose_orthologs,
                      cum_queries_for_loose_phogrows)
def netscope(request, sequence_id=None):
    if 'sequence_id' in request.GET:
      putative_sequence_id = request.GET['sequence_id'].rstrip()
      m = phog_re.match(putative_sequence_id.upper())
      if m and len(m.group()) == len(putative_sequence_id):
        redirect_url = "/net/%s" % putative_sequence_id
        return HttpResponseRedirect(redirect_url)
      #m = scopid_re.match(putative_sequence_id.lower())
      #if not m:
      #  m = bpgid_re.match(putative_sequence_id.lower())
      #if m and len(m.group()) == len(putative_sequence_id):
      #  redirect_url = "/family/%s" % putative_sequence_id
      #  return HttpResponseRedirect(redirect_url)
    context = {'page_title': "PHOG Interactome Viewer"}
    context_for_datagrid = {}
    #if sequence_id == None and \
    #      ('sequence_id' not in request.GET or \
    #        request.GET['sequence_id'] == u'') and \
    #    'sequence_fasta' in request.GET and \
    #    request.GET['sequence_fasta'] != u'':
    #  m = fasta_re.match(request.GET['sequence_fasta'])
    #  if m:
    #    (sequence_id, record) = get_uniprot_id_from_fasta(request.GET['sequence_fasta'])
    #    sequence_id = None
    #    if not record is None:
    #      return approximate_matches(request, record, context)
    #    else:
    #      context['fasta_error'] = 'Invalid FASTA sequence'
    #  else:
    #    context['fasta_error'] = 'Invalid FASTA sequence'
    if sequence_id != None or \
        ('sequence_id' in request.GET and \
          request.GET['sequence_id'] != request.GET['sequence_id'].upper()):
      if not sequence_id:
        sequence_id = request.GET['sequence_id'].rstrip()
      sequence_id = sequence_id.upper().rstrip()
      newGET = request.GET.copy()
      newGET.update({'sequence_id': sequence_id})
      request.GET = newGET
      context['sequence_id'] = sequence_id
      context_for_datagrid['extra_query'] = "sequence_id=%s&" % sequence_id
      form = OrthologForm(request.GET)
      form.sequence_id = sequence_id
    elif 'sequence_id' in request.GET:
      sequence_id = request.GET['sequence_id'].rstrip()
      context['sequence_id'] = request.GET['sequence_id']
      context_for_datagrid['extra_query'] \
        = "sequence_id=%s" % request.GET['sequence_id']
      form = OrthologForm(request.GET)
      form.sequence_id = request.GET['sequence_id']
    else: 
      form = OrthologForm()
    context['form'] = form
    if form.is_bound and form.is_valid() and sequence_id != None and \
        sequence_id != u'':
      if form.non_field_errors():
        context['form_error'] = form.non_field_errors().as_text()
      else:
        # For some reason, ortholog_type comes in as Unicode
        try:
          ortholog_type = int(form.cleaned_data['ortholog_type']) 
        except ValueError:
          ortholog_type = OrthologTypes.SuperOrtholog
        threshold = form.cleaned_data['threshold']
        # threshold = preset_thresholds[ortholog_type]
        if (OrthologTypes.SuperOrtholog == ortholog_type):
          context['threshold_type']  = "Super orthology"
        elif (OrthologTypes.PHOG_T_Tight == ortholog_type):
          context['threshold_type']  = "Close"
        elif (OrthologTypes.PHOG_T_Medium == ortholog_type):
          context['threshold_type']  = "Moderate"
        elif (OrthologTypes.PHOG_T_Loose == ortholog_type):
          context['threshold_type']  = "Distant"
        elif (OrthologTypes.PHOG_T_Custom == ortholog_type):
          context['threshold_type']  = "Custom"
        else:
          context['threshold_type']  = "Unknown"
        context_for_datagrid['extra_query'] \
          = context_for_datagrid['extra_query'] \
          + "&ortholog_type=%d&threshold=%g" % (ortholog_type, threshold)
        (ownUniProt, phogs, best_phogs, 
            orthologs, phog_of_ortholog, error) \
          = getOrthologQuerySet(form.cleaned_data['sequence_id'],
                                ortholog_type, threshold)
        if (error != None):
            context['db_error'] = error
        else:
            have_nontrivial_phogs = False
            for phog in phogs.all():
              if phog.get_num_nonredundant_sequences(ortholog_type,
                                                      threshold) >= 2:
                have_nontrivial_phogs = True
            if not have_nontrivial_phogs:
              context['db_error'] = not_in_phog(sequence_id)
              return render_to_response('ppi/netscope.html', context)
            context['query_description'] = ownUniProt.description
            context['query_species'] = ownUniProt.taxon.scientific_name
            
            taxon = ownUniProt.taxon
            taxon_id = taxon.id

            (edge_list, node_coords, filename, observed_partners, predicted_partners) = \
                        run_netscope(ownUniProt, taxon, ortholog_type, threshold)
            context['edge_list']         = edge_list
            context['node_coords']       = node_coords
            context['filename']          = filename
            context['taxon_scientific']  = taxon.scientific_name
            context['taxon_common']      = taxon.common_name
            context['query_sequence_id'] = ownUniProt.id
            context['threshold']         = threshold
            context['ortholog_type']     = ortholog_type

            observed_partner_rows = []
            for partner in observed_partners:
              observed_partner_rows.append(PartnerRow(partner[0], partner[1]))
            context['observed_partners'] = observed_partner_rows

            predicted_partner_rows = []
            for partner in predicted_partners:
              predicted_partner_rows.append(PartnerRow(partner))
            context['predicted_partners'] = predicted_partner_rows

            return render_to_response('ppi/netscope.html', context)
    return render_to_response('ppi/netscope.html', context)
def orthologs(request, sequence_id=None):
    with_family_type = request.GET.get('with_family_type', False)
    for_iframe = request.GET.get('for_iframe', False)
    if 'sequence_id' in request.GET:
      putative_sequence_id = request.GET['sequence_id'].strip()
      m = phog_re.match(putative_sequence_id.upper())
      if m and len(m.group()) == len(putative_sequence_id):
        redirect_url = "/phog/%s" % putative_sequence_id
        return HttpResponseRedirect(redirect_url)
      m = scopid_re.match(putative_sequence_id.lower())
      if not m:
        m = bpgid_re.match(putative_sequence_id.lower())
      if m and len(m.group()) == len(putative_sequence_id):
        redirect_url = "/family/%s" % putative_sequence_id
        return HttpResponseRedirect(redirect_url)
    context = {'page_title': "PHOGs: PhyloFacts Orthology Groups"}
    context_for_datagrid = {}
    if sequence_id == None and \
          ('sequence_id' not in request.GET or \
            request.GET['sequence_id'] == u'') and \
        'sequence_fasta' in request.GET and \
        request.GET['sequence_fasta'] != u'':
      m = fasta_re.match(request.GET['sequence_fasta'])
      if m:
        (sequence_id, record) = get_uniprot_id_from_fasta(request.GET['sequence_fasta'])
        sequence_id = None
        if not record is None:
          return approximate_matches(request, record, context)
        else:
          context['fasta_error'] = 'Invalid FASTA sequence'
      else:
        context['fasta_error'] = 'Invalid FASTA sequence'
    if sequence_id != None or \
        ('sequence_id' in request.GET and \
          request.GET['sequence_id'] != request.GET['sequence_id'].upper()):
      if not sequence_id:
        sequence_id = request.GET['sequence_id'].rstrip()
      sequence_id = sequence_id.upper().rstrip()
      newGET = request.GET.copy()
      newGET.update({'sequence_id': sequence_id})
      request.GET = newGET
      context['sequence_id'] = sequence_id
      context_for_datagrid['extra_query'] = "sequence_id=%s&" % sequence_id
      form = OrthologForm(request.GET)
      form.sequence_id = sequence_id
    elif 'sequence_id' in request.GET:
      sequence_id = request.GET['sequence_id'].rstrip()
      context['sequence_id'] = request.GET['sequence_id']
      context_for_datagrid['extra_query'] \
        = "sequence_id=%s" % request.GET['sequence_id']
      form = OrthologForm(request.GET)
      form.sequence_id = request.GET['sequence_id']
    else:
      form = OrthologForm()
    context['form'] = form
    if form.is_bound and form.is_valid() and sequence_id != None and \
        sequence_id != u'':
      if form.non_field_errors():
        context['form_error'] = form.non_field_errors().as_text()
      else:
        # For some reason, ortholog_type comes in as Unicode
        try:
          ortholog_type = int(form.cleaned_data['ortholog_type']) 
        except ValueError:
          ortholog_type = OrthologTypes.SuperOrtholog
        threshold = form.cleaned_data['threshold']
        context_for_datagrid['extra_query'] \
          = context_for_datagrid['extra_query'] \
          + "&ortholog_type=%d&threshold=%g" % (ortholog_type, threshold)
        if with_family_type:
            context_for_datagrid['extra_query'] += '&with_family_type=1'
        if for_iframe:
            context_for_datagrid['extra_query'] += '&for_iframe=1'
        (ownUniProt, phogs, best_phogs, 
            orthologs, phog_of_ortholog, error) \
          = getOrthologQuerySet(form.cleaned_data['sequence_id'],
                                ortholog_type, threshold)
        if (error != None):
            context['db_error'] = error
        else:
            have_nontrivial_phogs = False
            for phog in phogs.all():
              if phog.get_num_nonredundant_sequences(ortholog_type,
                                                      threshold) >= 2:
                have_nontrivial_phogs = True
            if not have_nontrivial_phogs:
              context['db_error'] = not_in_phog(sequence_id)
              return render_to_response('phog/orthologs.html', context)
            phog_rows = [PHOGRow(phog, ortholog_type, threshold) 
                          for phog in phogs]
            context['phogs'] = phog_rows
            
            #context['phogs'] = []
            context['query_description'] = ownUniProt.de
            context['query_species'] = ownUniProt.taxon.scientific_name

            # Determine if the ppi link should be shown and set appropriate
            # context variable if it should.
            context['show_ppi_link'] = False
            # FIXME: 2010/06/13 RSD
            # Commenting this out since we currently don't have the PPI data in
            # the schema or models in the database, let alone populated.
            """
            for ortholog in orthologs:
              if bool(ortholog.sequence_header.uniprot.get_interacting_partners()):
                context['show_ppi_link'] = True
                # context['ortholog_type'] = ortholog_type
                context['netscope_url'] = \
                 ortholog.sequence_header.uniprot.get_netscope_url(ortholog_type, threshold)
                break
            """

            ## @@@ this is not sufficient as the sequence header identifier may differ
            ##     from the sequence id, resulting in no url being stored.
            # Put url for the query into a context variable.
            # for ortholog in orthologs:
            #   if sequence_id == ortholog.sequence_header.identifier():
            #     context['query_url'] = ortholog.sequence_header.get_absolute_url()

            n_sequences_of_family = {}
            for phog in phogs:
              n_sequences = phog.tree.family.canonical_root_node(
                  ).get_num_included_leaves(OrthologTypes.PHOG_T_Custom, 
                                            threshold = 10000.0)
              n_sequences_of_family[phog.tree.family] = n_sequences
            return OrthologDataGrid(request, orthologs, 
                  with_family_type = with_family_type,
                  uniprot = ownUniProt,
                  ortholog_type = ortholog_type,
                  threshold = threshold,
                  phog_of_ortholog = phog_of_ortholog,
                  n_sequences_of_family = n_sequences_of_family,
                  extra_context=context_for_datagrid).render_to_response(
                                          for_iframe and 'phog/orthologs_for_iframe.html' or 'phog/orthologs.html',
                                          context)
    return render_to_response('phog/orthologs.html', context)