def product_ajax_save(request):
    if request.method == "POST":
        productForm = ProductForm(request.POST, prefix='product')
        if productForm.is_valid():
            product = productForm.save()
            product.user = request.user
            product.save()
            cdsForm = CdsForm(request.POST, prefix='cds')

            cdsForm.full_clean()
            initialDict = cdsForm.cleaned_data

            initialDict['product'] = product
            updatedCdsForm = CdsForm(initial=initialDict, prefix='cds')

            t = loader.get_template('databaseInput/cdsInputTab.html')
            c = RequestContext(request, {
                'form': updatedCdsForm,
            })
            return JsonResponse({'html': t.render(c)})

        else:
            t = loader.get_template('databaseInput/addProduct.html')
            c = RequestContext(request, {
                'form': productForm,
            })
            return JsonResponse({'html': t.render(c)}, ERROR)
def origin_ajax_save(request):
    if request.method == "POST":
        originForm = OriginForm(request.POST, prefix='origin')
        if originForm.is_valid():
            origin = originForm.save()
            origin.user = request.user
            origin.save()
            cdsForm = CdsForm(request.POST, prefix='cds')

            cdsForm.full_clean()
            initialDict = cdsForm.cleaned_data

            initialDict['origin'] = origin
            updatedCdsForm = CdsForm(initial=initialDict, prefix='cds')

            t = loader.get_template('databaseInput/cdsInputTab.html')
            c = RequestContext(request, {
                'form': updatedCdsForm,
            })
            return JsonResponse({'html': t.render(c)})

        else:
            t = loader.get_template('databaseInput/addOrigin.html')
            c = RequestContext(request, {
                'form': originForm,
            })
            return JsonResponse({'html': t.render(c)}, ERROR)
def change_password(request):
    if request.method == "POST" and "oldpw" in request.POST and "newpw" in request.POST:
        if not request.user.check_password(request.POST['oldpw']):
            return JsonResponse({"field": "oldpw"}, ERROR)
        else:
            request.user.set_password(request.POST['newpw'])
            request.user.save()
            return JsonResponse({})
Exemple #4
0
def part_import(request):
    """API to import a part via AJAX"""
    if request.method == 'GET' and 'part' in request.GET:
        name = request.GET.get('part', '')
        try:
            part = Part(name)
            record = part.to_seq_record()
            Gene.add(record, 'BB', request.user)
        except Exception, e:
            return JsonResponse(e.message, ERROR)
        return JsonResponse('ok')
def save_cds_domains(request):
    if request.method == "POST":
        DomainFormSet = inlineformset_factory(Cds, Domain, form=DomainForm)
        cdsForm = CdsForm(request.POST, prefix='cds')
        if cdsForm.is_valid():
            cds = cdsForm.save(commit=False)
            cds.user = request.user
            domainFormSet = DomainFormSet(request.POST, instance=cds)
            if domainFormSet.is_valid():
                cds.save()
                domains = domainFormSet.save(commit=False)
                for domain in domains:
                    domain.user = request.user
                    domain.save()
                domainFormSet.save_m2m()
                #if successful, render cds input form with clean form again!
                t = loader.get_template('databaseInput/cdsInputTab.html')
                cdsForm = CdsForm(prefix='cds')
                c = RequestContext(
                    request, {
                        'form':
                        cdsForm,
                        'isAjax':
                        True,
                        'djangoSuccess':
                        '<strong>Well done!</strong> Successfully added new coding sequence into database!'
                    })
                return JsonResponse({'html': t.render(c)})
            else:
                t = loader.get_template('databaseInput/domainInput.html')
                c = RequestContext(request, {
                    'domainFormSet': domainFormSet,
                })
                return JsonResponse({'html': t.render(c)}, ERROR)
        else:
            # if cds form does not validate, return original page again..with appropriate error alert
            # this view is just in case and should not be returned under normal circumstances
            # as javascript checks for changes in input after prediction as well
            t = loader.get_template('databaseInput/cdsInputTab.html')
            c = RequestContext(
                request, {
                    'form':
                    cdsForm,
                    'isAjax':
                    True,
                    'djangoError':
                    '<strong>Woops..</strong>It appears the original Cds got tampered with after domain prediction. Please fix your input and try again!'
                })
            return JsonResponse({'html': t.render(c)})
    else:
        # should not be accessed via get request
        return HttpResponseBadRequest()
