Esempio n. 1
0
def svgview(request, tree_id, tree_src=None):
    with get_treestore() as treestore:
        if not tree_src: tree_src = '/trees/%s/download?format=newick' % tree_id
        
        return render_to_response(
            'svgview.html',
            {'tree_src': tree_src, 'tree_id': tree_id, 'tree_uri': uri_from_tree_id(tree_id)},
            context_instance=RequestContext(request)
        )
Esempio n. 2
0
def view(request, tree_id=None):
    with get_treestore() as treestore:
        tree_uri = uri_from_tree_id(tree_id)
        
        params = {
                  'tree_uri': tree_uri,
                  'tree_id': tree_id,
                  'formats': sorted(bp._io.supported_formats.keys()) + ['ascii'],
                  }
                  
        try:
            all_tree_info = treestore.get_tree_info(tree_uri)
            tree_info = {}
            tree_info.update(all_tree_info[0])
            tree_info['citation'] = []
            for x in all_tree_info:
                if x['citation']: tree_info['citation'].append(x['citation'])
        except IndexError:
            raise Http404
            return not_found(request, tree_uri)
        obj_info = treestore.get_object_info(tree_uri)
        prefixes = treestore.prefixes
        def add_prefix(x):
            for prefix, uri in prefixes:
                if x.startswith(uri):
                    if prefix == 'obo':
                        try: return 'cdao:%s (obo:%s)' % (obo_to_cdao[x[len(uri):]], x[len(uri):])
                        except: pass
                    return '%s:%s' % (prefix, x[len(uri):])
            return x
        obj_info = [sum([(x, add_prefix(x)) for x in row], ()) for row in obj_info]
        
        params.update(tree_info)
        params['obj_info'] = obj_info
            
        return render_to_response(
            'view.html',
            params,
            context_instance=RequestContext(request)
        )
Esempio n. 3
0
def download(request, tree_id=None):
    with get_treestore() as treestore:
        tree_uri = uri_from_tree_id(tree_id)

        if 'format' in request.GET:
            format = request.GET.get('format')
        else: format = 'newick'

        if format == 'taxa_list':
            # download list of taxa
            names = treestore.get_names(tree_uri)
            spp_list = ','.join(names)
            return download_plaintext(request, spp_list)

        trees = treestore.get_trees(tree_uri=tree_uri)
        response = HttpResponse(mimetype='text/plain')
        if format == 'ascii':
            bp._utils.draw_ascii(trees[0], file=response)
        else: 
            bp.write(trees, response, format)

        return download_plaintext(request, response=response)
Esempio n. 4
0
def upload_approve(request, tree_id):
    submission = TreeSubmission.objects.get(id=tree_id)
    tree_id = submission.tree_id
    file_path = submission.tree_file.path
    
    try:
        tree = bp.read(file_path, submission.format)
        with get_treestore() as treestore:
            treestore.add_trees(file_path, submission.format,
                                tree_uri=uri_from_tree_id(tree_id))
                                
            
            text = 'Successfully uploaded <b>%s</b>.' % (uri_from_tree_id(tree_id))
            
            submission.delete()

    except Exception as e:
        text = '<b>ERROR:</b> <p>%s</p>' % e
    
    response = HttpResponse(mimetype='text/html')
    response.write(text)

    return response
Esempio n. 5
0
def tree_list(request):
    with get_treestore() as treestore:
        if request.method == 'POST':
            form = SearchForm(request.POST)
            if form.is_valid():
                taxa = form.cleaned_data['taxa']
                filter = form.cleaned_data['filter']
                params = [(x, y) for x, y in form.cleaned_data.items()]
                return redirect('/trees/?' + urllib.urlencode(params))
        else:    
            taxa = request.GET.get('taxa')
            filter = request.GET.get('filter')
            filter = filter if filter else None

            form = SearchForm(initial=request.GET)
            form.full_clean()

        taxa = [x.strip() for x in taxa.split(',')] if taxa else []
        
        params = {'form': form, 'taxonomy':settings.DEFAULT_TAXONOMY}
        params.update(csrf(request))
        
        try:
            trees = list(treestore.list_trees_containing_taxa(contains=taxa, filter=filter, 
                            taxonomy=settings.DEFAULT_TAXONOMY, show_counts=True))
        except Exception as e:
            errors = form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())
            err_msg = "There was a problem with your search: %s" % e
            errors.append(err_msg)
            
            return render_to_response(
                'list.html',
                params,
                context_instance=RequestContext(request)
            )
            
        trees = [(tree_id_from_uri(m[0]), int(m[1])) for m in trees]
        paginator = Paginator(trees, TREES_PER_PAGE)
        
        page = request.GET.get('page')
        try:
            tree_list = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            tree_list = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            tree_list = paginator.page(paginator.num_pages)
        
        params.update({'tree_list': tree_list,
                       'max_match_count': len(taxa)})

        num_pages = paginator.num_pages
        page_range = [n for n in range(tree_list.number - 2, tree_list.number + 3) 
                      if n >= 1 and n <= num_pages]

        params.update({
            'total_results': len(trees),
            'low_result': TREES_PER_PAGE * (tree_list.number - 1) + 1,
            'high_result': min(len(trees), TREES_PER_PAGE * tree_list.number)
            })
        
        if page_range[0] == 2: page_range = [1] + page_range
        elif page_range[0] > 2: page_range = [1, '...'] + page_range
        
        if page_range[-1] == num_pages - 1: page_range += [num_pages]
        elif page_range[-1] < num_pages - 1: page_range += ['...', num_pages]
        
        pages = []
        
        for page in page_range:
            if page == '...': pages.append((page, None))
            else:
                p = []
                for arg in ('taxa', 'filter'):
                    if arg in request.GET:
                        p += [(arg, request.GET.get(arg))]
                p += [('page', page)]
                pages.append((page, '/trees/?' + urllib.urlencode(p)))
        
        params['pages'] = pages
        
        return render_to_response(
            'list.html',
            params,
            context_instance=RequestContext(request)
        )
