Ejemplo n.º 1
0
def islandpick_genomes(request, aid):
    context = {}
    
    try:
        analysis = Analysis.objects.get(pk=aid)
        context['accnum'] = analysis.ext_id
        context['default_analysis'] = (True if analysis.default_analysis == 1 else False)
    except Analysis.DoesNotExist:
        if settings.DEBUG:
            print "Can't fetch analysis"
        return HttpResponse(status = 403)
        
    kwargs = {}

    selected = {}
    try:
        iptask = GIAnalysisTask.objects.get(aid=aid, prediction_method='Islandpick')
        
        parameters = json.loads(iptask.parameters)
        context['parameters'] = parameters

        if 'min_cutoff' in parameters:
            kwargs.update({'min_cutoff': float(parameters['min_cutoff'])})

        if 'max_distance' in parameters:
            kwargs.update({'max_cutoff': float(parameters['max_cutoff'])})

    except Exception as e:
        if settings.DEBUG:
            print e
        return HttpResponse(status = 403)

    try:
        if request.GET.get('min_cutoff'):
            kwargs.update({'min_cutoff': float(request.GET.get('min_cutoff'))})
            
        if request.GET.get('max_cutoff'):
            kwargs.update({'max_cutoff': float(request.GET.get('max_cutoff'))})

        if request.GET.get('max_dist_single_cutoff'):
            kwargs.update({'max_dist_single_cutoff': float(request.GET.get('max_dist_single_cutoff'))})

        if request.GET.get('min_compare_cutoff'):
            kwargs.update({'min_compare_cutoff': float(request.GET.get('min_compare_cutoff'))})

        if request.GET.get('max_compare_cutoff'):
            kwargs.update({'max_compare_cutoff': float(request.GET.get('max_compare_cutoff'))})
        
    except ValueError as e:
        if settings.DEBUG:
            print e
        return HttpResponse(status = 403)

    if 'comparison_genomes' in parameters:
        selected = {x: True for x in parameters['comparison_genomes'].split()}
        kwargs.update({'extra_genomes': selected})
    else:
        context['nogenomesselected'] = True
        
    genomes = Distance.find_genomes(analysis.ext_id, **kwargs)

    if request.method == 'GET':

        try:

            # Now get all the names
            ext_ids = [g for g,d in genomes]
            cache_names = NameCache.objects.filter(cid__in=ext_ids).values('cid', 'name')
            cache_names = {x['cid']:x['name'] for x in cache_names}
            cids = [int(x) for x in ext_ids if x.isdigit()]
            custom_names = CustomGenome.objects.filter(cid__in=cids).values('cid', 'name')
            custom_names = {x['cid']:x['name'] for x in custom_names}

#            cluster_list = ext_ids
#            cluster_list.insert(0, analysis.ext_id)
#            print len(cluster_list)
#            context['tree'] = Distance.distance_matrix(cluster_list)
                                    
        except Exception as e:
            print str(e)
            pass

        genome_list = OrderedDict()

        # We need the genomes to display in order
        for g,dist in sorted(genomes, key=lambda genome: genome[1]):
            # We don't want custom genomes, so skip anything without
            # a namecache entry for now
            if g not in cache_names:
                continue
            genome_list.update({g: {'dist': "%0.3f" % dist,
                                    'used': (True if g in selected else False),
                                    'picked' : (True if g in selected and 'reselect' not in request.GET else False),
                                    'name': (cache_names[g] if g in cache_names else custom_names[g] if g in custom_names else "Unknown" )
                                    }
                                })

        if request.GET.get('reselect'):
            try:
                # If we're re-selecting the candidates, make the call to the backend
                picker = send_picker(analysis.ext_id, **kwargs)
                
                if 'code' in picker and picker['code'] == 200:
                    for acc in picker['data']:
                        if "picked" in picker['data'][acc] and acc in genome_list:
                            genome_list[acc]["picked"] = 'true'
                    
                context['picker'] = picker
            except Exception as e:
                if settings.DEBUG:
                    print "Exception: " + str(e)
                context['picker'] = {'code': 500}


        context['genomes'] = genome_list
        context['status'] = "OK"            
        
        data = json.dumps(context, indent=4, sort_keys=False)
    
        return HttpResponse(data, content_type="application/json")

    else:
        try:
        
            #print request.GET.get('min_gi_size')
            accnums = []
            min_gi_size = filter(lambda x: x.isdigit(), request.GET.get('min_gi_size') )
            for name in request.POST:
                #print name, request.POST[name]
                if name not in (x[0] for  x in genomes):
                    if settings.DEBUG:
                        print "Error, " + name + " not in genomes set"
                    raise Exception("Error, requested genome isn't in the allowed set")
                accnums.append(name)

            clone_kwargs = { 'args': { 'modules': { 'Islandpick': { 'args': { 'comparison_genomes':  ' '.join(accnums), 'MIN_GI_SIZE': min_gi_size } } } } }

            # Check if we've run these settings before, if so, just redirect to that
            match_aid = Analysis.find_islandpick(analysis.ext_id, accnums, min_gi_size)
            if match_aid:
                context['status'] = 'success'
                context['aid'], token = match_aid
                if token:
                    context['token'] = token
            
            else:
                clone_ret = send_clone(aid, **clone_kwargs)
            
                if 'code' in clone_ret and clone_ret['code'] == 200:
                    if settings.DEBUG:
                        print "Job submitted, new aid: " + clone_ret['data']
                    
                    context['status'] = 'success'
                    aid = clone_ret['data']
                    context['aid'] = aid
                    try:
                        new_analysis = Analysis.objects.get(pk=aid)
                        if new_analysis.token:
                            context['token'] = new_analysis.token
                    except:
                        pass               
        
        except Exception as e:
            if settings.DEBUG:
                print "Error in post"
                print str(e)
            return HttpResponse(status = 403)

        data = json.dumps(context, indent=4, sort_keys=False)
    
        return HttpResponse(data, content_type="application/json")