Exemple #6
0
def set_features(request, fid):
    """Save a fragment's features"""
    if request.method == 'POST':
        try:
            g = get_gene(request.user, fid)
            feats = request.POST.get('features')
            if feats:
                write_features(g, feats)
                return JsonResponse('Done')
            return JsonResponse('No features provided', ERROR)
        except ObjectDoesNotExist:
            JsonResponse("Fragment with ID='%s' does not exist" % fid, ERROR)
    raise Http404
Exemple #7
0
def get_fragment(request, fid):
    """Return a small amount of information about the fragment"""
    try:
        fid = int(fid)
    except ValueError:
        return JsonResponse("Invalid fragment id: %s" % fid, ERROR)
    g = get_gene(request.user, fid)
    return JsonResponse({
        'id': fid,
        'name': g.name,
        'desc': g.description,
        'length': g.length(),
        'viewable': g.viewable
    })
def domain_prediction(request):
    if request.method == "POST":
        cdsForm = CdsForm(request.POST, prefix='cds')
        if cdsForm.is_valid():
            cds = cdsForm.save(commit=False)
            #test_task = cds.predictDomains.delay()
            task = cds.predictDomains.delay()
            return JsonResponse({'taskId': task.id})
        else:
            t = loader.get_template('databaseInput/cdsInputTab.html')
            c = RequestContext(request, {
                'form': cdsForm,
                'isAjax': True,
            })
            return JsonResponse({'html': t.render(c)}, ERROR)
Exemple #9
0
def get_sequence(request, fid):
    """Stream the sequence in blocks of 1kB by default"""
    try:
        chunk_size = int(request.GET.get('chunk_size', 1024))
    except ValueError:
        return JsonResponse(
            "ERROR: Invalid chunk_size '%s'." %
            request.GET.get('chunk_size', 1024), ERROR)

    pad_char = request.GET.get('pad_char', ' ')
    g = get_gene(request.user, fid)
    if g:
        resp = HttpResponse(chunk_sequence(g, chunk_size, pad_char),
                            mimetype="text/plain")
        return resp
    return JsonResponse('Could Not Stream Sequence', ERROR)
Exemple #10
0
def list_fragments(request):
    """Return metadata of all fragments owned by a user"""
    args = {'owner': request.user, 'viewable__in': ['L', 'G']}
    try:
        if 'type[]' in request.POST:
            args['annotations__key__exact'] = 'part_type'
            args['annotations__value__in'] = request.POST.getlist('type[]')
            frags = Gene.objects.select_related('annotations').filter(**args)
        else:
            frags = Gene.objects.filter(**args)
    except ObjectDoesNotExist:
        return JsonResponse('Could not read fragments', ERROR)
    ret = []
    for f in frags:
        ret.append(read_meta(f))
    return JsonResponse(ret)
Exemple #11
0
def do_msa(request):
    if request.method == "POST":
        cdsForm = CdsForm(request.POST, prefix="cds")
        #import pdb;pdb.set_trace()
        if cdsForm.is_valid():
            cds = cdsForm.save()
            # let's modify request.POST, so that the user still gets a
            # response, even if module number has not been entered yet
            post = request.POST.copy()
            post[u'domains-module'] = u'0'

            # prefix for domainForm extracted from DomainFormSet by JS
            domainForm = DomainForm(post, prefix="domains")
            if domainForm.is_valid():

                initialDict = domainForm.cleaned_data

                del initialDict['substrateSpecificity']
                initialDict['cds'] = cds
                domain = Domain.objects.create(**initialDict)
                task = domain.align_same_type.delay()
                return JsonResponse({'taskId': task.id})
                t = loader.get_template('databaseInput/MSA_test.html')
                c = RequestContext(request, {'jsonMSA': MSA})

                domain.delete()
                cds.delete()
                return HttpResponse(t.render(c))
        else:
            return HttpResponse("")  #think of how to best handle errors..
    else:
        return HttpResponse("")
Exemple #12
0
def fragment_clipping(request, cid, cfid):
    con = get_construct(request.user, cid)
    if con:
        try:
            cf = con.cf.get(id=cfid)
        except:
            return JsonResponse('Could not find ConstructFragment(%s)' % cfid,
                                ERROR)
        t = loader.get_template('gibson/fragment_clipping.html')
        d = {
            'feature_list': cf.fragment.features.all(),
            'cfid': cfid,
            'from_absolute': not cf.start_is_relative(),
            'to_absolute': not cf.end_is_relative(),
            'length': cf.fragment.length(),
            'max': cf.fragment.length() - 1,
        }
        if cf.start_is_relative():
            d['start_feat'] = cf.start_feature.id
        d['start_offset'] = cf.start_offset
        if cf.end_is_relative():
            d['end_feat'] = cf.end_feature.id
        d['end_offset'] = cf.end_offset

        c = RequestContext(request, d)
        return HttpResponse(t.render(c))
    raise Http404
