Ejemplo n.º 1
0
    def wrapped(*args, **kwargs):
        _args = []
        try:
            for i in args:

                # i is a SMILES string

                sdf = mkstemp()
                _args.append(sdf[1])
                sdf = os.fdopen(sdf[0], 'w')
                sdf.write(smiles_to_sdf(i))
                sdf.close()
        except:
            for i in _args:
                try:
                    os.unlink(i)
                except:
                    pass
            raise

        try:
            ret = func(*_args, **kwargs)
        finally:
            for i in _args:
                os.unlink(i)
        return ret
Ejemplo n.º 2
0
    def wrapped(*args, **kwargs):
        _args = []
        try:
            for i in args:

                # i is a SMILES string

                sdf = mkstemp()
                _args.append(sdf[1])
                sdf = os.fdopen(sdf[0], 'w')
                sdf.write(smiles_to_sdf(i))
                sdf.close()
        except:
            for i in _args:
                try:
                    os.unlink(i)
                except:
                    pass
            raise

        try:
            ret = func(*_args, **kwargs)
        finally:
            for i in _args:
                os.unlink(i)
        return ret
Ejemplo n.º 3
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='')
Ejemplo n.º 4
0
def smiles2sdf(smiles):
    sdf = smiles_to_sdf(smiles)
    return HttpResponse(sdf, content_type='text/plain')
Ejemplo n.º 5
0
def search(request):
    if request.is_ajax():
        if 'application_id' in request.GET:
            form = getAppForm(request.GET['application_id'], request.user)()
            return HttpResponse(str(form))
        else:
            return HttpResponse("", status_code=404)
    elif request.method != 'POST':
        smi = ''
        if 'smi' in request.GET:
            smi = str(request.GET['smi'])
            smi = urlunquote(smi)
        allTags = Tag.allUserTagNames(request.user)

        fields = {}
        category = ApplicationCategories.objects.get(name="Search")
        apps = Application.objects.filter(category=category).exclude(
            name__exact="pubchemID2SDF")
        fields['application'] = ModelChoiceField(queryset=apps, empty_label='')
        form = type('%sForm' % 'choose application', (Form, ), fields)

        return render(request, 'search.html',
                      dict(mode='form', smi=smi, appsForm=form, tags=allTags))
    else:
        sdf = None
        smiles = None
        compid = u'query'
        form = None
        application = None
        application_id = None

        if 'application' in request.POST:
            application_id = request.POST['application']
            application = Application.objects.get(id=application_id)

        if 'tags' in request.POST:
            givenTags = request.POST.getlist("tags")
            compoundList = Compound.byTagNames(givenTags, request.user)
            if len(compoundList) == 0:
                messages.error(request,
                               "Error: No compounds found with selected tags")
            else:
                sdf = u''
                for compound in compoundList:
                    sdf = sdf + compound.sdffile_set.all()[0].sdffile.rstrip(
                    ) + '\n'
                smiles = sdf_to_smiles(sdf)
        elif 'smiles' in request.POST:
            input_mode = 'smiles-input'
            sdf = u''
            try:
                smiles = request.POST['smiles']
                sdf = smiles_to_sdf(smiles)
            except:
                messages.error(request, 'Error: Invalid SMILES string!')
                sdf = None
        elif 'sdf' in request.FILES:
            input_mode = 'sdf-upload'
            try:
                sdf = request.FILES['sdf']
                sdf = first_mol(sdf.read())
                smiles = sdf_to_smiles(sdf)
            except:
                print(traceback.format_exc())
                messages.error(request, 'Invalid SDF!')
                sdf = None
        elif 'sdf' in request.POST:
            if 'draw' in request.POST:
                input_mode = 'draw'
                sdf = request.POST['sdf'] + '$$$$'
                try:
                    smiles = sdf_to_smiles(sdf)
                    smiles = re.match(r"^(\S+)", smiles).group(1)
                    smiles = smiles + ' ' + compid
                    sdf = smiles_to_sdf(smiles)
                except:
                    print(traceback.format_exc())
                    messages.error(request, 'Invalid drawing!')
                    sdf = None
            else:
                try:
                    input_mode = 'sdf-input'
                    sdf = first_mol(request.POST['sdf'])
                    smiles = sdf_to_smiles(sdf)
                except:
                    print(traceback.format_exc())
                    messages.error(request, 'Invalid input SDF!')
                    sdf = None

        if application_id != None:
            AppFormSet = getAppForm(request.POST['application'], request.user)
            form = AppFormSet(request.POST)

        if form != None and form.is_valid():
            commandOptions, optionsList = parseToolForm(form)
        else:
            sdf = None
            messages.error(request, "Invalid form options!")
        if not sdf:
            print("no sdf found")
            return redirect(structure_search.views.search)
        smiles = re.search(r'(\S+)', smiles).group(1)
        smiles = urlquote(smiles)

        #print("command options: "+str(commandOptions))

        if application.name == "PubChem Fingerprint Search":
            newJob = createJob(request.user, application.name, optionsList,
                               commandOptions, sdf, smiles)
        elif application.name == "ChEMBL Fingerprint Search":
            newJob = createJob(request.user, application.name, optionsList,
                               commandOptions, sdf, smiles)
        elif application.name == "ChEMBL EI Search":
            newJob = createJob(request.user, application.name, optionsList,
                               commandOptions, sdf, smiles)

        time.sleep(1)
        return redirect(tools.views.view_job, job_id=newJob.id, resource='')