Ejemplo n.º 2
0
def results(request, aid):
    # Create the context we're going to add
    # our variables for rending to
    context = {}
    context['container']=request.GET.get('container','circularchart')
    try:
        analysis = Analysis.objects.get(pk=aid)
        context['noanalysis'] = False
    except Analysis.DoesNotExist:
        context['noanalysis'] = True;

    if context['noanalysis'] != True:
        context['aid'] = aid
        context['default_analysis'] = (True if analysis.default_analysis == 1 else False)

        # Check for a security token 
        if analysis.token and analysis.owner_id != 0:
            # We have a security token
            if request.GET.get('token'):
                token = request.GET.get('token')
                if token != analysis.token:
                    # Uh-oh, the token didn't match!
                    return HttpResponse(status=403)
                    
            else:
                # There's a token in the analysis but the user didn't supply one...
                return HttpResponse(status=403)


        # Fetch the genome name and such
        if(analysis.atype == Analysis.CUSTOM):
            genome = CustomGenome.objects.get(pk=analysis.ext_id)
            context['genomename'] = genome.name
            
            if genome.contigs > 1:
                ref_accnum = analysis.find_reference_genome()
                ref_genome = Analysis.lookup_genome(ref_accnum)
                
                context['ref_genome'] = ref_genome.name
                
        elif(analysis.atype == Analysis.MICROBEDB):
#            gpv_id = Replicon.objects.using('microbedb').filter(rep_accnum=analysis.ext_id)[0].gpv_id
#            context['genomename'] = Genomeproject.objects.using('microbedb').get(pk=gpv_id).org_name
            context['genomename'] = NameCache.objects.get(cid=analysis.ext_id).name
#            context['genomename'] = 'Something from Microbedb'

        # Fetch the virulence factors
#        island_genes = Genes.objects.filter(ext_id=analysis.ext_id).order_by('start').all() 
#        vir_list = Virulence.objects.using('microbedb').filter(protein_accnum__in=
#                                                              list(island_genes.values_list('name', flat=True))).values_list('source', flat=True).distinct()
#        context['vir_types'] = {}
#        context['has_vir'] = False
#        for vir in VIRULENCE_FACTORS.keys():
#            if vir in vir_list:
#                context['vir_types'][vir] = True
#                context['has_vir'] = True
#            else:
#                context['vir_types'][vir] = False


        # Remember the methods we have available
#        context['methods'] = dict.fromkeys(GenomicIsland.objects.filter(aid_id=aid).values_list("prediction_method", flat=True).distinct(), 1)

        CHOICES = dict(STATUS_CHOICES)
        context['status'] = CHOICES[analysis.status]

        if analysis.status == STATUS['PENDING'] or analysis.status == STATUS['RUNNING']:
            try:    
                context['emails'] = ','.join(Notification.objects.filter(analysis=analysis).values_list('email', flat=True))
            except Exception as e:
                if settings.DEBUG:
                    print e
            pass    


    if request.GET.get('load'):
        context['reload'] = request.GET.get('load')

        context['showtour'] = True
    
    return render(request, 'results.html', context)