Exemple #13
0
def peptide_add(request):
    if request.method == 'POST':
        form = NRPForm(request.POST, prefix='nrp')
        if form.is_valid():
            c = form.save(commit=False)
            c.owner = request.user
            c.save()
            return JsonResponse({'url': reverse('peptides') })
        t = loader.get_template('designerGui/peptideform.html')
        con = NRP.objects.all().filter(owner=request.user)
        c = RequestContext(request, {
            'NRPform':form,
        })
        return JsonResponse({'html': t.render(c),}, ERROR)
    else:
        return HttpResponseNotFound()
Exemple #14
0
def manual_add(request):
    """Add a fragment manually"""
    if request.method == 'GET':
        meta = MetaForm(request.GET)
        seq = SequenceForm(request.GET)
        if meta.is_valid() and seq.is_valid():
            record = SeqRecord(seq.cleaned_data['seq'],
                               name=meta.cleaned_data['name'],
                               id=meta.cleaned_data['name'],
                               description=meta.cleaned_data['desc'])
            Gene.add(record, 'MN', request.user)
            return JsonResponse('OK')
        #figure out what the errors where
        errors = meta.errors
        errors.update(seq.errors)
        return JsonResponse(errors, ERROR)
    raise Http404
Exemple #15
0
def entrez_summary(request):
    """	Handle JSON Entrez summary request"""
    if request.method == 'GET' and 'id' in request.GET:
        id = request.GET['id']
        db = request.GET.get('database',
                             'nucleotide')  #assume nucleotide by default

        #fetch summary information for the id

        handle = Entrez.esummary(db=db, id=id)
        record = Entrez.read(handle)
        if record is None or len(record) < 1:
            return JsonResponse(
                "Error: Could not get summary information for id '%s'" % id,
                ERROR)
        return JsonResponse(record[0])
    raise Http404
Exemple #16
0
def get_features(request, fid):
    """Get a fragment's features"""
    g = get_gene(request.user, fid)
    return JsonResponse({
        'feats': read_features(g),
        'alpha': get_alphabet(),
        'length': len(g.sequence),
    })
Exemple #17
0
def peptide_delete(request, cid):
    peptide = NRP.objects.get(owner = request.user, pk = cid)
    if peptide:
        peptide.fullDelete()
        if request.is_ajax():
            return JsonResponse('/peptides')
        return HttpResponseRedirect('/peptides')
    else:
        return HttpResponseNotFound()
Exemple #18
0
def construct_delete(request, cid):
    con = get_construct(request.user, cid)
    if con:
        con.delete()
        if request.is_ajax():
            return JsonResponse('/gibthon')
        return HttpResponseRedirect('/gibthon')
    else:
        return HttpResponseNotFound()
Exemple #19
0
def construct_add(request):
    if request.method == 'POST':
        rp = fix_request(request.POST)
        form = ConstructForm(rp)
        if form.is_valid():
            c = form.save()
            c.owner = request.user
            c.save()
            return JsonResponse({
                'url': '/gibthon/%s/' % c.id,
            })
        t = loader.get_template('gibson/constructform.html')
        con = Construct.objects.all().filter(owner=request.user)
        c = RequestContext(request, {
            'construct_form': form,
        })
        return JsonResponse({
            'html': t.render(c),
        }, ERROR)
    else:
        return HttpResponseNotFound()
Exemple #20
0
def entrez_search(request):
    """	Handle JSON Entrez search request"""
    if request.method == 'GET':  # and request.is_ajax():
        query = request.GET.get('query', '')
        db = request.GET.get('database',
                             'nucleotide')  #assume nucleotide by default
        if query != '' and query != None:
            #fetch a list of Ids which match
            handle = Entrez.esearch(db=db, term=query)
            record = Entrez.read(handle)
            ids = record['IdList']
            if len(ids) == 0:
                return JsonResponse(
                    "No results for search '%s' on database '%s'." %
                    (query, db), ERROR)
            else:
                return JsonResponse(ids)
        else:
            return JsonResponse("Error: Blank search query", ERROR)

    raise Http404
Exemple #21
0
def entrez_import(request):
    """Handle a request to import an ID"""
    if request.method == 'GET' and 'id' in request.GET:
        id = request.GET['id']
        db = request.GET.get('database',
                             'nucleotide')  #assume nucleotide by default
        handle = Entrez.efetch(db=db, id=id, rettype="gb")
        records = SeqIO.parse(handle, 'gb')
        for r in records:
            if len(Gene.objects.filter(name=r.name, owner=request.user)) == 0:
                Gene.add(r, 'NT', request.user)
        return JsonResponse("Imported id '%s' from Entrez." % id)

    raise Http404
