def get(self, request, *args, **kwargs): if self.kwargs['substructure'] == 'select': return HttpResponseRedirect('/structure/pdb_segment_selection') if self.kwargs['substructure'] == 'full': out_stream = request.session['cleaned_structures'] elif self.kwargs['substructure'] == 'custom': simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) io = PDBIO() zipf_in = zipfile.ZipFile(request.session['cleaned_structures'], 'r') out_stream = BytesIO() zipf_out = zipfile.ZipFile(out_stream, 'w', zipfile.ZIP_DEFLATED) for name in zipf_in.namelist(): tmp = StringIO() io.set_structure(PDBParser(QUIET=True).get_structure(name, StringIO(zipf_in.read(name).decode('utf-8')))[0]) io.save(tmp, SubstructureSelector(request.session['substructure_mapping'], parsed_selection=SelectionParser(selection))) zipf_out.writestr(name, tmp.getvalue()) zipf_in.close() zipf_out.close() del request.session['substructure_mapping'] if len(out_stream.getvalue()) > 0: response = HttpResponse(content_type="application/zip") response['Content-Disposition'] = 'attachment; filename="pdb_structures.zip"' response.write(out_stream.getvalue()) return response
def post (self, request, *args, **kwargs): # create full selection and import simple selection (if it exists) simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if 'ref_file' in request.FILES: request.session['ref_file'] = request.FILES['ref_file'] if 'alt_files' in request.FILES: request.session['alt_files'] = request.FILES.getlist('alt_files') context = super(SuperpositionWorkflowSelection, self).get_context_data(**kwargs) context['selection'] = {} for selection_box, include in self.selection_boxes.items(): if include: context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box] attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return render(request, self.template_name, context)
def get_context_data (self, **kwargs): context = super(SuperpositionWorkflowIndex, self).get_context_data(**kwargs) # get selection from session and add to context # get simple selection from session simple_selection = self.request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) #Clearing selections for fresh run if 'clear' in self.kwargs.keys(): selection.clear('reference') selection.clear('targets') selection.clear('segments') if 'alt_files' in self.request.session.keys(): del self.request.session['alt_files'] if 'ref_file' in self.request.session.keys(): del self.request.session['ref_file'] context['selection'] = {} for selection_box, include in self.selection_boxes.items(): if include: context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box] # get attributes of this class and add them to the context context['form_code'] = str(self.form_code) attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return context
def get_context_data(self, **kwargs): """get context from parent class (really only relevant for child classes of this class, as TemplateView does not have any context variables)""" context = super().get_context_data(**kwargs) # get selection from session and add to context # get simple selection from session simple_selection = self.request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() # on the first page of a workflow, clear the selection (or dont' import from the session) if self.step is not 1: if simple_selection: selection.importer(simple_selection) context['selection'] = {} context['selection']['tree_settings'] = selection.tree_settings for selection_box, include in self.selection_boxes.items(): if include: context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box] # get attributes of this class and add them to the context attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return context
def get_context_data(self, **kwargs): self.buttons = { 'continue': { 'label': 'Download substructures', 'url': '/structure/superposition_workflow_results/custom', 'color': 'success', }, } context = super(SuperpositionWorkflowSelection, self).get_context_data(**kwargs) simple_selection = self.request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) context['selection'] = {} context['selection']['site_residue_groups'] = selection.site_residue_groups context['selection']['active_site_residue_group'] = selection.active_site_residue_group for selection_box, include in self.selection_boxes.items(): if include: context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box] # get attributes of this class and add them to the context attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return context
def get(self, request, *args, **kwargs): if self.kwargs['substructure'] == 'custom': return HttpResponseRedirect('/structure/generic_numbering_selection') simple_selection = self.request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) out_stream = StringIO() io = PDBIO() request.session['gn_outfile'].seek(0) gn_struct = PDBParser(PERMISSIVE=True, QUIET=True).get_structure(request.session['gn_outfname'], request.session['gn_outfile'])[0] if self.kwargs['substructure'] == 'full': io.set_structure(gn_struct) io.save(out_stream) if self.kwargs['substructure'] == 'substr': io.set_structure(gn_struct) io.save(out_stream, GenericNumbersSelector(parsed_selection=SelectionParser(selection))) root, ext = os.path.splitext(request.session['gn_outfname']) response = HttpResponse(content_type="chemical/x-pdb") response['Content-Disposition'] = 'attachment; filename="{}_GPCRDB.pdb"'.format(root) response.write(out_stream.getvalue()) return response
def SelectionAnnotation(request): """Updates the selected level of annotation""" protein_source = request.GET['protein_source'] if protein_source == 'All': pss = ProteinSource.objects.all() else: pss = ProteinSource.objects.filter(name=protein_source) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # reset the annotation selection selection.clear('annotation') # add the selected items to the selection for ps in pss: selection_object = SelectionItem('annotation', ps) selection.add('annotation', 'annotation', selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_filters_annotation.html', selection.dict('annotation'))
def TargetDetails(request, **kwargs): if 'slug' in kwargs: slug = kwargs['slug'] if slug.count('_') == 0 : ps = AssayExperiment.objects.filter(protein__family__parent__parent__parent__slug=slug, ligand__properities__web_links__web_resource__slug = 'chembl_ligand') elif slug.count('_') == 1 and len(slug) == 7: ps = AssayExperiment.objects.filter(protein__family__parent__parent__slug=slug, ligand__properities__web_links__web_resource__slug = 'chembl_ligand') elif slug.count('_') == 2: ps = AssayExperiment.objects.filter(protein__family__parent__slug=slug, ligand__properities__web_links__web_resource__slug = 'chembl_ligand') #elif slug.count('_') == 3: elif slug.count('_') == 1 and len(slug) != 7: ps = AssayExperiment.objects.filter(protein__entry_name = slug, ligand__properities__web_links__web_resource__slug = 'chembl_ligand') if slug.count('_') == 1 and len(slug) == 7: f = ProteinFamily.objects.get(slug=slug) else: f = slug context = { 'target':f } else: simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if selection.targets != []: prot_ids = [x.item.id for x in selection.targets] ps = AssayExperiment.objects.filter(protein__in=prot_ids, ligand__properities__web_links__web_resource__slug = 'chembl_ligand') context = { 'target': ', '.join([x.item.entry_name for x in selection.targets]) } ps = ps.values('standard_type', 'standard_relation', 'standard_value', 'assay_description', 'assay_type', #'standard_units', 'pchembl_value', 'ligand__id', 'ligand__properities_id', 'ligand__properities__web_links__index', #'ligand__properities__vendors__vendor__name', 'protein__species__common_name', 'protein__entry_name', 'ligand__properities__mw', 'ligand__properities__logp', 'ligand__properities__rotatable_bonds', 'ligand__properities__smiles', 'ligand__properities__hdon', 'ligand__properities__hacc','protein' ).annotate(num_targets = Count('protein__id', distinct=True)) for record in ps: record['purchasability'] = 'Yes' if len(LigandVendorLink.objects.filter(lp=record['ligand__properities_id']).exclude(vendor__name__in=['ZINC', 'ChEMBL', 'BindingDB', 'SureChEMBL', 'eMolecules', 'MolPort', 'PubChem'])) > 0 else 'No' context['proteins'] = ps return render(request, 'target_details.html', context)
def ToggleFamilyTreeNode(request): """Opens/closes a node in the family selection tree""" action = request.GET['action'] type_of_selection = request.GET['type_of_selection'] node_id = request.GET['node_id'] parent_tree_indent_level = int(request.GET['tree_indent_level']) tree_indent_level = [] for i in range(parent_tree_indent_level + 1): tree_indent_level.append(0) parent_tree_indent_level = tree_indent_level[:] del parent_tree_indent_level[-1] # session simple_selection = request.session.get('selection') selection = Selection() if simple_selection: selection.importer(simple_selection) ppf = ProteinFamily.objects.get(pk=node_id) if action == 'expand': pfs = ProteinFamily.objects.filter(parent=node_id) # species filter species_list = [] for species in selection.species: species_list.append(species.item) # annotation filter protein_source_list = [] for protein_source in selection.annotation: protein_source_list.append(protein_source.item) if species_list: ps = Protein.objects.order_by('id').filter( family=ppf, species__in=(species_list), source__in=(protein_source_list)).order_by('source_id', 'id') else: ps = Protein.objects.order_by('id').filter( family=ppf, source__in=(protein_source_list)).order_by('source_id', 'id') action = 'collapse' else: pfs = ps = {} action = 'expand' return render( request, 'common/selection_tree.html', { 'action': action, 'type_of_selection': type_of_selection, 'ppf': ppf, 'pfs': pfs, 'ps': ps, 'parent_tree_indent_level': parent_tree_indent_level, 'tree_indent_level': tree_indent_level, })
def ResiduesUpload(request): """Receives a file containing generic residue positions along with numbering scheme and adds those to the selection.""" # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) selection_type = 'segments' if request.FILES == {}: return render(request, 'common/selection_lists.html', '') #Overwriting the existing selection selection.clear(selection_type) #The excel file o = [] workbook = xlrd.open_workbook( file_contents=request.FILES['xml_file'].read()) worksheets = workbook.sheet_names() for worksheet_name in worksheets: worksheet = workbook.sheet_by_name(worksheet_name) for row in worksheet.get_rows(): if len(row) < 2: continue try: if row[0].value == 'residue': position = ResidueGenericNumberEquivalent.objects.get( label=row[2].value, scheme__slug=row[1].value) o.append(position) elif row[0].value == 'helix': o.append(ProteinSegment.objects.get(slug=row[2].value)) except Exception as msg: print(msg) continue for obj in o: # add the selected item to the selection if obj.__class__.__name__ == 'ResidueGenericNumberEquivalent': selection_subtype = 'residue' else: selection_subtype = 'helix' selection_object = SelectionItem(selection_subtype, obj) selection.add(selection_type, selection_subtype, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def SelectionSchemesToggle(request): """Updates the selected numbering schemes arbitrary selections""" numbering_scheme_id = request.GET['numbering_scheme_id'] gns = ResidueNumberingScheme.objects.filter(pk=numbering_scheme_id) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # add the selected items to the selection for gn in gns: exists = selection.remove('numbering_schemes', 'numbering_schemes', numbering_scheme_id) if not exists: selection_object = SelectionItem('numbering_schemes', gn) selection.add('numbering_schemes', 'numbering_schemes', selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # add all species objects to context (for comparison to selected species) context = selection.dict('numbering_schemes') context['gns'] = ResidueNumberingScheme.objects.exclude(slug=settings.DEFAULT_NUMBERING_SCHEME) return render(request, 'common/selection_filters_numbering_schemes.html', context)
def SelectionSpeciesToggle(request): """Updates the selected species arbitrary selections""" species_id = request.GET['species_id'] all_sps = Species.objects.all() sps = Species.objects.filter(pk=species_id) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # add the selected items to the selection for sp in sps: exists = selection.remove('species', 'species', species_id) if not exists: selection_object = SelectionItem('species', sp) selection.add('species', 'species', selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # add all species objects to context (for comparison to selected species) context = selection.dict('species') context['sps'] = Species.objects.all() return render(request, 'common/selection_filters_species_selector.html', context)
def ToggleFamilyTreeNode(request): """Opens/closes a node in the family selection tree""" action = request.GET['action'] type_of_selection = request.GET['type_of_selection'] node_id = request.GET['node_id'] parent_tree_indent_level = int(request.GET['tree_indent_level']) tree_indent_level = [] for i in range(parent_tree_indent_level+1): tree_indent_level.append(0) parent_tree_indent_level = tree_indent_level[:] del parent_tree_indent_level[-1] # session simple_selection = request.session.get('selection') selection = Selection() if simple_selection: selection.importer(simple_selection) ppf = ProteinFamily.objects.get(pk=node_id) if action == 'expand': pfs = ProteinFamily.objects.filter(parent=node_id) # species filter species_list = [] for species in selection.species: species_list.append(species.item) # annotation filter protein_source_list = [] for protein_source in selection.annotation: protein_source_list.append(protein_source.item) if species_list: ps = Protein.objects.order_by('id').filter(family=ppf, species__in=(species_list), source__in=(protein_source_list)).order_by('source_id', 'id') else: ps = Protein.objects.order_by('id').filter(family=ppf, source__in=(protein_source_list)).order_by('source_id', 'id') action = 'collapse' else: pfs = ps = {} action = 'expand' return render(request, 'common/selection_tree.html', { 'action': action, 'type_of_selection': type_of_selection, 'ppf': ppf, 'pfs': pfs, 'ps': ps, 'parent_tree_indent_level': parent_tree_indent_level, 'tree_indent_level': tree_indent_level, })
def TargetPurchasabilityDetails(request, **kwargs): simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if selection.targets != []: prot_ids = [x.item.id for x in selection.targets] ps = AssayExperiment.objects.filter(protein__in=prot_ids, ligand__properities__web_links__web_resource__slug = 'chembl_ligand') context = { 'target': ', '.join([x.item.entry_name for x in selection.targets]) } ps = ps.values('standard_type', 'standard_relation', 'standard_value', 'assay_description', 'assay_type', 'standard_units', 'pchembl_value', 'ligand__id', 'ligand__properities_id', 'ligand__properities__web_links__index', 'ligand__properities__vendors__vendor__id', 'ligand__properities__vendors__vendor__name', 'protein__species__common_name', 'protein__entry_name', 'ligand__properities__mw', 'ligand__properities__logp', 'ligand__properities__rotatable_bonds', 'ligand__properities__smiles', 'ligand__properities__hdon', 'ligand__properities__hacc','protein' ).annotate(num_targets = Count('protein__id', distinct=True)) purchasable = [] for record in ps: try: if record['ligand__properities__vendors__vendor__name'] in ['ZINC', 'ChEMBL', 'BindingDB', 'SureChEMBL', 'eMolecules', 'MolPort', 'PubChem', 'IUPHAR/BPS Guide to PHARMACOLOGY']: continue tmp = LigandVendorLink.objects.filter(vendor=record['ligand__properities__vendors__vendor__id'], lp=record['ligand__properities_id'])[0] record['vendor_id'] = tmp.vendor_external_id record['vendor_link'] = tmp.url purchasable.append(record) except: continue context['proteins'] = purchasable return render(request, 'target_purchasability_details.html', context)
def SelectAlignableSegments(request): """Adds all alignable segments to the selection""" selection_type = request.GET['selection_type'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # get all segments segments = ProteinSegment.objects.filter(partial=False, slug__startswith='TM') for segment in segments: selection_object = SelectionItem(segment.category, segment) # add the selected item to the selection selection.add(selection_type, segment.category, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def ResiduesUpload(request): """Receives a file containing generic residue positions along with numbering scheme and adds those to the selection.""" # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) selection_type = 'segments' if request.FILES == {}: return render(request, 'common/selection_lists.html', '') #Overwriting the existing selection selection.clear(selection_type) #The excel file o = [] workbook = xlrd.open_workbook(file_contents=request.FILES['xml_file'].read()) worksheets = workbook.sheet_names() for worksheet_name in worksheets: worksheet = workbook.sheet_by_name(worksheet_name) for row in worksheet.get_rows(): if len(row) < 2: continue try: if row[0].value == 'residue': position = ResidueGenericNumberEquivalent.objects.get(label=row[2].value, scheme__slug=row[1].value) o.append(position) elif row[0].value == 'helix': o.append(ProteinSegment.objects.get(slug=row[2].value)) except Exception as msg: print(msg) continue for obj in o: # add the selected item to the selection if obj.__class__.__name__ == 'ResidueGenericNumberEquivalent': selection_subtype = 'residue' else: selection_subtype = 'helix' selection_object = SelectionItem(selection_subtype, obj) selection.add(selection_type, selection_subtype, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def SelectAlignableSegments(request): """Adds all alignable segments to the selection""" selection_type = request.GET['selection_type'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # get all segments # get all segments if "protein_type" in request.GET: gsegments = definitions.G_PROTEIN_SEGMENTS preserved = Case(*[When(slug=pk, then=pos) for pos, pk in enumerate(gsegments['Structured'])]) segments = ProteinSegment.objects.filter(slug__in = gsegments['Structured'], partial=False).order_by(preserved) else: segments = ProteinSegment.objects.filter(partial=False, slug__startswith='TM') for segment in segments: selection_object = SelectionItem(segment.category, segment) # add the selected item to the selection selection.add(selection_type, segment.category, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def SelectResidueGroup(request): """Receives a selection request, updates the active residue group, and returns the updated selection""" selection_type = request.GET['selection_type'] group_id = int(request.GET['group_id']) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # update the selected group selection.active_site_residue_group = group_id # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # context context = selection.dict(selection_type) # amino acid groups amino_acid_groups = { 'amino_acid_groups': definitions.AMINO_ACID_GROUPS, 'amino_acid_group_names': definitions.AMINO_ACID_GROUP_NAMES } context.update(amino_acid_groups) # template to load template = 'common/selection_lists_sitesearch.html' return render(request, template, context)
def SelectionSchemesPredefined(request): """Updates the selected numbering_schemes to predefined sets (GPCRdb and All)""" numbering_schemes = request.GET['numbering_schemes'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) all_gns = ResidueNumberingScheme.objects.exclude( slug=settings.DEFAULT_NUMBERING_SCHEME) gns = False if numbering_schemes == 'All': print(len(selection.numbering_schemes), all_gns.count()) if len(selection.numbering_schemes) == all_gns.count(): gns = [] else: gns = all_gns # reset the species selection selection.clear('numbering_schemes') # add the selected items to the selection for gn in gns: selection_object = SelectionItem('numbering_schemes', gn) selection.add('numbering_schemes', 'numbering_schemes', selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # add all species objects to context (for comparison to selected species) context = selection.dict('numbering_schemes') context['gns'] = all_gns return render(request, 'common/selection_filters_numbering_schemes.html', context)
def UpdateSiteResidueFeatures(request): """Updates the selected features of a site residue""" selection_type = request.GET['selection_type'] selection_subtype = request.GET['selection_subtype'] selection_id = request.GET['selection_id'] o = [] if selection_type == 'reference' or selection_type == 'targets': if selection_subtype == 'protein': o.append(Protein.objects.get(pk=selection_id)) elif selection_subtype == 'protein_set': selection_subtype = 'protein' pset = ProteinSet.objects.get(pk=selection_id) for protein in pset.proteins.all(): o.append(protein) elif selection_subtype == 'family': o.append(ProteinFamily.objects.get(pk=selection_id)) elif selection_subtype == 'set': o.append(ProteinSet.objects.get(pk=selection_id)) elif selection_subtype == 'structure': o.append(Protein.objects.get(entry_name=selection_id.lower())) elif selection_type == 'segments': if selection_subtype == 'residue': o.append( ResidueGenericNumberEquivalent.objects.get(pk=selection_id)) elif selection_subtype == 'residue_with_properties': # used in site search o.append( ResidueGenericNumberEquivalent.objects.get(pk=selection_id)) else: o.append(ProteinSegment.objects.get(pk=selection_id)) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) for obj in o: # add the selected item to the selection selection_object = SelectionItem(selection_subtype, obj) selection.add(selection_type, selection_subtype, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def SelectResidueFeature(request): """Receives a selection request, add a feature selection to an item, and returns the updated selection""" selection_type = request.GET['selection_type'] selection_subtype = request.GET['selection_subtype'] selection_id = int(request.GET['selection_id']) feature = request.GET['feature'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # process selected object if selection_type == 'segments' and selection_subtype == 'site_residue': for obj in selection.segments: if int(obj.item.id) == selection_id: obj.properties['feature'] = feature obj.properties['amino_acids'] = ','.join(definitions.AMINO_ACID_GROUPS[feature]) break # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # context context = selection.dict(selection_type) # amino acid groups amino_acid_groups = { 'amino_acid_groups': definitions.AMINO_ACID_GROUPS, 'amino_acid_group_names': definitions.AMINO_ACID_GROUP_NAMES } context.update(amino_acid_groups) # template to load template = 'common/selection_lists_sitesearch.html' return render(request, template, context)
def get_context_data (self, **kwargs): context = super(PDBClean, self).get_context_data(**kwargs) self.success = False self.posted = False # get simple selection from session simple_selection = self.request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if selection.targets != []: self.success = True attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return context
def get_context_data (self, **kwargs): context = super(SuperpositionWorkflowResults, self).get_context_data(**kwargs) simple_selection = self.request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if 'ref_file' in self.request.session.keys(): ref_file = StringIO(self.request.session['ref_file'].file.read().decode('UTF-8')) elif selection.reference != []: ref_file = StringIO(selection.reference[0].item.get_cleaned_pdb()) if 'alt_files' in self.request.session.keys(): alt_files = [StringIO(alt_file.file.read().decode('UTF-8')) for alt_file in self.request.session['alt_files']] elif selection.targets != []: alt_files = [StringIO(x.item.get_cleaned_pdb()) for x in selection.targets if x.type == 'structure'] superposition = ProteinSuperpose(deepcopy(ref_file),alt_files, selection) out_structs = superposition.run() if 'alt_files' in self.request.session.keys(): alt_file_names = [x.name for x in self.request.session['alt_files']] else: alt_file_names = ['{}_{}.pdb'.format(x.item.protein_conformation.protein.parent.entry_name, x.item.pdb_code.index) for x in selection.targets if x.type == 'structure'] if len(out_structs) == 0: self.success = False elif len(out_structs) >= 1: io = PDBIO() self.request.session['alt_structs'] = {} for alt_struct, alt_file_name in zip(out_structs, alt_file_names): tmp = StringIO() io.set_structure(alt_struct) io.save(tmp) self.request.session['alt_structs'][alt_file_name] = tmp self.success = True attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return context
def get_context_data(self, **kwargs): context = super(GenericNumberingSelection, self).get_context_data(**kwargs) simple_selection = self.request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) context['selection'] = {} context['selection']['site_residue_groups'] = selection.site_residue_groups context['selection']['active_site_residue_group'] = selection.active_site_residue_group for selection_box, include in self.selection_boxes.items(): if include: context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box] # get attributes of this class and add them to the context attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return context
def SelectionSpeciesPredefined(request): """Updates the selected species to predefined sets (Human and all)""" species = request.GET['species'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) all_sps = Species.objects.all() sps = False if species == 'All': sps = [] if species != 'All' and species: sps = Species.objects.filter(common_name=species) if sps != False: # reset the species selection selection.clear('species') # add the selected items to the selection for sp in sps: selection_object = SelectionItem('species', sp) selection.add('species', 'species', selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # add all species objects to context (for comparison to selected species) context = selection.dict('species') context['sps'] = all_sps return render(request, 'common/selection_filters_species.html', context)
def SelectRange(request): """Adds generic numbers within the given range""" selection_type = request.GET['selection_type'] selection_subtype = request.GET['selection_subtype'] range_start = request.GET['range_start'] range_end = request.GET['range_end'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # process selected object o = [] if selection_type == 'segments' and selection_subtype == 'residue': residue_nums = ResidueGenericNumberEquivalent.objects.all() for resn in residue_nums: if range_start < float(resn.label.replace('x','.')) < range_end: o.append(resn)
def SelectionSchemesPredefined(request): """Updates the selected numbering_schemes to predefined sets (GPCRdb and All)""" numbering_schemes = request.GET['numbering_schemes'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) all_gns = ResidueNumberingScheme.objects.exclude(slug=settings.DEFAULT_NUMBERING_SCHEME) gns = False if numbering_schemes == 'All': print(len(selection.numbering_schemes), all_gns.count()) if len(selection.numbering_schemes) == all_gns.count(): gns = [] else: gns = all_gns # reset the species selection selection.clear('numbering_schemes') # add the selected items to the selection for gn in gns: selection_object = SelectionItem('numbering_schemes', gn) selection.add('numbering_schemes', 'numbering_schemes', selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # add all species objects to context (for comparison to selected species) context = selection.dict('numbering_schemes') context['gns'] = all_gns return render(request, 'common/selection_filters_numbering_schemes.html', context)
def UpdateSiteResidueFeatures(request): """Updates the selected features of a site residue""" selection_type = request.GET['selection_type'] selection_subtype = request.GET['selection_subtype'] selection_id = request.GET['selection_id'] o = [] if selection_type == 'reference' or selection_type == 'targets': if selection_subtype == 'protein': o.append(Protein.objects.get(pk=selection_id)) elif selection_subtype == 'protein_set': selection_subtype = 'protein' pset = ProteinSet.objects.get(pk=selection_id) for protein in pset.proteins.all(): o.append(protein) elif selection_subtype == 'family': o.append(ProteinFamily.objects.get(pk=selection_id)) elif selection_subtype == 'set': o.append(ProteinSet.objects.get(pk=selection_id)) elif selection_subtype == 'structure': o.append(Protein.objects.get(entry_name=selection_id.lower())) elif selection_type == 'segments': if selection_subtype == 'residue': o.append(ResidueGenericNumberEquivalent.objects.get(pk=selection_id)) elif selection_subtype == 'residue_with_properties': # used in site search o.append(ResidueGenericNumberEquivalent.objects.get(pk=selection_id)) else: o.append(ProteinSegment.objects.get(pk=selection_id)) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) for obj in o: # add the selected item to the selection selection_object = SelectionItem(selection_subtype, obj) selection.add(selection_type, selection_subtype, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def SelectionGproteinPredefined(request): """Updates the selected species to predefined sets (Human and all)""" g_protein = request.GET['g_protein'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) all_gprots = ProteinGProtein.objects.all() gprots = False if g_protein == 'All': gprots = [] if g_protein != 'All' and g_protein: gprots = ProteinGProtein.objects.filter(name=g_protein) if gprots != False: # reset the species selection selection.clear('g_proteins') # add the selected items to the selection for gprot in gprots: selection_object = SelectionItem('g_protein', gprot) selection.add('g_proteins', 'g_proteins', selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # add all species objects to context (for comparison to selected species) context = selection.dict('g_proteins') context['gprots'] = all_gprots return render(request, 'common/selection_filters_gproteins.html', context)
def SetTreeSelection(request): """Adds all alignable segments to the selection""" option_no = request.GET['option_no'] option_id = request.GET['option_id'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) selection.tree_settings[int(option_no)]=option_id simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/tree_options.html', selection.dict('tree_settings'))
def ConvertStructuresToProteins(request): "For alignment from structure browser" simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if selection.targets != []: for struct in selection.targets: prot = struct.item.protein_conformation.protein.parent selection.remove('targets', 'structure', struct.item.id) selection.add('targets', 'protein', SelectionItem('protein', prot)) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return HttpResponseRedirect('/alignment/segmentselection')
def RemoveResidueGroup(request): """Receives a selection request, removes a residue group, and returns the updated selection""" selection_type = request.GET['selection_type'] group_id = int(request.GET['group_id']) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # find all positions in the group and delete them for position in selection.segments: if position.type == 'site_residue': if position.properties['site_residue_group'] == group_id: selection.remove(selection_type, position.type, position.item.id) else: if position.properties['site_residue_group'] > group_id: position.properties['site_residue_group'] -= 1 # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # context context = selection.dict(selection_type) # amino acid groups amino_acid_groups = { 'amino_acid_groups': definitions.AMINO_ACID_GROUPS, 'amino_acid_group_names': definitions.AMINO_ACID_GROUP_NAMES } context.update(amino_acid_groups) # template to load template = 'common/selection_lists_sitesearch.html' return render(request, template, context)
def SelectAlignableSegments(request): """Adds all alignable segments to the selection""" selection_type = request.GET['selection_type'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # get all segments # get all segments if "protein_type" in request.GET: gsegments = definitions.G_PROTEIN_SEGMENTS preserved = Case(*[ When(slug=pk, then=pos) for pos, pk in enumerate(gsegments['Structured']) ]) segments = ProteinSegment.objects.filter( slug__in=gsegments['Structured'], partial=False).order_by(preserved) else: segments = ProteinSegment.objects.filter(partial=False, slug__startswith='TM') for segment in segments: selection_object = SelectionItem(segment.category, segment) # add the selected item to the selection selection.add(selection_type, segment.category, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def post(self, request, *args, **kwargs): context = super(PDBClean, self).get_context_data(**kwargs) self.posted = True pref = True water = False hets = False if 'pref_chain' not in request.POST.keys(): pref = False if 'water' in request.POST.keys(): water = True if 'hets' in request.POST.keys(): hets = True # get simple selection from session simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) out_stream = BytesIO() io = PDBIO() zipf = zipfile.ZipFile(out_stream, 'w', zipfile.ZIP_DEFLATED) if selection.targets != []: for selected_struct in [x for x in selection.targets if x.type == 'structure']: struct_name = '{}_{}.pdb'.format(selected_struct.item.protein_conformation.protein.parent.entry_name, selected_struct.item.pdb_code.index) if hets: lig_names = [x.pdb_reference for x in StructureLigandInteraction.objects.filter(structure=selected_struct.item, annotated=True)] else: lig_names = None gn_assigner = GenericNumbering(structure=PDBParser(QUIET=True).get_structure(struct_name, StringIO(selected_struct.item.get_cleaned_pdb(pref, water, lig_names)))[0]) tmp = StringIO() io.set_structure(gn_assigner.assign_generic_numbers()) request.session['substructure_mapping'] = gn_assigner.get_substructure_mapping_dict() io.save(tmp) zipf.writestr(struct_name, tmp.getvalue()) del gn_assigner, tmp for struct in selection.targets: selection.remove('targets', 'structure', struct.item.id) # export simple selection that can be serialized simple_selection = selection.exporter() request.session['selection'] = simple_selection request.session['cleaned_structures'] = out_stream attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a))) for a in attributes: if not(a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return render(request, self.template_name, context)
def get_context_data(self, **kwargs): """get context from parent class (really only relevant for children of this class, as TemplateView does not have any context variables)""" context = super().get_context_data(**kwargs) # get selection from session and add to context # get simple selection from session simple_selection = self.request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() # on the first page of a workflow, clear the selection (or dont' import from the session) if self.step is not 1: if simple_selection: selection.importer(simple_selection) # default species selection if self.default_species: sp = Species.objects.get(common_name=self.default_species) o = SelectionItem('species', sp) selection.species = [o] # update session simple_selection = selection.exporter() self.request.session['selection'] = simple_selection context['selection'] = {} for selection_box, include in self.selection_boxes.items(): if include: context['selection'][selection_box] = selection.dict( selection_box)['selection'][selection_box] if self.filters: context['selection']['species'] = selection.species context['selection']['annotation'] = selection.annotation context['selection']['g_proteins'] = selection.g_proteins context['selection']['pref_g_proteins'] = selection.pref_g_proteins # get attributes of this class and add them to the context attributes = inspect.getmembers(self, lambda a: not (inspect.isroutine(a))) for a in attributes: if not (a[0].startswith('__') and a[0].endswith('__')): context[a[0]] = a[1] return context
def preserve_targets(request): request.session['targets_pos'] = deepcopy(request.session.get('selection', False)) # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) selection.clear('targets') # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return redirect('/seqsign/negativegroupselection',)
def ReadTargetInput(request): """Receives the data from the input form nd adds the listed targets to the selection""" # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) selection_type = 'targets' selection_subtype = 'protein' if request.POST == {}: return render(request, 'common/selection_lists.html', '') o = [] up_names = request.POST['input-targets'].split('\r') for up_name in up_names: try: o.append(Protein.objects.get(entry_name=up_name.strip().lower())) except: continue for obj in o: # add the selected item to the selection selection_object = SelectionItem(selection_subtype, obj) selection.add(selection_type, selection_subtype, selection_object) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # context context = selection.dict(selection_type) return render(request, 'common/selection_lists.html', context)
def ClearSelection(request): """Clears all selected items of the selected type from the session""" selection_type = request.GET['selection_type'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # remove the selected item to the selection selection.clear(selection_type) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection return render(request, 'common/selection_lists.html', selection.dict(selection_type))
def RemoveFromSelection(request): """Removes one selected item from the session""" selection_type = request.GET['selection_type'] selection_subtype = request.GET['selection_subtype'] selection_id = request.GET['selection_id'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # remove the selected item to the selection selection.remove(selection_type, selection_subtype, selection_id) # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # context context = selection.dict(selection_type) # template to load if selection_subtype == 'site_residue': template = 'common/selection_lists_sitesearch.html' amino_acid_groups = { 'amino_acid_groups': definitions.AMINO_ACID_GROUPS, 'amino_acid_group_names': definitions.AMINO_ACID_GROUP_NAMES } context.update(amino_acid_groups) else: template = 'common/selection_lists.html' return render(request, template, context)
def SelectResidueFeature(request): """Receives a selection request, add a feature selection to an item, and returns the updated selection""" selection_type = request.GET['selection_type'] selection_subtype = request.GET['selection_subtype'] selection_id = int(request.GET['selection_id']) feature = request.GET['feature'] # get simple selection from session simple_selection = request.session.get('selection', False) # create full selection and import simple selection (if it exists) selection = Selection() if simple_selection: selection.importer(simple_selection) # process selected object if selection_type == 'segments' and selection_subtype == 'site_residue': for obj in selection.segments: if int(obj.item.id) == selection_id: obj.properties['feature'] = feature obj.properties['amino_acids'] = ','.join( definitions.AMINO_ACID_GROUPS[feature]) break # export simple selection that can be serialized simple_selection = selection.exporter() # add simple selection to session request.session['selection'] = simple_selection # context context = selection.dict(selection_type) # amino acid groups amino_acid_groups = { 'amino_acid_groups': definitions.AMINO_ACID_GROUPS, 'amino_acid_group_names': definitions.AMINO_ACID_GROUP_NAMES } context.update(amino_acid_groups) # template to load template = 'common/selection_lists_sitesearch.html' return render(request, template, context)
def TargetDetailsCompact(request, **kwargs): if 'slug' in kwargs: slug = kwargs['slug'] if slug.count('_') == 0: ps = AssayExperiment.objects.filter( protein__family__parent__parent__parent__slug=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') elif slug.count('_') == 1 and len(slug) == 7: ps = AssayExperiment.objects.filter( protein__family__parent__parent__slug=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') elif slug.count('_') == 2: ps = AssayExperiment.objects.filter( protein__family__parent__slug=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') #elif slug.count('_') == 3: elif slug.count('_') == 1 and len(slug) != 7: ps = AssayExperiment.objects.filter( protein__entry_name=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') if slug.count('_') == 1 and len(slug) == 7: f = ProteinFamily.objects.get(slug=slug) else: f = slug context = {'target': f} else: simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if selection.targets != []: prot_ids = [x.item.id for x in selection.targets] ps = AssayExperiment.objects.filter( protein__in=prot_ids, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') context = { 'target': ', '.join([x.item.entry_name for x in selection.targets]) } ps = ps.prefetch_related('protein', 'ligand__properities__web_links__web_resource', 'ligand__properities__vendors__vendor') d = {} for p in ps: if p.ligand not in d: d[p.ligand] = {} if p.protein not in d[p.ligand]: d[p.ligand][p.protein] = [] d[p.ligand][p.protein].append(p) ligand_data = [] for lig, records in d.items(): links = lig.properities.web_links.all() chembl_id = [ x for x in links if x.web_resource.slug == 'chembl_ligand' ][0].index vendors = lig.properities.vendors.all() purchasability = 'No' for v in vendors: if v.vendor.name not in [ 'ZINC', 'ChEMBL', 'BindingDB', 'SureChEMBL', 'eMolecules', 'MolPort', 'PubChem' ]: purchasability = 'Yes' for record, vals in records.items(): per_target_data = vals protein_details = record """ A dictionary of dictionaries with a list of values. Assay_type | -> Standard_type [list of values] """ tmp = defaultdict(list) tmp_count = 0 for data_line in per_target_data: tmp["Bind" if data_line.assay_type == 'b' else "Funct"].append( data_line.pchembl_value) tmp_count += 1 values = list(itertools.chain(*tmp.values())) ligand_data.append({ 'ligand_id': chembl_id, 'protein_name': protein_details.entry_name, 'species': protein_details.species.common_name, 'record_count': tmp_count, 'assay_type': ', '.join(tmp.keys()), 'purchasability': purchasability, #Flattened list of lists of dict keys: 'low_value': min(values), 'average_value': sum(values) / len(values), 'high_value': max(values), 'standard_units': ', '.join( list(set([x.standard_units for x in per_target_data]))), 'smiles': lig.properities.smiles, 'mw': lig.properities.mw, 'rotatable_bonds': lig.properities.rotatable_bonds, 'hdon': lig.properities.hdon, 'hacc': lig.properities.hacc, 'logp': lig.properities.logp, }) context['ligand_data'] = ligand_data return render(request, 'target_details_compact.html', context)
def SelectionAutocomplete(request): if request.is_ajax(): q = request.GET.get('term') type_of_selection = request.GET.get('type_of_selection') results = [] # session simple_selection = request.session.get('selection') selection = Selection() if simple_selection: selection.importer(simple_selection) # species filter species_list = [] for species in selection.species: species_list.append(species.item) # annotation filter protein_source_list = [] for protein_source in selection.annotation: protein_source_list.append(protein_source.item) # find proteins ps = Protein.objects.filter(Q(name__icontains=q) | Q(entry_name__icontains=q) | Q(family__name__icontains=q), species__in=(species_list), source__in=(protein_source_list))[:10] for p in ps: p_json = {} p_json['id'] = p.id p_json['label'] = p.name + " [" + p.species.common_name + "]" p_json['slug'] = p.entry_name p_json['type'] = 'protein' p_json['category'] = 'Targets' results.append(p_json) # find protein aliases pas = ProteinAlias.objects.prefetch_related('protein').filter( name__icontains=q, protein__species__in=(species_list), protein__source__in=(protein_source_list))[:10] for pa in pas: pa_json = {} pa_json['id'] = pa.protein.id pa_json[ 'label'] = pa.protein.name + " [" + pa.protein.species.common_name + "]" pa_json['slug'] = pa.protein.entry_name pa_json['type'] = 'protein' pa_json['category'] = 'Targets' if pa_json not in results: results.append(pa_json) # protein families if type_of_selection == 'targets' or type_of_selection == 'browse': # find protein families pfs = ProteinFamily.objects.filter(name__icontains=q).exclude( slug='000')[:10] for pf in pfs: pf_json = {} pf_json['id'] = pf.id pf_json['label'] = pf.name pf_json['slug'] = pf.slug pf_json['type'] = 'family' pf_json['category'] = 'Target families' results.append(pf_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype)
def SelectionAutocomplete(request): if request.is_ajax(): q = request.GET.get('term') type_of_selection = request.GET.get('type_of_selection') selection_only_receptors = request.GET.get('selection_only_receptors') referer = request.META.get('HTTP_REFERER') if 'gproteinselection' in str(referer) or 'signprot' in str(referer) and not 'ginterface' in str(referer): exclusion_slug = '00' else: exclusion_slug = '100' results = [] # session simple_selection = request.session.get('selection') selection = Selection() if simple_selection: selection.importer(simple_selection) # species filter species_list = [] for species in selection.species: species_list.append(species.item) # annotation filter protein_source_list = [] for protein_source in selection.annotation: protein_source_list.append(protein_source.item) # find proteins if type_of_selection!='navbar': ps = Protein.objects.filter(Q(name__icontains=q) | Q(entry_name__icontains=q), species__in=(species_list), source__in=(protein_source_list)).exclude(family__slug__startswith=exclusion_slug)[:10] else: ps = Protein.objects.filter(Q(name__icontains=q) | Q(entry_name__icontains=q) | Q(family__name__icontains=q), species__common_name='Human', source__name='SWISSPROT').exclude(family__slug__startswith=exclusion_slug)[:10] for p in ps: p_json = {} p_json['id'] = p.id p_json['label'] = p.name + " [" + p.species.common_name + "]" p_json['slug'] = p.entry_name p_json['type'] = 'protein' p_json['category'] = 'Targets' results.append(p_json) if type_of_selection!='navbar': # find protein aliases pas = ProteinAlias.objects.prefetch_related('protein').filter(name__icontains=q, protein__species__in=(species_list), protein__source__in=(protein_source_list)).exclude(protein__family__slug__startswith=exclusion_slug)[:10] for pa in pas: pa_json = {} pa_json['id'] = pa.protein.id pa_json['label'] = pa.protein.name + " [" + pa.protein.species.common_name + "]" pa_json['slug'] = pa.protein.entry_name pa_json['type'] = 'protein' pa_json['category'] = 'Targets' if pa_json not in results: results.append(pa_json) # protein families if (type_of_selection == 'targets' or type_of_selection == 'browse' or type_of_selection == 'gproteins') and selection_only_receptors!="True": # find protein families pfs = ProteinFamily.objects.filter(name__icontains=q).exclude(slug='000').exclude(slug__startswith=exclusion_slug)[:10] for pf in pfs: pf_json = {} pf_json['id'] = pf.id pf_json['label'] = pf.name pf_json['slug'] = pf.slug pf_json['type'] = 'family' pf_json['category'] = 'Target families' results.append(pf_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype)
def TargetDetailsCompact(request, **kwargs): if 'slug' in kwargs: slug = kwargs['slug'] if slug.count('_') == 0: ps = AssayExperiment.objects.filter( protein__family__parent__parent__parent__slug=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') elif slug.count('_') == 1 and len(slug) == 7: ps = AssayExperiment.objects.filter( protein__family__parent__parent__slug=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') elif slug.count('_') == 2: ps = AssayExperiment.objects.filter( protein__family__parent__slug=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') #elif slug.count('_') == 3: elif slug.count('_') == 1 and len(slug) != 7: ps = AssayExperiment.objects.filter( protein__entry_name=slug, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') if slug.count('_') == 1 and len(slug) == 7: f = ProteinFamily.objects.get(slug=slug) else: f = slug context = {'target': f} else: simple_selection = request.session.get('selection', False) selection = Selection() if simple_selection: selection.importer(simple_selection) if selection.targets != []: prot_ids = [x.item.id for x in selection.targets] ps = AssayExperiment.objects.filter( protein__in=prot_ids, ligand__properities__web_links__web_resource__slug= 'chembl_ligand') context = { 'target': ', '.join([x.item.entry_name for x in selection.targets]) } ligands = [x.ligand for x in ps.distinct('ligand')] record_count = ps.values('protein', ).annotate(num_records=Count( 'protein__entry_name')).order_by('protein__entry_name') ligand_data = [] for lig in ligands: ligand_records = ps.filter(ligand=lig).order_by('protein__entry_name') for record in record_count: per_target_data = ligand_records.filter(protein=record['protein']) if list(per_target_data) == []: continue protein_details = Protein.objects.get(pk=record['protein']) """ A dictionary of dictionaries with a list of values. Assay_type | -> Standard_type [list of values] """ tmp = defaultdict(list) tmp_count = 0 for data_line in per_target_data: tmp["Bind" if data_line.assay_type == 'b' else "Funct"].append( data_line.pchembl_value) tmp_count += 1 values = list(itertools.chain(*tmp.values())) ligand_data.append({ 'ligand_id': lig.properities.web_links.filter( web_resource__slug='chembl_ligand')[0].index, 'protein_name': protein_details.entry_name, 'species': protein_details.species.common_name, 'record_count': tmp_count, 'assay_type': ', '.join(tmp.keys()), 'purchasability': 'Yes' if len( LigandVendorLink.objects.filter( lp=lig.properities).exclude(vendor__name__in=[ 'ZINC', 'ChEMBL', 'BindingDB', 'SureChEMBL', 'eMolecules', 'MolPort', 'PubChem' ])) > 0 else 'No', #Flattened list of lists of dict keys: 'low_value': min(values), 'average_value': sum(values) / len(values), 'high_value': max(values), 'standard_units': ', '.join( list(set([x.standard_units for x in per_target_data]))), 'smiles': lig.properities.smiles, 'mw': lig.properities.mw, 'rotatable_bonds': lig.properities.rotatable_bonds, 'hdon': lig.properities.hdon, 'hacc': lig.properities.hacc, 'logp': lig.properities.logp, }) context['ligand_data'] = ligand_data return render(request, 'target_details_compact.html', context)
def get_context(view): valid = True valid_needle = True position = Selection.get_position(view) # regions word_region = view.word(position) line_region = view.line(position) pre_region = sublime.Region(line_region.a, word_region.a) post_region = sublime.Region(word_region.b, line_region.b) # text line = view.substr(line_region) word = view.substr(word_region) pre = view.substr(pre_region) post = view.substr(post_region) needle_region = view.word(position) # st2: unmutable region needle_start = needle_region.a needle_end = needle_region.b # grab everything in 'separators' needle = "" separator = False pre_match = "" # search for a separator before current word, i.e. <">path/to/<position> pre_quotes = re.search( "([" + NEEDLE_SEPARATOR_BEFORE + "])([^" + NEEDLE_SEPARATOR + "]*)$", pre) if pre_quotes: needle += pre_quotes.group(2) + word separator = pre_quotes.group(1) pre_match = pre_quotes.group(2) needle_start -= len(pre_quotes.group(2)) else: # use whitespace as separator pre_quotes = re.search("(\s)([^" + NEEDLE_SEPARATOR + "\s]*)$", pre) if pre_quotes: needle = pre_quotes.group(2) + word separator = pre_quotes.group(1) pre_match = pre_quotes.group(2) needle_start -= len(pre_quotes.group(2)) if pre_quotes: post_quotes = re.search("^([" + NEEDLE_SEPARATOR_AFTER + "]*)", post) if post_quotes: needle += post_quotes.group(1) needle_end += len(post_quotes.group(1)) else: print("no post quotes found => invalid") valid = False elif not re.search("[" + NEEDLE_INVALID_CHARACTERS + "]", needle): needle = pre + word needle_start = pre_region.a else: needle = word needle_region = sublime.Region(needle_start, needle_end) # grab prefix prefix_region = sublime.Region(line_region.a, pre_region.b - len(pre_match) - 1) prefix_line = view.substr(prefix_region) # # print("prefix line", prefix_line) #define? (["...", "..."]) -> before? # before: ABC =:([ prefix = re.search( "\s*([" + NEEDLE_CHARACTERS + "]+)[" + DELIMITER + "]*$", prefix_line) if prefix is None: # validate array, like define(["...", ".CURSOR."]) prefix = re.search( "^\s*([" + NEEDLE_CHARACTERS + "]+)[" + DELIMITER + "]+", prefix_line) if prefix: # print("prefix:", prefix.group(1)) prefix = prefix.group(1) tag = re.search("<\s*([" + NEEDLE_CHARACTERS + "]*)\s*[^>]*$", prefix_line) if tag: tag = tag.group(1) # print("tag:", tag) style = re.search( "[\s\"\'']*([" + NEEDLE_CHARACTERS + "]*)[\s\"\']*\:[^\:]*$", prefix_line) if style: style = style.group(1) # print("style:", style) if separator is False: # print("context", "separator undefined => invalid", needle) valid = False elif re.search("[" + NEEDLE_INVALID_CHARACTERS + "]", needle): # print("context", "invalid characters in needle => invalid", needle) valid_needle = False valid = False elif prefix is None and separator.strip() == "": # print("context", "prefix undefined => invalid", needle) valid = False return { "is_valid": valid, "valid_needle": valid_needle, "needle": needle, "prefix": prefix, "tagName": tag, "style": style, "region": needle_region }
def get_context_data(self, **kwargs): """ Get the selection data (proteins and numbering schemes) and prepare it for display. """ context = super().get_context_data(**kwargs) # get the user selection from session simple_selection = self.request.session.get('selection', False) # local protein list proteins = [] # flatten the selection into individual proteins for target in simple_selection.targets: if target.type == 'protein': proteins.append(target.item) elif target.type == 'family': # species filter species_list = [] for species in simple_selection.species: species_list.append(species.item) # annotation filter protein_source_list = [] for protein_source in simple_selection.annotation: protein_source_list.append(protein_source.item) if species_list: family_proteins = Protein.objects.filter(family__slug__startswith=target.item.slug, species__in=(species_list), source__in=(protein_source_list)).select_related('residue_numbering_scheme', 'species') else: family_proteins = Protein.objects.filter(family__slug__startswith=target.item.slug, source__in=(protein_source_list)).select_related('residue_numbering_scheme', 'species') for fp in family_proteins: proteins.append(fp) longest_name = 0 species_list = {} for protein in proteins: if protein.species.common_name not in species_list: if len(protein.species.common_name)>10 and len(protein.species.common_name.split())>1: name = protein.species.common_name.split()[0][0]+". "+" ".join(protein.species.common_name.split()[1:]) if len(" ".join(protein.species.common_name.split()[1:]))>11: name = protein.species.common_name.split()[0][0]+". "+" ".join(protein.species.common_name.split()[1:])[:8]+".." else: name = protein.species.common_name species_list[protein.species.common_name] = name else: name = species_list[protein.species.common_name] if len(re.sub('<[^>]*>', '', protein.name)+" "+name)>longest_name: longest_name = len(re.sub('<[^>]*>', '', protein.name)+" "+name) # get the selection from session selection = Selection() if simple_selection: selection.importer(simple_selection) # # extract numbering schemes and proteins numbering_schemes = [x.item for x in selection.numbering_schemes] # # get the helices (TMs only at first) # segments = ProteinSegment.objects.filter(category='helix', proteinfamily='GPCR') # Get all the segments segments = ProteinSegment.objects.filter(proteinfamily='GPCR') if ResidueNumberingScheme.objects.get(slug=settings.DEFAULT_NUMBERING_SCHEME) in numbering_schemes: default_scheme = ResidueNumberingScheme.objects.get(slug=settings.DEFAULT_NUMBERING_SCHEME) else: default_scheme = numbering_schemes[0] # prepare the dictionary # each segment has a dictionary of positions # default_generic_number or first scheme on the list is the key # value is a dictionary of other gn positions and residues from selected proteins data = OrderedDict() for segment in segments: data[segment.slug] = OrderedDict() residues = Residue.objects.filter(protein_segment=segment, protein_conformation__protein__in=proteins, generic_number__isnull=False).prefetch_related('protein_conformation__protein', 'protein_conformation__state', 'protein_segment', 'generic_number__scheme', 'display_generic_number__scheme', 'alternative_generic_numbers__scheme') for scheme in numbering_schemes: if scheme == default_scheme and scheme.slug == settings.DEFAULT_NUMBERING_SCHEME: for pos in list(set([x.generic_number.label for x in residues if x.protein_segment == segment])): data[segment.slug][pos] = {scheme.slug : pos, 'seq' : ['-']*len(proteins)} elif scheme == default_scheme: for pos in list(set([x.generic_number.label for x in residues if x.protein_segment == segment])): data[segment.slug][pos] = {scheme.slug : pos, 'seq' : ['-']*len(proteins)} for residue in residues: alternatives = residue.alternative_generic_numbers.all() pos = residue.generic_number for alternative in alternatives: scheme = alternative.scheme if default_scheme.slug == settings.DEFAULT_NUMBERING_SCHEME: pos = residue.generic_number if scheme == pos.scheme: data[segment.slug][pos.label]['seq'][proteins.index(residue.protein_conformation.protein)] = str(residue) else: if scheme.slug not in data[segment.slug][pos.label].keys(): data[segment.slug][pos.label][scheme.slug] = alternative.label if alternative.label not in data[segment.slug][pos.label][scheme.slug]: data[segment.slug][pos.label][scheme.slug] += " "+alternative.label data[segment.slug][pos.label]['seq'][proteins.index(residue.protein_conformation.protein)] = str(residue) else: if scheme.slug not in data[segment.slug][pos.label].keys(): data[segment.slug][pos.label][scheme.slug] = alternative.label if alternative.label not in data[segment.slug][pos.label][scheme.slug]: data[segment.slug][pos.label][scheme.slug] += " "+alternative.label data[segment.slug][pos.label]['seq'][proteins.index(residue.protein_conformation.protein)] = str(residue) # Preparing the dictionary of list of lists. Dealing with tripple nested dictionary in django templates is a nightmare flattened_data = OrderedDict.fromkeys([x.slug for x in segments], []) for s in iter(flattened_data): flattened_data[s] = [[data[s][x][y.slug] if y.slug in data[s][x] else '-' for y in numbering_schemes ] + data[s][x]['seq'] for x in sorted(data[s]) ] #Purging the empty segments clean_dict = OrderedDict() clean_segments = [] for s in iter(flattened_data): if flattened_data[s] != []: clean_dict[s] = flattened_data[s] clean_segments.append(s) context['header'] = zip([x.short_name for x in numbering_schemes] + [x.name+" "+species_list[x.species.common_name] for x in proteins], [x.name for x in numbering_schemes] + [x.name for x in proteins],[x.name for x in numbering_schemes] + [x.entry_name for x in proteins]) context['segments'] = clean_segments context['data'] = clean_dict context['number_of_schemes'] = len(numbering_schemes) context['longest_name'] = {'div' : longest_name*2, 'height': longest_name*2+80} return context
def render_residue_table_excel(request): simple_selection = request.session.get('selection', False) # local protein list proteins = [] # flatten the selection into individual proteins for target in simple_selection.targets: if target.type == 'protein': proteins.append(target.item) elif target.type == 'family': # species filter species_list = [] for species in simple_selection.species: species_list.append(species.item) # annotation filter protein_source_list = [] for protein_source in simple_selection.annotation: protein_source_list.append(protein_source.item) if species_list: family_proteins = Protein.objects.filter(family__slug__startswith=target.item.slug, species__in=(species_list), source__in=(protein_source_list)).select_related('residue_numbering_scheme', 'species') else: family_proteins = Protein.objects.filter(family__slug__startswith=target.item.slug, source__in=(protein_source_list)).select_related('residue_numbering_scheme', 'species') for fp in family_proteins: proteins.append(fp) longest_name = 0 species_list = {} for protein in proteins: if protein.species.common_name not in species_list: if len(protein.species.common_name)>10 and len(protein.species.common_name.split())>1: name = protein.species.common_name.split()[0][0]+". "+" ".join(protein.species.common_name.split()[1:]) if len(" ".join(protein.species.common_name.split()[1:]))>11: name = protein.species.common_name.split()[0][0]+". "+" ".join(protein.species.common_name.split()[1:])[:8]+".." else: name = protein.species.common_name species_list[protein.species.common_name] = name else: name = species_list[protein.species.common_name] if len(re.sub('<[^>]*>', '', protein.name)+" "+name)>longest_name: longest_name = len(re.sub('<[^>]*>', '', protein.name)+" "+name) # get the selection from session selection = Selection() if simple_selection: selection.importer(simple_selection) # # extract numbering schemes and proteins numbering_schemes = [x.item for x in selection.numbering_schemes] segments = ProteinSegment.objects.filter(proteinfamily='GPCR') if ResidueNumberingScheme.objects.get(slug=settings.DEFAULT_NUMBERING_SCHEME) in numbering_schemes: default_scheme = ResidueNumberingScheme.objects.get(slug=settings.DEFAULT_NUMBERING_SCHEME) else: default_scheme = numbering_schemes[0] # prepare the dictionary # each helix has a dictionary of positions # default_generic_number or first scheme on the list is the key # value is a dictionary of other gn positions and residues from selected proteins data = OrderedDict() for segment in segments: data[segment.slug] = OrderedDict() residues = Residue.objects.filter(protein_segment=segment, protein_conformation__protein__in=proteins, generic_number__isnull=False).prefetch_related('protein_conformation__protein', 'protein_conformation__state', 'protein_segment', 'generic_number__scheme', 'display_generic_number__scheme', 'alternative_generic_numbers__scheme') for scheme in numbering_schemes: if scheme == default_scheme and scheme.slug == settings.DEFAULT_NUMBERING_SCHEME: for pos in list(set([x.generic_number.label for x in residues if x.protein_segment == segment])): data[segment.slug][pos] = {scheme.slug : pos, 'seq' : ['-']*len(proteins)} elif scheme == default_scheme: for pos in list(set([x.generic_number.label for x in residues if x.protein_segment == segment])): data[segment.slug][pos] = {scheme.slug : pos, 'seq' : ['-']*len(proteins)} for residue in residues: alternatives = residue.alternative_generic_numbers.all() pos = residue.generic_number for alternative in alternatives: scheme = alternative.scheme if default_scheme.slug == settings.DEFAULT_NUMBERING_SCHEME: pos = residue.generic_number if scheme == pos.scheme: data[segment.slug][pos.label]['seq'][proteins.index(residue.protein_conformation.protein)] = str(residue) else: if scheme.slug not in data[segment.slug][pos.label].keys(): data[segment.slug][pos.label][scheme.slug] = alternative.label if alternative.label not in data[segment.slug][pos.label][scheme.slug]: data[segment.slug][pos.label][scheme.slug] += " "+alternative.label data[segment.slug][pos.label]['seq'][proteins.index(residue.protein_conformation.protein)] = str(residue) else: if scheme.slug not in data[segment.slug][pos.label].keys(): data[segment.slug][pos.label][scheme.slug] = alternative.label if alternative.label not in data[segment.slug][pos.label][scheme.slug]: data[segment.slug][pos.label][scheme.slug] += " "+alternative.label data[segment.slug][pos.label]['seq'][proteins.index(residue.protein_conformation.protein)] = str(residue) # Preparing the dictionary of list of lists. Dealing with tripple nested dictionary in django templates is a nightmare flattened_data = OrderedDict.fromkeys([x.slug for x in segments], []) for s in iter(flattened_data): flattened_data[s] = [[data[s][x][y.slug] for y in numbering_schemes]+data[s][x]['seq'] for x in sorted(data[s])] #Purging the empty segments clean_dict = OrderedDict() clean_segments = [] for s in iter(flattened_data): if flattened_data[s] != []: clean_dict[s] = flattened_data[s] clean_segments.append(s) segments = clean_segments flattened_data = clean_dict header = [x.short_name for x in numbering_schemes] + [x.name+" "+species_list[x.species.common_name] for x in proteins] # Now excel time outstream = BytesIO() wb = xlsxwriter.Workbook(outstream, {'in_memory': True}) sub = wb.add_format({'font_script': 2}) bold = wb.add_format({'bold': True}) worksheet = wb.add_worksheet('Residue table') row_offset = 0 #Header row #Numbering schemes for i, x in enumerate(numbering_schemes): worksheet.write(0, i, x.short_name) #Protein names col_offset = len(numbering_schemes) for i, x in enumerate(proteins): t = html_to_rich_format_string(x.name + " " + species_list[x.species.common_name], sub) if len(t) < 2: worksheet.write(0, col_offset + i, html.unescape(x.name + " " + species_list[x.species.common_name])) else: worksheet.write_rich_string(0, col_offset + i, *t) row_offset += 1 for segment in segments: worksheet.write(row_offset, 0, segment, bold) row_offset += 1 for j, data_row in enumerate(flattened_data[segment]): worksheet.write_row(row_offset + j, 0, data_row) row_offset += len(flattened_data[segment]) wb.close() outstream.seek(0) response = HttpResponse( outstream.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) response['Content-Disposition'] = "attachment; filename=residue_table.xlsx" return response