Esempio n. 6
0
def query(request):
    with get_treestore() as treestore:
        tree_uri = None
        params = {
            'taxa': '',
            'format': 'view',
            'prune': True,
            'tree': None,
            'filter': '',
            'taxonomy': settings.DEFAULT_TAXONOMY,
            }
        
        if request.method == 'POST':
            form = QueryForm(request.POST)
            if form.is_valid():
                url = '/query/?' + urllib.urlencode(form.cleaned_data.items())
                if len(url) < 200: return redirect(url)
                params.update(form.cleaned_data)
                submitted_query = True
            else:
                submitted_query = False
            
        elif request.method == 'GET' and 'taxa' in request.GET:
            submitted_query = True
            taxa = request.GET.get('taxa')
            params.update(request.GET.dict())
            if 'prune' in request.GET: params['prune'] = params['prune'] == 'True'
            form = QueryForm(initial=request.GET.dict())
            form.full_clean()
            
        else:
            submitted_query = False
            form = QueryForm(initial=request.GET.dict())
        

        best_match = params['tree'] == 'best'
        
        if submitted_query:
            if best_match: tree_uri = None
            else: tree_uri = uri_from_tree_id(params['tree']) if params['tree'] else None
            taxonomy = uri_from_tree_id(params['taxonomy']) if params['taxonomy'] else None
            
            if params['format'] == 'view' and tree_uri:
                params['format'] = 'newick'
                tree_src = '/query/?' + urllib.urlencode(params.items())

                return treeview.views.svgview(request, params['tree'], tree_src=tree_src)
            
            # execute the query and return the result as a plaintext tree
            contains = [t.strip() for t in params['taxa'].split(',')]
            
            e = None
            response = None
            
            if tree_uri is None:
                # 'select automatically' was chosen; perform the disambiguation step
                # if there are more than one matching tree
                trees = None
                matches = []
                try:
                    for match in treestore.list_trees_containing_taxa(contains=contains, 
                                                                      show_counts=True,
                                                                      taxonomy=taxonomy,
                                                                      filter=params['filter']):
                        if int(match[1]) < 2 and params['prune']:
                            if not matches:
                                raise Exception("The top match only matched one taxon, which isn't enough to make a tree. Try unchecking the 'prune results' checkbox or changing your search.")
                            break
                        matches.append((match[0], int(match[1])))
                        if len(matches) >= (1 if best_match else MAX_DISAMBIG_MATCHES): break

                except Exception as e:
                    trees = None
                
                if matches and not e:
                    if best_match:
                        if params['format'] == 'view':
                            params['format'] = 'newick'
                            params['tree'] = matches[0][0]
                            tree_src = '/query/?' + urllib.urlencode(params.items())

                            return treeview.views.svgview(request, tree_id_from_uri(matches[0][0]), 
                                                          tree_src=tree_src)

                        response = HttpResponse(mimetype='text/plain')
                        treestore.get_subtree(contains=contains,
                                              tree_uri=matches[0][0],
                                              format=params['format'],
                                              prune=params['prune'],
                                              filter=params['filter'],
                                              taxonomy=taxonomy,
                                              handle=response)
                    else: return query_disambiguate(request, matches, params)
                elif not e:
                    trees = None
                    e = 'There were no trees that matched your query.'
                
                    
            else:
                try:
                    response = HttpResponse(mimetype='text/plain')
                    treestore.get_subtree(contains=contains,
                                          tree_uri=tree_uri,
                                          format=params['format'],
                                          prune=params['prune'],
                                          filter=params['filter'],
                                          taxonomy=taxonomy,
                                          handle=response)
                except Exception as e:
                    trees = None
                    exception = e
                    
            if response:
                return download_plaintext(request, response=response)
            elif trees:
                return download_plaintext(request, trees)
                
            else:
                errors = form._errors.setdefault(NON_FIELD_ERRORS, ErrorList())
                if e:
                    errors.append('There was a problem with your query: %s' % e)
                else:
                    err_msg = "Your query didn't return a result. Try entering a new list of taxa"
                    if tree_uri: err_msg += ' or selecting a different tree'
                    err_msg += '.'
                    errors.append(err_msg)
            
            
        # show the query builder page
                
        params = {
                  'form': form,
                  'domain': settings.DOMAIN.rstrip('/'),
                  'tree_uri': settings.TREE_URI,
                  }
        params.update(csrf(request))
                
        return render_to_response(
            'query.html',
            params,
            context_instance=RequestContext(request)
        )