Exemple #22
0
def set_meta(request, fid):
    """Update a fragment's metadata"""
    if request.method == 'POST':
        try:
            g = get_gene(request.user, fid)
            meta = {
                'name': request.POST.get('name'),
                'desc': request.POST.get('desc'),
            }
            meta['annots'] = []
            for i in range(0, len(request.POST) - 2):
                m = request.POST.getlist('annots[%s][]' % i)
                if m:
                    meta['annots'].append(m)
            print 'meta = %s' % meta
            if meta:
                write_meta(g, meta)
                return get_meta(request, fid)
            return JsonResponse("No metadata supplied.", ERROR)
        except ObjectDoesNotExist:
            return JsonResponse("Fragment with ID='%s' does not exist." % fid,
                                ERROR)
    raise Http404
Exemple #23
0
def getConstruct(request, pid):
    nrp = NRP.objects.get(owner=request.user, pk=pid)
    if not nrp.designed:
        return makeConstruct(request, pid)
    elif nrp.construct is None or nrp.construct.fragments.count() == 0:
        con = nrp.makeConstruct()
    con = nrp.construct
    constructId = con.pk
    designTabLink = reverse('design_tab', kwargs= {'cid' : constructId})
    primerTabLink = reverse('primers', kwargs= {'cid' : constructId})
    domainSequenceTabLink = reverse('domainSequence', kwargs = {'pid' : pid})
    return JsonResponse({"constructId": constructId,
                         'designTabLink': designTabLink,
                         'primerTabLink': primerTabLink,
                         'domainSequenceTablLink': domainSequenceTabLink})
Exemple #24
0
def get_predicted_domain_formset(request, task_id):
    if request.method == "POST":
        initialDict = AsyncResult(task_id).get()
        t = loader.get_template('databaseInput/domainInput.html')
        DomainFormSet = inlineformset_factory(Cds,
                                              Domain,
                                              form=DomainForm,
                                              extra=len(initialDict))
        c = RequestContext(request, {
            'domainFormSet': DomainFormSet(initial=initialDict),
        })
        #return HttpResponse(t.render(c))
        return JsonResponse({
            'html': t.render(c),
        })
Exemple #25
0
def celery_task_log(request, task_id):
    task = AsyncResult(task_id)
    out = dict()
    if task.ready() and task.successful():
        out = {'status': 'SUCCESS'}
    elif task.ready() and task.failed():
        out = {'status': 'FAILED', 'output': str(task.result)}
    elif task.status == "log":
        if 'log' in task.result:
            task_log = task.result['log']
        else:
            task_log = []
        out = {'status': 'log', 'output': task_log}
    else:
        out = {'status': task.status}
    out['taskId'] = task_id
    return JsonResponse(out)
Exemple #26
0
def processLibrary(request, pid):
    if request.method == 'POST':
        data = json.loads(request.body)
        monomers = []
        haveUseAll = -1
        i = 0
        for m in data['as']:
            monomers.append(m[0])
            if len(m) > 1 and m[1] == True:
                haveUseAll = i
            i += 1
        if haveUseAll != -1:
            for m in data['as']:
                del m[1:]
            substrates = get_available_substrates(monomers, True, data['curatedonly'], haveUseAll)
            scaffold = data['as'][haveUseAll][0]
            for s in substrates:
                if s.pk != scaffold:
                    data['as'][haveUseAll].append(s.pk)
        nrp = NRP.objects.get(owner=request.user, pk=pid)
        return JsonResponse({'taskId': nrp.makeLibrary.delay(data['as'], data['curatedonly']).id})
Exemple #27
0
def construct_fragment(request, cid):
    con = get_construct(request.user, cid)
    if con and not request.is_ajax():
        t = loader.get_template('gibson/constructfragment.html')
        cf_list = con.cf.all()
        feature_list = [FeatureListForm(cf, con) for cf in cf_list]
        list = zip(cf_list, feature_list)
        c = RequestContext(request, {'list': list})
        return HttpResponse(t.render(c))
    if con and request.is_ajax():
        cf_list = con.cf.all()
        frag_list = [{
            'fid': cf.fragment.id,
            'cfid': cf.id,
            'name': cf.fragment.name,
            'desc': cf.fragment.description,
            'length': abs(cf.end() - cf.start()),
        } for cf in cf_list]
        return JsonResponse(frag_list)

    return HttpResponseNotFound()
