Example #1
0
def getStructures(request, job_id, format):

    # takes a search job ID and returns an SDF of the compounds from this result

    try:
        job = updateJob(request.user, job_id)
        f = open(job.output, 'r')
        csvinput = csv.reader(f, delimiter=' ')
        #read each line, extrace the second column, and combine all values
        #into a new-line separated string
        targetIds = "\n".join([line[0] for line in csvinput])
        print("targetIds: " + str(targetIds))
        f.close()
        #result = '\n'.join(re.findall(r'^\S+', result, re.MULTILINE))
    except Job.DoesNotExist:
        print(traceback.format_exc())
        raise Http404
    newJob = createJob(request.user,
                       'pubchemID2SDF',
                       '', [],
                       targetIds,
                       format,
                       wait=True)
    if format == 'smiles':
        filename = 'search_result.smi'
    else:
        filename = 'search_result.sdf'
    return redirect(tools.views.view_job,
                    job_id=newJob.id,
                    resource='other',
                    filename=filename)
Example #2
0
def getStructures(request, job_id, format):

    # takes a search job ID and returns an SDF of the compounds from this result

    try:
        job = updateJob(request.user, job_id)
        f = open(job.output, 'r')
        result = f.read()
        f.close()
        result = join(re.findall(r'^\S+', result, re.MULTILINE), sep='\n')
    except Job.DoesNotExist:
        raise Http404
    newJob = createJob(request.user,
                       'pubchemID2SDF',
                       '', [],
                       result,
                       format,
                       async=False)
    if format == 'smiles':
        filename = 'search_result.smi'
    else:
        filename = 'search_result.sdf'
    return redirect('tools.views.view_job',
                    job_id=newJob.id,
                    resource='other',
                    filename=filename)
Example #3
0
def getStructures(request, job_id, format):

    # takes a search job ID and returns an SDF of the compounds from this result

    try:
        job = updateJob(request.user, job_id)
        f = open(job.output, "r")
        result = f.read()
        f.close()
        result = join(re.findall(r"^\S+", result, re.MULTILINE), sep="\n")
    except Job.DoesNotExist:
        raise Http404
    newJob = createJob(request.user, "pubchemID2SDF", "", [], result, format, async=False)
    if format == "smiles":
        filename = "search_result.smi"
    else:
        filename = "search_result.sdf"
    return redirect("tools.views.view_job", job_id=newJob.id, resource="other", filename=filename)
Example #4
0
def getStructures(request, job_id, format):

    # takes a search job ID and returns an SDF of the compounds from this result 

    try:
        job = updateJob(request.user, job_id)
        f = open(job.output, 'r')
        result = f.read()
        f.close() 
        result = join(re.findall(r'^\S+', result, re.MULTILINE), sep='\n')
    except Job.DoesNotExist:
        raise Http404
    newJob = createJob(request.user, 'pubchemID2SDF', '', '', result,
                       format, async=False) 
    if format == 'smiles':
        filename = 'search_result.smi'
    else:
        filename = 'search_result.sdf' 
    return redirect('tools.views.view_job', job_id=newJob.id,resource='other',filename=filename)
Example #5
0
def addCompoundsAjax(user, source_id, ids, tags):
    if len(tags) != 0:
        Tag.ensureAllExist(tags, user)

    if len(ids) == 0:
        raise Exception('Empty list of "ids".')

    if source_id == 'chembl':
        sdfs = get_chembl_sdfs(ids)
        sdf = '\n$$$$\n'.join(sdfs) + '\n$$$$\n'

        newJob = createJob(
            user, 'Upload Compounds', '',
            ['--user='******'--tags=' + (','.join(tags))], sdf)
        time.sleep(2)
        newJob = updateJob(user, newJob.id)
        if newJob.status == Job.RUNNING:
            ajaxResponse = {
                'success':
                True,
                'message':
                'Compound upload in progress. Check "Past Jobs" for status.'
            }
        elif newJob.status == Job.FINISHED:
            ajaxResponse = {
                'success': True,
                'message': 'Compounds uploaded successfully.'
            }
        else:
            ajaxResponse = {
                'success': False,
                'message': 'An error occurred while uploading your compounds.'
            }
        return ajaxResponse
    else:
        raise Exception('Unknown source_id: {}'.format(source_id))