Ejemplo n.º 6
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='')
Ejemplo n.º 7
0
def search(request):
    application = Application.objects.get(name='EI Search')
    AppFormSet = getAppForm(application.id, request.user)
    if request.method != 'POST':
        smi = ''
        if 'smi' in request.GET:
            smi = str(request.GET['smi'])
            smi = urlunquote(smi)
        form = AppFormSet()
        form = str(form)
        return render_to_response('search.html', dict(mode='form',
            smi=smi, form=form),
            context_instance=RequestContext(request)) 
    else:
        sdf = None
        smiles = None
        compid = u'query'
        if 'smiles' in request.POST:
            input_mode = 'smiles-input'
            sdf = u''
            try:
                smiles = request.POST['smiles']
                sdf = smiles_to_sdf(str(smiles))
            except:
                messages.error(request, 'Error: Invalid SMILES string!')
                sdf = None
        elif 'sdf' in request.FILES:
            input_mode = 'sdf-upload'
            try:
                sdf = request.FILES['sdf']
                sdf = first_mol(sdf.read())
                smiles = sdf_to_smiles(sdf)
            except:
                messages.error(request, 'Invalid SDF!')
                sdf = None
        elif 'sdf' in request.POST:
            if 'draw' in request.POST:
                input_mode = 'draw'
                sdf = request.POST['sdf'] + '$$$$'
                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:
                try:
                    input_mode = 'sdf-input'
                    sdf = first_mol(request.POST['sdf'])
                    smiles = sdf_to_smiles(sdf)
                except:
                    messages.error(request, 'Invalid input SDF!')
                    sdf = None
        form = AppFormSet(request.POST)
        if form.is_valid():
            commandOptions, optionsList = parseToolForm(form) 
        else:
            sdf = None
            messages.error(request, "Invalid form options!")
        if not sdf:
            return redirect('eisearch.views.search')
        smiles = re.search(r'(\S+)', smiles).group(1)
        smiles = urlquote(smiles)
        newJob = createJob(request.user, 'EI Search', optionsList, 
                           commandOptions, sdf, smiles)
        time.sleep(1)
        return redirect('tools.views.view_job', job_id=newJob.id,resource='')
Ejemplo n.º 8
0
def smiles2sdf(smiles):
    sdf = smiles_to_sdf(smiles)
    return HttpResponse(sdf, mimetype='text/plain')