Exemple #28
0
def get_available_monomers(request):
    if request.method == 'POST' and "monomer[]" in request.POST:
        monomers = request.POST.getlist("monomer[]")
        if 'selected' in request.POST:
            selected = int(request.POST['selected'])
        else:
            selected = None
        aas = get_available_substrates(monomers, toBool(request.POST['current']), toBool(request.POST['curatedonly']), selected)
    else:
        aas = filter(lambda x: x.can_be_added(), Substrate.objects.exclude(user__username='******'))
    json = {}
    minid = float("Inf")
    for aa in aas:
        if aa.parent is None:
            name = aa.name
            if aa.name[0:2].upper() == 'L-' or aa.name[0:2].upper() == 'D-':
                name = aa.name[2:]
            if aa.pk in json:
                key = aa.pk
            elif aa.enantiomer is not None and aa.enantiomer.pk in json:
                key = aa.enantiomer.pk
            else:
                key = None
            if aa.enantiomer is None:
                chirality = 'N'
            else:
                chirality = aa.chirality
            if key is not None:
                if key < minid:
                    minid = key
                json[key][chirality.lower() + "id"] = aa.pk
                json[key][chirality+'Children'] = [{"text": c.name, "id": c.pk} for c in aa.child.all()]
                #names[name]['name'] = name
            else:
                json[aa.pk] = {"id": aa.pk, chirality.lower() + "id": aa.pk, 'text': name, aa.chirality+'Children': [{"text": c.name, "id": c.pk} for c in aa.child.all()]}

    jsonlist = json.values()
    jsonlist.sort(lambda x,y: cmp(x['text'], y['text']))
    return JsonResponse({"monomers": json, "monomerslist": jsonlist})
Exemple #29
0
def makeConstruct(request,pid):
    nrp = NRP.objects.get(owner=request.user, pk=pid)
    nrp.designed = False
    return JsonResponse({'taskId': nrp.designDomains.delay(toBool(request.POST['curatedonly'])).id})
Exemple #30
0
def apply_clipping(request, cid, cfid):
    con = get_construct(request.user, cid)
    if con:
        try:
            cf = con.cf.get(id=cfid)
        except:
            return JsonResponse('Could not find ConstructFragment(%s)' % cfid,
                                ERROR)

        try:
            f_type = request.POST['from_type'].lower()
            t_type = request.POST['to_type'].lower()

            if f_type == 'absolute':
                start = int(request.POST['from_abs'])
                if start < 0 or start > cf.fragment.length() - 1:
                    raise ValueError('"start" must be within range [0:%i]' %
                                     cf.fragment.length() - 1)
                if cf.start_offset != start or cf.start_feature != None:
                    cf.start_offset = start
                    cf.start_feature = None
                    con.processed = False
            elif f_type == 'relative':
                start = int(request.POST['from_rel'])
                start_fid = int(request.POST['start_feat'])
                print "available ids are %s" % [
                    feat.id for feat in cf.fragment.features.all()
                ]
                start_feature = cf.fragment.features.get(id=start_fid)
                if cf.start_offset != start or cf.start_feature != start_feature:
                    cf.start_offset = start
                    cf.start_feature = start_feature
                    con.processed = False
            else:
                raise ValueError('"f_type" must be "absolute" or "relative"')

            if t_type == 'absolute':
                end = int(request.POST['to_abs'])
                if end < 0 or end > cf.fragment.length() - 1:
                    raise ValueError('"end" must be within range [0:%i]' %
                                     cf.fragment.length() - 1)
                if cf.end_offset != end or cf.end_feature != None:
                    cf.end_offset = end
                    cf.end_feature = None
                    con.processed = False
            elif t_type == 'relative':
                end = int(request.POST['to_rel'])
                end_fid = int(request.POST['end_feat'])
                end_feature = cf.fragment.features.get(id=end_fid)
                if cf.end_offset != end or cf.end_feature != end_feature:
                    cf.end_offset = end
                    cf.end_feature = end_feature
                    con.processed = False
            else:
                raise ValueError('"t_type" must be "absolute" or "relative"')

        except KeyError as e:
            return JsonResponse('Value required for "%s"' % e.message, ERROR)
        except ValueError as e:
            return JsonResponse('ValueError: %s' % e.message, ERROR)
        except ObjectDoesNotExist as e:
            return JsonResponse(
                'DoesNotExist: %s (%s)' % (e.message, start_fid), ERROR)

        cf.save()
        con.save()
        return JsonResponse('OK')
    raise Http404