Example #6
0
def uploadCompound(request, resource = None, job_id = None):
    if (request.method == 'GET') and (resource != u'job'):
        return render_to_response('addCompounds.html',
                                  dict(input_mode='smiles-input'),
                                  context_instance=RequestContext(request))
    else:
        sdf = None
        name = None
        compid = None
        smiles = None
        if 'smiles' in request.POST:
            input_mode = 'smiles-input'
            sdf = u''
            try:
                smiles = request.POST['smiles'].split('\n')
                for line in smiles:
                    if re.match(r"^\S+", line):
                        sdf = sdf + smiles_to_sdf(str(line))
            except:
                messages.error(request, 'Error: Invalid SMILES string!')
                sdf = None
        elif resource == 'job':
            input_mode = 'sdf-upload'
            job = updateJob(request.user, job_id)
            f = open(job.output, 'r')
            sdf = f.read()
            f.close()
        elif 'sdf' in request.FILES:
            input_mode = 'sdf-upload'
            try:
                sdf = request.FILES['sdf']
                sdf = sdf.read()
            except (InputError, InvalidInputError):
                messages.error(request, 'Invalid SDF!')
                sdf = None
        elif 'sdf' in request.POST:
            if 'draw' in request.POST:
                input_mode = 'draw'
                sdf = request.POST['sdf'] + '$$$$'
                compid = str(request.POST['id'])
                compid = re.match(r"^(\S{0,20})", compid).group(1)
                try:
                    smiles = sdf_to_smiles(sdf)
                    smiles = re.match(r"^(\S+)", smiles).group(1)
                    smiles = smiles + ' ' + compid
                    sdf = smiles_to_sdf(smiles)
                except:
                    messages.error(request, 'Invalid drawing!')
                    sdf = None
            else:
                input_mode = 'sdf-input'
                sdf = request.POST['sdf']
                if not sdf:
                    messages.error(request, 'No input found!')
        elif 'pubchem' in request.POST:
            cids = request.POST['pubchem']
            cids = cids.split()
            input_mode = 'pubchem'
            filteredCIDs = []
            for cid in cids[:]:
                match = re.search("(\d{1,200})", cid)
                if match:
                    filteredCIDs.append(int(match.group(1)))

            if len(filteredCIDs) > 0:
                try:
                    sdf = DownloadCIDs(filteredCIDs)
                except:
                    messages.error(request,
                                   'Invalid CIDs or no response from PubChem!'
                                   )
                    sdf = None
            else:
                messages.error(request, 'Error: No valid CIDs entered!')
                sdf = None

        if not sdf:
            return render_to_response('addCompounds.html',
                    dict(input_mode=input_mode,
                    post_data=request.POST),
                    context_instance=RequestContext(request))
        newJob = createJob(request.user, 'Upload Compounds', '',
                           ['--user='******'tools.views.view_job', job_id=newJob.id,
                        resource='')
Example #7
0
def uploadCompound(request, resource = None, job_id = None):
    allTags = Tag.allUserTagNames(request.user)


    if (request.method == 'GET') and (resource != u'job'):
        return render(request,'addCompounds.html',
                                  dict(input_mode='smiles-input',
                                      tags=allTags))
    else:
        sdf = None
        name = None
        compid = None
        smiles = None
        compoundTags = []
        input_mode='smiles-input'

        if 'tags' in request.POST:

            compoundTags = set(request.POST.getlist('tags'))

            Tag.ensureAllExist(compoundTags,request.user)

            #existingTags = set(allTags)
            #print("compound tags: "+str(compoundTags))

            #for newTag in compoundTags.difference(existingTags):
            #    print("creating new tag: "+newTag+" for user "+request.user.username)
            #    Tag.objects.create(name = newTag, user=request.user)


        if 'smiles' in request.POST:
            input_mode = 'smiles-input'
            sdf = u''
            try:
                smiles = request.POST['smiles'].split('\n')
                for line in smiles:
                    if re.match(r"^\S+", line):
                        sdf = sdf + smiles_to_sdf(str(line))
            except:
                print("Unexpected error:", sys.exc_info())
                traceback.print_tb(sys.exc_info()[2])
                messages.error(request, 'Error: Invalid SMILES string!')
                sdf = None
        elif resource == 'job':
            input_mode = 'sdf-upload'
            job = updateJob(request.user, job_id)
            f = open(job.output, 'r')
            sdf = f.read()
            f.close()
        elif 'sdf' in request.FILES:
            input_mode = 'sdf-upload'
            try:
                sdf = request.FILES['sdf']
                sdf = sdf.read().decode("utf-8")
            except (InputError, InvalidInputError):
                messages.error(request, 'Invalid SDF!')
                sdf = None
        elif 'sdf' in request.POST:
            if 'draw' in request.POST:
                input_mode = 'draw'
                sdf = request.POST['sdf'] + '$$$$'
                compid = str(request.POST['id'])
                compid = re.match(r"^(\S{0,20})", compid).group(1)
                try:
                    smiles = sdf_to_smiles(sdf)
                    smiles = re.match(r"^(\S+)", smiles).group(1)
                    smiles = smiles + ' ' + compid
                    sdf = smiles_to_sdf(smiles)
                except:
                    print("Unexpected error:", sys.exc_info())
                    traceback.print_tb(sys.exc_info()[2])
                    messages.error(request, 'Invalid drawing!')
                    sdf = None
            else:
                input_mode = 'sdf-input'
                sdf = request.POST['sdf']
                if not sdf:
                    messages.error(request, 'No input found!')
        elif 'pubchem' in request.POST:
            cids = request.POST['pubchem']
            cids = cids.split()
            input_mode = 'pubchem'
            filteredCIDs = []
            for cid in cids[:]:
                match = re.search("(\d{1,200})", cid)
                if match:
                    filteredCIDs.append(int(match.group(1)))

            if len(filteredCIDs) > 0:
                try:
                    sdf = DownloadCIDs(cids)
                except:
                    print("Unexpected error:", sys.exc_info())
                    traceback.print_tb(sys.exc_info()[2])
                    messages.error(request,
                                   'Invalid CIDs or no response from PubChem!'
                                   )
                    sdf = None
            else:
                messages.error(request, 'Error: No valid CIDs entered!')
                sdf = None
        elif 'chembl' in request.POST:
            cids = tuple(request.POST['chembl'].split())

            if len(cids) > 0:
                try:
                    sdfs = get_chembl_sdfs(cids)
                    sdf = "\n$$$$\n".join(sdfs)+"\n$$$$\n"
                except:
                    print("Unexpected error:", sys.exc_info())
                    traceback.print_tb(sys.exc_info()[2])
                    messages.error(request,
                                   'Invalid CIDs or no response from ChEMBL!'
                                   )
                    sdf = None
            else:
                print("no chembl cids given")
                messages.error(request, 'Error: No valid ChEMBL CIDs entered!')
                sdf = None


        if not sdf:
            return render('addCompounds.html',
                    dict(input_mode=input_mode,
                    post_data=request.POST,
                    tags=compoundTags))
        jobArgs = ['--user='******'dedup' in request.POST:
            jobArgs += ["--deduplicate"]
        newJob = createJob(request.user, 'Upload Compounds', '',jobArgs , sdf)
        time.sleep(2)
        return redirect(tools.views.view_job, job_id=newJob.id,
                        resource='')