Ejemplo n.º 9
0
def search(request):
    application = Application.objects.get(name='EI Search')
    AppFormSet = getAppForm(application.id, request.user)
    if request.method != 'POST':
        smi = ''
        if 'smi' in request.GET:
            smi = str(request.GET['smi'])
            smi = urlunquote(smi)
        form = AppFormSet()
        form = str(form)
        return render_to_response('search.html',
                                  dict(mode='form', smi=smi, form=form),
                                  context_instance=RequestContext(request))
    else:
        sdf = None
        smiles = None
        compid = u'query'
        if 'smiles' in request.POST:
            input_mode = 'smiles-input'
            sdf = u''
            try:
                smiles = request.POST['smiles']
                sdf = smiles_to_sdf(str(smiles))
            except:
                messages.error(request, 'Error: Invalid SMILES string!')
                sdf = None
        elif 'sdf' in request.FILES:
            input_mode = 'sdf-upload'
            try:
                sdf = request.FILES['sdf']
                sdf = first_mol(sdf.read())
                smiles = sdf_to_smiles(sdf)
            except:
                messages.error(request, 'Invalid SDF!')
                sdf = None
        elif 'sdf' in request.POST:
            if 'draw' in request.POST:
                input_mode = 'draw'
                sdf = request.POST['sdf'] + '$$$$'
                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:
                try:
                    input_mode = 'sdf-input'
                    sdf = first_mol(request.POST['sdf'])
                    smiles = sdf_to_smiles(sdf)
                except:
                    messages.error(request, 'Invalid input SDF!')
                    sdf = None
        form = AppFormSet(request.POST)
        if form.is_valid():
            commandOptions, optionsList = parseToolForm(form)
        else:
            sdf = None
            messages.error(request, "Invalid form options!")
        if not sdf:
            return redirect('eisearch.views.search')
        smiles = re.search(r'(\S+)', smiles).group(1)
        smiles = urlquote(smiles)
        if request.POST['algorithm'] == u'fp':
            newJob = createJob(request.user, 'Fingerprint Search', optionsList,
                               commandOptions, sdf, smiles)
        else:
            newJob = createJob(request.user, 'EI Search', optionsList,
                               commandOptions, sdf, smiles)
        time.sleep(1)
        return redirect('tools.views.view_job', job_id=newJob.id, resource='')
Ejemplo n.º 10
0
def search(request):
    application = Application.objects.get(name="EI Search")
    AppFormSet = getAppForm(application.id, request.user)
    if request.method != "POST":
        smi = ""
        if "smi" in request.GET:
            smi = str(request.GET["smi"])
            smi = urlunquote(smi)
        form = AppFormSet()
        form = str(form)
        return render_to_response(
            "search.html", dict(mode="form", smi=smi, form=form), context_instance=RequestContext(request)
        )
    else:
        sdf = None
        smiles = None
        compid = u"query"
        if "smiles" in request.POST:
            input_mode = "smiles-input"
            sdf = u""
            try:
                smiles = request.POST["smiles"]
                sdf = smiles_to_sdf(str(smiles))
            except:
                messages.error(request, "Error: Invalid SMILES string!")
                sdf = None
        elif "sdf" in request.FILES:
            input_mode = "sdf-upload"
            try:
                sdf = request.FILES["sdf"]
                sdf = first_mol(sdf.read())
                smiles = sdf_to_smiles(sdf)
            except:
                messages.error(request, "Invalid SDF!")
                sdf = None
        elif "sdf" in request.POST:
            if "draw" in request.POST:
                input_mode = "draw"
                sdf = request.POST["sdf"] + "$$$$"
                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:
                try:
                    input_mode = "sdf-input"
                    sdf = first_mol(request.POST["sdf"])
                    smiles = sdf_to_smiles(sdf)
                except:
                    messages.error(request, "Invalid input SDF!")
                    sdf = None
        form = AppFormSet(request.POST)
        if form.is_valid():
            commandOptions, optionsList = parseToolForm(form)
        else:
            sdf = None
            messages.error(request, "Invalid form options!")
        if not sdf:
            return redirect("eisearch.views.search")
        smiles = re.search(r"(\S+)", smiles).group(1)
        smiles = urlquote(smiles)
        if request.POST["algorithm"] == u"fp":
            newJob = createJob(request.user, "Fingerprint Search", optionsList, commandOptions, sdf, smiles)
        else:
            newJob = createJob(request.user, "EI Search", optionsList, commandOptions, sdf, smiles)
        time.sleep(1)
        return redirect("tools.views.view_job", job_id=newJob.id, resource="")
Ejemplo n.º 11
0
def uploadCompound(request, *args, **kargs):
    if request.method == "GET":
        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 "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="")